dsh-data-domain-knowledge 0.1.1-alpha.2 → 0.1.1-alpha.3

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 (189) hide show
  1. package/README.md +23 -16
  2. package/lib/client.js +596 -841
  3. package/lib/contract-refs.d.ts +0 -1
  4. package/lib/doc-page.js +7 -7
  5. package/lib/pages.js +928 -1145
  6. package/lib/types/agent-behavior-rules.d.ts.map +1 -1
  7. package/lib/types/agent-behavior-rules.js +1 -2
  8. package/lib/types/agent-behavior-rules.js.map +1 -1
  9. package/lib/types/axis-contract.js +1 -1
  10. package/lib/types/axis-contract.js.map +1 -1
  11. package/lib/types/card-organize.d.ts +2 -1
  12. package/lib/types/card-organize.d.ts.map +1 -1
  13. package/lib/types/card-organize.js +5 -3
  14. package/lib/types/card-organize.js.map +1 -1
  15. package/lib/types/config-schema.d.ts +1 -1
  16. package/lib/types/config-schema.js +1 -1
  17. package/lib/types/convert/host.d.ts +2 -3
  18. package/lib/types/convert/host.d.ts.map +1 -1
  19. package/lib/types/convert/host.js +5 -2
  20. package/lib/types/convert/host.js.map +1 -1
  21. package/lib/types/convert/ingest.d.ts +2 -0
  22. package/lib/types/convert/ingest.d.ts.map +1 -1
  23. package/lib/types/convert/ingest.js +1 -0
  24. package/lib/types/convert/ingest.js.map +1 -1
  25. package/lib/types/diagnosis/types.d.ts +1 -1
  26. package/lib/types/diagnosis/types.js +1 -1
  27. package/lib/types/images.js +1 -1
  28. package/lib/types/index.d.ts +0 -4
  29. package/lib/types/index.d.ts.map +1 -1
  30. package/lib/types/index.js +30 -41
  31. package/lib/types/index.js.map +1 -1
  32. package/lib/types/knowledge-contract.d.ts +6 -0
  33. package/lib/types/knowledge-contract.d.ts.map +1 -1
  34. package/lib/types/knowledge-contract.js +6 -2
  35. package/lib/types/knowledge-contract.js.map +1 -1
  36. package/lib/types/layout.d.ts +9 -26
  37. package/lib/types/layout.d.ts.map +1 -1
  38. package/lib/types/layout.js +10 -28
  39. package/lib/types/layout.js.map +1 -1
  40. package/lib/types/materialize-snapshot.d.ts +5 -0
  41. package/lib/types/materialize-snapshot.d.ts.map +1 -1
  42. package/lib/types/migrate.d.ts +3 -1
  43. package/lib/types/migrate.d.ts.map +1 -1
  44. package/lib/types/migrate.js +3 -1
  45. package/lib/types/migrate.js.map +1 -1
  46. package/lib/types/organize-contract.d.ts.map +1 -1
  47. package/lib/types/organize-contract.js +2 -1
  48. package/lib/types/organize-contract.js.map +1 -1
  49. package/lib/types/pipeline/engine.d.ts +1 -0
  50. package/lib/types/pipeline/engine.d.ts.map +1 -1
  51. package/lib/types/pipeline/engine.js +9 -3
  52. package/lib/types/pipeline/engine.js.map +1 -1
  53. package/lib/types/pipeline/types.d.ts +6 -0
  54. package/lib/types/pipeline/types.d.ts.map +1 -1
  55. package/lib/types/pipeline/types.js.map +1 -1
  56. package/lib/types/present.d.ts +1 -1
  57. package/lib/types/present.js +1 -1
  58. package/lib/types/preset-ids.d.ts +0 -1
  59. package/lib/types/preset-ids.d.ts.map +1 -1
  60. package/lib/types/preset-ids.js +0 -3
  61. package/lib/types/preset-ids.js.map +1 -1
  62. package/lib/types/query-analysis.d.ts +0 -5
  63. package/lib/types/query-analysis.d.ts.map +1 -1
  64. package/lib/types/query-analysis.js +0 -16
  65. package/lib/types/query-analysis.js.map +1 -1
  66. package/lib/types/recall-delivery.d.ts +36 -0
  67. package/lib/types/recall-delivery.d.ts.map +1 -0
  68. package/lib/types/recall-delivery.js +16 -0
  69. package/lib/types/recall-delivery.js.map +1 -0
  70. package/lib/types/runtime.d.ts +26 -12
  71. package/lib/types/runtime.d.ts.map +1 -1
  72. package/lib/types/runtime.js +231 -106
  73. package/lib/types/runtime.js.map +1 -1
  74. package/lib/types/settings-volatile.d.ts +0 -7
  75. package/lib/types/settings-volatile.d.ts.map +1 -1
  76. package/lib/types/settings-volatile.js +0 -7
  77. package/lib/types/settings-volatile.js.map +1 -1
  78. package/lib/types/source-identity.d.ts +3 -0
  79. package/lib/types/source-identity.d.ts.map +1 -0
  80. package/lib/types/source-identity.js +5 -0
  81. package/lib/types/source-identity.js.map +1 -0
  82. package/lib/types/store/axis-references.d.ts.map +1 -1
  83. package/lib/types/store/axis-references.js +5 -3
  84. package/lib/types/store/axis-references.js.map +1 -1
  85. package/lib/types/store/knowledge-db.d.ts +1 -1
  86. package/lib/types/store/knowledge-db.d.ts.map +1 -1
  87. package/lib/types/store/knowledge-db.js +16 -2
  88. package/lib/types/store/knowledge-db.js.map +1 -1
  89. package/lib/types/types.d.ts +5 -4
  90. package/lib/types/types.d.ts.map +1 -1
  91. package/lib/types/types.js +6 -3
  92. package/lib/types/types.js.map +1 -1
  93. package/lib/types/wiki-availability.d.ts +11 -0
  94. package/lib/types/wiki-availability.d.ts.map +1 -0
  95. package/lib/types/wiki-availability.js +39 -0
  96. package/lib/types/wiki-availability.js.map +1 -0
  97. package/lib/types/wiki-finalize.d.ts +4 -2
  98. package/lib/types/wiki-finalize.d.ts.map +1 -1
  99. package/lib/types/wiki-finalize.js +9 -27
  100. package/lib/types/wiki-finalize.js.map +1 -1
  101. package/lib/types/wiki-links.d.ts +35 -0
  102. package/lib/types/wiki-links.d.ts.map +1 -0
  103. package/lib/types/wiki-links.js +129 -0
  104. package/lib/types/wiki-links.js.map +1 -0
  105. package/package.json +16 -16
  106. package/scripts/doctor.mjs +0 -7
  107. package/scripts/setup-embedding.sh +0 -0
  108. package/src/agent-behavior-rules.ts +1 -2
  109. package/src/axis-contract.ts +1 -1
  110. package/src/card-organize.ts +5 -3
  111. package/src/client/AttributionEventGuide.tsx +3 -3
  112. package/src/client/AxisMatrix.tsx +86 -19
  113. package/src/client/DirectoryPicker.tsx +0 -2
  114. package/src/client/GuideArchitectureCanvas.tsx +5 -12
  115. package/src/client/ImportFilesDialog.tsx +1 -0
  116. package/src/client/InfoHint.tsx +1 -1
  117. package/src/client/KnowledgeBaseTab.tsx +113 -39
  118. package/src/client/KnowledgePanel.tsx +16 -9
  119. package/src/client/OperationLogTab.tsx +1 -1
  120. package/src/client/RecallPanel.tsx +5 -16
  121. package/src/client/TabGuide.tsx +3 -7
  122. package/src/client/WikiFlowPanel.tsx +10 -11
  123. package/src/client/arch/NodeLogicPanel.tsx +3 -3
  124. package/src/client/arch/model.ts +5 -113
  125. package/src/client/architecture.css +1 -1
  126. package/src/client/architecture.tsx +13 -27
  127. package/src/client/attribution/AttributionTab.tsx +141 -10
  128. package/src/client/pages.css +2 -2
  129. package/src/client/pages.tsx +4 -11
  130. package/src/client/styles.css +15 -96
  131. package/src/config-schema.ts +1 -1
  132. package/src/convert/host.ts +7 -5
  133. package/src/convert/ingest.ts +3 -0
  134. package/src/diagnosis/types.ts +1 -1
  135. package/src/images.ts +1 -1
  136. package/src/index.ts +27 -49
  137. package/src/knowledge-contract.ts +7 -2
  138. package/src/layout.ts +10 -32
  139. package/src/materialize-snapshot.ts +1 -0
  140. package/src/migrate.ts +3 -1
  141. package/src/organize-contract.ts +2 -1
  142. package/src/pipeline/engine.ts +9 -3
  143. package/src/pipeline/types.ts +2 -0
  144. package/src/present.ts +1 -1
  145. package/src/preset-ids.ts +0 -4
  146. package/src/query-analysis.ts +0 -20
  147. package/src/recall-delivery.ts +19 -0
  148. package/src/runtime.ts +220 -102
  149. package/src/settings-volatile.ts +0 -7
  150. package/src/source-identity.ts +4 -0
  151. package/src/store/axis-references.ts +5 -3
  152. package/src/store/knowledge-db.ts +14 -2
  153. package/src/types.ts +6 -4
  154. package/src/wiki-availability.ts +37 -0
  155. package/src/wiki-finalize.ts +9 -25
  156. package/src/wiki-links.ts +120 -0
  157. package/lib/types/intent/engine.d.ts +0 -122
  158. package/lib/types/intent/engine.d.ts.map +0 -1
  159. package/lib/types/intent/engine.js +0 -488
  160. package/lib/types/intent/engine.js.map +0 -1
  161. package/lib/types/intent/host.d.ts +0 -68
  162. package/lib/types/intent/host.d.ts.map +0 -1
  163. package/lib/types/intent/host.js +0 -249
  164. package/lib/types/intent/host.js.map +0 -1
  165. package/lib/types/intent/scope.d.ts +0 -25
  166. package/lib/types/intent/scope.d.ts.map +0 -1
  167. package/lib/types/intent/scope.js +0 -116
  168. package/lib/types/intent/scope.js.map +0 -1
  169. package/lib/types/intent/store.d.ts +0 -33
  170. package/lib/types/intent/store.d.ts.map +0 -1
  171. package/lib/types/intent/store.js +0 -239
  172. package/lib/types/intent/store.js.map +0 -1
  173. package/lib/types/intent/tools.d.ts +0 -62
  174. package/lib/types/intent/tools.d.ts.map +0 -1
  175. package/lib/types/intent/tools.js +0 -130
  176. package/lib/types/intent/tools.js.map +0 -1
  177. package/lib/types/intent/types.d.ts +0 -170
  178. package/lib/types/intent/types.d.ts.map +0 -1
  179. package/lib/types/intent/types.js +0 -56
  180. package/lib/types/intent/types.js.map +0 -1
  181. package/src/client/IntentLogic.tsx +0 -192
  182. package/src/client/IntentTab.tsx +0 -343
  183. package/src/intent/README.md +0 -42
  184. package/src/intent/engine.ts +0 -515
  185. package/src/intent/host.ts +0 -315
  186. package/src/intent/scope.ts +0 -125
  187. package/src/intent/store.ts +0 -218
  188. package/src/intent/tools.ts +0 -154
  189. package/src/intent/types.ts +0 -229
