dsh-data-domain-knowledge 0.1.0-alpha.2 → 0.1.0-alpha.4

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 (180) hide show
  1. package/README.md +147 -19
  2. package/cordis.patch.yml +25 -10
  3. package/lib/client.js +6400 -3326
  4. package/lib/doc-page.js +7761 -0
  5. package/lib/types/convert/host.d.ts.map +1 -1
  6. package/lib/types/convert/host.js +63 -11
  7. package/lib/types/convert/host.js.map +1 -1
  8. package/lib/types/convert/ingest.d.ts +7 -4
  9. package/lib/types/convert/ingest.d.ts.map +1 -1
  10. package/lib/types/convert/ingest.js +52 -14
  11. package/lib/types/convert/ingest.js.map +1 -1
  12. package/lib/types/convert/types.d.ts +2 -2
  13. package/lib/types/convert/types.d.ts.map +1 -1
  14. package/lib/types/convert/types.js +2 -2
  15. package/lib/types/convert/types.js.map +1 -1
  16. package/lib/types/diagnosis/cards.d.ts +8 -7
  17. package/lib/types/diagnosis/cards.d.ts.map +1 -1
  18. package/lib/types/diagnosis/cards.js +119 -49
  19. package/lib/types/diagnosis/cards.js.map +1 -1
  20. package/lib/types/diagnosis/run.d.ts +57 -0
  21. package/lib/types/diagnosis/run.d.ts.map +1 -0
  22. package/lib/types/diagnosis/run.js +245 -0
  23. package/lib/types/diagnosis/run.js.map +1 -0
  24. package/lib/types/diagnosis/schema.d.ts +25 -2
  25. package/lib/types/diagnosis/schema.d.ts.map +1 -1
  26. package/lib/types/diagnosis/schema.js +64 -25
  27. package/lib/types/diagnosis/schema.js.map +1 -1
  28. package/lib/types/diagnosis/seed-source.d.ts +17 -2
  29. package/lib/types/diagnosis/seed-source.d.ts.map +1 -1
  30. package/lib/types/diagnosis/seed-source.js +19 -2
  31. package/lib/types/diagnosis/seed-source.js.map +1 -1
  32. package/lib/types/diagnosis/seed.d.ts +32 -42
  33. package/lib/types/diagnosis/seed.d.ts.map +1 -1
  34. package/lib/types/diagnosis/seed.js +187 -51
  35. package/lib/types/diagnosis/seed.js.map +1 -1
  36. package/lib/types/diagnosis/store.d.ts +95 -25
  37. package/lib/types/diagnosis/store.d.ts.map +1 -1
  38. package/lib/types/diagnosis/store.js +297 -166
  39. package/lib/types/diagnosis/store.js.map +1 -1
  40. package/lib/types/diagnosis/types.d.ts +168 -16
  41. package/lib/types/diagnosis/types.d.ts.map +1 -1
  42. package/lib/types/diagnosis/types.js +1 -1
  43. package/lib/types/diagnosis/types.js.map +1 -1
  44. package/lib/types/document-page.d.ts +39 -0
  45. package/lib/types/document-page.d.ts.map +1 -0
  46. package/lib/types/document-page.js +43 -0
  47. package/lib/types/document-page.js.map +1 -0
  48. package/lib/types/extract-model.d.ts +67 -27
  49. package/lib/types/extract-model.d.ts.map +1 -1
  50. package/lib/types/extract-model.js +225 -97
  51. package/lib/types/extract-model.js.map +1 -1
  52. package/lib/types/extract.d.ts +16 -0
  53. package/lib/types/extract.d.ts.map +1 -1
  54. package/lib/types/extract.js +19 -2
  55. package/lib/types/extract.js.map +1 -1
  56. package/lib/types/fs-atomic.d.ts +11 -0
  57. package/lib/types/fs-atomic.d.ts.map +1 -0
  58. package/lib/types/fs-atomic.js +41 -0
  59. package/lib/types/fs-atomic.js.map +1 -0
  60. package/lib/types/index.d.ts.map +1 -1
  61. package/lib/types/index.js +466 -63
  62. package/lib/types/index.js.map +1 -1
  63. package/lib/types/intent/types.js +1 -1
  64. package/lib/types/intent/types.js.map +1 -1
  65. package/lib/types/knowledge-bases.d.ts +23 -12
  66. package/lib/types/knowledge-bases.d.ts.map +1 -1
  67. package/lib/types/knowledge-bases.js +37 -44
  68. package/lib/types/knowledge-bases.js.map +1 -1
  69. package/lib/types/layout.d.ts +3 -3
  70. package/lib/types/layout.d.ts.map +1 -1
  71. package/lib/types/layout.js +4 -4
  72. package/lib/types/layout.js.map +1 -1
  73. package/lib/types/migrate.d.ts +1 -1
  74. package/lib/types/migrate.js +2 -2
  75. package/lib/types/migrate.js.map +1 -1
  76. package/lib/types/model-text.d.ts +99 -0
  77. package/lib/types/model-text.d.ts.map +1 -0
  78. package/lib/types/model-text.js +103 -0
  79. package/lib/types/model-text.js.map +1 -0
  80. package/lib/types/present.d.ts +239 -0
  81. package/lib/types/present.d.ts.map +1 -0
  82. package/lib/types/present.js +255 -0
  83. package/lib/types/present.js.map +1 -0
  84. package/lib/types/recall-rank.d.ts +37 -0
  85. package/lib/types/recall-rank.d.ts.map +1 -1
  86. package/lib/types/recall-rank.js +41 -1
  87. package/lib/types/recall-rank.js.map +1 -1
  88. package/lib/types/runtime.d.ts +564 -31
  89. package/lib/types/runtime.d.ts.map +1 -1
  90. package/lib/types/runtime.js +2645 -292
  91. package/lib/types/runtime.js.map +1 -1
  92. package/lib/types/settings-schema.d.ts +4 -2
  93. package/lib/types/settings-schema.d.ts.map +1 -1
  94. package/lib/types/settings-schema.js +2 -0
  95. package/lib/types/settings-schema.js.map +1 -1
  96. package/lib/types/source-images.d.ts +118 -0
  97. package/lib/types/source-images.d.ts.map +1 -0
  98. package/lib/types/source-images.js +288 -0
  99. package/lib/types/source-images.js.map +1 -0
  100. package/lib/types/types.d.ts +356 -28
  101. package/lib/types/types.d.ts.map +1 -1
  102. package/lib/types/types.js +112 -18
  103. package/lib/types/types.js.map +1 -1
  104. package/lib/types/wiki-finalize.d.ts +140 -0
  105. package/lib/types/wiki-finalize.d.ts.map +1 -0
  106. package/lib/types/wiki-finalize.js +269 -0
  107. package/lib/types/wiki-finalize.js.map +1 -0
  108. package/lib/types/wiki-types.d.ts +10 -2
  109. package/lib/types/wiki-types.d.ts.map +1 -1
  110. package/lib/types/wiki-types.js +27 -30
  111. package/lib/types/wiki-types.js.map +1 -1
  112. package/package.json +4 -3
  113. package/preset/tita-data-agent/agent.cordis.yml +25 -10
  114. package/src/client/DirectoryPicker.tsx +12 -12
  115. package/src/client/DrawerSection.tsx +18 -0
  116. package/src/client/InfoHint.tsx +21 -8
  117. package/src/client/IntentTab.tsx +20 -26
  118. package/src/client/KnowledgeBaseTab.tsx +458 -158
  119. package/src/client/KnowledgePanel.tsx +44 -10
  120. package/src/client/KnowledgeStepRail.tsx +3 -0
  121. package/src/client/KnowledgeToolRow.tsx +331 -0
  122. package/src/client/NodeSettings.tsx +20 -22
  123. package/src/client/PreviewSections.tsx +178 -43
  124. package/src/client/RecallPanel.tsx +418 -127
  125. package/src/client/TypeDefinitionDrawer.tsx +154 -54
  126. package/src/client/WikiCardReview.tsx +266 -0
  127. package/src/client/WikiFlowCard.tsx +57 -95
  128. package/src/client/WikiTypeEditor.tsx +197 -95
  129. package/src/client/arch/AgentArchitectureGraph.tsx +30 -14
  130. package/src/client/arch/NodeLogicPanel.tsx +6 -3
  131. package/src/client/arch/model.ts +164 -26
  132. package/src/client/architecture.css +25 -10
  133. package/src/client/architecture.tsx +66 -41
  134. package/src/client/asset-images.ts +125 -0
  135. package/src/client/attribution/AttributionGraph.tsx +481 -34
  136. package/src/client/attribution/AttributionTab.tsx +501 -106
  137. package/src/client/attribution/CaseView.tsx +9 -14
  138. package/src/client/attribution/GraphStage.tsx +25 -18
  139. package/src/client/attribution/RunView.tsx +27 -9
  140. package/src/client/attribution/StageChrome.tsx +280 -140
  141. package/src/client/attribution/graph-options.ts +611 -47
  142. package/src/client/attribution/model.ts +559 -30
  143. package/src/client/convert/ConvertPanel.tsx +36 -4
  144. package/src/client/doc-page.css +134 -0
  145. package/src/client/doc-page.tsx +242 -0
  146. package/src/client/index.ts +18 -0
  147. package/src/client/panel-state.ts +105 -0
  148. package/src/client/problem-domains.ts +1 -1
  149. package/src/client/request.ts +36 -0
  150. package/src/client/styles.css +397 -54
  151. package/src/client/useFitScale.ts +15 -2
  152. package/src/client/wiki-type-groups.ts +86 -0
  153. package/src/convert/host.ts +68 -9
  154. package/src/convert/ingest.ts +61 -18
  155. package/src/convert/types.ts +2 -2
  156. package/src/diagnosis/cards.ts +120 -50
  157. package/src/diagnosis/run.ts +251 -0
  158. package/src/diagnosis/schema.ts +67 -26
  159. package/src/diagnosis/seed-source.ts +29 -4
  160. package/src/diagnosis/seed.ts +187 -85
  161. package/src/diagnosis/store.ts +310 -173
  162. package/src/diagnosis/types.ts +181 -16
  163. package/src/document-page.ts +51 -0
  164. package/src/extract-model.ts +254 -99
  165. package/src/extract.ts +35 -3
  166. package/src/fs-atomic.ts +41 -0
  167. package/src/index.ts +499 -62
  168. package/src/intent/types.ts +1 -1
  169. package/src/knowledge-bases.ts +50 -49
  170. package/src/layout.ts +4 -4
  171. package/src/migrate.ts +2 -2
  172. package/src/model-text.ts +126 -0
  173. package/src/present.ts +367 -0
  174. package/src/recall-rank.ts +57 -2
  175. package/src/runtime.ts +2802 -293
  176. package/src/settings-schema.ts +2 -0
  177. package/src/source-images.ts +326 -0
  178. package/src/types.ts +446 -45
  179. package/src/wiki-finalize.ts +310 -0
  180. package/src/wiki-types.ts +28 -32
