clearai-dsh 0.5.1 → 0.5.2

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.
@@ -1027,6 +1027,7 @@ export function describeDomainGraph(lexicon) {
1027
1027
  // 会话账本只活在一次会话里,而研究要跨会话攒下来。所以「攒下来的东西」住在工作区的文件里:
1028
1028
  // · `clear/knowledge/facts/<id>.json`:升格的事实,一条一个文件,只有系统写;
1029
1029
  // · `clear/knowledge/lessons/<id>.json`:结案时经独立评估核过的经验,一条一个文件,只有系统写;
1030
+ // · `clear/knowledge/negatives/<id>.json`:负向条目(已排除、未解、缺陷),系统随发生随写;
1030
1031
  // · `clear/ontology/{concepts,relations,entities}/**.json`:本体,模型用原生文件工具直接写。
1031
1032
  // 内核每一拍把这两处的变化折成一条 `workspace/synced` 变更,投影从文件内容派生词汇、实体与
1032
1033
  // 事实——折法仍然只吃账本,文件是账本之外唯一的输入,而且进账本时就是一条可重放的事实。
@@ -1035,6 +1036,8 @@ export function describeDomainGraph(lexicon) {
1035
1036
  export const FACTS_DIR = 'clear/knowledge/facts'
1036
1037
  /** 经验文件所在的目录(相对工作区)。 */
1037
1038
  export const LESSONS_DIR = 'clear/knowledge/lessons'
1039
+ /** 负向条目(已排除、未解、缺陷):内核随发生随写,一条一个文件。 */
1040
+ export const NEGATIVES_DIR = 'clear/knowledge/negatives'
1038
1041
  /** 经验的四类:坑、要核的读数、会骗人的捷径、先验。 */
1039
1042
  export const LESSON_KINDS = ['trap', 'check', 'shortcut', 'prior']
1040
1043
  /** 本体文件树的根(相对工作区)。 */
@@ -1064,7 +1067,7 @@ export function definitionFingerprint(entry) {
1064
1067
  /** 单位与形状只在写了时进指纹:没写这两格的旧词条,指纹与从前逐字相同。 */
1065
1068
  const meaning =
1066
1069
  'range' in entry || 'domain' in entry
1067
- ? { domain: text(entry.domain), range: isPlainObject(entry.range) ? { term: text(entry.range.term), form: text(entry.range.form), unit: text(entry.range.unit) } : null, functional: entry.functional === true, ...(text(entry.shape) === '' ? {} : { shape: text(entry.shape) }) }
1070
+ ? { domain: text(entry.domain), range: isPlainObject(entry.range) ? { term: text(entry.range.term), form: text(entry.range.form), unit: text(entry.range.unit) } : null, functional: entry.functional === true, gloss: text(entry.gloss), check: text(entry.check), ...(text(entry.shape) === '' ? {} : { shape: text(entry.shape) }) }
1068
1071
  : { gloss: text(entry.gloss), parent: text(entry.parent), ...(text(entry.unit) === '' ? {} : { unit: text(entry.unit) }) }
1069
1072
  return `fnv:${hashText(JSON.stringify(meaning))}`
1070
1073
  }
@@ -1125,6 +1128,8 @@ export function classifyWorkspacePath(path) {
1125
1128
  if (parts.length === facts.length + 1 && facts.every((part, index) => parts[index] === part)) return { kind: 'fact', id, dirs: [] }
1126
1129
  const lessons = LESSONS_DIR.split('/')
1127
1130
  if (parts.length === lessons.length + 1 && lessons.every((part, index) => parts[index] === part)) return { kind: 'lesson', id, dirs: [] }
1131
+ const negatives = NEGATIVES_DIR.split('/')
1132
+ if (parts.length === negatives.length + 1 && negatives.every((part, index) => parts[index] === part)) return { kind: 'negative', id, dirs: [] }
1128
1133
  const root = ONTOLOGY_DIR.split('/')
1129
1134
  if (parts.length >= root.length + 2 && root.every((part, index) => parts[index] === part)) {
1130
1135
  const kind = ONTOLOGY_BRANCHES[parts[root.length]]
@@ -1145,7 +1150,16 @@ export function factFromFile(data, path) {
1145
1150
  goal: data.goal ?? null,
1146
1151
  hypothesis: data.hypothesis ?? null,
1147
1152
  text: String(data.text),
1148
- scope: data.scope ?? null,
1153
+ about: stringList(data.about),
1154
+ scope: data.scope_spec === undefined && data.refute_when === undefined ? null : data.scope ?? null,
1155
+ scope_spec: isPlainObject(data.scope_spec) ? clone(data.scope_spec) : null,
1156
+ use: typeof data.use === 'string' && data.use !== '' ? data.use : null,
1157
+ refute_when: typeof data.refute_when === 'string' ? data.refute_when : data.scope_spec === undefined && typeof data.scope === 'string' ? data.scope : null,
1158
+ boundaries: Array.isArray(data.boundaries) ? clone(data.boundaries) : [],
1159
+ challenges: Array.isArray(data.challenges) ? clone(data.challenges) : [],
1160
+ calculation: isPlainObject(data.calculation) ? clone(data.calculation) : null,
1161
+ rechecks: Array.isArray(data.rechecks) ? clone(data.rechecks) : [],
1162
+ evidence_records: Array.isArray(data.evidence_records) ? clone(data.evidence_records) : [],
1149
1163
  level: data.level ?? null,
1150
1164
  evidence: Array.isArray(data.evidence) ? data.evidence : [],
1151
1165
  assertions: Array.isArray(data.assertions) ? clone(data.assertions) : null,
@@ -1167,7 +1181,8 @@ export function lessonFromFile(data, path) {
1167
1181
  goal: data.goal ?? null,
1168
1182
  text: String(data.text),
1169
1183
  kind: LESSON_KINDS.includes(data.kind) ? data.kind : 'trap',
1170
- about: Array.isArray(data.about) ? data.about.map(String).filter((item) => item.trim() !== '').slice(0, 6) : [],
1184
+ about: stringList(data.about),
1185
+ scope_spec: isPlainObject(data.scope_spec) ? clone(data.scope_spec) : null,
1171
1186
  evidence: typeof data.evidence === 'string' ? data.evidence : null,
1172
1187
  boundary: typeof data.boundary === 'string' ? data.boundary : null,
1173
1188
  status: data.status === 'retracted' ? 'retracted' : 'active',
@@ -1176,6 +1191,38 @@ export function lessonFromFile(data, path) {
1176
1191
  }
1177
1192
  }
1178
1193
 
1194
+ /** 负向条目的种类与状态(与内核 `knowledge-items.js` 同值)。 */
1195
+ export const NEGATIVE_KINDS = ['excluded', 'unresolved', 'defect']
1196
+ export const NEGATIVE_STATUS = ['excluded', 'preliminary_excluded', 'unresolved', 'explained', 'ruled_out', 'escalated', 'defect']
1197
+
1198
+ /**
1199
+ * 负向条目文件 → 条目行。人可以在文件上写 `review`(如 `{"decision": "retracted"}`)撤回一条,撤回的不再列出。
1200
+ */
1201
+ export function negativeFromFile(data, path) {
1202
+ if (!isPlainObject(data) || text(data.id) === '' || text(data.statement) === '') return null
1203
+ const kind = NEGATIVE_KINDS.includes(data.kind) ? data.kind : 'unresolved'
1204
+ return {
1205
+ id: text(data.id),
1206
+ kind,
1207
+ status: NEGATIVE_STATUS.includes(data.status) ? data.status : kind,
1208
+ statement: String(data.statement),
1209
+ touches: stringList(data.touches),
1210
+ evidence: Array.isArray(data.evidence) ? clone(data.evidence) : [],
1211
+ about: stringList(data.about),
1212
+ scope_spec: isPlainObject(data.scope) ? clone(data.scope) : null,
1213
+ strength: isPlainObject(data.strength) ? clone(data.strength) : null,
1214
+ resolution: isPlainObject(data.resolution) ? clone(data.resolution) : null,
1215
+ source: isPlainObject(data.source) ? clone(data.source) : null,
1216
+ review: isPlainObject(data.review) ? clone(data.review) : null,
1217
+ path: path ?? null,
1218
+ at: typeof data.at === 'number' ? data.at : null,
1219
+ }
1220
+ }
1221
+
1222
+ function stringList(raw) {
1223
+ return Array.isArray(raw) ? raw.map(String).filter((item) => item.trim() !== '').slice(0, 12) : []
1224
+ }
1225
+
1179
1226
  // ═══ 本体文件树:字段、单文件校验、从文件折出词汇与实体 ═════════════════════════
1180
1227
  //
1181
1228
  // 本体由模型用原生文件工具直接写,住在 `clear/ontology/{concepts,relations,entities}/` 下:
@@ -1315,7 +1362,7 @@ function evidenceShape(value, at) {
1315
1362
  */
1316
1363
  export function checkOntologyFile(path, content) {
1317
1364
  const place = classifyWorkspacePath(path)
1318
- if (place === null || place.kind === 'fact' || place.kind === 'lesson') return [tr(`不是本体文件的位置:本体文件要放在 ${ONTOLOGY_DIR}/{concepts,relations,entities}/ 下,扩展名 .json`, `Not an ontology file location: ontology files go under ${ONTOLOGY_DIR}/{concepts,relations,entities}/ with a .json extension`)]
1365
+ if (place === null || place.kind === 'fact' || place.kind === 'lesson' || place.kind === 'negative') return [tr(`不是本体文件的位置:本体文件要放在 ${ONTOLOGY_DIR}/{concepts,relations,entities}/ 下,扩展名 .json`, `Not an ontology file location: ontology files go under ${ONTOLOGY_DIR}/{concepts,relations,entities}/ with a .json extension`)]
1319
1366
  let data = content
1320
1367
  if (typeof content === 'string') {
1321
1368
  try {
@@ -1423,7 +1470,7 @@ export function materializeOntology(files) {
1423
1470
  const flag = (path, id, code, detail, severity = 'warning') => problems.push({ path, id, code, detail, severity })
1424
1471
  const entries = Object.entries(isPlainObject(files) ? files : {})
1425
1472
  .map(([path, file]) => ({ path, file, place: classifyWorkspacePath(path) }))
1426
- .filter((item) => item.place !== null && item.place.kind !== 'fact' && item.place.kind !== 'lesson')
1473
+ .filter((item) => item.place !== null && item.place.kind !== 'fact' && item.place.kind !== 'lesson' && item.place.kind !== 'negative')
1427
1474
  .sort((a, b) => (a.path < b.path ? -1 : 1))
1428
1475
  const terms = []
1429
1476
  const predicates = []
package/lib/fold.js CHANGED
@@ -16,9 +16,10 @@
16
16
  * 与预设内核的契约:`meta = { kind: 'clearai', v: 1, mutation: { t, ... } }`。
17
17
  * 词汇表由本文件的 `applyMutation` 定义;预设侧只负责产出,不负责解释。
18
18
  */
19
- import { applyLexiconMutation, changedDefinitions, materializeOntology, classifyWorkspacePath, deriveConflicts, emptyLexicon, factFromFile, formatAssertion, lessonFromFile, graphProjection, lexiconHealth, normalizeLexicon, objectKey, termUsage, VALUE_FORMS } from './domain-language.js'
19
+ import { applyLexiconMutation, changedDefinitions, materializeOntology, classifyWorkspacePath, deriveConflicts, emptyLexicon, factFromFile, formatAssertion, lessonFromFile, negativeFromFile, graphProjection, lexiconHealth, normalizeLexicon, objectKey, termUsage, VALUE_FORMS } from './domain-language.js'
20
20
  import { handleOf, knowledgeView, trustOf } from './knowledge-view.js'
21
21
  import { bilingual, detectLanguage, messageText, tr, withLanguage } from './lang.js'
22
+ import { compareScope, scopeText } from './scope.js'
22
23
 
23
24
  /** 五个等级,由低到高。等级是「这条证据有多大程度只能靠信任做的人」的刻度(见 docs/verification-loop.md 的等级表)。 */
24
25
  const LEVELS = ['L0', 'L1', 'L2', 'L3', 'L4']
@@ -70,9 +71,15 @@ export const MUTATION_KIND = 'clearai'
70
71
  * 与结案时的 `answers`(按问题的结论四部分);判断带 `question`(属于哪个问题或板块)与 `from`
71
72
  * (由本体里哪条关系提出);步骤带 `serves` 与按候选分别写的 `predictions`;未解释项带 `touches`
72
73
  * (涉及的量、判断或事实)。全部可选:旧日志折出来就是整个目标一个问题。
74
+ * v19 → v20:**适用范围与推翻条件分开**:目标带 `conditions`(本次所处的条件);判断带 `scope`
75
+ * (`{conditions, ranges, note}`);事实带 `scope_spec`、`refute_when` 与 `boundaries`
76
+ * (`fact/bounded`:检验落在适用范围之外时记下的边界,事实保持成立)。旧账的 `scope` 写的是推翻条件。
77
+ * 同一版里目标、判断与事实还带 `about`(涉及的实体或量),未解释项带 `defect`(解释为测量或方法缺陷);
78
+ * 派生多一份 `negativeRows`(`clear/knowledge/negatives/` 的负向条目)。
79
+ * v20 → v21:持久核算复核、最终实际引用、幂等审计派发;旧日志原样重放。
73
80
  * 投影缓存按版本判定,所以旧缓存会被丢弃、从日志重折一遍。
74
81
  */
75
- export const STATE_VERSION = 19
82
+ export const STATE_VERSION = 21
76
83
 
77
84
  /**
78
85
  * **只留台账、不折进视图**的变更类型(词汇表的另一半)。
@@ -214,6 +221,24 @@ export function normalizeTests(tests) {
214
221
  }
215
222
 
216
223
  /** 预测清单的唯一形状:`[{hypothesis, expect}]`,空的去掉。 */
224
+ /** 适用范围的形状:`{conditions?, ranges?, note?}`(内核已规整过,这里只认形状)。 */
225
+ function isScope(value) {
226
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && (typeof value.conditions === 'object' || typeof value.ranges === 'object' || typeof value.note === 'string')
227
+ }
228
+
229
+ /** 涉及的实体或量:字符串数组。 */
230
+ function isAbout(value) {
231
+ return Array.isArray(value) && value.every((item) => typeof item === 'string')
232
+ }
233
+
234
+ /** 归知识库管、不进本体的工作区文件种类:事实、经验、负向条目。 */
235
+ const KNOWLEDGE_FILE_KINDS = ['fact', 'lesson', 'negative']
236
+
237
+ /** 立题的条件:`{维度: 值}`。 */
238
+ function isConditions(value) {
239
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every((item) => typeof item === 'string')
240
+ }
241
+
217
242
  export function normalizePredictions(raw) {
218
243
  if (!Array.isArray(raw)) return []
219
244
  return raw
@@ -303,6 +328,8 @@ export function applyMutation(state, mutation) {
303
328
  if (questions !== null) previous.questions = questions
304
329
  const areas = normalizeAreas(mutation.areas)
305
330
  if (areas !== null) previous.areas = areas
331
+ if (isConditions(mutation.conditions)) previous.conditions = clone(mutation.conditions)
332
+ if (isAbout(mutation.about)) previous.about = mutation.about.map(String)
306
333
  previous.reasons.push(mutation.reason ?? null)
307
334
  } else {
308
335
  if (previous !== null && previous.status === 'open') previous.status = 'superseded'
@@ -339,6 +366,10 @@ export function applyMutation(state, mutation) {
339
366
  /** 问题与调研板块(可选)。没有问题时,整个目标就是唯一的问题。 */
340
367
  questions: normalizeQuestions(mutation.questions) ?? [],
341
368
  areas: normalizeAreas(mutation.areas) ?? [],
369
+ /** 这次问题所处的条件(如产线、月份):判断没写适用范围时的默认,引用已有知识时据此判是否适用。 */
370
+ conditions: isConditions(mutation.conditions) ? clone(mutation.conditions) : {},
371
+ /** 这次问题涉及的实体或量(id):留下的知识条目挂在它们上面。 */
372
+ about: isAbout(mutation.about) ? mutation.about.map(String) : [],
342
373
  /** 结案时按问题写的结论四部分(`Conclude.answers`)。 */
343
374
  answers: [],
344
375
  }
@@ -366,6 +397,10 @@ export function applyMutation(state, mutation) {
366
397
  if (Array.isArray(hypothesis.assertions)) known.assertions = clone(hypothesis.assertions)
367
398
  if (typeof hypothesis.question === 'string' && hypothesis.question !== '') known.question = hypothesis.question
368
399
  if (typeof hypothesis.from === 'string' && hypothesis.from !== '') known.from = hypothesis.from
400
+ if (isScope(hypothesis.scope)) known.scope = clone(hypothesis.scope)
401
+ if (isAbout(hypothesis.about)) known.about = hypothesis.about.map(String)
402
+ if (Array.isArray(hypothesis.uses)) known.uses = clone(hypothesis.uses)
403
+ if (typeof hypothesis.use === 'string' && hypothesis.use !== '') known.use = hypothesis.use
369
404
  continue
370
405
  }
371
406
  next.hypotheses.push({
@@ -388,6 +423,13 @@ export function applyMutation(state, mutation) {
388
423
  ...(typeof hypothesis.question === 'string' && hypothesis.question !== '' ? { question: hypothesis.question } : {}),
389
424
  /** 由本体里哪条关系提出(关系 id);没写或写「直觉」都如实显示。 */
390
425
  ...(typeof hypothesis.from === 'string' && hypothesis.from !== '' ? { from: hypothesis.from } : {}),
426
+ /** 适用范围(在哪里成立),与推翻条件分开:`{conditions, ranges, note}`。 */
427
+ ...(isScope(hypothesis.scope) ? { scope: clone(hypothesis.scope) } : {}),
428
+ /** 涉及的实体或量(id);没写就用立题的 about。 */
429
+ ...(isAbout(hypothesis.about) ? { about: hypothesis.about.map(String) } : {}),
430
+ /** 用到的已有条目与立题那一刻的适用性判定:`[{id, kind, verdict}]`。 */
431
+ ...(Array.isArray(hypothesis.uses) ? { uses: clone(hypothesis.uses) } : {}),
432
+ ...(typeof hypothesis.use === 'string' && hypothesis.use !== '' ? { use: hypothesis.use } : {}),
391
433
  at,
392
434
  })
393
435
  }
@@ -489,6 +531,8 @@ export function applyMutation(state, mutation) {
489
531
  item.status = mutation.outcome
490
532
  item.reason = mutation.reason ?? null
491
533
  item.explainedBy = mutation.by ?? null
534
+ /** 解释为测量或方法的缺陷:回灌成实体上的「缺陷」条目。 */
535
+ if (mutation.outcome === 'explained' && mutation.defect === true) item.defect = true
492
536
  item.resolvedAt = at
493
537
  break
494
538
  }
@@ -539,6 +583,12 @@ export function applyMutation(state, mutation) {
539
583
  break
540
584
  }
541
585
  case 'audit/dispatched': {
586
+ const previous = next.audits.find((item) => item.id === mutation.id)
587
+ if (previous !== undefined) {
588
+ if (mutation.evaluator_session) previous.child = mutation.evaluator_session
589
+ if (mutation.capability) previous.capability = mutation.capability
590
+ break
591
+ }
542
592
  next.audits.push({
543
593
  id: mutation.id,
544
594
  step: mutation.step,
@@ -592,6 +642,7 @@ export function applyMutation(state, mutation) {
592
642
  audit.verdict = mutation.verdict
593
643
  /** 两项裁决:交付成立吗 + 每条判断的结果。旧账没有这两格,`verdict` 那时说的就是交付成立吗。 */
594
644
  audit.holds = mutation.holds ?? null
645
+ audit.reuse = Array.isArray(mutation.reuse) ? clone(mutation.reuse) : []
595
646
  audit.results = Array.isArray(mutation.results) ? mutation.results : []
596
647
  audit.shortfalls = mutation.shortfalls ?? []
597
648
  audit.basis = mutation.basis ?? null
@@ -602,7 +653,7 @@ export function applyMutation(state, mutation) {
602
653
  const found = Array.isArray(mutation.anomalies) ? mutation.anomalies : []
603
654
  for (const [index, item] of found.entries()) {
604
655
  const id = `${mutation.id}#u${index + 1}`
605
- if (next.anomalies.some((entry) => entry.id === id)) continue
656
+ if (next.anomalies.some((entry) => entry.id === id || (entry.by === 'evaluator' && entry.step === mutation.step && entry.what === String(item?.what ?? '')))) continue
606
657
  next.anomalies.push({ id, what: String(item?.what ?? ''), anchor: null, step: mutation.step ?? null, by: 'evaluator', matters: item?.matters ?? null, status: 'open', reason: null, explainedBy: null, at, resolvedAt: null })
607
658
  }
608
659
  break
@@ -672,13 +723,22 @@ export function applyMutation(state, mutation) {
672
723
  goal: mutation.goal,
673
724
  hypothesis: mutation.hypothesis ?? null,
674
725
  text: mutation.text,
675
- scope: mutation.scope ?? null,
726
+ /** 涉及的实体或量(id):文件查找按它们取到这条事实。 */
727
+ about: isAbout(mutation.about) ? mutation.about.map(String) : [],
728
+ scope: mutation.scope_spec === undefined && mutation.refute_when === undefined ? null : mutation.scope ?? null,
729
+ /** 可比较的适用范围(`{conditions, ranges, note}`);旧账没有这一格,那时 `scope` 写的是推翻条件。 */
730
+ scope_spec: isScope(mutation.scope_spec) ? clone(mutation.scope_spec) : null,
731
+ refute_when: typeof mutation.refute_when === 'string' ? mutation.refute_when : mutation.scope_spec === undefined && typeof mutation.scope === 'string' ? mutation.scope : null,
732
+ /** 已知不适用之处:检验落在适用范围之外时记下的边界(`fact/bounded`),事实本身保持成立。 */
733
+ boundaries: [],
676
734
  level: mutation.level ?? null,
677
735
  evidence: mutation.evidence ?? [],
678
736
  path: mutation.path ?? null,
679
737
  assertions: Array.isArray(mutation.assertions) ? clone(mutation.assertions) : null,
680
738
  /** 升格那一刻,断言用到的词条各自的含义指纹:之后定义改了,这条事实要复核。 */
681
739
  definitions: mutation.definitions !== null && typeof mutation.definitions === 'object' && !Array.isArray(mutation.definitions) ? clone(mutation.definitions) : null,
740
+ /** 支撑它的可重跑核算(`clear/models/<id>.json`);没有就是 null。 */
741
+ use: typeof mutation.use === 'string' && mutation.use !== '' ? mutation.use : null,
682
742
  at,
683
743
  })
684
744
  break
@@ -707,9 +767,9 @@ export function applyMutation(state, mutation) {
707
767
  */
708
768
  const touchedOntology = (mutation.changes ?? []).some((change) => {
709
769
  const kind = classifyWorkspacePath(change?.path)?.kind
710
- return kind !== undefined && kind !== 'fact' && kind !== 'lesson'
770
+ return kind !== undefined && !KNOWLEDGE_FILE_KINDS.includes(kind)
711
771
  })
712
- if (touchedOntology || Object.keys(files).some((path) => !['fact', 'lesson'].includes(classifyWorkspacePath(path)?.kind))) {
772
+ if (touchedOntology || Object.keys(files).some((path) => !KNOWLEDGE_FILE_KINDS.includes(classifyWorkspacePath(path)?.kind))) {
713
773
  const ontology = materializeOntology(files)
714
774
  next.lexicon = ontology.lexicon
715
775
  next.entities = ontology.entities
@@ -731,6 +791,29 @@ export function applyMutation(state, mutation) {
731
791
  fact.review = { decision: mutation.decision === 'retracted' ? 'retracted' : 'kept', reason: mutation.reason ?? null, at, by: mutation.by ?? 'user' }
732
792
  break
733
793
  }
794
+ case 'fact/bounded': {
795
+ /**
796
+ * **检验落在事实的适用范围之外**:不是推翻,是记下一处边界(在哪里不成立)。
797
+ * 事实保持成立,不问人撤回;0.5.1 里九月数据撤回八月事实,就是把这两件事混成了一件。
798
+ */
799
+ const fact = next.facts.find((item) => item.id === mutation.fact)
800
+ if (fact === undefined) break
801
+ if (!Array.isArray(fact.boundaries)) fact.boundaries = []
802
+ fact.boundaries.push({ verdict: mutation.verdict ?? 'out_of_scope', reasons: Array.isArray(mutation.reasons) ? clone(mutation.reasons) : [], hypothesis: mutation.hypothesis ?? null, basis: mutation.basis ?? null, at })
803
+ break
804
+ }
805
+ case 'fact/questioned': {
806
+ /**
807
+ * **引用过它的判断被推翻**,而推翻落在它的适用范围之内(或范围说不清):事实回到「待核验」,
808
+ * 不撤回、不问人——判断被推翻不等于它引用的事实错了,但它不能再照旧当已知用。
809
+ * 人复核过(`fact/reviewed`)或别的会话的文件上记了复核,疑问就算处理了。
810
+ */
811
+ const fact = next.facts.find((item) => item.id === mutation.fact)
812
+ if (fact === undefined) break
813
+ if (!Array.isArray(fact.challenges)) fact.challenges = []
814
+ fact.challenges.push({ hypothesis: mutation.hypothesis ?? null, verdict: mutation.verdict ?? null, basis: mutation.basis ?? null, at })
815
+ break
816
+ }
734
817
  case 'ontology/term_added':
735
818
  case 'ontology/predicate_added':
736
819
  case 'ontology/term_revised':
@@ -909,6 +992,8 @@ export function applyEvent(state, event) {
909
992
  }
910
993
 
911
994
  function foldEvent(state, event) {
995
+ if (event.type === 'hook/result' && event.data?.point === 'ClearAIFact' && event.data?.handlerId?.startsWith('clearai-fact-') && isClearaiSource(event.data?.notice?.source)) return foldEvent(state, { ...event, type: 'user/message', data: event.data.notice })
996
+ if (event.type === 'clearai/facts') return foldEvent(state, { ...event, type: 'user/message' })
912
997
  if (event.type === 'user/message') {
913
998
  // 内核观察到的事实(候选技能、采纳记录、合并目录)走**插件消息的结构化 section**——
914
999
  // 记在会话日志里,所以状态仍然可以从日志重放出来,而不是靠一句散文。
@@ -1234,7 +1319,7 @@ export function knowledgePreflight(state, derived) {
1234
1319
  predicates: matchedPredicates.slice(0, LIMIT).map((predicate) => ({ id: predicate.id, label: predicate.label, gloss: predicate.gloss ?? '', kind: predicate.kind ?? null, shape: predicate.shape ?? null, check: predicate.check ?? null, domain: predicate.domain, range: predicate.range, functional: predicate.functional === true, status: predicate.status, uses: predicate.uses ?? 0, basis: predicate.basis ?? null })),
1235
1320
  predicatesTruncated: Math.max(0, matchedPredicates.length - LIMIT),
1236
1321
  /** 命中的既有事实(可复用的「已知」)。 */
1237
- facts: matchedFacts.slice(0, LIMIT).map((fact) => ({ id: fact.id, text: fact.text, level: fact.level ?? null, scope: fact.scope ?? null, hypothesis: fact.hypothesis ?? null, review: fact.review?.decision ?? null, foreign: fact.foreign === true })),
1322
+ facts: matchedFacts.slice(0, LIMIT).map((fact) => ({ id: fact.id, text: fact.text, level: fact.level ?? null, scope: tr(scopeText(fact.scope_spec, 'zh'), scopeText(fact.scope_spec, 'en')) || fact.scope || null, hypothesis: fact.hypothesis ?? null, review: fact.review?.decision ?? null, foreign: fact.foreign === true })),
1238
1323
  factsTruncated: Math.max(0, matchedFacts.length - LIMIT),
1239
1324
  /** 冲突:有就带上(它们约束「哪些结论还不能随便写)。 */
1240
1325
  conflicts: conflicts.map((conflict) => ({ predicate: conflict.predicate, subject: conflict.subject })),
@@ -1420,6 +1505,9 @@ function factHistory(fact, evidence) {
1420
1505
  reason: fact.review.reason ?? null,
1421
1506
  })
1422
1507
  }
1508
+ for (const bound of Array.isArray(fact?.boundaries) ? fact.boundaries : []) {
1509
+ events.push({ kind: 'fact/bounded', at: bound.at ?? null, summary: tr('检验落在适用范围之外:记下边界,事实保持成立', 'A test fell outside its scope: the boundary is recorded and the fact stays'), reason: bound.basis ?? null })
1510
+ }
1423
1511
  for (const item of evidence) events.push({ kind: 'evidence/recorded', at: item.at ?? null, summary: `${item.verdict}(${item.evaluator} · ${item.level})`, reason: item.basis ?? null })
1424
1512
  return events.filter((event) => event.at !== null).sort((left, right) => left.at - right.at)
1425
1513
  }
@@ -1840,6 +1928,10 @@ export function derive(state) {
1840
1928
  if (ownIds.has(row.id)) {
1841
1929
  const own = ownFacts.find((fact) => fact.id === row.id)
1842
1930
  if (own.review === null && row.review !== null) own.review = row.review
1931
+ own.calculation = row.calculation
1932
+ own.rechecks = row.rechecks
1933
+ own.evidence_records = row.evidence_records
1934
+ own.challenges = row.challenges
1843
1935
  continue
1844
1936
  }
1845
1937
  foreignFacts.push({ ...row, refuted: retestRefuted.has(row.id), foreign: true })
@@ -1854,8 +1946,20 @@ export function derive(state) {
1854
1946
  * 有它,这条事实就回到「待核验」:写进长期知识的东西遇到说不通的读数,不能照旧当已知用。
1855
1947
  */
1856
1948
  const openAnomalies = (state.anomalies ?? []).filter((item) => item?.status === 'open')
1857
- const questionedBy = (id) => openAnomalies.filter((item) => (item.touches ?? []).includes(id)).map((item) => item.id)
1858
- const factRows = [...foreignFacts, ...ownFacts].map((fact) => ({ ...fact, definitionsChanged: changedDefinitions(lexicon, fact.definitions), questioned: questionedBy(fact.id) }))
1949
+ const durableAnomalies = Object.entries(state.workspace?.files ?? {}).filter(([path]) => classifyWorkspacePath(path)?.kind === 'negative').map(([path, file]) => negativeFromFile(file?.data, path)).filter((row) => row && row.review?.decision !== 'retracted' && ['unresolved', 'defect', 'escalated'].includes(row.status))
1950
+ const questionedBy = (fact) => [
1951
+ ...openAnomalies.filter((item) => (item.touches ?? []).includes(fact.id)).map((item) => item.id),
1952
+ ...durableAnomalies.filter((row) => {
1953
+ if (!(row.touches.length ? row.touches : row.source?.anomaly ? row.about : []).includes(fact.id)) return false
1954
+ if (['out_of_scope', 'out_of_range'].includes(compareScope(fact.scope_spec, row.scope_spec).verdict)) return false
1955
+ if (fact.review?.decision === 'kept' && (fact.review.at ?? 0) >= (row.at ?? 0)) return false
1956
+ if ((fact.rechecks ?? []).some((reason) => reason.source === row.id && reason.status === 'resolved')) return false
1957
+ return true
1958
+ }).map((row) => row.id),
1959
+ ]
1960
+ /** 引用过它的判断被推翻留下的疑问(`fact/questioned` 或文件上的 `challenges`),人复核之后的不再算。 */
1961
+ const challengedBy = (fact) => (Array.isArray(fact.challenges) ? fact.challenges : []).filter((item) => fact.review === null || fact.review === undefined || (fact.review.at ?? 0) < (item.at ?? 0)).map((item) => `challenge:${item.hypothesis ?? '?'}`)
1962
+ const factRows = [...foreignFacts, ...ownFacts].map((fact) => ({ ...fact, definitionsChanged: changedDefinitions(lexicon, fact.definitions), questioned: [...questionedBy(fact), ...challengedBy(fact), ...(fact.rechecks ?? []).filter((reason) => reason.status === 'pending').map((reason) => `recheck:${reason.id}`)] }))
1859
1963
 
1860
1964
  /**
1861
1965
  * **领域词汇的派生读数**(两条,都不新存东西):
@@ -1878,6 +1982,17 @@ export function derive(state) {
1878
1982
  if (row !== null) lessonById.set(row.id, { ...lessonById.get(row.id), ...row, at: row.at ?? lessonById.get(row.id)?.at ?? null })
1879
1983
  }
1880
1984
  const lessonRows = [...lessonById.values()].filter((item) => item.status !== 'retracted').sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
1985
+ /**
1986
+ * **负向条目行**(已排除、未解、缺陷):只从 `clear/knowledge/negatives/` 读——内核随发生随写,
1987
+ * 本会话的条目同步进来以后与别的会话的同样读法。人在文件上写 `review.decision: "retracted"` 的不再列出。新的在前。
1988
+ */
1989
+ const negativeRows = []
1990
+ for (const [path, file] of Object.entries(state.workspace?.files ?? {})) {
1991
+ if (classifyWorkspacePath(path)?.kind !== 'negative' || file?.data === undefined) continue
1992
+ const row = negativeFromFile(file.data, path)
1993
+ if (row !== null && row.review?.decision !== 'retracted') negativeRows.push(row)
1994
+ }
1995
+ negativeRows.sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
1881
1996
  const conflicts = deriveConflicts(factRows, lexicon)
1882
1997
  const lexiconIssues = lexiconHealth(lexicon, factRows)
1883
1998
  /**
@@ -1926,6 +2041,7 @@ export function derive(state) {
1926
2041
  pendingAudit,
1927
2042
  factRows,
1928
2043
  lessonRows,
2044
+ negativeRows,
1929
2045
  settlement,
1930
2046
  stepOf,
1931
2047
  needYou,
@@ -1950,7 +2066,6 @@ const CANDIDATE_STATE = { credible: 'adopted', refuted: 'excluded', replaced: 's
1950
2066
  * 没写问题的目标就是一个问题(旧会话照样读得通);没指明归属的判断归第一个问题。
1951
2067
  * 候选的状态只从证据来(可信度分组的另一种读法),界面与卡读同一份。
1952
2068
  *
1953
- * `untapped`:本体里带形状的「影响」关系,还没有任何候选由它提出——只列出,不强制。
1954
2069
  * `next.indistinct`:下一步给每个候选都写了预测,但预测全一样:这一步区分不了它们。
1955
2070
  */
1956
2071
  export function deriveExploration(state, hypotheses, lexicon, activePlan) {
@@ -2002,8 +2117,6 @@ export function deriveExploration(state, hypotheses, lexicon, activePlan) {
2002
2117
  return { id: area.id, name: area.name, state, judgments: linked.length, verified: linked.filter((row) => row.state === 'adopted').length, openAnomalies: touched, questions: questionRows.filter((question) => question.area === area.id).map((question) => question.id) }
2003
2118
  })
2004
2119
  const current = questionRows.find((question) => question.status === 'open' && question.counts.examining > 0) ?? questionRows.find((question) => question.status === 'open') ?? null
2005
- const cited = new Set(mine.map((hypothesis) => hypothesis.from).filter((from) => typeof from === 'string'))
2006
- const untapped = (lexicon?.predicates ?? []).filter((predicate) => predicate.kind === 'affects' && typeof predicate.shape === 'string' && predicate.status !== 'deprecated' && !cited.has(predicate.id)).map((predicate) => ({ id: predicate.id, label: predicate.label || predicate.id, shape: predicate.shape }))
2007
2120
  const first = steps.find((step) => step.status === 'open') ?? null
2008
2121
  let next = null
2009
2122
  if (first !== null) {
@@ -2016,7 +2129,7 @@ export function deriveExploration(state, hypotheses, lexicon, activePlan) {
2016
2129
  const distinct = new Set(predictions.map((item) => item.expect.replace(/\s+/g, '')))
2017
2130
  next = { step: first.id, ordinal: first.ordinal, do: first.do, serves: first.serves ?? null, expect: first.expect ?? null, predictions, indistinct: predictions.length >= 2 && distinct.size === 1 }
2018
2131
  }
2019
- return { mode: goal.mode ?? null, questions: questionRows, areas: areaRows, current: current?.id ?? null, untapped, next, answers }
2132
+ return { mode: goal.mode ?? null, questions: questionRows, areas: areaRows, current: current?.id ?? null, next, answers }
2020
2133
  }
2021
2134
 
2022
2135
  /**
@@ -2101,9 +2214,146 @@ function historyRows(state, hypothesis) {
2101
2214
  }
2102
2215
 
2103
2216
  /** 面板契约。浏览器读的就是这个,一字不改。 */
2217
+ /** 名称比对用的规整(与内核取用时同一条规则):去空白、短横、下划线,小写。 */
2218
+ const nameKey = (raw) =>
2219
+ String(raw ?? '')
2220
+ .replace(/[\s_-]+/g, '')
2221
+ .toLowerCase()
2222
+
2223
+ /** 适用范围的一行读法:条件、取值范围、补充说明。 */
2224
+ function scopeLine(spec) {
2225
+ if (!isPlainObject(spec)) return null
2226
+ const parts = []
2227
+ for (const [key, value] of Object.entries(isPlainObject(spec.conditions) ? spec.conditions : {})) parts.push(`${key}=${Array.isArray(value) ? value.join('/') : String(value)}`)
2228
+ for (const [key, range] of Object.entries(isPlainObject(spec.ranges) ? spec.ranges : {})) {
2229
+ if (Array.isArray(range)) { parts.push(`${key} ${range[0]}–${range[1]}${spec.units?.[key] ? ` ${spec.units[key]}` : ''}`); continue }
2230
+ if (!isPlainObject(range)) continue
2231
+ const low = range.min ?? range.low ?? null
2232
+ const high = range.max ?? range.high ?? null
2233
+ parts.push(`${key} ${low ?? '…'}–${high ?? '…'}${range.unit ? ` ${range.unit}` : ''}`)
2234
+ }
2235
+ if (typeof spec.note === 'string' && spec.note.trim() !== '') parts.push(spec.note.trim())
2236
+ return parts.length === 0 ? null : parts.join(';')
2237
+ }
2238
+
2239
+ /**
2240
+ * **沉淀下来的知识,按条目列一份**(本体货架的实体卡、图上的计数、探索货架的两节与结论卡的摘要读它)。
2241
+ *
2242
+ * 事实:已撤回的不列;有推翻证据、开着的疑问或口径已变的是「待核验」,其余「已确立」;收窄过范围的带 `boundaries`。
2243
+ * 负向条目照文件上的状态;经验照种类。每条带 `about`,界面按实体的 id、名称与别名把条目挂到实体上。
2244
+ */
2245
+ function knowledgeItems(state, derived) {
2246
+ const items = []
2247
+ const evidencePaths = (rows) => [...new Set(rows.flatMap((row) => typeof row === 'string' ? [] : [row.ref, ...(row.refs ?? []), ...(row.origins ?? []).map((origin) => origin.path)]).filter((path) => typeof path === 'string' && /[/.]/.test(path)))]
2248
+ for (const fact of derived.factRows ?? []) {
2249
+ if (fact?.review?.decision === 'retracted') continue
2250
+ const pending = (fact.refuted === true && (fact.review === null || fact.review === undefined)) || (fact.questioned ?? []).length > 0 || (fact.definitionsChanged ?? []).length > 0
2251
+ items.push({
2252
+ id: fact.id,
2253
+ kind: 'fact',
2254
+ status: pending ? 'pending' : 'established',
2255
+ text: fact.text ?? '',
2256
+ about: Array.isArray(fact.about) ? fact.about : [],
2257
+ scope: scopeLine(fact.scope_spec),
2258
+ rechecks: (fact.rechecks ?? []).filter((row) => row.status === 'pending'),
2259
+ evidence: fact.evidence ?? [],
2260
+ evidencePaths: evidencePaths(fact.evidence_records ?? []),
2261
+ definitionsChanged: fact.definitionsChanged ?? [],
2262
+ recovery: '匹配范围的独立复检(retests)或人工明确裁决;其他未解决原因继续保留',
2263
+ boundaries: (Array.isArray(fact.boundaries) ? fact.boundaries : []).map((bound) => ({ verdict: bound.verdict ?? null, basis: bound.basis ?? null })),
2264
+ challenged: (fact.questioned ?? []).some((id) => String(id).startsWith('challenge:')),
2265
+ level: fact.level ?? null,
2266
+ goal: fact.goal ?? null,
2267
+ path: fact.path ?? null,
2268
+ })
2269
+ }
2270
+ for (const row of derived.negativeRows ?? []) {
2271
+ items.push({
2272
+ id: row.id,
2273
+ kind: 'negative',
2274
+ status: row.status,
2275
+ text: row.statement,
2276
+ about: row.about ?? [],
2277
+ scope: scopeLine(row.scope_spec),
2278
+ strength: row.strength ?? null,
2279
+ basis: row.resolution?.reason ?? null,
2280
+ evidencePaths: evidencePaths(row.evidence ?? []),
2281
+ goal: row.source?.goal ?? null,
2282
+ path: row.path ?? null,
2283
+ })
2284
+ }
2285
+ for (const lesson of derived.lessonRows ?? []) {
2286
+ items.push({ id: lesson.id, kind: 'lesson', status: lesson.kind ?? 'trap', text: lesson.text ?? '', about: Array.isArray(lesson.about) ? lesson.about : [], scope: lesson.boundary ?? scopeLine(lesson.scope_spec), evidencePaths: typeof lesson.evidence === 'string' && /[/.]/.test(lesson.evidence) ? [lesson.evidence] : [], goal: lesson.goal ?? null, path: lesson.path ?? null })
2287
+ }
2288
+ return items
2289
+ }
2290
+
2291
+ /** 一条条目在实体上算哪一格计数(图上的小数字与实体卡的栏目同一套)。 */
2292
+ const COUNT_BUCKET = { established: 'established', pending: 'pending', excluded: 'excluded', preliminary_excluded: 'excluded', unresolved: 'unresolved', escalated: 'unresolved' }
2293
+
2294
+ /** 实体图节点 → 挂在它上面的条目(按 id、名称、别名对 `about`)与各格计数。 */
2295
+ function entityKnowledge(state, graph, items) {
2296
+ const aliasesOf = new Map((Array.isArray(state.entities) ? state.entities : []).map((entity) => [String(entity?.id ?? ''), Array.isArray(entity?.aliases) ? entity.aliases : []]))
2297
+ const out = {}
2298
+ for (const node of graph.nodes) {
2299
+ if (node.layer !== 'entity' || node.kind !== 'instance') continue
2300
+ const keys = new Set([node.ref, node.label, ...(aliasesOf.get(String(node.ref ?? '')) ?? [])].map(nameKey).filter((key) => key.length >= 2))
2301
+ const ids = []
2302
+ const counts = { established: 0, excluded: 0, bounded: 0, pending: 0, unresolved: 0 }
2303
+ for (const item of items) {
2304
+ if (!item.about.some((name) => keys.has(nameKey(name)))) continue
2305
+ ids.push(`${item.kind}:${item.id}`)
2306
+ const bucket = item.kind === 'lesson' ? null : COUNT_BUCKET[item.status]
2307
+ if (bucket !== undefined && bucket !== null) counts[bucket] += 1
2308
+ if (item.kind === 'fact' && item.boundaries.length > 0) counts.bounded += 1
2309
+ }
2310
+ if (ids.length > 0) out[node.id] = { items: ids, counts }
2311
+ }
2312
+ return out
2313
+ }
2314
+
2315
+ /**
2316
+ * 探索货架的两节与结论卡的摘要:
2317
+ * · `cited`——本次判断通过 `uses` 引用的条目与系统判定(不是「适用」的排前面);
2318
+ * · `settling`——本目标已写下的负向条目,加上结案时待独立核验的判断;
2319
+ * · `settled`——本目标已沉淀的条数(已确立 / 已排除 / 未解释 / 测量或方法缺陷 / 经验)。
2320
+ */
2321
+ function knowledgeFlow(state, derived, items, promotedIds) {
2322
+ const goalId = state.goal?.id ?? null
2323
+ const byKey = new Map(items.map((item) => [item.id, item]))
2324
+ const cited = new Map()
2325
+ for (const hypothesis of derived.hypotheses ?? []) {
2326
+ for (const use of Array.isArray(hypothesis.uses) ? hypothesis.uses : []) {
2327
+ const key = `${use.id}|${use.verdict}`
2328
+ if (!cited.has(key)) cited.set(key, { id: use.id, kind: use.kind ?? byKey.get(use.id)?.kind ?? null, verdict: use.verdict ?? 'unknown', text: byKey.get(use.id)?.text ?? null, path: byKey.get(use.id)?.path ?? null, by: [] })
2329
+ cited.get(key).by.push(handleOf(hypothesis))
2330
+ }
2331
+ }
2332
+ const citedRows = [...cited.values()].sort((left, right) => (left.verdict === 'applies' ? 1 : 0) - (right.verdict === 'applies' ? 1 : 0))
2333
+ const mine = goalId === null ? [] : items.filter((item) => item.goal === goalId)
2334
+ const awaiting = (derived.hypotheses ?? []).filter((hypothesis) => !promotedIds.has(hypothesis.id) && ['credible', 'pending'].includes(trustOf(hypothesis, false))).map((hypothesis) => ({ id: hypothesis.id, name: handleOf(hypothesis), claim: hypothesis.claim ?? '' }))
2335
+ const count = (predicate) => mine.filter(predicate).length
2336
+ return {
2337
+ cited: citedRows,
2338
+ settling: { negatives: mine.filter((item) => item.kind === 'negative'), awaiting },
2339
+ settled:
2340
+ goalId === null
2341
+ ? null
2342
+ : {
2343
+ established: count((item) => item.kind === 'fact' && item.status === 'established'),
2344
+ excluded: count((item) => item.kind === 'negative' && (item.status === 'excluded' || item.status === 'preliminary_excluded')),
2345
+ unresolved: count((item) => item.kind === 'negative' && (item.status === 'unresolved' || item.status === 'escalated')),
2346
+ defects: count((item) => item.kind === 'negative' && item.status === 'defect'),
2347
+ lessons: count((item) => item.kind === 'lesson'),
2348
+ },
2349
+ }
2350
+ }
2351
+
2104
2352
  export function view(state, sessionId) {
2105
2353
  const derived = derive(state)
2106
2354
  const promotedIds = new Set((state.facts ?? []).map((fact) => fact?.hypothesis).filter((id) => typeof id === 'string'))
2355
+ const items = knowledgeItems(state, derived)
2356
+ const graph = graphProjection(state)
2107
2357
  const plan = derived.activePlan ?? derived.closedPlans[derived.closedPlans.length - 1] ?? null
2108
2358
  const sid = sessionId === undefined || sessionId === null ? (state.sessionId ?? null) : String(sessionId)
2109
2359
  return {
@@ -2140,7 +2390,7 @@ export function view(state, sessionId) {
2140
2390
  predicates: derived.lexicon.predicates,
2141
2391
  conflicts: derived.conflicts,
2142
2392
  health: derived.lexiconIssues,
2143
- graph: graphProjection(state),
2393
+ graph,
2144
2394
  /** 本体文件里的实体(带所在目录的容器)与跨文件问题:本体页的问题列表读它。 */
2145
2395
  entities: Array.isArray(state.entities) ? state.entities : [],
2146
2396
  problems: Array.isArray(state.ontologyProblems) ? state.ontologyProblems : [],
@@ -2150,6 +2400,14 @@ export function view(state, sessionId) {
2150
2400
  * 与卡片读的是同一份派生(判据只有一处:`deriveKnowledge`)。
2151
2401
  */
2152
2402
  knowledge: derived.knowledge,
2403
+ /**
2404
+ * **沉淀下来的知识**(事实、负向条目、经验,一条一行)与它们在实体上的挂法:
2405
+ * 实体卡与图上的计数读 `entityKnowledge`,探索货架的「引用的已有知识」「将沉淀的内容」
2406
+ * 与结论卡的「本次沉淀」读 `knowledgeFlow`。
2407
+ */
2408
+ knowledgeItems: items,
2409
+ entityKnowledge: entityKnowledge(state, graph, items),
2410
+ knowledgeFlow: knowledgeFlow(state, derived, items, promotedIds),
2153
2411
  /**
2154
2412
  * **单一叙述源**(`knowledge-view.js` 的 `knowledgeView`)。
2155
2413
  *
@@ -2194,6 +2452,8 @@ export function view(state, sessionId) {
2194
2452
  refuteWhen: hypothesis.refute_when,
2195
2453
  question: hypothesis.question ?? null,
2196
2454
  from: hypothesis.from ?? null,
2455
+ /** 引用的已有条目与系统当场的判定(`[{id, kind, verdict}]`)。 */
2456
+ uses: Array.isArray(hypothesis.uses) ? hypothesis.uses : [],
2197
2457
  status: hypothesis.status,
2198
2458
  supportedLevel: hypothesis.supportedLevel,
2199
2459
  refutations: hypothesis.refutations,