clearai-dsh 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -338,7 +339,7 @@ export function readingOf(hypothesis) {
338
339
  /** 步骤状态的人话。 */
339
340
  const STEP_WORD = bilingual({ open: ['待做', 'to do'], advanced: ['已交付', 'delivered'], void: ['已作废', 'voided'] })
340
341
 
341
- /** 一条事实在卡上的一行:原话、边界、等级;来自别的会话的标出来。 */
342
+ /** 一条事实在卡上的一行:原话、适用范围、等级;来自别的会话的标出来。 */
342
343
  /** 有开着的未解释项点名这条事实:它回到「待核验」,直到那些未解释项有了去处。 */
343
344
  function questionedNote(fact, language) {
344
345
  const ids = Array.isArray(fact?.questioned) ? fact.questioned : []
@@ -347,10 +348,10 @@ function questionedNote(fact, language) {
347
348
  }
348
349
 
349
350
  function factLine(fact) {
350
- const scope = oneLine(fact?.scope ?? '')
351
+ const scope = oneLine(tr(scopeText(fact?.scope_spec, 'zh'), scopeText(fact?.scope_spec, 'en')) || fact?.scope || '')
351
352
  return tr(
352
- ` · 「${clamp(fact?.text, 100)}」${scope === '' ? '' : ` — 边界:${clamp(scope, 80)}`}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · 以前的会话' : ''}${questionedNote(fact, 'zh')}`,
353
- ` · "${clamp(fact?.text, 100)}"${scope === '' ? '' : ` — boundary: ${clamp(scope, 80)}`}${fact?.level ? ` · ${fact.level}` : ''}${fact?.foreign === true ? ' · earlier session' : ''}${questionedNote(fact, 'en')}`,
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')}`,
354
355
  )
355
356
  }
356
357
 
@@ -444,12 +445,6 @@ function cardLines(state, derived, options, view) {
444
445
  push(` ${question.id === exploration.current ? '▸' : '·'} ${question.id}「${clamp(question.text, 60)}」${status}`, question.id === exploration.current ? 0 : 1)
445
446
  }
446
447
  }
447
- /** 本体里带形状、还没有候选由它提出的影响关系:只列出,不强制(不为竞争而竞争)。 */
448
- const untapped = Array.isArray(exploration.untapped) ? exploration.untapped : []
449
- if (untapped.length > 0) {
450
- const SHAPE = { increasing: tr('单调升', 'increasing'), decreasing: tr('单调降', 'decreasing'), peak: tr('有峰', 'has a peak'), threshold: tr('有阈值', 'has a threshold'), coupled: tr('耦合', 'coupled') }
451
- push(tr(`- 本体中尚无候选假设引用的影响关系:${untapped.slice(0, 5).map((item) => `${item.label}(${SHAPE[item.shape] ?? item.shape})`).join('、')}——若它们可能改变结论,可据此提出候选(\`from\` 写关系 id)`, `- Affects relations in the ontology no candidate cites yet: ${untapped.slice(0, 5).map((item) => `${item.label} (${SHAPE[item.shape] ?? item.shape})`).join(', ')}; if they could change the conclusion, propose candidates from them (\`from\` = the relation id)`), 1)
452
- }
453
448
  }
454
449
  if (plan === null) {
455
450
  if (goal !== null && String(goal.status) === 'open') push(tr('- 计划:还没有(用 CreatePlan 把检验拆成步骤)', '- Plan: none yet (use CreatePlan to split the tests into steps)'), 1)
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.1",
3
+ "version": "0.5.3",
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,
@@ -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,11 +181,10 @@
185
181
  # 为什么要有它:判据是"怎样算完成",它一变前面所有工作的验收含义跟着变——
186
182
  # 允许在同一次 Frame 里顺手改掉,等于允许把"做不到"重新定义成"做到了"。
187
183
  requireCriteriaVerdict: true
188
- # 测量门槛:首次立题要在 Frame.ontology 里写出答案涉及的度量,以及每个度量由什么测量、读数如何核对。
189
- # 为什么:真跑里唯一一条错误事实,来自把控制器回读值当成釜温。
190
- requireMeasures: true
191
184
  # 停止检查:achieved 结案要按问题写结论;仍在考察中的候选与开着的未解释项须写进「尚未确定的事项」。
192
185
  requireAnswers: true
186
+ ontologyFeedback: true
187
+ nativeTodoProgress: true
193
188
  # deny_rules 十条里可移植的九条(路径越狱那条不搬:宿主沙箱已经拥有它,ClearAI 自己也说「不重复」)
194
189
  bashDenyRules: true
195
190
  # 独立评估者:spawn = fresh context(fork 会继承历史,做的人与判的人就分不开了)
@@ -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,11 +198,10 @@
202
198
  # 为什么要有它:判据是"怎样算完成",它一变前面所有工作的验收含义跟着变——
203
199
  # 允许在同一次 Frame 里顺手改掉,等于允许把"做不到"重新定义成"做到了"。
204
200
  requireCriteriaVerdict: true
205
- # 测量门槛:首次立题要在 Frame.ontology 里写出答案涉及的度量,以及每个度量由什么测量、读数如何核对。
206
- # 为什么:真跑里唯一一条错误事实,来自把控制器回读值当成釜温。
207
- requireMeasures: true
208
201
  # 停止检查:achieved 结案要按问题写结论;仍在考察中的候选与开着的未解释项须写进「尚未确定的事项」。
209
202
  requireAnswers: true
203
+ ontologyFeedback: true
204
+ nativeTodoProgress: true
210
205
  # deny_rules 十条里可移植的九条(路径越狱那条不搬:宿主沙箱已经拥有它,ClearAI 自己也说「不重复」)
211
206
  bashDenyRules: true
212
207
  # 独立评估者: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
+ }