clearai-dsh 0.5.0 → 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.
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { graphProjection } from './domain-language.js'
22
22
  import { bilingual, tr } from './lang.js'
23
+ import { scopeText } from './scope.js'
23
24
 
24
25
  /** 卡文本上限。模型每一步只读这一张卡,而卡是**每回合**重算的:它必须小到能进预算。 */
25
26
  const CARD_LIMIT = 3000
@@ -67,7 +68,7 @@ export const GLOSSARY = bilingual({
67
68
  nextAction: ['派一次独立评估,把评估卡作为出处', 'Get one independent evaluation and cite its evaluation card'],
68
69
  },
69
70
  L4: {
70
- plain: ['人放行:交付前有人看过并批准', 'Released by a person: someone looked at it and approved before delivery'],
71
+ plain: ['人工批准:交付前已有人审阅并批准', 'Released by a person: someone looked at it and approved before delivery'],
71
72
  where: ['docs/verification-loop.md 的等级表', 'the level table in docs/verification-loop.md'],
72
73
  nextAction: ['等一次人的放行记录;没有人就不要声称到过这一级', 'Wait for a person to release it; without one, do not claim this level'],
73
74
  },
@@ -144,8 +145,8 @@ export const GLOSSARY = bilingual({
144
145
  plain: ['命题只有散文主张:两条结论是不是在说同一件事只能靠重读判断', 'Prose-only claims: whether two conclusions say the same thing can only be judged by rereading'],
145
146
  where: ['运行态卡 · 缺口', 'runtime card · gaps'],
146
147
  nextAction: [
147
- '先在 clear/ontology/ 下写概念、关系与主体的实体文件,再用 Frame 修订把主张写成断言(主词–谓词–宾语)',
148
- 'First write concept, relation and subject entity files under clear/ontology/, then revise with Frame to turn the claim into assertions (subject–predicate–object)',
148
+ '可选:用 Frame 修订在 ontology 里补上概念与关系,再把主张写成断言(主词–谓词–宾语)',
149
+ 'Optional: revise with Frame to add the concepts and relations in ontology, then write the claim as assertions (subject–predicate–object)',
149
150
  ],
150
151
  },
151
152
  untouched_claims: {
@@ -192,8 +193,8 @@ export const LEVELS = ['L0', 'L1', 'L2', 'L3', 'L4']
192
193
  * **说人话的三张小表**(第六阶段)。内部名不改;卡、工具结果与面板上一律写右边那一列。
193
194
  * 模型读到什么就会照着说什么——所以卡先说人话,答复才说得出人话。
194
195
  */
195
- /** 等级只说三档:L0–L2 合并成「自己检验」(旧账里的 L0 / L1 也这么读),L3 独立评估,L4 人放行。 */
196
- export const LEVEL_WORD = bilingual({ L0: ['自己检验', 'self-tested'], L1: ['自己检验', 'self-tested'], L2: ['自己检验', 'self-tested'], L3: ['独立核验', 'independent check'], L4: ['人放行', 'released by a person'] })
196
+ /** 等级只说三档:L0–L2 合并成「自行检验」(旧账里的 L0 / L1 也这么读),L3 独立评估,L4 人工批准。 */
197
+ export const LEVEL_WORD = bilingual({ L0: ['自行检验', 'self-tested'], L1: ['自行检验', 'self-tested'], L2: ['自行检验', 'self-tested'], L3: ['独立核验', 'independent check'], L4: ['人工批准', 'approved by a person'] })
197
198
  export const VERDICT_WORD = bilingual({ support: ['支持', 'support'], refute: ['推翻', 'refute'], inconclusive: ['不确定', 'inconclusive'] })
198
199
  /** 判断短名的上限(汉字);没起名时取主张开头这么宽。与内核同一个数。 */
199
200
  export const HANDLE_LIMIT = 12
@@ -338,12 +339,19 @@ export function readingOf(hypothesis) {
338
339
  /** 步骤状态的人话。 */
339
340
  const STEP_WORD = bilingual({ open: ['待做', 'to do'], advanced: ['已交付', 'delivered'], void: ['已作废', 'voided'] })
340
341
 
341
- /** 一条事实在卡上的一行:原话、边界、等级;来自别的会话的标出来。 */
342
+ /** 一条事实在卡上的一行:原话、适用范围、等级;来自别的会话的标出来。 */
343
+ /** 有开着的未解释项点名这条事实:它回到「待核验」,直到那些未解释项有了去处。 */
344
+ function questionedNote(fact, language) {
345
+ const ids = Array.isArray(fact?.questioned) ? fact.questioned : []
346
+ if (ids.length === 0) return ''
347
+ return language === 'en' ? ` · pending re-check (unexplained ${ids.join(', ')})` : ` · 待核验(未解释项 ${ids.join('、')})`
348
+ }
349
+
342
350
  function factLine(fact) {
343
- const scope = oneLine(fact?.scope ?? '')
351
+ const scope = oneLine(tr(scopeText(fact?.scope_spec, 'zh'), scopeText(fact?.scope_spec, 'en')) || fact?.scope || '')
344
352
  return tr(
345
- ` · 「${clamp(fact?.text, 100)}」${scope === '' ? '' : ` — 边界:${clamp(scope, 80)}`}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · 以前的会话' : ''}`,
346
- ` · "${clamp(fact?.text, 100)}"${scope === '' ? '' : ` — boundary: ${clamp(scope, 80)}`}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · earlier session' : ''}`,
353
+ ` · 「${clamp(fact?.text, 100)}」 — 适用范围:${scope === '' ? '未声明' : clamp(scope, 80)}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · 以前的会话' : ''}${questionedNote(fact, 'zh')}`,
354
+ ` · "${clamp(fact?.text, 100)}" — scope: ${scope === '' ? 'not declared' : clamp(scope, 80)}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · earlier session' : ''}${questionedNote(fact, 'en')}`,
347
355
  )
348
356
  }
349
357
 
@@ -413,11 +421,30 @@ function cardLines(state, derived, options, view) {
413
421
  const terminal = group.key === 'refuted' || group.key === 'replaced'
414
422
  const named = typeof hypothesis.name === 'string' && hypothesis.name.trim() !== ''
415
423
  const head = tr(named ? `「${hypothesis.name.trim()}」${clamp(hypothesis.claim, 120)}` : `「${clamp(hypothesis.claim, 120)}」`, named ? `"${hypothesis.name.trim()}" ${clamp(hypothesis.claim, 120)}` : `"${clamp(hypothesis.claim, 120)}"`)
416
- const refute = terminal ? '' : tr(` — 算错的条件:${clamp(hypothesis.refute_when, 100)}`, ` — wrong if: ${clamp(hypothesis.refute_when, 100)}`)
424
+ const refute = terminal ? '' : tr(` — 推翻条件:${clamp(hypothesis.refute_when, 100)}`, ` — wrong if: ${clamp(hypothesis.refute_when, 100)}`)
417
425
  push(` · ${head}${refute} · ${readingOf(hypothesis)}`, terminal ? 1 : 0)
418
426
  }
419
427
  }
420
- if (hypotheses.length > 10) push(tr(` · 还有 ${hypotheses.length - 10} 条判断没展开(面板「本体」里有全部)`, ` · ${hypotheses.length - 10} more judgments not shown (all are in the Ontology pane)`), 2)
428
+ if (hypotheses.length > 10) push(tr(` · 还有 ${hypotheses.length - 10} 条判断没展开(「探索」货架里有全部)`, ` · ${hypotheses.length - 10} more judgments not shown (all are in the Explore shelf)`), 2)
429
+ }
430
+ /**
431
+ * **当前位置**:问题 → 候选假设(或调研板块)的计数,与探索货架同一份派生(`derived.exploration`)。
432
+ * 只在目标开着时给;没列问题的目标就是一个问题,这一行省掉(上面的判断列表已经说清)。
433
+ */
434
+ const exploration = isPlainObject(derived?.exploration) ? derived.exploration : null
435
+ if (exploration !== null && goal !== null && String(goal.status) === 'open') {
436
+ const STATE_WORD = { examining: tr('考察中', 'being examined'), excluded: tr('已排除', 'excluded'), adopted: tr('已采纳', 'adopted'), set_aside: tr('暂不考察', 'set aside') }
437
+ const AREA_WORD = { not_started: tr('未开始', 'not started'), in_progress: tr('调研中', 'in progress'), clear: tr('已厘清', 'clear') }
438
+ const declared = (exploration.questions ?? []).filter((question) => !question.implicit)
439
+ if (declared.length > 0 || (exploration.areas ?? []).length > 0) {
440
+ push(tr('- 当前位置:', '- Where things stand:'))
441
+ for (const area of (exploration.areas ?? []).slice(0, 8)) push(tr(` 板块「${clamp(area.name, 30)}」${AREA_WORD[area.state] ?? area.state} · 判断 ${area.judgments} 条,已采纳 ${area.verified} 条${area.openAnomalies > 0 ? ` · 未解释 ${area.openAnomalies} 条` : ''}`, ` Area "${clamp(area.name, 30)}" ${AREA_WORD[area.state] ?? area.state} · ${area.judgments} judgments, ${area.verified} adopted${area.openAnomalies > 0 ? ` · ${area.openAnomalies} unexplained` : ''}`), 1)
442
+ for (const question of declared.slice(0, 8)) {
443
+ const counts = Object.entries({ examining: question.counts?.examining, excluded: question.counts?.excluded, adopted: question.counts?.adopted }).filter(([, value]) => value > 0).map(([key, value]) => tr(`${STATE_WORD[key]} ${value}`, `${STATE_WORD[key]} ${value}`))
444
+ const status = question.status === 'answered' ? tr('已作答', 'answered') : question.status === 'emergent' ? tr('新发现,待人决定是否立为问题', 'newly found, awaiting a decision') : question.status === 'parked' ? tr('暂缓', 'parked') : counts.length > 0 ? tr(`候选假设 ${counts.join(' / ')}`, `candidates ${counts.join(' / ')}`) : tr('还没有候选假设', 'no candidates yet')
445
+ push(` ${question.id === exploration.current ? '▸' : '·'} ${question.id}「${clamp(question.text, 60)}」${status}`, question.id === exploration.current ? 0 : 1)
446
+ }
447
+ }
421
448
  }
422
449
  if (plan === null) {
423
450
  if (goal !== null && String(goal.status) === 'open') push(tr('- 计划:还没有(用 CreatePlan 把检验拆成步骤)', '- Plan: none yet (use CreatePlan to split the tests into steps)'), 1)
@@ -429,15 +456,23 @@ function cardLines(state, derived, options, view) {
429
456
  const tests = tested.length === 0 ? '' : tr(` · 检验 ${tested.map(nameOf).join('、')}(${level})`, ` · tests ${tested.map(nameOf).join(', ')} (${level})`)
430
457
  push(tr(` 第 ${step.ordinal} 步(${step.id})${clamp(step.do, 60)} · ${STEP_WORD[step.status] ?? step.status}${tests}`, ` Step ${step.ordinal} (${step.id}) ${clamp(step.do, 60)} · ${STEP_WORD[step.status] ?? step.status}${tests}`), 2)
431
458
  }
432
- if (plan.steps.length > 12) push(tr(` · 还有 ${plan.steps.length - 12} 步没展开(右栏「世界树」里有全部)`, ` · ${plan.steps.length - 12} more steps not shown (all are in the World Tree on the right)`), 2)
459
+ if (plan.steps.length > 12) push(tr(` · 还有 ${plan.steps.length - 12} 步没展开(「探索」货架里有全部)`, ` · ${plan.steps.length - 12} more steps not shown (all are in the Explore shelf)`), 2)
433
460
  const first = plan.steps.find((step) => step.status === 'open')
434
461
  if (first !== undefined) {
435
462
  push(tr(`- 下一步:交付第 ${first.ordinal} 步(${first.id})——只能交付第一个没做完的步`, `- Next: deliver step ${first.ordinal} (${first.id}); only the first unfinished step can be delivered`))
436
463
  /** 预期可选,但卡上提醒:没写下来的预期,落空了也看不见。 */
437
- if (typeof first.expect === 'string' && first.expect !== '') push(tr(` 预期:${clamp(first.expect, 160)}——结果对不上的地方写进 anomalies,不要解释过去`, ` Expected: ${clamp(first.expect, 160)}; whatever does not match goes in anomalies, do not explain it away`))
438
- else push(tr(' 动手前写下预期(RevisePlan action="expect":预计看到什么、从哪条关系或经验来),落空才看得见', ' Before acting, write the expectation (RevisePlan action="expect": what you expect and from which relation or lesson), so a miss is visible'), 1)
464
+ const next = exploration?.next ?? null
465
+ const predictions = next !== null && next.step === first.id && Array.isArray(next.predictions) ? next.predictions : []
466
+ if (predictions.length > 0) {
467
+ push(tr(' 各候选的预测:', ' Predictions per candidate:'))
468
+ for (const item of predictions.slice(0, 5)) push(tr(` · 若「${item.name}」成立:${clamp(item.expect, 120)}`, ` · If "${item.name}" holds: ${clamp(item.expect, 120)}`))
469
+ if (next.indistinct === true) push(tr(' 注意:各候选的预测相同,这一步区分不了它们;应改用能区分的检验(RevisePlan)', ' Warning: every candidate predicts the same, so this step cannot tell them apart; switch to a test that can (RevisePlan)'))
470
+ else push(tr(' 结果与预测不符的地方写进 anomalies,不要解释过去', ' Whatever contradicts the predictions goes in anomalies; do not explain it away'), 1)
471
+ }
472
+ if (typeof first.expect === 'string' && first.expect !== '') push(tr(` 预测:${clamp(first.expect, 160)}。结果与预测不符之处写入 anomalies,不要强行解释`, ` Expected: ${clamp(first.expect, 160)}; whatever does not match goes in anomalies, do not explain it away`))
473
+ else if (predictions.length === 0) push(tr(' 动手前写下预测(RevisePlan action="expect":按候选分别写 predictions,或写 expect 并注明来自哪条关系或经验),落空才看得见', ' Before acting, write predictions (RevisePlan action="expect": predictions per candidate, or expect with the relation or lesson it comes from), so a miss is visible'), 1)
439
474
  }
440
- else if (goal !== null && String(goal.status) === 'open') push(tr('- 下一步:计划的步都做完了,ClosePlan 收尾,然后 Conclude 结案或开下一阶段', '- Next: every step is done; ClosePlan, then Conclude or start the next stage'))
475
+ else if (goal !== null && String(goal.status) === 'open') push(tr('- 下一步:计划的步都做完了,ClosePlan 收尾,然后 Conclude 结案(answers 按问题写结论、依据、尚未确定的事项、待您决策)或开下一阶段', '- Next: every step is done; ClosePlan, then Conclude (answers per question: conclusion, basis, open points, decisions for the user) or start the next stage'))
441
476
  if (plan.blocked !== undefined && plan.blocked !== null) push(tr(`- 计划停下等人:${plan.blocked.reason}(连续 ${plan.blocked.attempts} 次没过,已经问人怎么办;没人答就等着)`, `- Plan stopped, waiting for a person: ${plan.blocked.reason} (failed ${plan.blocked.attempts}× in a row; a person has been asked; wait if nobody answers)`))
442
477
  }
443
478
  /**
@@ -448,7 +483,7 @@ function cardLines(state, derived, options, view) {
448
483
  const openAnomalies = anomalies.filter((item) => item?.status === 'open')
449
484
  if (openAnomalies.length > 0) {
450
485
  push(tr(`- 未解释(${openAnomalies.length} 条开着;用 Anomaly 解释、排除或交给人,不要解释过去):`, `- Unexplained (${openAnomalies.length} open; explain, rule out or hand to a person with Anomaly; do not explain them away):`))
451
- for (const item of openAnomalies.slice(0, 8)) push(tr(` · ${item.id}${item.by === 'evaluator' ? '(评估者发现)' : ''}:${clamp(item.what, 140)}${item.anchor ? ` · 在 ${clamp(item.anchor, 30)}` : ''}`, ` · ${item.id}${item.by === 'evaluator' ? ' (found by the evaluator)' : ''}: ${clamp(item.what, 140)}${item.anchor ? ` · on ${clamp(item.anchor, 30)}` : ''}`))
486
+ for (const item of openAnomalies.slice(0, 8)) push(tr(` · ${item.id}${item.by === 'evaluator' ? '(评估者发现)' : ''}:${clamp(item.what, 140)}${item.anchor ? ` · 在 ${clamp(item.anchor, 30)}` : ''}${(item.touches ?? []).length > 0 ? ` · 涉及 ${item.touches.slice(0, 4).join('、')}` : ''}`, ` · ${item.id}${item.by === 'evaluator' ? ' (found by the evaluator)' : ''}: ${clamp(item.what, 140)}${item.anchor ? ` · on ${clamp(item.anchor, 30)}` : ''}${(item.touches ?? []).length > 0 ? ` · touches ${item.touches.slice(0, 4).join(', ')}` : ''}`))
452
487
  if (openAnomalies.length > 8) push(tr(` · 还有 ${openAnomalies.length - 8} 条`, ` · ${openAnomalies.length - 8} more`), 1)
453
488
  }
454
489
  const settledAnomalies = anomalies.length - openAnomalies.length
@@ -473,8 +508,8 @@ function cardLines(state, derived, options, view) {
473
508
  const context = `${goal?.claim ?? ''}\n${nextStep?.do ?? ''}`.toLowerCase()
474
509
  const score = (lesson) => (lesson.about ?? []).filter((item) => item !== '' && context.includes(String(item).toLowerCase())).length
475
510
  const ranked = lessonRows.map((lesson, index) => ({ lesson, index, score: score(lesson) })).sort((a, b) => b.score - a.score || a.index - b.index)
476
- const kindWord = { trap: tr('坑', 'trap'), check: tr('先核', 'check'), shortcut: tr('别走的捷径', 'misleading shortcut'), prior: tr('先验', 'prior') }
477
- push(tr(`- 以前留下的经验(${lessonRows.length} 条;定计划、写预期前先看,用上了就在预期里写明来自哪条):`, `- Lessons left earlier (${lessonRows.length}; read before planning or writing an expectation, and name the one you use in the expectation):`), 1)
511
+ const kindWord = { trap: tr('常见误区', 'common pitfall'), check: tr('前置核查', 'check first'), shortcut: tr('不可取的捷径', 'misleading shortcut'), prior: tr('先验知识', 'prior') }
512
+ push(tr(`- 以前留下的经验(${lessonRows.length} 条;制定计划、写预测前先阅读,引用时在预测中注明来自哪条):`, `- Lessons left earlier (${lessonRows.length}; read before planning or writing an expectation, and name the one you use in the expectation):`), 1)
478
513
  for (const { lesson } of ranked.slice(0, 6)) push(` · ${lesson.id} · ${kindWord[lesson.kind] ?? lesson.kind} · ${clamp(lesson.text, 160)}${lesson.boundary ? tr(`(不适用:${clamp(lesson.boundary, 80)})`, ` (does not apply: ${clamp(lesson.boundary, 80)})`) : ''}`, 1)
479
514
  if (lessonRows.length > 6) push(tr(` · 还有 ${lessonRows.length - 6} 条(clear/knowledge/lessons/)`, ` · ${lessonRows.length - 6} more (clear/knowledge/lessons/)`), 2)
480
515
  }
@@ -533,7 +568,7 @@ function cardLines(state, derived, options, view) {
533
568
  const telling = preflight.predicates.filter((predicate) => predicate.shape || predicate.check)
534
569
  const plain = preflight.predicates.filter((predicate) => !(predicate.shape || predicate.check))
535
570
  if (telling.length > 0) {
536
- push(tr('- 用到的关系(预期从这里来):', '- Relations in use (expectations come from these):'), 1)
571
+ push(tr('- 用到的关系(预测的来源):', '- Relations in use (expectations come from these):'), 1)
537
572
  for (const predicate of telling.slice(0, 4)) push(` · ${named(predicate)}${predicate.shape ? tr(`:${SHAPE_WORD[predicate.shape] ?? predicate.shape}`, `: ${SHAPE_WORD[predicate.shape] ?? predicate.shape}`) : ''}${predicate.gloss ? tr(`(${clamp(predicate.gloss, 80)})`, ` (${clamp(predicate.gloss, 80)})`) : ''}${predicate.check ? tr(` · 读数这样核:${clamp(predicate.check, 80)}`, ` · check readings by: ${clamp(predicate.check, 80)}`) : ''}`, 1)
538
573
  }
539
574
  if (plain.length > 0) push(tr(`- 用到的关系:${plain.slice(0, 6).map(named).join('、')}${more(preflight.predicatesTruncated)}`, `- Relations in use: ${plain.slice(0, 6).map(named).join(', ')}${more(preflight.predicatesTruncated)}`), 2)
@@ -541,17 +576,11 @@ function cardLines(state, derived, options, view) {
541
576
  push(tr(`- 和这些判断有关的已知${more(preflight.factsTruncated)}(引用前看边界;要复检就在判断上写 retests):`, `- Known facts related to these judgments${more(preflight.factsTruncated)} (check the boundary before citing; to re-test, put retests on a judgment):`), 1)
542
577
  for (const fact of preflight.facts.slice(0, 3)) push(factLine(fact), 1)
543
578
  }
544
- } else
545
- push(
546
- tr(
547
- '- 已有的词里没有命中这些判断的:要写「主体 · 关系 · 对象」就先在 clear/ontology/ 下写概念与关系文件(字段见 SCHEMA.json);查不到不等于不存在',
548
- '- No existing term matches these judgments: to write "subject · relation · object", first write concept and relation files under clear/ontology/ (fields in SCHEMA.json); not found does not mean it does not exist',
549
- ),
550
- 1,
551
- )
579
+ }
552
580
  if (gaps.length === 0) push(tr('- 结构完整:判断都写成了断言、都检验过、主体都在实体图上', '- Structure complete: every judgment has assertions, has been tested, and its subjects are on the entity graph'))
553
581
  /** 缺口只给模型(人看不到):说清欠什么、下一步做什么,不写 code。 */
554
- for (const gap of gaps) push(tr(`- 还欠的:${gap.detail} → ${gap.nextAction}`, `- Still owed: ${gap.detail} → ${gap.nextAction}`))
582
+ /** 只有散文的判断不上卡(它是可选的加法,重复提醒从没改变过下一步);面板照旧列出。 */
583
+ for (const gap of gaps.filter((item) => item.code !== 'prose_only_claims')) push(tr(`- 还欠的:${gap.detail} → ${gap.nextAction}`, `- Still owed: ${gap.detail} → ${gap.nextAction}`))
555
584
  }
556
585
  for (const conflict of conflicts.slice(0, 3)) {
557
586
  push(
package/lib/scope.js ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * scope —— 知识的**适用范围**:它在什么条件下、什么取值范围内成立。
3
+ *
4
+ * 适用范围与推翻条件是两回事。推翻条件说「什么结果会推翻它」;适用范围说「它在哪里成立」
5
+ * (产线、月份、批次、工况,以及变量的取值范围)。0.5.1 把两者写在同一格里,于是九月的数据
6
+ * 撤回了一条在八月范围内成立的事实:系统分不清「换了范围」与「被推翻」。
7
+ *
8
+ * 形状(都可选):
9
+ * { conditions: { 维度: 值 }, ranges: { 量: [下限, 上限] }, note: 一句补充 }
10
+ *
11
+ * 这里只有纯函数:规整、合并、写成一行字、比较两份范围。内核与测试共用。
12
+ */
13
+
14
+ const WIDTH = { key: 60, value: 80, note: 200 }
15
+ const MAX_ENTRIES = 12
16
+
17
+ /** 规整一份范围;什么都没有就返回 null(「范围未声明」)。 */
18
+ export function normalizeScope(raw) {
19
+ if (raw === null || raw === undefined || typeof raw !== 'object' || Array.isArray(raw)) return null
20
+ const conditions = {}
21
+ for (const [key, value] of Object.entries(raw.conditions ?? {}).slice(0, MAX_ENTRIES)) {
22
+ const name = String(key ?? '').trim().slice(0, WIDTH.key)
23
+ const text = String(value ?? '').trim().slice(0, WIDTH.value)
24
+ if (name !== '' && text !== '') conditions[name] = text
25
+ }
26
+ const ranges = {}
27
+ const units = {}
28
+ for (const [key, value] of Object.entries(raw.ranges ?? {}).slice(0, MAX_ENTRIES)) {
29
+ const name = String(key ?? '').trim().slice(0, WIDTH.key)
30
+ if (name === '' || !Array.isArray(value) || value.length !== 2) continue
31
+ const [low, high] = value
32
+ if (typeof low !== 'number' || typeof high !== 'number') continue
33
+ if (!Number.isFinite(low) || !Number.isFinite(high)) continue
34
+ ranges[name] = low <= high ? [low, high] : [high, low]
35
+ if (typeof raw.units?.[key] === 'string' && raw.units[key].trim()) units[name] = raw.units[key].trim()
36
+ }
37
+ const note = typeof raw.note === 'string' ? raw.note.trim().slice(0, WIDTH.note) : ''
38
+ if (Object.keys(conditions).length === 0 && Object.keys(ranges).length === 0 && note === '') return null
39
+ return { conditions, ranges, ...(Object.keys(units).length ? { units } : {}), ...(note === '' ? {} : { note }) }
40
+ }
41
+
42
+ /** 合并:`primary` 的条目覆盖 `fallback` 的同名条目(判断自己写的优先于目标的默认条件)。 */
43
+ export function mergeScope(primary, fallback) {
44
+ const first = normalizeScope(primary)
45
+ const second = normalizeScope(fallback)
46
+ if (first === null) return second
47
+ if (second === null) return first
48
+ return normalizeScope({
49
+ conditions: { ...second.conditions, ...first.conditions },
50
+ ranges: { ...second.ranges, ...first.ranges },
51
+ units: { ...second.units, ...first.units },
52
+ note: first.note ?? second.note,
53
+ })
54
+ }
55
+
56
+ /** 写成一行给人和模型读;没有范围返回 null。 */
57
+ export function scopeText(raw, language = 'zh') {
58
+ const scope = normalizeScope(raw)
59
+ if (scope === null) return null
60
+ const en = language === 'en'
61
+ const parts = []
62
+ const conditions = Object.entries(scope.conditions).map(([key, value]) => `${key}=${value}`)
63
+ if (conditions.length > 0) parts.push(en ? `conditions ${conditions.join(', ')}` : `条件 ${conditions.join('、')}`)
64
+ const ranges = Object.entries(scope.ranges).map(([key, [low, high]]) => `${key} ${low}–${high}${scope.units?.[key] ? ` ${scope.units[key]}` : ""}`)
65
+ if (ranges.length > 0) parts.push(en ? `ranges ${ranges.join(', ')}` : `取值 ${ranges.join('、')}`)
66
+ if (scope.note !== undefined) parts.push(scope.note)
67
+ return parts.join(en ? '; ' : ';')
68
+ }
69
+
70
+ const same = (left, right) => String(left).trim().toLowerCase() === String(right).trim().toLowerCase()
71
+
72
+ /**
73
+ * 一条知识(`item`)放到当前情形(`current`)里还适用吗。
74
+ *
75
+ * 只做确定性的比对,不判断语义:
76
+ * · item 有某个条件维度,current 写了不同的值 → out_of_scope(超出范围);
77
+ * · item 有某个量的取值范围,current 的取值落在外面 → out_of_range(超出取值范围);
78
+ * · item 有某个维度或量,current 没写 → undeclared(条件未声明,不当作适用);
79
+ * · item 本身没有范围 → unscoped(范围未声明);
80
+ * · 其余 → applies(适用)。
81
+ * 同时出现几种时取最强的一种(超出范围 > 超出取值范围 > 条件未声明)。
82
+ */
83
+ export function compareScope(item, current) {
84
+ const scope = normalizeScope(item)
85
+ if (scope === null) return { verdict: 'unscoped', reasons: [] }
86
+ const here = normalizeScope(current) ?? { conditions: {}, ranges: {} }
87
+ const outside = []
88
+ const beyond = []
89
+ const missing = scope.note ? ["文字边界 / text boundary"] : []
90
+ for (const [key, value] of Object.entries(scope.conditions)) {
91
+ if (!(key in here.conditions)) missing.push(key)
92
+ else if (!same(here.conditions[key], value)) outside.push({ key, expected: value, actual: here.conditions[key] })
93
+ }
94
+ for (const [key, [low, high]] of Object.entries(scope.ranges)) {
95
+ if (!(key in here.ranges) || !scope.units?.[key] || !here.units?.[key] || scope.units[key] !== here.units[key]) missing.push(key)
96
+ else {
97
+ const [from, to] = here.ranges[key]
98
+ if (to < low || from > high) beyond.push({ key, expected: [low, high], actual: [from, to] })
99
+ else if (from < low || to > high) missing.push(key)
100
+ }
101
+ }
102
+ if (outside.length > 0) return { verdict: 'out_of_scope', reasons: outside }
103
+ if (beyond.length > 0) return { verdict: 'out_of_range', reasons: beyond }
104
+ if (missing.length > 0) return { verdict: 'undeclared', reasons: missing.map((key) => ({ key })) }
105
+ return { verdict: 'applies', reasons: [] }
106
+ }
107
+
108
+ /** 比较结果写成一句话。 */
109
+ export function scopeVerdictText(result, language = 'zh') {
110
+ const en = language === 'en'
111
+ const reasons = Array.isArray(result?.reasons) ? result.reasons : []
112
+ switch (result?.verdict) {
113
+ case 'out_of_scope':
114
+ return en
115
+ ? `out of scope (${reasons.map((item) => `${item.key}: holds for ${item.expected}, here ${item.actual}`).join('; ')})`
116
+ : `超出范围(${reasons.map((item) => `${item.key}:原范围为 ${item.expected},本次为 ${item.actual}`).join(';')})`
117
+ case 'out_of_range':
118
+ return en
119
+ ? `out of range (${reasons.map((item) => `${item.key}: holds for ${item.expected.join('–')}, here ${item.actual.join('–')}`).join('; ')})`
120
+ : `超出取值范围(${reasons.map((item) => `${item.key}:原范围为 ${item.expected.join('–')},本次为 ${item.actual.join('–')}`).join(';')})`
121
+ case 'undeclared':
122
+ return en ? `conditions not declared here (${reasons.map((item) => item.key).join(', ')})` : `条件未声明(本次未写明 ${reasons.map((item) => item.key).join('、')})`
123
+ case 'unscoped':
124
+ return en ? 'scope not declared' : '范围未声明'
125
+ default:
126
+ return en ? 'applies' : '适用'
127
+ }
128
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clearai-dsh",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "ClearAI: an ontology-first DSH agent preset — evidence-checked research that grows into a domain ontology.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -21,7 +21,7 @@
21
21
  name: '@deepseek-ai/dsh-persona'
22
22
  config:
23
23
  prefix: '你是 ClearAI 的主人格,运行在 DeepSeek Harness 上。怎么工作见下面三段:身份、循环、对人说话。'
24
- suffix: 你的工作目录是 {{cwd}}。工作区就是用户的文件夹;`clear/` 是系统的目录,其余目录都是用户的。
24
+ suffix: 你的工作目录是 {{cwd}}。工作区就是用户的文件夹;`clear/` 下除本体(`clear/ontology/`)外是系统的目录,其余目录都是用户的。
25
25
 
26
26
  - id: agent-instructions
27
27
  name: '@deepseek-ai/dsh-agent-instructions'
@@ -169,10 +169,6 @@
169
169
  l4RequiresHumanRelease: true
170
170
  # L4 只认外部来源:做的人自己写过的路径不算观测
171
171
  l4RejectSelfWritten: true
172
- # 假设数量下限:首次立目标至少登记 2 条候选假设(0 条一样拦)。候选对比是检验的前提——
173
- # 只有一个猜想时,「验证」容易退化成找证据支持自己。修订目标不受此限。
174
- # 内核缺省是 0(=机制中立);**这里写 2 是产品立场**,所以它是硬门,不是文案。
175
- minHypotheses: 2
176
172
  # 实体门(结案唯一的结构关口):将要升格的判断里,断言主体还不是实体图上的节点 ⇒ 结案被拒
177
173
  # (在派评估者**之前**拦)。只有散文、没有断言的判断不拦,那只是卡上的一条缺口。
178
174
  # 为什么要有它:「本体写得漂亮、实体图是空的」是这套系统最容易交付出来的假完成
@@ -185,6 +181,8 @@
185
181
  # 为什么要有它:判据是"怎样算完成",它一变前面所有工作的验收含义跟着变——
186
182
  # 允许在同一次 Frame 里顺手改掉,等于允许把"做不到"重新定义成"做到了"。
187
183
  requireCriteriaVerdict: true
184
+ # 停止检查:achieved 结案要按问题写结论;仍在考察中的候选与开着的未解释项须写进「尚未确定的事项」。
185
+ requireAnswers: true
188
186
  # deny_rules 十条里可移植的九条(路径越狱那条不搬:宿主沙箱已经拥有它,ClearAI 自己也说「不重复」)
189
187
  bashDenyRules: true
190
188
  # 独立评估者:spawn = fresh context(fork 会继承历史,做的人与判的人就分不开了)
@@ -38,7 +38,7 @@
38
38
  name: '@deepseek-ai/dsh-persona'
39
39
  config:
40
40
  prefix: '你是 ClearAI 的主人格,运行在 DeepSeek Harness 上。怎么工作见下面三段:身份、循环、对人说话。'
41
- suffix: 你的工作目录是 {{cwd}}。工作区就是用户的文件夹;`clear/` 是系统的目录,其余目录都是用户的。
41
+ suffix: 你的工作目录是 {{cwd}}。工作区就是用户的文件夹;`clear/` 下除本体(`clear/ontology/`)外是系统的目录,其余目录都是用户的。
42
42
 
43
43
  - id: agent-instructions
44
44
  name: '@deepseek-ai/dsh-agent-instructions'
@@ -186,10 +186,6 @@
186
186
  l4RequiresHumanRelease: true
187
187
  # L4 只认外部来源:做的人自己写过的路径不算观测
188
188
  l4RejectSelfWritten: true
189
- # 假设数量下限:首次立目标至少登记 2 条候选假设(0 条一样拦)。候选对比是检验的前提——
190
- # 只有一个猜想时,「验证」容易退化成找证据支持自己。修订目标不受此限。
191
- # 内核缺省是 0(=机制中立);**这里写 2 是产品立场**,所以它是硬门,不是文案。
192
- minHypotheses: 2
193
189
  # 实体门(结案唯一的结构关口):将要升格的判断里,断言主体还不是实体图上的节点 ⇒ 结案被拒
194
190
  # (在派评估者**之前**拦)。只有散文、没有断言的判断不拦,那只是卡上的一条缺口。
195
191
  # 为什么要有它:「本体写得漂亮、实体图是空的」是这套系统最容易交付出来的假完成
@@ -202,6 +198,8 @@
202
198
  # 为什么要有它:判据是"怎样算完成",它一变前面所有工作的验收含义跟着变——
203
199
  # 允许在同一次 Frame 里顺手改掉,等于允许把"做不到"重新定义成"做到了"。
204
200
  requireCriteriaVerdict: true
201
+ # 停止检查:achieved 结案要按问题写结论;仍在考察中的候选与开着的未解释项须写进「尚未确定的事项」。
202
+ requireAnswers: true
205
203
  # deny_rules 十条里可移植的九条(路径越狱那条不搬:宿主沙箱已经拥有它,ClearAI 自己也说「不重复」)
206
204
  bashDenyRules: true
207
205
  # 独立评估者:spawn = fresh context(fork 会继承历史,做的人与判的人就分不开了)
@@ -0,0 +1,59 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import { isAbsolute, relative, resolve } from 'node:path'
4
+
5
+ // Both logical identifiers are opaque. No characters from either reach a path.
6
+ export const auditPathComponent = (id) => createHash('sha256').update(String(id)).digest('hex')
7
+
8
+ export function canonical(value) {
9
+ if (Array.isArray(value)) return value.map(canonical)
10
+ if (value !== null && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().filter((key) => value[key] !== undefined).map((key) => [key, canonical(value[key])]))
11
+ return value
12
+ }
13
+ export const contentDigest = (value) => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(canonical(value))).digest('hex')
14
+
15
+ // Missing/unreadable inputs are material too. Only workspace-relative references
16
+ // are inspected; hashing must not create a new privilege or disclose file bytes.
17
+ export function fileDigest(cwd, path) {
18
+ if (!cwd || typeof path !== 'string' || isAbsolute(path)) return 'unavailable'
19
+ const file = resolve(cwd, path)
20
+ const rel = relative(cwd, file)
21
+ if (rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) return 'outside-workspace'
22
+ try { return contentDigest(readFileSync(file)) } catch { return 'missing-or-unreadable' }
23
+ }
24
+
25
+ export function methodSnapshot(cwd, spec, registration) {
26
+ const scripts = new Set(spec?.scripts ?? [])
27
+ // Declared scripts are preferred; ordinary command file operands also count.
28
+ for (const word of String(spec?.command ?? '').match(/[^\s"'`;|&<>]+/g) ?? []) {
29
+ if (/\.(?:[cm]?js|py|sh|r|R)$/.test(word)) scripts.add(word)
30
+ }
31
+ return contentDigest({ registration: fileDigest(cwd, registration), command: spec?.command, scripts: [...scripts].sort().map((path) => [path, fileDigest(cwd, path)]) })
32
+ }
33
+
34
+ export function auditMaterialDigest({ kind, step, plan, state, gate, cwd }) {
35
+ const currentPlan = (state.plans ?? []).find((row) => row.id === plan?.id) ?? plan
36
+ const modelIds = new Set((state.hypotheses ?? []).map((row) => row.use).filter(Boolean))
37
+ const refs = new Set((state.hypotheses ?? []).flatMap((row) => (row.uses ?? []).map((use) => typeof use === 'string' ? use : use.id)))
38
+ for (const answer of gate.answers ?? []) for (const id of answer.uses ?? []) refs.add(id)
39
+ const files = state.workspace?.files ?? {}
40
+ const knowledge = Object.entries(files).filter(([, file]) => refs.has(file?.data?.id)).map(([path, file]) => {
41
+ if (file?.data?.use) modelIds.add(file.data.use)
42
+ return [path, fileDigest(cwd, path)]
43
+ })
44
+ const paths = new Set((currentPlan?.steps ?? []).flatMap((row) => row.artifacts ?? []))
45
+ for (const row of gate.confirmed ?? []) if (!/^(?:evidence|hypothesis):/.test(row.ref)) paths.add(row.ref)
46
+ for (const row of state.materials ?? []) for (const path of [row.path, row.ref, ...(row.refs ?? [])]) if (typeof path === 'string' && !path.includes(':')) paths.add(path)
47
+ const methods = [...modelIds].sort().map((id) => {
48
+ const path = `clear/models/${id}.json`
49
+ let spec = null
50
+ try { spec = JSON.parse(readFileSync(resolve(cwd, path), 'utf8')) } catch {}
51
+ return [id, methodSnapshot(cwd, spec, path), (spec?.inputs ?? []).map((input) => [input, fileDigest(cwd, input)]), spec?.output ? fileDigest(cwd, spec.output) : null]
52
+ })
53
+ const semantic = (entry) => Object.fromEntries(['id', 'gloss', 'parent', 'kind', 'unit', 'domain', 'range', 'functional', 'shape', 'check', 'type', 'relations', 'status', 'replaced_by'].filter((key) => entry[key] !== undefined).map((key) => [key, entry[key]]))
54
+ const lexicon = state.lexicon ?? {}
55
+ const definitions = ['terms', 'predicates', 'entities'].flatMap((key) => (lexicon[key] ?? []).map(semantic))
56
+ const anomalies = [...(state.anomalies ?? []), ...(gate.anomalies ?? [])].filter((row) => row.by !== 'evaluator' || row.status !== 'open').map((row) => ({ id: row.id, what: row.what, status: row.status, reason: row.reason, explainedBy: row.explainedBy }))
57
+ const materials = [...new Set((state.materials ?? []).map(({ id, at, ...row }) => JSON.stringify(canonical(row))))].sort().map((row) => JSON.parse(row))
58
+ return `v5:${contentDigest({ kind, step: step.id, criteria: step.done_criteria, goal: state.goal, steps: currentPlan?.steps, answers: gate.answers, lessons: gate.lessons, extra: gate.extra, hypotheses: (state.hypotheses ?? []).map(({ supportedLevel, refutations, inconclusive, ...row }) => row), facts: state.facts, evidence: (state.evidence ?? []).filter((row) => row.anchor !== 'auditor'), materials, anomalies, definitions, knowledge, methods, artifacts: [...paths].sort().map((path) => [path, fileDigest(cwd, path)]) })}`
59
+ }
@@ -0,0 +1,25 @@
1
+ /** DSH rc.2 enforces a JSON-schema subset. Bounds remain annotations and runtime limits. */
2
+ export function nativeAuditSchema(value) {
3
+ if (Array.isArray(value)) return value.map(nativeAuditSchema)
4
+ if (!value || typeof value !== 'object') return value
5
+ const result = Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'maxLength').map(([key, child]) => [key, nativeAuditSchema(child)]))
6
+ if (value.maxLength !== undefined) result.description = `${value.description ?? ''} (maximum ${value.maxLength} characters; excess is truncated by the consumer)`
7
+ return result
8
+ }
9
+
10
+ /** Only a successful authoritative structured_output result survives child recovery. */
11
+ export function recoveredStructuredOutput(events) {
12
+ const calls = new Map()
13
+ let value
14
+ for (const event of events) {
15
+ if (event.type === 'tool/call' && event.data?.name === 'structured_output') {
16
+ try { calls.set(event.data.callId, typeof event.data.arguments === 'string' ? JSON.parse(event.data.arguments) : event.data.arguments) } catch {}
17
+ }
18
+ if (event.type === 'tool/result') {
19
+ const message = event.data?.message
20
+ const id = message?.toolCallId ?? message?.source?.callId
21
+ if (calls.has(id) && message?.isError !== true && !event.data.error) value = calls.get(id)
22
+ }
23
+ }
24
+ return value
25
+ }