@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README-ZH.md +13 -3
  3. package/README.md +13 -3
  4. package/agent-pack/README.md +2 -0
  5. package/agent-pack/mdgraph-agent-instructions.md +5 -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 +125 -6
  12. package/dist/db/connection.js +17 -1
  13. package/dist/db/repositories.d.ts +30 -5
  14. package/dist/db/repositories.js +171 -8
  15. package/dist/db/sqlite-adapter.js +8 -2
  16. package/dist/evaluation/retrieval-eval.d.ts +11 -0
  17. package/dist/evaluation/retrieval-eval.js +35 -1
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +3 -0
  20. package/dist/indexer.js +64 -6
  21. package/dist/mcp/server.js +5 -4
  22. package/dist/mcp/tools.js +26 -11
  23. package/dist/query/context-builder.d.ts +2 -0
  24. package/dist/query/context-builder.js +154 -24
  25. package/dist/query/knowledge-card.d.ts +90 -0
  26. package/dist/query/knowledge-card.js +676 -0
  27. package/dist/query/search.js +30 -8
  28. package/dist/scanner/file-scanner.js +7 -7
  29. package/dist/semantic/ollama-provider.js +6 -1
  30. package/dist/utils/fts.d.ts +1 -0
  31. package/dist/utils/fts.js +68 -13
  32. package/dist/utils/path-safety.d.ts +3 -0
  33. package/dist/utils/path-safety.js +27 -0
  34. package/dist/watcher/file-watcher.js +121 -17
  35. package/dist/wiki/wiki-dependencies.d.ts +20 -0
  36. package/dist/wiki/wiki-dependencies.js +45 -0
  37. package/dist/wiki/wiki-domains.d.ts +13 -0
  38. package/dist/wiki/wiki-domains.js +55 -0
  39. package/dist/wiki/wiki-evidence.d.ts +27 -0
  40. package/dist/wiki/wiki-evidence.js +112 -0
  41. package/dist/wiki/wiki-plan.d.ts +121 -0
  42. package/dist/wiki/wiki-plan.js +616 -0
  43. package/dist/wiki/wiki-status.d.ts +67 -0
  44. package/dist/wiki/wiki-status.js +451 -0
  45. package/docs/EN/Agent_Integration.md +16 -4
  46. package/docs/EN/Architecture.md +14 -2
  47. package/docs/EN/Evaluation_Questions.md +21 -1
  48. package/docs/EN/Knowledge_Cards_and_Wiki_Workflow.md +97 -0
  49. package/docs/EN/Operations.md +22 -0
  50. package/docs/EN/Output_Contracts.md +44 -3
  51. package/docs/EN/Public_Contracts.md +4 -2
  52. package/docs/EN/Public_Contracts_1.0.md +4 -0
  53. package/docs/EN/README.md +1 -0
  54. package/docs/EN/Release_Checklist.md +3 -2
  55. package/docs/EN/Retrieval_and_Context.md +20 -5
  56. package/docs/ZH/Agent_Integration.md +16 -4
  57. package/docs/ZH/Architecture.md +14 -4
  58. package/docs/ZH/Evaluation_Questions.md +21 -1
  59. package/docs/ZH/Knowledge_Cards_and_Wiki_Workflow.md +99 -0
  60. package/docs/ZH/Operations.md +22 -0
  61. package/docs/ZH/Output_Contracts.md +44 -3
  62. package/docs/ZH/Public_Contracts.md +4 -2
  63. package/docs/ZH/Public_Contracts_1.0.md +4 -0
  64. package/docs/ZH/README.md +1 -0
  65. package/docs/ZH/Release_Checklist.md +3 -2
  66. package/docs/ZH/Retrieval_and_Context.md +20 -5
  67. package/package.json +8 -3
package/dist/mcp/tools.js CHANGED
@@ -6,9 +6,10 @@ import { databasePath, loadConfig } from "../config/load-config.js";
6
6
  import { openExistingDatabase } from "../db/connection.js";
7
7
  import { GraphRepository } from "../db/repositories.js";
8
8
  import { CONTEXT_PACKING_STRATEGIES, buildContext, buildContextAsync } from "../query/context-builder.js";
