@daogee/mdgraph 1.2.0 → 1.2.1
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 +13 -0
- package/README-ZH.md +1 -1
- package/README.md +1 -1
- package/agent-pack/mdgraph-agent-instructions.md +2 -0
- package/dist/bin/mdgraph.js +2 -1
- package/dist/db/repositories.d.ts +2 -1
- package/dist/db/repositories.js +23 -3
- package/dist/mcp/tools.js +4 -3
- package/dist/query/context-builder.d.ts +1 -0
- package/dist/query/context-builder.js +124 -23
- package/dist/query/search.js +22 -5
- package/dist/scanner/file-scanner.js +7 -7
- package/dist/utils/fts.d.ts +1 -0
- package/dist/utils/fts.js +68 -13
- package/dist/watcher/file-watcher.js +41 -6
- package/docs/EN/Agent_Integration.md +2 -0
- package/docs/EN/Architecture.md +1 -2
- package/docs/EN/Evaluation_Questions.md +7 -1
- package/docs/EN/Operations.md +2 -0
- package/docs/EN/Output_Contracts.md +4 -2
- package/docs/EN/Public_Contracts.md +1 -1
- package/docs/EN/Release_Checklist.md +2 -2
- package/docs/EN/Retrieval_and_Context.md +14 -5
- package/docs/ZH/Agent_Integration.md +2 -0
- package/docs/ZH/Architecture.md +1 -2
- package/docs/ZH/Evaluation_Questions.md +7 -1
- package/docs/ZH/Operations.md +2 -0
- package/docs/ZH/Output_Contracts.md +4 -2
- package/docs/ZH/Public_Contracts.md +1 -1
- package/docs/ZH/Release_Checklist.md +2 -2
- package/docs/ZH/Retrieval_and_Context.md +14 -5
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to MDGraph are documented here. MDGraph follows semantic versioning for its public releases.
|
|
4
4
|
|
|
5
|
+
## Unreleased
|
|
6
|
+
|
|
7
|
+
## 1.2.1 - 2026-10-13
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- Ignore duplicate native Markdown change events when the indexed content hash is unchanged, while retaining real edits and configuration reloads.
|
|
12
|
+
|
|
13
|
+
- Replace the affected glob dependency chain while preserving include/exclude patterns, hidden-file handling, and symlink boundaries; update the source-map dependency to its patched release.
|
|
14
|
+
- Retrieve relevant body sections from known documents and source references, share the existing context budget across their evidence, and retain explicit section anchors.
|
|
15
|
+
- Preserve direct-hit relevance during context packing, redistribute unused shares by actual direct-evidence size for long queries, select relevant paragraphs from long sections, and expose partial-section markers with excerpt line ranges.
|
|
16
|
+
- Distribute FTS terms across query groups, preserve numeric versions and dates, and rank a bounded candidate pool by query coverage before returning the requested result count.
|
|
17
|
+
|
|
5
18
|
## 1.2.0 - 2026-09-12
|
|
6
19
|
|
|
7
20
|
### Added
|
package/README-ZH.md
CHANGED
|
@@ -148,7 +148,7 @@ mdgraph usage --path /your/project
|
|
|
148
148
|
|
|
149
149
|
完整 CLI 参考请使用 `mdgraph help` 或 `mdgraph help <command>`。
|
|
150
150
|
|
|
151
|
-
真 MMR 打包为 opt-in
|
|
151
|
+
真 MMR 打包为 opt-in;默认优先引入已知文件和直接搜索证据,再按文档轮询补入图扩展,详见[检索与上下文](./docs/ZH/Retrieval_and_Context.md)。Watcher polling 也必须显式启用(`watch --poll` 或 `serve --mcp --watch-poll`),因为它可能增加 I/O 和 CPU;详见[运行与故障处理](./docs/ZH/Operations.md)。
|
|
152
152
|
|
|
153
153
|
实验性的 `query` 命令提供有界、参数化的文档治理 DSL,不改变 `search` 或五工具 MCP surface。
|
|
154
154
|
|
package/README.md
CHANGED
|
@@ -148,7 +148,7 @@ mdgraph usage --path /your/project
|
|
|
148
148
|
|
|
149
149
|
Use `mdgraph help` or `mdgraph help <command>` for the full CLI reference.
|
|
150
150
|
|
|
151
|
-
True MMR packing is opt-in
|
|
151
|
+
True MMR packing is opt-in. The default prioritizes known-file evidence and direct search hits, then adds graph expansion in document round-robin order. See [Retrieval and Context](./docs/EN/Retrieval_and_Context.md). Watcher polling is also explicit (`watch --poll` or `serve --mcp --watch-poll`) because it can increase I/O and CPU use; see [Operations](./docs/EN/Operations.md).
|
|
152
152
|
|
|
153
153
|
The experimental `query` command provides a bounded, parameterized DSL for document governance without changing `search` or the five-tool MCP surface.
|
|
154
154
|
|
|
@@ -16,6 +16,8 @@ Default order for Markdown/documentation questions:
|
|
|
16
16
|
- Use `mdgraph_node` for known document paths, section anchors, entities, source paths, or graph ids.
|
|
17
17
|
- Use `mdgraph_trace` for relationship questions between two known documents, entities, or source references.
|
|
18
18
|
- Prefer returned context when it includes enough content, reasons, provenance, source refs, and risk notes.
|
|
19
|
+
- Use `path#anchor` in `knownFiles` when the relevant section is already known. If an item has `truncated: true`, its line range describes only the returned excerpt; use its path and section identity to locate any required original Markdown.
|
|
20
|
+
- Treat `maxChars` as the document-content plus card-summary budget. Host token limits and the full response size must be handled separately.
|
|
19
21
|
- Fall back to normal file reads when MDGraph is inactive, stale for the task, too sparse, or when exact source text is required.
|
|
20
22
|
|
|
21
23
|
Do not treat MDGraph as hidden memory, a source AST index, or an authority beyond the indexed Markdown corpus. Do not create or update an index unless the user asks for it.
|
package/dist/bin/mdgraph.js
CHANGED
|
@@ -879,7 +879,8 @@ function formatContext(context) {
|
|
|
879
879
|
const heading = item.heading ? `# ${item.heading}` : item.title;
|
|
880
880
|
const lines = item.lines ? `:${item.lines.start}` : "";
|
|
881
881
|
const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
|
|
882
|
-
|
|
882
|
+
const excerptNotice = item.truncated ? "\nPartial section: use the node or anchor to read the complete source." : "";
|
|
883
|
+
return `## ${index + 1}. ${item.path}${lines}\nReason: ${item.reason}${cardSummary}${excerptNotice}\n${heading}\n${item.content}`;
|
|
883
884
|
})
|
|
884
885
|
.join("\n\n");
|
|
885
886
|
if (!context.debug) {
|
|
@@ -169,7 +169,8 @@ export declare class GraphRepository {
|
|
|
169
169
|
dimensions: number;
|
|
170
170
|
}): ChunkVector[];
|
|
171
171
|
preservedDerivedEdges(records: GraphRecordSet): GraphEdge[];
|
|
172
|
-
searchChunks(ftsQuery: string, limit: number): ChunkSearchRow[];
|
|
172
|
+
searchChunks(ftsQuery: string, limit: number, documentId?: string): ChunkSearchRow[];
|
|
173
|
+
contextChunksForDocument(documentId: string): ChunkSearchRow[];
|
|
173
174
|
findEntitiesByNormalizedNames(names: string[]): GraphEntity[];
|
|
174
175
|
entityDocumentFrequencies(entityIds: string[]): Map<string, number>;
|
|
175
176
|
findEntityDefinitions(entityIds: string[]): EntityDefinitionSearchRow[];
|
package/dist/db/repositories.js
CHANGED
|
@@ -142,7 +142,7 @@ export class GraphRepository {
|
|
|
142
142
|
return rows.map(rowToEdge).filter((edge) => (candidateHashes.get(edge.fromId) === this.documentHash(edge.fromId)
|
|
143
143
|
&& candidateHashes.get(edge.toId) === this.documentHash(edge.toId)));
|
|
144
144
|
}
|
|
145
|
-
searchChunks(ftsQuery, limit) {
|
|
145
|
+
searchChunks(ftsQuery, limit, documentId) {
|
|
146
146
|
const rows = this.db.prepare(`
|
|
147
147
|
SELECT
|
|
148
148
|
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
@@ -158,9 +158,10 @@ export class GraphRepository {
|
|
|
158
158
|
JOIN documents d ON d.id = c.document_id
|
|
159
159
|
LEFT JOIN sections s ON s.id = c.section_id
|
|
160
160
|
WHERE chunks_fts MATCH ?
|
|
161
|
-
|
|
161
|
+
${documentId ? "AND d.id = ?" : ""}
|
|
162
|
+
ORDER BY rank ASC, c.id ASC
|
|
162
163
|
LIMIT ?
|
|
163
|
-
`).all(ftsQuery, limit);
|
|
164
|
+
`).all(...(documentId ? [ftsQuery, documentId, limit] : [ftsQuery, limit]));
|
|
164
165
|
return rows.map((row) => ({
|
|
165
166
|
document: rowToDocument(row, "d_"),
|
|
166
167
|
section: row.s_id ? rowToSection(row, "s_") : undefined,
|
|
@@ -168,6 +169,25 @@ export class GraphRepository {
|
|
|
168
169
|
rank: numberValue(row.rank)
|
|
169
170
|
}));
|
|
170
171
|
}
|
|
172
|
+
contextChunksForDocument(documentId) {
|
|
173
|
+
const rows = this.db.prepare(`
|
|
174
|
+
SELECT
|
|
175
|
+
d.id AS d_id, d.path AS d_path, d.title AS d_title, d.type AS d_type, d.status AS d_status,
|
|
176
|
+
d.hash AS d_hash, d.trust_tier AS d_trust_tier, d.updated_at AS d_updated_at,
|
|
177
|
+
d.indexed_at AS d_indexed_at, d.metadata_json AS d_metadata_json,
|
|
178
|
+
s.id AS s_id, s.document_id AS s_document_id, s.anchor AS s_anchor, s.heading AS s_heading,
|
|
179
|
+
s.level AS s_level, s.start_line AS s_start_line, s.end_line AS s_end_line, s.content AS s_content,
|
|
180
|
+
c.id AS c_id, c.document_id AS c_document_id, c.section_id AS c_section_id, c.content AS c_content,
|
|
181
|
+
c.token_estimate AS c_token_estimate, c.metadata_json AS c_metadata_json,
|
|
182
|
+
0 AS rank
|
|
183
|
+
FROM chunks c
|
|
184
|
+
JOIN documents d ON d.id = c.document_id
|
|
185
|
+
LEFT JOIN sections s ON s.id = c.section_id
|
|
186
|
+
WHERE d.id = ?
|
|
187
|
+
ORDER BY s.start_line ASC, c.id ASC
|
|
188
|
+
`).all(documentId);
|
|
189
|
+
return rows.map(rowToChunkSearchRow);
|
|
190
|
+
}
|
|
171
191
|
findEntitiesByNormalizedNames(names) {
|
|
172
192
|
if (!names.length) {
|
|
173
193
|
return [];
|
package/dist/mcp/tools.js
CHANGED
|
@@ -40,7 +40,7 @@ export const tools = [
|
|
|
40
40
|
knownFiles: {
|
|
41
41
|
type: "array",
|
|
42
42
|
items: { type: "string" },
|
|
43
|
-
description: "Optional
|
|
43
|
+
description: "Optional project-relative documents, path#anchor sections, or source paths. Document hints retrieve body sections under the shared character budget."
|
|
44
44
|
},
|
|
45
45
|
maxChars: { type: "number", description: "Optional character budget for the returned context package." },
|
|
46
46
|
packingStrategy: {
|
|
@@ -419,7 +419,7 @@ function agentContextMode(config, counts, query, knownFiles, requestedMaxChars)
|
|
|
419
419
|
const maxChars = requestedMaxChars ?? Math.min(config.search.maxContextChars, needsMoreDepth ? config.search.maxContextChars : 16_000);
|
|
420
420
|
return {
|
|
421
421
|
name: "auto",
|
|
422
|
-
searchLimit: searchMode.limit,
|
|
422
|
+
searchLimit: searchMode.limit * 2,
|
|
423
423
|
maxDepth,
|
|
424
424
|
maxChars,
|
|
425
425
|
reason: [searchMode.reason, requestedMaxChars ? "explicit character budget" : "auto character budget"].join("; ")
|
|
@@ -451,7 +451,8 @@ function formatContext(context) {
|
|
|
451
451
|
const sourceRefs = item.sourceRefs?.length ? `\nSource refs: ${item.sourceRefs.map((sourceRef) => `${sourceRef.path} (${sourceRef.edgeKind}/${sourceRef.provenance}, confidence ${sourceRef.confidence})`).join(", ")}` : "";
|
|
452
452
|
const riskNotes = item.riskNotes?.length ? `\nRisk notes: ${item.riskNotes.join("; ")}` : "";
|
|
453
453
|
const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
|
|
454
|
-
|
|
454
|
+
const excerptNotice = item.truncated ? "\nPartial section: use the node or anchor to read the complete source." : "";
|
|
455
|
+
return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}${cardSummary}${excerptNotice}\n${heading}\n${item.content}`;
|
|
455
456
|
});
|
|
456
457
|
const hints = [
|
|
457
458
|
context.mode ? `Mode: ${context.mode.name} (searchLimit ${context.mode.searchLimit}, maxDepth ${context.mode.maxDepth}; ${context.mode.reason})` : "",
|
|
@@ -2,12 +2,14 @@ import { explainSearchGraphAsync, searchGraph } from "./search.js";
|
|
|
2
2
|
import { scanContentRiskLines } from "../utils/content-risk.js";
|
|
3
3
|
import { normalizePath, uniqueStrings } from "../utils/text.js";
|
|
4
4
|
import { createKnowledgeCardBuilder } from "./knowledge-card.js";
|
|
5
|
+
import { ftsQueryFor, ftsQueryGroups } from "../utils/fts.js";
|
|
5
6
|
const DEFAULT_MAX_CONTEXT_NODES = 16;
|
|
6
7
|
const DEFAULT_MAX_CONTEXT_CARD_SUMMARIES = 4;
|
|
7
8
|
export const CONTEXT_PACKING_STRATEGY = "mmr-style-document-round-robin";
|
|
8
9
|
export const CONTEXT_PACKING_STRATEGIES = [CONTEXT_PACKING_STRATEGY, "mmr"];
|
|
9
10
|
export const DEFAULT_MMR_LAMBDA = 0.65;
|
|
10
11
|
const MMR_SAME_DOCUMENT_REDUNDANCY_THRESHOLD = 0.8;
|
|
12
|
+
const KNOWN_FILE_SECTION_LIMIT = 4;
|
|
11
13
|
export function buildContext(repository, config, query, options = {}) {
|
|
12
14
|
const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
|
|
13
15
|
const results = searchGraph(repository, config, query, searchLimit, options.searchOptions);
|
|
@@ -24,7 +26,7 @@ export function buildContextFromSearchResults(repository, config, query, results
|
|
|
24
26
|
const maxDepth = positiveIntegerOr(options.maxDepth, config.search.maxDepth);
|
|
25
27
|
const collection = collectContextCandidates(repository, config, results, maxDepth);
|
|
26
28
|
const candidates = knownFiles.length
|
|
27
|
-
? mergeKnownFileCandidates(repository, collection.candidates, knownFiles)
|
|
29
|
+
? mergeKnownFileCandidates(repository, collection.candidates, knownFiles, query, maxChars)
|
|
28
30
|
: collection.candidates;
|
|
29
31
|
const packingStrategy = options.packingStrategy ?? CONTEXT_PACKING_STRATEGY;
|
|
30
32
|
const packed = packContext(repository, config, query, enrichContextCandidates(repository, candidates), maxChars, options.mode, packingStrategy, mmrLambdaOrDefault(options.mmrLambda));
|
|
@@ -55,20 +57,23 @@ export function buildContextFromSearchResults(repository, config, query, results
|
|
|
55
57
|
}
|
|
56
58
|
};
|
|
57
59
|
}
|
|
58
|
-
function mergeKnownFileCandidates(repository, candidates, knownFiles) {
|
|
60
|
+
function mergeKnownFileCandidates(repository, candidates, knownFiles, query, maxChars) {
|
|
59
61
|
const merged = new Map();
|
|
60
62
|
for (const candidate of candidates) {
|
|
61
63
|
addCandidate(merged, candidate);
|
|
62
64
|
}
|
|
63
65
|
knownFiles.forEach((knownFile, index) => {
|
|
64
|
-
for (const candidate of candidatesForKnownFile(repository, knownFile, index)) {
|
|
66
|
+
for (const candidate of candidatesForKnownFile(repository, knownFile, index, query, Math.floor(maxChars / knownFiles.length))) {
|
|
65
67
|
addCandidate(merged, candidate);
|
|
66
68
|
}
|
|
67
69
|
});
|
|
68
70
|
return orderContextCandidates([...merged.values()]);
|
|
69
71
|
}
|
|
70
|
-
function candidatesForKnownFile(repository, knownFile, index) {
|
|
72
|
+
function candidatesForKnownFile(repository, knownFile, index, query, documentBudget) {
|
|
71
73
|
const resolution = resolveKnownFile(repository, knownFile);
|
|
74
|
+
if (resolution?.kind === "document") {
|
|
75
|
+
return candidatesForKnownDocument(repository, resolution.id, knownFile, index, query, documentBudget);
|
|
76
|
+
}
|
|
72
77
|
if (resolution?.kind !== "source_ref") {
|
|
73
78
|
const directRow = resolution ? repository.contextChunkForNode(resolution.id) : undefined;
|
|
74
79
|
return directRow ? [candidateFromKnownRow(directRow, `known file ${knownFile}`, index)] : [];
|
|
@@ -76,10 +81,27 @@ function candidatesForKnownFile(repository, knownFile, index) {
|
|
|
76
81
|
return repository.edgesForNode(resolution.id)
|
|
77
82
|
.map((edge) => {
|
|
78
83
|
const otherId = edge.fromId === resolution.id ? edge.toId : edge.fromId;
|
|
84
|
+
if (repository.getNode(otherId)?.kind === "document") {
|
|
85
|
+
return candidatesForKnownDocument(repository, otherId, `${knownFile} via ${edge.kind}/${edge.provenance}`, index, query, documentBudget);
|
|
86
|
+
}
|
|
79
87
|
const row = repository.contextChunkForNode(otherId);
|
|
80
|
-
return row ? candidateFromKnownRow(row, `known file ${knownFile} via ${edge.kind}/${edge.provenance}`, index) :
|
|
88
|
+
return row ? [candidateFromKnownRow(row, `known file ${knownFile} via ${edge.kind}/${edge.provenance}`, index)] : [];
|
|
81
89
|
})
|
|
82
|
-
.
|
|
90
|
+
.flat();
|
|
91
|
+
}
|
|
92
|
+
function candidatesForKnownDocument(repository, documentId, knownFile, index, query, documentBudget) {
|
|
93
|
+
const rows = repository.contextChunksForDocument(documentId);
|
|
94
|
+
if (rows.reduce((sum, row) => sum + row.chunk.content.length, 0) <= documentBudget) {
|
|
95
|
+
return rows.map((row) => candidateFromKnownRow(row, `known file ${knownFile}; complete document`, index));
|
|
96
|
+
}
|
|
97
|
+
const ftsQuery = ftsQueryFor(query);
|
|
98
|
+
const matches = ftsQuery ? repository.searchChunks(ftsQuery, KNOWN_FILE_SECTION_LIMIT, documentId) : [];
|
|
99
|
+
const candidates = matches.map((row) => candidateFromKnownRow(row, `known file ${knownFile}; FTS5 section match`, index));
|
|
100
|
+
const overview = rows[0];
|
|
101
|
+
if (overview && !matches.some((row) => row.chunk.id === overview.chunk.id)) {
|
|
102
|
+
candidates.push(candidateFromKnownRow(overview, `known file ${knownFile}; document overview`, index));
|
|
103
|
+
}
|
|
104
|
+
return candidates;
|
|
83
105
|
}
|
|
84
106
|
function resolveKnownFile(repository, knownFile) {
|
|
85
107
|
const queries = uniqueStrings([knownFile, normalizePath(knownFile)]);
|
|
@@ -107,8 +129,9 @@ function candidateFromKnownRow(row, reason, index) {
|
|
|
107
129
|
documentStatus: row.document.status,
|
|
108
130
|
trustTier: row.document.trustTier,
|
|
109
131
|
trustTierDeclared: hasDeclaredTrustTier(row.document),
|
|
110
|
-
score:
|
|
111
|
-
direct: true
|
|
132
|
+
score: 100 - row.rank - index / 1000,
|
|
133
|
+
direct: true,
|
|
134
|
+
known: true
|
|
112
135
|
};
|
|
113
136
|
}
|
|
114
137
|
function addAgentHints(result, knownFiles) {
|
|
@@ -283,8 +306,9 @@ function riskNotesForCandidate(candidate) {
|
|
|
283
306
|
}
|
|
284
307
|
function orderContextCandidates(candidates) {
|
|
285
308
|
return [
|
|
286
|
-
...orderContextCandidatesByPath(candidates.filter((candidate) => candidate.
|
|
287
|
-
...
|
|
309
|
+
...orderContextCandidatesByPath(candidates.filter((candidate) => candidate.known).sort(compareContextCandidates)),
|
|
310
|
+
...candidates.filter((candidate) => candidate.direct && !candidate.known).sort(compareContextCandidates),
|
|
311
|
+
...orderContextCandidatesByPath(candidates.filter((candidate) => !candidate.direct && !candidate.known).sort(compareContextCandidates))
|
|
288
312
|
];
|
|
289
313
|
}
|
|
290
314
|
function orderContextCandidatesByPath(sorted) {
|
|
@@ -323,22 +347,51 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
|
|
|
323
347
|
let usedChars = 0;
|
|
324
348
|
let budgetTruncatedItems = 0;
|
|
325
349
|
let budgetSkippedItems = 0;
|
|
326
|
-
|
|
327
|
-
|
|
350
|
+
const knownBudgets = knownDocumentBudgets(ranking.candidates, maxChars);
|
|
351
|
+
// Leave room for other direct evidence when a broad navigation section is large.
|
|
352
|
+
const directCount = Math.max(1, candidates.filter((candidate) => candidate.direct && !candidate.known).length);
|
|
353
|
+
const balancedQuery = ftsQueryGroups(query).some((tokens) => tokens.length > 12);
|
|
354
|
+
const directSectionBudget = Math.max(1, Math.floor(maxChars / Math.min(6, directCount)));
|
|
355
|
+
const directBudgets = balancedQuery
|
|
356
|
+
? allocateContextBudgets(ranking.candidates.filter((candidate) => candidate.direct && !candidate.known)
|
|
357
|
+
.map((candidate) => [candidate.nodeId, candidate.content.length]), maxChars - [...knownBudgets.values()].reduce((sum, chars) => sum + chars, 0))
|
|
358
|
+
: undefined;
|
|
359
|
+
const knownUsed = new Map();
|
|
360
|
+
const deferred = [];
|
|
361
|
+
const ordered = [...ranking.candidates];
|
|
362
|
+
for (let index = 0; index < ordered.length; index += 1) {
|
|
363
|
+
const candidate = ordered[index];
|
|
328
364
|
const remaining = maxChars - usedChars;
|
|
329
365
|
if (remaining <= 0) {
|
|
330
|
-
budgetSkippedItems +=
|
|
366
|
+
budgetSkippedItems += ordered.length - index;
|
|
331
367
|
break;
|
|
332
368
|
}
|
|
333
|
-
const
|
|
369
|
+
const available = candidate.known
|
|
370
|
+
? Math.min(remaining, (knownBudgets.get(candidate.path) ?? 0) - (knownUsed.get(candidate.path) ?? 0))
|
|
371
|
+
: Math.min(remaining, candidate.direct ? directBudgets?.get(candidate.nodeId) ?? directSectionBudget : remaining);
|
|
372
|
+
if (available <= 0) {
|
|
373
|
+
if (candidate.known)
|
|
374
|
+
deferred.push({ ...candidate, known: false });
|
|
375
|
+
else
|
|
376
|
+
budgetSkippedItems += 1;
|
|
377
|
+
if (index === ordered.length - 1)
|
|
378
|
+
ordered.push(...deferred.splice(0));
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
const excerpt = contextExcerpt(candidate, query, available);
|
|
382
|
+
const content = excerpt.content;
|
|
334
383
|
if (!content) {
|
|
335
384
|
budgetSkippedItems += 1;
|
|
385
|
+
if (index === ordered.length - 1)
|
|
386
|
+
ordered.push(...deferred.splice(0));
|
|
336
387
|
continue;
|
|
337
388
|
}
|
|
338
389
|
if (content.length < candidate.content.length) {
|
|
339
390
|
budgetTruncatedItems += 1;
|
|
340
391
|
}
|
|
341
392
|
usedChars += content.length;
|
|
393
|
+
if (candidate.known)
|
|
394
|
+
knownUsed.set(candidate.path, (knownUsed.get(candidate.path) ?? 0) + content.length);
|
|
342
395
|
items.push({
|
|
343
396
|
nodeId: candidate.nodeId,
|
|
344
397
|
documentId: candidate.documentId,
|
|
@@ -347,14 +400,17 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
|
|
|
347
400
|
path: candidate.path,
|
|
348
401
|
title: candidate.title,
|
|
349
402
|
heading: candidate.heading,
|
|
350
|
-
lines:
|
|
403
|
+
lines: excerpt.lines,
|
|
351
404
|
reason: candidate.reason,
|
|
352
405
|
matchedEntities: candidate.matchedEntities,
|
|
353
406
|
edgePath: candidate.edgePath,
|
|
354
407
|
sourceRefs: candidate.sourceRefs,
|
|
355
408
|
riskNotes: candidate.riskNotes,
|
|
356
|
-
content
|
|
409
|
+
content,
|
|
410
|
+
...(content.length < candidate.content.length ? { truncated: true } : {})
|
|
357
411
|
});
|
|
412
|
+
if (index === ordered.length - 1)
|
|
413
|
+
ordered.push(...deferred.splice(0));
|
|
358
414
|
}
|
|
359
415
|
const withCardSummaries = addContextCardSummaries(repository, items, maxChars - usedChars);
|
|
360
416
|
usedChars += withCardSummaries.usedChars;
|
|
@@ -381,6 +437,24 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
|
|
|
381
437
|
redundancySkippedItems: ranking.redundancySkippedItems
|
|
382
438
|
};
|
|
383
439
|
}
|
|
440
|
+
function knownDocumentBudgets(candidates, maxChars) {
|
|
441
|
+
const demand = new Map();
|
|
442
|
+
for (const candidate of candidates.filter((item) => item.known)) {
|
|
443
|
+
demand.set(candidate.path, (demand.get(candidate.path) ?? 0) + candidate.content.length);
|
|
444
|
+
}
|
|
445
|
+
return allocateContextBudgets([...demand], maxChars);
|
|
446
|
+
}
|
|
447
|
+
function allocateContextBudgets(demand, maxChars) {
|
|
448
|
+
const documents = [...demand].sort((left, right) => left[1] - right[1]);
|
|
449
|
+
const budgets = new Map();
|
|
450
|
+
let remaining = maxChars;
|
|
451
|
+
documents.forEach(([documentPath, chars], index) => {
|
|
452
|
+
const allocated = Math.min(chars, Math.floor(remaining / (documents.length - index)));
|
|
453
|
+
budgets.set(documentPath, allocated);
|
|
454
|
+
remaining -= allocated;
|
|
455
|
+
});
|
|
456
|
+
return budgets;
|
|
457
|
+
}
|
|
384
458
|
function addContextCardSummaries(repository, items, availableChars) {
|
|
385
459
|
if (availableChars < 32 || !items.length) {
|
|
386
460
|
return { items, usedChars: 0 };
|
|
@@ -434,7 +508,9 @@ function rankCandidatesWithMmr(repository, config, candidates, lambda) {
|
|
|
434
508
|
similaritySource: mostRedundant.source,
|
|
435
509
|
mmrScore: lambda * queryRelevance - (1 - lambda) * mostRedundant.value
|
|
436
510
|
};
|
|
437
|
-
}).sort((left, right) => (right.
|
|
511
|
+
}).sort((left, right) => (Number(Boolean(right.candidate.known)) - Number(Boolean(left.candidate.known))
|
|
512
|
+
|| Number(right.candidate.direct) - Number(left.candidate.direct)
|
|
513
|
+
|| right.mmrScore - left.mmrScore
|
|
438
514
|
|| right.queryRelevance - left.queryRelevance
|
|
439
515
|
|| left.order - right.order));
|
|
440
516
|
const best = scored[0];
|
|
@@ -547,10 +623,36 @@ function seedsFromSearchResult(result) {
|
|
|
547
623
|
function addCandidate(candidates, candidate) {
|
|
548
624
|
const key = candidate.nodeId;
|
|
549
625
|
const existing = candidates.get(key);
|
|
550
|
-
if (
|
|
551
|
-
|
|
626
|
+
if (existing?.direct && !candidate.direct)
|
|
627
|
+
return;
|
|
628
|
+
if (!existing || candidate.score > existing.score || (candidate.direct && !existing.direct) || candidate.known) {
|
|
629
|
+
candidates.set(key, existing ? {
|
|
630
|
+
...candidate,
|
|
631
|
+
known: candidate.known || existing.known,
|
|
632
|
+
score: Math.max(candidate.score, existing.score),
|
|
633
|
+
matchedEntities: uniqueStrings([...existing.matchedEntities, ...candidate.matchedEntities]),
|
|
634
|
+
reason: uniqueStrings([existing.reason, candidate.reason]).join("; ")
|
|
635
|
+
} : candidate);
|
|
552
636
|
}
|
|
553
637
|
}
|
|
638
|
+
function contextExcerpt(candidate, query, maxChars) {
|
|
639
|
+
if (candidate.content.length <= maxChars)
|
|
640
|
+
return { content: candidate.content, lines: candidate.lines };
|
|
641
|
+
const tokens = uniqueStrings(ftsQueryGroups(query).flat());
|
|
642
|
+
const paragraphs = [...candidate.content.matchAll(/[^\n]+(?:\n(?!\n)[^\n]+)*/gu)];
|
|
643
|
+
const best = paragraphs.map((match) => ({
|
|
644
|
+
offset: match.index,
|
|
645
|
+
content: match[0],
|
|
646
|
+
score: tokens.filter((token) => match[0].toLowerCase().includes(token)).length
|
|
647
|
+
})).sort((left, right) => right.score - left.score || left.offset - right.offset)[0];
|
|
648
|
+
const start = best?.score ? best.offset : 0;
|
|
649
|
+
const content = trimToBudget(candidate.content.slice(start), maxChars);
|
|
650
|
+
const firstLine = candidate.lines ? candidate.lines.start + candidate.content.slice(0, start).split("\n").length - 1 : undefined;
|
|
651
|
+
return {
|
|
652
|
+
content,
|
|
653
|
+
lines: firstLine === undefined ? undefined : { start: firstLine, end: Math.min(candidate.lines.end, firstLine + content.split("\n").length - 1) }
|
|
654
|
+
};
|
|
655
|
+
}
|
|
554
656
|
function edgeScore(edge) {
|
|
555
657
|
return edge.weight * edge.confidence;
|
|
556
658
|
}
|
|
@@ -582,10 +684,9 @@ function trimToBudget(content, maxChars) {
|
|
|
582
684
|
if (content.length <= maxChars) {
|
|
583
685
|
return content;
|
|
584
686
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
}
|
|
588
|
-
return `${content.slice(0, maxChars - 3).trimEnd()}...`.slice(0, maxChars);
|
|
687
|
+
const prefix = content.slice(0, maxChars <= 3 ? maxChars : maxChars - 3);
|
|
688
|
+
const safePrefix = /[\uD800-\uDBFF]$/u.test(prefix) ? prefix.slice(0, -1) : prefix;
|
|
689
|
+
return maxChars <= 3 ? safePrefix : `${safePrefix.trimEnd()}...`;
|
|
589
690
|
}
|
|
590
691
|
function hasDeclaredTrustTier(document) {
|
|
591
692
|
return typeof document.metadata?.declaredTrustTier === "string";
|
package/dist/query/search.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
|
|
2
2
|
import { createEmbeddingProvider, supportsSynchronousEmbeddingProvider } from "../semantic/provider-registry.js";
|
|
3
3
|
import { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector } from "../semantic/provider.js";
|
|
4
|
-
import { ftsQueryFor } from "../utils/fts.js";
|
|
4
|
+
import { ftsQueryFor, ftsQueryGroups } from "../utils/fts.js";
|
|
5
5
|
import { normalizeEntityName } from "../utils/text.js";
|
|
6
6
|
const RRF_K = 60;
|
|
7
7
|
const RRF_SCORE_WEIGHT = 1_000;
|
|
@@ -22,7 +22,19 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
|
|
|
22
22
|
const entityDocumentFrequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
|
|
23
23
|
const definitionRows = repository.findEntityDefinitions(matchedEntities.map((entity) => entity.id));
|
|
24
24
|
const ftsQuery = ftsQueryFor(query);
|
|
25
|
-
const
|
|
25
|
+
const queryGroups = ftsQueryGroups(query);
|
|
26
|
+
const balanceLongQuery = queryGroups.some((tokens) => tokens.length > 12);
|
|
27
|
+
const ftsRows = ftsQuery
|
|
28
|
+
? repository.searchChunks(ftsQuery, Math.min(128, Math.max(48, limit * 4, balanceLongQuery ? repository.counts().documents : 0)))
|
|
29
|
+
.map((row) => {
|
|
30
|
+
const coverage = countQueryGroupMatches(queryGroups, row.chunk.content);
|
|
31
|
+
const relevance = balanceLongQuery
|
|
32
|
+
? coverage / Math.sqrt(Math.max(300, row.chunk.content.length) / 300)
|
|
33
|
+
: coverage;
|
|
34
|
+
return { row, coverage, relevance };
|
|
35
|
+
})
|
|
36
|
+
.sort((left, right) => right.relevance - left.relevance || left.row.rank - right.row.rank)
|
|
37
|
+
: [];
|
|
26
38
|
const results = [];
|
|
27
39
|
for (const [index, row] of definitionRows.entries()) {
|
|
28
40
|
const matched = matchedEntitiesById.get(row.entityId);
|
|
@@ -39,7 +51,7 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
|
|
|
39
51
|
}
|
|
40
52
|
});
|
|
41
53
|
}
|
|
42
|
-
for (const [index, row] of ftsRows.entries()) {
|
|
54
|
+
for (const [index, { row, coverage, relevance }] of ftsRows.entries()) {
|
|
43
55
|
const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
|
|
44
56
|
const penalty = highFrequencyPenalty(matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold);
|
|
45
57
|
results.push({
|
|
@@ -48,8 +60,8 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
|
|
|
48
60
|
result: {
|
|
49
61
|
document: row.document,
|
|
50
62
|
section: row.section,
|
|
51
|
-
score: adjustScore(100 - row.rank, row.document, penalty),
|
|
52
|
-
reason: highFrequencyReason(
|
|
63
|
+
score: adjustScore(100 - (balanceLongQuery ? 0 : row.rank) + Math.min(20, relevance * 3), row.document, penalty),
|
|
64
|
+
reason: highFrequencyReason(`FTS5 content match${coverage > 1 ? `; matched ${Number(coverage.toFixed(2))} query groups` : ""}`, matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold),
|
|
53
65
|
content: row.chunk.content,
|
|
54
66
|
matchedEntities: matched
|
|
55
67
|
}
|
|
@@ -173,6 +185,11 @@ function matchedEntitiesForContent(entities, content) {
|
|
|
173
185
|
const lowerContent = content.toLowerCase();
|
|
174
186
|
return entities.filter((entity) => lowerContent.includes(entity.name.toLowerCase()) || lowerContent.includes(entity.normalizedName));
|
|
175
187
|
}
|
|
188
|
+
function countQueryGroupMatches(groups, content) {
|
|
189
|
+
const lowerContent = content.toLowerCase();
|
|
190
|
+
const uniqueGroups = new Map(groups.map((tokens) => [[...tokens].sort().join("\0"), tokens]));
|
|
191
|
+
return [...uniqueGroups.values()].reduce((coverage, tokens) => (coverage + tokens.filter((token) => lowerContent.includes(token)).length / tokens.length), 0);
|
|
192
|
+
}
|
|
176
193
|
function adjustScore(score, document, entityFrequencyPenalty = 0) {
|
|
177
194
|
return score + trustTierBoost(document.trustTier) + statusBoost(document.status) + entityFrequencyPenalty;
|
|
178
195
|
}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import
|
|
4
|
+
import { glob, globSync } from "tinyglobby";
|
|
5
5
|
import { BUILT_IN_DOC_EXCLUDES } from "../config/load-config.js";
|
|
6
6
|
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
7
7
|
export async function scanMarkdownFiles(projectRoot, config) {
|
|
8
8
|
const ignore = await resolveIgnorePatterns(projectRoot, config);
|
|
9
9
|
let entries;
|
|
10
10
|
try {
|
|
11
|
-
entries = await
|
|
11
|
+
entries = await glob(config.docs.include, {
|
|
12
12
|
cwd: projectRoot,
|
|
13
13
|
absolute: true,
|
|
14
14
|
onlyFiles: true,
|
|
15
|
-
|
|
15
|
+
expandDirectories: false,
|
|
16
16
|
dot: false,
|
|
17
17
|
followSymbolicLinks: false,
|
|
18
18
|
ignore
|
|
@@ -24,7 +24,7 @@ export async function scanMarkdownFiles(projectRoot, config) {
|
|
|
24
24
|
}
|
|
25
25
|
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
26
26
|
const accepted = [];
|
|
27
|
-
for (const entry of entries.sort()) {
|
|
27
|
+
for (const entry of [...new Set(entries)].sort()) {
|
|
28
28
|
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
29
29
|
continue;
|
|
30
30
|
}
|
|
@@ -42,11 +42,11 @@ export function scanMarkdownFilesSync(projectRoot, config) {
|
|
|
42
42
|
const ignore = resolveIgnorePatternsSync(projectRoot, config);
|
|
43
43
|
let entries;
|
|
44
44
|
try {
|
|
45
|
-
entries =
|
|
45
|
+
entries = globSync(config.docs.include, {
|
|
46
46
|
cwd: projectRoot,
|
|
47
47
|
absolute: true,
|
|
48
48
|
onlyFiles: true,
|
|
49
|
-
|
|
49
|
+
expandDirectories: false,
|
|
50
50
|
dot: false,
|
|
51
51
|
followSymbolicLinks: false,
|
|
52
52
|
ignore
|
|
@@ -57,7 +57,7 @@ export function scanMarkdownFilesSync(projectRoot, config) {
|
|
|
57
57
|
throw new Error(`Failed to scan Markdown files from ${projectRoot}: ${message}. Check docs.include and docs.exclude globs in ${path.join(projectRoot, ".mdgraph", "config.json")}.`);
|
|
58
58
|
}
|
|
59
59
|
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
60
|
-
return entries.sort().filter((entry) => {
|
|
60
|
+
return [...new Set(entries)].sort().filter((entry) => {
|
|
61
61
|
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
62
62
|
return false;
|
|
63
63
|
}
|
package/dist/utils/fts.d.ts
CHANGED
package/dist/utils/fts.js
CHANGED
|
@@ -1,30 +1,85 @@
|
|
|
1
1
|
const cjkRunPattern = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
|
|
2
|
+
const MAX_QUERY_TOKENS = 48;
|
|
2
3
|
export function ftsIndexContent(content) {
|
|
3
4
|
const cjkTokens = cjkNgramTokens(content);
|
|
4
5
|
return cjkTokens.length ? `${content}\n${cjkTokens.join(" ")}` : content;
|
|
5
6
|
}
|
|
6
7
|
export function ftsQueryFor(query) {
|
|
7
|
-
const
|
|
8
|
-
|
|
8
|
+
const groups = ftsQueryGroups(query);
|
|
9
|
+
const selected = new Set();
|
|
10
|
+
const order = [];
|
|
11
|
+
for (let left = 0, right = groups.length - 1; left <= right; left += 1, right -= 1) {
|
|
12
|
+
order.push(left);
|
|
13
|
+
if (left !== right)
|
|
14
|
+
order.push(right);
|
|
15
|
+
}
|
|
16
|
+
order.sort((left, right) => Number(isAsciiGroup(groups[right])) - Number(isAsciiGroup(groups[left])));
|
|
17
|
+
for (let offset = 0; selected.size < MAX_QUERY_TOKENS && groups.some((group) => offset < group.length); offset += 1) {
|
|
18
|
+
for (const index of order) {
|
|
19
|
+
if (selected.size === MAX_QUERY_TOKENS)
|
|
20
|
+
break;
|
|
21
|
+
const token = groups[index][offset];
|
|
22
|
+
if (token)
|
|
23
|
+
selected.add(token);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return [...selected].map((token) => /^\d+(?:\.\d+)+$/u.test(token)
|
|
27
|
+
? `(${token.split(".").join(" AND ")})`
|
|
28
|
+
: `${escapeFtsToken(token)}*`).join(" OR ");
|
|
9
29
|
}
|
|
10
30
|
export function ftsQueryTokens(query) {
|
|
31
|
+
// Local-hash vectors retain this frequency stream; query allocation uses groups.
|
|
11
32
|
const tokens = [];
|
|
12
|
-
const
|
|
13
|
-
for (const token of lexicalTokens) {
|
|
33
|
+
for (const token of query.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []) {
|
|
14
34
|
const cjkTokens = cjkNgramTokens(token);
|
|
15
35
|
tokens.push(...cjkTokens);
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
?.flatMap((part) => part.split("_")) ?? []);
|
|
20
|
-
if (!cjkTokens.length) {
|
|
36
|
+
tokens.push(...token.replace(cjkRunPattern, " ")
|
|
37
|
+
.match(/[\p{L}\p{N}_]+/gu)?.flatMap((part) => part.split("_")) ?? []);
|
|
38
|
+
if (!cjkTokens.length)
|
|
21
39
|
tokens.push(...token.split("_"));
|
|
40
|
+
}
|
|
41
|
+
return tokens.map(escapeFtsToken).filter((token) => token.length > 1 && !isFtsOperatorToken(token));
|
|
42
|
+
}
|
|
43
|
+
export function ftsQueryGroups(query) {
|
|
44
|
+
return (query.toLowerCase().match(/\d{4}-\d{2}-\d{2}|\d+(?:\.\d+)+|[\p{L}\p{N}_]+/gu) ?? [])
|
|
45
|
+
.map((token) => tokensForTerm(token))
|
|
46
|
+
.filter((tokens) => tokens.length > 0);
|
|
47
|
+
}
|
|
48
|
+
function tokensForTerm(token) {
|
|
49
|
+
if (/^\d{4}-\d{2}-\d{2}$/u.test(token))
|
|
50
|
+
return token.split("-");
|
|
51
|
+
if (/^\d+(?:\.\d+)+$/u.test(token))
|
|
52
|
+
return [token];
|
|
53
|
+
const tokens = [];
|
|
54
|
+
const cjkTokens = cjkNgramTokens(token);
|
|
55
|
+
tokens.push(...cjkTokens);
|
|
56
|
+
const nonCjkText = token.replace(cjkRunPattern, " ");
|
|
57
|
+
tokens.push(...nonCjkText
|
|
58
|
+
.match(/[\p{L}\p{N}_]+/gu)
|
|
59
|
+
?.flatMap((part) => part.split("_")) ?? []);
|
|
60
|
+
if (!cjkTokens.length) {
|
|
61
|
+
tokens.push(...token.split("_"));
|
|
62
|
+
}
|
|
63
|
+
const unique = [...new Set(tokens
|
|
64
|
+
.map(escapeFtsToken)
|
|
65
|
+
.filter((token) => token.length > 1)
|
|
66
|
+
.filter((token) => !isFtsOperatorToken(token)))];
|
|
67
|
+
const ascii = unique.filter((part) => /^[a-z0-9_]+$/u.test(part));
|
|
68
|
+
const cjk = unique.filter((part) => !/^[a-z0-9_]+$/u.test(part));
|
|
69
|
+
const alternating = [];
|
|
70
|
+
const bySize = [2, 3].map((size) => cjk.filter((part) => Array.from(part).length === size));
|
|
71
|
+
const longest = Math.max(...bySize.map((parts) => parts.length), 0);
|
|
72
|
+
for (let offset = 0; offset < longest; offset += 1) {
|
|
73
|
+
for (const parts of bySize) {
|
|
74
|
+
const index = offset % 2 === 0 ? Math.floor(offset / 2) : parts.length - 1 - Math.floor(offset / 2);
|
|
75
|
+
if (offset < parts.length)
|
|
76
|
+
alternating.push(parts[index]);
|
|
22
77
|
}
|
|
23
78
|
}
|
|
24
|
-
return
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
79
|
+
return [...ascii, ...alternating];
|
|
80
|
+
}
|
|
81
|
+
function isAsciiGroup(tokens) {
|
|
82
|
+
return tokens.some((token) => /^[a-z0-9_.]+$/u.test(token));
|
|
28
83
|
}
|
|
29
84
|
function cjkNgramTokens(content) {
|
|
30
85
|
const tokens = [];
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import chokidar from "chokidar";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { loadConfig } from "../config/load-config.js";
|
|
5
|
+
import { openExistingDatabase } from "../db/connection.js";
|
|
6
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
7
|
+
import { contentHash } from "../utils/id.js";
|
|
8
|
+
import { relativeUnixPath } from "../utils/text.js";
|
|
4
9
|
import { indexProject } from "../indexer.js";
|
|
5
10
|
import { resolveIgnorePatterns } from "../scanner/file-scanner.js";
|
|
6
11
|
import { WatchHealthTracker } from "./watch-health.js";
|
|
@@ -27,6 +32,7 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
27
32
|
let activeIndex;
|
|
28
33
|
let reloadInFlight;
|
|
29
34
|
let reloadQueued = false;
|
|
35
|
+
let indexedDocuments = new Map();
|
|
30
36
|
const runIndex = async () => {
|
|
31
37
|
if (closed) {
|
|
32
38
|
return;
|
|
@@ -40,6 +46,19 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
40
46
|
activeIndex = (async () => {
|
|
41
47
|
try {
|
|
42
48
|
const result = await indexProject(projectRoot, { semantic: options.semantic });
|
|
49
|
+
try {
|
|
50
|
+
const db = openExistingDatabase(projectRoot);
|
|
51
|
+
try {
|
|
52
|
+
indexedDocuments = new GraphRepository(db).documentHashes();
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
db.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Keep events eligible for indexing when the hash snapshot is unavailable.
|
|
60
|
+
indexedDocuments.clear();
|
|
61
|
+
}
|
|
43
62
|
health.recordIndexSuccess();
|
|
44
63
|
notifyIndexed(options.onIndexed, result);
|
|
45
64
|
}
|
|
@@ -70,23 +89,39 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
70
89
|
void runIndex();
|
|
71
90
|
}, debounceMs);
|
|
72
91
|
};
|
|
73
|
-
const scheduleIndexForMarkdown = (filePath) => {
|
|
92
|
+
const scheduleIndexForMarkdown = (filePath, event) => {
|
|
74
93
|
const lower = filePath.toLowerCase();
|
|
75
94
|
if (lower.endsWith(".md") || (config.index.parseMdx && lower.endsWith(".mdx"))) {
|
|
95
|
+
const absolutePath = path.resolve(projectRoot, filePath);
|
|
96
|
+
const indexed = indexedDocuments.get(relativeUnixPath(projectRoot, absolutePath));
|
|
97
|
+
if (event === "change" && indexed) {
|
|
98
|
+
try {
|
|
99
|
+
// Native watch can report a file read as a change; indexed content decides.
|
|
100
|
+
if (statSync(absolutePath).size <= config.index.maxFileBytes
|
|
101
|
+
&& contentHash(readFileSync(absolutePath, "utf8")) === indexed.hash)
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Let indexing diagnose unreadable or concurrently removed documents.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
76
108
|
scheduleIndex();
|
|
77
109
|
}
|
|
78
110
|
};
|
|
79
111
|
const bindWatcher = (candidate) => {
|
|
80
|
-
const onFileEvent = (filePath) => {
|
|
112
|
+
const onFileEvent = async (event, filePath) => {
|
|
81
113
|
if (isWatchControlFile(projectRoot, filePath)) {
|
|
82
114
|
void reloadWatchRules();
|
|
83
115
|
return;
|
|
84
116
|
}
|
|
85
|
-
|
|
117
|
+
if (activeIndex)
|
|
118
|
+
await activeIndex;
|
|
119
|
+
if (!closed)
|
|
120
|
+
scheduleIndexForMarkdown(filePath, event);
|
|
86
121
|
};
|
|
87
|
-
candidate.on("add", onFileEvent);
|
|
88
|
-
candidate.on("change", onFileEvent);
|
|
89
|
-
candidate.on("unlink", onFileEvent);
|
|
122
|
+
candidate.on("add", (filePath) => onFileEvent("add", filePath));
|
|
123
|
+
candidate.on("change", (filePath) => onFileEvent("change", filePath));
|
|
124
|
+
candidate.on("unlink", (filePath) => onFileEvent("unlink", filePath));
|
|
90
125
|
candidate.on("error", (error) => {
|
|
91
126
|
if (!ready)
|
|
92
127
|
return;
|
|
@@ -26,6 +26,8 @@ Use MDGraph as an invited documentation context layer, not as hidden memory and
|
|
|
26
26
|
When MDGraph detects a stale or unknown-freshness index, query tools may prepend a `⚠️ MDGraph freshness warning` banner and include additive `freshness` metadata in `structuredContent`. Treat that as a targeted warning about result freshness — refresh the index or read the named files directly — not as evidence that the MCP server itself is broken.
|
|
27
27
|
|
|
28
28
|
For coding tasks, include the task text in the `mdgraph_context` query and pass any known file paths through `knownFiles`. This gives MDGraph enough signal to return a task-start documentation brief with relevant docs, source refs, risk notes, provenance, deterministic auto-mode metadata, and `suggestedNextQueries`.
|
|
29
|
+
|
|
30
|
+
Document hints retrieve body sections within each named document, including an overview for long documents. Use `path#anchor` when a particular section is already known. Context auto mode sets `searchLimit` to twice the corresponding MCP search auto-mode result `limit` for the same query while keeping the requested character budget. Partial sections expose `truncated: true` and excerpt line ranges for a targeted follow-up read.
|
|
29
31
|
|
|
30
32
|
## Shared Instruction Template
|
|
31
33
|
|
package/docs/EN/Architecture.md
CHANGED
|
@@ -124,13 +124,12 @@ The diff report includes Markdown document additions, modifications, deletions,
|
|
|
124
124
|
- FTS5 chunk hits, including lightweight CJK n-gram matches for continuous Chinese/Japanese/Korean text.
|
|
125
125
|
- Exact entity matches.
|
|
126
126
|
- Optional embedding vector matches.
|
|
127
|
-
- Graph neighbors around matching entities.
|
|
128
127
|
|
|
129
128
|
When the same document or section is reached by multiple paths, search applies reciprocal rank fusion (RRF) across definition, FTS, and optional semantic channels, then keeps the highest base score while merging the main reasons and matched entities so provenance is not lost. Each fused result keeps an explainable `RRF fusion (...)` reason.
|
|
130
129
|
|
|
131
130
|
The synchronous `searchGraph`, `buildContext`, and `evaluateRetrieval` APIs retain their 1.0 behavior and can execute `local-hash` in process. Their async counterparts resolve external providers such as Ollama and are used by CLI and MCP query paths. Provider unavailability, timeouts, invalid responses, missing models, and missing vector coverage fall back to keyword/entity/graph retrieval with an additive `semanticDiagnostic`; CLI text and non-explain JSON commands also write the diagnostic to stderr.
|
|
132
131
|
|
|
133
|
-
`buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path. The
|
|
132
|
+
`buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path. The default retains its selector name while prioritizing known-document bodies and direct-hit relevance before document-round-robin graph expansion; known documents use file-scoped section retrieval and share the existing character budget. Partial sections include excerpt line ranges and a truncation marker. Opt-in `mmr` maximizes query relevance within the known-file, direct-search, and graph-expansion priority tiers minus redundancy, uses stored configured-provider vectors when both candidates have them, falls back to deterministic Unicode-token Jaccard otherwise, and prunes same-document near duplicates while preserving a first candidate from each document.
|
|
134
133
|
|
|
135
134
|
Every context result includes additive packing metadata. When requested through `context --debug`, context building also reports seed nodes, visited nodes, expanded edges, skipped expansion reasons, candidate counts, strategy/similarity selection, per-item query relevance, redundancy penalty and MMR score, redundancy pruning, and budget truncation counts. These diagnostics are not graph facts; they exist to explain context packing and evaluate retrieval quality.
|
|
136
135
|
|
|
@@ -79,7 +79,7 @@ For each question, compare agent behavior with and without MDGraph attached:
|
|
|
79
79
|
- Whether the context returned by MDGraph is sufficient without follow-up file inspection.
|
|
80
80
|
- Time and tool-call count for the full agent run.
|
|
81
81
|
- `mdgraph eval` metrics: top-K document recall, expected-section recall, context precision, trace success, latency, returned character count, budget fit, fanout, context diversity, reason coverage, and ranking reason coverage.
|
|
82
|
-
- `mdgraph eval` ranking report: query mode, RRF search fusion channels, compatibility context packing strategy, optional reranker status, and semantic-active case count. Use the focused context regression suite to compare opt-in true MMR against
|
|
82
|
+
- `mdgraph eval` ranking report: query mode, RRF search fusion channels, compatibility context packing strategy, optional reranker status, and semantic-active case count. Use the focused context regression suite to compare opt-in true MMR against the current deterministic default, recording the code version and character budget.
|
|
83
83
|
|
|
84
84
|
Use `mdgraph report --benchmark benchmark-runs.json --json` for A/B reporting on these questions. It consumes structured run records and reports aggregate deltas; full transcripts should remain outside public docs.
|
|
85
85
|
|
|
@@ -89,6 +89,12 @@ The legacy `entityRecall`, `sourceRefRecall`, and `edgeKindCoverage` metrics mea
|
|
|
89
89
|
|
|
90
90
|
Use `retrievedEntityRecall`, `retrievedSourceRefRecall`, and `retrievedEdgeKindCoverage` to measure evidence exposed by search, context, and the requested trace. `observed.retrievedEntities`, `retrievedSourceRefs`, and `retrievedEdgeKinds` identify that evidence. `retrievalEvidencePassed` requires both the legacy checks and complete returned-evidence coverage. `contextIrrelevantRatio` measures the fraction of returned context items outside the expected document set; an empty result has ratio zero but cannot establish recall.
|
|
91
91
|
|
|
92
|
+
## Fixed-corpus and held-out query checks
|
|
93
|
+
|
|
94
|
+
For retrieval changes, freeze the source revision or file hashes, index scope, question set, and character budget. Compare returned path-specific evidence against both the original baseline and the latest accepted version, retaining raw MCP responses outside public release artifacts. Separate target-section candidate recall from evidence retained after packing.
|
|
95
|
+
|
|
96
|
+
Freeze new questions before implementation and use them only for validation. Report their provenance: source-derived, maintainer-authored questions do not establish independent-user effectiveness. Preserve literal scores; any accepted equivalent wording must be declared explicitly. Report per-evidence gains and losses as well as aggregate complete-question counts. The fixed-set evidence score does not measure final model-answer accuracy.
|
|
97
|
+
|
|
92
98
|
## Reproducible performance samples
|
|
93
99
|
|
|
94
100
|
Run `npm run baseline:performance -- 100,500` after installing dependencies. The script creates independent synthetic document corpora, indexes local-hash vectors, modifies one document, and measures full/incremental indexing plus card, context, and semantic-query latency. Query values are medians of five samples following one warmup. Memory values are process heap/RSS after the operations, not peak allocation. The JSON includes runtime, platform, corpus sizes, counts, and retained fixture paths. These measurements are reproducible engineering samples, not real-agent effectiveness or large-production performance claims.
|
package/docs/EN/Operations.md
CHANGED
|
@@ -38,6 +38,8 @@ mdgraph watch --path /path/to/project
|
|
|
38
38
|
mdgraph serve --mcp --path /path/to/project
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
Native Markdown change events are compared with the last successfully indexed file-content hash. Unchanged content does not trigger another index callback; real edits, additions, removals, and configuration changes retain their update flow. Events arriving during indexing are checked after that attempt finishes.
|
|
42
|
+
|
|
41
43
|
The watcher exposes an in-process health snapshot through `WatchHandle.getHealth()`. Integrated MCP serving adds it to `mdgraph_status.structuredContent.watchHealth`.
|
|
42
44
|
|
|
43
45
|
| State | Meaning | Operator action |
|
|
@@ -74,10 +74,12 @@ When semantic retrieval is requested but cannot run, `search` still returns FTS5
|
|
|
74
74
|
|
|
75
75
|
- `query`: original query text.
|
|
76
76
|
- `maxChars`: configured context budget.
|
|
77
|
-
- `usedChars`: packed `content`
|
|
77
|
+
- `usedChars`: the sum of packed `content` and optional `cardSummary` lengths, measured in JavaScript UTF-16 code units.
|
|
78
78
|
- `packing`: additive packing metadata with `strategy`; opt-in MMR also reports `similarity`, `mmrLambda`, and optional `redundancySkippedItems`.
|
|
79
79
|
- `semanticDiagnostic`: optional provider fallback details; absent when semantic retrieval was not requested or completed normally.
|
|
80
|
-
- `items`: context items with `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath`, optional `sourceRefs`, optional `riskNotes`, optional `cardSummary`, and `content`.
|
|
80
|
+
- `items`: context items with `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, `path`, `title`, optional `heading`, optional `lines`, `reason`, `matchedEntities`, optional `edgePath`, optional `sourceRefs`, optional `riskNotes`, optional `cardSummary`, optional `truncated`, and `content`.
|
|
81
|
+
|
|
82
|
+
`truncated: true` identifies a partial section. Its `lines` cover the returned excerpt; the retained section identity and anchor resolve the complete source. Known-file evidence shares the same `maxChars` budget with ordinary search and graph evidence. The budget excludes JSON keys, reasons, paths, other metadata, and text-format headings; it is not a token budget or a limit on the serialized MCP response.
|
|
81
83
|
|
|
82
84
|
`cardSummary` is an experimental deterministic Knowledge Card summary. It is added only to the highest-ranked packed items when the original document content leaves spare budget; it is omitted if the complete summary does not fit, preserving original content and recovery fields.
|
|
83
85
|
|
|
@@ -40,7 +40,7 @@ This document records the public contract boundary for the current release line,
|
|
|
40
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. |
|
|
41
41
|
| MCP text output wording | experimental | `src/mcp/tools.ts` | Text is human-facing guidance; `structuredContent` is the preferred machine contract. |
|
|
42
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. |
|
|
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. |
|
|
43
|
+
| Context recovery fields | stable-additive | `src/query/context-builder.ts` | Context items expose `nodeId`, `documentId`, optional `sectionId`, optional `anchor`, excerpt line ranges, optional `truncated: true`, source refs, risk notes, and graph-expansion `edgePath` so agents can recover nodes and provenance without guessing from prose. |
|
|
44
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. |
|
|
45
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. |
|
|
46
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. |
|
|
@@ -4,7 +4,7 @@ Use this checklist before publishing an MDGraph release or asking a maintainer t
|
|
|
4
4
|
|
|
5
5
|
## Public checks
|
|
6
6
|
|
|
7
|
-
- Confirm the public package is `@daogee/mdgraph`, the installed binary remains `mdgraph`, and `package.json`
|
|
7
|
+
- Confirm the public package is `@daogee/mdgraph`, the installed binary remains `mdgraph`, and `package.json`, the root `package-lock.json` version, and the CLI version 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
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.
|
|
@@ -87,7 +87,7 @@ Expected results:
|
|
|
87
87
|
- Confirm the package includes `dist`, the agent pack, both README files, `CHANGELOG.md`, `LICENSE`, and the explicitly allowlisted English/Chinese guides.
|
|
88
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
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.
|
|
90
|
+
- Run `npm run smoke:pack`; it verifies runtime/type consumption and rejects implementation-stage documentation in the tarball. This smoke copies packed files into a temporary consumer and links existing runtime dependencies; record the clean-prefix tarball installation above separately.
|
|
91
91
|
|
|
92
92
|
## Note text
|
|
93
93
|
|
|
@@ -16,14 +16,17 @@ MDGraph combines deterministic full-text, entity, and graph retrieval by default
|
|
|
16
16
|
|
|
17
17
|
## Search Channels
|
|
18
18
|
|
|
19
|
-
`search` combines and deduplicates
|
|
19
|
+
`search` combines and deduplicates three explainable channels:
|
|
20
20
|
|
|
21
21
|
- FTS5 chunk matches, with lightweight CJK n-gram augmentation for continuous Chinese, Japanese, and Korean text.
|
|
22
22
|
- Exact technical-entity matches.
|
|
23
|
-
- Graph neighbors around matching entities and documents.
|
|
24
23
|
- Optional embedding-vector matches when a supported provider is enabled, indexed, and requested.
|
|
25
24
|
|
|
26
|
-
Reciprocal rank fusion (RRF) combines the active channels.
|
|
25
|
+
Reciprocal rank fusion (RRF) combines the active channels. Search results retain reasons, matched entities, and optional semantic provider/model metadata. Context graph expansion also reports edge provenance. Semantic results are an additional signal; they do not replace the deterministic channels. Graph neighbors are added during context building after search.
|
|
26
|
+
|
|
27
|
+
FTS queries deduplicate terms and distribute at most 48 tokens across the beginning and end of query groups. Latin identifiers, complete numeric versions, and dates retain their own groups; CJK two- and three-character grams share the allocation. Retrieval takes a bounded candidate pool independently of the requested result limit, then ranks FTS candidates by query-group coverage with BM25 as a tie-breaker before RRF. Coverage measures the fraction of each group's tokens present in the source text.
|
|
28
|
+
|
|
29
|
+
For queries with a group containing more than 12 grams, the candidate pool also grows with the indexed document count up to 128; smaller indexes retain the existing limit-based pool. Coverage is divided by `sqrt(max(300, section characters) / 300)` and the FTS base score omits raw BM25. Short keyword queries retain the BM25 contribution to the base score. Entity/semantic fusion and document trust/lifecycle adjustments also contribute to final result order. This remains lexical matching, not synonym understanding.
|
|
27
30
|
|
|
28
31
|
## Semantic Providers
|
|
29
32
|
|
|
@@ -83,7 +86,13 @@ Unicode-aware rules recognize CJK API paths such as `POST /接口/登录`, segme
|
|
|
83
86
|
|
|
84
87
|
`context` starts from ranked search sections, performs bounded graph expansion through non-containment edges, and packs selected sections under a character budget.
|
|
85
88
|
|
|
86
|
-
The
|
|
89
|
+
The default retains the selector `mmr-style-document-round-robin`. Known-file evidence is introduced across documents first; other direct search hits keep their relevance order, followed by document-round-robin graph expansion. This prevents a highly ranked section from being delayed behind many lower-ranked documents. It remains deterministic and does not calculate pairwise relevance and redundancy.
|
|
90
|
+
|
|
91
|
+
MCP `knownFiles` and library options accept document paths, explicit `path#anchor` sections, and indexed source references. A short document contributes its complete sections when they fit its initial budget share. A longer document contributes up to four file-scoped FTS sections in BM25 order plus its overview. SQL applies the document restriction before the candidate limit. Source references use the same document selection through their existing graph edges; an explicit section keeps its identity.
|
|
92
|
+
|
|
93
|
+
Known documents share the character budget according to their actual candidate sizes: short documents release unused capacity to longer documents. For queries with a group containing more than 12 grams, direct candidates share the remaining budget by actual text length before graph expansion. Short keyword queries use an initial per-section share based on at most six direct candidates.
|
|
94
|
+
|
|
95
|
+
A partial section starts at a query-relevant paragraph, includes `truncated: true`, and reports the excerpt's actual line range. Use the retained path, section identity, or anchor to locate the complete source for a targeted Markdown read. Original content and optional card summaries together remain bounded by `maxChars`.
|
|
87
96
|
|
|
88
97
|
True MMR is opt-in:
|
|
89
98
|
|
|
@@ -92,7 +101,7 @@ mdgraph context --packing mmr --mmr-lambda 0.65 --debug --json \
|
|
|
92
101
|
--path /path/to/project "session recovery"
|
|
93
102
|
```
|
|
94
103
|
|
|
95
|
-
MCP callers select the same behavior with `packingStrategy: "mmr"
|
|
104
|
+
MCP callers select the same behavior with `packingStrategy: "mmr"`; CLI and library callers may also provide `mmrLambda`. Within the known-file, direct-search, and graph-expansion priority tiers, MMR maximizes:
|
|
96
105
|
|
|
97
106
|
```text
|
|
98
107
|
lambda * queryRelevance - (1 - lambda) * maximumSimilarityToSelected
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
|
|
16
16
|
对于 coding task,把任务描述写进 `mdgraph_context` 查询,并通过 `knownFiles` 传入已知文件路径。这样 MDGraph 可以返回更像 task-start documentation brief 的结果:相关文档、source refs、risk notes、provenance、确定性的 auto-mode metadata 和 `suggestedNextQueries`。
|
|
17
17
|
|
|
18
|
+
文档路径会触发文件内部的正文章节检索;长文档同时保留概述。已经知道具体章节时,可传入 `path#anchor`。Context 自动模式的 `searchLimit` 是同一查询对应 MCP search 自动模式结果上限 `limit` 的两倍,仍遵守请求中的字符预算。部分章节通过 `truncated: true` 和实际片段行号,支持继续读取指定原文。
|
|
19
|
+
|
|
18
20
|
## 共享 Instruction Template
|
|
19
21
|
|
|
20
22
|
```text
|
package/docs/ZH/Architecture.md
CHANGED
|
@@ -109,13 +109,12 @@ Diff report 包含 Markdown 文档新增、修改、删除、Git 识别的 renam
|
|
|
109
109
|
- FTS5 块命中,包含连续中文/日文/韩文文本的轻量 CJK n-gram 命中。
|
|
110
110
|
- 精确实体匹配。
|
|
111
111
|
- 可选 embedding 向量匹配。
|
|
112
|
-
- 匹配实体周围的图邻居。
|
|
113
112
|
|
|
114
113
|
当同一文档或章节通过多条路径命中时,搜索会在 definition、FTS 和可选 semantic 通道之间应用 reciprocal rank fusion(RRF),再保留最高基础分,同时合并主要命中原因和匹配实体,避免丢失来源解释。每个融合结果都会保留可解释的 `RRF fusion (...)` reason。
|
|
115
114
|
|
|
116
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。
|
|
117
116
|
|
|
118
|
-
然后 `buildContext` 从排序后的搜索章节开始,通过非包含边执行有界图扩展,在字符预算下打包选定的章节,并包含原因,如 FTS
|
|
117
|
+
然后 `buildContext` 从排序后的搜索章节开始,通过非包含边执行有界图扩展,在字符预算下打包选定的章节,并包含原因,如 FTS 命中、语义命中、精确实体匹配或图边遍历路径。默认策略保留原选择器名称,先引入已知文档正文和按相关度排序的直接命中,再按文档轮询引入图扩展候选;已知文档先在文件内检索章节,并共享现有字符预算。部分章节返回实际片段行号和截断标记。可选 `mmr` 在已知文件、直接命中和图扩展各自的优先级内最大化 query relevance 并惩罚冗余;两个候选都有当前 provider 已存向量时使用向量相似度,否则回退到确定性的 Unicode token Jaccard,并剪除同文档近重复项,同时保留每个文档的首个候选。
|
|
119
118
|
|
|
120
119
|
每个 context 结果都会包含 additive packing metadata。当请求 `context --debug` 时,上下文构建还会报告 seed nodes、visited nodes、expanded edges、跳过原因、候选数量、策略/相似度选择、逐项 query relevance、redundancy penalty 和 MMR score、冗余剪枝及预算截断计数。这些诊断不是图事实,只用于解释上下文打包和评估检索质量。
|
|
121
120
|
|
|
@@ -67,7 +67,7 @@ Watcher tests 覆盖启动/运行期 `ENOSPC`、运行期 `EMFILE`、启动期 `
|
|
|
67
67
|
- MDGraph 返回的上下文是否足够,无需进一步检查文件。
|
|
68
68
|
- 整个代理运行的时间和工具调用次数。
|
|
69
69
|
- `mdgraph eval` 指标:top-K 文档召回、预期章节召回、上下文精度、trace 成功率、延迟、返回字符数、预算适配、fanout、上下文多样性、reason 覆盖率和 ranking reason 覆盖率。
|
|
70
|
-
- `mdgraph eval` 排序报告:query mode、RRF 搜索融合通道、兼容上下文打包策略、可选 reranker 状态和 semantic-active case 数量。使用聚焦 context 回归套件对比可选真 MMR
|
|
70
|
+
- `mdgraph eval` 排序报告:query mode、RRF 搜索融合通道、兼容上下文打包策略、可选 reranker 状态和 semantic-active case 数量。使用聚焦 context 回归套件对比可选真 MMR 和当前确定性默认策略,并记录代码版本与字符预算。
|
|
71
71
|
|
|
72
72
|
A/B 报告入口是 `mdgraph report --benchmark benchmark-runs.json --json`。它消费结构化 run records 并报告 aggregate deltas;完整 transcript 应保留在公开文档之外。
|
|
73
73
|
|
|
@@ -87,6 +87,12 @@ A/B 报告入口是 `mdgraph report --benchmark benchmark-runs.json --json`。
|
|
|
87
87
|
|
|
88
88
|
新增 `retrievedEntityRecall`、`retrievedSourceRefRecall`、`retrievedEdgeKindCoverage` 仅统计 search、context 和本次 trace 实际暴露的证据;对应名称记录在 `observed.retrievedEntities`、`retrievedSourceRefs`、`retrievedEdgeKinds`。`retrievalEvidencePassed` 要求原有检查和返回证据覆盖同时通过。`contextIrrelevantRatio` 是返回上下文中不属于预期文档的项目占比;空结果占比为零,但不代表召回成功。
|
|
89
89
|
|
|
90
|
+
## 固定语料与新问题验证
|
|
91
|
+
|
|
92
|
+
检索变化应冻结源码版本或文件哈希、索引范围、问题集和字符预算。按预期文件逐条比较返回证据,同时对比最初基线和最近采用的版本;完整 MCP 返回保留在公开发布包之外。分别测量目标章节进入候选集的比例,以及打包后保留的证据。
|
|
93
|
+
|
|
94
|
+
新问题在实施前固定,仅用于验证,并说明来源。依据同一语料由维护者编写的新题,不能证明独立用户的使用效果。保留严格字符串评分;接受等价措辞时应明确列出。除完整命中题数外,还应逐条报告证据增加和丢失。固定集的证据分数不代表模型最终答案正确率。
|
|
95
|
+
|
|
90
96
|
## 可重复的性能样本
|
|
91
97
|
|
|
92
98
|
安装依赖后运行 `npm run baseline:performance -- 100,500`。脚本生成独立的合成文档集,索引 local-hash 向量、修改一个文档,测量全量/增量索引以及卡片、context、语义查询耗时。查询先预热一次,再报告五次采样的中位数。内存是操作后的进程 heap/RSS,不是峰值分配。JSON 包含运行时、平台、文档规模、记录计数和保留的样本路径。这些结果用于工程比较,不代表真实代理效果或生产大规模性能。
|
package/docs/ZH/Operations.md
CHANGED
|
@@ -38,6 +38,8 @@ mdgraph watch --path /path/to/project
|
|
|
38
38
|
mdgraph serve --mcp --path /path/to/project
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
原生 Markdown 变更事件会与最近一次成功索引保存的文件内容哈希比较。文件内容相同不会再次触发索引回调;真实修改、新增、删除和配置变更仍按原有流程更新。索引运行期间收到的事件会在本次索引结束后检查。
|
|
42
|
+
|
|
41
43
|
Watcher 通过 `WatchHandle.getHealth()` 暴露进程内 health snapshot。集成 MCP serving 会把它加入 `mdgraph_status.structuredContent.watchHealth`。
|
|
42
44
|
|
|
43
45
|
| 状态 | 含义 | 运维动作 |
|
|
@@ -74,10 +74,12 @@
|
|
|
74
74
|
|
|
75
75
|
- `query`:原始查询文本。
|
|
76
76
|
- `maxChars`:配置的上下文预算。
|
|
77
|
-
- `usedChars`:已打包 `content` 与可选 `cardSummary`
|
|
77
|
+
- `usedChars`:已打包 `content` 与可选 `cardSummary` 的长度总和,按 JavaScript UTF-16 code unit 计数。
|
|
78
78
|
- `packing`:additive 打包 metadata,包含 `strategy`;可选 MMR 还会报告 `similarity`、`mmrLambda` 和可选 `redundancySkippedItems`。
|
|
79
79
|
- `semanticDiagnostic`:可选 provider 降级详情;未请求 semantic retrieval 或正常完成时不出现。
|
|
80
|
-
- `items`:上下文条目,包含 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor`、`path`、`title`、可选 `heading`、可选 `lines`、`reason`、`matchedEntities`、可选 `edgePath`、可选 `sourceRefs`、可选 `riskNotes`、可选 `cardSummary` 和 `content`。
|
|
80
|
+
- `items`:上下文条目,包含 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor`、`path`、`title`、可选 `heading`、可选 `lines`、`reason`、`matchedEntities`、可选 `edgePath`、可选 `sourceRefs`、可选 `riskNotes`、可选 `cardSummary`、可选 `truncated` 和 `content`。
|
|
81
|
+
|
|
82
|
+
`truncated: true` 表示只返回了部分章节。`lines` 对应实际返回片段,保留的章节身份和锚点可定位完整原文。已知文件证据与普通搜索、图扩展证据共享同一个 `maxChars` 预算。 预算不计 JSON 字段名、原因、路径等 metadata 或文本格式标题;它不是 token 预算,也不是整个序列化 MCP 响应的长度上限。
|
|
81
83
|
|
|
82
84
|
`cardSummary` 是实验性的确定性 Knowledge Card 摘要。只有原始文档内容装入后仍有剩余预算时,才会为排名最高的已选条目增加该字段;预算不足以容纳完整摘要时省略它,不会挤掉原始内容或恢复字段。
|
|
83
85
|
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
| 派生关系执行 | 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。 |
|
|
34
34
|
| MCP text output wording | experimental | `src/mcp/tools.ts` | 文本是面向人的提示;机器契约优先使用 `structuredContent`。 |
|
|
35
35
|
| 动态 Knowledge Card 投影 | experimental / stable-additive | `src/query/knowledge-card.ts`、`src/query/context-builder.ts`、`src/bin/mdgraph.ts`、`src/mcp/tools.ts` | 找到 document、section、entity 或 source-ref 时,`node` 结果可增量返回确定性、非持久化的 `card`;已选 context item 只会使用原始内容装入后的剩余预算增加 `cardSummary`,且字符计入 `usedChars`。既有 node 字段、ranking、trace path、SQLite counts 和五工具 MCP surface 均不改变。 |
|
|
36
|
-
| Context recovery fields | stable-additive | `src/query/context-builder.ts` | Context item 暴露 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor
|
|
36
|
+
| Context recovery fields | stable-additive | `src/query/context-builder.ts` | Context item 暴露 `nodeId`、`documentId`、可选 `sectionId`、可选 `anchor`、实际片段 line range、可选 `truncated: true`、source refs、risk notes 和 graph-expansion `edgePath`,让 agent 无需从 prose 猜测即可恢复节点和 provenance。 |
|
|
37
37
|
| `.mdgraph/config.json` fields | stable | `src/config/load-config.ts` | `docs`、`index`、`search`、`entities` 和 `embedding` 默认字段稳定。Additive embedding 字段为 `endpoint`、`timeoutMs` 和 `batchSize`,既有配置文件会取得默认值。当前 merge 逻辑会忽略未知字段。 |
|
|
38
38
|
| `.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`。 |
|
|
39
39
|
| SQLite schema metadata | stable | `src/db/schema.sql`、`src/db/connection.ts` | `schema_metadata.schema_version` 是兼容 gate。未来 schema version 会在应用本地 schema 前失败。 |
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
## 公开检查
|
|
6
6
|
|
|
7
|
-
- 确认公开 package 为 `@daogee/mdgraph`、安装后的 binary 仍为 `mdgraph`,并且 `package.json`
|
|
7
|
+
- 确认公开 package 为 `@daogee/mdgraph`、安装后的 binary 仍为 `mdgraph`,并且 `package.json`、`package-lock.json` 根包版本和 CLI 版本与 release tag 一致。
|
|
8
8
|
- Tag 前把 [CHANGELOG.md](../../CHANGELOG.md) 中与本次发布相关的 `Unreleased` 条目提升为带日期、且版本号与 `package.json` 一致的正式版本。
|
|
9
9
|
- 当公开 CLI/MCP 行为变化时,复查 README quick start、运行要求、MCP setup、输出契约、公开契约标签和已知 tradeoff。
|
|
10
10
|
- 确认 GitHub 仓库仍公开 `README.md`、`LICENSE`、`CONTRIBUTING.md`、`SECURITY.md`、Issue templates 与 PR template;公开发布前复查 GitHub community profile。
|
|
@@ -87,7 +87,7 @@ git diff --check
|
|
|
87
87
|
- 确认 package 包含 `dist`、agent pack、两份 README、`CHANGELOG.md`、`LICENSE` 和显式 allowlist 中的中英文指南。
|
|
88
88
|
- 确认 package 不包含编号实施阶段文档、内部实施 ADR、`docs/tasks/`、`.mdgraph/`、本地数据库、`.DS_Store`、临时输出或外部工作区内容。
|
|
89
89
|
- 发布前在干净的临时 prefix 中全局安装打包 tarball,并验证 `mdgraph --version`、`init` 和一个代表性查询。
|
|
90
|
-
- 运行 `npm run smoke:pack`;它会验证 runtime/type consumer,并拒绝 tarball 中的实施阶段文档。
|
|
90
|
+
- 运行 `npm run smoke:pack`;它会验证 runtime/type consumer,并拒绝 tarball 中的实施阶段文档。 该 smoke 将打包文件复制到临时 consumer,并链接已有 runtime dependencies;上面的干净 prefix tarball 安装应另行记录。
|
|
91
91
|
|
|
92
92
|
## Release notes 文案
|
|
93
93
|
|
|
@@ -16,14 +16,17 @@ MDGraph 默认组合确定性的全文、实体与图检索。真实 embedding p
|
|
|
16
16
|
|
|
17
17
|
## 搜索通道
|
|
18
18
|
|
|
19
|
-
`search`
|
|
19
|
+
`search` 会组合并去重三类可解释通道:
|
|
20
20
|
|
|
21
21
|
- FTS5 chunk 匹配;连续中文、日文和韩文会增加轻量 CJK n-gram token。
|
|
22
22
|
- 精确技术实体匹配。
|
|
23
|
-
- 匹配实体和文档周围的图邻居。
|
|
24
23
|
- 当支持的 provider 已启用、完成索引并被请求时,增加可选 embedding vector 匹配。
|
|
25
24
|
|
|
26
|
-
Reciprocal rank fusion(RRF
|
|
25
|
+
Reciprocal rank fusion(RRF)会融合当前激活的通道。搜索结果保留原因、命中实体和可选的 semantic provider/model metadata;context 图扩展还会报告边的 provenance。语义结果是附加信号,不会替代确定性通道。 图邻居由后续 context 构建阶段引入。
|
|
26
|
+
|
|
27
|
+
FTS 查询先去重,再把最多 48 个词元分配到各查询组的前后部分。Latin 标识符、完整数字版本号和日期保留各自的查询组;CJK 二元和三元片段共同分配名额。检索先取有界候选集,候选数量与最终结果数量分开控制;FTS 候选先按查询组覆盖比例排序,相同时用 BM25 决定顺序,再参与 RRF。覆盖比例表示各组词元在正文中出现的比例。
|
|
28
|
+
|
|
29
|
+
当任一查询组包含超过 12 个词元片段时,候选范围也随已索引文档数量增长,最多 128 条;较小索引保持原有按结果数量计算的范围。覆盖比例除以 `sqrt(max(300, 章节字符数) / 300)`,FTS 基础分不再包含原始 BM25;短关键词查询仍保留 BM25 基础分。实体/语义通道融合,以及文档可信级别和生命周期状态,也会影响最终顺序。这仍是词法匹配,不代表能理解同义改写。
|
|
27
30
|
|
|
28
31
|
## 语义 Provider
|
|
29
32
|
|
|
@@ -83,7 +86,13 @@ Unicode-aware 规则可识别 `POST /接口/登录` 这样的 CJK API path、`
|
|
|
83
86
|
|
|
84
87
|
`context` 从排序后的 search section 开始,通过非 containment edge 做有界图扩展,并在字符预算内打包入选 section。
|
|
85
88
|
|
|
86
|
-
|
|
89
|
+
默认策略继续使用 `mmr-style-document-round-robin` 这一名称。已知文件的证据先按文档轮流引入,其他直接搜索命中保持相关度顺序,图扩展候选随后按文档轮询。这样,高排名章节不会因为同一文件已出现过而被推迟到许多低排名文档之后。该策略保持确定性,不计算候选之间的两两冗余。
|
|
90
|
+
|
|
91
|
+
MCP `knownFiles` 和库选项接受文档路径、明确的 `path#anchor` 章节,以及已索引的源码引用。短文档在初始预算份额内可贡献全部章节;长文档贡献文件内部 FTS 按 BM25 排序的前四个章节及文档概述。SQL 在限制候选数量前先限定文件。源码引用沿既有图边使用同一文档选择方法;明确的章节保留其节点身份。
|
|
92
|
+
|
|
93
|
+
已知文档按候选正文的实际长度共享字符预算,短文档未使用的额度交给长文档。当任一查询组包含超过 12 个词元片段时,直接候选按实际正文长度分配剩余预算,之后才打包图扩展;短关键词查询按最多六个直接候选计算初始单项份额。
|
|
94
|
+
|
|
95
|
+
部分正文从与查询相关的段落开始,带有 `truncated: true`,行号对应实际返回的片段。需要完整原文时,使用保留的路径、章节身份或锚点定位并读取相应 Markdown。原始正文和可选 Card 摘要的总长度仍不超过 `maxChars`。
|
|
87
96
|
|
|
88
97
|
真正的 MMR 必须显式选择:
|
|
89
98
|
|
|
@@ -92,7 +101,7 @@ mdgraph context --packing mmr --mmr-lambda 0.65 --debug --json \
|
|
|
92
101
|
--path /path/to/project "session recovery"
|
|
93
102
|
```
|
|
94
103
|
|
|
95
|
-
MCP caller 使用 `packingStrategy: "mmr"`
|
|
104
|
+
MCP caller 使用 `packingStrategy: "mmr"` 选择同一行为;CLI 和库调用也可以提供 `mmrLambda`。MMR 在已知文件、直接搜索命中和图扩展候选各自的优先级内最大化:
|
|
96
105
|
|
|
97
106
|
```text
|
|
98
107
|
lambda * queryRelevance - (1 - lambda) * maximumSimilarityToSelected
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@daogee/mdgraph",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "Local-first Markdown document graph for AI coding workflows.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -79,9 +79,9 @@
|
|
|
79
79
|
"dependencies": {
|
|
80
80
|
"chokidar": "^4.0.3",
|
|
81
81
|
"commander": "^12.1.0",
|
|
82
|
-
"fast-glob": "^3.3.3",
|
|
83
82
|
"remark-gfm": "^4.0.1",
|
|
84
83
|
"remark-parse": "^11.0.0",
|
|
84
|
+
"tinyglobby": "^0.2.15",
|
|
85
85
|
"unified": "^11.0.5",
|
|
86
86
|
"yaml": "^2.9.0"
|
|
87
87
|
},
|