@daogee/mdgraph 1.1.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README-ZH.md +13 -3
  3. package/README.md +13 -3
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +5 -1
  6. package/agent-pack/prompts/wiki-authoring.md +12 -0
  7. package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
  8. package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
  9. package/dist/analysis/status-freshness.d.ts +8 -1
  10. package/dist/analysis/status-freshness.js +19 -6
  11. package/dist/bin/mdgraph.js +125 -6
  12. package/dist/db/connection.js +17 -1
  13. package/dist/db/repositories.d.ts +30 -5
  14. package/dist/db/repositories.js +171 -8
  15. package/dist/db/sqlite-adapter.js +8 -2
  16. package/dist/evaluation/retrieval-eval.d.ts +11 -0
  17. package/dist/evaluation/retrieval-eval.js +35 -1
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +3 -0
  20. package/dist/indexer.js +64 -6
  21. package/dist/mcp/server.js +5 -4
  22. package/dist/mcp/tools.js +26 -11
  23. package/dist/query/context-builder.d.ts +2 -0
  24. package/dist/query/context-builder.js +154 -24
  25. package/dist/query/knowledge-card.d.ts +90 -0
  26. package/dist/query/knowledge-card.js +676 -0
  27. package/dist/query/search.js +30 -8
  28. package/dist/scanner/file-scanner.js +7 -7
  29. package/dist/semantic/ollama-provider.js +6 -1
  30. package/dist/utils/fts.d.ts +1 -0
  31. package/dist/utils/fts.js +68 -13
  32. package/dist/utils/path-safety.d.ts +3 -0
  33. package/dist/utils/path-safety.js +27 -0
  34. package/dist/watcher/file-watcher.js +121 -17
  35. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  36. package/dist/wiki/wiki-dependencies.js +45 -0
  37. package/dist/wiki/wiki-domains.d.ts +13 -0
  38. package/dist/wiki/wiki-domains.js +55 -0
  39. package/dist/wiki/wiki-evidence.d.ts +27 -0
  40. package/dist/wiki/wiki-evidence.js +112 -0
  41. package/dist/wiki/wiki-plan.d.ts +121 -0
  42. package/dist/wiki/wiki-plan.js +616 -0
  43. package/dist/wiki/wiki-status.d.ts +67 -0
  44. package/dist/wiki/wiki-status.js +451 -0
  45. package/docs/EN/Agent_Integration.md +16 -4
  46. package/docs/EN/Architecture.md +14 -2
  47. package/docs/EN/Evaluation_Questions.md +21 -1
  48. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  49. package/docs/EN/Operations.md +22 -0
  50. package/docs/EN/Output_Contracts.md +44 -3
  51. package/docs/EN/Public_Contracts.md +4 -2
  52. package/docs/EN/Public_Contracts_1.0.md +4 -0
  53. package/docs/EN/README.md +1 -0
  54. package/docs/EN/Release_Checklist.md +3 -2
  55. package/docs/EN/Retrieval_and_Context.md +20 -5
  56. package/docs/ZH/Agent_Integration.md +16 -4
  57. package/docs/ZH/Architecture.md +14 -4
  58. package/docs/ZH/Evaluation_Questions.md +21 -1
  59. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  60. package/docs/ZH/Operations.md +22 -0
  61. package/docs/ZH/Output_Contracts.md +44 -3
  62. package/docs/ZH/Public_Contracts.md +4 -2
  63. package/docs/ZH/Public_Contracts_1.0.md +4 -0
  64. package/docs/ZH/README.md +1 -0
  65. package/docs/ZH/Release_Checklist.md +3 -2
  66. package/docs/ZH/Retrieval_and_Context.md +20 -5
  67. package/package.json +8 -3