9
+ import { buildKnowledgeCard, formatKnowledgeCard } from "../query/knowledge-card.js";
9
10
  import { explainSearchGraphAsync, searchGraph } from "../query/search.js";
10
11
  import { traceNodes } from "../query/trace.js";
11
- import { isPathInsideOrEqual } from "../utils/path-safety.js";
12
+ import { assertProjectFilesInsideRoot, isPathInsideOrEqual } from "../utils/path-safety.js";
12
13
  export class McpInputError extends Error {
13
14
  name = "McpInputError";
14
15
  }
@@ -39,7 +40,7 @@ export const tools = [
39
40
  knownFiles: {
40
41
  type: "array",
41
42
  items: { type: "string" },
42
- description: "Optional known project-relative document or source paths to seed the task-start brief."
43
+ description: "Optional project-relative documents, path#anchor sections, or source paths. Document hints retrieve body sections under the shared character budget."
43
44
  },
44
45
  maxChars: { type: "number", description: "Optional character budget for the returned context package." },
45
46
  packingStrategy: {
@@ -97,9 +98,10 @@ export class ToolHandler {
97
98
  boundProjectRoot;
98
99
  constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot, watchHealthProvider) {
99
100
  this.watchHealthProvider = watchHealthProvider;
100
- this.boundProjectRoot = validatedProjectRoot(path.resolve(boundProjectRoot));
101
+ this.boundProjectRoot = fs.realpathSync(validatedProjectRoot(path.resolve(boundProjectRoot)));
101
102
  this.defaultProjectRoot = validatedProjectRoot(path.resolve(defaultProjectRoot));
102
- if (!isPathInsideOrEqual(this.boundProjectRoot, this.defaultProjectRoot)) {
103
+ assertProjectFilesInsideRoot(this.boundProjectRoot, this.defaultProjectRoot);
104
+ if (!isPathInsideOrEqual(this.boundProjectRoot, fs.realpathSync(this.defaultProjectRoot))) {
103
105
  throw new McpInputError(`Default project root must stay inside served root: ${this.boundProjectRoot}`);
104
106
  }
105
107
  }
@@ -167,7 +169,9 @@ export class ToolHandler {
167
169
  if (resolution.status === "ambiguous") {
168
170
  return withFreshnessNotice(textResult(formatAmbiguousNodeQuery(resolution), { projectRoot, query, error: resolution.error, candidates: resolution.candidates, node: null }), freshness);
169
171
  }
170
- return withFreshnessNotice(textResult(formatNode(resolution.node, repository), { projectRoot, node: resolution.node }), freshness);
172
+ const card = buildKnowledgeCard(repository, resolution.node);
173
+ const node = card ? { ...resolution.node, card } : resolution.node;
174
+ return withFreshnessNotice(textResult(formatNode(resolution.node, repository, card), { projectRoot, node }), freshness);
171
175
  });
172
176
  case "mdgraph_trace":
173
177
  return this.withRepository(projectRoot, (repository) => {
@@ -232,6 +236,7 @@ export class ToolHandler {
232
236
  });
233
237
  }
234
238
  withRepository(projectRoot, fn) {
239
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
235
240
  const repository = new GraphRepository(openExistingDatabase(projectRoot));
236
241
  try {
237
242
  return fn(repository);
@@ -241,6 +246,7 @@ export class ToolHandler {
241
246
  }
242
247
  }
243
248
  async withRepositoryAsync(projectRoot, fn) {
249
+ assertProjectFilesInsideRoot(this.boundProjectRoot, projectRoot);
244
250
  const repository = new GraphRepository(openExistingDatabase(projectRoot));
245
251
  try {
246
252
  return await fn(repository);
@@ -413,7 +419,7 @@ function agentContextMode(config, counts, query, knownFiles, requestedMaxChars)
413
419
  const maxChars = requestedMaxChars ?? Math.min(config.search.maxContextChars, needsMoreDepth ? config.search.maxContextChars : 16_000);
414
420
  return {
415
421
  name: "auto",
416
- searchLimit: searchMode.limit,
422
+ searchLimit: searchMode.limit * 2,
417
423
  maxDepth,
418
424
  maxChars,
419
425
  reason: [searchMode.reason, requestedMaxChars ? "explicit character budget" : "auto character budget"].join("; ")
@@ -444,7 +450,9 @@ function formatContext(context) {
444
450
  const entities = item.matchedEntities.length ? `\nMatched entities: ${item.matchedEntities.join(", ")}` : "";
445
451
  const sourceRefs = item.sourceRefs?.length ? `\nSource refs: ${item.sourceRefs.map((sourceRef) => `${sourceRef.path} (${sourceRef.edgeKind}/${sourceRef.provenance}, confidence ${sourceRef.confidence})`).join(", ")}` : "";
446
452
  const riskNotes = item.riskNotes?.length ? `\nRisk notes: ${item.riskNotes.join("; ")}` : "";
447
- return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}\n${heading}\n${item.content}`;
453
+ const cardSummary = item.cardSummary ? `\nKnowledge Card: ${item.cardSummary}` : "";
454
+ const excerptNotice = item.truncated ? "\nPartial section: use the node or anchor to read the complete source." : "";
455
+ return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}${cardSummary}${excerptNotice}\n${heading}\n${item.content}`;
448
456
  });
449
457
  const hints = [
450
458
  context.mode ? `Mode: ${context.mode.name} (searchLimit ${context.mode.searchLimit}, maxDepth ${context.mode.maxDepth}; ${context.mode.reason})` : "",
@@ -453,7 +461,7 @@ function formatContext(context) {
453
461
  ].filter(Boolean);
454
462
  return [header, ...hints, ...items].join("\n\n");
455
463
  }
456
- function formatNode(node, repository) {
464
+ function formatNode(node, repository, card) {
457
465
  const edges = repository.edgesForNode(node.id).slice(0, 12);
458
466
  const related = edges.map((edge) => {
459
467
  const otherId = edge.fromId === node.id ? edge.toId : edge.fromId;
@@ -463,8 +471,9 @@ function formatNode(node, repository) {
463
471
  return [
464
472
  `${node.kind}: ${node.label}`,
465
473
  JSON.stringify(node.data, null, 2),
466
- related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none"
467
- ].join("\n\n");
474
+ related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none",
475
+ card ? formatKnowledgeCard(card) : ""
476
+ ].filter(Boolean).join("\n\n");
468
477
  }
469
478
  function formatAmbiguousNodeQuery(resolution) {
470
479
  const candidates = resolution.candidates
@@ -509,7 +518,13 @@ function validatedProjectRoot(projectRoot) {
509
518
  }
510
519
  function validatedBoundProjectRoot(projectRoot, boundProjectRoot) {
511
520
  const resolved = validatedProjectRoot(projectRoot);
512
- if (!isPathInsideOrEqual(boundProjectRoot, resolved)) {
521
+ try {
522
+ assertProjectFilesInsideRoot(boundProjectRoot, resolved);
523
+ }
524
+ catch (error) {
525
+ throw new McpInputError(error instanceof Error ? error.message : String(error));
526
+ }
527
+ if (!isPathInsideOrEqual(boundProjectRoot, fs.realpathSync(resolved))) {
513
528
  throw new McpInputError(`projectPath must stay inside served project root: ${boundProjectRoot}`);
514
529
  }
515
530
  return resolved;
@@ -23,7 +23,9 @@ export interface ContextItem {
23
23
  edgePath?: ContextEdgePathStep[];
24
24
  sourceRefs?: ContextSourceRef[];
25
25
  riskNotes?: string[];
26
+ cardSummary?: string;
26
27
  content: string;
28
+ truncated?: boolean;
27
29
  }
28
30
  export interface ContextEdgePathStep {
29
31
  fromId: string;
@@ -1,11 +1,15 @@
1
1
  import { explainSearchGraphAsync, searchGraph } from "./search.js";
2
2
  import { scanContentRiskLines } from "../utils/content-risk.js";
3
3
  import { normalizePath, uniqueStrings } from "../utils/text.js";
4
+ import { createKnowledgeCardBuilder } from "./knowledge-card.js";
5
+ import { ftsQueryFor, ftsQueryGroups } from "../utils/fts.js";
4
6
  const DEFAULT_MAX_CONTEXT_NODES = 16;
7
+ const DEFAULT_MAX_CONTEXT_CARD_SUMMARIES = 4;
5
8
  export const CONTEXT_PACKING_STRATEGY = "mmr-style-document-round-robin";
6
9
  export const CONTEXT_PACKING_STRATEGIES = [CONTEXT_PACKING_STRATEGY, "mmr"];
7
10
  export const DEFAULT_MMR_LAMBDA = 0.65;
8
11
  const MMR_SAME_DOCUMENT_REDUNDANCY_THRESHOLD = 0.8;
12
+ const KNOWN_FILE_SECTION_LIMIT = 4;
9
13
  export function buildContext(repository, config, query, options = {}) {
10
14
  const searchLimit = positiveIntegerOr(options.searchLimit, config.search.defaultLimit * 2);
11
15
  const results = searchGraph(repository, config, query, searchLimit, options.searchOptions);
@@ -22,7 +26,7 @@ export function buildContextFromSearchResults(repository, config, query, results
22
26
  const maxDepth = positiveIntegerOr(options.maxDepth, config.search.maxDepth);
23
27
  const collection = collectContextCandidates(repository, config, results, maxDepth);
24
28
  const candidates = knownFiles.length
25
- ? mergeKnownFileCandidates(repository, collection.candidates, knownFiles)
29
+ ? mergeKnownFileCandidates(repository, collection.candidates, knownFiles, query, maxChars)
26
30
  : collection.candidates;
27
31
  const packingStrategy = options.packingStrategy ?? CONTEXT_PACKING_STRATEGY;
28
32
  const packed = packContext(repository, config, query, enrichContextCandidates(repository, candidates), maxChars, options.mode, packingStrategy, mmrLambdaOrDefault(options.mmrLambda));
@@ -53,20 +57,23 @@ export function buildContextFromSearchResults(repository, config, query, results
53
57
  }
54
58
  };
55
59
  }
56
- function mergeKnownFileCandidates(repository, candidates, knownFiles) {
60
+ function mergeKnownFileCandidates(repository, candidates, knownFiles, query, maxChars) {
57
61
  const merged = new Map();
58
62
  for (const candidate of candidates) {
59
63
  addCandidate(merged, candidate);
60
64
  }
61
65
  knownFiles.forEach((knownFile, index) => {
62
- for (const candidate of candidatesForKnownFile(repository, knownFile, index)) {
66
+ for (const candidate of candidatesForKnownFile(repository, knownFile, index, query, Math.floor(maxChars / knownFiles.length))) {
63
67
  addCandidate(merged, candidate);
64
68
  }
65
69
  });
66
70
  return orderContextCandidates([...merged.values()]);
67
71
  }
68
- function candidatesForKnownFile(repository, knownFile, index) {
72
+ function candidatesForKnownFile(repository, knownFile, index, query, documentBudget) {
69
73
  const resolution = resolveKnownFile(repository, knownFile);
74
+ if (resolution?.kind === "document") {
75
+ return candidatesForKnownDocument(repository, resolution.id, knownFile, index, query, documentBudget);
76
+ }
70
77
  if (resolution?.kind !== "source_ref") {
71
78
  const directRow = resolution ? repository.contextChunkForNode(resolution.id) : undefined;
72
79
  return directRow ? [candidateFromKnownRow(directRow, `known file ${knownFile}`, index)] : [];
@@ -74,10 +81,27 @@ function candidatesForKnownFile(repository, knownFile, index) {
74
81
  return repository.edgesForNode(resolution.id)
75
82
  .map((edge) => {
76
83
  const otherId = edge.fromId === resolution.id ? edge.toId : edge.fromId;
84
+ if (repository.getNode(otherId)?.kind === "document") {
85
+ return candidatesForKnownDocument(repository, otherId, `${knownFile} via ${edge.kind}/${edge.provenance}`, index, query, documentBudget);
86
+ }
77
87
  const row = repository.contextChunkForNode(otherId);
78
- return row ? candidateFromKnownRow(row, `known file ${knownFile} via ${edge.kind}/${edge.provenance}`, index) : undefined;
88
+ return row ? [candidateFromKnownRow(row, `known file ${knownFile} via ${edge.kind}/${edge.provenance}`, index)] : [];
79
89
  })
80
- .filter((candidate) => Boolean(candidate));
90
+ .flat();
91
+ }
92
+ function candidatesForKnownDocument(repository, documentId, knownFile, index, query, documentBudget) {
93
+ const rows = repository.contextChunksForDocument(documentId);
94
+ if (rows.reduce((sum, row) => sum + row.chunk.content.length, 0) <= documentBudget) {
95
+ return rows.map((row) => candidateFromKnownRow(row, `known file ${knownFile}; complete document`, index));
96
+ }
97
+ const ftsQuery = ftsQueryFor(query);
98
+ const matches = ftsQuery ? repository.searchChunks(ftsQuery, KNOWN_FILE_SECTION_LIMIT, documentId) : [];
99
+ const candidates = matches.map((row) => candidateFromKnownRow(row, `known file ${knownFile}; FTS5 section match`, index));
100
+ const overview = rows[0];
101
+ if (overview && !matches.some((row) => row.chunk.id === overview.chunk.id)) {
102
+ candidates.push(candidateFromKnownRow(overview, `known file ${knownFile}; document overview`, index));
103
+ }
104
+ return candidates;
81
105
  }
82
106
  function resolveKnownFile(repository, knownFile) {
83
107
  const queries = uniqueStrings([knownFile, normalizePath(knownFile)]);
@@ -105,8 +129,9 @@ function candidateFromKnownRow(row, reason, index) {
105
129
  documentStatus: row.document.status,
106
130
  trustTier: row.document.trustTier,
107
131
  trustTierDeclared: hasDeclaredTrustTier(row.document),
108
- score: 10_000 - index,
109
- direct: true
132
+ score: 100 - row.rank - index / 1000,
133
+ direct: true,
134
+ known: true
110
135
  };
111
136
  }
112
137
  function addAgentHints(result, knownFiles) {
@@ -281,8 +306,9 @@ function riskNotesForCandidate(candidate) {
281
306
  }
282
307
  function orderContextCandidates(candidates) {
283
308
  return [
284
- ...orderContextCandidatesByPath(candidates.filter((candidate) => candidate.direct).sort(compareContextCandidates)),
285
- ...orderContextCandidatesByPath(candidates.filter((candidate) => !candidate.direct).sort(compareContextCandidates))
309
+ ...orderContextCandidatesByPath(candidates.filter((candidate) => candidate.known).sort(compareContextCandidates)),
310
+ ...candidates.filter((candidate) => candidate.direct && !candidate.known).sort(compareContextCandidates),
311
+ ...orderContextCandidatesByPath(candidates.filter((candidate) => !candidate.direct && !candidate.known).sort(compareContextCandidates))
286
312
  ];
287
313
  }
288
314
  function orderContextCandidatesByPath(sorted) {
@@ -321,22 +347,51 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
321
347
  let usedChars = 0;
322
348
  let budgetTruncatedItems = 0;
323
349
  let budgetSkippedItems = 0;
324
- for (let index = 0; index < ranking.candidates.length; index += 1) {
325
- const candidate = ranking.candidates[index];
350
+ const knownBudgets = knownDocumentBudgets(ranking.candidates, maxChars);
351
+ // Leave room for other direct evidence when a broad navigation section is large.
352
+ const directCount = Math.max(1, candidates.filter((candidate) => candidate.direct && !candidate.known).length);
353
+ const balancedQuery = ftsQueryGroups(query).some((tokens) => tokens.length > 12);
354
+ const directSectionBudget = Math.max(1, Math.floor(maxChars / Math.min(6, directCount)));
355
+ const directBudgets = balancedQuery
356
+ ? allocateContextBudgets(ranking.candidates.filter((candidate) => candidate.direct && !candidate.known)
357
+ .map((candidate) => [candidate.nodeId, candidate.content.length]), maxChars - [...knownBudgets.values()].reduce((sum, chars) => sum + chars, 0))
358
+ : undefined;
359
+ const knownUsed = new Map();
360
+ const deferred = [];
361
+ const ordered = [...ranking.candidates];
362
+ for (let index = 0; index < ordered.length; index += 1) {
363
+ const candidate = ordered[index];
326
364
  const remaining = maxChars - usedChars;
327
365
  if (remaining <= 0) {
328
- budgetSkippedItems += ranking.candidates.length - index;
366
+ budgetSkippedItems += ordered.length - index;
329
367
  break;
330
368
  }
331
- const content = trimToBudget(candidate.content, remaining);
369
+ const available = candidate.known
370
+ ? Math.min(remaining, (knownBudgets.get(candidate.path) ?? 0) - (knownUsed.get(candidate.path) ?? 0))
371
+ : Math.min(remaining, candidate.direct ? directBudgets?.get(candidate.nodeId) ?? directSectionBudget : remaining);
372
+ if (available <= 0) {
373
+ if (candidate.known)
374
+ deferred.push({ ...candidate, known: false });
375
+ else
376
+ budgetSkippedItems += 1;
377
+ if (index === ordered.length - 1)
378
+ ordered.push(...deferred.splice(0));
379
+ continue;
380
+ }
381
+ const excerpt = contextExcerpt(candidate, query, available);
382
+ const content = excerpt.content;
332
383
  if (!content) {
333
384
  budgetSkippedItems += 1;
385
+ if (index === ordered.length - 1)
386
+ ordered.push(...deferred.splice(0));
334
387
  continue;
335
388
  }
336
389
  if (content.length < candidate.content.length) {
337
390
  budgetTruncatedItems += 1;
338
391
  }
339
392
  usedChars += content.length;
393
+ if (candidate.known)
394
+ knownUsed.set(candidate.path, (knownUsed.get(candidate.path) ?? 0) + content.length);
340
395
  items.push({
341
396
  nodeId: candidate.nodeId,
342
397
  documentId: candidate.documentId,
@@ -345,22 +400,27 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
345
400
  path: candidate.path,
346
401
  title: candidate.title,
347
402
  heading: candidate.heading,
348
- lines: candidate.lines,
403
+ lines: excerpt.lines,
349
404
  reason: candidate.reason,
350
405
  matchedEntities: candidate.matchedEntities,
351
406
  edgePath: candidate.edgePath,
352
407
  sourceRefs: candidate.sourceRefs,
353
408
  riskNotes: candidate.riskNotes,
354
- content
409
+ content,
410
+ ...(content.length < candidate.content.length ? { truncated: true } : {})
355
411
  });
412
+ if (index === ordered.length - 1)
413
+ ordered.push(...deferred.splice(0));
356
414
  }
415
+ const withCardSummaries = addContextCardSummaries(repository, items, maxChars - usedChars);
416
+ usedChars += withCardSummaries.usedChars;
357
417
  return {
358
418
  result: {
359
419
  query,
360
420
  maxChars,
361
421
  usedChars,
362
422
  mode,
363
- items,
423
+ items: withCardSummaries.items,
364
424
  packing: {
365
425
  strategy: packingStrategy,
366
426
  similarity: ranking.packingSimilarity,
@@ -377,6 +437,49 @@ function packContext(repository, config, query, candidates, maxChars, mode, pack
377
437
  redundancySkippedItems: ranking.redundancySkippedItems
378
438
  };
379
439
  }
440
+ function knownDocumentBudgets(candidates, maxChars) {
441
+ const demand = new Map();
442
+ for (const candidate of candidates.filter((item) => item.known)) {
443
+ demand.set(candidate.path, (demand.get(candidate.path) ?? 0) + candidate.content.length);
444
+ }
445
+ return allocateContextBudgets([...demand], maxChars);
446
+ }
447
+ function allocateContextBudgets(demand, maxChars) {
448
+ const documents = [...demand].sort((left, right) => left[1] - right[1]);
449
+ const budgets = new Map();
450
+ let remaining = maxChars;
451
+ documents.forEach(([documentPath, chars], index) => {
452
+ const allocated = Math.min(chars, Math.floor(remaining / (documents.length - index)));
453
+ budgets.set(documentPath, allocated);
454
+ remaining -= allocated;
455
+ });
456
+ return budgets;
457
+ }
458
+ function addContextCardSummaries(repository, items, availableChars) {
459
+ if (availableChars < 32 || !items.length) {
460
+ return { items, usedChars: 0 };
461
+ }
462
+ const builder = createKnowledgeCardBuilder(repository);
463
+ let remaining = availableChars;
464
+ let added = 0;
465
+ const enriched = items.map((item) => {
466
+ if (added >= DEFAULT_MAX_CONTEXT_CARD_SUMMARIES || remaining < 32) {
467
+ return item;
468
+ }
469
+ const card = builder.build(item.nodeId);
470
+ if (!card) {
471
+ return item;
472
+ }
473
+ const cardSummary = card.summary;
474
+ if (cardSummary.length < 32 || cardSummary.length > remaining || cardSummary.endsWith("…")) {
475
+ return item;
476
+ }
477
+ remaining -= cardSummary.length;
478
+ added += 1;
479
+ return { ...item, cardSummary };
480
+ });
481
+ return { items: enriched, usedChars: availableChars - remaining };
482
+ }
380
483
  function rankCandidatesWithMmr(repository, config, candidates, lambda) {
381
484
  if (!candidates.length) {
382
485
  return {
@@ -405,7 +508,9 @@ function rankCandidatesWithMmr(repository, config, candidates, lambda) {
405
508
  similaritySource: mostRedundant.source,
406
509
  mmrScore: lambda * queryRelevance - (1 - lambda) * mostRedundant.value
407
510
  };
408
- }).sort((left, right) => (right.mmrScore - left.mmrScore
511
+ }).sort((left, right) => (Number(Boolean(right.candidate.known)) - Number(Boolean(left.candidate.known))
512
+ || Number(right.candidate.direct) - Number(left.candidate.direct)
513
+ || right.mmrScore - left.mmrScore
409
514
  || right.queryRelevance - left.queryRelevance
410
515
  || left.order - right.order));
411
516
  const best = scored[0];
@@ -518,10 +623,36 @@ function seedsFromSearchResult(result) {
518
623
  function addCandidate(candidates, candidate) {
519
624
  const key = candidate.nodeId;
520
625
  const existing = candidates.get(key);
521
- if (!existing || candidate.score > existing.score || (candidate.direct && !existing.direct)) {
522
- candidates.set(key, candidate);
626
+ if (existing?.direct && !candidate.direct)
627
+ return;
628
+ if (!existing || candidate.score > existing.score || (candidate.direct && !existing.direct) || candidate.known) {
629
+ candidates.set(key, existing ? {
630
+ ...candidate,
631
+ known: candidate.known || existing.known,
632
+ score: Math.max(candidate.score, existing.score),
633
+ matchedEntities: uniqueStrings([...existing.matchedEntities, ...candidate.matchedEntities]),
634
+ reason: uniqueStrings([existing.reason, candidate.reason]).join("; ")
635
+ } : candidate);
523
636
  }
524
637
  }
638
+ function contextExcerpt(candidate, query, maxChars) {
639
+ if (candidate.content.length <= maxChars)
640
+ return { content: candidate.content, lines: candidate.lines };
641
+ const tokens = uniqueStrings(ftsQueryGroups(query).flat());
642
+ const paragraphs = [...candidate.content.matchAll(/[^\n]+(?:\n(?!\n)[^\n]+)*/gu)];
643
+ const best = paragraphs.map((match) => ({
644
+ offset: match.index,
645
+ content: match[0],
646
+ score: tokens.filter((token) => match[0].toLowerCase().includes(token)).length
647
+ })).sort((left, right) => right.score - left.score || left.offset - right.offset)[0];
648
+ const start = best?.score ? best.offset : 0;
649
+ const content = trimToBudget(candidate.content.slice(start), maxChars);
650
+ const firstLine = candidate.lines ? candidate.lines.start + candidate.content.slice(0, start).split("\n").length - 1 : undefined;
651
+ return {
652
+ content,
653
+ lines: firstLine === undefined ? undefined : { start: firstLine, end: Math.min(candidate.lines.end, firstLine + content.split("\n").length - 1) }
654
+ };
655
+ }
525
656
  function edgeScore(edge) {
526
657
  return edge.weight * edge.confidence;
527
658
  }
@@ -553,10 +684,9 @@ function trimToBudget(content, maxChars) {
553
684
  if (content.length <= maxChars) {
554
685
  return content;
555
686
  }
556
- if (maxChars <= 3) {
557
- return content.slice(0, maxChars);
558
- }
559
- return `${content.slice(0, maxChars - 3).trimEnd()}...`.slice(0, maxChars);
687
+ const prefix = content.slice(0, maxChars <= 3 ? maxChars : maxChars - 3);
688
+ const safePrefix = /[\uD800-\uDBFF]$/u.test(prefix) ? prefix.slice(0, -1) : prefix;
689
+ return maxChars <= 3 ? safePrefix : `${safePrefix.trimEnd()}...`;
560
690
  }
561
691
  function hasDeclaredTrustTier(document) {
562
692
  return typeof document.metadata?.declaredTrustTier === "string";
@@ -0,0 +1,90 @@
1
+ import { GraphRepository, type NodeRecord } from "../db/repositories.js";
2
+ import type { EdgeKind, Provenance } from "../types.js";
3
+ export declare const DEFAULT_KNOWLEDGE_CARD_LIMITS: {
4
+ readonly definitions: 8;
5
+ readonly sourceRefs: 8;
6
+ readonly relatedDocuments: 8;
7
+ readonly evidence: 12;
8
+ readonly nextReads: 6;
9
+ readonly maxChars: 4000;
10
+ };
11
+ export type KnowledgeCardNodeKind = Exclude<NodeRecord["kind"], "chunk">;
12
+ export type CardAssociation = "direct" | "inherited" | "related";
13
+ export interface CardReference {
14
+ nodeId: string;
15
+ kind: KnowledgeCardNodeKind;
16
+ label: string;
17
+ path?: string;
18
+ anchor?: string;
19
+ lines?: {
20
+ start: number;
21
+ end: number;
22
+ };
23
+ edgeKind?: EdgeKind;
24
+ provenance?: Provenance;
25
+ confidence?: number;
26
+ /** Whether this card owns the edge, inherited it from containment, or reaches it through another graph node. */
27
+ association?: CardAssociation;
28
+ /** The graph node that owns the displayed fact when it is not this card's node. */
29
+ originNodeId?: string;
30
+ /** The graph node used to reach a related fact. */
31
+ viaNodeId?: string;
32
+ }
33
+ export interface CardSourceReference {
34
+ nodeId: string;
35
+ path: string;
36
+ edgeKind: Extract<EdgeKind, "IMPLEMENTS" | "REFERENCES_SOURCE">;
37
+ provenance: Provenance;
38
+ confidence: number;
39
+ association?: CardAssociation;
40
+ originNodeId?: string;
41
+ viaNodeId?: string;
42
+ }
43
+ export interface CardEvidence {
44
+ edgeId: string;
45
+ fromId: string;
46
+ fromLabel: string;
47
+ toId: string;
48
+ toLabel: string;
49
+ edgeKind: EdgeKind;
50
+ provenance: Provenance;
51
+ confidence: number;
52
+ association?: CardAssociation;
53
+ originNodeId?: string;
54
+ viaNodeId?: string;
55
+ }
56
+ export interface CardNextRead extends CardReference {
57
+ reason: string;
58
+ }
59
+ export interface KnowledgeCard {
60
+ nodeId: string;
61
+ kind: KnowledgeCardNodeKind;
62
+ label: string;
63
+ summary: string;
64
+ definitions: CardReference[];
65
+ sourceRefs: CardSourceReference[];
66
+ relatedDocuments: CardReference[];
67
+ evidence: CardEvidence[];
68
+ nextReads?: CardNextRead[];
69
+ truncated?: {
70
+ definitions?: number;
71
+ sourceRefs?: number;
72
+ relatedDocuments?: number;
73
+ evidence?: number;
74
+ nextReads?: number;
75
+ };
76
+ }
77
+ export interface KnowledgeCardOptions {
78
+ maxDefinitions?: number;
79
+ maxSourceRefs?: number;
80
+ maxRelatedDocuments?: number;
81
+ maxEvidence?: number;
82
+ maxNextReads?: number;
83
+ maxChars?: number;
84
+ }
85
+ export interface KnowledgeCardBuilder {
86
+ build(nodeOrId: NodeRecord | string): KnowledgeCard | undefined;
87
+ }
88
+ export declare function createKnowledgeCardBuilder(repository: GraphRepository, options?: KnowledgeCardOptions): KnowledgeCardBuilder;
89
+ export declare function buildKnowledgeCard(repository: GraphRepository, nodeOrId: NodeRecord | string, options?: KnowledgeCardOptions): KnowledgeCard | undefined;
90
+ export declare function formatKnowledgeCard(card: KnowledgeCard): string;