@@ -1,4 +1,8 @@
1
- import { wikiProjection, procedureText } from './knowledge-contract.js';
1
+ import { compileWikiNavigation, scanWikiLinks, stripWikiNavigation, wikiIndexContent, wikiLinkCandidates, wikiReference } from './wiki-links.js';
2
+ import { wikiProjection, wikiGroupKey, procedureText } from './knowledge-contract.js';
3
+ import { wikiUnavailableReason } from './wiki-availability.js';
4
+ import { newSourceId } from './source-identity.js';
5
+ import { agentContextItem } from './recall-delivery.js';
2
6
  import { buildDeriveSystem, DERIVE_CONTRACT_VERSION } from './derive-contract.js';
3
7
  import { createHash, randomUUID } from 'node:crypto';
4
8
  import { spawn } from 'node:child_process';
@@ -23,7 +27,7 @@ import { EXTRACTION_CONTRACT_VERSION } from './extract-table.js';
23
27
  import { KnowledgePipeline } from './pipeline/engine.js';
24
28
  import { PipelineStore } from './pipeline/store.js';
25
29
  import { candidatesFromReport, coordinateIdsOf } from './wiki-materialize.js';
26
- import { sectionRecords, buildOrganizePrompt, buildOrganizeSystem, checkOrganize, citationsFrom, layoutHash, layoutOf, parseOrganize, placementsOf, renderFootnoteDefinitions, renderOrganizeBody, } from './card-organize.js';
30
+ import { sectionRecords, ORGANIZE_VERSION, buildOrganizePrompt, buildOrganizeSystem, checkOrganize, citationsFrom, layoutHash, layoutOf, parseOrganize, placementsOf, renderFootnoteDefinitions, renderOrganizeBody, } from './card-organize.js';
27
31
  import { FTS_FILE, loadSqlite, segment } from './fts.js';
28
32
  import { attachImagesToKnowledge, insertImage, planSourceImages } from './source-images.js';
29
33
  import { buildWikiIndex, cardKey, deadLinksOf, planRelated, relatedByGroupKey, relatedEntriesOf, stripRelatedSection, RELATED_METADATA_KEY, } from './wiki-finalize.js';