@@ -0,0 +1,67 @@
1
+ import { GraphRepository } from "../db/repositories.js";
2
+ import { type StatusFreshness } from "../analysis/status-freshness.js";
3
+ import { type WikiPlan } from "./wiki-plan.js";
4
+ import { type WikiDependencyChange, type WikiDependencyAssessment } from "./wiki-dependencies.js";
5
+ export declare const WIKI_STATUS_FORMAT: "mdgraph-wiki-status";
6
+ export declare const WIKI_STATUS_FORMAT_VERSION: 1;
7
+ export declare const WIKI_VERIFICATION_FORMAT: "mdgraph-wiki-verification";
8
+ export declare const WIKI_VERIFICATION_FORMAT_VERSION: 1;
9
+ export type WikiPageState = "current" | "needs_update" | "missing" | "orphaned";
10
+ export interface WikiPageStatus {
11
+ id: string;
12
+ path: string;
13
+ state: WikiPageState;
14
+ changes?: WikiDependencyChange[];
15
+ selectionChanges?: Array<{
16
+ field: "source_docs" | "source_refs";
17
+ added: string[];
18
+ missing: string[];
19
+ }>;
20
+ evidenceState?: WikiDependencyAssessment["state"];
21
+ reason?: string;
22
+ recovery?: string;
23
+ }
24
+ export interface WikiPlanStatus {
25
+ state: "current" | "stale";
26
+ graphHash: string;
27
+ sourceHash: string;
28
+ currentGraphHash: string;
29
+ currentSourceHash: string;
30
+ reason?: string;
31
+ recovery?: string;
32
+ /** Strict document content evidence used for Wiki maintenance decisions. */
33
+ indexFreshness?: StatusFreshness;
34
+ }
35
+ export interface WikiStatus {
36
+ format: typeof WIKI_STATUS_FORMAT;
37
+ formatVersion: typeof WIKI_STATUS_FORMAT_VERSION;
38
+ wikiDir: string;
39
+ plan: WikiPlanStatus;
40
+ pages: WikiPageStatus[];
41
+ summary: Record<WikiPageState, number>;
42
+ }
43
+ export interface WikiVerificationIssue {
44
+ code: string;
45
+ message: string;
46
+ pageId?: string;
47
+ path?: string;
48
+ evidence?: string;
49
+ recovery: string;
50
+ }
51
+ export interface WikiVerification {
52
+ format: typeof WIKI_VERIFICATION_FORMAT;
53
+ formatVersion: typeof WIKI_VERIFICATION_FORMAT_VERSION;
54
+ valid: boolean;
55
+ scope: "maintenance-and-evidence";
56
+ contentReview: "not-evaluated";
57
+ errors: WikiVerificationIssue[];
58
+ warnings: WikiVerificationIssue[];
59
+ status: WikiStatus;
60
+ }
61
+ export interface WikiStatusOptions {
62
+ planPath?: string;
63
+ }
64
+ export declare function buildWikiStatus(projectRoot: string, repository: GraphRepository, wikiDir: string, plan: WikiPlan, options?: WikiStatusOptions): WikiStatus;
65
+ export declare function verifyWiki(projectRoot: string, repository: GraphRepository, wikiDir: string, plan: WikiPlan, options?: WikiStatusOptions): WikiVerification;
66
+ export declare function formatWikiStatus(status: WikiStatus): string;
67
+ export declare function formatWikiVerification(verification: WikiVerification): string;
@@ -0,0 +1,451 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { buildGraphJsonExport } from "../export/graphjson.js";
4
+ import { parseFrontmatterBlock } from "../parser/frontmatter.js";
5
+ import { parseMarkdownDocument } from "../parser/markdown-parser.js";
6
+ import { isPathInsideOrEqual, resolveInsideRoot } from "../utils/path-safety.js";
7
+ import { normalizePath, slugifyHeading, uniqueStrings } from "../utils/text.js";
8
+ import { WIKI_PLAN_FORMAT_VERSION, WikiPlanError, safeProjectRelativePath, safeWikiPagePath, wikiSourceHash } from "./wiki-plan.js";
9
+ import { sourceRefFingerprint, wikiContentFreshness } from "./wiki-evidence.js";
10
+ import { assessWikiDependencies } from "./wiki-dependencies.js";
11
+ export const WIKI_STATUS_FORMAT = "mdgraph-wiki-status";
12
+ export const WIKI_STATUS_FORMAT_VERSION = 1;
13
+ export const WIKI_VERIFICATION_FORMAT = "mdgraph-wiki-verification";
14
+ export const WIKI_VERIFICATION_FORMAT_VERSION = 1;
15
+ const MAX_WIKI_MARKDOWN_FILES = 10_000;
16
+ const MAX_WIKI_DIRECTORY_DEPTH = 32;
17
+ const MAX_WIKI_PAGE_BYTES = 2 * 1024 * 1024;
18
+ export function buildWikiStatus(projectRoot, repository, wikiDir, plan, options = {}) {
19
+ const resolvedWikiDir = path.resolve(wikiDir);
20
+ assertWikiDirectoryReadable(resolvedWikiDir);
21
+ const currentGraph = buildGraphJsonExport(projectRoot, repository);
22
+ const planCommand = wikiPlanRecoveryCommand(options.planPath);
23
+ const indexFreshness = wikiContentFreshness(projectRoot, repository, { wikiDir: resolvedWikiDir });
24
+ const currentSourceHash = plan.formatVersion === 2 ? wikiSourceHash(repository, plan.wikiDir) : currentGraph.sourceHash;
25
+ const planCurrent = (plan.formatVersion === 2 || plan.graphHash === currentGraph.graphHash)
26
+ && plan.sourceHash === currentSourceHash
27
+ && indexFreshness.state === "fresh";
28
+ const planStatus = {
29
+ state: planCurrent ? "current" : "stale",
30
+ graphHash: plan.graphHash,
31
+ sourceHash: plan.sourceHash,
32
+ currentGraphHash: currentGraph.graphHash,
33
+ currentSourceHash,
34
+ reason: planCurrent ? undefined : indexFreshness.state !== "fresh"
35
+ ? `Indexed Markdown evidence is ${indexFreshness.state}; ${indexFreshness.recommendation}.`
36
+ : "The graph or indexed document source snapshot has changed since this plan was created.",
37
+ recovery: planCurrent ? undefined : indexFreshness.state !== "fresh"
38
+ ? "Run `mdgraph index`, then regenerate the Wiki plan before relying on this status."
39
+ : planCommand,
40
+ indexFreshness
41
+ };
42
+ const documentsById = new Map(repository.allDocuments().map((document) => [document.id, document]));
43
+ const pageStatuses = plan.pages.map((page) => {
44
+ const evidence = assessWikiDependencies(projectRoot, repository, page, indexFreshness, plan.wikiDir ?? normalizePath(path.relative(projectRoot, resolvedWikiDir)));
45
+ return {
46
+ ...statusForPlannedPage(projectRoot, repository, resolvedWikiDir, page, documentsById, planCommand, evidence),
47
+ changes: evidence.changes,
48
+ selectionChanges: wikiSelectionChanges(resolvedWikiDir, page, documentsById),
49
+ evidenceState: evidence.state
50
+ };
51
+ });
52
+ const plannedPaths = new Set(plan.pages.map((page) => page.path));
53
+ const orphaned = scanWikiMarkdownFiles(resolvedWikiDir)
54
+ .filter((pagePath) => !plannedPaths.has(pagePath))
55
+ .flatMap((pagePath) => {
56
+ const pageFile = readWikiPageFile(resolvedWikiDir, pagePath);
57
+ const wikiId = optionalFrontmatterString(pageFile.frontmatter.wiki_id);
58
+ if (!wikiId) {
59
+ return [];
60
+ }
61
+ return [{
62
+ id: wikiId,
63
+ path: pagePath,
64
+ state: "orphaned",
65
+ reason: plan.pages.some((page) => page.id === wikiId)
66
+ ? `The page uses planned wiki_id ${wikiId}, but its path is not ${plan.pages.find((page) => page.id === wikiId)?.path}.`
67
+ : `The page declares wiki_id ${wikiId}, which is not present in the plan.`,
68
+ recovery: `Review ${pagePath}; move it to the planned path, remove its wiki_id, or regenerate the plan before deleting user content.`
69
+ }];
70
+ });
71
+ const pages = [...pageStatuses, ...orphaned.sort(comparePageStatus)];
72
+ const summary = {
73
+ current: 0,
74
+ needs_update: 0,
75
+ missing: 0,
76
+ orphaned: 0
77
+ };
78
+ for (const page of pages) {
79
+ summary[page.state] += 1;
80
+ }
81
+ return {
82
+ format: WIKI_STATUS_FORMAT,
83
+ formatVersion: WIKI_STATUS_FORMAT_VERSION,
84
+ wikiDir: normalizePath(wikiDir),
85
+ plan: planStatus,
86
+ pages,
87
+ summary
88
+ };
89
+ }
90
+ export function verifyWiki(projectRoot, repository, wikiDir, plan, options = {}) {
91
+ const status = buildWikiStatus(projectRoot, repository, wikiDir, plan, options);
92
+ const resolvedWikiDir = path.resolve(wikiDir);
93
+ const errors = [];
94
+ const warnings = [];
95
+ if (plan.formatVersion !== 1 && plan.formatVersion !== WIKI_PLAN_FORMAT_VERSION) {
96
+ errors.push(issue("wiki.plan_version", `Unsupported Wiki plan formatVersion: ${plan.formatVersion}.`, "Regenerate the plan with the current MDGraph CLI."));
97
+ }
98
+ if (status.plan.state === "stale") {
99
+ warnings.push(issue("wiki.plan_stale", status.plan.reason ?? "The Wiki plan is stale.", status.plan.recovery ?? wikiPlanRecoveryCommand(options.planPath)));
100
+ }
101
+ const strictFreshness = status.plan.indexFreshness;
102
+ if (strictFreshness && strictFreshness.state !== "fresh") {
103
+ errors.push(issue("wiki.index_stale", `Indexed Markdown evidence is ${strictFreshness.state}; ${strictFreshness.recommendation}.`, "Run `mdgraph index`, regenerate the Wiki plan, then update the affected Wiki pages."));
104
+ }
105
+ for (const pageStatus of status.pages) {
106
+ if (pageStatus.state === "current") {
107
+ continue;
108
+ }
109
+ errors.push(issue(`wiki.page_${pageStatus.state}`, pageStatus.reason ?? `Wiki page ${pageStatus.id} is ${pageStatus.state}.`, pageStatus.recovery ?? "Run `mdgraph wiki status` and repair this page.", pageStatus.id, pageStatus.path));
110
+ }
111
+ const indexedPaths = new Set(repository.allDocuments().map((document) => document.path));
112
+ for (const page of plan.pages) {
113
+ const absolutePath = path.resolve(resolvedWikiDir, page.path);
114
+ if (!fs.existsSync(absolutePath) || !fs.lstatSync(absolutePath).isFile()) {
115
+ continue;
116
+ }
117
+ const pageFile = readWikiPageFile(resolvedWikiDir, page.path);
118
+ if (pageFile.frontmatterError) {
119
+ errors.push(issue("wiki.frontmatter_invalid", pageFile.frontmatterError, `Repair YAML front matter in ${page.path}.`, page.id, page.path));
120
+ continue;
121
+ }
122
+ const sourceDocs = frontmatterStringArray(pageFile.frontmatter.source_docs);
123
+ const sourceRefs = frontmatterStringArray(pageFile.frontmatter.source_refs);
124
+ verifyFrontmatterPathArray(page, "source_docs", pageFile.frontmatter.source_docs, errors);
125
+ verifyFrontmatterPathArray(page, "source_refs", pageFile.frontmatter.source_refs, errors);
126
+ verifySourceDocuments(projectRoot, page, sourceDocs, indexedPaths, errors);
127
+ verifySourceRefs(projectRoot, page, sourceRefs, errors);
128
+ verifyRelativeLinks(resolvedWikiDir, page, errors);
129
+ }
130
+ return {
131
+ format: WIKI_VERIFICATION_FORMAT,
132
+ formatVersion: WIKI_VERIFICATION_FORMAT_VERSION,
133
+ valid: errors.length === 0,
134
+ scope: "maintenance-and-evidence",
135
+ contentReview: "not-evaluated",
136
+ errors,
137
+ warnings,
138
+ status
139
+ };
140
+ }
141
+ export function formatWikiStatus(status) {
142
+ const lines = [
143
+ `Wiki status: ${status.summary.current} current, ${status.summary.needs_update} needs update, ${status.summary.missing} missing, ${status.summary.orphaned} orphaned`,
144
+ "Current means recorded dependencies and maintenance fields match; prose correctness is not evaluated.",
145
+ `Plan: ${status.plan.state}`,
146
+ `Evidence freshness: ${status.plan.indexFreshness?.state ?? "unknown"}`
147
+ ];
148
+ for (const page of status.pages) {
149
+ lines.push(`- ${page.id} [${page.state}] ${page.path}`);
150
+ for (const change of page.changes ?? [])
151
+ lines.push(` Changed ${change.kind}: ${change.path} (${change.reason})`);
152
+ for (const selection of page.selectionChanges ?? [])
153
+ lines.push(` Review ${selection.field}: added ${selection.added.join(", ") || "none"}; missing ${selection.missing.join(", ") || "none"}`);
154
+ if (page.reason) {
155
+ lines.push(` Reason: ${page.reason}`);
156
+ }
157
+ if (page.recovery) {
158
+ lines.push(` Recovery: ${page.recovery}`);
159
+ }
160
+ }
161
+ if (status.plan.recovery) {
162
+ lines.push(`Plan recovery: ${status.plan.recovery}`);
163
+ }
164
+ if (status.plan.indexFreshness?.state !== "fresh") {
165
+ lines.push(`Evidence recovery: ${status.plan.indexFreshness?.recommendation ?? "Run \`mdgraph index\`, then regenerate the Wiki plan."}`);
166
+ }
167
+ return lines.join("\n");
168
+ }
169
+ export function formatWikiVerification(verification) {
170
+ const lines = [
171
+ "Scope: maintenance fields, links, and evidence. Prose correctness is not evaluated.",
172
+ `Wiki verification: ${verification.valid ? "valid" : "invalid"}`,
173
+ `Errors: ${verification.errors.length}; warnings: ${verification.warnings.length}`
174
+ ];
175
+ for (const error of verification.errors) {
176
+ lines.push(`- ERROR ${error.code}: ${error.message}`);
177
+ lines.push(` Recovery: ${error.recovery}`);
178
+ }
179
+ for (const warning of verification.warnings) {
180
+ lines.push(`- WARNING ${warning.code}: ${warning.message}`);
181
+ lines.push(` Recovery: ${warning.recovery}`);
182
+ }
183
+ return lines.join("\n");
184
+ }
185
+ function wikiSelectionChanges(wikiDir, page, documents) {
186
+ const absolutePath = path.resolve(wikiDir, page.path);
187
+ if (!fs.existsSync(absolutePath) || !fs.lstatSync(absolutePath).isFile())
188
+ return [];
189
+ const file = readWikiPageFile(wikiDir, page.path);
190
+ const expectedDocs = page.documentIds.flatMap((id) => documents.get(id) ? [documents.get(id).path] : []);
191
+ return ["source_docs", "source_refs"].flatMap((field) => {
192
+ if (!isFrontmatterPathArray(file.frontmatter[field]))
193
+ return [];
194
+ const actual = frontmatterStringArray(file.frontmatter[field]);
195
+ const expected = field === "source_docs" ? expectedDocs : page.sourceRefs;
196
+ const added = actual.filter((value) => !expected.includes(value));
197
+ const missing = expected.filter((value) => !actual.includes(value));
198
+ return added.length || missing.length ? [{ field, added, missing }] : [];
199
+ });
200
+ }
201
+ function statusForPlannedPage(projectRoot, repository, wikiDir, page, documentsById, planCommand, evidence) {
202
+ const absolutePath = path.resolve(wikiDir, page.path);
203
+ if (!isPathInsideOrEqual(wikiDir, absolutePath)) {
204
+ return pageProblem(page, "needs_update", "The planned page path escapes the Wiki directory.", planCommand);
205
+ }
206
+ if (!fs.existsSync(absolutePath)) {
207
+ return pageProblem(page, "missing", "The plan requires this page, but the file does not exist.", `Create ${page.path} from mdgraph wiki brief ${page.id} and preserve its maintenance front matter.`);
208
+ }
209
+ const stat = fs.lstatSync(absolutePath);
210
+ if (!stat.isFile() || stat.isSymbolicLink()) {
211
+ return pageProblem(page, "needs_update", "The planned page must be a regular Markdown file, not a directory or symbolic link.", `Replace ${page.path} with a regular Markdown file after preserving any user content.`);
212
+ }
213
+ const pageFile = readWikiPageFile(wikiDir, page.path);
214
+ if (pageFile.frontmatterError) {
215
+ return pageProblem(page, "needs_update", pageFile.frontmatterError, `Repair YAML front matter in ${page.path}.`);
216
+ }
217
+ const wikiId = optionalFrontmatterString(pageFile.frontmatter.wiki_id);
218
+ if (wikiId !== page.id) {
219
+ return pageProblem(page, "needs_update", `Expected wiki_id ${page.id}, found ${wikiId ?? "none"}.`, `Set wiki_id to ${page.id} in ${page.path}.`);
220
+ }
221
+ if (evidence.state !== "fresh") {
222
+ const change = evidence.changes[0];
223
+ return pageProblem(page, "needs_update", change
224
+ ? `${change.kind} dependency ${change.path}: ${change.reason}.`
225
+ : "Cannot establish whether the page dependencies are current.", evidence.recovery ?? planCommand);
226
+ }
227
+ const evidenceHash = optionalFrontmatterString(pageFile.frontmatter.evidence_hash);
228
+ if (evidenceHash !== page.evidenceHash) {
229
+ return pageProblem(page, "needs_update", `Expected evidence_hash ${page.evidenceHash}, found ${evidenceHash ?? "none"}.`, `Use mdgraph wiki brief ${page.id}, update the page, then set evidence_hash to ${page.evidenceHash}.`);
230
+ }
231
+ const expectedSourceDocs = page.documentIds.flatMap((documentId) => {
232
+ const document = documentsById.get(documentId);
233
+ return document ? [document.path] : [];
234
+ });
235
+ const sourceDocs = frontmatterStringArray(pageFile.frontmatter.source_docs);
236
+ if (!isFrontmatterPathArray(pageFile.frontmatter.source_docs)) {
237
+ return pageProblem(page, "needs_update", "source_docs must be a non-empty-string array; scalar, empty, and mixed values are not valid evidence.", `Replace source_docs in ${page.path} with the project-relative paths from the current page brief.`);
238
+ }
239
+ if (!sameStrings(sourceDocs, expectedSourceDocs)) {
240
+ return pageProblem(page, "needs_update", "source_docs does not match the plan evidence documents.", `Review source_docs in ${page.path}; add intended sources to the plan documentIds, refresh the plan and brief, then synchronize fields. Preserve user-selected sources until reviewed.`);
241
+ }
242
+ const sourceRefs = frontmatterStringArray(pageFile.frontmatter.source_refs);
243
+ if (!isFrontmatterPathArray(pageFile.frontmatter.source_refs)) {
244
+ return pageProblem(page, "needs_update", "source_refs must be a non-empty-string array; scalar, empty, and mixed values are not valid evidence.", `Replace source_refs in ${page.path} with the project-relative paths from the current page brief.`);
245
+ }
246
+ if (!sameStrings(sourceRefs, page.sourceRefs)) {
247
+ return pageProblem(page, "needs_update", "source_refs does not match the plan evidence source refs.", `Review source_refs in ${page.path}; add intended sources to the plan sourceRefs, refresh the plan and brief, then synchronize fields. Preserve user-selected sources until reviewed.`);
248
+ }
249
+ return { id: page.id, path: page.path, state: "current" };
250
+ }
251
+ function readWikiPageFile(wikiDir, pagePath) {
252
+ const safePath = safeWikiPagePath(pagePath);
253
+ if (!safePath) {
254
+ throw new WikiPlanError("wiki.page_path", `Unsafe Wiki page path: ${pagePath}`, "Regenerate the Wiki plan.");
255
+ }
256
+ const absolutePath = path.resolve(wikiDir, safePath);
257
+ if (!isPathInsideOrEqual(wikiDir, absolutePath)) {
258
+ throw new WikiPlanError("wiki.page_path", `Wiki page path escapes the Wiki directory: ${pagePath}`, "Regenerate the Wiki plan.");
259
+ }
260
+ const size = fs.statSync(absolutePath).size;
261
+ if (size > MAX_WIKI_PAGE_BYTES) {
262
+ return {
263
+ path: safePath,
264
+ absolutePath,
265
+ raw: "",
266
+ frontmatter: {},
267
+ frontmatterError: `Wiki page exceeds ${MAX_WIKI_PAGE_BYTES} bytes: ${safePath}.`
268
+ };
269
+ }
270
+ const raw = fs.readFileSync(absolutePath, "utf8");
271
+ const parsed = parseFrontmatterBlock(raw);
272
+ const fatalDiagnostic = parsed.diagnostics.find((diagnostic) => diagnostic.code !== "front_matter.invalid_field");
273
+ return {
274
+ path: safePath,
275
+ absolutePath,
276
+ raw,
277
+ frontmatter: parsed.data,
278
+ frontmatterError: fatalDiagnostic ? `${fatalDiagnostic.message} (line ${fatalDiagnostic.line})` : undefined
279
+ };
280
+ }
281
+ function verifySourceDocuments(projectRoot, page, sourceDocs, indexedPaths, errors) {
282
+ for (const sourceDoc of sourceDocs) {
283
+ const safe = safeProjectRelativePath(sourceDoc);
284
+ if (!safe || !resolveInsideRoot(projectRoot, safe)) {
285
+ errors.push(issue("wiki.source_doc_unsafe", `Unsafe source_docs path: ${sourceDoc}.`, `Use an indexed project-relative Markdown path in ${page.path}.`, page.id, page.path, sourceDoc));
286
+ }
287
+ else if (!indexedPaths.has(safe)) {
288
+ errors.push(issue("wiki.source_doc_unindexed", `source_docs path is not a currently indexed document: ${safe}.`, "Reindex the project, correct source_docs, or regenerate the plan.", page.id, page.path, safe));
289
+ }
290
+ }
291
+ }
292
+ function verifySourceRefs(projectRoot, page, sourceRefs, errors) {
293
+ for (const sourceRef of sourceRefs) {
294
+ const safe = safeProjectRelativePath(sourceRef);
295
+ if (!safe) {
296
+ errors.push(issue("wiki.source_ref_unsafe", `Unsafe source_refs path: ${sourceRef}.`, `Use a project-relative path in ${page.path}.`, page.id, page.path, sourceRef));
297
+ continue;
298
+ }
299
+ const fingerprint = sourceRefFingerprint(projectRoot, safe);
300
+ if (!/^[a-f0-9]{64}$/.test(fingerprint)) {
301
+ errors.push(issue("wiki.source_ref_missing", `source_refs path is not a safe existing file: ${safe} (${fingerprint}).`, "Restore the source path, correct source_refs, or regenerate the plan.", page.id, page.path, safe));
302
+ }
303
+ }
304
+ }
305
+ function verifyRelativeLinks(wikiDir, page, errors) {
306
+ let parsed;
307
+ try {
308
+ parsed = parseMarkdownDocument(wikiDir, path.resolve(wikiDir, page.path));
309
+ }
310
+ catch (error) {
311
+ errors.push(issue("wiki.page_parse", `Cannot parse ${page.path}: ${error instanceof Error ? error.message : String(error)}`, `Repair Markdown in ${page.path}.`, page.id, page.path));
312
+ return;
313
+ }
314
+ for (const link of parsed.markdownLinks) {
315
+ const result = resolveWikiLink(wikiDir, page.path, link.url);
316
+ if (result.state === "external") {
317
+ continue;
318
+ }
319
+ if (result.state === "invalid") {
320
+ errors.push(issue("wiki.link_unresolved", `Unresolved relative link in ${page.path}:${link.line}: ${link.url}.`, `Correct the link target or add the missing Wiki page.`, page.id, page.path, link.url));
321
+ continue;
322
+ }
323
+ if (result.anchor && result.target.toLowerCase().endsWith(".md")) {
324
+ try {
325
+ const target = parseMarkdownDocument(wikiDir, path.resolve(wikiDir, result.target));
326
+ const anchors = new Set(target.sections.map((section) => section.anchor));
327
+ if (!anchors.has(slugifyHeading(result.anchor))) {
328
+ errors.push(issue("wiki.link_anchor", `Missing anchor #${result.anchor} in ${result.target}.`, `Correct the anchor referenced from ${page.path}:${link.line}.`, page.id, page.path, link.url));
329
+ }
330
+ }
331
+ catch (error) {
332
+ errors.push(issue("wiki.link_target_parse", `Cannot parse link target ${result.target}: ${error instanceof Error ? error.message : String(error)}`, `Repair ${result.target}.`, page.id, page.path, link.url));
333
+ }
334
+ }
335
+ }
336
+ }
337
+ function resolveWikiLink(wikiDir, fromPath, rawUrl) {
338
+ if (/^[a-z][a-z0-9+.-]*:/i.test(rawUrl) || rawUrl.startsWith("//")) {
339
+ return { state: "external" };
340
+ }
341
+ let decoded;
342
+ try {
343
+ decoded = decodeURI(rawUrl);
344
+ }
345
+ catch {
346
+ return { state: "invalid" };
347
+ }
348
+ const [targetWithQuery, rawAnchor] = decoded.split("#", 2);
349
+ const rawTarget = targetWithQuery.split("?", 1)[0];
350
+ if (rawTarget.startsWith("/")) {
351
+ return { state: "invalid" };
352
+ }
353
+ const relativeTarget = rawTarget || path.posix.basename(fromPath);
354
+ const combined = normalizePath(path.posix.join(path.posix.dirname(fromPath), relativeTarget));
355
+ const safe = safeProjectRelativePath(combined);
356
+ if (!safe) {
357
+ return { state: "invalid" };
358
+ }
359
+ const candidates = linkTargetCandidates(wikiDir, safe);
360
+ const target = candidates.find((candidate) => {
361
+ const absolute = path.resolve(wikiDir, candidate);
362
+ return isPathInsideOrEqual(wikiDir, absolute) && fs.existsSync(absolute) && fs.lstatSync(absolute).isFile();
363
+ });
364
+ return target ? { state: "resolved", target, anchor: rawAnchor || undefined } : { state: "invalid" };
365
+ }
366
+ function linkTargetCandidates(wikiDir, target) {
367
+ const absolute = path.resolve(wikiDir, target);
368
+ const candidates = [target];
369
+ if (!path.posix.extname(target)) {
370
+ candidates.push(`${target}.md`, path.posix.join(target, "index.md"));
371
+ }
372
+ if (fs.existsSync(absolute) && fs.lstatSync(absolute).isDirectory()) {
373
+ candidates.push(path.posix.join(target, "index.md"));
374
+ }
375
+ return uniqueStrings(candidates);
376
+ }
377
+ function scanWikiMarkdownFiles(wikiDir) {
378
+ if (!fs.existsSync(wikiDir)) {
379
+ return [];
380
+ }
381
+ const files = [];
382
+ const queue = [{ absolutePath: wikiDir, relativePath: "", depth: 0 }];
383
+ while (queue.length) {
384
+ const current = queue.shift();
385
+ if (current.depth > MAX_WIKI_DIRECTORY_DEPTH) {
386
+ throw new WikiPlanError("wiki.directory_depth", `Wiki directory exceeds depth ${MAX_WIKI_DIRECTORY_DEPTH}.`, "Narrow the Wiki directory or remove recursive directory cycles.");
387
+ }
388
+ const entries = fs.readdirSync(current.absolutePath, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
389
+ for (const entry of entries) {
390
+ if (entry.isSymbolicLink()) {
391
+ continue;
392
+ }
393
+ const relativePath = normalizePath(path.posix.join(current.relativePath, entry.name));
394
+ const absolutePath = path.join(current.absolutePath, entry.name);
395
+ if (entry.isDirectory()) {
396
+ queue.push({ absolutePath, relativePath, depth: current.depth + 1 });
397
+ }
398
+ else if (entry.isFile() && relativePath.toLowerCase().endsWith(".md")) {
399
+ files.push(relativePath);
400
+ if (files.length > MAX_WIKI_MARKDOWN_FILES) {
401
+ throw new WikiPlanError("wiki.directory_files", `Wiki directory exceeds ${MAX_WIKI_MARKDOWN_FILES} Markdown files.`, "Narrow the Wiki directory or split verification into smaller maintained Wiki roots.");
402
+ }
403
+ }
404
+ }
405
+ }
406
+ return files.sort();
407
+ }
408
+ function assertWikiDirectoryReadable(wikiDir) {
409
+ if (!fs.existsSync(wikiDir)) {
410
+ return;
411
+ }
412
+ if (!fs.lstatSync(wikiDir).isDirectory()) {
413
+ throw new WikiPlanError("wiki.directory", `Wiki target is not a directory: ${wikiDir}`, "Pass the directory that contains the planned Wiki pages.");
414
+ }
415
+ }
416
+ function frontmatterStringArray(value) {
417
+ if (!Array.isArray(value)) {
418
+ return [];
419
+ }
420
+ return value.flatMap((item) => typeof item === "string" && item.trim() ? [normalizePath(item.trim())] : []);
421
+ }
422
+ function isFrontmatterPathArray(value) {
423
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim().length > 0);
424
+ }
425
+ function verifyFrontmatterPathArray(page, field, value, errors) {
426
+ if (isFrontmatterPathArray(value)) {
427
+ return;
428
+ }
429
+ const actual = value === undefined ? "missing" : Array.isArray(value) ? "contains an empty or non-string item" : "is a scalar or non-array value";
430
+ errors.push(issue(`wiki.${field}_invalid`, `${field} in ${page.path} ${actual}; it must be an array of non-empty project-relative paths.`, `Replace ${field} in ${page.path} with the project-relative paths from \`mdgraph wiki brief ${page.id}\`.`, page.id, page.path));
431
+ }
432
+ function optionalFrontmatterString(value) {
433
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
434
+ }
435
+ function sameStrings(left, right) {
436
+ const normalizedLeft = uniqueStrings(left).sort();
437
+ const normalizedRight = uniqueStrings(right).sort();
438
+ return normalizedLeft.length === normalizedRight.length && normalizedLeft.every((value, index) => value === normalizedRight[index]);
439
+ }
440
+ function pageProblem(page, state, reason, recovery) {
441
+ return { id: page.id, path: page.path, state, reason, recovery };
442
+ }
443
+ function issue(code, message, recovery, pageId, issuePath, evidence) {
444
+ return { code, message, pageId, path: issuePath, evidence, recovery };
445
+ }
446
+ function comparePageStatus(left, right) {
447
+ return left.path.localeCompare(right.path) || left.id.localeCompare(right.id);
448
+ }
449
+ function wikiPlanRecoveryCommand(planPath) {
450
+ return `mdgraph wiki plan --out ${planPath ? JSON.stringify(planPath) : "<plan-file>"}`;
451
+ }
@@ -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
 
