@daogee/mdgraph 1.1.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README-ZH.md +12 -2
  3. package/README.md +12 -2
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +3 -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 +124 -6
  12. package/dist/db/connection.js +17 -1
  13. package/dist/db/repositories.d.ts +28 -4
  14. package/dist/db/repositories.js +148 -5
  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 +23 -9
  23. package/dist/query/context-builder.d.ts +1 -0
  24. package/dist/query/context-builder.js +30 -1
  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 +8 -3
  28. package/dist/semantic/ollama-provider.js +6 -1
  29. package/dist/utils/path-safety.d.ts +3 -0
  30. package/dist/utils/path-safety.js +27 -0
  31. package/dist/watcher/file-watcher.js +85 -16
  32. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  33. package/dist/wiki/wiki-dependencies.js +45 -0
  34. package/dist/wiki/wiki-domains.d.ts +13 -0
  35. package/dist/wiki/wiki-domains.js +55 -0
  36. package/dist/wiki/wiki-evidence.d.ts +27 -0
  37. package/dist/wiki/wiki-evidence.js +112 -0
  38. package/dist/wiki/wiki-plan.d.ts +121 -0
  39. package/dist/wiki/wiki-plan.js +616 -0
  40. package/dist/wiki/wiki-status.d.ts +67 -0
  41. package/dist/wiki/wiki-status.js +451 -0
  42. package/docs/EN/Agent_Integration.md +14 -4
  43. package/docs/EN/Architecture.md +13 -0
  44. package/docs/EN/Evaluation_Questions.md +14 -0
  45. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  46. package/docs/EN/Operations.md +20 -0
  47. package/docs/EN/Output_Contracts.md +42 -3
  48. package/docs/EN/Public_Contracts.md +3 -1
  49. package/docs/EN/Public_Contracts_1.0.md +4 -0
  50. package/docs/EN/README.md +1 -0
  51. package/docs/EN/Release_Checklist.md +1 -0
  52. package/docs/EN/Retrieval_and_Context.md +6 -0
  53. package/docs/ZH/Agent_Integration.md +14 -4
  54. package/docs/ZH/Architecture.md +13 -2
  55. package/docs/ZH/Evaluation_Questions.md +14 -0
  56. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  57. package/docs/ZH/Operations.md +20 -0
  58. package/docs/ZH/Output_Contracts.md +42 -3
  59. package/docs/ZH/Public_Contracts.md +3 -1
  60. package/docs/ZH/Public_Contracts_1.0.md +4 -0
  61. package/docs/ZH/README.md +1 -0
  62. package/docs/ZH/Release_Checklist.md +1 -0
  63. package/docs/ZH/Retrieval_and_Context.md +6 -0
  64. package/package.json +7 -2
