clearai-dsh 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/fold.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * 与预设内核的契约:`meta = { kind: 'clearai', v: 1, mutation: { t, ... } }`。
17
17
  * 词汇表由本文件的 `applyMutation` 定义;预设侧只负责产出,不负责解释。
18
18
  */
19
- import { applyLexiconMutation, changedDefinitions, materializeOntology, classifyWorkspacePath, deriveConflicts, emptyLexicon, factFromFile, formatAssertion, graphProjection, lexiconHealth, normalizeLexicon, objectKey, termUsage, VALUE_FORMS } from './domain-language.js'
19
+ import { applyLexiconMutation, changedDefinitions, materializeOntology, classifyWorkspacePath, deriveConflicts, emptyLexicon, factFromFile, formatAssertion, lessonFromFile, 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
22
 
@@ -60,9 +60,19 @@ export const MUTATION_KIND = 'clearai'
60
60
  * `definitionsChanged`。本体(词汇、实体、实体关系)改为从本体文件折出来,跨文件问题记在
61
61
  * `ontologyProblems`。旧日志里没有这些,折出来就是空的。
62
62
  * v15 → v16:多了 `language`(人说话用的语言,从人的消息折出来):系统写给人的话、面板里的读数都跟着它。
63
+ * v16 → v17:**预期与未解释**:步骤带 `expect`(`step/expected` 也能补写);多了 `anomalies`(未解释项,
64
+ * `anomaly/opened` / `anomaly/resolved` 折进来,评估者报的随 `audit/settled` 一起来);目标带
65
+ * `irreversible`(不可逆动作的命令特征);放行带 `action`。对手判断(`rival` / `split_by`)删了,
66
+ * 旧账里的这两格不再读。
67
+ * v17 → v18:多了 `lessons`(经验:结案时经独立评估核过的「下次要留意什么」,`lesson/recorded` 折进来;
68
+ * 别的会话留下的从 `clear/knowledge/lessons/<id>.json` 经 `workspace/synced` 进来)。
69
+ * v18 → v19:**探索的结构**:目标带 `mode`(广度调研 / 定向求解)、`questions`(问题)、`areas`(调研板块)
70
+ * 与结案时的 `answers`(按问题的结论四部分);判断带 `question`(属于哪个问题或板块)与 `from`
71
+ * (由本体里哪条关系提出);步骤带 `serves` 与按候选分别写的 `predictions`;未解释项带 `touches`
72
+ * (涉及的量、判断或事实)。全部可选:旧日志折出来就是整个目标一个问题。
63
73
  * 投影缓存按版本判定,所以旧缓存会被丢弃、从日志重折一遍。
64
74
  */
65
- export const STATE_VERSION = 16
75
+ export const STATE_VERSION = 19
66
76
 
67
77
  /**
68
78
  * **只留台账、不折进视图**的变更类型(词汇表的另一半)。
@@ -89,6 +99,13 @@ export function emptyState() {
89
99
  facts: [],
90
100
  blocks: {},
91
101
  releases: [],
102
+ /**
103
+ * **未解释项**(认识论里的「反常」):和预期或本体对不上的观测。只有三个去处:
104
+ * 被解释(`explained`)、写明理由排除(`ruled_out`)、交给人(`escalated`);没去处的就是开着(`open`)。
105
+ */
106
+ anomalies: [],
107
+ /** **经验**:本会话结案写下的(别的会话的在工作区文件里,派生时合进来)。 */
108
+ lessons: [],
92
109
  /**
93
110
  * **本体形状**:内核随投影下发的那份声明(对象/状态/边/等级)。
94
111
  * 为什么进投影而不是在界面里手抄:面板那一格的页眉要从**声明**生成——
@@ -196,6 +213,32 @@ export function normalizeTests(tests) {
196
213
  return { hypotheses, level: tests.level ?? null }
197
214
  }
198
215
 
216
+ /** 预测清单的唯一形状:`[{hypothesis, expect}]`,空的去掉。 */
217
+ export function normalizePredictions(raw) {
218
+ if (!Array.isArray(raw)) return []
219
+ return raw
220
+ .map((item) => ({ hypothesis: String(item?.hypothesis ?? '').trim(), expect: String(item?.expect ?? '').trim() }))
221
+ .filter((item) => item.hypothesis !== '' && item.expect !== '')
222
+ }
223
+
224
+ /** 问题与板块的唯一形状(目标上的读面):id、一句话、状态、所属板块。 */
225
+ const QUESTION_STATUS = ['open', 'emergent', 'parked']
226
+ function normalizeQuestions(raw) {
227
+ if (!Array.isArray(raw)) return null
228
+ return raw
229
+ .map((item) => ({
230
+ id: String(item?.id ?? '').trim(),
231
+ text: String(item?.text ?? '').trim(),
232
+ status: QUESTION_STATUS.includes(item?.status) ? item.status : 'open',
233
+ area: typeof item?.area === 'string' && item.area.trim() !== '' ? item.area.trim() : null,
234
+ }))
235
+ .filter((item) => item.id !== '' && item.text !== '')
236
+ }
237
+ function normalizeAreas(raw) {
238
+ if (!Array.isArray(raw)) return null
239
+ return raw.map((item) => ({ id: String(item?.id ?? '').trim(), name: String(item?.name ?? '').trim() })).filter((item) => item.id !== '' && item.name !== '')
240
+ }
241
+
199
242
  function appendSteps(plan, rawSteps) {
200
243
  for (const raw of rawSteps) {
201
244
  plan.steps.push({
@@ -205,6 +248,12 @@ function appendSteps(plan, rawSteps) {
205
248
  artifacts: raw.artifacts ?? [],
206
249
  done_criteria: raw.done_criteria,
207
250
  tests: normalizeTests(raw.tests),
251
+ /** 动手前写下的预期(可选);落空的地方记成未解释项。 */
252
+ expect: typeof raw.expect === 'string' && raw.expect !== '' ? raw.expect : null,
253
+ /** 这一步服务哪个问题或板块(可选;不写就挂在当前问题下)。 */
254
+ serves: typeof raw.serves === 'string' && raw.serves !== '' ? raw.serves : null,
255
+ /** 按候选分别写的预测:`{hypothesis, expect}`。各候选预测相同的一步区分不了它们。 */
256
+ predictions: normalizePredictions(raw.predictions),
208
257
  status: 'open',
209
258
  evidence: null,
210
259
  advancedAt: null,
@@ -226,6 +275,7 @@ export function applyMutation(state, mutation) {
226
275
  if (mutation === null || typeof mutation !== 'object' || typeof mutation.t !== 'string') return state
227
276
  const at = typeof mutation.at === 'number' ? mutation.at : 0
228
277
  const next = clone(state)
278
+ if (!Array.isArray(next.anomalies)) next.anomalies = []
229
279
  const RANK = { open: 0, blocked: 0, advanced: 1, void: 1 }
230
280
  const settle = (step, status) => {
231
281
  if (step === undefined || step === null) return
@@ -243,10 +293,16 @@ export function applyMutation(state, mutation) {
243
293
  previous.claim = mutation.claim
244
294
  previous.done_criteria = mutation.done_criteria
245
295
  previous.promote_at_level = mutation.promote_at_level
296
+ if (Array.isArray(mutation.irreversible)) previous.irreversible = clone(mutation.irreversible)
246
297
  /** 修订可以带上新的速览与判据清单(没带就保持旧值——「不提供」不等于「清空」)。 */
247
298
  if (typeof mutation.headline === 'string' && mutation.headline !== '') previous.headline = mutation.headline
248
299
  if (Array.isArray(mutation.criteria)) previous.criteria = clone(mutation.criteria)
249
300
  if (typeof mutation.criteria_note === 'string') previous.criteria_note = mutation.criteria_note
301
+ if (typeof mutation.mode === 'string' && mutation.mode !== '') previous.mode = mutation.mode
302
+ const questions = normalizeQuestions(mutation.questions)
303
+ if (questions !== null) previous.questions = questions
304
+ const areas = normalizeAreas(mutation.areas)
305
+ if (areas !== null) previous.areas = areas
250
306
  previous.reasons.push(mutation.reason ?? null)
251
307
  } else {
252
308
  if (previous !== null && previous.status === 'open') previous.status = 'superseded'
@@ -255,6 +311,8 @@ export function applyMutation(state, mutation) {
255
311
  claim: mutation.claim,
256
312
  done_criteria: mutation.done_criteria,
257
313
  promote_at_level: mutation.promote_at_level,
314
+ /** 不可逆动作:`{action, command}`,命令里出现 `command` 那段原文就要人放行。 */
315
+ irreversible: Array.isArray(mutation.irreversible) ? clone(mutation.irreversible) : [],
258
316
  status: 'open',
259
317
  revision: mutation.revision ?? 1,
260
318
  reasons: [mutation.reason ?? null],
@@ -276,6 +334,13 @@ export function applyMutation(state, mutation) {
276
334
  * `audit`,所以每一次改动都能指回是谁裁的。它只增不删(判据的历史就是判据的一部分)。
277
335
  */
278
336
  criteriaHistory: [],
337
+ /** 工作方式:`survey`(广度调研)/ `solve`(定向求解)/ `survey_then_solve`;没写就是 null。 */
338
+ mode: typeof mutation.mode === 'string' && mutation.mode !== '' ? mutation.mode : null,
339
+ /** 问题与调研板块(可选)。没有问题时,整个目标就是唯一的问题。 */
340
+ questions: normalizeQuestions(mutation.questions) ?? [],
341
+ areas: normalizeAreas(mutation.areas) ?? [],
342
+ /** 结案时按问题写的结论四部分(`Conclude.answers`)。 */
343
+ answers: [],
279
344
  }
280
345
  }
281
346
  for (const hypothesis of mutation.hypotheses ?? []) {
@@ -297,7 +362,10 @@ export function applyMutation(state, mutation) {
297
362
  known.refute_when = hypothesis.refute_when
298
363
  known.version = hypothesis.version ?? known.version
299
364
  if (typeof hypothesis.name === 'string' && hypothesis.name !== '') known.name = hypothesis.name
365
+ if (typeof hypothesis.retests === 'string' && hypothesis.retests !== '') known.retests = hypothesis.retests
300
366
  if (Array.isArray(hypothesis.assertions)) known.assertions = clone(hypothesis.assertions)
367
+ if (typeof hypothesis.question === 'string' && hypothesis.question !== '') known.question = hypothesis.question
368
+ if (typeof hypothesis.from === 'string' && hypothesis.from !== '') known.from = hypothesis.from
301
369
  continue
302
370
  }
303
371
  next.hypotheses.push({
@@ -307,6 +375,8 @@ export function applyMutation(state, mutation) {
307
375
  ...(typeof hypothesis.name === 'string' && hypothesis.name !== '' ? { name: hypothesis.name } : {}),
308
376
  claim,
309
377
  refute_when: hypothesis.refute_when,
378
+ /** 复检的是哪条已有事实(事实 id;可以是别的会话留下的)。 */
379
+ ...(typeof hypothesis.retests === 'string' && hypothesis.retests !== '' ? { retests: hypothesis.retests } : {}),
310
380
  status: 'proposed',
311
381
  version: hypothesis.version ?? 1,
312
382
  /**
@@ -314,6 +384,10 @@ export function applyMutation(state, mutation) {
314
384
  * 不写断言照旧成立(宽松+校验);写了就是「这条主张用这门语言怎么说」。
315
385
  */
316
386
  assertions: Array.isArray(hypothesis.assertions) ? clone(hypothesis.assertions) : null,
387
+ /** 属于哪个问题或板块(id);没写就归当前目标的第一个问题。 */
388
+ ...(typeof hypothesis.question === 'string' && hypothesis.question !== '' ? { question: hypothesis.question } : {}),
389
+ /** 由本体里哪条关系提出(关系 id);没写或写「直觉」都如实显示。 */
390
+ ...(typeof hypothesis.from === 'string' && hypothesis.from !== '' ? { from: hypothesis.from } : {}),
317
391
  at,
318
392
  })
319
393
  }
@@ -326,6 +400,7 @@ export function applyMutation(state, mutation) {
326
400
  next.goal.closeVerdict = mutation.verdict ?? null
327
401
  // 结案时如实记下「没被任何证据触及的假设」:未判不是「没问题」,是「没看过」。
328
402
  next.goal.unjudged = Array.isArray(mutation.unjudged) ? mutation.unjudged.slice() : []
403
+ if (Array.isArray(mutation.answers)) next.goal.answers = clone(mutation.answers)
329
404
  }
330
405
  break
331
406
  }
@@ -378,6 +453,45 @@ export function applyMutation(state, mutation) {
378
453
  step.criteria_versions.push(mutation.new_criteria) // 旧版本留着,什么都不删
379
454
  break
380
455
  }
456
+ case 'step/expected': {
457
+ const step = stepOf(mutation.plan, mutation.step)
458
+ if (step === undefined || step.status !== 'open') break
459
+ if (mutation.expect !== undefined) step.expect = String(mutation.expect ?? '') || null
460
+ if (Array.isArray(mutation.predictions)) step.predictions = normalizePredictions(mutation.predictions)
461
+ break
462
+ }
463
+ case 'anomaly/opened': {
464
+ if (next.anomalies.some((item) => item.id === mutation.id)) break
465
+ next.anomalies.push({ id: mutation.id, what: String(mutation.what ?? ''), anchor: mutation.anchor ?? null, touches: Array.isArray(mutation.touches) ? mutation.touches.map(String) : [], step: mutation.step ?? null, by: mutation.by ?? 'model', status: 'open', reason: null, explainedBy: null, at, resolvedAt: null })
466
+ break
467
+ }
468
+ case 'lesson/recorded': {
469
+ if (!Array.isArray(next.lessons)) next.lessons = []
470
+ if (next.lessons.some((item) => item.id === mutation.id)) break
471
+ next.lessons.push({
472
+ id: mutation.id,
473
+ goal: mutation.goal ?? null,
474
+ text: String(mutation.text ?? ''),
475
+ kind: mutation.kind ?? 'trap',
476
+ about: Array.isArray(mutation.about) ? mutation.about.map(String) : [],
477
+ evidence: mutation.evidence ?? null,
478
+ boundary: mutation.boundary ?? null,
479
+ status: 'active',
480
+ path: mutation.path ?? null,
481
+ at,
482
+ })
483
+ break
484
+ }
485
+ case 'anomaly/resolved': {
486
+ const item = next.anomalies.find((entry) => entry.id === mutation.id)
487
+ if (item === undefined || item.status !== 'open') break
488
+ if (!['explained', 'ruled_out', 'escalated'].includes(mutation.outcome)) break
489
+ item.status = mutation.outcome
490
+ item.reason = mutation.reason ?? null
491
+ item.explainedBy = mutation.by ?? null
492
+ item.resolvedAt = at
493
+ break
494
+ }
381
495
  case 'plan/voided': {
382
496
  const step = stepOf(mutation.plan, mutation.step)
383
497
  if (step === undefined) break
@@ -484,6 +598,13 @@ export function applyMutation(state, mutation) {
484
598
  audit.card_path = mutation.card_path ?? null
485
599
  if (mutation.digest !== undefined) audit.digest = mutation.digest ?? null
486
600
  }
601
+ /** 评估者报的、做的人没登记的异常:记成未解释项(id 由裁决 id 派生,重放幂等)。 */
602
+ const found = Array.isArray(mutation.anomalies) ? mutation.anomalies : []
603
+ for (const [index, item] of found.entries()) {
604
+ const id = `${mutation.id}#u${index + 1}`
605
+ if (next.anomalies.some((entry) => entry.id === id)) continue
606
+ 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
+ }
487
608
  break
488
609
  }
489
610
  case 'evidence/recorded': {
@@ -534,6 +655,8 @@ export function applyMutation(state, mutation) {
534
655
  via: mutation.via ?? null,
535
656
  at,
536
657
  call: mutation.call ?? null,
658
+ /** 放行的是哪件不可逆动作(拦在命令上的那道门);步级放行没有这一格。 */
659
+ ...(typeof mutation.action === 'string' && mutation.action !== '' ? { action: mutation.action } : {}),
537
660
  })
538
661
  break
539
662
  }
@@ -584,9 +707,9 @@ export function applyMutation(state, mutation) {
584
707
  */
585
708
  const touchedOntology = (mutation.changes ?? []).some((change) => {
586
709
  const kind = classifyWorkspacePath(change?.path)?.kind
587
- return kind !== undefined && kind !== 'fact'
710
+ return kind !== undefined && kind !== 'fact' && kind !== 'lesson'
588
711
  })
589
- if (touchedOntology || Object.keys(files).some((path) => classifyWorkspacePath(path)?.kind !== 'fact')) {
712
+ if (touchedOntology || Object.keys(files).some((path) => !['fact', 'lesson'].includes(classifyWorkspacePath(path)?.kind))) {
590
713
  const ontology = materializeOntology(files)
591
714
  next.lexicon = ontology.lexicon
592
715
  next.entities = ontology.entities
@@ -1077,7 +1200,9 @@ export function knowledgePreflight(state, derived) {
1077
1200
  const factRows = Array.isArray(derived?.factRows) ? derived.factRows : []
1078
1201
  const conflicts = Array.isArray(derived?.conflicts) ? derived.conflicts : []
1079
1202
  /** 命题的文本面:目标主张 + 每条命题的主张(去空白后做包含判断)。 */
1080
- const claimText = [state?.goal?.claim, ...hypotheses.map((item) => item.claim)].filter((text) => typeof text === 'string' && text !== '').map((text) => String(text).replace(/\s+/g, ''))
1203
+ /** 加上下一步要做什么与它的预期:预期引用的关系也要递到眼前。 */
1204
+ const nextStep = (derived?.activePlan?.steps ?? []).find((step) => step?.status === 'open') ?? null
1205
+ const claimText = [state?.goal?.claim, ...hypotheses.map((item) => item.claim), nextStep?.do, nextStep?.expect].filter((text) => typeof text === 'string' && text !== '').map((text) => String(text).replace(/\s+/g, ''))
1081
1206
  /** 命题已经引用的谓词(断言在假设上时就该算「在用」)。 */
1082
1207
  const usedPredicates = new Set(hypotheses.flatMap((item) => (Array.isArray(item.assertions) ? item.assertions : [])).map((assertion) => String(assertion?.predicate ?? '')))
1083
1208
  const hits = (entry) => {
@@ -1089,19 +1214,27 @@ export function knowledgePreflight(state, derived) {
1089
1214
  const matchedPredicates = predicates.filter((predicate) => usedPredicates.has(predicate.id) || hits(predicate))
1090
1215
  const matchedTermIds = new Set(matchedTerms.map((term) => term.id))
1091
1216
  const matchedPredicateIds = new Set(matchedPredicates.map((predicate) => predicate.id))
1092
- /** 事实:断言引用了命中的谓词,或主词类型是命中的概念。 */
1093
- const matchedFacts = factRows.filter((fact) =>
1094
- (Array.isArray(fact.assertions) ? fact.assertions : []).some((assertion) => matchedPredicateIds.has(String(assertion?.predicate ?? '')) || matchedTermIds.has(String(assertion?.subject?.type ?? ''))),
1217
+ /**
1218
+ * 事实:断言引用了命中的谓词或概念;**或**升格时按词面挂上的定义里有命中的词(真跑里事实几乎都没有断言,
1219
+ * 只认断言等于从不命中);**或**有判断用 `retests` 指着它。撤回的不给。
1220
+ */
1221
+ const retested = new Set(hypotheses.map((item) => item.retests).filter((id) => typeof id === 'string'))
1222
+ const matchedFacts = factRows.filter(
1223
+ (fact) =>
1224
+ fact.review?.decision !== 'retracted' &&
1225
+ (retested.has(fact.id) ||
1226
+ Object.keys(fact.definitions ?? {}).some((id) => matchedTermIds.has(id) || matchedPredicateIds.has(id)) ||
1227
+ (Array.isArray(fact.assertions) ? fact.assertions : []).some((assertion) => matchedPredicateIds.has(String(assertion?.predicate ?? '')) || matchedTermIds.has(String(assertion?.subject?.type ?? '')))),
1095
1228
  )
1096
1229
  return {
1097
1230
  mode: 'knowledge',
1098
1231
  /** 词面命中的词汇:模型接下来要写的结论大概率会用到它们。 */
1099
- terms: matchedTerms.slice(0, LIMIT).map((term) => ({ id: term.id, label: term.label, gloss: term.gloss, parent: term.parent ?? null, status: term.status, uses: term.uses ?? 0, basis: term.basis ?? null })),
1232
+ terms: matchedTerms.slice(0, LIMIT).map((term) => ({ id: term.id, label: term.label, gloss: term.gloss, kind: term.kind ?? null, unit: term.unit ?? null, parent: term.parent ?? null, status: term.status, uses: term.uses ?? 0, basis: term.basis ?? null })),
1100
1233
  termsTruncated: Math.max(0, matchedTerms.length - LIMIT),
1101
- predicates: matchedPredicates.slice(0, LIMIT).map((predicate) => ({ id: predicate.id, label: predicate.label, domain: predicate.domain, range: predicate.range, functional: predicate.functional === true, status: predicate.status, uses: predicate.uses ?? 0, basis: predicate.basis ?? null })),
1234
+ 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 })),
1102
1235
  predicatesTruncated: Math.max(0, matchedPredicates.length - LIMIT),
1103
1236
  /** 命中的既有事实(可复用的「已知」)。 */
1104
- 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 })),
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 })),
1105
1238
  factsTruncated: Math.max(0, matchedFacts.length - LIMIT),
1106
1239
  /** 冲突:有就带上(它们约束「哪些结论还不能随便写)。 */
1107
1240
  conflicts: conflicts.map((conflict) => ({ predicate: conflict.predicate, subject: conflict.subject })),
@@ -1685,15 +1818,18 @@ export function derive(state) {
1685
1818
  * · `review` ——人已经审查过(撤回 / 维持),决定连缘由一起留着。
1686
1819
  */
1687
1820
  const lexicon = normalizeLexicon(state.lexicon)
1821
+ /** 声明了 `retests` 的判断被推翻 ⇒ 它复检的那条事实也算被推翻(跨会话只认事实 id)。 */
1822
+ const retestRefuted = new Set(hypotheses.filter((item) => typeof item.retests === 'string' && (item.refutations ?? 0) > 0).map((item) => item.retests))
1688
1823
  const ownFacts = (state.facts ?? []).map((fact) => {
1689
1824
  const linked = typeof fact.hypothesis === 'string' && fact.hypothesis !== ''
1690
1825
  const owner = hypotheses.find((item) => (linked ? item.id === fact.hypothesis : String(item.claim ?? '') === String(fact.text ?? '')))
1691
- return { ...fact, refuted: (owner?.refutations ?? 0) > 0, review: fact.review ?? null, foreign: false }
1826
+ return { ...fact, refuted: (owner?.refutations ?? 0) > 0 || retestRefuted.has(fact.id), review: fact.review ?? null, foreign: false }
1692
1827
  })
1693
1828
  /**
1694
1829
  * **别的会话留下的事实**(住在 `clear/knowledge/facts/<id>.json`,经 `workspace/synced` 进账)。
1695
1830
  * 同一个 id 本会话账上也有就以账上那条为准(它带着推翻读数);文件上的复核结论照样认。
1696
- * 它们的假设不在本会话,所以 `refuted` 只能是 false——推翻要在这里重新检验一次才算。
1831
+ * 它们的假设不在本会话,所以推翻要在这里重新检验一次才算:本会话的判断用 `retests` 指向它,
1832
+ * 那条判断被推翻,这条事实就标「被推翻」。
1697
1833
  */
1698
1834
  const ownIds = new Set(ownFacts.map((fact) => fact.id))
1699
1835
  const foreignFacts = []
@@ -1706,14 +1842,20 @@ export function derive(state) {
1706
1842
  if (own.review === null && row.review !== null) own.review = row.review
1707
1843
  continue
1708
1844
  }
1709
- foreignFacts.push({ ...row, refuted: false, foreign: true })
1845
+ foreignFacts.push({ ...row, refuted: retestRefuted.has(row.id), foreign: true })
1710
1846
  }
1711
1847
  foreignFacts.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
1712
1848
  /**
1713
1849
  * `definitionsChanged`:升格那一刻用到的词条,**含义**此后改过或已不在的那些 id。
1714
1850
  * 只是读数,不撤回事实:改了定义的人知道为什么改,复核交给人与证据。
1715
1851
  */
1716
- const factRows = [...foreignFacts, ...ownFacts].map((fact) => ({ ...fact, definitionsChanged: changedDefinitions(lexicon, fact.definitions) }))
1852
+ /**
1853
+ * `questioned`:还开着、且点名涉及这条事实的未解释项(`touches` 里写了事实 id)。
1854
+ * 有它,这条事实就回到「待核验」:写进长期知识的东西遇到说不通的读数,不能照旧当已知用。
1855
+ */
1856
+ 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) }))
1717
1859
 
1718
1860
  /**
1719
1861
  * **领域词汇的派生读数**(两条,都不新存东西):
@@ -1724,6 +1866,18 @@ export function derive(state) {
1724
1866
  * 两者都吃 `factRows` 而不是 `state.facts`:事实的复核态与推翻标记是派生的,
1725
1867
  * 在这里重算一遍就等于第二份判据。
1726
1868
  */
1869
+ /**
1870
+ * **经验行**:本会话写下的,加上别的会话留在 `clear/knowledge/lessons/` 的。同 id 以文件为准
1871
+ * (人可以在文件上标 `status: "retracted"` 撤回);撤回的不再推送。新的在前。
1872
+ */
1873
+ const lessonById = new Map()
1874
+ for (const item of state.lessons ?? []) lessonById.set(item.id, { ...item })
1875
+ for (const [path, file] of Object.entries(state.workspace?.files ?? {})) {
1876
+ if (classifyWorkspacePath(path)?.kind !== 'lesson' || file?.data === undefined) continue
1877
+ const row = lessonFromFile(file.data, path)
1878
+ if (row !== null) lessonById.set(row.id, { ...lessonById.get(row.id), ...row, at: row.at ?? lessonById.get(row.id)?.at ?? null })
1879
+ }
1880
+ const lessonRows = [...lessonById.values()].filter((item) => item.status !== 'retracted').sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
1727
1881
  const conflicts = deriveConflicts(factRows, lexicon)
1728
1882
  const lexiconIssues = lexiconHealth(lexicon, factRows)
1729
1883
  /**
@@ -1771,6 +1925,7 @@ export function derive(state) {
1771
1925
  closedPlans,
1772
1926
  pendingAudit,
1773
1927
  factRows,
1928
+ lessonRows,
1774
1929
  settlement,
1775
1930
  stepOf,
1776
1931
  needYou,
@@ -1780,7 +1935,88 @@ export function derive(state) {
1780
1935
  lexiconIssues,
1781
1936
  /** 知识模式(分诊)与缺口读数:结构判据,不猜词面(见 `deriveKnowledge`)。 */
1782
1937
  knowledge: deriveKnowledge(state, hypotheses, factRows, lexicon),
1938
+ /** 探索的结构:问题 → 候选假设(或板块 → 新发现的问题)、下一步各候选的预测(见 `deriveExploration`)。 */
1939
+ exploration: deriveExploration(state, hypotheses, lexicon, activePlan),
1940
+ }
1941
+ }
1942
+
1943
+ /** 候选假设的四种状态(界面:考察中 / 已排除 / 已采纳 / 暂不考察),由可信度分组算出,不另存。 */
1944
+ const CANDIDATE_STATE = { credible: 'adopted', refuted: 'excluded', replaced: 'set_aside', pending: 'examining', testing: 'examining', unclear: 'examining' }
1945
+
1946
+ /**
1947
+ * **探索的结构**(派生,不存):课题 → 问题 → 候选假设 → 步骤;广度调研时课题 → 调研板块 → 问题。
1948
+ *
1949
+ * 问题与板块由模型立题时写(`Frame.questions` / `areas`),判断用 `question` 指明属于哪个问题或板块。
1950
+ * 没写问题的目标就是一个问题(旧会话照样读得通);没指明归属的判断归第一个问题。
1951
+ * 候选的状态只从证据来(可信度分组的另一种读法),界面与卡读同一份。
1952
+ *
1953
+ * `untapped`:本体里带形状的「影响」关系,还没有任何候选由它提出——只列出,不强制。
1954
+ * `next.indistinct`:下一步给每个候选都写了预测,但预测全一样:这一步区分不了它们。
1955
+ */
1956
+ export function deriveExploration(state, hypotheses, lexicon, activePlan) {
1957
+ const goal = state?.goal ?? null
1958
+ if (goal === null) return null
1959
+ const promoted = new Set((state.facts ?? []).map((fact) => fact?.hypothesis).filter((id) => typeof id === 'string'))
1960
+ const mine = hypotheses.filter((item) => typeof item.goal !== 'string' || item.goal === goal.id)
1961
+ const declared = Array.isArray(goal.questions) ? goal.questions : []
1962
+ const areas = Array.isArray(goal.areas) ? goal.areas : []
1963
+ const areaIds = new Set(areas.map((area) => area.id))
1964
+ const answers = Array.isArray(goal.answers) ? goal.answers : []
1965
+ const questions =
1966
+ declared.length > 0
1967
+ ? declared.map((item) => ({ ...item, implicit: false }))
1968
+ : areas.length > 0
1969
+ ? []
1970
+ : [{ id: 'goal', text: String(goal.headline ?? goal.claim ?? ''), status: 'open', area: null, implicit: true }]
1971
+ const fallback = questions.find((item) => item.status === 'open')?.id ?? questions[0]?.id ?? null
1972
+ const homeOf = (hypothesis) => {
1973
+ const wanted = typeof hypothesis.question === 'string' ? hypothesis.question : ''
1974
+ if (questions.some((item) => item.id === wanted) || areaIds.has(wanted)) return wanted
1975
+ return fallback
1976
+ }
1977
+ const candidateOf = (hypothesis) => ({
1978
+ id: hypothesis.id,
1979
+ name: handleOf(hypothesis),
1980
+ claim: hypothesis.claim ?? '',
1981
+ refuteWhen: hypothesis.refute_when ?? '',
1982
+ from: typeof hypothesis.from === 'string' && hypothesis.from !== '' ? hypothesis.from : null,
1983
+ state: CANDIDATE_STATE[trustOf(hypothesis, promoted.has(hypothesis.id))] ?? 'examining',
1984
+ supportedLevel: hypothesis.supportedLevel ?? null,
1985
+ refutations: hypothesis.refutations ?? 0,
1986
+ inconclusive: hypothesis.inconclusive ?? 0,
1987
+ })
1988
+ const count = (rows) => ({ examining: rows.filter((row) => row.state === 'examining').length, excluded: rows.filter((row) => row.state === 'excluded').length, adopted: rows.filter((row) => row.state === 'adopted').length, setAside: rows.filter((row) => row.state === 'set_aside').length })
1989
+ const questionRows = questions.map((question) => {
1990
+ const candidates = mine.filter((hypothesis) => homeOf(hypothesis) === question.id).map(candidateOf)
1991
+ const answer = answers.find((item) => item?.question === question.id) ?? (question.implicit ? (answers[0] ?? null) : null)
1992
+ return { ...question, status: answer !== null && answer !== undefined ? 'answered' : question.status, candidates, counts: count(candidates) }
1993
+ })
1994
+ const openAnomalies = (state.anomalies ?? []).filter((item) => item?.status === 'open')
1995
+ const steps = activePlan?.steps ?? []
1996
+ const areaRows = areas.map((area) => {
1997
+ const linked = mine.filter((hypothesis) => homeOf(hypothesis) === area.id || questions.some((question) => question.area === area.id && homeOf(hypothesis) === question.id)).map(candidateOf)
1998
+ const served = steps.some((step) => step.serves === area.id)
1999
+ const touched = openAnomalies.filter((item) => (item.touches ?? []).includes(area.id) || (item.touches ?? []).includes(area.name)).length
2000
+ const settled = linked.length > 0 && linked.every((row) => row.state === 'adopted' || row.state === 'excluded' || row.state === 'set_aside')
2001
+ const state = linked.length === 0 && !served ? 'not_started' : settled && touched === 0 ? 'clear' : 'in_progress'
2002
+ 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
+ })
2004
+ 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
+ const first = steps.find((step) => step.status === 'open') ?? null
2008
+ let next = null
2009
+ if (first !== null) {
2010
+ const named = new Map(mine.map((hypothesis) => [hypothesis.id, hypothesis]))
2011
+ const byName = (key) => mine.find((hypothesis) => hypothesis.id === key || hypothesis.name === key) ?? null
2012
+ const predictions = (first.predictions ?? []).map((item) => {
2013
+ const hypothesis = byName(item.hypothesis)
2014
+ return { hypothesis: hypothesis?.id ?? null, name: hypothesis === null ? item.hypothesis : handleOf(named.get(hypothesis.id)), expect: item.expect }
2015
+ })
2016
+ const distinct = new Set(predictions.map((item) => item.expect.replace(/\s+/g, '')))
2017
+ 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 }
1783
2018
  }
2019
+ return { mode: goal.mode ?? null, questions: questionRows, areas: areaRows, current: current?.id ?? null, untapped, next, answers }
1784
2020
  }