@@ -113,13 +115,23 @@ Relationship question:
113
115
  2. `mdgraph_trace` between the resolved nodes
114
116
  3. `mdgraph_context` for surrounding sections if the trace path needs explanation
115
117
 
116
- Documentation health check:
118
+ Documentation health check:
117
119
 
118
120
  1. `mdgraph_status`
119
121
  2. CLI `mdgraph doctor --json` when the user asks for docs health or CI gating
120
- 3. Raw file edits only after the doctor output names affected documents
121
-
122
- ## Current Limits
122
+ 3. Raw file edits only after the doctor output names affected documents
123
+
124
+ Project Wiki authoring:
125
+
126
+ 1. Run CLI `mdgraph wiki plan --out <plan-file>` once for the current graph.
127
+ 2. Run `mdgraph wiki status <wiki-dir> --plan <plan-file> --json` and select only missing or needs-update pages.
128
+ 3. Fetch one `mdgraph wiki brief <page-id> --plan <plan-file> --json`, then read its document and source-ref evidence before writing.
129
+ 4. Preserve user prose and maintenance front matter, then run `mdgraph wiki verify`.
130
+ 5. Review orphaned pages manually; the workflow never deletes them.
131
+
132
+ Hosts that support reusable skills can use [`agent-pack/skills/wiki-authoring`](../../agent-pack/skills/wiki-authoring/SKILL.md); other hosts can use the matching prompt template.
133
+
134
+ ## Current Limits
123
135
 
