@daogee/mdgraph 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README-ZH.md +66 -4
- package/README.md +84 -22
- package/agent-pack/README.md +2 -0
- package/agent-pack/mdgraph-agent-instructions.md +3 -1
- package/agent-pack/prompts/wiki-authoring.md +12 -0
- package/agent-pack/skills/wiki-authoring/SKILL.md +38 -0
- package/agent-pack/skills/wiki-authoring/agents/openai.yaml +4 -0
- package/dist/analysis/status-freshness.d.ts +8 -1
- package/dist/analysis/status-freshness.js +19 -6
- package/dist/bin/mdgraph.js +260 -25
- package/dist/config/limits.d.ts +2 -0
- package/dist/config/limits.js +3 -1
- package/dist/config/load-config.js +8 -2
- package/dist/db/connection.js +17 -1
- package/dist/db/repositories.d.ts +55 -4
- package/dist/db/repositories.js +458 -11
- package/dist/db/sqlite-adapter.js +8 -2
- package/dist/evaluation/context-packing-evaluation.d.ts +29 -0
- package/dist/evaluation/context-packing-evaluation.js +134 -0
- package/dist/evaluation/entity-extraction-evaluation.d.ts +38 -0
- package/dist/evaluation/entity-extraction-evaluation.js +118 -0
- package/dist/evaluation/historical-baseline.d.ts +70 -0
- package/dist/evaluation/historical-baseline.js +278 -0
- package/dist/evaluation/related-documents-evaluation.d.ts +26 -0
- package/dist/evaluation/related-documents-evaluation.js +163 -0
- package/dist/evaluation/retrieval-eval.d.ts +25 -5
- package/dist/evaluation/retrieval-eval.js +79 -7
- package/dist/evaluation/structured-query-evaluation.d.ts +27 -0
- package/dist/evaluation/structured-query-evaluation.js +156 -0
- package/dist/extraction/entity-extractor.js +42 -22
- package/dist/extraction/graph-builder.js +2 -18
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -4
- package/dist/indexer.js +80 -4
- package/dist/mcp/server.d.ts +4 -0
- package/dist/mcp/server.js +21 -11
- package/dist/mcp/tools.d.ts +5 -1
- package/dist/mcp/tools.js +116 -18
- package/dist/parser/markdown-parser.js +2 -0
- package/dist/query/context-builder.d.ts +32 -2
- package/dist/query/context-builder.js +191 -12
- package/dist/query/knowledge-card.d.ts +90 -0
- package/dist/query/knowledge-card.js +676 -0
- package/dist/query/search.d.ts +5 -1
- package/dist/query/search.js +85 -16
- package/dist/query/structured-query-executor.d.ts +28 -0
- package/dist/query/structured-query-executor.js +138 -0
- package/dist/query/structured-query.d.ts +50 -0
- package/dist/query/structured-query.js +390 -0
- package/dist/relationships/derive-related.d.ts +86 -0
- package/dist/relationships/derive-related.js +322 -0
- package/dist/reporting/report.js +2 -2
- package/dist/semantic/embed-chunks.d.ts +2 -0
- package/dist/semantic/embed-chunks.js +31 -0
- package/dist/semantic/ollama-provider.d.ts +6 -0
- package/dist/semantic/ollama-provider.js +136 -0
- package/dist/semantic/provider-registry.d.ts +8 -0
- package/dist/semantic/provider-registry.js +66 -0
- package/dist/semantic/provider.d.ts +35 -0
- package/dist/semantic/provider.js +29 -0
- package/dist/semantic/status.d.ts +6 -1
- package/dist/semantic/status.js +49 -3
- package/dist/types.d.ts +7 -2
- package/dist/types.js +2 -1
- package/dist/utils/path-safety.d.ts +3 -0
- package/dist/utils/path-safety.js +27 -0
- package/dist/watcher/file-watcher.d.ts +4 -0
- package/dist/watcher/file-watcher.js +151 -17
- package/dist/watcher/watch-health.d.ts +34 -0
- package/dist/watcher/watch-health.js +75 -0
- package/dist/wiki/wiki-dependencies.d.ts +20 -0
- package/dist/wiki/wiki-dependencies.js +45 -0
- package/dist/wiki/wiki-domains.d.ts +13 -0
- package/dist/wiki/wiki-domains.js +55 -0
- package/dist/wiki/wiki-evidence.d.ts +27 -0
- package/dist/wiki/wiki-evidence.js +112 -0
- package/dist/wiki/wiki-plan.d.ts +121 -0
- package/dist/wiki/wiki-plan.js +616 -0
- package/dist/wiki/wiki-status.d.ts +67 -0
- package/dist/wiki/wiki-status.js +451 -0
- package/docs/EN/Agent_Integration.md +15 -5
- package/docs/EN/Architecture.md +52 -16
- package/docs/EN/Evaluation_Questions.md +35 -5
- package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
- package/docs/EN/Operations.md +111 -0
- package/docs/EN/Output_Contracts.md +83 -10
- package/docs/EN/Public_Contracts.md +25 -16
- package/docs/EN/Public_Contracts_1.0.md +32 -18
- package/docs/EN/README.md +24 -0
- package/docs/EN/Release_Checklist.md +27 -13
- package/docs/EN/Retrieval_and_Context.md +118 -0
- package/docs/EN/Structured_Query_and_Relationships.md +111 -0
- package/docs/ZH/Agent_Integration.md +15 -5
- package/docs/ZH/Architecture.md +52 -21
- package/docs/ZH/Evaluation_Questions.md +36 -6
- package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
- package/docs/ZH/Operations.md +111 -0
- package/docs/ZH/Output_Contracts.md +83 -10
- package/docs/ZH/Public_Contracts.md +24 -15
- package/docs/ZH/Public_Contracts_1.0.md +31 -17
- package/docs/ZH/README.md +24 -0
- package/docs/ZH/Release_Checklist.md +27 -13
- package/docs/ZH/Retrieval_and_Context.md +118 -0
- package/docs/ZH/Structured_Query_and_Relationships.md +111 -0
- package/package.json +50 -19
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
export const DEFAULT_KNOWLEDGE_CARD_LIMITS = {
|
|
2
|
+
definitions: 8,
|
|
3
|
+
sourceRefs: 8,
|
|
4
|
+
relatedDocuments: 8,
|
|
5
|
+
evidence: 12,
|
|
6
|
+
nextReads: 6,
|
|
7
|
+
maxChars: 4_000
|
|
8
|
+
};
|
|
9
|
+
export function createKnowledgeCardBuilder(repository, options = {}) {
|
|
10
|
+
const limits = knowledgeCardLimits(options);
|
|
11
|
+
const documents = repository.allDocuments();
|
|
12
|
+
const sections = repository.allSections();
|
|
13
|
+
const entities = repository.allEntities();
|
|
14
|
+
const sourceRefs = repository.allSourceRefs();
|
|
15
|
+
const edges = repository.allEdges().sort(compareEdges);
|
|
16
|
+
const nodes = structuralNodeMap(documents, sections, entities, sourceRefs);
|
|
17
|
+
const sectionsByDocument = groupSectionsByDocument(sections);
|
|
18
|
+
const edgesByNode = groupEdgesByNode(edges);
|
|
19
|
+
return {
|
|
20
|
+
build(nodeOrId) {
|
|
21
|
+
const node = typeof nodeOrId === "string" ? nodes.get(nodeOrId) : nodeOrId;
|
|
22
|
+
if (!node || node.kind === "chunk") {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
const scopeIds = cardScopeIds(node, sectionsByDocument);
|
|
26
|
+
const directEdges = edgesForScope(scopeIds, edgesByNode);
|
|
27
|
+
const facts = collectCardFacts(node, directEdges, nodes, sectionsByDocument, edgesByNode);
|
|
28
|
+
const summary = cardSummary(node, facts, nodes);
|
|
29
|
+
return fitCardToLimits({
|
|
30
|
+
nodeId: node.id,
|
|
31
|
+
kind: node.kind,
|
|
32
|
+
label: node.label,
|
|
33
|
+
summary,
|
|
34
|
+
definitions: facts.definitions,
|
|
35
|
+
sourceRefs: facts.sourceRefs,
|
|
36
|
+
relatedDocuments: facts.relatedDocuments,
|
|
37
|
+
evidence: facts.evidence,
|
|
38
|
+
nextReads: facts.nextReads
|
|
39
|
+
}, limits);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function buildKnowledgeCard(repository, nodeOrId, options = {}) {
|
|
44
|
+
return createKnowledgeCardBuilder(repository, options).build(nodeOrId);
|
|
45
|
+
}
|
|
46
|
+
export function formatKnowledgeCard(card) {
|
|
47
|
+
const sections = [
|
|
48
|
+
"Knowledge Card (experimental)",
|
|
49
|
+
`Summary: ${card.summary}`,
|
|
50
|
+
formatReferenceList("Definitions", card.definitions),
|
|
51
|
+
formatSourceReferenceList(card.sourceRefs),
|
|
52
|
+
formatReferenceList("Related documents", card.relatedDocuments),
|
|
53
|
+
formatEvidenceList(card.evidence),
|
|
54
|
+
formatNextReadList(card.nextReads ?? [])
|
|
55
|
+
];
|
|
56
|
+
const truncated = card.truncated
|
|
57
|
+
? Object.entries(card.truncated).map(([field, count]) => `${field}: ${count}`).join(", ")
|
|
58
|
+
: "";
|
|
59
|
+
if (truncated) {
|
|
60
|
+
sections.push(`Truncated: ${truncated}`);
|
|
61
|
+
}
|
|
62
|
+
return sections.join("\n\n");
|
|
63
|
+
}
|
|
64
|
+
function collectCardFacts(node, directEdges, nodes, sectionsByDocument, edgesByNode) {
|
|
65
|
+
const definitions = definitionReferences(node, directEdges, nodes);
|
|
66
|
+
const relatedDocumentIds = relatedDocumentsForNode(node, directEdges, nodes);
|
|
67
|
+
const sourceRefEdges = node.kind === "entity"
|
|
68
|
+
? sourceRefEdgesForDocuments(relatedDocumentIds, sectionsByDocument, edgesByNode, nodes)
|
|
69
|
+
: directEdges;
|
|
70
|
+
const sourceReferences = sourceReferencesFromEdges(sourceRefEdges, nodes, node, directEdges);
|
|
71
|
+
const relatedDocuments = [...relatedDocumentIds]
|
|
72
|
+
.flatMap((documentId) => {
|
|
73
|
+
const document = nodes.get(documentId);
|
|
74
|
+
return document?.kind === "document" ? [referenceForNode(document, undefined, nodes, {
|
|
75
|
+
association: node.kind === "section" && document.id === node.data.documentId ? "inherited" : "related",
|
|
76
|
+
originNodeId: document.id
|
|
77
|
+
})] : [];
|
|
78
|
+
})
|
|
79
|
+
.sort(compareReferences);
|
|
80
|
+
const evidence = directEdges
|
|
81
|
+
.filter((edge) => edge.kind !== "CONTAINS")
|
|
82
|
+
.flatMap((edge) => evidenceForEdge(edge, nodes, associationForEdge(node, edge, nodes)))
|
|
83
|
+
.sort(compareEvidence);
|
|
84
|
+
const nextReads = nextReadsForFacts(node, definitions, sourceReferences, relatedDocuments, evidence, nodes);
|
|
85
|
+
return {
|
|
86
|
+
definitions: dedupeReferences(definitions).sort(compareReferences),
|
|
87
|
+
sourceRefs: dedupeSourceReferences(sourceReferences).sort(compareSourceReferences),
|
|
88
|
+
relatedDocuments,
|
|
89
|
+
evidence,
|
|
90
|
+
nextReads
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function definitionReferences(node, edges, nodes) {
|
|
94
|
+
const definitions = [];
|
|
95
|
+
for (const edge of edges) {
|
|
96
|
+
if (edge.kind !== "DEFINES") {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (node.kind === "entity") {
|
|
100
|
+
if (edge.toId !== node.id) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const location = nodes.get(edge.fromId);
|
|
104
|
+
if (location && location.kind !== "chunk") {
|
|
105
|
+
definitions.push(referenceForNode(location, edge, nodes, associationForEdge(node, edge, nodes)));
|
|
106
|
+
}
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const entity = nodes.get(edge.toId);
|
|
110
|
+
if (entity?.kind === "entity") {
|
|
111
|
+
definitions.push(referenceForNode(entity, edge, nodes, associationForEdge(node, edge, nodes)));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return definitions;
|
|
115
|
+
}
|
|
116
|
+
function relatedDocumentsForNode(node, edges, nodes) {
|
|
117
|
+
const documentIds = new Set();
|
|
118
|
+
if (node.kind === "section") {
|
|
119
|
+
documentIds.add(node.data.documentId);
|
|
120
|
+
}
|
|
121
|
+
for (const edge of edges) {
|
|
122
|
+
for (const endpointId of [edge.fromId, edge.toId]) {
|
|
123
|
+
const documentId = owningDocumentId(nodes.get(endpointId));
|
|
124
|
+
if (documentId) {
|
|
125
|
+
documentIds.add(documentId);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (node.kind === "document") {
|
|
130
|
+
documentIds.delete(node.id);
|
|
131
|
+
}
|
|
132
|
+
return documentIds;
|
|
133
|
+
}
|
|
134
|
+
function sourceRefEdgesForDocuments(documentIds, sectionsByDocument, edgesByNode, nodes) {
|
|
135
|
+
const scopeIds = [...documentIds].flatMap((documentId) => [
|
|
136
|
+
documentId,
|
|
137
|
+
...(sectionsByDocument.get(documentId) ?? []).map((section) => section.id)
|
|
138
|
+
]);
|
|
139
|
+
return edgesForScope(scopeIds, edgesByNode).filter((edge) => {
|
|
140
|
+
if (edge.kind !== "IMPLEMENTS" && edge.kind !== "REFERENCES_SOURCE") {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
return nodes.get(edge.fromId)?.kind === "source_ref" || nodes.get(edge.toId)?.kind === "source_ref";
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function sourceReferencesFromEdges(edges, nodes, cardNode, directEdges) {
|
|
147
|
+
const references = [];
|
|
148
|
+
for (const edge of edges) {
|
|
149
|
+
if (edge.kind !== "IMPLEMENTS" && edge.kind !== "REFERENCES_SOURCE") {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const sourceNode = nodes.get(edge.fromId)?.kind === "source_ref"
|
|
153
|
+
? nodes.get(edge.fromId)
|
|
154
|
+
: nodes.get(edge.toId)?.kind === "source_ref"
|
|
155
|
+
? nodes.get(edge.toId)
|
|
156
|
+
: undefined;
|
|
157
|
+
if (sourceNode?.kind !== "source_ref") {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
references.push({
|
|
161
|
+
nodeId: sourceNode.id,
|
|
162
|
+
path: sourceNode.data.path,
|
|
163
|
+
edgeKind: edge.kind,
|
|
164
|
+
provenance: edge.provenance,
|
|
165
|
+
confidence: edge.confidence,
|
|
166
|
+
...associationForSourceRef(cardNode, edge, nodes, directEdges)
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return references;
|
|
170
|
+
}
|
|
171
|
+
function cardSummary(node, facts, nodes) {
|
|
172
|
+
switch (node.kind) {
|
|
173
|
+
case "document": {
|
|
174
|
+
const document = node.data;
|
|
175
|
+
const direct = facts.evidence.find((fact) => fact.association === "direct" && fact.edgeKind !== "CONTAINS");
|
|
176
|
+
return direct
|
|
177
|
+
? `${document.path} (${document.type}, ${document.status}) directly ${edgeSummaryVerb(direct.edgeKind)} ${direct.toLabel} via ${direct.provenance}.`
|
|
178
|
+
: `${document.path} (${document.type}, ${document.status}) is located at the document root; section facts retain their section origins.`;
|
|
179
|
+
}
|
|
180
|
+
case "section": {
|
|
181
|
+
const section = node.data;
|
|
182
|
+
const document = nodes.get(section.documentId);
|
|
183
|
+
const path = document?.kind === "document" ? document.data.path : section.documentId;
|
|
184
|
+
const direct = facts.evidence.find((fact) => fact.association === "direct" && fact.edgeKind !== "CONTAINS");
|
|
185
|
+
return direct
|
|
186
|
+
? `${path}#${section.anchor} at lines ${section.startLine}-${section.endLine} directly ${edgeSummaryVerb(direct.edgeKind)} ${direct.toLabel} via ${direct.provenance}; document-frontmatter facts are marked inherited.`
|
|
187
|
+
: `${path}#${section.anchor} at lines ${section.startLine}-${section.endLine}; document-frontmatter facts are marked inherited.`;
|
|
188
|
+
}
|
|
189
|
+
case "entity": {
|
|
190
|
+
const entity = node.data;
|
|
191
|
+
const definition = facts.definitions.find((fact) => fact.association === "direct");
|
|
192
|
+
return definition
|
|
193
|
+
? `${entity.name} (${entity.kind}) is directly defined at ${referenceLocation(definition)} via ${definition.provenance}.`
|
|
194
|
+
: `${entity.name} (${entity.kind}) has no direct definition edge; related source references are graph background, not implementation proof.`;
|
|
195
|
+
}
|
|
196
|
+
case "source_ref": {
|
|
197
|
+
const sourceRef = node.data;
|
|
198
|
+
const direct = facts.evidence.find((fact) => fact.association === "direct" && fact.edgeKind !== "CONTAINS");
|
|
199
|
+
return direct
|
|
200
|
+
? `${sourceRef.path} is directly linked to ${direct.fromLabel} by ${direct.edgeKind}/${direct.provenance}.`
|
|
201
|
+
: `${sourceRef.path} is a source reference represented by the current graph.`;
|
|
202
|
+
}
|
|
203
|
+
default:
|
|
204
|
+
return `${node.label} is represented by the current graph.`;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function fitCardToLimits(card, limits) {
|
|
208
|
+
const minimum = minimumCard(card);
|
|
209
|
+
const minimumChars = serializedCardLength(minimum);
|
|
210
|
+
if (minimumChars > limits.maxChars) {
|
|
211
|
+
throw new RangeError(`Knowledge card budget ${limits.maxChars} is below the minimum representable card size ${minimumChars}.`);
|
|
212
|
+
}
|
|
213
|
+
const truncated = {};
|
|
214
|
+
const fitted = {
|
|
215
|
+
...card,
|
|
216
|
+
definitions: takeWithOmitted(card.definitions, limits.definitions, "definitions", truncated),
|
|
217
|
+
sourceRefs: takeWithOmitted(card.sourceRefs, limits.sourceRefs, "sourceRefs", truncated),
|
|
218
|
+
relatedDocuments: takeWithOmitted(card.relatedDocuments, limits.relatedDocuments, "relatedDocuments", truncated),
|
|
219
|
+
evidence: takeWithOmitted(card.evidence, limits.evidence, "evidence", truncated),
|
|
220
|
+
nextReads: takeWithOmitted(card.nextReads ?? [], limits.nextReads, "nextReads", truncated)
|
|
221
|
+
};
|
|
222
|
+
if (Object.keys(truncated).length) {
|
|
223
|
+
fitted.truncated = truncated;
|
|
224
|
+
}
|
|
225
|
+
while (serializedCardLength(fitted) > limits.maxChars) {
|
|
226
|
+
const field = removeLowestPriorityFact(fitted);
|
|
227
|
+
if (!field) {
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
fitted.truncated ??= {};
|
|
231
|
+
fitted.truncated[field] = (fitted.truncated[field] ?? 0) + 1;
|
|
232
|
+
}
|
|
233
|
+
return fitCardTextToBudget(fitted, limits.maxChars);
|
|
234
|
+
}
|
|
235
|
+
function removeLowestPriorityFact(card) {
|
|
236
|
+
const remove = (field, predicate) => {
|
|
237
|
+
const values = card[field];
|
|
238
|
+
const index = predicate ? lastMatchingIndex(values, predicate) : values.length - 1;
|
|
239
|
+
if (index < 0) {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
values.splice(index, 1);
|
|
243
|
+
return true;
|
|
244
|
+
};
|
|
245
|
+
if (remove("relatedDocuments"))
|
|
246
|
+
return "relatedDocuments";
|
|
247
|
+
if (remove("sourceRefs", (item) => item.association !== "direct"))
|
|
248
|
+
return "sourceRefs";
|
|
249
|
+
if (remove("evidence", (item) => item.association !== "direct"))
|
|
250
|
+
return "evidence";
|
|
251
|
+
if (remove("definitions", (item) => item.association !== "direct"))
|
|
252
|
+
return "definitions";
|
|
253
|
+
if (remove("nextReads"))
|
|
254
|
+
return "nextReads";
|
|
255
|
+
if (remove("evidence"))
|
|
256
|
+
return "evidence";
|
|
257
|
+
if (remove("sourceRefs"))
|
|
258
|
+
return "sourceRefs";
|
|
259
|
+
if (remove("definitions"))
|
|
260
|
+
return "definitions";
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
function lastMatchingIndex(values, predicate) {
|
|
264
|
+
for (let index = values.length - 1; index >= 0; index -= 1) {
|
|
265
|
+
if (predicate(values[index])) {
|
|
266
|
+
return index;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return -1;
|
|
270
|
+
}
|
|
271
|
+
function minimumCard(card) {
|
|
272
|
+
const minimum = {
|
|
273
|
+
nodeId: card.nodeId,
|
|
274
|
+
kind: card.kind,
|
|
275
|
+
label: "",
|
|
276
|
+
summary: "",
|
|
277
|
+
definitions: [],
|
|
278
|
+
sourceRefs: [],
|
|
279
|
+
relatedDocuments: [],
|
|
280
|
+
evidence: [],
|
|
281
|
+
nextReads: []
|
|
282
|
+
};
|
|
283
|
+
if (card.truncated) {
|
|
284
|
+
minimum.truncated = card.truncated;
|
|
285
|
+
}
|
|
286
|
+
return minimum;
|
|
287
|
+
}
|
|
288
|
+
function serializedCardLength(card) {
|
|
289
|
+
return JSON.stringify(card).length;
|
|
290
|
+
}
|
|
291
|
+
function fitCardTextToBudget(card, maxChars) {
|
|
292
|
+
const minimumChars = serializedCardLength(minimumCard(card));
|
|
293
|
+
if (minimumChars > maxChars) {
|
|
294
|
+
throw new RangeError(`Knowledge card budget ${maxChars} cannot represent required truncation metadata (${minimumChars} characters).`);
|
|
295
|
+
}
|
|
296
|
+
if (serializedCardLength(card) <= maxChars) {
|
|
297
|
+
return card;
|
|
298
|
+
}
|
|
299
|
+
const markerCard = {
|
|
300
|
+
...card,
|
|
301
|
+
label: card.label ? "…" : "",
|
|
302
|
+
summary: card.summary ? "…" : ""
|
|
303
|
+
};
|
|
304
|
+
if (serializedCardLength(markerCard) > maxChars) {
|
|
305
|
+
throw new RangeError(`Knowledge card budget ${maxChars} cannot represent required truncated text markers.`);
|
|
306
|
+
}
|
|
307
|
+
const withLabel = {
|
|
308
|
+
...markerCard,
|
|
309
|
+
label: longestPrefixWithinCardBudget(markerCard, "label", card.label, maxChars)
|
|
310
|
+
};
|
|
311
|
+
const fitted = {
|
|
312
|
+
...withLabel,
|
|
313
|
+
summary: longestPrefixWithinCardBudget(withLabel, "summary", card.summary, maxChars)
|
|
314
|
+
};
|
|
315
|
+
return fitted;
|
|
316
|
+
}
|
|
317
|
+
function longestPrefixWithinCardBudget(card, field, value, maxChars) {
|
|
318
|
+
if (serializedCardLength({ ...card, [field]: value }) <= maxChars) {
|
|
319
|
+
return value;
|
|
320
|
+
}
|
|
321
|
+
const codePoints = Array.from(value);
|
|
322
|
+
const marker = "…";
|
|
323
|
+
if (serializedCardLength({ ...card, [field]: marker }) > maxChars) {
|
|
324
|
+
throw new RangeError(`Knowledge card budget ${maxChars} cannot represent a truncated ${field} marker.`);
|
|
325
|
+
}
|
|
326
|
+
let lower = 0;
|
|
327
|
+
let upper = codePoints.length;
|
|
328
|
+
while (lower < upper) {
|
|
329
|
+
const middle = Math.ceil((lower + upper) / 2);
|
|
330
|
+
const candidate = { ...card, [field]: `${codePoints.slice(0, middle).join("")}${marker}` };
|
|
331
|
+
if (serializedCardLength(candidate) <= maxChars) {
|
|
332
|
+
lower = middle;
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
upper = middle - 1;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return `${codePoints.slice(0, lower).join("")}${marker}`;
|
|
339
|
+
}
|
|
340
|
+
function takeWithOmitted(values, limit, field, truncated) {
|
|
341
|
+
const selected = values.slice(0, limit);
|
|
342
|
+
const omitted = values.length - selected.length;
|
|
343
|
+
if (omitted > 0) {
|
|
344
|
+
truncated[field] = omitted;
|
|
345
|
+
}
|
|
346
|
+
return selected;
|
|
347
|
+
}
|
|
348
|
+
function knowledgeCardLimits(options) {
|
|
349
|
+
return {
|
|
350
|
+
definitions: nonNegativeIntegerOr(options.maxDefinitions, DEFAULT_KNOWLEDGE_CARD_LIMITS.definitions),
|
|
351
|
+
sourceRefs: nonNegativeIntegerOr(options.maxSourceRefs, DEFAULT_KNOWLEDGE_CARD_LIMITS.sourceRefs),
|
|
352
|
+
relatedDocuments: nonNegativeIntegerOr(options.maxRelatedDocuments, DEFAULT_KNOWLEDGE_CARD_LIMITS.relatedDocuments),
|
|
353
|
+
evidence: nonNegativeIntegerOr(options.maxEvidence, DEFAULT_KNOWLEDGE_CARD_LIMITS.evidence),
|
|
354
|
+
nextReads: nonNegativeIntegerOr(options.maxNextReads, DEFAULT_KNOWLEDGE_CARD_LIMITS.nextReads),
|
|
355
|
+
maxChars: positiveIntegerOr(options.maxChars, DEFAULT_KNOWLEDGE_CARD_LIMITS.maxChars)
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
function structuralNodeMap(documents, sections, entities, sourceRefs) {
|
|
359
|
+
const nodes = new Map();
|
|
360
|
+
for (const document of documents) {
|
|
361
|
+
nodes.set(document.id, { id: document.id, label: document.title, kind: "document", data: document });
|
|
362
|
+
}
|
|
363
|
+
for (const section of sections) {
|
|
364
|
+
nodes.set(section.id, { id: section.id, label: section.heading, kind: "section", data: section });
|
|
365
|
+
}
|
|
366
|
+
for (const entity of entities) {
|
|
367
|
+
nodes.set(entity.id, { id: entity.id, label: entity.name, kind: "entity", data: entity });
|
|
368
|
+
}
|
|
369
|
+
for (const sourceRef of sourceRefs) {
|
|
370
|
+
nodes.set(sourceRef.id, { id: sourceRef.id, label: sourceRef.path, kind: "source_ref", data: sourceRef });
|
|
371
|
+
}
|
|
372
|
+
return nodes;
|
|
373
|
+
}
|
|
374
|
+
function groupSectionsByDocument(sections) {
|
|
375
|
+
const grouped = new Map();
|
|
376
|
+
for (const section of sections) {
|
|
377
|
+
grouped.set(section.documentId, [...(grouped.get(section.documentId) ?? []), section]);
|
|
378
|
+
}
|
|
379
|
+
return grouped;
|
|
380
|
+
}
|
|
381
|
+
function groupEdgesByNode(edges) {
|
|
382
|
+
const grouped = new Map();
|
|
383
|
+
for (const edge of edges) {
|
|
384
|
+
grouped.set(edge.fromId, [...(grouped.get(edge.fromId) ?? []), edge]);
|
|
385
|
+
if (edge.toId !== edge.fromId) {
|
|
386
|
+
grouped.set(edge.toId, [...(grouped.get(edge.toId) ?? []), edge]);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return grouped;
|
|
390
|
+
}
|
|
391
|
+
function cardScopeIds(node, sectionsByDocument) {
|
|
392
|
+
if (node.kind === "document") {
|
|
393
|
+
return [node.id, ...(sectionsByDocument.get(node.id) ?? []).map((section) => section.id)];
|
|
394
|
+
}
|
|
395
|
+
if (node.kind === "section") {
|
|
396
|
+
return [node.id, node.data.documentId];
|
|
397
|
+
}
|
|
398
|
+
return [node.id];
|
|
399
|
+
}
|
|
400
|
+
function edgesForScope(scopeIds, edgesByNode) {
|
|
401
|
+
const edges = new Map();
|
|
402
|
+
for (const nodeId of scopeIds) {
|
|
403
|
+
for (const edge of edgesByNode.get(nodeId) ?? []) {
|
|
404
|
+
edges.set(edge.id, edge);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return [...edges.values()].sort(compareEdges);
|
|
408
|
+
}
|
|
409
|
+
function owningDocumentId(node) {
|
|
410
|
+
if (node?.kind === "document") {
|
|
411
|
+
return node.id;
|
|
412
|
+
}
|
|
413
|
+
if (node?.kind === "section") {
|
|
414
|
+
return node.data.documentId;
|
|
415
|
+
}
|
|
416
|
+
return undefined;
|
|
417
|
+
}
|
|
418
|
+
function referenceForNode(node, edge, nodes, association) {
|
|
419
|
+
const reference = {
|
|
420
|
+
nodeId: node.id,
|
|
421
|
+
kind: node.kind,
|
|
422
|
+
label: node.label
|
|
423
|
+
};
|
|
424
|
+
if (node.kind === "document") {
|
|
425
|
+
reference.path = node.data.path;
|
|
426
|
+
}
|
|
427
|
+
else if (node.kind === "section") {
|
|
428
|
+
const section = node.data;
|
|
429
|
+
const document = nodes?.get(section.documentId);
|
|
430
|
+
if (document?.kind === "document") {
|
|
431
|
+
reference.path = document.data.path;
|
|
432
|
+
}
|
|
433
|
+
reference.anchor = section.anchor;
|
|
434
|
+
reference.lines = { start: section.startLine, end: section.endLine };
|
|
435
|
+
}
|
|
436
|
+
else if (node.kind === "source_ref") {
|
|
437
|
+
reference.path = node.data.path;
|
|
438
|
+
}
|
|
439
|
+
if (edge) {
|
|
440
|
+
reference.edgeKind = edge.kind;
|
|
441
|
+
reference.provenance = edge.provenance;
|
|
442
|
+
reference.confidence = edge.confidence;
|
|
443
|
+
}
|
|
444
|
+
return { ...reference, ...association };
|
|
445
|
+
}
|
|
446
|
+
function evidenceForEdge(edge, nodes, association) {
|
|
447
|
+
const from = nodes.get(edge.fromId);
|
|
448
|
+
const to = nodes.get(edge.toId);
|
|
449
|
+
if (!from || !to || from.kind === "chunk" || to.kind === "chunk") {
|
|
450
|
+
return [];
|
|
451
|
+
}
|
|
452
|
+
return [{
|
|
453
|
+
edgeId: edge.id,
|
|
454
|
+
fromId: edge.fromId,
|
|
455
|
+
fromLabel: from.label,
|
|
456
|
+
toId: edge.toId,
|
|
457
|
+
toLabel: to.label,
|
|
458
|
+
edgeKind: edge.kind,
|
|
459
|
+
provenance: edge.provenance,
|
|
460
|
+
confidence: edge.confidence,
|
|
461
|
+
...association
|
|
462
|
+
}];
|
|
463
|
+
}
|
|
464
|
+
function associationForEdge(cardNode, edge, nodes) {
|
|
465
|
+
if (edge.fromId === cardNode.id || edge.toId === cardNode.id) {
|
|
466
|
+
return { association: "direct", originNodeId: cardNode.id };
|
|
467
|
+
}
|
|
468
|
+
if (cardNode.kind === "document") {
|
|
469
|
+
const section = [edge.fromId, edge.toId]
|
|
470
|
+
.map((id) => nodes.get(id))
|
|
471
|
+
.find((candidate) => candidate?.kind === "section" && candidate.data.documentId === cardNode.id);
|
|
472
|
+
if (section) {
|
|
473
|
+
return { association: "inherited", originNodeId: section.id, viaNodeId: section.id };
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (cardNode.kind === "section") {
|
|
477
|
+
const documentId = cardNode.data.documentId;
|
|
478
|
+
if (edge.fromId === documentId || edge.toId === documentId) {
|
|
479
|
+
return { association: "inherited", originNodeId: documentId, viaNodeId: documentId };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return { association: "related", originNodeId: edge.fromId, viaNodeId: edge.fromId };
|
|
483
|
+
}
|
|
484
|
+
function associationForSourceRef(cardNode, edge, nodes, directEdges) {
|
|
485
|
+
if (cardNode.kind !== "entity") {
|
|
486
|
+
return associationForEdge(cardNode, edge, nodes);
|
|
487
|
+
}
|
|
488
|
+
const document = [edge.fromId, edge.toId]
|
|
489
|
+
.map((id) => nodes.get(id))
|
|
490
|
+
.find((candidate) => candidate?.kind === "document");
|
|
491
|
+
const entityLink = document
|
|
492
|
+
? directEdges.find((candidate) => {
|
|
493
|
+
if (candidate.fromId === cardNode.id) {
|
|
494
|
+
return owningDocumentId(nodes.get(candidate.toId)) === document.id;
|
|
495
|
+
}
|
|
496
|
+
if (candidate.toId === cardNode.id) {
|
|
497
|
+
return owningDocumentId(nodes.get(candidate.fromId)) === document.id;
|
|
498
|
+
}
|
|
499
|
+
return false;
|
|
500
|
+
})
|
|
501
|
+
: undefined;
|
|
502
|
+
const viaNodeId = entityLink
|
|
503
|
+
? entityLink.fromId === cardNode.id ? entityLink.toId : entityLink.fromId
|
|
504
|
+
: undefined;
|
|
505
|
+
return {
|
|
506
|
+
association: "related",
|
|
507
|
+
originNodeId: document?.id ?? edge.fromId,
|
|
508
|
+
...(viaNodeId ? { viaNodeId } : {})
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
function nextReadsForFacts(node, definitions, sourceRefs, relatedDocuments, evidence, nodes) {
|
|
512
|
+
const nextReads = [];
|
|
513
|
+
for (const definition of definitions.filter((fact) => fact.nodeId !== node.id && Boolean(fact.path))) {
|
|
514
|
+
nextReads.push({ ...definition, reason: "Read the definition location recorded by the graph." });
|
|
515
|
+
}
|
|
516
|
+
for (const related of relatedDocuments.filter((fact) => fact.nodeId !== node.id && Boolean(fact.path))) {
|
|
517
|
+
nextReads.push({ ...related, reason: "Read the graph-linked document for relationship context." });
|
|
518
|
+
}
|
|
519
|
+
for (const source of sourceRefs) {
|
|
520
|
+
const sourceNode = nodes.get(source.nodeId);
|
|
521
|
+
if (sourceNode?.kind === "source_ref" && sourceNode.id !== node.id) {
|
|
522
|
+
nextReads.push({
|
|
523
|
+
...referenceForNode(sourceNode, undefined, nodes, source),
|
|
524
|
+
reason: source.association === "direct"
|
|
525
|
+
? "Inspect the source reference directly linked by this graph edge."
|
|
526
|
+
: "Inspect the source reference as related graph background; it is not direct implementation proof for this card."
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
for (const item of evidence.filter((fact) => fact.association === "direct")) {
|
|
531
|
+
const candidateId = item.fromId === node.id ? item.toId : item.fromId;
|
|
532
|
+
const candidate = nodes.get(candidateId);
|
|
533
|
+
if (candidate && candidate.kind !== "chunk" && candidate.id !== node.id) {
|
|
534
|
+
const reference = referenceForNode(candidate, undefined, nodes, item);
|
|
535
|
+
if (reference.path) {
|
|
536
|
+
nextReads.push({
|
|
537
|
+
...reference,
|
|
538
|
+
reason: `Follow the direct ${item.edgeKind}/${item.provenance} graph edge.`
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return dedupeNextReads(nextReads).sort(compareNextReads);
|
|
544
|
+
}
|
|
545
|
+
function dedupeNextReads(reads) {
|
|
546
|
+
const deduped = new Map();
|
|
547
|
+
for (const read of reads.filter((candidate) => Boolean(candidate.path))) {
|
|
548
|
+
const key = `${read.nodeId}:${read.association ?? ""}:${read.originNodeId ?? ""}:${read.viaNodeId ?? ""}`;
|
|
549
|
+
if (!deduped.has(key)) {
|
|
550
|
+
deduped.set(key, read);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return [...deduped.values()];
|
|
554
|
+
}
|
|
555
|
+
function compareNextReads(left, right) {
|
|
556
|
+
return associationPriority(left.association) - associationPriority(right.association)
|
|
557
|
+
|| compareReferences(left, right)
|
|
558
|
+
|| left.reason.localeCompare(right.reason);
|
|
559
|
+
}
|
|
560
|
+
function associationPriority(value) {
|
|
561
|
+
return value === "direct" ? 0 : value === "inherited" ? 1 : 2;
|
|
562
|
+
}
|
|
563
|
+
function edgeSummaryVerb(kind) {
|
|
564
|
+
return kind === "DEFINES" ? "defines" : kind.toLowerCase().replaceAll("_", " ");
|
|
565
|
+
}
|
|
566
|
+
function referenceLocation(reference) {
|
|
567
|
+
const location = reference.path ?? reference.nodeId;
|
|
568
|
+
return reference.anchor ? `${location}#${reference.anchor}` : location;
|
|
569
|
+
}
|
|
570
|
+
function dedupeReferences(references) {
|
|
571
|
+
const deduped = new Map();
|
|
572
|
+
for (const reference of references.sort(compareReferences)) {
|
|
573
|
+
const key = `${reference.nodeId}:${reference.association ?? ""}:${reference.originNodeId ?? ""}:${reference.viaNodeId ?? ""}`;
|
|
574
|
+
if (!deduped.has(key)) {
|
|
575
|
+
deduped.set(key, reference);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return [...deduped.values()];
|
|
579
|
+
}
|
|
580
|
+
function dedupeSourceReferences(references) {
|
|
581
|
+
const deduped = new Map();
|
|
582
|
+
for (const reference of references.sort(compareSourceReferences)) {
|
|
583
|
+
const key = `${reference.nodeId}:${reference.edgeKind}:${reference.association ?? ""}:${reference.originNodeId ?? ""}:${reference.viaNodeId ?? ""}`;
|
|
584
|
+
if (!deduped.has(key)) {
|
|
585
|
+
deduped.set(key, reference);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return [...deduped.values()];
|
|
589
|
+
}
|
|
590
|
+
function compareReferences(left, right) {
|
|
591
|
+
return associationPriority(left.association) - associationPriority(right.association)
|
|
592
|
+
|| (left.path ?? "").localeCompare(right.path ?? "")
|
|
593
|
+
|| (left.lines?.start ?? 0) - (right.lines?.start ?? 0)
|
|
594
|
+
|| left.label.localeCompare(right.label)
|
|
595
|
+
|| left.nodeId.localeCompare(right.nodeId);
|
|
596
|
+
}
|
|
597
|
+
function compareSourceReferences(left, right) {
|
|
598
|
+
return associationPriority(left.association) - associationPriority(right.association)
|
|
599
|
+
|| left.path.localeCompare(right.path)
|
|
600
|
+
|| left.edgeKind.localeCompare(right.edgeKind)
|
|
601
|
+
|| left.provenance.localeCompare(right.provenance)
|
|
602
|
+
|| left.nodeId.localeCompare(right.nodeId);
|
|
603
|
+
}
|
|
604
|
+
function compareEvidence(left, right) {
|
|
605
|
+
return associationPriority(left.association) - associationPriority(right.association)
|
|
606
|
+
|| edgeKindPriority(left.edgeKind) - edgeKindPriority(right.edgeKind)
|
|
607
|
+
|| left.fromLabel.localeCompare(right.fromLabel)
|
|
608
|
+
|| left.toLabel.localeCompare(right.toLabel)
|
|
609
|
+
|| left.edgeId.localeCompare(right.edgeId);
|
|
610
|
+
}
|
|
611
|
+
function compareEdges(left, right) {
|
|
612
|
+
return edgeKindPriority(left.kind) - edgeKindPriority(right.kind)
|
|
613
|
+
|| left.fromId.localeCompare(right.fromId)
|
|
614
|
+
|| left.toId.localeCompare(right.toId)
|
|
615
|
+
|| left.kind.localeCompare(right.kind)
|
|
616
|
+
|| left.provenance.localeCompare(right.provenance)
|
|
617
|
+
|| left.id.localeCompare(right.id);
|
|
618
|
+
}
|
|
619
|
+
function edgeKindPriority(kind) {
|
|
620
|
+
const order = [
|
|
621
|
+
"DEFINES",
|
|
622
|
+
"IMPLEMENTS",
|
|
623
|
+
"REFERENCES_SOURCE",
|
|
624
|
+
"DEPENDS_ON",
|
|
625
|
+
"SUPERSEDES",
|
|
626
|
+
"DEPRECATED_BY",
|
|
627
|
+
"LINKS_TO",
|
|
628
|
+
"REFERENCES",
|
|
629
|
+
"RELATED_TO",
|
|
630
|
+
"SAME_AS",
|
|
631
|
+
"CONTRADICTS",
|
|
632
|
+
"CONTAINS"
|
|
633
|
+
];
|
|
634
|
+
return order.indexOf(kind);
|
|
635
|
+
}
|
|
636
|
+
function formatReferenceList(title, references) {
|
|
637
|
+
if (!references.length) {
|
|
638
|
+
return `${title}: none`;
|
|
639
|
+
}
|
|
640
|
+
const lines = references.map((reference) => {
|
|
641
|
+
const location = reference.path
|
|
642
|
+
? ` (${reference.path})`
|
|
643
|
+
: reference.anchor
|
|
644
|
+
? ` (#${reference.anchor}${reference.lines ? `:${reference.lines.start}-${reference.lines.end}` : ""})`
|
|
645
|
+
: "";
|
|
646
|
+
const edge = reference.edgeKind
|
|
647
|
+
? ` [${reference.edgeKind}/${reference.provenance}, confidence ${reference.confidence}]`
|
|
648
|
+
: "";
|
|
649
|
+
return `- ${reference.label}${location}${edge} [${reference.nodeId}]`;
|
|
650
|
+
});
|
|
651
|
+
return `${title}:\n${lines.join("\n")}`;
|
|
652
|
+
}
|
|
653
|
+
function formatSourceReferenceList(references) {
|
|
654
|
+
if (!references.length) {
|
|
655
|
+
return "Source refs: none";
|
|
656
|
+
}
|
|
657
|
+
return `Source refs:\n${references.map((reference) => `- ${reference.path} [${reference.edgeKind}/${reference.provenance}, confidence ${reference.confidence}; ${reference.nodeId}]`).join("\n")}`;
|
|
658
|
+
}
|
|
659
|
+
function formatEvidenceList(evidence) {
|
|
660
|
+
if (!evidence.length) {
|
|
661
|
+
return "Evidence: none";
|
|
662
|
+
}
|
|
663
|
+
return `Evidence:\n${evidence.map((item) => `- ${item.fromLabel} --${item.edgeKind}/${item.provenance}, confidence ${item.confidence}--> ${item.toLabel} [${item.edgeId}]`).join("\n")}`;
|
|
664
|
+
}
|
|
665
|
+
function formatNextReadList(nextReads) {
|
|
666
|
+
if (!nextReads.length) {
|
|
667
|
+
return "Next reads: none";
|
|
668
|
+
}
|
|
669
|
+
return `Next reads:\n${nextReads.map((item) => `- ${referenceLocation(item)}: ${item.reason} [${item.association ?? "related"}; ${item.nodeId}]`).join("\n")}`;
|
|
670
|
+
}
|
|
671
|
+
function nonNegativeIntegerOr(value, fallback) {
|
|
672
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : fallback;
|
|
673
|
+
}
|
|
674
|
+
function positiveIntegerOr(value, fallback) {
|
|
675
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
|
|
676
|
+
}
|