@daogee/mdgraph 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README-ZH.md +66 -4
- package/README.md +84 -22
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +3 -1
- package/agent-pack/prompts/wiki-authoring.md +12 -0
- package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
- package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
- package/dist/analysis/status-freshness.d.ts +8 -1
- package/dist/analysis/status-freshness.js +19 -6
- package/dist/bin/mdgraph.js +260 -25
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +55 -4
- package/dist/db/repositories.js +458 -11
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +25 -5
- package/dist/evaluation/retrieval-eval.js +79 -7
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -4
- package/dist/indexer.js +80 -4
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +21 -11
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +116 -18
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +32 -2
- package/dist/query/context-builder.js +191 -12
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +85 -16
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +136 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +151 -17
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/dist/wiki/wiki-dependencies.d.ts +20 -0
- package/dist/wiki/wiki-dependencies.js +45 -0
- package/dist/wiki/wiki-domains.d.ts +13 -0
- package/dist/wiki/wiki-domains.js +55 -0
- package/dist/wiki/wiki-evidence.d.ts +27 -0
- package/dist/wiki/wiki-evidence.js +112 -0
- package/dist/wiki/wiki-plan.d.ts +121 -0
- package/dist/wiki/wiki-plan.js +616 -0
- package/dist/wiki/wiki-status.d.ts +67 -0
- package/dist/wiki/wiki-status.js +451 -0
- package/docs/EN/Agent_Integration.md +15 -5
- package/docs/EN/Architecture.md +52 -16
- package/docs/EN/Evaluation_Questions.md +35 -5
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +111 -0
- package/docs/EN/Output_Contracts.md +83 -10
- package/docs/EN/Public_Contracts.md +25 -16
- package/docs/EN/Public_Contracts_1.0.md +32 -18
- package/docs/EN/README.md +24 -0
- package/docs/EN/Release_Checklist.md +27 -13
- package/docs/EN/Retrieval_and_Context.md +118 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +15 -5
- package/docs/ZH/Architecture.md +52 -21
- package/docs/ZH/Evaluation_Questions.md +36 -6
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +111 -0
- package/docs/ZH/Output_Contracts.md +83 -10
- package/docs/ZH/Public_Contracts.md +24 -15
- package/docs/ZH/Public_Contracts_1.0.md +31 -17
- package/docs/ZH/README.md +24 -0
- package/docs/ZH/Release_Checklist.md +27 -13
- package/docs/ZH/Retrieval_and_Context.md +118 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +50 -19
|
@@ -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
|
+
}
|
|
@@ -8,7 +8,7 @@ source_refs:
|
|
|
8
8
|
|
|
9
9
|
# MDGraph Agent Integration
|
|
10
10
|
|
|
11
|
-
This guide is the shared
|
|
11
|
+
This guide is the shared integration contract for coding agents. Host-specific setup should stay thin: start the same MCP server, expose the same five tools, and teach the agent when to query MDGraph before reading Markdown files directly.
|
|
12
12
|
|
|
13
13
|
For active documentation editing sessions, use `serve --mcp`; the same MCP process keeps the local graph fresh by default.
|
|
14
14
|
|
|
@@ -113,13 +113,23 @@ Relationship question:
|
|
|
113
113
|
2. `mdgraph_trace` between the resolved nodes
|
|
114
114
|
3. `mdgraph_context` for surrounding sections if the trace path needs explanation
|
|
115
115
|
|
|
116
|
-
Documentation health check:
|
|
116
|
+
Documentation health check:
|
|
117
117
|
|
|
118
118
|
1. `mdgraph_status`
|
|
119
119
|
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
|
-
|
|
120
|
+
3. Raw file edits only after the doctor output names affected documents
|
|
121
|
+
|
|
122
|
+
Project Wiki authoring:
|
|
123
|
+
|
|
124
|
+
1. Run CLI `mdgraph wiki plan --out <plan-file>` once for the current graph.
|
|
125
|
+
2. Run `mdgraph wiki status <wiki-dir> --plan <plan-file> --json` and select only missing or needs-update pages.
|
|
126
|
+
3. Fetch one `mdgraph wiki brief <page-id> --plan <plan-file> --json`, then read its document and source-ref evidence before writing.
|
|
127
|
+
4. Preserve user prose and maintenance front matter, then run `mdgraph wiki verify`.
|
|
128
|
+
5. Review orphaned pages manually; the workflow never deletes them.
|
|
129
|
+
|
|
130
|
+
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.
|
|
131
|
+
|
|
132
|
+
## Current Limits
|
|
123
133
|
|
|
124
134
|
- MDGraph indexes Markdown documents, not source ASTs or arbitrary files.
|
|
125
135
|
- The MCP surface intentionally stays at five tools: search, context, node, trace, and status.
|