124
136
  - MDGraph indexes Markdown documents, not source ASTs or arbitrary files.
125
137
  - The MCP surface intentionally stays at five tools: search, context, node, trace, and status.
@@ -3,6 +3,8 @@ implements:
3
3
  - src/indexer.ts
4
4
  - src/db/repositories.ts
5
5
  - src/query/context-builder.ts
6
+ - src/wiki/wiki-plan.ts
7
+ - src/wiki/wiki-status.ts
6
8
  source_refs:
7
9
  - src/db/schema.sql
8
10
  - src/types.ts
@@ -27,6 +29,7 @@ MDGraph uses this implemented pipeline: scanner -> parser -> extractor/resolver
27
29
  | Resolution | `src/resolution/link-resolver.ts` | Resolves Markdown and WikiLink targets to indexed documents or sections. |
28
30
  | Storage | `src/db/*` | SQLite connection, schema, record replacement, incremental updates, graph queries, and storage diagnostics. |
29
31
  | Query | `src/query/*` | Search ranking, context packing, graph trace, and the experimental structured-query tokenizer/AST/executor. |
32
+ | Wiki | `src/wiki/*` | Experimental deterministic Wiki planning, evidence briefs, impact status, and read-only verification; prose remains host-agent/user maintained. |
30
33
  | Evaluation | `src/evaluation/*` | Retrieval evaluation cases, expected records, and lightweight metrics for search/context/trace quality. |
