@daogee/mdgraph 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README-ZH.md +13 -3
- package/README.md +13 -3
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +5 -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 +125 -6
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +30 -5
- package/dist/db/repositories.js +171 -8
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/retrieval-eval.d.ts +11 -0
- package/dist/evaluation/retrieval-eval.js +35 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.js +3 -0
- package/dist/indexer.js +64 -6
- package/dist/mcp/server.js +5 -4
- package/dist/mcp/tools.js +26 -11
- package/dist/query/context-builder.d.ts +2 -0
- package/dist/query/context-builder.js +154 -24
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.js +30 -8
- package/dist/scanner/file-scanner.js +7 -7
- package/dist/semantic/ollama-provider.js +6 -1
- package/dist/utils/fts.d.ts +1 -0
- package/dist/utils/fts.js +68 -13
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.js +121 -17
- 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 +16 -4
- package/docs/EN/Architecture.md +14 -2
- package/docs/EN/Evaluation_Questions.md +21 -1
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +22 -0
- package/docs/EN/Output_Contracts.md +44 -3
- package/docs/EN/Public_Contracts.md +4 -2
- package/docs/EN/Public_Contracts_1.0.md +4 -0
- package/docs/EN/README.md +1 -0
- package/docs/EN/Release_Checklist.md +3 -2
- package/docs/EN/Retrieval_and_Context.md +20 -5
- package/docs/ZH/Agent_Integration.md +16 -4
- package/docs/ZH/Architecture.md +14 -4
- package/docs/ZH/Evaluation_Questions.md +21 -1
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +22 -0
- package/docs/ZH/Output_Contracts.md +44 -3
- package/docs/ZH/Public_Contracts.md +4 -2
- package/docs/ZH/Public_Contracts_1.0.md +4 -0
- package/docs/ZH/README.md +1 -0
- package/docs/ZH/Release_Checklist.md +3 -2
- package/docs/ZH/Retrieval_and_Context.md +20 -5
- package/package.json +8 -3
package/dist/query/search.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { embedTextLocal, supportsLocalEmbedding } from "../semantic/local-embedding.js";
|
|
2
2
|
import { createEmbeddingProvider, supportsSynchronousEmbeddingProvider } from "../semantic/provider-registry.js";
|
|
3
3
|
import { EmbeddingProviderError, embeddingDiagnostic, validateEmbeddingVector } from "../semantic/provider.js";
|
|
4
|
-
import { ftsQueryFor } from "../utils/fts.js";
|
|
4
|
+
import { ftsQueryFor, ftsQueryGroups } from "../utils/fts.js";
|
|
5
5
|
import { normalizeEntityName } from "../utils/text.js";
|
|
6
6
|
const RRF_K = 60;
|
|
7
7
|
const RRF_SCORE_WEIGHT = 1_000;
|
|
@@ -18,13 +18,26 @@ 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
|
-
const
|
|
25
|
+
const queryGroups = ftsQueryGroups(query);
|
|
26
|
+
const balanceLongQuery = queryGroups.some((tokens) => tokens.length > 12);
|
|
27
|
+
const ftsRows = ftsQuery
|
|
28
|
+
? repository.searchChunks(ftsQuery, Math.min(128, Math.max(48, limit * 4, balanceLongQuery ? repository.counts().documents : 0)))
|
|
29
|
+
.map((row) => {
|
|
30
|
+
const coverage = countQueryGroupMatches(queryGroups, row.chunk.content);
|
|
31
|
+
const relevance = balanceLongQuery
|
|
32
|
+
? coverage / Math.sqrt(Math.max(300, row.chunk.content.length) / 300)
|
|
33
|
+
: coverage;
|
|
34
|
+
return { row, coverage, relevance };
|
|
35
|
+
})
|
|
36
|
+
.sort((left, right) => right.relevance - left.relevance || left.row.rank - right.row.rank)
|
|
37
|
+
: [];
|
|
25
38
|
const results = [];
|
|
26
39
|
for (const [index, row] of definitionRows.entries()) {
|
|
27
|
-
const matched =
|
|
40
|
+
const matched = matchedEntitiesById.get(row.entityId);
|
|
28
41
|
results.push({
|
|
29
42
|
channel: "definition",
|
|
30
43
|
rank: index + 1,
|
|
@@ -34,11 +47,11 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
|
|
|
34
47
|
score: adjustScore(200 + row.rank, row.document),
|
|
35
48
|
reason: "definition matched an explicit query entity",
|
|
36
49
|
content: row.chunk.content,
|
|
37
|
-
matchedEntities: matched
|
|
50
|
+
matchedEntities: matched ? [matched] : []
|
|
38
51
|
}
|
|
39
52
|
});
|
|
40
53
|
}
|
|
41
|
-
for (const [index, row] of ftsRows.entries()) {
|
|
54
|
+
for (const [index, { row, coverage, relevance }] of ftsRows.entries()) {
|
|
42
55
|
const matched = matchedEntitiesForContent(matchedEntities, row.chunk.content);
|
|
43
56
|
const penalty = highFrequencyPenalty(matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold);
|
|
44
57
|
results.push({
|
|
@@ -47,8 +60,8 @@ function rankSearchResults(repository, config, query, limit, semanticRows, seman
|
|
|
47
60
|
result: {
|
|
48
61
|
document: row.document,
|
|
49
62
|
section: row.section,
|
|
50
|
-
score: adjustScore(100 - row.rank, row.document, penalty),
|
|
51
|
-
reason: highFrequencyReason(
|
|
63
|
+
score: adjustScore(100 - (balanceLongQuery ? 0 : row.rank) + Math.min(20, relevance * 3), row.document, penalty),
|
|
64
|
+
reason: highFrequencyReason(`FTS5 content match${coverage > 1 ? `; matched ${Number(coverage.toFixed(2))} query groups` : ""}`, matched, entityDocumentFrequencies, config.search.highFrequencyEntityThreshold),
|
|
52
65
|
content: row.chunk.content,
|
|
53
66
|
matchedEntities: matched
|
|
54
67
|
}
|
|
@@ -162,12 +175,21 @@ async function executeSearchGraphAsync(repository, config, query, limit, options
|
|
|
162
175
|
}
|
|
163
176
|
export function extractQueryEntityCandidates(query) {
|
|
164
177
|
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
|
-
|
|
178
|
+
const wholeQuery = query.replace(/^`|`$/g, "").trim();
|
|
179
|
+
return [...new Set([
|
|
180
|
+
wholeQuery,
|
|
181
|
+
...candidates.map((candidate) => candidate.replace(/^`|`$/g, "").trim())
|
|
182
|
+
].filter(Boolean))];
|
|
166
183
|
}
|
|
167
184
|
function matchedEntitiesForContent(entities, content) {
|
|
168
185
|
const lowerContent = content.toLowerCase();
|
|
169
186
|
return entities.filter((entity) => lowerContent.includes(entity.name.toLowerCase()) || lowerContent.includes(entity.normalizedName));
|
|
170
187
|
}
|
|
188
|
+
function countQueryGroupMatches(groups, content) {
|
|
189
|
+
const lowerContent = content.toLowerCase();
|
|
190
|
+
const uniqueGroups = new Map(groups.map((tokens) => [[...tokens].sort().join("\0"), tokens]));
|
|
191
|
+
return [...uniqueGroups.values()].reduce((coverage, tokens) => (coverage + tokens.filter((token) => lowerContent.includes(token)).length / tokens.length), 0);
|
|
192
|
+
}
|
|
171
193
|
function adjustScore(score, document, entityFrequencyPenalty = 0) {
|
|
172
194
|
return score + trustTierBoost(document.trustTier) + statusBoost(document.status) + entityFrequencyPenalty;
|
|
173
195
|
}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import
|
|
4
|
+
import { glob, globSync } from "tinyglobby";
|
|
5
5
|
import { BUILT_IN_DOC_EXCLUDES } from "../config/load-config.js";
|
|
6
6
|
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
7
7
|
export async function scanMarkdownFiles(projectRoot, config) {
|
|
8
8
|
const ignore = await resolveIgnorePatterns(projectRoot, config);
|
|
9
9
|
let entries;
|
|
10
10
|
try {
|
|
11
|
-
entries = await
|
|
11
|
+
entries = await glob(config.docs.include, {
|
|
12
12
|
cwd: projectRoot,
|
|
13
13
|
absolute: true,
|
|
14
14
|
onlyFiles: true,
|
|
15
|
-
|
|
15
|
+
expandDirectories: false,
|
|
16
16
|
dot: false,
|
|
17
17
|
followSymbolicLinks: false,
|
|
18
18
|
ignore
|
|
@@ -24,7 +24,7 @@ export async function scanMarkdownFiles(projectRoot, config) {
|
|
|
24
24
|
}
|
|
25
25
|
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
26
26
|
const accepted = [];
|
|
27
|
-
for (const entry of entries.sort()) {
|
|
27
|
+
for (const entry of [...new Set(entries)].sort()) {
|
|
28
28
|
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
29
29
|
continue;
|
|
30
30
|
}
|
|
@@ -42,11 +42,11 @@ export function scanMarkdownFilesSync(projectRoot, config) {
|
|
|
42
42
|
const ignore = resolveIgnorePatternsSync(projectRoot, config);
|
|
43
43
|
let entries;
|
|
44
44
|
try {
|
|
45
|
-
entries =
|
|
45
|
+
entries = globSync(config.docs.include, {
|
|
46
46
|
cwd: projectRoot,
|
|
47
47
|
absolute: true,
|
|
48
48
|
onlyFiles: true,
|
|
49
|
-
|
|
49
|
+
expandDirectories: false,
|
|
50
50
|
dot: false,
|
|
51
51
|
followSymbolicLinks: false,
|
|
52
52
|
ignore
|
|
@@ -57,7 +57,7 @@ export function scanMarkdownFilesSync(projectRoot, config) {
|
|
|
57
57
|
throw new Error(`Failed to scan Markdown files from ${projectRoot}: ${message}. Check docs.include and docs.exclude globs in ${path.join(projectRoot, ".mdgraph", "config.json")}.`);
|
|
58
58
|
}
|
|
59
59
|
const allowedExtensions = config.index.parseMdx ? [".md", ".mdx"] : [".md"];
|
|
60
|
-
return entries.sort().filter((entry) => {
|
|
60
|
+
return [...new Set(entries)].sort().filter((entry) => {
|
|
61
61
|
if (!isPathInsideOrEqual(projectRoot, entry)) {
|
|
62
62
|
return false;
|
|
63
63
|
}
|
|
@@ -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
|
-
|
|
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);
|
package/dist/utils/fts.d.ts
CHANGED
package/dist/utils/fts.js
CHANGED
|
@@ -1,30 +1,85 @@
|
|
|
1
1
|
const cjkRunPattern = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
|
|
2
|
+
const MAX_QUERY_TOKENS = 48;
|
|
2
3
|
export function ftsIndexContent(content) {
|
|
3
4
|
const cjkTokens = cjkNgramTokens(content);
|
|
4
5
|
return cjkTokens.length ? `${content}\n${cjkTokens.join(" ")}` : content;
|
|
5
6
|
}
|
|
6
7
|
export function ftsQueryFor(query) {
|
|
7
|
-
const
|
|
8
|
-
|
|
8
|
+
const groups = ftsQueryGroups(query);
|
|
9
|
+
const selected = new Set();
|
|
10
|
+
const order = [];
|
|
11
|
+
for (let left = 0, right = groups.length - 1; left <= right; left += 1, right -= 1) {
|
|
12
|
+
order.push(left);
|
|
13
|
+
if (left !== right)
|
|
14
|
+
order.push(right);
|
|
15
|
+
}
|
|
16
|
+
order.sort((left, right) => Number(isAsciiGroup(groups[right])) - Number(isAsciiGroup(groups[left])));
|
|
17
|
+
for (let offset = 0; selected.size < MAX_QUERY_TOKENS && groups.some((group) => offset < group.length); offset += 1) {
|
|
18
|
+
for (const index of order) {
|
|
19
|
+
if (selected.size === MAX_QUERY_TOKENS)
|
|
20
|
+
break;
|
|
21
|
+
const token = groups[index][offset];
|
|
22
|
+
if (token)
|
|
23
|
+
selected.add(token);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return [...selected].map((token) => /^\d+(?:\.\d+)+$/u.test(token)
|
|
27
|
+
? `(${token.split(".").join(" AND ")})`
|
|
28
|
+
: `${escapeFtsToken(token)}*`).join(" OR ");
|
|
9
29
|
}
|
|
10
30
|
export function ftsQueryTokens(query) {
|
|
31
|
+
// Local-hash vectors retain this frequency stream; query allocation uses groups.
|
|
11
32
|
const tokens = [];
|
|
12
|
-
const
|
|
13
|
-
for (const token of lexicalTokens) {
|
|
33
|
+
for (const token of query.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []) {
|
|
14
34
|
const cjkTokens = cjkNgramTokens(token);
|
|
15
35
|
tokens.push(...cjkTokens);
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
?.flatMap((part) => part.split("_")) ?? []);
|
|
20
|
-
if (!cjkTokens.length) {
|
|
36
|
+
tokens.push(...token.replace(cjkRunPattern, " ")
|
|
37
|
+
.match(/[\p{L}\p{N}_]+/gu)?.flatMap((part) => part.split("_")) ?? []);
|
|
38
|
+
if (!cjkTokens.length)
|
|
21
39
|
tokens.push(...token.split("_"));
|
|
40
|
+
}
|
|
41
|
+
return tokens.map(escapeFtsToken).filter((token) => token.length > 1 && !isFtsOperatorToken(token));
|
|
42
|
+
}
|
|
43
|
+
export function ftsQueryGroups(query) {
|
|
44
|
+
return (query.toLowerCase().match(/\d{4}-\d{2}-\d{2}|\d+(?:\.\d+)+|[\p{L}\p{N}_]+/gu) ?? [])
|
|
45
|
+
.map((token) => tokensForTerm(token))
|
|
46
|
+
.filter((tokens) => tokens.length > 0);
|
|
47
|
+
}
|
|
48
|
+
function tokensForTerm(token) {
|
|
49
|
+
if (/^\d{4}-\d{2}-\d{2}$/u.test(token))
|
|
50
|
+
return token.split("-");
|
|
51
|
+
if (/^\d+(?:\.\d+)+$/u.test(token))
|
|
52
|
+
return [token];
|
|
53
|
+
const tokens = [];
|
|
54
|
+
const cjkTokens = cjkNgramTokens(token);
|
|
55
|
+
tokens.push(...cjkTokens);
|
|
56
|
+
const nonCjkText = token.replace(cjkRunPattern, " ");
|
|
57
|
+
tokens.push(...nonCjkText
|
|
58
|
+
.match(/[\p{L}\p{N}_]+/gu)
|
|
59
|
+
?.flatMap((part) => part.split("_")) ?? []);
|
|
60
|
+
if (!cjkTokens.length) {
|
|
61
|
+
tokens.push(...token.split("_"));
|
|
62
|
+
}
|
|
63
|
+
const unique = [...new Set(tokens
|
|
64
|
+
.map(escapeFtsToken)
|
|
65
|
+
.filter((token) => token.length > 1)
|
|
66
|
+
.filter((token) => !isFtsOperatorToken(token)))];
|
|
67
|
+
const ascii = unique.filter((part) => /^[a-z0-9_]+$/u.test(part));
|
|
68
|
+
const cjk = unique.filter((part) => !/^[a-z0-9_]+$/u.test(part));
|
|
69
|
+
const alternating = [];
|
|
70
|
+
const bySize = [2, 3].map((size) => cjk.filter((part) => Array.from(part).length === size));
|
|
71
|
+
const longest = Math.max(...bySize.map((parts) => parts.length), 0);
|
|
72
|
+
for (let offset = 0; offset < longest; offset += 1) {
|
|
73
|
+
for (const parts of bySize) {
|
|
74
|
+
const index = offset % 2 === 0 ? Math.floor(offset / 2) : parts.length - 1 - Math.floor(offset / 2);
|
|
75
|
+
if (offset < parts.length)
|
|
76
|
+
alternating.push(parts[index]);
|
|
22
77
|
}
|
|
23
78
|
}
|
|
24
|
-
return
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
79
|
+
return [...ascii, ...alternating];
|
|
80
|
+
}
|
|
81
|
+
function isAsciiGroup(tokens) {
|
|
82
|
+
return tokens.some((token) => /^[a-z0-9_.]+$/u.test(token));
|
|
28
83
|
}
|
|
29
84
|
function cjkNgramTokens(content) {
|
|
30
85
|
const tokens = [];
|
|
@@ -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,6 +1,11 @@
|
|
|
1
1
|
import chokidar from "chokidar";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { loadConfig } from "../config/load-config.js";
|
|
5
|
+
import { openExistingDatabase } from "../db/connection.js";
|
|
6
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
7
|
+
import { contentHash } from "../utils/id.js";
|
|
8
|
+
import { relativeUnixPath } from "../utils/text.js";
|
|
4
9
|
import { indexProject } from "../indexer.js";
|
|
5
10
|
import { resolveIgnorePatterns } from "../scanner/file-scanner.js";
|
|
6
11
|
import { WatchHealthTracker } from "./watch-health.js";
|
|
@@ -18,7 +23,6 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
18
23
|
health.close();
|
|
19
24
|
throw error;
|
|
20
25
|
}
|
|
21
|
-
const watchesMdx = config.index.parseMdx;
|
|
22
26
|
const debounceMs = options.debounceMs ?? 250;
|
|
23
27
|
let timer;
|
|
24
28
|
let running = false;
|
|
@@ -26,6 +30,9 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
26
30
|
let closed = false;
|
|
27
31
|
let ready = false;
|
|
28
32
|
let activeIndex;
|
|
33
|
+
let reloadInFlight;
|
|
34
|
+
let reloadQueued = false;
|
|
35
|
+
let indexedDocuments = new Map();
|
|
29
36
|
const runIndex = async () => {
|
|
30
37
|
if (closed) {
|
|
31
38
|
return;
|
|
@@ -39,6 +46,19 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
39
46
|
activeIndex = (async () => {
|
|
40
47
|
try {
|
|
41
48
|
const result = await indexProject(projectRoot, { semantic: options.semantic });
|
|
49
|
+
try {
|
|
50
|
+
const db = openExistingDatabase(projectRoot);
|
|
51
|
+
try {
|
|
52
|
+
indexedDocuments = new GraphRepository(db).documentHashes();
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
db.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Keep events eligible for indexing when the hash snapshot is unavailable.
|
|
60
|
+
indexedDocuments.clear();
|
|
61
|
+
}
|
|
42
62
|
health.recordIndexSuccess();
|
|
43
63
|
notifyIndexed(options.onIndexed, result);
|
|
44
64
|
}
|
|
@@ -69,22 +89,103 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
69
89
|
void runIndex();
|
|
70
90
|
}, debounceMs);
|
|
71
91
|
};
|
|
72
|
-
const scheduleIndexForMarkdown = (filePath) => {
|
|
92
|
+
const scheduleIndexForMarkdown = (filePath, event) => {
|
|
73
93
|
const lower = filePath.toLowerCase();
|
|
74
|
-
if (lower.endsWith(".md") || (
|
|
94
|
+
if (lower.endsWith(".md") || (config.index.parseMdx && lower.endsWith(".mdx"))) {
|
|
95
|
+
const absolutePath = path.resolve(projectRoot, filePath);
|
|
96
|
+
const indexed = indexedDocuments.get(relativeUnixPath(projectRoot, absolutePath));
|
|
97
|
+
if (event === "change" && indexed) {
|
|
98
|
+
try {
|
|
99
|
+
// Native watch can report a file read as a change; indexed content decides.
|
|
100
|
+
if (statSync(absolutePath).size <= config.index.maxFileBytes
|
|
101
|
+
&& contentHash(readFileSync(absolutePath, "utf8")) === indexed.hash)
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Let indexing diagnose unreadable or concurrently removed documents.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
75
108
|
scheduleIndex();
|
|
76
109
|
}
|
|
77
110
|
};
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
111
|
+
const bindWatcher = (candidate) => {
|
|
112
|
+
const onFileEvent = async (event, filePath) => {
|
|
113
|
+
if (isWatchControlFile(projectRoot, filePath)) {
|
|
114
|
+
void reloadWatchRules();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (activeIndex)
|
|
118
|
+
await activeIndex;
|
|
119
|
+
if (!closed)
|
|
120
|
+
scheduleIndexForMarkdown(filePath, event);
|
|
121
|
+
};
|
|
122
|
+
candidate.on("add", (filePath) => onFileEvent("add", filePath));
|
|
123
|
+
candidate.on("change", (filePath) => onFileEvent("change", filePath));
|
|
124
|
+
candidate.on("unlink", (filePath) => onFileEvent("unlink", filePath));
|
|
125
|
+
candidate.on("error", (error) => {
|
|
126
|
+
if (!ready)
|
|
127
|
+
return;
|
|
128
|
+
health.recordError(error, "runtime");
|
|
129
|
+
notifyError(options.onError, error);
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
const createWatcher = (nextConfig, nextIgnored) => {
|
|
133
|
+
const candidate = chokidar.watch(".", {
|
|
81
134
|
cwd: projectRoot,
|
|
82
|
-
ignored: createWatchIgnoreMatcher(projectRoot,
|
|
135
|
+
ignored: createWatchIgnoreMatcher(projectRoot, nextIgnored, nextConfig.index.parseMdx),
|
|
83
136
|
ignoreInitial: true,
|
|
84
137
|
persistent: true,
|
|
85
138
|
usePolling: options.usePolling ?? false,
|
|
86
139
|
awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
|
|
87
140
|
});
|
|
141
|
+
bindWatcher(candidate);
|
|
142
|
+
return candidate;
|
|
143
|
+
};
|
|
144
|
+
let watcher;
|
|
145
|
+
const reloadWatchRules = async () => {
|
|
146
|
+
if (reloadInFlight) {
|
|
147
|
+
reloadQueued = true;
|
|
148
|
+
return reloadInFlight;
|
|
149
|
+
}
|
|
150
|
+
reloadInFlight = (async () => {
|
|
151
|
+
let replacement;
|
|
152
|
+
try {
|
|
153
|
+
const nextConfig = loadConfig(projectRoot);
|
|
154
|
+
const nextIgnored = await resolveIgnorePatterns(projectRoot, nextConfig);
|
|
155
|
+
replacement = createWatcher(nextConfig, nextIgnored);
|
|
156
|
+
await waitForReady(replacement);
|
|
157
|
+
if (closed) {
|
|
158
|
+
await replacement.close();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const previous = watcher;
|
|
162
|
+
// Keep the previous watch registered until this one is ready. Events in
|
|
163
|
+
// the overlap simply coalesce through the existing debounce queue.
|
|
164
|
+
watcher = replacement;
|
|
165
|
+
config = nextConfig;
|
|
166
|
+
ignored = nextIgnored;
|
|
167
|
+
await previous.close();
|
|
168
|
+
scheduleIndex();
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
await replacement?.close();
|
|
172
|
+
// Invalid transient config must not drop the current watcher. A later
|
|
173
|
+
// valid write will retry this path and index success restores health.
|
|
174
|
+
health.recordError(error, "indexing");
|
|
175
|
+
notifyError(options.onError, error);
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
reloadInFlight = undefined;
|
|
179
|
+
if (reloadQueued && !closed) {
|
|
180
|
+
reloadQueued = false;
|
|
181
|
+
void reloadWatchRules();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
})();
|
|
185
|
+
return reloadInFlight;
|
|
186
|
+
};
|
|
187
|
+
try {
|
|
188
|
+
watcher = createWatcher(config, ignored);
|
|
88
189
|
}
|
|
89
190
|
catch (error) {
|
|
90
191
|
health.recordError(error, "startup");
|
|
@@ -92,16 +193,6 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
92
193
|
health.close();
|
|
93
194
|
throw error;
|
|
94
195
|
}
|
|
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
196
|
try {
|
|
106
197
|
await waitForReady(watcher);
|
|
107
198
|
ready = true;
|
|
@@ -128,6 +219,9 @@ export async function watchProject(projectRoot, options = {}) {
|
|
|
128
219
|
if (activeIndex) {
|
|
129
220
|
await activeIndex;
|
|
130
221
|
}
|
|
222
|
+
if (reloadInFlight) {
|
|
223
|
+
await reloadInFlight;
|
|
224
|
+
}
|
|
131
225
|
}
|
|
132
226
|
finally {
|
|
133
227
|
await watcher.close();
|
|
@@ -145,6 +239,11 @@ function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
|
|
|
145
239
|
return false;
|
|
146
240
|
}
|
|
147
241
|
const normalizedPath = relativePath.split(path.sep).join("/");
|
|
242
|
+
// Keep the directory traversable so chokidar can observe config.json even
|
|
243
|
+
// though normal MDGraph artifacts remain ignored below it.
|
|
244
|
+
if (normalizedPath === ".mdgraph" || isWatchControlFile(projectRoot, absolutePath)) {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
148
247
|
if (patterns.some((pattern) => (path.matchesGlob(normalizedPath, pattern)
|
|
149
248
|
|| path.matchesGlob(`${normalizedPath}/`, pattern)))) {
|
|
150
249
|
return true;
|
|
@@ -156,6 +255,11 @@ function createWatchIgnoreMatcher(projectRoot, patterns, watchesMdx) {
|
|
|
156
255
|
return false;
|
|
157
256
|
};
|
|
158
257
|
}
|
|
258
|
+
function isWatchControlFile(projectRoot, candidatePath) {
|
|
259
|
+
const absolutePath = path.isAbsolute(candidatePath) ? candidatePath : path.resolve(projectRoot, candidatePath);
|
|
260
|
+
const relativePath = path.relative(projectRoot, absolutePath).split(path.sep).join("/");
|
|
261
|
+
return relativePath === ".gitignore" || relativePath === ".mdgraph/config.json";
|
|
262
|
+
}
|
|
159
263
|
function notifyIndexed(onIndexed, result) {
|
|
160
264
|
try {
|
|
161
265
|
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
|
+
];
|