@@ -1,37 +1,38 @@
1
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
1
+ import { readFile, readdir } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { SEED_CASES, SEED_GRAPH } from './seed.js';
4
4
  import { seedSources } from './seed-source.js';
5
- import { DIAGNOSIS_ENTITIES, templateCard, validateDiagnosis } from './schema.js';
6
- import { cardsToGraph, cardPathOf, graphToCards, parseCard, serializeCard, RUN_EDGE_KINDS, } from './cards.js';
5
+ import { validateDiagnosis } from './schema.js';
6
+ import { cardsToGraph, CARD_EDGE_KINDS, graphToCards, parseCard, serializeCard, RUN_EDGE_KINDS, } from './cards.js';
7
+ import { caseCardOf, parseRunSource, renderRunSource, runReferenceProblems, runToGraph } from './run.js';
7
8
  /**
8
- * `05_diagnosis/` 的落盘与读取(v0.7 起:**卡片才是真相,这里只放一次排查的产物**)。
9
+ * 排查知识的读取与写入(v1.1 起:**没有 `05_diagnosis/` 了**)。
9
10
  *
10
- * ## 为什么要改
11
- *
12
- * 改版前这里同时扮演两个角色:既是 seed 写出来的 jsonl 数据集,又被当成图的唯一来源。
13
- * 后果是排查思路**从来没进过 wiki** —— 不在 `01_source_truth`、不是 `02_wiki` 的卡片、
14
- * 编译器不认它的 entity_type,于是不会被 wikiNote 化、不会进向量索引,**永远召不回来**。
15
- * 而 `store.ts` 顶上那句「全部内容都能从 wiki 卡片确定性重建」描述的其实是目标状态,
16
- * 代码走的是相反的路径。
17
- *
18
- * ## 现在的分工
11
+ * ## 三段,各一个答案
19
12
  *
20
13
  * | 目录 | 内容 | 谁是真相 |
21
14
  * | --- | --- | --- |
22
- * | `01_source_truth/` | 手册与复盘原文(`sourceType=question`) | 人写的原始材料 |
23
- * | `02_wiki/diagnosis/` | 五类卡片(三段式) | **知识侧的唯一真相** |
24
- * | `05_diagnosis/` | `evidence` / `cause` / 执行边(`produces` `supports` `refutes` `confirmed_as`)与模板卡 | 一次排查的产物 |
15
+ * | `01_source_raw/question/` | 手册与复盘原文 | 人写的原始材料 |
16
+ * | `01_source_raw/agent_diagnosis_case/` | 一次排查的过程记录(一条 SourceRaw) | Agent 跑出来的原始记录 |
17
+ * | `02_wiki/diagnosis/` | 五类卡片(三段式) | **知识侧的唯一真相**,由一次排查 / 载入示例 / 迁移直接写入(0044 起不经人确认) |
18
+ *
19
+ * `05_diagnosis/` 在 v1.1 撤销了(0021 §0.3)。它同时装着两类东西 —— 「一次排查的产物」
20
+ * (源头)与「五类模板卡」(配置)—— 一个编号段混装两种性质,`rebuild --only` 的语义
21
+ * 立刻含糊。而且它自造的 jsonl 过不了 `source_refs` 那道门:卡片要求引用**真实存在的
22
+ * SourceRaw**,jsonl 不是。
23
+ *
24
+ * 旧的 `05_diagnosis/*.jsonl` 因此降为**只读的迁移输入与历史快照**:还在,还能读,
25
+ * 但不再被写、也不再是任何东西的真相。
26
+ *
27
+ * ## 读取顺序是显式的(`snapshot().source` 会把它报给界面)
25
28
  *
26
- * 读取顺序是显式的:**有卡片就编译卡片;没有卡片但有旧 jsonl 就按旧格式读出来(并尝试
27
- * 前向迁移);两者都没有才灌 seed**。老知识根不会因为这次改动而读不出内容。
29
+ * 1. 有卡片 → 卡片 + 一次排查的 SourceRaw;
30
+ * 2. 没有卡片但有旧 jsonl → 按旧格式读出来(并尝试**无损**前向迁移);
31
+ * 3. 两者都没有 → **什么都不写**:空态 + 「载入内置示例」按钮。
28
32
  */