31
34
  | Benchmark | `src/benchmark/*` | Structured with/without-MDGraph agent run record parsing and paired delta aggregation. |
32
35
  | Bundle | `src/bundle/*` | Private directory graph bundle creation and verification using schema/source/config/document hashes. |
@@ -121,13 +124,12 @@ The diff report includes Markdown document additions, modifications, deletions,
121
124
  - FTS5 chunk hits, including lightweight CJK n-gram matches for continuous Chinese/Japanese/Korean text.
122
125
  - Exact entity matches.
123
126
  - Optional embedding vector matches.
124
- - Graph neighbors around matching entities.
125
127
 
126
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.
127
129
 
128
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.
129
131
 
130
- `buildContext` then starts from ranked search sections, performs bounded graph expansion through non-containment edges, packages selected sections under a character budget, and includes reasons such as FTS hit, semantic hit, exact entity match, or the graph edge traversal path. The compatibility default orders candidates by document round-robin. Opt-in `mmr` maximizes query relevance minus redundancy, uses stored configured-provider vectors when both candidates have them, falls back to deterministic Unicode-token Jaccard otherwise, and prunes same-document near duplicates while preserving a first candidate from each document.
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.
131
133
 
132
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.
133
135
 
@@ -139,6 +141,12 @@ The experimental structured-query path is separate from natural-language search.
139
141
 