1785
2021
 
1786
2022
  /**
@@ -1889,6 +2125,10 @@ export function view(state, sessionId) {
1889
2125
  releases: (state.releases ?? []).map((item) => ({ step: item.step ?? null, plan: item.plan ?? null, via: item.via ?? null, call: item.call ?? null, at: item.at ?? null })),
1890
2126
  /** 本体形状(面板页眉据此生成,不手抄)。 */
1891
2127
  ontology: state.ontology ?? null,
2128
+ /** 探索的结构(探索货架读它;与卡上「你在哪」同一份派生)。 */
2129
+ exploration: derived.exploration,
2130
+ /** 未解释项(探索货架「过程记录」与本体货架的复核标记读它)。 */
2131
+ anomalies: (state.anomalies ?? []).map((item) => ({ id: item.id, what: item.what, anchor: item.anchor ?? null, touches: item.touches ?? [], step: item.step ?? null, by: item.by ?? 'model', status: item.status, reason: item.reason ?? null, explainedBy: item.explainedBy ?? null, at: item.at ?? null })),
1892
2132
  /**
1893
2133
  * **领域词汇的读面**:概念、谓词、冲突、健康读数与图投影。
1894
2134
  *
@@ -1941,6 +2181,10 @@ export function view(state, sessionId) {
1941
2181
  // 结案留痕:没被任何证据触及的假设。未判不是「没问题」,是「没看过」。
1942
2182
  unjudged: Array.isArray(state.goal.unjudged) ? state.goal.unjudged.slice() : [],
1943
2183
  closeVerdict: state.goal.closeVerdict ?? null,
2184
+ headline: state.goal.headline ?? null,
2185
+ mode: state.goal.mode ?? null,
2186
+ /** 结案时按问题写的结论四部分(本体货架的结论卡读它)。 */
2187
+ answers: Array.isArray(state.goal.answers) ? state.goal.answers : [],
1944
2188
  hypotheses: derived.hypotheses.map((hypothesis) => ({
1945
2189
  id: hypothesis.id,
1946
2190
  name: handleOf(hypothesis),
@@ -1948,6 +2192,8 @@ export function view(state, sessionId) {
1948
2192
  trust: trustOf(hypothesis, promotedIds.has(hypothesis.id)),
1949
2193
  claim: hypothesis.claim,
1950
2194
  refuteWhen: hypothesis.refute_when,
2195
+ question: hypothesis.question ?? null,
2196
+ from: hypothesis.from ?? null,
1951
2197
  status: hypothesis.status,
1952
2198
  supportedLevel: hypothesis.supportedLevel,
1953
2199
  refutations: hypothesis.refutations,
@@ -1981,6 +2227,9 @@ export function view(state, sessionId) {
1981
2227
  artifacts: (step.artifacts ?? []).map((artifact) => (typeof artifact === 'string' ? { path: artifact, exists: null } : artifact)),
1982
2228
  doneCriteria: step.done_criteria,
1983
2229
  tests: step.tests,
2230
+ expect: step.expect ?? null,
2231
+ serves: step.serves ?? null,
2232
+ predictions: step.predictions ?? [],
1984
2233
  status: step.status,
1985
2234
  evidenceIds: step.evidence ?? [],
1986
2235
  /** 交付本身(谁判的、凭什么、出处);旧账为 null。 */
@@ -2010,6 +2259,9 @@ export function view(state, sessionId) {
2010
2259
  artifacts: (step.artifacts ?? []).map((artifact) => (typeof artifact === 'string' ? { path: artifact, exists: null } : artifact)),
2011
2260
  doneCriteria: step.done_criteria,
2012
2261
  tests: step.tests,
2262
+ expect: step.expect ?? null,
2263
+ serves: step.serves ?? null,
2264
+ predictions: step.predictions ?? [],
2013
2265
  status: step.status,
2014
2266
  evidenceIds: step.evidence ?? [],
2015
2267
  /** 交付本身(谁判的、凭什么、出处);旧账为 null。 */
@@ -2099,7 +2351,11 @@ export function view(state, sessionId) {
2099
2351
  /** 派生:收到过推翻证据(要复核)与人的审查决定(撤回 / 维持)。 */
2100
2352
  refuted: item.refuted === true,
2101
2353
  review: item.review ?? null,
2354
+ /** 还开着、点名涉及它的未解释项:有就回到「待核验」。 */
2355
+ questioned: item.questioned ?? [],
2102
2356
  })),
2357
+ /** 经验(本体货架列出;与卡上同一份,含别的会话留下的)。 */
2358
+ lessons: (derived.lessonRows ?? []).map((item) => ({ id: item.id, kind: item.kind ?? 'trap', text: item.text ?? '', boundary: item.boundary ?? null, about: item.about ?? [] })),
2103
2359
  }
2104
2360
  }
2105
2361