29
- const DIR = '05_diagnosis';
30
- /** 一次排查写下的节点:它们不是知识,所以留在这里,不进卡片。 */
31
- const RUN_NODE_SHARDS = {
32
- 'evidence.jsonl': 'evidence',
33
- 'causes.jsonl': 'cause',
34
- };
33
+ const LEGACY_DIR = '05_diagnosis';
34
+ /** 一次排查的产物:`01_source_raw/<这个分类>/`。 */
35
+ const RUN_SOURCE_TYPE = 'agent_diagnosis_case';
35
36
  /**
36
37
  * 旧版的类型层分片。**只读,不再写**:v0.7 之前它们就是真相,现在它们的角色是
37
38
  * 「迁移输入 + 历史快照」。迁移成功后内容已经在卡片里,这些文件保持原样以便追溯。
@@ -39,28 +40,22 @@ const RUN_NODE_SHARDS = {
39
40
  const LEGACY_SHARDS = {
40
41
  'symptoms.jsonl': 'symptom',
41
42
  'hypotheses.jsonl': 'hypothesis',
42
- 'checks.jsonl': 'check',
43
- 'failure-modes.jsonl': 'failure-mode',
43
+ 'checks.jsonl': 'check_point',
44
+ 'failure-modes.jsonl': 'failure_reason',
44
45
  'assets.jsonl': 'asset',
45
46
  'cases.jsonl': 'case',
46
47
  };
47
- const README = `# 05_diagnosis
48
-
49
- 这个目录**只放一次排查的产物**(\`evidence\` / \`cause\` / 执行边),以及新人照抄的模板卡。
50
-
51
- 排查思路本身(现象 / 假设 / 检查 / 失败模式 / 案例)现在是 **wiki 卡片**,住在
52
- \`02_wiki/diagnosis/\`,出处是 \`01_source_truth/\` 里的手册与复盘。图由卡片编译而来 ——
53
- 所以改知识要改卡片(或改它的来源文档再重新编译),不要改这里。
54
-
55
- \`*.jsonl\` 里若出现 \`symptoms\` / \`hypotheses\` / \`checks\` / \`failure-modes\` / \`assets\`
56
- 等分片,那是 v0.7 之前的历史快照:版本升级时被读出来迁移成了卡片,之后不再更新。
57
- `;
48
+ /** 一次排查写下的节点(旧格式)。同样只读。 */
49
+ const LEGACY_RUN_SHARDS = {
50
+ 'evidence.jsonl': 'evidence',
51
+ 'causes.jsonl': 'cause',
52
+ };
58
53
  export class DiagnosisStore {
59
54
  host;
60
55
  constructor(host) {
61
56
  this.host = host;
62
57
  }
63
- get dir() { return join(this.host.rootDir, DIR); }
58
+ get legacyDir() { return join(this.host.rootDir, LEGACY_DIR); }
64
59
  get cardsDir() { return join(this.host.rootDir, '02_wiki', 'diagnosis'); }
65
60
  /**
66
61
  * 幂等初始化。三种状态各自处理,互不覆盖:
@@ -69,84 +64,149 @@ export class DiagnosisStore {
69
64
  * 2. 没有卡片但有旧 jsonl → **前向迁移**:把旧图反推成卡片写出去,并**校验迁移无损**
70
65
  * (重新编译一遍与旧图比对,不一致就不认这次迁移,继续按 jsonl 读 —— 宁可留在旧形态,
71
66
  * 也不要静默丢知识);
72
- * 3. 两者都没有 → 首次启动:先落手册与复盘的 SourceRaw,再把 seed 编译成卡片。
67
+ * 3. 两者都没有 → **什么都不写**。这个库还没开始做排查。
68
+ *
69
+ * 第 3 条原来是自动写入内置示例。实跑反馈把它改掉了:那份示例长得像真的业务文档,
70
+ * 而它落在用户自己的 `01_source_raw/` 与 `02_wiki/` 里 —— 新装一台机器,一打开
71
+ * 「智能归因」就凭空多出几份来源和几十张卡片。示例还在(`loadSample()`),
72
+ * 但改成**用户点一下才载入**。
73
+ *
74
+ * **v1.1 起连模板文件也不铺了**:模板卡由类型定义派生(0021 §6.6),落成磁盘文件会
75
+ * 造出「设置里改了、磁盘上那份没改」的第二真源。
73
76
  */
74
77
  async ensure() {
75
- await mkdir(this.dir, { recursive: true });
76
- const templates = join(this.dir, 'templates');
77
- await mkdir(templates, { recursive: true });
78
- await Promise.all(DIAGNOSIS_ENTITIES.map(spec => this.writeIfAbsent(join(templates, `${spec.entityType.replace(/\//g, '-')}.md`), templateCard(spec))));
79
- // 目录角色的说明也要落盘:下一个人只打开 05_diagnosis 时,得知道知识已经搬走了。
80
- await this.writeIfAbsent(join(this.dir, 'README.md'), README);
81
- // 注意:**不要**在这里为一次排查的产物建空占位文件。它们走 `writeIfAbsent`,
82
- // 而「占位」会在首次 seed 之前就把文件创建出来,于是 seed 的真实内容被判为「已存在」
83
- // 而写不进去 —— 结果是图上少了 evidence / cause 五个节点,且没有任何报错。
84
78
  if ((await this.readCards()).length > 0)
85
79
  return { seeded: false, migrated: false, problems: [] };
86
80
  if ((await this.legacyShardFiles()).length > 0)
87
81
  return await this.migrate();
88
- return await this.seed();
82
+ return { seeded: false, migrated: false, problems: [] };
83
+ }
84
+ /**
85
+ * 载入**内置示例**:一份排查手册 + 三篇复盘 + 三次排查日志 → SourceRaw → 卡片 → 图。
86
+ *
87
+ * 只有用户明确点了「载入内置示例」才走这里(`ensure()` 不再自动调用)。幂等:
88
+ * `addSource` 按 `externalId`、`writeCard` 按 entityId,点两次不会写出第二份。
89
+ *
90
+ * **它走的是「提议 → 确认」那条门,不是绕过它**(0021 §6.1)。区别只在确认者是谁:
91
+ * 用户点「载入内置示例」这个动作本身就是**对整批示例的确认**,所以这里给每条提议记下
92
+ * `confirmedBy = user:load-sample`,然后照常走 `writeCard`。这样做的两个好处:
93
+ * 待办区里能看到这批卡片是怎么来的;而「未确认不落 `02_wiki/`」这条规则没有被开一个
94
+ * 后门 —— 例外是**确认者的身份**,不是门的缺失。
95
+ */
96
+ async loadSample() {
97
+ const { problems: sourceProblems, refs } = await this.writeSources(seedSources());
98
+ const cards = withSourceRefs(graphToCards(SEED_GRAPH, SEED_CASES), refs, SEED_CASES);
99
+ const problems = [...sourceProblems, ...await this.writeCards(cards, 'user:load-sample')];
100
+ return { seeded: true, migrated: false, problems };
89
101
  }
90
102
  async snapshot() {
91
103
  const { seeded, migrated, problems } = await this.ensure();
92
104
  const cards = await this.readCards();
93
- const run = await this.readRunArtifacts();
105
+ /**
106
+ * 「什么都没有」= 没有卡片、也没有旧 jsonl。它是**可以载入内置示例**的唯一条件:
107
+ * 已经有知识(不管哪一代形态)时不该再往里塞示例 —— 那会变成第二份互相矛盾的知识。
108
+ */
109
+ const canLoadSample = cards.length === 0 && (await this.legacyShardFiles()).length === 0;
94
110
  if (cards.length > 0) {
95
- const compiled = cardsToGraph(cards);
96
- const graph = {
97
- nodes: [...compiled.graph.nodes, ...run.nodes],
98
- edges: [...compiled.graph.edges, ...run.edges],
99
- };
111
+ const built = await this.buildGraph(cards);
100
112
  return {
101
- graph,
102
- cases: compiled.cases,
103
- issues: validateDiagnosis(graph),
113
+ graph: built.graph,
114
+ cases: built.cases,
115
+ issues: validateDiagnosis(built.graph),
104
116
  seeded,
105
117
  migrated,
106
118
  source: 'cards',
107
- problems: [...problems, ...compiled.problems],
119
+ canLoadSample: false,
120
+ problems: [...problems, ...built.problems],
108
121
  };
109
122
  }
110
- // 还没有卡片:旧 jsonl(或 seed 刚写下的那份)就是当前可读的来源。
111
- const graph = await this.readGraph();
112
- const cases = await this.readCases();
123
+ // 还没有卡片:旧 jsonl 就是当前可读的来源;两份都没有就是一个空库。
124
+ const graph = await this.readLegacyGraph();
125
+ const cases = await this.readLegacyCases();
113
126
  return {
114
127
  graph,
115
128
  cases,
116
129
  issues: validateDiagnosis(graph),
117
130
  seeded,
118
131
  migrated,
119
- source: (await this.legacyShardFiles()).length > 0 ? 'jsonl' : 'seed',
132
+ source: canLoadSample ? 'empty' : 'jsonl',
133
+ canLoadSample,
120
134
  problems,
121
135
  };
122
136
  }
123
137
  /**
124
- * 图。
138
+ * 图 = **卡片那张图** + **一次排查的产物**。
139
+ *
140
+ * 两条来源严格分工:类型层与引用层(以及六种卡片边)全部来自卡片;`evidence` / `cause`
141
+ * 与四条执行边全部来自 `agent_diagnosis_case` 的 SourceRaw。合成一张图是**读**的时候
142
+ * 做的,不是写的时候 —— 写的时候合成,等于让一次执行的结果变成可复用的知识。
143
+ */
144
+ async buildGraph(cards) {
145
+ const compiled = cardsToGraph(cards);
146
+ const problems = [...compiled.problems];
147
+ const nodes = [...compiled.graph.nodes];
148
+ const edges = [...compiled.graph.edges];
149
+ const runs = await this.readRuns();
150
+ problems.push(...runs.problems);
151
+ for (const record of runs.records) {
152
+ const run = runToGraph(record);
153
+ // 引用完整性要**连这次排查自己产出的 id 一起算**:路径里的 `E1` / `C1` 正是它写下的。
154
+ const known = new Set([...compiled.graph.nodes.map(node => node.id), ...run.nodes.map(node => node.id)]);
155
+ problems.push(...run.problems, ...runReferenceProblems(record, known));
156
+ nodes.push(...run.nodes);
157
+ edges.push(...run.edges);
158
+ }
159
+ /**
160
+ * **旧 jsonl 里的执行产物继续可读。**
161
+ *
162
+ * 它们是只读的历史快照(v0.7 之前一次排查的产物就写在那里),而卡片表达不了它们
163
+ * —— `evidence` / `cause` 与四条执行边不属于任何卡片。所以迁移只搬「卡片能表达的那
164
+ * 部分」,这一部分留在原处继续供读。少了这一段,一次旧知识根迁移之后图会静默地
165
+ * 少掉全部证据与根因,而迁移还报成功。
166
+ */
167
+ const legacyRun = await this.readLegacyRunArtifacts();
168
+ nodes.push(...legacyRun.nodes);
169
+ edges.push(...legacyRun.edges);
170
+ return { graph: dedupe({ nodes, edges }, problems), cases: compiled.cases, problems };
171
+ }
172
+ /**
173
+ * 旧 `05_diagnosis/` 里的执行产物:`evidence.jsonl` / `causes.jsonl` / `edges.jsonl`。
125
174
  *
126
- * 有卡片:`cardsToGraph(卡片)` + 一次排查的产物;没有卡片:按旧 jsonl 读。
127
- * 两条路径都返回同一种形状,调用方不需要知道现在是哪一代。
175
+ * 只取**执行边**:卡片边由卡片投影出来,这里再读一遍就会出现重复边。同时按 id 去重
176
+ * —— 已经由 `agent_diagnosis_case` 解析出来的节点不重复加(新旧两代可能描述同一次排查)。
128
177
  */
178
+ async readLegacyRunArtifacts() {
179
+ const nodes = [];
180
+ for (const file of Object.keys(LEGACY_RUN_SHARDS)) {
181
+ for (const row of await this.readLines(join(this.legacyDir, file))) {
182
+ try {
183
+ nodes.push(JSON.parse(row));
184
+ }
185
+ catch { /* 跳过损坏行 */ }
186
+ }
187
+ }
188
+ const edges = [];
189
+ for (const row of await this.readLines(join(this.legacyDir, 'edges.jsonl'))) {
190
+ try {
191
+ const edge = JSON.parse(row);
192
+ if (RUN_EDGE_KINDS.includes(edge.kind))
193
+ edges.push(edge);
194
+ }
195
+ catch { /* 同上 */ }
196
+ }
197
+ return { nodes, edges };
198
+ }
129
199
  async readGraph() {
130
200
  const cards = await this.readCards();
131
- if (cards.length > 0) {
132
- const compiled = cardsToGraph(cards);
133
- const run = await this.readRunArtifacts();
134
- return { nodes: [...compiled.graph.nodes, ...run.nodes], edges: [...compiled.graph.edges, ...run.edges] };
135
- }
201
+ if (cards.length > 0)
202
+ return (await this.buildGraph(cards)).graph;
136
203
  return await this.readLegacyGraph();
137
204
  }
138
205
  async readCases() {
139
206
  const cards = await this.readCards();
140
207
  if (cards.length > 0)
141
208
  return cardsToGraph(cards).cases;
142
- try {
143
- const raw = await readFile(join(this.dir, 'cases.json'), 'utf8');
144
- const parsed = JSON.parse(raw);
145
- return Array.isArray(parsed) ? parsed : [];
146
- }
147
- catch {
148
- return [];
149
- }
209
+ return await this.readLegacyCases();
150
210
  }
151
211
  /* ────────────────────────────────────────────── 卡片:读写 ── */
152
212
  /** 读 `02_wiki/diagnosis/**` 下的全部卡片。解析不出来的文件按「不是卡片」跳过。 */
@@ -159,57 +219,88 @@ export class DiagnosisStore {
159
219
  }
160
220
  return cards;
161
221
  }
