@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.
Files changed (106) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README-ZH.md +66 -4
  3. package/README.md +84 -22
  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 +260 -25
  12. package/dist/config/limits.d.ts +2 -0
  13. package/dist/config/limits.js +3 -1
  14. package/dist/config/load-config.js +8 -2
  15. package/dist/db/connection.js +17 -1
  16. package/dist/db/repositories.d.ts +55 -4
  17. package/dist/db/repositories.js +458 -11
  18. package/dist/db/sqlite-adapter.js +8 -2
  19. package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
  20. package/dist/evaluation/context-packing-evaluation.js +134 -0
  21. package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
  22. package/dist/evaluation/entity-extraction-evaluation.js +118 -0
  23. package/dist/evaluation/historical-baseline.d.ts +70 -0
  24. package/dist/evaluation/historical-baseline.js +278 -0
  25. package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
  26. package/dist/evaluation/related-documents-evaluation.js +163 -0
  27. package/dist/evaluation/retrieval-eval.d.ts +25 -5
  28. package/dist/evaluation/retrieval-eval.js +79 -7
  29. package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
  30. package/dist/evaluation/structured-query-evaluation.js +156 -0
  31. package/dist/extraction/entity-extractor.js +42 -22
  32. package/dist/extraction/graph-builder.js +2 -18
  33. package/dist/index.d.ts +24 -4
  34. package/dist/index.js +12 -4
  35. package/dist/indexer.js +80 -4
  36. package/dist/mcp/server.d.ts +4 -0
  37. package/dist/mcp/server.js +21 -11
  38. package/dist/mcp/tools.d.ts +5 -1
  39. package/dist/mcp/tools.js +116 -18
  40. package/dist/parser/markdown-parser.js +2 -0
  41. package/dist/query/context-builder.d.ts +32 -2
  42. package/dist/query/context-builder.js +191 -12
  43. package/dist/query/knowledge-card.d.ts +90 -0
  44. package/dist/query/knowledge-card.js +676 -0
  45. package/dist/query/search.d.ts +5 -1
  46. package/dist/query/search.js +85 -16
  47. package/dist/query/structured-query-executor.d.ts +28 -0
  48. package/dist/query/structured-query-executor.js +138 -0
  49. package/dist/query/structured-query.d.ts +50 -0
  50. package/dist/query/structured-query.js +390 -0
  51. package/dist/relationships/derive-related.d.ts +86 -0
  52. package/dist/relationships/derive-related.js +322 -0
  53. package/dist/reporting/report.js +2 -2
  54. package/dist/semantic/embed-chunks.d.ts +2 -0
  55. package/dist/semantic/embed-chunks.js +31 -0
  56. package/dist/semantic/ollama-provider.d.ts +6 -0
  57. package/dist/semantic/ollama-provider.js +136 -0
  58. package/dist/semantic/provider-registry.d.ts +8 -0
  59. package/dist/semantic/provider-registry.js +66 -0
  60. package/dist/semantic/provider.d.ts +35 -0
  61. package/dist/semantic/provider.js +29 -0
  62. package/dist/semantic/status.d.ts +6 -1
  63. package/dist/semantic/status.js +49 -3
  64. package/dist/types.d.ts +7 -2
  65. package/dist/types.js +2 -1
  66. package/dist/utils/path-safety.d.ts +3 -0
  67. package/dist/utils/path-safety.js +27 -0
  68. package/dist/watcher/file-watcher.d.ts +4 -0
  69. package/dist/watcher/file-watcher.js +151 -17
  70. package/dist/watcher/watch-health.d.ts +34 -0
  71. package/dist/watcher/watch-health.js +75 -0
  72. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  73. package/dist/wiki/wiki-dependencies.js +45 -0
  74. package/dist/wiki/wiki-domains.d.ts +13 -0
  75. package/dist/wiki/wiki-domains.js +55 -0
  76. package/dist/wiki/wiki-evidence.d.ts +27 -0
  77. package/dist/wiki/wiki-evidence.js +112 -0
  78. package/dist/wiki/wiki-plan.d.ts +121 -0
  79. package/dist/wiki/wiki-plan.js +616 -0
  80. package/dist/wiki/wiki-status.d.ts +67 -0
  81. package/dist/wiki/wiki-status.js +451 -0
  82. package/docs/EN/Agent_Integration.md +15 -5
  83. package/docs/EN/Architecture.md +52 -16
  84. package/docs/EN/Evaluation_Questions.md +35 -5
  85. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  86. package/docs/EN/Operations.md +111 -0
  87. package/docs/EN/Output_Contracts.md +83 -10
  88. package/docs/EN/Public_Contracts.md +25 -16
  89. package/docs/EN/Public_Contracts_1.0.md +32 -18
  90. package/docs/EN/README.md +24 -0
  91. package/docs/EN/Release_Checklist.md +27 -13
  92. package/docs/EN/Retrieval_and_Context.md +118 -0
  93. package/docs/EN/Structured_Query_and_Relationships.md +111 -0
  94. package/docs/ZH/Agent_Integration.md +15 -5
  95. package/docs/ZH/Architecture.md +52 -21
  96. package/docs/ZH/Evaluation_Questions.md +36 -6
  97. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  98. package/docs/ZH/Operations.md +111 -0
  99. package/docs/ZH/Output_Contracts.md +83 -10
  100. package/docs/ZH/Public_Contracts.md +24 -15
  101. package/docs/ZH/Public_Contracts_1.0.md +31 -17
  102. package/docs/ZH/README.md +24 -0
  103. package/docs/ZH/Release_Checklist.md +27 -13
  104. package/docs/ZH/Retrieval_and_Context.md +118 -0
  105. package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
  106. package/package.json +50 -19