@@ -18,13 +18,14 @@ export async function searchGraphAsync(repository, config, query, limit = config
18
18
  function rankSearchResults(repository, config, query, limit, semanticRows, semanticProvider) {
19
19
  const entityCandidates = extractQueryEntityCandidates(query);
20
20
  const matchedEntities = repository.findEntitiesByNormalizedNames(entityCandidates.map(normalizeEntityName));
21
+ const matchedEntitiesById = new Map(matchedEntities.map((entity) => [entity.id, entity]));
21
22
  const entityDocumentFrequencies = repository.entityDocumentFrequencies(matchedEntities.map((entity) => entity.id));
22
23
  const definitionRows = repository.findEntityDefinitions(matchedEntities.map((entity) => entity.id));
23
24
  const ftsQuery = ftsQueryFor(query);
24
25
  const ftsRows = ftsQuery ? repository.searchChunks(ftsQuery, limit * 2) : [];
25
26
  const results = [];
26
27
  for (const [index, row] of definitionRows.entries()) {
27
- const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
28
+ const matched = matchedEntitiesById.get(row.entityId);
28
29
  results.push({
29
30
  channel: "definition",
30
31
  rank: index + 1,
@@ -34,7 +35,7 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
34
35
  score: adjustScore(200 + row.rank, row.document),
35
36
  reason: "definition matched an explicit query entity",
36
37
  content: row.chunk.content,
37
- matchedEntities: matched
38
+ matchedEntities: matched ? [matched] : []
38
39
  }
39
40
  });
40
41
  }
@@ -162,7 +163,11 @@ async function executeSearchGraphAsync(repository, config, query, limit, options
162
163
  }
163
164
  export function extractQueryEntityCandidates(query) {
164
165
  const candidates = query.match(/`([^`]+)`|\b[A-Z][A-Za-z0-9_.]+\b|\b[A-Z][A-Z0-9_]{2,}\b|\/[A-Za-z0-9_./:{}-]+/g) ?? [];
165
- return candidates.map((candidate) => candidate.replace(/^`|`$/g, "").trim()).filter(Boolean);
166
+ const wholeQuery = query.replace(/^`|`$/g, "").trim();
167
+ return [...new Set([
168
+ wholeQuery,
169
+ ...candidates.map((candidate) => candidate.replace(/^`|`$/g, "").trim())
170
+ ].filter(Boolean))];
166
171
  }
167
172
  function matchedEntitiesForContent(entities, content) {
168
173
  const lowerContent = content.toLowerCase();
@@ -72,7 +72,12 @@ async function fetchWithTimeout(url, init, timeoutMs) {
72
72
  const controller = new AbortController();
73
73
  const timer = setTimeout(() => controller.abort(), timeoutMs);
74
74
  try {
75
- return await fetch(url, { ...init, signal: controller.signal });
75
+ const response = await fetch(url, { ...init, signal: controller.signal });
76
+ const body = await response.arrayBuffer();
77
+ return new Response(body.byteLength ? body : null, { status: response.status, statusText: response.statusText, headers: response.headers });
78
+ }
79
+ catch (error) {
80
+ throw normalizeFetchError(error, timeoutMs);
76
81
  }
77
82
  finally {
78
83
  clearTimeout(timer);
@@ -2,3 +2,6 @@ export declare function isPathInsideOrEqual(root: string, target: string): boole
2
2
  export declare function resolveInsideRoot(root: string, target: string): string | undefined;
3
3
  export declare function assertInsideRoot(root: string, target: string, label?: string): string;
4
4
  export declare function relativePathInsideRoot(root: string, target: string): string | undefined;
5
+ /** Resolve existing ancestors as well as the final target, including storage not created yet. */
6
+ export declare function realPathForAccess(target: string): string;
7
+ export declare function assertProjectFilesInsideRoot(root: string, project: string): void;
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  import { normalizePath } from "./text.js";
3
4
  export function isPathInsideOrEqual(root, target) {
@@ -23,3 +24,29 @@ export function relativePathInsideRoot(root, target) {
23
24
  }
24
25
  return normalizePath(path.relative(path.resolve(root), path.resolve(target)));
25
26
  }
27
+ /** Resolve existing ancestors as well as the final target, including storage not created yet. */
28
+ export function realPathForAccess(target) {
29
+ const absolute = path.resolve(target);
30
+ try {
31
+ return fs.realpathSync(absolute);
32
+ }
33
+ catch (error) {
34
+ if (error.code !== "ENOENT")
35
+ throw error;
36
+ // A dangling link is not an absent path and must not be treated as safe to create.
37
+ if (fs.lstatSync(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
38
+ throw error;
39
+ const parent = path.dirname(absolute);
40
+ if (parent === absolute)
41
+ throw error;
42
+ return path.join(realPathForAccess(parent), path.basename(absolute));
43
+ }
44
+ }
45
+ export function assertProjectFilesInsideRoot(root, project) {
46
+ const actualRoot = fs.realpathSync(root);
47
+ for (const target of [project, ...[".gitignore", ".mdgraph", ".mdgraph/config.json", ".mdgraph/graph.db", ".mdgraph/graph.db-wal", ".mdgraph/graph.db-shm", ".mdgraph/graph.db-journal"].map((entry) => path.join(project, entry))]) {
48
+ if (!isPathInsideOrEqual(actualRoot, realPathForAccess(target))) {
49
+ throw new Error(`Project files must stay inside served project root: ${root}. Start a separate MDGraph server with --path set to the intended external project.`);
50
+ }
51
+ }
52
+ }
@@ -18,7 +18,6 @@ export async function watchProject(projectRoot, options = {}) {
18
18
  health.close();
19
19
  throw error;
20
20
  }
21
- const watchesMdx = config.index.parseMdx;
22
21
  const debounceMs = options.debounceMs ?? 250;
23
22
  let timer;
24
23
  let running = false;
@@ -26,6 +25,8 @@ export async function watchProject(projectRoot, options = {}) {
26
25
  let closed = false;
27
26
  let ready = false;
28
27
  let activeIndex;
28
+ let reloadInFlight;
29
+ let reloadQueued = false;
29
30
  const runIndex = async () => {
30
31
  if (closed) {
31
32
  return;
@@ -71,20 +72,85 @@ export async function watchProject(projectRoot, options = {}) {
71
72
  };
72
73
  const scheduleIndexForMarkdown = (filePath) => {
73
74
  const lower = filePath.toLowerCase();
74
- if (lower.endsWith(".md") || (watchesMdx && lower.endsWith(".mdx"))) {
75
+ if (lower.endsWith(".md") || (config.index.parseMdx && lower.endsWith(".mdx"))) {
75
76
  scheduleIndex();
76
77
  }
77
78
  };
78
- let watcher;
79
- try {
80
- watcher = chokidar.watch(".", {
79
+ const bindWatcher = (candidate) => {
80
+ const onFileEvent = (filePath) => {
81
+ if (isWatchControlFile(projectRoot, filePath)) {
82
+ void reloadWatchRules();
83
+ return;
84
+ }
85
+ scheduleIndexForMarkdown(filePath);
86
+ };
87
+ candidate.on("add", onFileEvent);
88
+ candidate.on("change", onFileEvent);
89
+ candidate.on("unlink", onFileEvent);
90
+ candidate.on("error", (error) => {
91
+ if (!ready)
92
+ return;
93
+ health.recordError(error, "runtime");
94
+ notifyError(options.onError, error);
95
+ });
96
+ };
97
+ const createWatcher = (nextConfig, nextIgnored) => {
98
+ const candidate = chokidar.watch(".", {
81
99
  cwd: projectRoot,
82
- ignored: createWatchIgnoreMatcher(projectRoot, ignored, watchesMdx),
100
+ ignored: createWatchIgnoreMatcher(projectRoot, nextIgnored, nextConfig.index.parseMdx),
83
101
  ignoreInitial: true,
84
102
  persistent: true,
85
103
  usePolling: options.usePolling ?? false,
86
104
  awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
87
105
  });
106
+ bindWatcher(candidate);
107
+ return candidate;
108
+ };
109
+ let watcher;
110
+ const reloadWatchRules = async () => {
111
+ if (reloadInFlight) {
112
+ reloadQueued = true;
113
+ return reloadInFlight;
114
+ }
115
+ reloadInFlight = (async () => {
116
+ let replacement;
117
+ try {
118
+ const nextConfig = loadConfig(projectRoot);
119
+ const nextIgnored = await resolveIgnorePatterns(projectRoot, nextConfig);
120
+ replacement = createWatcher(nextConfig, nextIgnored);
121
+ await waitForReady(replacement);
122
+ if (closed) {
123
+ await replacement.close();
124
+ return;
125
+ }
126
+ const previous = watcher;
127
+ // Keep the previous watch registered until this one is ready. Events in
128
+ // the overlap simply coalesce through the existing debounce queue.
129
+ watcher = replacement;
130
+ config = nextConfig;
131
+ ignored = nextIgnored;
132
+ await previous.close();
133
+ scheduleIndex();
134
+ }
135
+ catch (error) {
136
+ await replacement?.close();
137
+ // Invalid transient config must not drop the current watcher. A later
138
+ // valid write will retry this path and index success restores health.
139
+ health.recordError(error, "indexing");
140
+ notifyError(options.onError, error);
141
+ }
142
+ finally {
143
+ reloadInFlight = undefined;
144
+ if (reloadQueued && !closed) {
145
+ reloadQueued = false;
146
+ void reloadWatchRules();
147
+ }
148
+ }
149
+ })();
150
+ return reloadInFlight;
151
+ };
152
+ try {
153
+ watcher = createWatcher(config, ignored);
88
154
  }
89
155
  catch (error) {
90
156
  health.recordError(error, "startup");
@@ -92,16 +158,6 @@ export async function watchProject(projectRoot, options = {}) {
92
158
  health.close();
93
159
  throw error;
94
160
  }
95
- watcher.on("add", scheduleIndexForMarkdown);
96
- watcher.on("change", scheduleIndexForMarkdown);
97
- watcher.on("unlink", scheduleIndexForMarkdown);
98
- watcher.on("error", (error) => {
99
- if (!ready) {
100
- return;
101
- }
102
- health.recordError(error, "runtime");
103
- notifyError(options.onError, error);
104
- });
105
161
  try {
106
162
  await waitForReady(watcher);
107
163
  ready = true;
@@ -128,6 +184,9 @@ export async function watchProject(projectRoot, options = {}) {
128
184
  if (activeIndex) {
129
185
  await activeIndex;
130
186
  }
187
+ if (reloadInFlight) {
188
+ await reloadInFlight;
189
+ }
131
190
  }
132
191
  finally {
133
192
  await watcher.close();
@@ -145,6 +204,11 @@ function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
145
204
  return false;
146
205
  }
147
206
  const normalizedPath = relativePath.split(path.sep).join("/");
207
+ // Keep the directory traversable so chokidar can observe config.json even
208
+ // though normal MDGraph artifacts remain ignored below it.
209
+ if (normalizedPath === ".mdgraph" || isWatchControlFile(projectRoot, absolutePath)) {
210
+ return false;
211
+ }
148
212
  if (patterns.some((pattern) => (path.matchesGlob(normalizedPath, pattern)
149
213
  || path.matchesGlob(`${normalizedPath}/`, pattern)))) {
150
214
  return true;
@@ -156,6 +220,11 @@ function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
156
220
  return false;
157
221
  };
158
222
  }
223
+ function isWatchControlFile(projectRoot, candidatePath) {
224
+ const absolutePath = path.isAbsolute(candidatePath) ? candidatePath : path.resolve(projectRoot, candidatePath);
225
+ const relativePath = path.relative(projectRoot, absolutePath).split(path.sep).join("/");
226
+ return relativePath === ".gitignore" || relativePath === ".mdgraph/config.json";
227
+ }
159
228
  function notifyIndexed(onIndexed, result) {
160
229
  try {
161
230
  onIndexed?.(result);
@@ -0,0 +1,20 @@
1
+ import type { GraphRepository } from "../db/repositories.js";
2
+ import type { StatusFreshness } from "../analysis/status-freshness.js";
3
+ import { type WikiEvidencePage } from "./wiki-evidence.js";
4
+ import type { WikiDependencySnapshot } from "./wiki-plan.js";
5
+ export interface WikiDependencyChange {
6
+ kind: "document" | "source_ref" | "plan";
7
+ path: string;
8
+ reason: "modified" | "deleted" | "unavailable" | "plan_changed";
9
+ }
10
+ export interface WikiDependencyAssessment {
11
+ state: "fresh" | "stale" | "unknown";
12
+ currentEvidenceHash: string;
13
+ changes: WikiDependencyChange[];
14
+ recovery?: string;
15
+ }
16
+ /** Compare only a page's selected dependencies, retaining global index status separately. */
17
+ export declare function assessWikiDependencies(projectRoot: string, repository: GraphRepository, page: WikiEvidencePage & {
18
+ evidenceHash: string;
19
+ dependencySnapshot?: WikiDependencySnapshot;
20
+ }, freshness: StatusFreshness, wikiDir?: string): WikiDependencyAssessment;
@@ -0,0 +1,45 @@
1
+ import { calculateWikiPageEvidenceHash, sourceRefFingerprint } from "./wiki-evidence.js";
2
+ /** Compare only a page's selected dependencies, retaining global index status separately. */
3
+ export function assessWikiDependencies(projectRoot, repository, page, freshness, wikiDir) {
4
+ const changes = [];
5
+ const documents = new Map(repository.allDocuments().map((document) => [document.id, document]));
6
+ const savedDocuments = new Map(page.dependencySnapshot?.documents.map((document) => [document.id, document]) ?? []);
7
+ const diskChanges = new Map(freshness.issues?.map((issue) => [issue.path, issue.reason]) ?? []);
8
+ const isWikiOutput = (value) => Boolean(wikiDir && (value === wikiDir || value.startsWith(`${wikiDir}/`)));
9
+ for (const id of page.documentIds) {
10
+ const current = documents.get(id);
11
+ const saved = savedDocuments.get(id);
12
+ const documentPath = current?.path ?? saved?.path ?? id;
13
+ const diskChange = diskChanges.get(documentPath);
14
+ if (isWikiOutput(documentPath))
15
+ changes.push({ kind: "document", path: documentPath, reason: "unavailable" });
16
+ else if (!current || diskChange === "deleted")
17
+ changes.push({ kind: "document", path: documentPath, reason: "deleted" });
18
+ else if (diskChange === "modified" || (saved && saved.hash !== current.hash))
19
+ changes.push({ kind: "document", path: documentPath, reason: "modified" });
20
+ }
21
+ const savedRefs = new Map(page.dependencySnapshot?.sourceRefs.map((ref) => [ref.path, ref.fingerprint]) ?? []);
22
+ for (const sourcePath of page.sourceRefs) {
23
+ const fingerprint = sourceRefFingerprint(projectRoot, sourcePath);
24
+ if (isWikiOutput(sourcePath))
25
+ changes.push({ kind: "source_ref", path: sourcePath, reason: "unavailable" });
26
+ else if (fingerprint === "missing")
27
+ changes.push({ kind: "source_ref", path: sourcePath, reason: "deleted" });
28
+ else if (!/^[a-f0-9]{64}$/.test(fingerprint))
29
+ changes.push({ kind: "source_ref", path: sourcePath, reason: "unavailable" });
30
+ else if (savedRefs.has(sourcePath) && savedRefs.get(sourcePath) !== fingerprint)
31
+ changes.push({ kind: "source_ref", path: sourcePath, reason: "modified" });
32
+ }
33
+ const currentEvidenceHash = calculateWikiPageEvidenceHash(projectRoot, repository, page);
34
+ if (!changes.length && currentEvidenceHash !== page.evidenceHash)
35
+ changes.push({ kind: "plan", path: page.path, reason: "plan_changed" });
36
+ changes.sort((a, b) => a.kind.localeCompare(b.kind) || a.path.localeCompare(b.path) || a.reason.localeCompare(b.reason));
37
+ const state = freshness.state === "unknown" || changes.some((change) => change.reason === "unavailable")
38
+ ? "unknown" : changes.length ? "stale" : "fresh";
39
+ return {
40
+ state, currentEvidenceHash, changes,
41
+ recovery: state === "fresh" ? undefined : state === "unknown"
42
+ ? "Inspect unavailable sources and run `mdgraph doctor --json`; refresh the index and plan before accepting page evidence."
43
+ : "Run `mdgraph index`, update the plan with `wiki plan --from <plan> --out <next-plan>`, review the changes, then update this page from its new brief."
44
+ };
45
+ }
@@ -0,0 +1,13 @@
1
+ import type { GraphDocument } from "../types.js";
2
+ /** Project-neutral starting points; page evidence supplies the actual project vocabulary. */
3
+ export interface WikiDomain {
4
+ id: string;
5
+ title: string;
6
+ path: string;
7
+ purpose: string;
8
+ audience: string;
9
+ outline: string[];
10
+ evidenceQueries: string[];
11
+ score(document: GraphDocument): number;
12
+ }
13
+ export declare const WIKI_DOMAINS: WikiDomain[];
@@ -0,0 +1,55 @@
1
+ const words = (document, values) => {
2
+ const text = `${document.title} ${document.path}`.toLowerCase();
3
+ return values.reduce((score, word) => score + (text.includes(word) ? 3 : 0), 0);
4
+ };
5
+ const basename = (document, names) => names.includes(document.path.split("/").at(-1).toLowerCase()) ? 12 : 0;
6
+ export const WIKI_DOMAINS = [
7
+ {
8
+ id: "project-overview", title: "Project Overview", path: "index.md",
9
+ purpose: "Explain what this project does, who it serves, how to start, and where to find the next useful instructions.",
10
+ audience: "New users and contributors evaluating or starting with the project.",
11
+ outline: ["Purpose and audience", "Core concepts", "Getting started", "First successful task", "Next steps"],
12
+ evidenceQueries: ["project purpose getting started"],
13
+ score: (document) => basename(document, ["readme.md", "readme-zh.md"]) + words(document, ["overview", "introduction", "quickstart", "概览", "快速开始"])
14
+ },
15
+ {
16
+ id: "architecture", title: "Architecture", path: "architecture.md",
17
+ purpose: "Explain implemented components, their responsibilities, data flow, and the decisions behind their boundaries.",
18
+ audience: "Contributors changing behavior across components.",
19
+ outline: ["System boundary", "Components", "Data flow", "Decisions", "Extension points"],
20
+ evidenceQueries: ["architecture components decisions"],
21
+ score: (document) => (document.type === "adr" ? 8 : document.type === "design" ? 5 : 0) + words(document, ["architecture", "design", "decision", "架构", "设计", "决策"])
22
+ },
23
+ {
24
+ id: "core-workflows", title: "Core Workflows", path: "core-workflows.md",
25
+ purpose: "Describe the project's main user tasks, their prerequisites, successful outcomes, and recovery steps.",
26
+ audience: "Users applying the project to real tasks.",
27
+ outline: ["Main tasks", "Prerequisites", "Steps and outcomes", "Failure recovery", "Related tasks"],
28
+ evidenceQueries: ["usage workflow tasks"],
29
+ score: (document) => (document.type === "spec" ? 2 : 0) + words(document, ["workflow", "usage", "tutorial", "guide", "工作流", "使用", "教程"])
30
+ },
31
+ {
32
+ id: "development", title: "Development Guide", path: "development.md",
33
+ purpose: "Explain contributor setup, repository conventions, checks, and the change workflow.",
34
+ audience: "Contributors implementing and reviewing changes.",
35
+ outline: ["Setup", "Conventions", "Build and test", "Change workflow", "Review"],
36
+ evidenceQueries: ["development contribution build test"],
37
+ score: (document) => basename(document, ["agents.md", "contributing.md"]) + words(document, ["development", "contributing", "testing", "开发", "贡献", "测试"])
38
+ },
39
+ {
40
+ id: "operations", title: "Operations and Troubleshooting", path: "operations.md",
41
+ purpose: "Explain how to run the project, inspect failures, and recover normal operation.",
42
+ audience: "Users and maintainers operating or troubleshooting the project.",
43
+ outline: ["Running the project", "Diagnostics", "Common failures", "Recovery", "Maintenance"],
44
+ evidenceQueries: ["operations troubleshooting recovery"],
45
+ score: (document) => (document.type === "runbook" || document.type === "incident" ? 8 : 0) + words(document, ["operations", "runbook", "incident", "troubleshoot", "运维", "排障", "故障"])
46
+ },
47
+ {
48
+ id: "reference", title: "Reference", path: "reference.md",
49
+ purpose: "Locate exact public interfaces, configuration, compatibility requirements, and input/output contracts.",
50
+ audience: "Users and integrators needing precise interface details.",
51
+ outline: ["Public interfaces", "Configuration", "Inputs and outputs", "Compatibility", "Examples"],
52
+ evidenceQueries: ["reference interfaces configuration contracts"],
53
+ score: (document) => (document.type === "api" ? 7 : 0) + words(document, ["reference", "contract", "configuration", "参考", "契约", "配置"])
54
+ }
55
+ ];
@@ -0,0 +1,27 @@
1
+ import { type StatusFreshness } from "../analysis/status-freshness.js";
2
+ import type { GraphRepository } from "../db/repositories.js";
3
+ export interface WikiEvidencePage {
4
+ id: string;
5
+ title: string;
6
+ path: string;
7
+ parentId?: string;
8
+ purpose: string;
9
+ audience: string;
10
+ outline: string[];
11
+ documentIds: string[];
12
+ sourceRefs: string[];
13
+ evidenceQueries: string[];
14
+ }
15
+ export interface WikiContentFreshnessOptions {
16
+ wikiDir?: string;
17
+ }
18
+ export interface WikiPageEvidenceStatus {
19
+ currentEvidenceHash: string;
20
+ staleDocumentPaths: string[];
21
+ }
22
+ /** Returns the strict on-disk Markdown evidence used by Wiki plan, brief, and status. */
23
+ export declare function wikiContentFreshness(projectRoot: string, repository: GraphRepository, options?: WikiContentFreshnessOptions): StatusFreshness;
24
+ export declare function calculateWikiPageEvidenceHash(projectRoot: string, repository: GraphRepository, page: WikiEvidencePage): string;
25
+ export declare function wikiPageEvidenceStatus(projectRoot: string, repository: GraphRepository, page: WikiEvidencePage, freshness: StatusFreshness): WikiPageEvidenceStatus;
26
+ export declare function sourceRefFingerprint(projectRoot: string, sourceRef: string): string;
27
+ export declare function safeProjectRelativePath(value: string): string | undefined;
@@ -0,0 +1,112 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { computeStatusFreshness } from "../analysis/status-freshness.js";
5
+ import { hashCanonical } from "../bundle/bundle.js";
6
+ import { loadConfig } from "../config/load-config.js";
7
+ import { isPathInsideOrEqual, resolveInsideRoot } from "../utils/path-safety.js";
8
+ import { normalizePath } from "../utils/text.js";
9
+ /** Returns the strict on-disk Markdown evidence used by Wiki plan, brief, and status. */
10
+ export function wikiContentFreshness(projectRoot, repository, options = {}) {
11
+ const wikiRelativePath = options.wikiDir && isPathInsideOrEqual(projectRoot, options.wikiDir)
12
+ ? normalizePath(path.relative(projectRoot, options.wikiDir))
13
+ : undefined;
14
+ return computeStatusFreshness(projectRoot, loadConfig(projectRoot), repository, {
15
+ strictContentHash: true,
16
+ ignorePaths: wikiRelativePath && wikiRelativePath !== "." ? [wikiRelativePath] : undefined
17
+ });
18
+ }
19
+ export function calculateWikiPageEvidenceHash(projectRoot, repository, page) {
20
+ const documentsById = new Map(repository.allDocuments().map((document) => [document.id, document]));
21
+ const documents = page.documentIds.map((documentId) => {
22
+ const document = documentsById.get(documentId);
23
+ return document
24
+ ? { id: document.id, path: document.path, hash: document.hash }
25
+ : { id: documentId, missing: true };
26
+ });
27
+ const sourceRefs = page.sourceRefs.map((sourceRef) => ({
28
+ path: sourceRef,
29
+ fingerprint: sourceRefFingerprint(projectRoot, sourceRef)
30
+ }));
31
+ return hashCanonical({
32
+ page: {
33
+ id: page.id,
34
+ title: page.title,
35
+ path: page.path,
36
+ parentId: page.parentId,
37
+ purpose: page.purpose,
38
+ audience: page.audience,
39
+ outline: page.outline,
40
+ documentIds: page.documentIds,
41
+ sourceRefs: page.sourceRefs,
42
+ evidenceQueries: page.evidenceQueries
43
+ },
44
+ documents,
45
+ sourceRefs
46
+ });
47
+ }
48
+ export function wikiPageEvidenceStatus(projectRoot, repository, page, freshness) {
49
+ const documentsById = new Map(repository.allDocuments().map((document) => [document.id, document.path]));
50
+ const stalePaths = new Set(freshness.issues
51
+ ?.filter((issue) => issue.reason === "modified" || issue.reason === "deleted")
52
+ .map((issue) => issue.path) ?? []);
53
+ return {
54
+ currentEvidenceHash: calculateWikiPageEvidenceHash(projectRoot, repository, page),
55
+ staleDocumentPaths: page.documentIds.flatMap((documentId) => {
56
+ const documentPath = documentsById.get(documentId);
57
+ return documentPath && stalePaths.has(documentPath) ? [documentPath] : [];
58
+ })
59
+ };
60
+ }
61
+ export function sourceRefFingerprint(projectRoot, sourceRef) {
62
+ const normalized = safeProjectRelativePath(sourceRef);
63
+ if (!normalized)
64
+ return "unsafe";
65
+ try {
66
+ const resolved = resolveInsideRoot(projectRoot, normalized);
67
+ if (!resolved || !fs.existsSync(resolved))
68
+ return "missing";
69
+ const stat = fs.lstatSync(resolved);
70
+ if (stat.isSymbolicLink()) {
71
+ let realPath;
72
+ try {
73
+ realPath = fs.realpathSync(resolved);
74
+ }
75
+ catch {
76
+ return "broken-symlink";
77
+ }
78
+ if (!isPathInsideOrEqual(projectRoot, realPath))
79
+ return "unsafe-symlink";
80
+ }
81
+ if (!stat.isFile() && !stat.isSymbolicLink())
82
+ return "not-file";
83
+ return hashFile(resolved);
84
+ }
85
+ catch {
86
+ return "unreadable";
87
+ }
88
+ }
89
+ export function safeProjectRelativePath(value) {
90
+ const normalized = normalizePath(value.trim()).replace(/^\.\//, "");
91
+ const segments = normalized.split("/");
92
+ return !normalized || normalized.includes("\0") || path.isAbsolute(normalized) || path.posix.isAbsolute(normalized) || /^[a-z]:\//i.test(normalized) || segments.some((segment) => !segment || segment === "." || segment === "..")
93
+ ? undefined
94
+ : normalized;
95
+ }
96
+ function hashFile(filePath) {
97
+ const hash = createHash("sha256");
98
+ const buffer = Buffer.allocUnsafe(64 * 1024);
99
+ const descriptor = fs.openSync(filePath, "r");
100
+ try {
101
+ let bytesRead = 0;
102
+ do {
103
+ bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, null);
104
+ if (bytesRead > 0)
105
+ hash.update(buffer.subarray(0, bytesRead));
106
+ } while (bytesRead > 0);
107
+ }
108
+ finally {
109
+ fs.closeSync(descriptor);
110
+ }
111
+ return hash.digest("hex");
112
+ }
@@ -0,0 +1,121 @@
1
+ import { GraphRepository } from "../db/repositories.js";
2
+ import { type StatusFreshness } from "../analysis/status-freshness.js";
3
+ import { type ContextItem } from "../query/context-builder.js";
4
+ import { type KnowledgeCard } from "../query/knowledge-card.js";
5
+ import type { GraphDocument, MDGraphConfig } from "../types.js";
6
+ import { type WikiDependencyAssessment } from "./wiki-dependencies.js";
7
+ export { calculateWikiPageEvidenceHash, safeProjectRelativePath, sourceRefFingerprint } from "./wiki-evidence.js";
8
+ export declare const WIKI_PLAN_FORMAT: "mdgraph-wiki-plan";
9
+ export declare const WIKI_PLAN_FORMAT_VERSION: 2;
10
+ export declare const WIKI_PAGE_BRIEF_FORMAT: "mdgraph-wiki-page-brief";
11
+ export declare const WIKI_PAGE_BRIEF_FORMAT_VERSION: 1;
12
+ export interface WikiPlan {
13
+ format: typeof WIKI_PLAN_FORMAT;
14
+ formatVersion: 1 | typeof WIKI_PLAN_FORMAT_VERSION;
15
+ graphHash: string;
16
+ sourceHash: string;
17
+ /** v2 records the project-relative generated Wiki root. */
18
+ wikiDir?: string;
19
+ /** Additive strict Markdown content evidence for deciding whether to use this plan. */
20
+ strictFreshness?: WikiStrictFreshness;
21
+ pages: WikiPlanPage[];
22
+ suggestions?: WikiPlanSuggestions;
23
+ gaps?: WikiPlanGap[];
24
+ }
25
+ export interface WikiPlanSuggestions {
26
+ pages: WikiPlanPage[];
27
+ sources: Array<{
28
+ pageId: string;
29
+ documentIds: string[];
30
+ sourceRefs: string[];
31
+ }>;
32
+ }
33
+ export interface WikiPlanGap {
34
+ kind: "document" | "source_ref" | "domain";
35
+ path?: string;
36
+ reason: string;
37
+ recovery: string;
38
+ }
39
+ export interface WikiPlanOptions {
40
+ from?: WikiPlan;
41
+ wikiDir?: string;
42
+ }
43
+ export interface WikiStrictFreshness {
44
+ state: StatusFreshness["state"];
45
+ recommendation: string;
46
+ issues?: NonNullable<StatusFreshness["issues"]>;
47
+ }
48
+ export interface WikiPlanPage {
49
+ id: string;
50
+ title: string;
51
+ path: string;
52
+ parentId?: string;
53
+ purpose: string;
54
+ audience: string;
55
+ outline: string[];
56
+ documentIds: string[];
57
+ sourceRefs: string[];
58
+ evidenceQueries: string[];
59
+ evidenceHash: string;
60
+ dependencySnapshot?: WikiDependencySnapshot;
61
+ gaps?: WikiPlanGap[];
62
+ }
63
+ export interface WikiDependencySnapshot {
64
+ documents: Array<{
65
+ id: string;
66
+ path?: string;
67
+ hash?: string;
68
+ missing?: true;
69
+ }>;
70
+ sourceRefs: Array<{
71
+ path: string;
72
+ fingerprint: string;
73
+ }>;
74
+ }
75
+ export interface WikiPageBrief {
76
+ format: typeof WIKI_PAGE_BRIEF_FORMAT;
77
+ formatVersion: typeof WIKI_PAGE_BRIEF_FORMAT_VERSION;
78
+ page: WikiPlanPage;
79
+ maxChars: number;
80
+ usedChars: number;
81
+ sourceDocuments: WikiBriefSourceDocument[];
82
+ supplementaryDocuments: WikiBriefSourceDocument[];
83
+ sourceInspections: Array<{
84
+ path: string;
85
+ instruction: string;
86
+ }>;
87
+ evidenceGaps: WikiPlanGap[];
88
+ dependencyEvidence: WikiDependencyAssessment;
89
+ contextItems: ContextItem[];
90
+ knowledgeCards: KnowledgeCard[];
91
+ writingRequirements: string[];
92
+ suggestedNextQueries: string[];
93
+ /** Strict Markdown content evidence available when the brief was prepared. */
94
+ strictFreshness: WikiStrictFreshness;
95
+ }
96
+ export interface WikiBriefSourceDocument {
97
+ id: string;
98
+ path: string;
99
+ title: string;
100
+ type: GraphDocument["type"];
101
+ status: string;
102
+ trustTier: GraphDocument["trustTier"];
103
+ }
104
+ export interface WikiBriefOptions {
105
+ maxChars?: number;
106
+ }
107
+ export declare class WikiPlanError extends Error {
108
+ readonly code: string;
109
+ readonly recovery: string;
110
+ constructor(code: string, message: string, recovery: string);
111
+ }
112
+ export declare function buildWikiPlan(projectRoot: string, repository: GraphRepository, options?: WikiPlanOptions): WikiPlan;
113
+ export declare function buildWikiPageBrief(projectRoot: string, repository: GraphRepository, config: MDGraphConfig, plan: WikiPlan, pageId: string, options?: WikiBriefOptions): WikiPageBrief;
114
+ export declare function stableWikiPlan(plan: WikiPlan): string;
115
+ export declare function formatWikiPlan(plan: WikiPlan): string;
116
+ export declare function formatWikiPageBrief(brief: WikiPageBrief): string;
117
+ export declare function writeWikiPlan(filePath: string, plan: WikiPlan): void;
118
+ export declare function readWikiPlan(filePath: string): WikiPlan;
119
+ export declare function validateWikiPlan(value: unknown): WikiPlan;
120
+ export declare function safeWikiPagePath(value: string): string | undefined;
121
+ export declare function wikiSourceHash(repository: GraphRepository, wikiDir?: string): string;