@@ -806,7 +810,7 @@ function parseLineage(value) {
806
810
  return undefined;
807
811
  const record = value;
808
812
  const lineage = {};
809
- for (const key of ['sessionId', 'turnId', 'intentId', 'taskId', 'subtaskId', 'parentSubtaskId', 'runId', 'traceId', 'domain']) {
813
+ for (const key of ['sessionId', 'turnId', 'taskId', 'subtaskId', 'parentSubtaskId', 'runId', 'traceId', 'domain']) {
810
814
  if (typeof record[key] === 'string' && record[key].trim())
811
815
  lineage[key] = record[key].trim().slice(0, 160);
812
816
  }
@@ -954,7 +958,7 @@ export function splitWikiNotes(card) {
954
958
  const sections = [];
955
959
  let current;
956
960
  let fence;
957
- for (const line of card.content.trim().split('\n')) {
961
+ for (const line of stripWikiNavigation(card.content).trim().split('\n')) {
958
962
  const code = line.match(/^\s*(?:(?:\d+[.)]|[-+*])\s+)?(`{3,}|~{3,})(.*)$/);
959
963
  if (code) {
960
964
  if (!fence)
@@ -2697,6 +2701,7 @@ export class KnowledgeRuntime {
2697
2701
  for (const [index, item] of items.entries()) {
2698
2702
  const title = item?.title?.trim() || undefined;
2699
2703
  const result = await this.addSource({
2704
+ ...(item?.sourceId ? { sourceId: item.sourceId } : {}),
2700
2705
  ...(title ? { title } : {}),
2701
2706
  content: item?.content,
2702
2707
  ...(item?.externalId ? { externalId: item.externalId } : {}),
@@ -2831,7 +2836,7 @@ export class KnowledgeRuntime {
2831
2836
  if (db === null) {
2832
2837
  return failure({ sourceId: '' }, 'STORE_UNAVAILABLE', this.storeProblem ?? '知识库不可用', true, '检查 Node 版本(正文进库之后需要 22.5+ 的 node:sqlite)与知识库文件的属主标记。');
2833
2838
  }
2834
- const sourceId = input.sourceId?.trim() || hash(input.externalId ?? input.content);
2839
+ const sourceId = input.sourceId?.trim() || (input.externalId?.startsWith('upload:') ? newSourceId() : hash(input.externalId ?? input.content));
2835
2840
  if (!SAFE_ID.test(sourceId))
2836
2841
  return failure({ sourceId: '' }, 'SOURCE_ID_INVALID', 'source_id 含有非法字符', false);
2837
2842
  const title = input.title?.trim() || sourceId;
@@ -3934,7 +3939,8 @@ export class KnowledgeRuntime {
3934
3939
  return { ok: false, reason: '知识库不可用,这次没有组织卡片(正文退回确定性布局)' };
3935
3940
  const listed = input.knowledge ? { knowledge: input.knowledge, total: input.knowledge.length } : await store.list({
3936
3941
  objectId: input.coordinate.objectId,
3937
- ...(input.existing?.metadata.wiki_kind ? { kind: input.existing.metadata.wiki_kind === 'way' ? 'procedure' : 'fact', ...(input.coordinate.actionId ? { actionId: input.coordinate.actionId } : {}) } : { actionId: input.coordinate.actionId, sceneId: input.coordinate.sceneId }),
3942
+ actionId: input.coordinate.actionId, sceneId: input.coordinate.sceneId,
3943
+ ...(input.existing?.metadata.wiki_kind ? { kind: input.existing.metadata.wiki_kind === 'way' ? 'procedure' : 'fact' } : {}),
3938
3944
  excludeWithdrawn: true,
3939
3945
  limit: MAX_ORGANIZE_KNOWLEDGE,
3940
3946
  });
@@ -3984,7 +3990,7 @@ export class KnowledgeRuntime {
3984
3990
  hash,
3985
3991
  layout,
3986
3992
  reuse,
3987
- system: buildOrganizeSystem(input.coordinate.actionId ? 'way' : 'fact'),
3993
+ system: buildOrganizeSystem(input.existing?.metadata.wiki_kind === 'way' || listed.knowledge[0]?.kind === 'procedure' ? 'way' : 'fact'),
3988
3994
  prompt: buildOrganizePrompt(organizeInput),
3989
3995
  };
3990
3996
  }
@@ -4178,7 +4184,7 @@ export class KnowledgeRuntime {
4178
4184
  const entries = plan.get(cardKey(card));
4179
4185
  if (entries === undefined || entries.length === 0)
4180
4186
  return {};
4181
- return { related: entries.map(entry => ({ title: entry.title, entityType: entry.entityType, reason: entry.reason })) };
4187
+ return { related: entries.map(entry => ({ title: entry.title, entityType: entry.entityType, entityId: entry.entityId, reason: entry.reason })) };
4182
4188
  }
4183
4189
  catch {
4184
4190
  // 相关投影是**增强**:算不出来时不给清单,于是正文里一个 `[[…]]` 都不许出现 —— 而不是把卡片卡住。
@@ -4364,7 +4370,11 @@ export class KnowledgeRuntime {
4364
4370
  const createdAt = typeof existing?.frontmatter.created_at === 'string' && existing.frontmatter.created_at ? existing.frontmatter.created_at : updatedAt;
4365
4371
  const provenance = [...(input.provenance ?? []), ...(input.lineage ? [{ ...input.lineage, role: 'created', refType: 'knowledge_card', refId: input.entityId }] : [])];
4366
4372
  // 旧版本曾把 schema_issues 写入 metadata。重写卡片时主动摘掉它,避免旧的待补结果继续出现。
4367
- const { schema_issues: _staleIssues, ...metadata } = input.metadata ?? {};
4373
+ const { schema_issues: _staleIssues, ...metadata } = input.metadata ?? previous?.metadata ?? {};
4374
+ if (status === 'deprecated' && (input.origin === 'review' || input.origin === 'manual' || (input.origin === undefined && previous?.status !== 'deprecated')))
4375
+ metadata.wiki_deprecation_origin = 'manual';
4376
+ if (status !== 'deprecated')
4377
+ delete metadata.wiki_deprecation_origin;
4368
4378
  void _staleIssues;
4369
4379
  // 备注与 review **默认继承库里已有的**:不传不等于清空(见入参注释)。
4370
4380
  const annotations = input.annotations ?? previousAnnotations ?? [];
@@ -4441,7 +4451,98 @@ export class KnowledgeRuntime {
4441
4451
  }
4442
4452
  return success({ entityId: input.entityId, ...(input.lineage ? { lineage: input.lineage } : {}) });
4443
4453
  }
4444
- /** Resolve one card by id, optionally constrained to a type (ids are unique per type). */
4454
+ /** Shared by direct reads, index publication and recall; always reads live contributions. */
4455
+ async wikiUnavailability(cards, suppliedPlacements) {
4456
+ const truth = await this.storeHandle();
4457
+ const knowledge = await this.knowledgeStore();
4458
+ if (!truth || !knowledge)
4459
+ return new Map(cards.map(card => [cardKey(card), '知识真源不可用,无法核验 Wiki。']));
4460
+ const placements = suppliedPlacements ?? truth.placementsOf(cards.map(card => card.entityId));
4461
+ const ids = [...new Set(cards.flatMap(card => [...(placements.get(card.entityId) ?? []).map(row => row.knowledgeId), ...Object.keys(card.metadata.knowledge_versions ?? {})]))];
4462
+ const rows = new Map();
4463
+ for (let offset = 0; offset < ids.length; offset += 500) {
4464
+ const page = await knowledge.list({ ids: ids.slice(offset, offset + 500), includeMerged: true, limit: 500 });
4465
+ for (const row of page.knowledge)
4466
+ rows.set(row.id, row);
4467
+ }
4468
+ const sources = new Map(truth.raw('SELECT entity_id,head_version FROM source').all().map(row => [row.entity_id, row.head_version]));
4469
+ const cases = new Map();
4470
+ const result = new Map();
4471
+ for (const card of cards) {
4472
+ const reason = wikiUnavailableReason(card, placements.get(card.entityId) ?? [], { knowledge: rows, sources, caseVersion: id => {
4473
+ if (!cases.has(id))
4474
+ cases.set(id, truth.event(id)?.version);
4475
+ return cases.get(id);
4476
+ } });
4477
+ if (reason)
4478
+ result.set(cardKey(card), reason);
4479
+ }
4480
+ return result;
4481
+ }
4482
+ /** Read a stable Wiki link or browse an Object's coordinates without flattening its files. */
4483
+ async readWiki(input = {}) {
4484
+ const empty = { wikis: [], total: 0, offset: input.offset ?? 0, hasMore: false, outgoing: [], backlinks: [] };
4485
+ const limit = input.limit ?? 20, offset = input.offset ?? 0;
4486
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(offset) || offset < 0)
4487
+ return failure(empty, 'WIKI_PAGE_INVALID', 'limit 必须为 1–100 的整数,offset 必须为非负整数。', false);
4488
+ if (input.wikiKind !== undefined && input.wikiKind !== 'fact' && input.wikiKind !== 'way')
4489
+ return failure(empty, 'WIKI_KIND_INVALID', 'wiki_kind 只能为 fact 或 way。', false);
4490
+ if (!input.target?.trim() && !input.objectId?.trim() && !input.object?.trim())
4491
+ return failure(empty, 'WIKI_SCOPE_REQUIRED', '请提供双链 target、object_id 或明确的 Object 名称。', false);
4492
+ const cards = await this.loadCards();
4493
+ let objectId = input.objectId;
4494
+ if (input.object !== undefined) {
4495
+ const name = input.object.trim().toLocaleLowerCase();
4496
+ const objects = (await this.listAxisEntities('object') ?? []).filter(object => object.status !== 'deprecated' && object.status !== 'merged'
4497
+ && [object.id, object.name, ...object.aliases].some(value => value.toLocaleLowerCase() === name));
4498
+ if (objects.length !== 1)
4499
+ return failure({ ...empty, candidates: objects.map(object => ({ id: object.id, name: object.name })) }, objects.length ? 'OBJECT_AMBIGUOUS' : 'OBJECT_NOT_FOUND', 'Object 名称未唯一解析,请使用明确的 object_id。', false);
4500
+ if (objectId !== undefined && objectId !== objects[0].id)
4501
+ return failure(empty, 'OBJECT_SCOPE_CONFLICT', 'object 与 object_id 指向不同对象。', false);
4502
+ objectId = objects[0].id;
4503
+ }
4504
+ const inScope = (card) => (objectId === undefined || card.coordinate?.objectId === objectId)
4505
+ && (input.actionId === undefined || card.coordinate?.actionId === input.actionId)
4506
+ && (input.sceneId === undefined || card.coordinate?.sceneId === input.sceneId)
4507
+ && (input.wikiKind === undefined || card.metadata.wiki_kind === input.wikiKind);
4508
+ let selected = cards.filter(inScope);
4509
+ if (input.target?.trim()) {
4510
+ selected = wikiLinkCandidates(selected, input.target);
4511
+ if (selected.length !== 1)
4512
+ return failure({ ...empty, candidates: selected.map(card => ({ ...wikiReference(card), coordinate: card.coordinate, wikiKind: card.metadata.wiki_kind })) }, selected.length ? 'WIKI_LINK_AMBIGUOUS' : 'WIKI_NOT_FOUND', '双链未唯一指向 Wiki,请从候选中使用稳定 target。', false);
4513
+ if (selected[0].status === 'deprecated')
4514
+ return failure(empty, 'WIKI_UNAVAILABLE', '目标 Wiki 已停用,请按 Object 坐标查找当前文件。', false);
4515
+ }
4516
+ selected = selected.filter(card => card.status !== 'deprecated').sort((a, b) => wikiReference(a).target.localeCompare(wikiReference(b).target));
4517
+ const page = selected.slice(offset, offset + limit);
4518
+ const includeContent = input.includeContent ?? Boolean(input.target);
4519
+ const truth = await this.storeHandle();
4520
+ const placements = truth?.placementsOf(page.map(card => card.entityId)) ?? new Map();
4521
+ const unavailableByKey = await this.wikiUnavailability(page, placements);
4522
+ const wikis = [];
4523
+ for (const card of page) {
4524
+ const unavailable = unavailableByKey.get(cardKey(card));
4525
+ wikis.push({ ...wikiReference(card), coordinate: card.coordinate, wikiKind: card.metadata.wiki_kind, status: card.status, available: !unavailable,
4526
+ ...(unavailable ? { reason: unavailable } : {}), ...(card.coordinate ? { coordinateLabels: await this.coordinateNames(card.coordinate) } : {}),
4527
+ ...(includeContent && !unavailable ? { wiki: card } : {}),
4528
+ });
4529
+ }
4530
+ const first = input.target ? page[0] : undefined;
4531
+ const live = cards.filter(card => card.status !== 'deprecated');
4532
+ const outgoing = first ? [...new Map(scanWikiLinks(first.content).flatMap(link => {
4533
+ const targets = wikiLinkCandidates(live, link.target);
4534
+ return targets.length === 1 && targets[0].entityId !== first.entityId ? [[targets[0].entityId, wikiReference(targets[0])]] : [];
4535
+ })).values()] : [];
4536
+ const backlinks = first ? live.filter(card => card.entityId !== first.entityId && scanWikiLinks(card.content).some(link => {
4537
+ const targets = wikiLinkCandidates(live, link.target);
4538
+ return targets.length === 1 && targets[0].entityId === first.entityId;
4539
+ })).map(wikiReference) : [];
4540
+ const data = { wikis, total: selected.length, offset, hasMore: offset + page.length < selected.length,
4541
+ nextOffset: offset + page.length < selected.length ? offset + page.length : null, outgoing, backlinks };
4542
+ await this.audit('wiki.read', { target: input.target, objectId, actionId: input.actionId, sceneId: input.sceneId, wikiKind: input.wikiKind, includeContent, returned: page.length });
4543
+ return success(data);
4544
+ }
4545
+ /** Resolve one card by its stable ID, optionally constrained to a type. */
4445
4546
  async readCard(entityId, entityType) {
4446
4547
  const db = await this.storeHandle();
4447
4548
  if (db === null)
@@ -4539,7 +4640,7 @@ export class KnowledgeRuntime {
4539
4640
  return failure({ entityId, status }, 'STATUS_TRANSITION_INVALID', 'problem 不能直接恢复为其他状态,请先改为 unreviewed', false);
4540
4641
  const eventLineage = withRun(lineage, 'knowledge-status');
4541
4642
  const provenance = [...(card.provenance ?? []), ...(eventLineage ? [{ ...eventLineage, role: 'executed', refType: 'knowledge_status', refId: entityId }] : [])];
4542
- const written = await this.writeCard({ ...card, status, sourceRefs: card.sourceRefs, provenance, metadata: { ...card.metadata, ...(problemNote?.trim() ? { problem_note: problemNote.trim() } : {}) } });
4643
+ const written = await this.writeCard({ ...card, status, sourceRefs: card.sourceRefs, provenance, origin: 'review', metadata: { ...card.metadata, ...(problemNote?.trim() ? { problem_note: problemNote.trim() } : {}) } });
4543
4644
  if (written.ok === false)
4544
4645
  return failure({ entityId, status }, written.error.code, written.error.message, written.error.retryable, written.error.suggestion);
4545
4646
  return success({ entityId, status, ...(eventLineage ? { lineage: eventLineage } : {}) });
@@ -4586,7 +4687,7 @@ export class KnowledgeRuntime {
4586
4687
  * `metadata.related_cards`;这里继续剥离旧版本正文里的标记,保证存量卡片迁移期间
4587
4688
  * 也不会把导航送进召回。
4588
4689
  */
4589
- const recallBody = stripEventReferenceSection(stripRelatedSection(card.content));
4690
+ const recallBody = wikiIndexContent(stripEventReferenceSection(stripRelatedSection(card.content)));
4590
4691
  for (const [index, chunk] of splitWikiNotes({ ...card, content: recallBody }).entries()) {
4591
4692
  const baseId = `${card.entityType}:${card.entityId}`;
4592
4693
  const stableSection = layoutOf(card.metadata)?.sections?.find(section => section.title === chunk.heading);
@@ -5149,7 +5250,7 @@ export class KnowledgeRuntime {
5149
5250
  existing: card,
5150
5251
  ...(input.imagePlan.byCard.get(key) === undefined ? {} : { images: input.imagePlan.byCard.get(key) }),
5151
5252
  ...(relatedPlan.get(key) === undefined ? {} : {
5152
- related: (relatedPlan.get(key) ?? []).map(entry => ({ title: entry.title, entityType: entry.entityType, reason: entry.reason })),
5253
+ related: (relatedPlan.get(key) ?? []).map(entry => ({ title: entry.title, entityType: entry.entityType, entityId: entry.entityId, reason: entry.reason })),
5153
5254
  }),
5154
5255
  call: input.call,
5155
5256
  });
@@ -5725,12 +5826,11 @@ export class KnowledgeRuntime {
5725
5826
  }
5726
5827
  // ------------------------------------------- Finalize · 索引 / 断链 / 相关(0049)
5727
5828
  /**
5728
- * 收尾段的**结构化数据层**:把相关卡片写进 `metadata.related_cards`,清理旧版本写进
5729
- * 正文的相关块,并把断链统计交给编译报告与索引页。
5829
+ * 编译收尾:生成类型化 Wiki 的稳定双链与导航,更新 `metadata.related_cards`,
5830
+ * 清理旧相关块,并把断链统计交给编译报告与索引页。
5730
5831
  *
5731
- * 相关卡片是派生导航数据,不是知识正文。它放在 metadata 里有三个好处:正文不会被
5732
- * 机器段落污染,召回不需要再剥离导航块,面板也能直接按结构展示。旧卡片上的
5733
- * `<!-- compiled:related -->` 只在这里做一次兼容清理。
5832
+ * 导航只放链接,不复制目标正文;面板使用结构化元数据,检索排除生成的导航块。
5833
+ * 旧卡片上的 `<!-- compiled:related -->` 在这里兼容清理。
5734
5834
  *
5735
5835
  * 三段都是确定性的,所以这个函数可以重复跑:正文和结构化相关数据都没变化时不写盘。
5736
5836
  */
@@ -5740,11 +5840,25 @@ export class KnowledgeRuntime {
5740
5840
  * 它是**算出来的**,不是谁声明的:这张卡里的知识引用了哪个轴实体,而那个轴自己
5741
5841
  * 有一张卡,就有了链接。模型抽出来的关系(`relations`)是第二层。
5742
5842
  */
5743
- const projected = await this.projectedRelated(cards);
5744
- const related = planRelated(cards, relations, projected);
5745
- /** 统计清理旧导航块之后的正文断链;相关卡片本身不再伪装成正文链接。 */
5746
- const nextCards = cards.map(card => ({ ...card, content: stripEventReferenceSection(stripRelatedSection(card.content)) }));
5747
- const deadLinks = deadLinksOf(nextCards);
5843
+ const axes = (await this.listAxisEntities() ?? []).filter(axis => axis.status !== 'deprecated' && axis.status !== 'merged');
5844
+ const objects = axes.filter(axis => axis.kind === 'object');
5845
+ const names = new Map(axes.map(axis => [axis.id, axis.name]));
5846
+ const labeled = cards.map(card => card.metadata.wiki_kind && card.coordinate ? { ...card, metadata: { ...card.metadata,
5847
+ wiki_coordinate_labels: { object: names.get(card.coordinate.objectId) ?? card.coordinate.objectId, action: names.get(card.coordinate.actionId) ?? card.coordinate.actionId, scene: names.get(card.coordinate.sceneId) ?? card.coordinate.sceneId },
5848
+ } } : card);
5849
+ const live = labeled.filter(card => card.status !== 'deprecated');
5850
+ const nextCards = labeled.map(card => {
5851
+ const base = { ...card, content: stripEventReferenceSection(stripRelatedSection(card.content)) };
5852
+ if (!card.metadata.wiki_kind || card.status === 'deprecated')
5853
+ return base;
5854
+ const navigation = compileWikiNavigation(base, live, objects);
5855
+ return { ...base, content: navigation.content, metadata: { ...base.metadata,
5856
+ wiki_links: navigation.outgoing, wiki_inline_targets: navigation.inlineTargets, wiki_object_refs: navigation.objectIds,
5857
+ } };
5858
+ });
5859
+ const projected = await this.projectedRelated(nextCards);
5860
+ const related = planRelated(live, relations, projected);
5861
+ const deadLinks = deadLinksOf(nextCards.filter(card => card.status !== 'deprecated'));
5748
5862
  let rewritten = 0;
5749
5863
  for (const [index, card] of cards.entries()) {
5750
5864
  const key = cardKey(card);
@@ -5752,7 +5866,7 @@ export class KnowledgeRuntime {
5752
5866
  const entries = related.get(key) ?? [];
5753
5867
  const previousEntries = relatedEntriesOf(card.metadata);
5754
5868
  const contentChanged = nextCard.content !== card.content;
5755
- const relatedChanged = JSON.stringify(previousEntries) !== JSON.stringify(entries);
5869
+ const relatedChanged = JSON.stringify(previousEntries) !== JSON.stringify(entries) || JSON.stringify(card.metadata.wiki_coordinate_labels) !== JSON.stringify(nextCard.metadata.wiki_coordinate_labels) || JSON.stringify(card.metadata.wiki_links) !== JSON.stringify(nextCard.metadata.wiki_links) || JSON.stringify(card.metadata.wiki_inline_targets) !== JSON.stringify(nextCard.metadata.wiki_inline_targets) || JSON.stringify(card.metadata.wiki_object_refs) !== JSON.stringify(nextCard.metadata.wiki_object_refs);
5756
5870
  if (!contentChanged && !relatedChanged)
5757
5871
  continue;
5758
5872
  /**
@@ -5774,7 +5888,7 @@ export class KnowledgeRuntime {
5774
5888
  status: card.status,
5775
5889
  ...(card.owner ? { owner: card.owner } : {}),
5776
5890
  ...(card.provenance ? { provenance: card.provenance } : {}),
5777
- metadata: { ...card.metadata, [RELATED_METADATA_KEY]: entries },
5891
+ metadata: { ...nextCard.metadata, [RELATED_METADATA_KEY]: entries },
5778
5892
  origin: 'compile',
5779
5893
  });
5780
5894
  if (written.ok === false) {
@@ -5900,14 +6014,9 @@ export class KnowledgeRuntime {
5900
6014
  included: [],
5901
6015
  };
5902
6016
  }
5903
- /** 一条上下文条目「值多少字符」:命中条目算它那些 note 的正文,扩展条目算标题 + 摘要(+ 正文)。 */
5904
- contextCost(item, full) {
5905
- const card = item.wiki;
5906
- if (card === null)
5907
- return 0;
5908
- const shallow = card.title.length + (card.summary?.length ?? 0);
5909
- const knowledge = (item.knowledge ?? []).reduce((sum, row) => sum + row.text.length + row.state.length + 8, 0);
5910
- return knowledge + shallow + card.content.length;
6017
+ /** 与 Agent 实际收到的上下文条目使用同一序列化形状,包含完整 Wiki、依据和引用。 */
6018
+ contextCost(item) {
6019
+ return JSON.stringify(agentContextItem(item)).length;
5911
6020
  }
5912
6021
  /** 溢出目录:**系统临时目录**,不随知识库走(0050 的取舍,见 issue)。 */
5913
6022
  recallOverflowDir() {
@@ -5929,17 +6038,14 @@ export class KnowledgeRuntime {
5929
6038
  const { items, maxChars, recallId } = input;
5930
6039
  const hitCards = items.filter(item => item.reason === 'hit').length;
5931
6040
  const expandedCards = items.length - hitCards;
5932
- const totalChars = items.reduce((sum, item) => sum + this.contextCost(item, true), 0);
6041
+ const totalChars = items.reduce((sum, item) => sum + this.contextCost(item), 0);
5933
6042
  if (!Number.isFinite(maxChars) || maxChars <= 0) {
5934
6043
  return { items, report: { maxChars: 0, usedChars: totalChars, omittedCards: 0, omittedChars: 0, hitCards, expandedCards } };
5935
6044
  }
5936
6045
  const keptItems = [];
5937
6046
  let used = 0;
5938
6047
  for (const item of items) {
5939
- const full = this.contextCost(item, true);
5940
- const shallow = this.contextCost(item, false);
5941
- // 命中条目按整条算(它的正文就是证据);扩展条目可以先按「浅」那一档进。
5942
- const cost = item.reason === 'hit' ? full : shallow;
6048
+ const cost = this.contextCost(item);
5943
6049
  if (used + cost > maxChars)
5944
6050
  continue;
5945
6051
  used += cost;
@@ -5951,7 +6057,7 @@ export class KnowledgeRuntime {
5951
6057
  maxChars,
5952
6058
  usedChars: used,
5953
6059
  omittedCards: omitted.length,
5954
- omittedChars: omitted.reduce((sum, item) => sum + this.contextCost(item, true), 0),
6060
+ omittedChars: omitted.reduce((sum, item) => sum + this.contextCost(item), 0),
5955
6061
  hitCards: keptItems.filter(item => item.reason === 'hit').length,
5956
6062
  expandedCards: keptItems.filter(item => item.reason === 'expansion').length,
5957
6063
  };
@@ -6072,21 +6178,25 @@ export class KnowledgeRuntime {
6072
6178
  * 而不是报错:这一层是**增强**,它坏了不该让编译失败。
6073
6179
  */
6074
6180
  async projectedRelated(cards) {
6181
+ const links = cards.flatMap(card => scanWikiLinks(card.content).flatMap(link => {
6182
+ const candidates = wikiLinkCandidates(cards.filter(target => target.status !== 'deprecated'), link.target);
6183
+ return candidates.length === 1 && candidates[0].entityId !== card.entityId ? [{ fromKey: cardKey(card), toKey: cardKey(candidates[0]) }] : [];
6184
+ }));
6075
6185
  const knowledge = await this.knowledgeStore();
6076
6186
  if (knowledge === null)
6077
- return [];
6187
+ return links;
6078
6188
  const db = await this.storeHandle();
6079
6189
  if (db === null)
6080
- return [];
6190
+ return links;
6081
6191
  let placements;
6082
6192
  try {
6083
6193
  placements = db.placements();
6084
6194
  }
6085
6195
  catch {
6086
- return [];
6196
+ return links;
6087
6197
  }
6088
6198
  if (placements.size === 0)
6089
- return [];
6199
+ return links;
6090
6200
  /**
6091
6201
  * 单轴卡:坐标里恰好只有一个分量非空。
6092
6202
  *
@@ -6114,16 +6224,16 @@ export class KnowledgeRuntime {
6114
6224
  byAxis.set(axis, bucket);
6115
6225
  }
6116
6226
  if (byAxis.size === 0)
6117
- return [];
6227
+ return links;
6118
6228
  const ids = [...new Set([...placements.values()].flat().map(row => row.knowledgeId))];
6119
6229
  if (ids.length === 0)
6120
- return [];
6230
+ return links;
6121
6231
  let axes;
6122
6232
  try {
6123
6233
  axes = await knowledge.axesOf(ids);
6124
6234
  }
6125
6235
  catch {
6126
- return [];
6236
+ return links;
6127
6237
  }
6128
6238
  const pairs = new Map();
6129
6239
  for (const [cardId, rows] of placements) {
@@ -6148,7 +6258,7 @@ export class KnowledgeRuntime {
6148
6258
  }
6149
6259
  }
6150
6260
  }
6151
- return [...pairs.values()];
6261
+ return [...pairs.values(), ...links];
6152
6262
  }
6153
6263
  /**
6154
6264
  * 一张卡片的出链与入链(面板抽屉里的「相关」分块)。
@@ -7676,7 +7786,7 @@ export class KnowledgeRuntime {
7676
7786
  : card.metadata.wiki_kind
7677
7787
  ? events.filter(event => {
7678
7788
  const c = event.coordinateIds;
7679
- return c.objectId === card.coordinate.objectId && (card.metadata.wiki_kind === 'fact' || c.actionId === card.coordinate.actionId);
7789
+ return coordinateKeyOf(c) === coordinateKeyOf(card.coordinate);
7680
7790
  }).map(event => event.id).sort()
7681
7791
  : (eventsByCoordinate.get(coordinateKeyOf(card.coordinate)) ?? []).sort();
7682
7792
  const oldRaw = card.metadata.event_refs;
@@ -7914,9 +8024,16 @@ export class KnowledgeRuntime {
7914
8024
  derive: (sourceIds, context, force, output, checkpoint) => this.deriveProcedures(sourceIds, context, force, output, checkpoint),
7915
8025
  groups: async (context) => {
7916
8026
  const snapshot = await this.materializationSnapshot(store, context);
7917
- return { groups: snapshot.groups, blocked: snapshot.blocked, blockedAmbiguous: snapshot.blockedAmbiguous, blockedAwaitingNormalize: snapshot.blockedAwaitingNormalize, snapshot };
8027
+ return { groups: snapshot.groups, blocked: snapshot.blocked, blockedAmbiguous: snapshot.blockedAmbiguous, blockedAwaitingNormalize: snapshot.blockedAwaitingNormalize, blockedItems: snapshot.blockedItems, snapshot };
7918
8028
  },
7919
8029
  materialize: (group, context, output, snapshot) => this.materializePipelineGroup(store, group, context, output, snapshot),
8030
+ link: async () => {
8031
+ const warnings = [];
8032
+ const finalized = await this.runFinalizeStage(await this.loadCards(), Object.values(await this.readExtractedRelations()).flat(), warnings);
8033
+ if (warnings.length)
8034
+ throw new Error(warnings.join(';'));
8035
+ return `已更新 Wiki 双链与导航:${finalized.rewritten} 份`;
8036
+ },
7920
8037
  build: async (taskId, checkpoint) => {
7921
8038
  let result;
7922
8039
  try {
@@ -8131,7 +8248,7 @@ export class KnowledgeRuntime {
8131
8248
  const relations = Object.values(await this.readExtractedRelations()).flat();
8132
8249
  for (const [key, entries] of planRelated(cards, relations, await this.projectedRelated(cards))) {
8133
8250
  if (entries.length > 0)
8134
- plan.set(key, entries.map(entry => ({ title: entry.title, entityType: entry.entityType, reason: entry.reason })));
8251
+ plan.set(key, entries.map(entry => ({ title: entry.title, entityType: entry.entityType, entityId: entry.entityId, reason: entry.reason })));
8135
8252
  }
8136
8253
  }
8137
8254
  catch { /* 增强项:算不出来就不给清单 */ }
@@ -8155,23 +8272,20 @@ export class KnowledgeRuntime {
8155
8272
  const evidence = [...item.sources, ...item.timeline.flatMap(step => step.sources)];
8156
8273
  const sourceVersions = new Map(evidence.map(e => [e.documentId, db.source(e.documentId)?.version]));
8157
8274
  const fingerprint = contentHashOf(JSON.stringify({ contract: DERIVE_CONTRACT_VERSION, item: { ...item, updatedAt: undefined }, sourceVersions: [...sourceVersions], model: { provider: context.model.provider, model: context.model.model, reasoningEffort: context.model.reasoningEffort } }));
8158
- const receipt = db.raw('SELECT fingerprint, knowledge_ids FROM pipeline_derivations WHERE case_id=?').get(item.id);
8159
- if (!force && receipt?.fingerprint === fingerprint) {
8160
- done++;
8161
- reused++;
8162
- continue;
8163
- }
8275
+ const receipt = db.raw('SELECT fingerprint, response, knowledge_ids FROM pipeline_derivations WHERE case_id=?').get(item.id);
8276
+ // Replay validated cached output through ingest too: normalization may have withdrawn its support.
8277
+ const cachedResponse = !force && receipt?.fingerprint === fingerprint ? receipt.response : undefined;
8164
8278
  const auditId = randomUUID();
8165
8279
  const request = { system: buildDeriveSystem(), prompt: JSON.stringify({ case: { ...item, version: caseVersion }, sourceEvidence: evidence, sourceVersions: [...sourceVersions] }) };
8166
- let response = '{"procedures":[],"skipped_cases":[]}';
8280
+ let response = cachedResponse ?? '{"procedures":[],"skipped_cases":[]}';
8167
8281
  db.raw('INSERT INTO pipeline_derivation_runs VALUES (?,?,?,?,?,?,?,?,?)').run(auditId, item.id, caseVersion, fingerprint, JSON.stringify(request), '', 'running', null, new Date().toISOString());
8168
8282
  try {
8169
- if (item.timeline.some(step => step.type === 'check' || step.type === 'action')) {
8283
+ if (cachedResponse === undefined && item.timeline.some(step => step.type === 'check' || step.type === 'action')) {
8170
8284
  if (!context.model.call)
8171
8285
  throw new Error(`提炼模型不可用:${context.model.why ?? '请选择模型'}`);
8172
8286
  response = await context.model.call({ ...request, sessionId: `knowledge:${this.baseId || 'default'}:derive`, onDelta: output });
8173
8287
  }
8174
- else
8288
+ else if (cachedResponse === undefined)
8175
8289
  output(`Case ${item.id} 没有已执行过程,不反推 Procedure。\n`);
8176
8290
  const parsed = JSON.parse(response.trim().replace(/^```(?:json)?\s*/, '').replace(/\s*```$/, ''));
8177
8291
  if (!Array.isArray(parsed.procedures))
@@ -8217,6 +8331,8 @@ export class KnowledgeRuntime {
8217
8331
  db.raw("UPDATE pipeline_derivation_runs SET response=?,state='succeeded' WHERE id=?").run(response, auditId);
8218
8332
  output(`Case ${item.id}:保存 ${ids.length} 条候选 Procedure。\n`);
8219
8333
  done++;
8334
+ if (cachedResponse !== undefined)
8335
+ reused++;
8220
8336
  }
8221
8337
  catch (cause) {
8222
8338
  db.raw("UPDATE pipeline_derivation_runs SET response=?,state='failed',error=? WHERE id=?").run(response, cause instanceof Error ? cause.message : String(cause), auditId);
@@ -8232,7 +8348,7 @@ export class KnowledgeRuntime {
8232
8348
  * 两处必须用同一个表达式,否则「什么算变化」就有两套说法。
8233
8349
  */
8234
8350
  pipelineGroupFingerprint(knowledge, context) {
8235
- return contentHashOf(JSON.stringify({ knowledge: knowledge.map(row => ({ id: row.id, kind: row.kind ?? 'fact', data: row.data, text: row.text, status: row.status, sources: row.sources.filter(source => !source.withdrawn) })).sort((a, b) => a.id.localeCompare(b.id)), profile: context.profile, organize: context.organize, model: context.organize ? { provider: context.model.provider, model: context.model.model, reasoningEffort: context.model.reasoningEffort } : undefined }));
8351
+ return contentHashOf(JSON.stringify({ contract: 'coordinate-wiki-v2', organizeVersion: context.organize ? ORGANIZE_VERSION : undefined, knowledge: knowledge.map(row => ({ id: row.id, kind: row.kind ?? 'fact', data: row.data, text: row.text, status: row.status, sources: row.sources.filter(source => !source.withdrawn) })).sort((a, b) => a.id.localeCompare(b.id)), profile: context.profile, organize: context.organize, model: context.organize ? { provider: context.model.provider, model: context.model.model, reasoningEffort: context.model.reasoningEffort } : undefined }));
8236
8352
  }
8237
8353
  /**
8238
8354
  * **只读这一组**的事实指纹,写回之前复查用。
@@ -8265,13 +8381,13 @@ export class KnowledgeRuntime {
8265
8381
  method?.limitations.length ? `边界:${method.limitations.join(';')}` : '',
8266
8382
  ].filter(Boolean).map(text => `- ${text}[^${row.id}]`).join('\n');
8267
8383
  }
8268
- async freshGroupFingerprint(coordinate, context, db) {
8384
+ async freshGroupFingerprint(coordinate, wikiKind, context, db) {
8269
8385
  const store = await this.knowledgeStore();
8270
8386
  if (!store)
8271
8387
  return '';
8272
8388
  const raw = [];
8273
8389
  for (let offset = 0;; offset += 500) {
8274
- const page = await store.list({ objectId: coordinate.objectId, kind: coordinate.actionId ? 'procedure' : 'fact', ...(coordinate.actionId ? { actionId: coordinate.actionId } : {}), excludeWithdrawn: true, limit: 500, offset });
8390
+ const page = await store.list({ objectId: coordinate.objectId, kind: wikiKind === 'way' ? 'procedure' : 'fact', actionId: coordinate.actionId, sceneId: coordinate.sceneId, excludeWithdrawn: true, limit: 500, offset });
8275
8391
  raw.push(...page.knowledge);
8276
8392
  if (offset + page.knowledge.length >= page.total)
8277
8393
  break;
@@ -8285,7 +8401,7 @@ export class KnowledgeRuntime {
8285
8401
  bodies.set(id, { version: source.version, content: source.record.content });
8286
8402
  }
8287
8403
  const rows = raw
8288
- .filter(row => row.status !== 'deprecated' && (row.kind !== 'procedure' || (row.data?.procedure?.completeness === 'complete' && row.data.procedure.method.length > 0 && row.status !== 'disputed' && row.data.procedure.caseRefs.every(ref => db.event(ref.id)?.version === ref.version) && !row.sources.some(source => source.toVersion !== undefined && db.source(source.documentId)?.version !== source.toVersion))))
8404
+ .filter(row => row.status !== 'deprecated' && (row.kind !== 'procedure' || (row.data?.procedure?.completeness === 'complete' && row.data.procedure.method.length > 0 && row.status !== 'disputed' && row.data.procedure.caseRefs.every(ref => db.event(ref.id)?.version === ref.version) && !row.sources.some(source => !source.withdrawn && source.toVersion !== undefined && db.source(source.documentId)?.version !== source.toVersion))))
8289
8405
  .map(row => assessKnowledgeEvidence(row, db, bodies))
8290
8406
  .map(row => ({ ...row, sources: row.sources.filter(source => !source.withdrawn && source.evidenceStatus !== 'missing') }))
8291
8407
  .filter(row => row.sources.length > 0);
@@ -8308,10 +8424,11 @@ export class KnowledgeRuntime {
8308
8424
  const grouped = new Map();
8309
8425
  let blockedAmbiguous = 0;
8310
8426
  let blockedAwaitingNormalize = 0;
8311
- const groupFor = (coordinate) => {
8312
- const key = coordinateKeyOf(coordinate);
8427
+ const blockedItems = [];
8428
+ const groupFor = (coordinate, wikiKind) => {
8429
+ const key = wikiGroupKey(wikiKind, coordinate);
8313
8430
  if (!grouped.has(key))
8314
- grouped.set(key, { coordinate, knowledge: [] });
8431
+ grouped.set(key, { coordinate, wikiKind, knowledge: [] });
8315
8432
  return grouped.get(key);
8316
8433
  };
8317
8434
  const caseStore = await this.storeHandle();
@@ -8322,9 +8439,10 @@ export class KnowledgeRuntime {
8322
8439
  const method = row.data?.procedure;
8323
8440
  if (!coordinate || (row.kind === 'procedure' && (!method || method.completeness !== 'complete' || !method.method.length || row.status === 'disputed' || method.caseRefs.some(ref => caseStore?.event(ref.id)?.version !== ref.version) || row.sources.some(source => source.toVersion !== undefined && caseStore?.source(source.documentId)?.version !== source.toVersion)))) {
8324
8441
  blockedAmbiguous += 1;
8442
+ blockedItems.push({ knowledgeId: row.id, sourceIds: [...new Set(row.sources.map(source => source.documentId).filter(Boolean))], ...(coordinate ? { groupKey: wikiGroupKey(row.kind === 'procedure' ? 'way' : 'fact', coordinate) } : {}) });
8325
8443
  continue;
8326
8444
  }
8327
- groupFor(coordinate).knowledge.push(row);
8445
+ groupFor(coordinate, row.kind === 'procedure' ? 'way' : 'fact').knowledge.push(row);
8328
8446
  }
8329
8447
  const db = await this.storeHandle();
8330
8448
  const events = new Map();
@@ -8332,17 +8450,17 @@ export class KnowledgeRuntime {
8332
8450
  const coordinate = event.coordinateIds;
8333
8451
  if (!coordinate.objectId)
8334
8452
  continue;
8335
- for (const projection of [wikiProjection('fact', coordinate), wikiProjection('procedure', coordinate)]) {
8336
- if (!projection)
8337
- continue;
8338
- const key = coordinateKeyOf(projection);
8453
+ for (const kind of ['fact', 'way']) {
8454
+ const key = wikiGroupKey(kind, coordinate);
8339
8455
  const bucket = events.get(key) ?? [];
8340
8456
  bucket.push(event);
8341
8457
  events.set(key, bucket);
8342
8458
  }
8343
8459
  }
8344
8460
  const cards = await this.loadCards();
8345
- const byCoordinate = new Map(cards.filter(card => card.coordinate).map(card => [coordinateKeyOf(card.coordinate), card]));
8461
+ const groupKeyOf = (card) => card.coordinate && (card.metadata.wiki_kind === 'fact' || card.metadata.wiki_kind === 'way')
8462
+ ? wikiGroupKey(card.metadata.wiki_kind, card.coordinate) : card.coordinate ? coordinateKeyOf(card.coordinate) : '';
8463
+ const byCoordinate = new Map(cards.filter(card => card.coordinate).map(card => [groupKeyOf(card), card]));
8346
8464
  const groups = [];
8347
8465
  const knowledge = new Map();
8348
8466
  for (const [key, value] of grouped) {
@@ -8357,12 +8475,14 @@ export class KnowledgeRuntime {
8357
8475
  if (needsNormalization)
8358
8476
  blockedAwaitingNormalize += value.knowledge.length;
8359
8477
  knowledge.set(key, value.knowledge);
8360
- groups.push({ key, wikiKind: value.coordinate.actionId ? 'way' : 'fact', title: existing?.title ?? `${names.object}${names.action ? ` · ${names.action}` : ''} · ${value.coordinate.actionId ? 'Wiki Way' : 'Wiki Fact'}`, coordinate: value.coordinate, knowledgeCount: value.knowledge.length, eventCount: events.get(key)?.length ?? 0, sourceIds: contributingSources, ...(existing ? { cardId: existing.entityId } : {}), state: needsNormalization ? 'blocked' : current ? 'current' : existing ? 'changed' : 'new', ...(needsNormalization ? { reason: '分组中的来源已变化、新抽取待归一或坐标有歧义,请先完成归一' } : {}), fingerprint });
8478
+ groups.push({ key, wikiKind: value.wikiKind, title: existing?.title ?? `${names.object}${names.action ? ` · ${names.action}` : ''}${names.scene ? ` · ${names.scene}` : ''} · ${value.wikiKind === 'way' ? 'Wiki Way' : 'Wiki Fact'}`, coordinate: value.coordinate, knowledgeCount: value.knowledge.length, eventCount: events.get(key)?.length ?? 0, sourceIds: contributingSources, ...(existing ? { cardId: existing.entityId } : {}), state: needsNormalization ? 'blocked' : current ? 'current' : existing ? 'changed' : 'new', ...(needsNormalization ? { reason: '分组中的来源已变化、新抽取待归一或坐标有歧义,请先完成归一' } : {}), fingerprint });
8361
8479
  }
8362
8480
  for (const card of cards) {
8363
- if (!card.coordinate || grouped.has(coordinateKeyOf(card.coordinate)) || !store.materialization(coordinateKeyOf(card.coordinate)) || card.status === 'deprecated')
8481
+ const key = groupKeyOf(card);
8482
+ const legacyReceipt = card.coordinate ? store.materialization(coordinateKeyOf(card.coordinate)) : undefined;
8483
+ if (!card.coordinate || grouped.has(key) || (!store.materialization(key) && !legacyReceipt && card.metadata.pipeline_materialization !== true) || card.status === 'deprecated')
8364
8484
  continue;
8365
- groups.push({ key: coordinateKeyOf(card.coordinate), title: card.title, coordinate: card.coordinate, knowledgeCount: 0, eventCount: 0, sourceIds: card.sourceRefs, cardId: card.entityId, state: card.sourceRefs.some(id => unresolved.sources.has(id)) ? 'blocked' : 'withdrawn', ...(card.sourceRefs.some(id => unresolved.sources.has(id)) ? { reason: '来源中的坐标仍有歧义,请先完成归一' } : {}), fingerprint: 'withdrawn' });
8485
+ groups.push({ key, wikiKind: card.metadata.wiki_kind === 'way' ? 'way' : 'fact', title: card.title, coordinate: card.coordinate, knowledgeCount: 0, eventCount: 0, sourceIds: card.sourceRefs, cardId: card.entityId, state: card.sourceRefs.some(id => unresolved.sources.has(id)) ? 'blocked' : 'withdrawn', ...(card.sourceRefs.some(id => unresolved.sources.has(id)) ? { reason: '来源中的坐标仍有歧义,请先完成归一' } : {}), fingerprint: 'withdrawn' });
8366
8486
  }
8367
8487
  const sources = plans ? (await this.loadSources()).map(source => ({ sourceId: source.sourceId, content: source.content })) : [];
8368
8488
  const imagePlan = plans
@@ -8393,7 +8513,7 @@ export class KnowledgeRuntime {
8393
8513
  return {
8394
8514
  groups: groups.sort((a, b) => a.title.localeCompare(b.title)),
8395
8515
  blocked: blockedAmbiguous + blockedAwaitingNormalize,
8396
- blockedAmbiguous, blockedAwaitingNormalize,
8516
+ blockedAmbiguous, blockedAwaitingNormalize, blockedItems,
8397
8517
  knowledge, events, sources, images: imagePlan.byCard, related: relatedByKey,
8398
8518
  };
8399
8519
  }
@@ -8429,7 +8549,7 @@ export class KnowledgeRuntime {
8429
8549
  throw new Error('卡片在处理期间已被删除,本次物化未提交,请刷新后重试');
8430
8550
  if (statusBeforeDeprecate !== existing.status)
8431
8551
  throw new Error(`卡片在处理期间被人工改动(状态 ${existing.status} → ${statusBeforeDeprecate}),本次物化未提交,请重试`);
8432
- const written = await this.writeCard({ ...existing, status: 'deprecated', origin: 'compile' });
8552
+ const written = await this.writeCard({ ...existing, metadata: { ...existing.metadata, wiki_deprecation_origin: existing.status === 'deprecated' && existing.metadata.wiki_deprecation_origin !== 'withdrawal' ? 'manual' : 'withdrawal' }, status: 'deprecated', origin: 'compile' });
8433
8553
  if (!written.ok)
8434
8554
  throw new Error(written.error.message);
8435
8555
  store.materialized(group.key, group.fingerprint, existing.entityId);
@@ -8449,7 +8569,7 @@ export class KnowledgeRuntime {
8449
8569
  let content = knowledge.map(row => `## ${row.data?.procedure?.question ?? row.text.split('\n')[0].slice(0, 60)}\n\n${this.organizeKnowledgeText(row)}[^${row.id}]${boundaries.get(row.id) ? `\n\n### 适用条件与边界\n\n${boundaries.get(row.id)}` : ''}`).join('\n\n');
8450
8570
  let summary = knowledge[0]?.text ?? '';
8451
8571
  let placements = knowledge.map((row, index) => ({ knowledgeId: row.id, section: row.data?.procedure?.question ?? row.text.split('\n')[0].slice(0, 60), ordinal: index + 1, origin: 'compiler' }));
8452
- let metadata = { ...(existing?.metadata ?? {}), pipeline_materialization: true, wiki_kind: group.wikiKind ?? (group.coordinate.actionId ? 'way' : 'fact') };
8572
+ let metadata = { ...(existing?.metadata ?? {}), pipeline_materialization: true, wiki_kind: group.wikiKind ?? 'fact', wiki_coordinate_version: 2, knowledge_versions: Object.fromEntries(knowledge.map(row => [row.id, row.version])) };
8453
8573
  const entityId = existing?.entityId ?? `coord-${hash(group.key)}`;
8454
8574
  const images = snapshot.images.get(group.key) ?? [];
8455
8575
  const related = existing && snapshot.related.has(group.key) ? { related: snapshot.related.get(group.key) } : {};
@@ -8482,7 +8602,7 @@ export class KnowledgeRuntime {
8482
8602
  */
8483
8603
  if (this.needsNormalizationForGroup(store, knowledge, store.unresolvedKnowledge(), db))
8484
8604
  throw new Error('卡片组织期间事实发生变化,结果未提交,请重试');
8485
- if (await this.freshGroupFingerprint(group.coordinate, context, db) !== group.fingerprint)
8605
+ if (await this.freshGroupFingerprint(group.coordinate, group.wikiKind ?? 'fact', context, db) !== group.fingerprint)
8486
8606
  throw new Error('卡片分组在处理期间事实发生了变化,结果未提交,请重试');
8487
8607
  if (this.closed)
8488
8608
  throw new Error('知识库已关闭,本次物化未提交');
@@ -8501,7 +8621,8 @@ export class KnowledgeRuntime {
8501
8621
  if (statusAtWrite !== existing?.status) {
8502
8622
  throw new Error(`卡片在处理期间被人工改动(状态 ${existing?.status ?? '未知'} → ${statusAtWrite ?? '未知'}),本次物化未提交,请重试`);
8503
8623
  }
8504
- const written = await this.writeCard({ entityType, entityId, title, content, summary, sourceRefs: group.sourceIds, status: statusAtWrite === 'deprecated' ? 'unreviewed' : statusAtWrite ?? 'unreviewed', coordinate: group.coordinate, placements, metadata, origin: 'compile' });
8624
+ const nextStatus = statusAtWrite === 'deprecated' && existing?.metadata.wiki_deprecation_origin === 'withdrawal' ? 'unreviewed' : statusAtWrite ?? 'unreviewed';
8625
+ const written = await this.writeCard({ entityType, entityId, title, content, summary, sourceRefs: group.sourceIds, status: nextStatus, coordinate: group.coordinate, placements, metadata, origin: 'compile' });
8505
8626
  if (!written.ok)
8506
8627
  throw new Error(written.error.message);
8507
8628
  db.setCardEvents(entityId, eventIds);
@@ -8521,7 +8642,7 @@ export class KnowledgeRuntime {
8521
8642
  card: {
8522
8643
  id: entityId,
8523
8644
  title,
8524
- status: statusAtWrite === 'deprecated' ? 'unreviewed' : statusAtWrite ?? 'unreviewed',
8645
+ status: nextStatus,
8525
8646
  characters: content.length,
8526
8647
  events: eventIds.length,
8527
8648
  images: images.length,
@@ -8544,7 +8665,9 @@ export class KnowledgeRuntime {
8544
8665
  const db = await this.derivedHandle();
8545
8666
  const manifest = db?.artifact('build-manifest.json');
8546
8667
  const hashes = manifest ? JSON.parse(manifest).cardHashes ?? {} : {};
8547
- const cards = await this.loadCards();
8668
+ const allCards = await this.loadCards();
8669
+ const unavailable = await this.wikiUnavailability(allCards);
8670
+ const cards = allCards.filter(card => !card.metadata.wiki_kind || !unavailable.has(cardKey(card)));
8548
8671
  const indexPending = cards.some(card => hashes[`${card.entityType}:${card.entityId}`] !== this.cardHashOf(card)) || Object.keys(hashes).length !== cards.length;
8549
8672
  return { sources: rows, groups, blocked, pendingNew: groups.filter(group => group.state === 'new').length, pendingUpdated: groups.filter(group => group.state === 'changed').length, pendingWithdrawn: groups.filter(group => group.state === 'withdrawn').length, indexPending };
8550
8673
  }
@@ -8787,6 +8910,9 @@ export class KnowledgeRuntime {
8787
8910
  };
8788
8911
  this.publication.artifacts.set(COMPILE_SNAPSHOT, JSON.stringify(snapshot));
8789
8912
  await this.checkpointCompileTask(runId);
8913
+ const changedWiki = await this.wikiUnavailability(snapshot.cards, new Map(snapshot.placements));
8914
+ if (snapshot.cards.some(card => card.metadata.wiki_kind && changedWiki.has(cardKey(card))))
8915
+ throw new Error('WIKI_CHANGED_DURING_BUILD: Wiki 的支撑知识在构建期间变化,请重新组织并构建索引');
8790
8916
  if (JSON.stringify({ config: this.config, fingerprint: this.embeddingFingerprint() }) !== configAtStart)
8791
8917
  throw new Error('COMPILE_CONFIG_CHANGED: 编译期间设置已变化,请重新编译');
8792
8918
  await options.checkpoint?.();
@@ -8797,6 +8923,8 @@ export class KnowledgeRuntime {
8797
8923
  }
8798
8924
  finally {
8799
8925
  this.publication = undefined;
8926
+ // Compilation filters unavailable projections; the browsing cache still represents all saved Wiki.
8927
+ this.cards = await this.loadCards();
8800
8928
  }
8801
8929
  }
8802
8930
  async prepareCompile(runId, only = 'all', lineage, options = {}) {
@@ -9067,6 +9195,11 @@ export class KnowledgeRuntime {
9067
9195
  // 相关 metadata 或旧正文清理刚落盘:stage 2 必须看到最新卡片。
9068
9196
  if (finalize.rewritten > 0)
9069
9197
  this.cards = await this.loadCards();
9198
+ const unavailableWiki = await this.wikiUnavailability(this.cards);
9199
+ for (const card of this.cards)
9200
+ if (card.metadata.wiki_kind && unavailableWiki.has(cardKey(card)))
9201
+ warnings.push(`Wiki「${card.title}」未进入索引:${unavailableWiki.get(cardKey(card))}`);
9202
+ this.cards = this.cards.filter(card => !card.metadata.wiki_kind || !unavailableWiki.has(cardKey(card)));
9070
9203
  /**
9071
9204
  * 索引页也是这次编译的产物,所以它变了也算「语料变了」。
9072
9205
  *
@@ -9485,12 +9618,11 @@ export class KnowledgeRuntime {
9485
9618
  }
9486
9619
  }
9487
9620
  /**
9488
- * Coordinate 路:先解析 Query 中出现的 Object / Action / Scene,再把命中的卡片拆成
9621
+ * Coordinate 路:解析 Query 中出现的 Object / Action / Scene,再把命中的卡片拆成
9489
9622
  * Section 候选。它和 FTS / Vector 使用同一个 `unitId` 粒度,后面才能统一 RRF 与重排。
9490
9623
  *
9491
9624
  * 这里不让模型自由生成实体名:注册表负责 canonical / alias 命中,只有真实存在的
9492
- * 坐标 id 才能进入候选。意图目前使用轻量规则分类,结果会随 queryAnalysis 一起返回,
9493
- * 后续接入模型消歧时不需要改变召回合同。
9625
+ * 坐标 id 才能进入候选。未解析的原文继续交给关键词、向量路线与统一重排。
9494
9626
  */
9495
9627
  async coordinateRoute(query, eligible, cards, pool) {
9496
9628
  const registry = await this.axisRegistry();
@@ -10113,21 +10245,9 @@ export class KnowledgeRuntime {
10113
10245
  if (snapshotCardByKey.get(key)?.sourceRefs.some(ref => !liveSourceIds.has(ref)))
10114
10246
  liveKeys.delete(key);
10115
10247
  }
10116
- // A method becomes unavailable immediately when its supporting Case or structured content changes.
10117
- // Do not wait for a later rebuild to stop serving the old instructions.
10118
- const unsafeProcedures = new Set(snapshot.knowledge.filter(row => {
10119
- if (row.kind !== 'procedure')
10120
- return false;
10121
- const current = truthAtRead?.raw('SELECT status,head_version FROM knowledge WHERE id=?').get(row.id);
10122
- return !current || current.status === 'deprecated' || current.status === 'disputed' || current.head_version !== row.version
10123
- || !row.data?.procedure || row.data.procedure.completeness !== 'complete'
10124
- || row.data.procedure.caseRefs.some(ref => truthAtRead?.event(ref.id)?.version !== ref.version)
10125
- || row.sources.some(source => source.toVersion !== undefined && truthAtRead?.source(source.documentId)?.version !== source.toVersion);
10126
- }).map(row => row.id));
10127
- const unsafeCardIds = new Set(snapshot.placements.filter(([, placements]) => placements.some(p => unsafeProcedures.has(p.knowledgeId))).map(([id]) => id));
10128
- for (const key of liveKeys)
10129
- if (unsafeCardIds.has(snapshotCardByKey.get(key)?.entityId ?? ''))
10130
- liveKeys.delete(key);
10248
+ const unavailableWiki = await this.wikiUnavailability(snapshot.cards, new Map(snapshot.placements));
10249
+ for (const key of unavailableWiki.keys())
10250
+ liveKeys.delete(key);
10131
10251
  let publishedGraph = visibleGraph(snapshot.graph, truthAtRead ? liveGraphKeys(truthAtRead) : new Set());
10132
10252
  const currentByKey = new Map(liveCards.map(card => [cardKey(card), card]));
10133
10253
  let cards = snapshot.cards.filter(card => liveKeys.has(cardKey(card))).map(card => {
@@ -10244,9 +10364,6 @@ export class KnowledgeRuntime {
10244
10364
  else {
10245
10365
  const rerankQuery = [
10246
10366
  query,
10247
- ...(queryAnalysis.intent.id !== 'unknown' && queryAnalysis.intent.confidence >= 0.7
10248
- ? [`意图:${queryAnalysis.intent.id}`]
10249
- : []),
10250
10367
  ...['object', 'action', 'scene'].flatMap(kind => {
10251
10368
  const values = queryAnalysis.axes[kind].map(item => item.name).slice(0, 3);
10252
10369
  return values.length > 0 ? [`${kind}:${values.join('、')}`] : [];
@@ -10388,8 +10505,7 @@ export class KnowledgeRuntime {
10388
10505
  /**
10389
10506
  * 上下文预算(0050):装箱 + 溢出。
10390
10507
  *
10391
- * 让位顺序写死在 `packContext` 里:先保证命中 note 的正文完整(它是证据),
10392
- * 再给扩展卡片的标题 + 摘要 + 关系,最后才给扩展卡片的正文。
10508
+ * 让位顺序写死在 `packContext` 里:优先交付命中的完整 Wiki,再交付扩展 Wiki。
10393
10509
  */
10394
10510
  /**
10395
10511
  * 每次调用可以覆盖预算(0050):指路行里就写着「读不到就调大预算重新召回」,
@@ -10397,6 +10513,15 @@ export class KnowledgeRuntime {
10397
10513
  */
10398
10514
  const maxChars = options.contextMaxChars ?? this.config.contextMaxChars;
10399
10515
  const packed = await this.packContext({ items, maxChars, recallId });
10516
+ const deliveredKeys = new Set(packed.items.flatMap(item => item.wiki ? [cardKey(item.wiki)] : []));
10517
+ // Diagnostic HTTP requests may inspect unbudgeted candidate text. Normal delivery cannot leak it.
10518
+ const deliveredHits = options.detail ? hits : hits.map(hit => {
10519
+ if (deliveredKeys.has(wikiKey(hit)))
10520
+ return hit;
10521
+ const { evidence: _evidence, knowledge: _knowledge, ...reference } = hit;
10522
+ return { ...reference, content: '' };
10523
+ });
10524
+ const deliveredWiki = options.detail ? wiki : wiki.filter(card => deliveredKeys.has(cardKey(card)));
10400
10525
  /** 哪些扩展卡片真的进了上下文(被预算挡住的也如实报出来)。 */
10401
10526
  expansion.included = packed.items
10402
10527
  .filter(item => item.reason === 'expansion' && item.wiki !== null)
@@ -10456,7 +10581,7 @@ export class KnowledgeRuntime {
10456
10581
  totalMs: round1(performance.now() - startedAt),
10457
10582
  };
10458
10583
  const data = {
10459
- hits, context: packed.items, wiki, graph, backend, routes: ranRoutes, recallMode, rerank, recallTopK, candidatePool, fusedCount, contextTopN,
10584
+ hits: deliveredHits, context: packed.items, wiki: deliveredWiki, graph, backend, routes: ranRoutes, recallMode, rerank, recallTopK, candidatePool, fusedCount, contextTopN,
10460
10585
  queryAnalysis,
10461
10586
  insufficientEvidence, diagnostics, recallId, timings,
10462
10587
  expansion, budget: packed.report,