162
- /** 写一批卡片。返回写失败的原因(schema 不认、出处不存在等),由调用方决定怎么显示。 */
163
- async writeCards(cards) {
222
+ /* ────────────────────────────────────────────── 一次排查的记录 ── */
223
+ /**
224
+ * 读全部 `agent_diagnosis_case` 来源,解析出排查记录。
225
+ *
226
+ * 块坏了、`runId` 缺了、`symptomId` 缺了就**跳过并如实报问题** —— 不猜。
227
+ * 一条坏日志不该让整张图读不出来,但它也不能被静默吞掉。
228
+ */
229
+ async readRuns() {
230
+ const records = [];
164
231
  const problems = [];
165
- for (const card of cards) {
166
- const written = await this.host.writeCard({
167
- entityType: card.entityType,
168
- entityId: card.entityId,
169
- title: card.title,
170
- content: renderBody(card),
171
- sourceRefs: card.sourceRefs,
172
- status: card.status,
173
- ...(card.summary ? { summary: card.summary } : {}),
174
- ...(card.owner ? { owner: card.owner } : {}),
175
- });
176
- if (written.ok === false)
177
- problems.push(`卡片 ${card.entityId} 写入失败:${written.error.code} ${written.error.message}`);
232
+ for (const source of await this.host.loadSources()) {
233
+ if (source.sourceType !== RUN_SOURCE_TYPE)
234
+ continue;
235
+ const record = parseRunSource(source.content);
236
+ if (record)
237
+ records.push(record);
238
+ else
239
+ problems.push(`诊断日志 ${source.sourceId} 里没有可解析的 \`json diagnosis-run\` 块,已跳过`);
178
240
  }
179
- return problems;
241
+ return { records, problems };
180
242
  }
181
- /* ────────────────────────────────────────────── 首次 seed ── */
182
- async seed() {
183
- const { problems: sourceProblems, refs } = await this.writeSources(seedSources());
184
- const cards = withSourceRefs(graphToCards(SEED_GRAPH, SEED_CASES), refs, SEED_GRAPH, SEED_CASES);
185
- const problems = [...sourceProblems, ...await this.writeCards(cards)];
186
- // 一次排查的产物照旧落在这里 —— seed 本来就等于「已经发生过的那三次排查」。
187
- await this.writeRunArtifacts(SEED_GRAPH);
188
- await this.writeLegacySnapshot();
189
- return { seeded: true, migrated: false, problems };
243
+ /**
244
+ * 一次排查结束:写一条 `agent_diagnosis_case` 的 SourceRaw,并**直接写入**一张案例卡片。
245
+ *
246
+ * 0044:案例卡片原来只提议、等人确认。与编译那条链路一样改成直接入库 ——
247
+ * 一次排查的价值就在于「当时是怎么走的」,让它停在待办队列里等于把经验丢掉。
248
+ * 卡片会被标成 `unreviewed`,人在「知识库 → Wiki」里 review 它。
249
+ *
250
+ * 幂等:`externalId` = runId,同一次排查重跑不会写出第二条来源;卡片按 entityId 写入。
251
+ */
252
+ async recordRun(record) {
253
+ const problems = [];
254
+ const added = await this.host.addSource({
255
+ sourceType: RUN_SOURCE_TYPE,
256
+ title: `AI 诊断日志 · ${record.symptomId} · ${record.runId}`,
257
+ content: renderRunSource(record),
258
+ externalId: record.runId,
259
+ sourceId: `${RUN_SOURCE_TYPE}:${record.runId}`,
260
+ });
261
+ if (added.ok === false)
262
+ return { problems: [`诊断日志 ${record.runId} 写入失败:${added.error.code} ${added.error.message}`] };
263
+ const sourceId = added.data.sourceId;
264
+ const symptomTitle = (await this.readCards()).find(card => card.entityId === record.symptomId)?.title ?? record.symptomId;
265
+ const draft = caseCardOf(record, symptomTitle);
266
+ const written = await this.host.writeCard({
267
+ entityType: draft.entityType,
268
+ entityId: draft.entityId,
269
+ title: draft.title,
270
+ content: renderCardBody(draft),
271
+ sourceRefs: [sourceId],
272
+ status: 'unreviewed',
273
+ });
274
+ if (written.ok === false)
275
+ problems.push(`案例卡片 ${draft.entityId} 写入失败:${written.error.code} ${written.error.message}`);
276
+ return { sourceId, ...(written.ok === false ? {} : { entityId: draft.entityId }), problems };
190
277
  }
191
278
  /* ────────────────────────────────────────────── 旧知识根迁移 ── */
192
279
  async migrate() {
193
280
  const legacy = await this.readLegacyGraph();
194
- const cases = await this.readCases();
281
+ const cases = await this.readLegacyCases();
195
282
  // **先在内存里验证,通过才写盘。**
196
283
  //
197
284
  // 卡片表达不了的东西确实存在:手工加的边、没有任何假设引用的资产节点……一旦迁移会丢,
198
285
  // 就宁可留在旧形态,也不要静默丢知识。而「先写再验、失败回滚」会留一个更糟的中间态:
199
286
  // 卡片已经落盘,下一次读就成了卡片来源 —— 于是分歧只在第一次读时被报出来,
200
287
  // 之后再也看不见。所以顺序是:编译 → 比对 → 才写。
201
- const run = await this.readRunArtifacts();
202
288
  const draft = graphToCards(legacy, cases);
203
289
  const compiled = cardsToGraph(draft);
204
- const divergence = compareGraphs(legacy, {
205
- nodes: [...compiled.graph.nodes, ...run.nodes],
206
- edges: [...compiled.graph.edges, ...run.edges],
207
- });
290
+ /**
291
+ * 比对的是**卡片能表达的那部分**。
292
+ *
293
+ * `evidence` / `cause` 与四条执行边不在卡片里(§6.7 的边界表),它们留在
294
+ * `05_diagnosis/` 里继续供读(见 `readLegacyRunArtifacts`)。把它们算进比对,
295
+ * 结果是**任何带排查产物的旧知识根都迁不动** —— 而失败方式是静默的:图少了一半,
296
+ * 迁移还报成功。
297
+ */
298
+ const divergence = compareGraphs(cardExpressible(legacy), compiled.graph);
208
299
  if (divergence) {
209
300
  return { seeded: false, migrated: false, problems: [`迁移未生效(仍按 05_diagnosis/*.jsonl 读):${divergence}`] };
210
301
  }
211
302
  const { problems: sourceProblems, refs } = await this.writeSources(seedSources());
212
- const problems = [...sourceProblems, ...await this.writeCards(withSourceRefs(draft, refs, legacy, cases))];
303
+ const problems = [...sourceProblems, ...await this.writeCards(withSourceRefs(draft, refs, cases), 'migration:05_diagnosis')];
213
304
  return { seeded: false, migrated: problems.length === 0, problems };
214
305
  }
215
306
  /* ────────────────────────────────────────────── SourceRaw ── */
@@ -236,58 +327,60 @@ export class DiagnosisStore {
236
327
  }
237
328
  return { problems, refs };
238
329
  }
239
- /* ────────────────────────────────────────────── 一次排查的产物 ── */
240
- async readRunArtifacts() {
241
- const nodes = [];
242
- for (const file of Object.keys(RUN_NODE_SHARDS)) {
243
- for (const row of await this.readLines(join(this.dir, file))) {
244
- try {
245
- nodes.push(JSON.parse(row));
246
- }
247
- catch { /* 跳过损坏行,不让一行毁掉整张图 */ }
248
- }
249
- }
250
- const edges = [];
251
- for (const row of await this.readLines(join(this.dir, 'edges.jsonl'))) {
252
- try {
253
- const edge = JSON.parse(row);
254
- // 只认执行边:五种卡片边由卡片投影出来,这里再读一遍就会出现重复边。
255
- if (RUN_EDGE_KINDS.includes(edge.kind))
256
- edges.push(edge);
257
- }
258
- catch { /* 同上 */ }
330
+ /* ────────────────────────────────────────────── 写卡片 ── */
331
+ /**
332
+ * 写一批卡片。返回写失败的原因(类型不认、出处不存在等),由调用方决定怎么显示。
333
+ *
334
+ * 0044:**直接写**,不再先提一条提议再确认再落卡。`confirmedBy` 现在只是一个
335
+ * 归因用的标签(载入示例时是 `user:load-sample`,迁移时是迁移逻辑),不再是准入凭证 ——
336
+ * 凭证这道门已经不存在了。留它是因为它进 `writeCard` 的 lineage 留痕,
337
+ * 而「这张卡片是哪一次动作产生的」仍然值得回答。
338
+ */
339
+ async writeCards(cards, confirmedBy) {
340
+ const problems = [];
341
+ for (const card of cards) {
342
+ const written = await this.host.writeCard({
343
+ entityType: card.entityType,
344
+ entityId: card.entityId,
345
+ title: card.title,
346
+ content: renderCardBody(card),
347
+ sourceRefs: card.sourceRefs,
348
+ status: card.status,
349
+ ...(card.summary ? { summary: card.summary } : {}),
350
+ ...(card.owner ? { owner: card.owner } : {}),
351
+ });
352
+ if (written.ok === false)
353
+ problems.push(`卡片 ${card.entityId} 写入失败:${written.error.code} ${written.error.message}`);
259
354
  }
260
- return { nodes, edges };
355
+ if (problems.length > 0)
356
+ problems.push(`(这一批卡片由 ${confirmedBy} 写入)`);
357
+ return problems;
261
358
  }
262
- async writeRunArtifacts(graph) {
263
- for (const [file, kind] of Object.entries(RUN_NODE_SHARDS)) {
264
- const rows = graph.nodes.filter(node => node.kind === kind);
265
- await this.writeIfAbsent(join(this.dir, file), rows.map(row => JSON.stringify(row)).join('\n'));
359
+ /* ────────────────────────────────────────────── 旧读法(只读) ── */
360
+ async readLegacyCases() {
361
+ try {
362
+ const raw = await readFile(join(this.legacyDir, 'cases.json'), 'utf8');
363
+ const parsed = JSON.parse(raw);
364
+ return Array.isArray(parsed) ? parsed : [];
266
365
  }
267
- await this.writeIfAbsent(join(this.dir, 'edges.jsonl'), graph.edges.filter(edge => RUN_EDGE_KINDS.includes(edge.kind)).map(edge => JSON.stringify(edge)).join('\n'));
268
- }
269
- /** 旧版的类型层快照。首次 seed 时也写一份:它让 `05_diagnosis/` 仍是一份可读的完整快照。 */
270
- async writeLegacySnapshot() {
271
- for (const [file, kind] of Object.entries(LEGACY_SHARDS)) {
272
- const rows = SEED_GRAPH.nodes.filter(node => node.kind === kind);
273
- await this.writeIfAbsent(join(this.dir, file), rows.map(row => JSON.stringify(row)).join('\n'));
366
+ catch {
367
+ return [];
274
368
  }
275
- await this.writeIfAbsent(join(this.dir, 'cases.json'), JSON.stringify(SEED_CASES, null, 2));
276
369
  }
277
- /* ────────────────────────────────────────────── 旧读法 ── */
278
370
  async readLegacyGraph() {
279
371
  const nodes = [];
280
- for (const [file, kind] of Object.entries({ ...LEGACY_SHARDS, ...RUN_NODE_SHARDS })) {
281
- for (const row of await this.readLines(join(this.dir, file))) {
372
+ for (const file of Object.keys({ ...LEGACY_SHARDS, ...LEGACY_RUN_SHARDS })) {
373
+ for (const row of await this.readLines(join(this.legacyDir, file))) {
282
374
  try {
283
375
  nodes.push(JSON.parse(row));
284
376
  }
285
377
  catch { /* 跳过损坏行 */ }
286
378
  }
287
- void kind;
288
379
  }
289
380
  const edges = [];
290
- for (const row of await this.readLines(join(this.dir, 'edges.jsonl'))) {
381
+ for (const row of await this.readLines(join(this.legacyDir, 'edges.jsonl'))) {
382
+ // **全部边都读**,不筛:旧文件是**迁移输入**,六种卡片边正是要从这里反推成
383
+ // 卡片字段的。只在读「当前图」时才筛执行边(`readLegacyRunArtifacts`)。
291
384
  try {
292
385
  edges.push(JSON.parse(row));
293
386
  }
@@ -298,14 +391,13 @@ export class DiagnosisStore {
298
391
  /**
299
392
  * 是否存在**值得迁移的旧知识根**。
300
393
  *
301
- * 只看旧版的**类型层**分片,而且要求它真的有内容:`ensure()` 自己会为一次排查的产物
302
- * (`evidence.jsonl` 等)建空占位文件 —— 若把空文件也算成「旧知识根」,首次启动会走进
303
- * 迁移分支,然后在空图上白跑一趟。
394
+ * 只看旧版的**类型层**分片,而且要求它真的有内容:空文件不算「旧知识根」,
395
+ * 否则首次启动会走进迁移分支,然后在空图上白跑一趟。
304
396
  */
305
397
  async legacyShardFiles() {
306
398
  const found = [];
307
399
  for (const file of Object.keys(LEGACY_SHARDS)) {
308
- if ((await this.readLines(join(this.dir, file))).length > 0)
400
+ if ((await this.readLines(join(this.legacyDir, file))).length > 0)
309
401
  found.push(file);
310
402
  }
311
403
  return found;
@@ -318,18 +410,9 @@ export class DiagnosisStore {
318
410
  return [];
319
411
  }
320
412
  }
321
- async writeIfAbsent(path, content) {
322
- try {
323
- await readFile(path);
324
- return;
325
- }
326
- catch {
327
- await writeFile(path, content, 'utf8');
328
- }
329
- }
330
413
  }
331
414
  /** 卡片正文:小节 + 结构化块。复用编解码里的同一套序列化,避免两处格式漂移。 */
332
- function renderBody(card) {
415
+ export function renderCardBody(card) {
333
416
  const text = serializeCard(card);
334
417
  return text.slice(text.indexOf('\n---\n', 3) + 5).trim();
335
418
  }
@@ -339,7 +422,7 @@ function renderBody(card) {
339
422
  * 规则是**数据驱动的**,不是凭印象分的:案例卡片与它自己的复盘原文一一对应;
340
423
  * 其它卡片取「第一篇走过它的复盘」,没有走过它的就挂那本手册。
341
424
  */
342
- function withSourceRefs(cards, refs, graph, cases) {
425
+ function withSourceRefs(cards, refs, cases) {
343
426
  const handbook = refs.get('handbook');
344
427
  /** 节点 id → 它出现在哪篇复盘里(取第一篇)。 */
345
428
  const caseOf = new Map();
@@ -352,13 +435,62 @@ function withSourceRefs(cards, refs, graph, cases) {
352
435
  if (!caseOf.has(step.nodeId))
353
436
  caseOf.set(step.nodeId, ref);
354
437
  }
355
- void graph;
356
438
  return cards.map(card => {
357
439
  const own = card.entityType === 'diagnosis/case' ? refs.get(card.entityId) : undefined;
358
440
  const ref = own ?? caseOf.get(card.entityId) ?? handbook;
359
441
  return { ...card, sourceRefs: ref ? [ref] : [] };
360
442
  });
361
443
  }
444
+ /**
445
+ * 按 id 去重。
446
+ *
447
+ * 新旧两代可能描述**同一次排查**:一条 `agent_diagnosis_case` 的 SourceRaw(v1.1 起)
448
+ * 与 `05_diagnosis/evidence.jsonl`(历史快照)里会有同一个 `E1`。不去重的后果是图上
449
+ * 出现两个 `E1` —— 而画布按 id 建节点,第二个会静默覆盖第一个的位置与样式,
450
+ * 读起来像「这次排查跑了两遍」。
451
+ *
452
+ * 同 id 但 kind 不同是真冲突(同一份知识被两处定义成两样东西),报出来而不是静默取第一个。
453
+ */
454
+ function dedupe(graph, problems) {
455
+ const nodes = [];
456
+ const byId = new Map();
457
+ for (const node of graph.nodes) {
458
+ const previous = byId.get(node.id);
459
+ if (previous) {
460
+ if (previous.kind !== node.kind)
461
+ problems.push(`节点 ${node.id} 被定义成了两种类型(${previous.kind} / ${node.kind})—— 只保留第一个`);
462
+ continue;
463
+ }
464
+ byId.set(node.id, node);
465
+ nodes.push(node);
466
+ }
467
+ const edges = [];
468
+ const seen = new Set();
469
+ for (const edge of graph.edges) {
470
+ const key = `${edge.kind}:${edge.source}->${edge.target}`;
471
+ if (seen.has(key))
472
+ continue;
473
+ seen.add(key);
474
+ edges.push(edge);
475
+ }
476
+ return { nodes, edges };
477
+ }
478
+ /** 只能由一次排查产出的节点类型。它们不属于任何卡片(§6.7 的边界表)。 */
479
+ const RUN_ONLY_KINDS = ['evidence', 'cause', 'unknown'];
480
+ /**
481
+ * 旧图里**卡片能表达的那部分**:类型层、引用层的资产、案例桩,以及六种卡片边。
482
+ *
483
+ * 执行产物(`evidence` / `cause` / `unknown` 与四条执行边)不在其中 —— 它们的归宿是
484
+ * `agent_diagnosis_case` 的 SourceRaw,而不是卡片。
485
+ */
486
+ function cardExpressible(graph) {
487
+ const nodes = graph.nodes.filter(node => !RUN_ONLY_KINDS.includes(node.kind));
488
+ const ids = new Set(nodes.map(node => node.id));
489
+ return {
490
+ nodes,
491
+ edges: graph.edges.filter(edge => CARD_EDGE_KINDS.includes(edge.kind) && ids.has(edge.source) && ids.has(edge.target)),
492
+ };
493
+ }
362
494
  /**
363
495
  * 两张图是否一致。返回 `undefined` 表示一致,否则返回第一条差异的人话描述。
364
496
  *
@@ -405,5 +537,4 @@ async function walkMarkdown(dir) {
405
537
  }
406
538
  return found;
407
539
  }
408
- export { cardPathOf };
409
540
  //# sourceMappingURL=store.js.map