140
142
  `generateBenchmarkReport` consumes structured `AgentRunRecord` JSON only. It pairs one `with_mdgraph` and one `without_mdgraph` record by `questionId`, reports incomplete or duplicate pairs as skipped, and calculates deltas for file reads, searches, tool calls, MDGraph calls, character/token budgets, latency, raw-file fallback, and citation correctness. It does not parse transcripts, invoke models, or host agent runs.
141
143
 
144
+ ## Wiki Workflow
145
+
146
+ The experimental Wiki path is separate from indexing and natural-language query ranking. `buildWikiPlan` classifies only evidence-backed domains from indexed document metadata and explicit graph relationships, records graph/source hashes, and gives every page a dependency-local `evidenceHash` that also fingerprints safe project source refs. `buildWikiPageBrief` reuses context packing, known files, Knowledge Cards, and a shared character budget.
147
+
148
+ `buildWikiStatus` compares user-maintained page front matter with the plan and current dependency evidence, reporting `current`, `needs_update`, `missing`, or `orphaned` without modifying files. `verifyWiki` adds bounded checks for plan shape, indexed source documents, safe existing source refs, evidence freshness, and resolvable relative Markdown links. It does not evaluate prose quality, delete orphaned pages, invoke a model, or add an MCP tool.
149
+
142
150
  ## MCP Boundary