@@ -1,5 +1,7 @@
1
1
  import type { StorageDiagnostics, StatusCounts } from "../db/repositories.js";
2
2
  import type { MDGraphConfig } from "../types.js";
3
+ import type { EmbeddingCapability, EmbeddingRuntimeStatus } from "./provider.js";
4
+ export { SUPPORTED_EMBEDDING_PROVIDERS } from "./provider-registry.js";
3
5
  export type SemanticStatusState = "disabled" | "not_indexed" | "ready" | "unsupported_provider" | "needs_reindex";
4
6
  export interface SemanticStatusReport {
5
7
  state: SemanticStatusState;
@@ -8,6 +10,9 @@ export interface SemanticStatusReport {
8
10
  model: string;
9
11
  dimensions: number;
10
12
  providerSupported: boolean;
13
+ capability: EmbeddingCapability | "unknown";
14
+ runtimeStatus: EmbeddingRuntimeStatus;
15
+ runtimeReason?: string;
11
16
  indexed: boolean;
12
17
  chunks: number;
13
18
  vectors: number;
@@ -15,5 +20,5 @@ export interface SemanticStatusReport {
15
20
  indexedProviders: StorageDiagnostics["vectors"]["providers"];
16
21
  guidance: string[];
17
22
  }
18
- export declare const SUPPORTED_EMBEDDING_PROVIDERS: readonly ["local-hash"];
19
23
  export declare function semanticStatusReport(config: MDGraphConfig, counts: StatusCounts | undefined, storage: StorageDiagnostics | undefined): SemanticStatusReport;
24
+ export declare function semanticStatusReportAsync(config: MDGraphConfig, counts: StatusCounts | undefined, storage: StorageDiagnostics | undefined): Promise<SemanticStatusReport>;
@@ -1,5 +1,6 @@
1
1
  import { LOCAL_EMBEDDING_PROVIDER } from "./local-embedding.js";
2
- export const SUPPORTED_EMBEDDING_PROVIDERS = [LOCAL_EMBEDDING_PROVIDER];
2
+ import { createEmbeddingProvider, embeddingCapability, isSupportedEmbeddingProvider } from "./provider-registry.js";
3
+ export { SUPPORTED_EMBEDDING_PROVIDERS } from "./provider-registry.js";
3
4
  export function semanticStatusReport(config, counts, storage) {
4
5
  const providerSupported = isSupportedEmbeddingProvider(config.embedding.provider);
5
6
  const indexed = Boolean(counts);
@@ -39,6 +40,8 @@ export function semanticStatusReport(config, counts, storage) {
39
40
  model: config.embedding.model,
40
41
  dimensions: config.embedding.dimensions,
41
42
  providerSupported,
43
+ capability: embeddingCapability(config.embedding.provider),
44
+ runtimeStatus: initialRuntimeStatus(config, providerSupported),
42
45
  indexed,
43
46
  chunks,
44
47
  vectors,
@@ -47,8 +50,51 @@ export function semanticStatusReport(config, counts, storage) {
47
50
  guidance
48
51
  };
49
52
  }
50
- function isSupportedEmbeddingProvider(provider) {
51
- return SUPPORTED_EMBEDDING_PROVIDERS.includes(provider);
53
+ export async function semanticStatusReportAsync(config, counts, storage) {
54
+ const report = semanticStatusReport(config, counts, storage);
55
+ if (!config.embedding.enabled || !report.providerSupported || config.embedding.provider === LOCAL_EMBEDDING_PROVIDER) {
56
+ return report;
57
+ }
58
+ try {
59
+ const availability = await createEmbeddingProvider(config.embedding).availability();
60
+ if (availability.status === "available") {
61
+ return { ...report, runtimeStatus: "available" };
62
+ }
63
+ const guidance = [...report.guidance];
64
+ if (availability.status === "model_missing") {
65
+ guidance.push(`Install the configured embedding model '${config.embedding.model}' before indexing or semantic queries.`);
66
+ }
67
+ else {
68
+ guidance.push("Start the configured embedding provider or correct embedding.endpoint before retrying semantic operations.");
69
+ }
70
+ return {
71
+ ...report,
72
+ runtimeStatus: availability.status,
73
+ runtimeReason: availability.reason,
74
+ guidance
75
+ };
76
+ }
77
+ catch (error) {
78
+ const reason = error instanceof Error ? error.message : String(error);
79
+ return {
80
+ ...report,
81
+ runtimeStatus: "unavailable",
82
+ runtimeReason: reason,
83
+ guidance: [...report.guidance, "Correct the embedding provider configuration before retrying semantic operations."]
84
+ };
85
+ }
86
+ }
87
+ function initialRuntimeStatus(config, providerSupported) {
88
+ if (!config.embedding.enabled) {
89
+ return "disabled";
90
+ }
91
+ if (!providerSupported) {
92
+ return "unavailable";
93
+ }
94
+ if (config.embedding.provider === LOCAL_EMBEDDING_PROVIDER) {
95
+ return "available";
96
+ }
97
+ return "unchecked";
52
98
  }
53
99
  function semanticState(input) {
54
100
  if (!input.indexed) {
package/dist/types.d.ts CHANGED
@@ -3,8 +3,9 @@ export type TrustTier = "authored" | "generated" | "validated" | "external" | "u
3
3
  export type SearchQueryMode = "auto" | "keyword" | "semantic";
4
4
  export type EntityKind = "symbol" | "api_route" | "error_code" | "config_key" | "file_path" | "command" | "package" | "concept" | "decision";
5
5
  export type EdgeKind = "CONTAINS" | "DEFINES" | "REFERENCES" | "DEPENDS_ON" | "LINKS_TO" | "IMPLEMENTS" | "REFERENCES_SOURCE" | "SUPERSEDES" | "DEPRECATED_BY" | "SAME_AS" | "RELATED_TO" | "CONTRADICTS";
6
- export declare const RESERVED_EDGE_KINDS: readonly ["SAME_AS", "RELATED_TO", "CONTRADICTS"];
7
- export type Provenance = "frontmatter" | "markdown_link" | "wikilink" | "declared_section" | "heading" | "inline_code" | "code_block" | "regex";
6
+ export declare const RESERVED_EDGE_KINDS: readonly ["SAME_AS", "CONTRADICTS"];
7
+ export declare const DERIVED_EDGE_KINDS: readonly ["RELATED_TO"];
8
+ export type Provenance = "frontmatter" | "markdown_link" | "wikilink" | "declared_section" | "heading" | "inline_code" | "code_block" | "regex" | "embedding_similarity";
8
9
  export interface MDGraphConfig {
9
10
  docs: {
10
11
  include: string[];
@@ -30,6 +31,9 @@ export interface MDGraphConfig {
30
31
  provider: string;
31
32
  model: string;
32
33
  dimensions: number;
34
+ endpoint?: string;
35
+ timeoutMs?: number;
36
+ batchSize?: number;
33
37
  };
34
38
  }
35
39
  export interface DocumentFrontmatter {
@@ -92,6 +96,7 @@ export interface ParsedDocument {
92
96
  relativePath: string;
93
97
  title: string;
94
98
  hash: string;
99
+ updatedAt?: string;
95
100
  frontmatter: DocumentFrontmatter;
96
101
  frontmatterDiagnostics: FrontmatterDiagnostic[];
97
102
  body: string;
package/dist/types.js CHANGED
@@ -1,4 +1,5 @@
1
- export const RESERVED_EDGE_KINDS = ["SAME_AS", "RELATED_TO", "CONTRADICTS"];
1
+ export const RESERVED_EDGE_KINDS = ["SAME_AS", "CONTRADICTS"];
2
+ export const DERIVED_EDGE_KINDS = ["RELATED_TO"];
2
3
  export const EDGE_WEIGHTS = {
3
4
  CONTAINS: 5,
4
5
  DEFINES: 10,
@@ -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
+ }
@@ -1,11 +1,15 @@
1
1
  import { type IndexResult } from "../indexer.js";
2
+ import { type WatchHealthSnapshot } from "./watch-health.js";
2
3
  export interface WatchProjectOptions {
3
4
  debounceMs?: number;
4
5
  semantic?: boolean;
6
+ usePolling?: boolean;
5
7
  onIndexed?: (result: IndexResult) => void;
6
8
  onError?: (error: Error) => void;
9
+ onHealthChanged?: (health: WatchHealthSnapshot) => void;
7
10
  }
8
11
  export interface WatchHandle {
9
12
  close: () => Promise<void>;
13
+ getHealth: () => WatchHealthSnapshot;
10
14
  }
11
15
  export declare function watchProject(projectRoot: string, options?: WatchProjectOptions): Promise<WatchHandle>;
@@ -1,17 +1,32 @@
1
1
  import chokidar from "chokidar";
2
+ import path from "node:path";
2
3
  import { loadConfig } from "../config/load-config.js";
3
4
  import { indexProject } from "../indexer.js";
4
5
  import { resolveIgnorePatterns } from "../scanner/file-scanner.js";
6
+ import { WatchHealthTracker } from "./watch-health.js";
5
7
  export async function watchProject(projectRoot, options = {}) {
6
- const config = loadConfig(projectRoot);
7
- const ignored = await resolveIgnorePatterns(projectRoot, config);
8
- const watchesMdx = config.index.parseMdx;
8
+ const health = new WatchHealthTracker(options.usePolling ?? false, options.onHealthChanged);
9
+ let config;
10
+ let ignored;
11
+ try {
12
+ config = loadConfig(projectRoot);
13
+ ignored = await resolveIgnorePatterns(projectRoot, config);
14
+ }
15
+ catch (error) {
16
+ health.recordError(error, "startup");
17
+ notifyError(options.onError, error);
18
+ health.close();
19
+ throw error;
20
+ }
9
21
  const debounceMs = options.debounceMs ?? 250;
10
22
  let timer;
11
23
  let running = false;
12
24
  let queued = false;
13
25
  let closed = false;
26
+ let ready = false;
14
27
  let activeIndex;
28
+ let reloadInFlight;
29
+ let reloadQueued = false;
15
30
  const runIndex = async () => {
16
31
  if (closed) {
17
32
  return;
@@ -25,9 +40,11 @@ export async function watchProject(projectRoot, options = {}) {
25
40
  activeIndex = (async () => {
26
41
  try {
27
42
  const result = await indexProject(projectRoot, { semantic: options.semantic });
28
- options.onIndexed?.(result);
43
+ health.recordIndexSuccess();
44
+ notifyIndexed(options.onIndexed, result);
29
45
  }
30
46
  catch (error) {
47
+ health.recordError(error, "indexing");
31
48
  notifyError(options.onError, error);
32
49
  }
33
50
  finally {
@@ -55,33 +72,108 @@ export async function watchProject(projectRoot, options = {}) {
55
72
  };
56
73
  const scheduleIndexForMarkdown = (filePath) => {
57
74
  const lower = filePath.toLowerCase();
58
- if (lower.endsWith(".md") || (watchesMdx && lower.endsWith(".mdx"))) {
75
+ if (lower.endsWith(".md") || (config.index.parseMdx && lower.endsWith(".mdx"))) {
59
76
  scheduleIndex();
60
77
  }
61
78
  };
62
- const watcher = chokidar.watch(".", {
63
- cwd: projectRoot,
64
- ignored,
65
- ignoreInitial: true,
66
- persistent: true,
67
- awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
68
- });
69
- watcher.on("add", scheduleIndexForMarkdown);
70
- watcher.on("change", scheduleIndexForMarkdown);
71
- watcher.on("unlink", scheduleIndexForMarkdown);
72
- watcher.on("error", (error) => {
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(".", {
99
+ cwd: projectRoot,
100
+ ignored: createWatchIgnoreMatcher(projectRoot, nextIgnored, nextConfig.index.parseMdx),
101
+ ignoreInitial: true,
102
+ persistent: true,
103
+ usePolling: options.usePolling ?? false,
104
+ awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
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);
154
+ }
155
+ catch (error) {
156
+ health.recordError(error, "startup");
73
157
  notifyError(options.onError, error);
74
- });
158
+ health.close();
159
+ throw error;
160
+ }
75
161
  try {
76
162
  await waitForReady(watcher);
163
+ ready = true;
164
+ health.recordReady();
77
165
  await runIndex();
78
166
  }
79
167
  catch (error) {
80
168
  closed = true;
169
+ health.recordError(error, "startup");
170
+ notifyError(options.onError, error);
81
171
  await watcher.close();
172
+ health.close();
82
173
  throw error;
83
174
  }
84
175
  return {
176
+ getHealth: () => health.snapshot(),
85
177
  close: async () => {
86
178
  closed = true;
87
179
  if (timer) {
@@ -92,13 +184,55 @@ export async function watchProject(projectRoot, options = {}) {
92
184
  if (activeIndex) {
93
185
  await activeIndex;
94
186
  }
187
+ if (reloadInFlight) {
188
+ await reloadInFlight;
189
+ }
95
190
  }
96
191
  finally {
97
192
  await watcher.close();
193
+ health.close();
98
194
  }
99
195
  }
100
196
  };
101
197
  }
198
+ function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
199
+ const root = path.resolve(projectRoot);
200
+ return (candidatePath, stats) => {
201
+ const absolutePath = path.isAbsolute(candidatePath) ? candidatePath : path.resolve(root, candidatePath);
202
+ const relativePath = path.relative(root, absolutePath);
203
+ if (!relativePath || relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
204
+ return false;
205
+ }
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
+ }
212
+ if (patterns.some((pattern) => (path.matchesGlob(normalizedPath, pattern)
213
+ || path.matchesGlob(`${normalizedPath}/`, pattern)))) {
214
+ return true;
215
+ }
216
+ if (stats && !stats.isDirectory()) {
217
+ return !normalizedPath.toLowerCase().endsWith(".md")
218
+ && !(watchesMdx && normalizedPath.toLowerCase().endsWith(".mdx"));
219
+ }
220
+ return false;
221
+ };
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
+ }
228
+ function notifyIndexed(onIndexed, result) {
229
+ try {
230
+ onIndexed?.(result);
231
+ }
232
+ catch {
233
+ // User callbacks must not break watcher cleanup or future indexing.
234
+ }
235
+ }
102
236
  function notifyError(onError, error) {
103
237
  try {
104
238
  onError?.(error instanceof Error ? error : new Error(String(error)));
@@ -0,0 +1,34 @@
1
+ export type WatchHealthState = "starting" | "healthy" | "degraded" | "failed";
2
+ export type WatchFailurePhase = "startup" | "runtime" | "indexing";
3
+ export type WatchFailureCode = "ENOSPC" | "EMFILE" | "EACCES" | "INDEX_ERROR" | "UNKNOWN";
4
+ export interface WatchHealthError {
5
+ code: WatchFailureCode;
6
+ originalCode?: string;
7
+ phase: WatchFailurePhase;
8
+ message: string;
9
+ occurredAt: string;
10
+ fatal: boolean;
11
+ }
12
+ export interface WatchHealthSnapshot {
13
+ state: WatchHealthState;
14
+ startedAt: string;
15
+ updatedAt: string;
16
+ lastSuccessfulIndexAt?: string;
17
+ lastError?: WatchHealthError;
18
+ consecutiveIndexFailures: number;
19
+ coverageReliable: boolean;
20
+ polling: boolean;
21
+ closed: boolean;
22
+ }
23
+ export declare class WatchHealthTracker {
24
+ private readonly onChanged?;
25
+ private snapshotValue;
26
+ constructor(polling?: boolean, onChanged?: ((health: WatchHealthSnapshot) => void) | undefined, startedAt?: string);
27
+ snapshot(): WatchHealthSnapshot;
28
+ recordReady(at?: string): void;
29
+ recordIndexSuccess(at?: string): void;
30
+ recordError(error: unknown, phase: WatchFailurePhase, at?: string): WatchHealthError;
31
+ close(at?: string): void;
32
+ private update;
33
+ }
34
+ export declare function normalizeWatchError(error: unknown, phase: WatchFailurePhase, occurredAt?: string): WatchHealthError;
@@ -0,0 +1,75 @@
1
+ export class WatchHealthTracker {
2
+ onChanged;
3
+ snapshotValue;
4
+ constructor(polling = false, onChanged, startedAt = new Date().toISOString()) {
5
+ this.onChanged = onChanged;
6
+ this.snapshotValue = {
7
+ state: "starting",
8
+ startedAt,
9
+ updatedAt: startedAt,
10
+ consecutiveIndexFailures: 0,
11
+ coverageReliable: true,
12
+ polling,
13
+ closed: false
14
+ };
15
+ }
16
+ snapshot() {
17
+ return structuredClone(this.snapshotValue);
18
+ }
19
+ recordReady(at = new Date().toISOString()) {
20
+ this.update({ state: "healthy", updatedAt: at });
21
+ }
22
+ recordIndexSuccess(at = new Date().toISOString()) {
23
+ this.update({
24
+ state: this.snapshotValue.coverageReliable ? "healthy" : "degraded",
25
+ updatedAt: at,
26
+ lastSuccessfulIndexAt: at,
27
+ consecutiveIndexFailures: 0
28
+ });
29
+ }
30
+ recordError(error, phase, at = new Date().toISOString()) {
31
+ const normalized = normalizeWatchError(error, phase, at);
32
+ const coverageReliable = phase === "runtime" ? false : this.snapshotValue.coverageReliable;
33
+ this.update({
34
+ state: normalized.fatal ? "failed" : "degraded",
35
+ updatedAt: at,
36
+ lastError: normalized,
37
+ coverageReliable,
38
+ consecutiveIndexFailures: phase === "indexing" ? this.snapshotValue.consecutiveIndexFailures + 1 : this.snapshotValue.consecutiveIndexFailures
39
+ });
40
+ return normalized;
41
+ }
42
+ close(at = new Date().toISOString()) {
43
+ this.update({ updatedAt: at, closed: true });
44
+ }
45
+ update(changes) {
46
+ this.snapshotValue = { ...this.snapshotValue, ...changes };
47
+ try {
48
+ this.onChanged?.(this.snapshot());
49
+ }
50
+ catch {
51
+ // Health observers must not break watcher cleanup or indexing.
52
+ }
53
+ }
54
+ }
55
+ export function normalizeWatchError(error, phase, occurredAt = new Date().toISOString()) {
56
+ const message = error instanceof Error ? error.message : String(error);
57
+ const rawCode = errorCode(error);
58
+ const code = phase === "indexing"
59
+ ? "INDEX_ERROR"
60
+ : rawCode === "ENOSPC" || rawCode === "EMFILE" || rawCode === "EACCES" ? rawCode : "UNKNOWN";
61
+ return {
62
+ code,
63
+ originalCode: phase === "indexing" && rawCode ? rawCode : undefined,
64
+ phase,
65
+ message,
66
+ occurredAt,
67
+ fatal: phase === "startup"
68
+ };
69
+ }
70
+ function errorCode(error) {
71
+ if (!error || typeof error !== "object" || !("code" in error)) {
72
+ return undefined;
73
+ }
74
+ return typeof error.code === "string" && error.code ? error.code : undefined;
75
+ }
@@ -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[];