143
151
 
144
152
  The MCP server intentionally exposes only five tools. Search and context dispatch through the async provider-aware handlers, while node, trace, and status retain their synchronous behavior. Tool output is text-first and JSON-compatible so agents can use it without needing to inspect the SQLite database or read raw files first. A semantic fallback adds a text banner and structured diagnostic without turning a usable lexical/graph result into an MCP error. The server is project-bound: initialize roots and tool `projectPath` values must stay inside the served root.
@@ -156,3 +164,7 @@ The MCP server intentionally exposes only five tools. Search and context dispatc
156
164
  - Interoperability adapters are read-oriented. GraphJSON verify, Mermaid/Markdown/docs-site exports, and source bridge reports do not merge external graphs into the main SQLite index.
157
165
  - `RELATED_TO` is an experimental derived edge emitted only by explicit provider-gated execution; it is never emitted by ordinary deterministic indexing. `SAME_AS` and `CONTRADICTS` remain reserved, and contradiction-like signals continue to be reported by `doctor` rather than inserted as graph edges.
158
166
  - The current implementation favors a compact, deterministic core over broad Markdown/MDX dialect support.
167
+
168
+ ## Knowledge and Wiki evidence ownership
169
+
170
+ Card assembly distinguishes direct edges, inherited document/section context, and related source evidence. Stable provenance travels with references and bounded next-read entries. Wiki evidence hashing and strict content checks are shared in `src/wiki/wiki-evidence.ts`; dependency assessment in `src/wiki/wiki-dependencies.ts` supplies both brief guidance and page status. Plan v2 preserves authored selections and separates new suggestions. Its document source hash excludes Wiki output and volatile indexing metadata. SQLite schema and retrieval ranking are unchanged.
@@ -79,6 +79,26 @@ 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 that frozen default.
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
+
86
+ ## Returned evidence and compatibility metrics
87
+
88
+ The legacy `entityRecall`, `sourceRefRecall`, and `edgeKindCoverage` metrics measure existence in the index (and trace for edge kinds). Their meaning and the legacy `passed` result remain unchanged. They do not establish that a query returned the evidence.
89
+
90
+ Use `retrievedEntityRecall`, `retrievedSourceRefRecall`, and `retrievedEdgeKindCoverage` to measure evidence exposed by search, context, and the requested trace. `observed.retrievedEntities`, `retrievedSourceRefs`, and `retrievedEdgeKinds` identify that evidence. `retrievalEvidencePassed` requires both the legacy checks and complete returned-evidence coverage. `contextIrrelevantRatio` measures the fraction of returned context items outside the expected document set; an empty result has ratio zero but cannot establish recall.
91
+
92
+ ## 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
+
98
+ ## Reproducible performance samples
99
+
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.
101
+
102
+ ## Knowledge/Wiki output baseline
103
+
104
+ Run `npm run baseline:knowledge-wiki` for a deterministic orchard-project fixture. It reports Card JSON characters, references lacking ownership labels, and the rank of a known file in next-read entries. A null rank means the output has no matching next-read entry; it does not mean search failed. The plan/brief output checks project-neutral planning and evidence routing. This is an output-behavior comparison, not a measured independent-agent completion-time or prose-quality improvement.