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.
@@ -22,11 +22,16 @@
22
22
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
23
23
  import { tmpdir } from 'node:os'
24
24
 
25
- import { createHash } from 'node:crypto'
25
+ import { createHash, randomUUID } from 'node:crypto'
26
26
  import { AsyncLocalStorage } from 'node:async_hooks'
27
27
  import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
28
28
  import { SECTION_TABLE } from './prompts.js'
29
29
  import { VERIFICATION_LOOP, describeOntology, validateOntology } from './ontology.js'
30
+ import { compareScope, mergeScope, normalizeScope, scopeText, scopeVerdictText } from './scope.js'
31
+ import { citeVerdict, mergeAbout, negativeItems, relatedKnowledge, resolveAbout } from './knowledge-items.js'
32
+ import { auditMaterialDigest, auditPathComponent, contentDigest, fileDigest, methodSnapshot } from './audit-material.js'
33
+ import { nativeAuditSchema, recoveredStructuredOutput } from './audit-schema.js'
34
+ import { MODEL_ID, appendRun, checkModelSpec, compareOutputs, deviationText, needsRerun, numericOutputs } from './models.js'
30
35
 
31
36
  export const name = 'clearai-kernel'
32
37
  /** 宿主注册表 + `clearai` 读面(宿主包提供;缺了会在工具里明确报错,而不是静默不工作)。 */
@@ -121,7 +126,7 @@ const MESSAGE_SOURCE_KIND = 'plugin:clearai'
121
126
  const SELF_REFERENCE = [
122
127
  [/ClosePlan\s*(?:成功|succeed|success)/i, ['判据不得引用「ClosePlan 成功」——那是系统的动作,不是可核对的产物', 'Criteria cannot cite "ClosePlan succeeds": that is a system action, not a checkable output']],
123
128
  [/(?:计划状态|plan status)\s*(?:为|是|=|is)?\s*done/i, ['判据不得引用「计划状态 done」——状态由系统派生,不能作为判据', 'Criteria cannot cite "plan status done": status is derived by the system and cannot be a criterion']],
124
- [/(?:目标|goal)\s*(?:已|状态|is|status)?\s*achieved/i, ['判据不得引用「目标 achieved」——那是评估者的裁决,不是本步的产物', 'Criteria cannot cite "goal achieved": that is the evaluator\'s verdict, not this step\'s output']],
129
+ [/(?:目标|goal)\s*(?:(?:已|状态|结案|完成|为|是|置为|标为|is|status|set\s+to|marked\s+as)\s*)*achieved/i, ['判据不得引用「目标 achieved」——那是评估者的裁决,不是本步的产物', 'Criteria cannot cite "goal achieved": that is the evaluator\'s verdict, not this step\'s output']],
125
130
  [/(?:本步.{0,8}(?:标记|标为|置为)|mark(?:ed)?\s+(?:this\s+)?step(?:\s+as)?)\s*done/i, ['判据不得引用「本步标记 done」——没有手动标记这回事', 'Criteria cannot cite "mark this step done": there is no manual marking']],
126
131
  [/记录在对话(?:中|里)|recorded in the (?:conversation|chat)/i, ['判据不得是「记录在对话中」——对话不是可复核的产物', 'Criteria cannot be "recorded in the conversation": the conversation is not a checkable output']],
127
132
  [/见上文|see above/i, ['判据不得是「见上文」——评估者读不到你的上下文', 'Criteria cannot be "see above": the evaluator cannot read your context']],
@@ -212,13 +217,17 @@ export const CONFIG_KEYS = [
212
217
  'minHypotheses',
213
218
  'requireCriteriaVerdict',
214
219
  'requireLandedEntities',
220
+ 'requireAnswers',
215
221
  'bashDenyRules',
216
222
  'auditProvider',
217
223
  'auditTimeoutMs',
224
+ 'auditHardTimeoutMs',
218
225
  'auditToolFilter',
219
226
  'auditRerun',
220
227
  'runtimeCard',
221
228
  'contributions',
229
+ 'applicabilityFeedback',
230
+ 'negativeWriteback',
222
231
  ]
223
232
 
224
233
  /**
@@ -319,6 +328,9 @@ export function apply(ctx, config = {}) {
319
328
  throw new Error('invalid_config:clearai-kernel:blockedThreshold')
320
329
  }
321
330
  const CFG = {
331
+ // Native experimental variants; published ClearAI keeps both enabled.
332
+ applicabilityFeedback: config.applicabilityFeedback !== false,
333
+ negativeWriteback: config.negativeWriteback !== false,
322
334
  /**
323
335
  * 连拦阈值:同一件事连续冲闸这么多次没过,计划置 blocked、停下等人。
324
336
  * **它不是预算**:它管的是证据质量,
@@ -338,9 +350,22 @@ export function apply(ctx, config = {}) {
338
350
  * 出口两条:给主体写实体文件(`clear/ontology/entities/<id>.json`),或把断言从判断上拿掉 / 如实 abandoned。
339
351
  */
340
352
  requireLandedEntities: config.requireLandedEntities === true,
353
+ /**
354
+ * **测量门**(立题;机制缺省关,preset 里开):首次立题时,本体里至少有一个度量,而且每个度量都有一条
355
+ * 「测量」关系写明由什么测量、读数如何核对(`check`)。真跑里唯一一条错误事实,正是把设定值回读
356
+ * 当成了釜温;卡上提醒了几十次「先写本体」也没有用。
357
+ */
358
+ /**
359
+ * **结论门**(结案;机制缺省关,preset 里开):`achieved` 要按问题给出结论四部分,而且每个还在考察、
360
+ * 从没得到支持的候选与每条开着的未解释项,都写进「尚未确定的事项」并说明它若成立答案会怎样变。
361
+ * 只查写没写,不判写得对不对(对不对由结案评估者核)。
362
+ */
363
+ requireAnswers: config.requireAnswers === true,
341
364
  bashDenyRules: config.bashDenyRules !== false,
342
365
  auditProvider: config.auditProvider ?? 'spawn',
343
366
  auditTimeoutMs: config.auditTimeoutMs ?? 240000,
367
+ /** 一次评估从派出起最多等多久:超过就如实结成「未知」并放开,不让一次评估拖住整个目标。 */
368
+ auditHardTimeoutMs: config.auditHardTimeoutMs ?? 240000,
344
369
  // 三张脸的**候选**工具名。真正的 face 还要过一道「这个部署里到底有没有这件工具」的过滤
345
370
  // (见 resolveToolFace):`read_image` 只在挂了 `attachments` 的部署里存在,名单里写了它、
346
371
  // 部署里没有,`tools.restrict` 会**直接抛**(未知工具名)→ 评估整条路 fail-closed。
@@ -377,17 +402,43 @@ export function apply(ctx, config = {}) {
377
402
  */
378
403
  const pendingFacts = new Map()
379
404
  const pendingFactIds = new Set()
405
+ const failedFactAppends = new Map()
406
+ function appendFact(sessionId, mutation) {
407
+ const session = ctx.get('sessions')?.get?.(sessionId)
408
+ if (typeof session?.append !== 'function') throw new Error('native session append unavailable')
409
+ const events = session.snapshotEvents?.() ?? session.ownEvents?.() ?? []
410
+ const turn = events.findLast?.((event) => event.type === 'turn/start')?.data?.turn ?? 0
411
+ const handlerId = `clearai-fact-${randomUUID()}`
412
+ // This plugin's internal fact hook is log-only. A user/message here
413
+ // would split an assistant tool-call from its result at the provider.
414
+ session.append('hook/invoked', { turn, point: 'ClearAIFact', dialect: 'clearai', handlerId })
415
+ session.append('hook/result', { turn, point: 'ClearAIFact', handlerId, decision: 'pass', durationMs: 0, notice: pluginNotice({ turn, step: 0 }, '', [mutation]) })
416
+ }
380
417
  /** 把一条事实推进独立落账通道(返回它自己,方便调用方同时塞进工具结果的 mutations)。 */
381
418
  function landFact(sessionId, mutation) {
382
419
  if (mutation === null || typeof mutation !== 'object') return mutation
383
- const key = `${sessionId}:${String(mutation.t)}:${String(mutation.id ?? mutation.step ?? '')}`
420
+ const key = `${sessionId}:${String(mutation.t)}:${String(mutation.id ?? mutation.step ?? '')}:${String(mutation.status ?? '')}`
384
421
  if (pendingFactIds.has(key)) return mutation
385
422
  pendingFactIds.add(key)
386
423
  const list = pendingFacts.get(sessionId) ?? []
387
424
  list.push(mutation)
388
425
  pendingFacts.set(sessionId, list)
426
+ try {
427
+ appendFact(sessionId, mutation)
428
+ } catch (error) {
429
+ const failures = failedFactAppends.get(sessionId) ?? []
430
+ failures.push(mutation); failedFactAppends.set(sessionId, failures)
431
+ ctx.logger?.warn?.(`clearai: fact append failed: ${String(error?.message ?? error)}`)
432
+ }
389
433
  return mutation
390
434
  }
435
+ async function flushFacts(sessionId) {
436
+ const sessions = ctx.get('sessions')
437
+ const failures = failedFactAppends.get(sessionId) ?? []
438
+ for (const mutation of failures) appendFact(sessionId, mutation)
439
+ if (typeof sessions?.flush === 'function' && await sessions.flush(sessions.get(sessionId)) === false) throw new Error('session durability listener unavailable')
440
+ failedFactAppends.delete(sessionId)
441
+ }
391
442
  /** 取出并清空这一拍的兜底事实(只有 pre-step 调;重复取到空数组是正常的)。 */
392
443
  function drainPendingFacts(sessionId) {
393
444
  const list = pendingFacts.get(sessionId) ?? []
@@ -405,7 +456,9 @@ export function apply(ctx, config = {}) {
405
456
  const what = String(item?.what ?? '').trim()
406
457
  if (what === '') continue
407
458
  const anchor = String(item?.anchor ?? '').trim()
408
- opened.push(landFact(sessionId, { t: 'anomaly/opened', id: `u-${Math.random().toString(36).slice(2, 8)}`, what: what.slice(0, 400), ...(anchor === '' ? {} : { anchor: anchor.slice(0, 80) }), step, by }))
459
+ /** 涉及哪些量、候选假设或已升格的事实(id):点名事实的,那条事实回到「待核验」;结案时据此清点。 */
460
+ const touches = (Array.isArray(item?.touches) ? item.touches : []).map((ref) => String(ref ?? '').trim().slice(0, 80)).filter((ref) => ref !== '').slice(0, 12)
461
+ opened.push(landFact(sessionId, { t: 'anomaly/opened', id: `u-${Math.random().toString(36).slice(2, 8)}`, what: what.slice(0, 400), ...(anchor === '' ? {} : { anchor: anchor.slice(0, 80) }), ...(touches.length === 0 ? {} : { touches }), step, by }))
409
462
  }
410
463
  return opened
411
464
  }
@@ -415,7 +468,7 @@ export function apply(ctx, config = {}) {
415
468
  const lines = []
416
469
  if (found.length > 0) lines.push(tr(`评估者看到 ${found.length} 处没登记的异常,已记成未解释项挂在卡上:${found.map((item) => clip(item.what, 80)).join(';')}。先弄清它们,再往下走。`, `The evaluator saw ${found.length} anomaly(ies) you did not record; they are now unexplained items on the card: ${found.map((item) => clip(item.what, 80)).join('; ')}. Sort them out before moving on.`))
417
470
  if (opened.length > 0) lines.push(tr(`登记了 ${opened.length} 条未解释(${opened.map((item) => item.id).join('、')}):它们挂在卡上,直到被解释、写明理由排除、或交给人(Anomaly)。`, `${opened.length} unexplained item(s) recorded (${opened.map((item) => item.id).join(', ')}): they stay on the card until explained, ruled out with a reason, or handed to a person (Anomaly).`))
418
- else if (typeof step?.expect === 'string' && step.expect !== '') lines.push(tr(`这一步的预期是「${clip(step.expect, 80)}」。结果和它对不上的话,用 Anomaly 登记,不要解释过去。`, `This step expected "${clip(step.expect, 80)}". If the result does not match, record it with Anomaly; do not explain it away.`))
471
+ else if (typeof step?.expect === 'string' && step.expect !== '') lines.push(tr(`这一步的预测是「${clip(step.expect, 80)}」。结果与预测不符时,用 Anomaly 登记,不要强行解释。`, `This step expected "${clip(step.expect, 80)}". If the result does not match, record it with Anomaly; do not explain it away.`))
419
472
  return lines.length === 0 ? '' : `\n${lines.join('\n')}`
420
473
  }
421
474
 
@@ -520,6 +573,32 @@ export function apply(ctx, config = {}) {
520
573
  return { ok: true, tests: { hypotheses: ids, level: normalizeLevel(tests.level) } }
521
574
  }
522
575
 
576
+ /**
577
+ * 步骤的 `serves` 与按候选写的 `predictions`:判断名换成 id,问题 id 要真有。
578
+ * 返回 `{ ok, extra }`(extra 直接并进步骤),或 `{ ok: false, code, message }`。
579
+ */
580
+ function resolveStepExtras(state, step) {
581
+ const extra = {}
582
+ const serves = String(step?.serves ?? '').trim()
583
+ if (serves !== '') {
584
+ const homes = [...(state.goal?.questions ?? []), ...(state.goal?.areas ?? [])].map((item) => item.id)
585
+ if (!homes.includes(serves)) return { ok: false, code: 'question_unknown', message: tr(`步骤 ${step.id} 的 serves「${serves}」不是当前目标里的问题或板块。可选:${homes.join('、') || '(目标还没有列问题:不写 serves 即归整个目标)'}`, `Step ${step.id} serves "${serves}", which is not a question or area of the current goal. Options: ${homes.join(', ') || '(the goal lists no questions: omit serves to attach to the whole goal)'}`) }
586
+ extra.serves = serves
587
+ }
588
+ if (Array.isArray(step?.predictions) && step.predictions.length > 0) {
589
+ const predictions = []
590
+ for (const item of step.predictions) {
591
+ const expect = String(item?.expect ?? '').trim()
592
+ if (expect === '') continue
593
+ const found = matchHypothesis(state.hypotheses, item?.hypothesis)
594
+ if (found === null) return { ok: false, code: 'unknown_hypothesis', message: tr(`步骤 ${step.id} 的预测指向的判断「${String(item?.hypothesis ?? '')}」对不上任何一条已登记的判断。`, `A prediction of step ${step.id} names the judgment "${String(item?.hypothesis ?? '')}", which matches no registered judgment. `) + hypothesisMenu(state.hypotheses) }
595
+ predictions.push({ hypothesis: found.id, expect: expect.slice(0, 300) })
596
+ }
597
+ if (predictions.length > 0) extra.predictions = predictions
598
+ }
599
+ return { ok: true, extra }
600
+ }
601
+
523
602
  /** 一个已登记步骤检验的判断 id(兼容旧账本的单条写法)。 */
524
603
  function testedBy(step) {
525
604
  const tests = step?.tests
@@ -601,8 +680,8 @@ export function apply(ctx, config = {}) {
601
680
  function cardTail(sessionId, preview) {
602
681
  const card = preview?.card ?? null
603
682
  if (card === null || lastCard.get(sessionId) === card) return ''
604
- lastCard.set(sessionId, card)
605
- return `\n\n${card}`
683
+ const shown = cardText(sessionId, card)
684
+ return shown === '' ? '' : `\n\n${shown}`
606
685
  }
607
686
 
608
687
  /** 一次工具调用的收尾:预演变更 → 卡片 → 返回值。 */
@@ -614,13 +693,13 @@ export function apply(ctx, config = {}) {
614
693
  * **卡没变就不附**(第六阶段):回合开头与工具返回共用「上次发过的那张」。
615
694
  * 同一张卡在一轮里重发几遍,只是把同样的话塞给模型几遍——它读得越多,照抄得越多。
616
695
  */
617
- const fresh = card !== null && lastCard.get(sessionId) !== card
618
- if (fresh) lastCard.set(sessionId, card)
696
+ const shown = card !== null && lastCard.get(sessionId) !== card ? cardText(sessionId, card) : ''
697
+ const fresh = shown !== ''
619
698
  const result = {
620
699
  ...value,
621
700
  mutations,
622
701
  card,
623
- message: fresh ? `${value.message ?? value.code ?? 'ok'}\n\n${card}` : `${value.message ?? value.code ?? 'ok'}${card === null ? '' : tr('\n(状态卡与上次相同,不再重发。)', '\n(The status card is unchanged and is not repeated.)')}`,
702
+ message: fresh ? `${value.message ?? value.code ?? 'ok'}\n\n${shown}` : `${value.message ?? value.code ?? 'ok'}${card === null ? '' : tr('\n(状态卡与上次相同,不再重发。)', '\n(The status card is unchanged and is not repeated.)')}`,
624
703
  }
625
704
  // 输出**越界就裁掉并告警**:宿主会拿 output.schema 校验工具结果,多一个未声明的字段
626
705
  // 会让整个工具调用失败(CreatePlan 曾因此全军覆没)。
@@ -779,11 +858,12 @@ export function apply(ctx, config = {}) {
779
858
  '**纪律:**',
780
859
  '- 只核对不发挥:你的职责是对照标准验收,不是重做方案、不是提改进建议。',
781
860
  '- 你没有写入权限:任何需要产出文件的事都不是你的事。',
861
+ '- 本次裁决发生在系统收下交付/结案之前。本次评估卡、事实升格、目标完成标记都在裁决返回并复核后落盘,此刻尚未出现是正常时序,不是缺失证据。仍须核对已经声称存在的历史记录及实质产物。',
782
862
  '- 你给**两项**裁决,不要混在一起:',
783
863
  ' · **交付成立吗**(`holds`):yes = 判据逐条满足、观测真实;no = 有判据不满足,或观测与记录对不上;unclear = 凭现有材料判不了。',
784
864
  ' · **每条判断的结果**(`results`,这一步检验几条就给几格):对照它的推翻条件读——support = 没碰到推翻条件,refute = 碰到了,inconclusive = 这次观测区分不了。',
785
865
  '- 交付成立与判断被推翻可以同时为真:推翻是有价值的结果,它不让交付失败。不要为了让步骤通过而写 support。',
786
- '- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。没有就给空数组。',
866
+ '- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。结论用到了 clear/knowledge/ 下的已有条目、却没在判断的 uses 里引用的,也写进来(它绕过了适用性判定)。没有就给空数组。',
787
867
  '',
788
868
  '**回包的形状就是你的动作空间(字段长度由 schema 校验,超了会被拒):**',
789
869
  '- `basis` 是**一句话结论**,≤1200 字。**不要在这里写论证**——论证放 `refs`:逐条 `{path, line}` 指到你实际读过的文件与行,让第三方照着就能复核。',
@@ -802,11 +882,12 @@ export function apply(ctx, config = {}) {
802
882
  '**Discipline:**',
803
883
  '- Check, do not improvise: your job is to accept against the criteria, not to redo the work or suggest improvements.',
804
884
  '- You cannot write: anything that needs a file produced is not your job.',
885
+ '- This evaluation precedes acceptance and closure. Its card, fact promotion and goal completion markers are persisted only after your verdict returns and is rechecked; their absence now is expected, not missing evidence. Still verify claimed historical records and substantive outputs.',
805
886
  '- You give **two** verdicts; keep them apart:',
806
887
  ' · **Does the delivery hold** (`holds`): yes = every criterion met and the observations are real; no = some criterion unmet, or observations do not match the record; unclear = cannot be decided from the material.',
807
888
  ' · **The result for each judgment** (`results`, one entry per judgment this step tests): read it against its refutation condition; support = the condition was not hit, refute = it was hit, inconclusive = this observation cannot tell.',
808
889
  '- A delivery can hold while a judgment is refuted: refutation is a valuable result and does not fail the delivery. Do not write support to let a step pass.',
809
- '- You also check **what is still unexplained** (`anomalies`): does the raw data hold anomalies the worker did not record (a reference reading that disagrees, drift between repeated points, a gap between devices or batches, a magnitude that contradicts common knowledge or the ontology)? Re-run numbers matching does not mean the data can be trusted. For each unexplained item the worker ruled out, does the reason hold? If not, list it here too. If there are none, give an empty array.',
890
+ '- You also check **what is still unexplained** (`anomalies`): does the raw data hold anomalies the worker did not record (a reference reading that disagrees, drift between repeated points, a gap between devices or batches, a magnitude that contradicts common knowledge or the ontology)? Re-run numbers matching does not mean the data can be trusted. For each unexplained item the worker ruled out, does the reason hold? If not, list it here too. If the conclusion relies on existing items under clear/knowledge/ that no judgment cites in uses, list that too (it bypassed the applicability check). If there are none, give an empty array.',
810
891
  '',
811
892
  '**The shape of your reply is your action space (field lengths are checked by the schema; overruns are rejected):**',
812
893
  '- `basis` is a **one-sentence conclusion**, ≤1200 characters. **Do not argue here**; arguments go in `refs`: one `{path, line}` per file and line you actually read, so a third party can check.',
@@ -870,6 +951,8 @@ export function apply(ctx, config = {}) {
870
951
  additionalProperties: false,
871
952
  },
872
953
  },
954
+ rechecks: { type: 'array', description: '复检事实时逐条列出已独立解决的待核验原因;引用事实文件的 rechecks.id,说明当前证据怎样解决;未解决的不要列出', items: { type: 'object', properties: { fact: { type: 'string' }, id: { type: 'string' }, basis: { type: 'string' } }, required: ['fact', 'id', 'basis'], additionalProperties: false } },
955
+ reuse: { type: 'array', description: '逐条核验最终 uses:确实直接采用、依据可检查、范围适用才 support;否则 refute 或 inconclusive', items: { type: 'object', properties: { id: { type: 'string' }, verdict: { type: 'string', enum: ['support', 'refute', 'inconclusive'] }, basis: { type: 'string' } }, required: ['id', 'verdict', 'basis'], additionalProperties: false } },
873
956
  lessons: {
874
957
  type: 'array',
875
958
  description: tr('任务书列了待核的经验(L1、L2……)时,每条各一格;没列就给空数组。', 'When the brief lists lessons to check (L1, L2, ...), one entry each; otherwise an empty array.'),
@@ -968,6 +1051,8 @@ export function apply(ctx, config = {}) {
968
1051
  ],
969
1052
  ),
970
1053
  ...anomalyBrief(state, gate),
1054
+ ...tested.map(item => `Registered hypothesis ${item.id}: uses=${JSON.stringify(item.uses ?? [])}; scope=${JSON.stringify(mergeScope(item.scope, { conditions: goal?.conditions ?? {} }))}. These are framing declarations, not confirmation of final reuse.`),
1055
+ ...tested.filter((item) => item.retests).map((item) => `Re-test ${item.retests}: independently inspect each pending reason in clear/knowledge/facts/${item.retests}.json and report only resolved reason IDs in rechecks. A supporting result alone does not resolve all reasons.`),
971
1056
  ...(Array.isArray(gate.extra) && gate.extra.length > 0 ? ['', ...gate.extra] : []),
972
1057
  '',
973
1058
  ...tr(
@@ -1057,6 +1142,8 @@ export function apply(ctx, config = {}) {
1057
1142
  }
1058
1143
  const basis = typeof value?.basis === 'string' && value.basis.trim() !== '' ? value.basis.trim() : tr('评估者未给出依据', 'the evaluator gave no basis')
1059
1144
  return {
1145
+ rechecks: (Array.isArray(value?.rechecks) ? value.rechecks : []).filter((row) => typeof row.fact === 'string' && typeof row.id === 'string').map((row) => ({ fact: row.fact, id: row.id, basis: String(row.basis ?? '') })),
1146
+ reuse: (Array.isArray(value?.reuse) ? value.reuse : []).filter((row) => typeof row.id === 'string' && ['support', 'refute', 'inconclusive'].includes(row.verdict)).map((row) => ({ id: row.id, verdict: row.verdict, basis: String(row.basis ?? '') })),
1060
1147
  holds,
1061
1148
  results,
1062
1149
  anomalies,
@@ -1180,16 +1267,11 @@ export function apply(ctx, config = {}) {
1180
1267
  if (subagents === undefined) return { ok: false, reason: tr('subagents 服务不可用', 'the subagents service is unavailable'), failures: [] }
1181
1268
  const base = { label: options.label, parent: options.parent, signal: options.signal, prompt: text(options.prompt) }
1182
1269
  const persona = options.persona
1183
- const schema = options.outputSchema ?? undefined
1270
+ const schema = options.outputSchema ? nativeAuditSchema(options.outputSchema) : undefined
1184
1271
  const toolFilter = options.toolFilter ?? null
1185
1272
  const failures = []
1186
- const attempts = []
1187
- if (toolFilter !== null) attempts.push({ variant: { persona, outputSchema: schema, toolFilter }, capability: 'persona+outputSchema+toolFilter' })
1188
- attempts.push({ variant: { persona, outputSchema: schema }, capability: 'persona+outputSchema' })
1189
- if (toolFilter !== null) attempts.push({ variant: { persona, toolFilter }, capability: 'persona+toolFilter' })
1190
- attempts.push({ variant: { persona }, capability: 'persona' })
1191
- if (schema !== undefined) attempts.push({ variant: { outputSchema: schema }, capability: 'outputSchema' })
1192
- attempts.push({ variant: {}, capability: 'prompt-only' })
1273
+ // These are required audit capabilities. An infrastructure rejection must not silently weaken the verdict channel.
1274
+ const attempts = [{ variant: { persona, outputSchema: schema, ...(toolFilter ? { toolFilter } : {}) }, capability: 'persona+outputSchema+toolFilter' }]
1193
1275
  for (const attempt of attempts) {
1194
1276
  try {
1195
1277
  const run = await subagents.start(CFG.auditProvider, { ...base, ...attempt.variant })
@@ -1215,7 +1297,7 @@ export function apply(ctx, config = {}) {
1215
1297
  * 平台边界:宿主的 `sessions` 服务只认**活在当前进程里**的会话(`get(id)`)。
1216
1298
  * 会话不在了就返回 null,由调用方如实记为 unknown——这一层我们不假装能读。
1217
1299
  */
1218
- function recoverFromChildSession(childId) {
1300
+ async function recoverFromChildSession(childId) {
1219
1301
  const sessions = ctx.get('sessions')
1220
1302
  if (sessions === undefined || typeof sessions.get !== 'function') return null
1221
1303
  let session = null
@@ -1232,10 +1314,15 @@ export function apply(ctx, config = {}) {
1232
1314
  session = null
1233
1315
  }
1234
1316
  }
1235
- if (session === null) return null
1236
1317
  let events = []
1237
1318
  try {
1238
- events = typeof session.ownEvents === 'function' ? session.ownEvents() : typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : []
1319
+ if (session !== null) events = typeof session.ownEvents === 'function' ? session.ownEvents() : typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : []
1320
+ else {
1321
+ const query = ctx.get('sessionQuery')
1322
+ if (typeof query?.observeSession !== 'function') return null
1323
+ const observation = await query.observeSession(childId, { projectionMode: 'none' })
1324
+ try { events = [...observation.events] } finally { observation[Symbol.dispose]?.() }
1325
+ }
1239
1326
  } catch {
1240
1327
  return null
1241
1328
  }
@@ -1261,7 +1348,7 @@ export function apply(ctx, config = {}) {
1261
1348
  * 半截文本被当成「回灌过的结论」是这里最危险的假话。两条路形状一致,
1262
1349
  * 「这句话是从哪条路来的」就不再影响账本的可读性。
1263
1350
  */
1264
- return { ok, stopReason: reason, conclusion: ok ? conclusion : tr(`子任务未正常结束(${reason}):${conclusion.slice(0, 1200)}`, `The child task did not end normally (${reason}): ${conclusion.slice(0, 1200)}`) }
1351
+ return { ok, structured: recoveredStructuredOutput(events.slice(0, events.indexOf(end))), stopReason: reason, conclusion: ok ? conclusion : tr(`子任务未正常结束(${reason}):${conclusion.slice(0, 1200)}`, `The child task did not end normally (${reason}): ${conclusion.slice(0, 1200)}`) }
1265
1352
  }
1266
1353
 
1267
1354
 
@@ -1285,7 +1372,7 @@ export function apply(ctx, config = {}) {
1285
1372
  * 拿不到目录(服务不在 / 查询失败)时**什么都不做**:不猜、不误伤正在跑的裁决。
1286
1373
  */
1287
1374
  async function sweepEndedAudits(sessionId, state) {
1288
- const pending = (state?.audits ?? []).filter((audit) => audit.verdict === null && typeof audit.child === 'string' && audit.child !== '')
1375
+ const pending = (state?.audits ?? []).filter((audit) => audit.verdict === null)
1289
1376
  if (pending.length === 0) return { mutations: [], lost: 0, lines: [] }
1290
1377
  // 这个进程里正攥着的那几次派遣:它们是活的,不问目录。
1291
1378
  const known = new Set([...pendingAudits.values()].map((entry) => String(entry.run?.id ?? '')))
@@ -1303,17 +1390,23 @@ export function apply(ctx, config = {}) {
1303
1390
  const running = new Set((Array.isArray(children) ? children : []).filter((item) => item?.kind === 'child' && item.activity === 'running').map((item) => String(item.id)))
1304
1391
  const mutations = []
1305
1392
  const lines = []
1306
- for (const audit of unresolved) {
1393
+ for (const pendingAudit of unresolved) {
1394
+ const audit = { ...pendingAudit }
1395
+ if (!audit.child) {
1396
+ const child = children.find((child) => String(child.label ?? child.name ?? '').includes(audit.id))
1397
+ if (child) { audit.child = String(child.id); mutations.push({ t: 'audit/dispatched', id: audit.id, step: audit.step, evaluator_session: audit.child, status: 'recovered', digest: audit.digest }) }
1398
+ else if (Date.now() - (audit.at ?? 0) < CFG.auditHardTimeoutMs) continue
1399
+ }
1307
1400
  if (running.has(String(audit.child))) continue
1308
1401
  /**
1309
1402
  * 宿主说已结束 ⇒ **先把它的结论取回来**(读它自己的会话日志)。
1310
1403
  * 跳过它就把「结束」误报成「死亡」,还会诱导重新交付 ⇒ 同一次评估被重做。
1311
1404
  */
1312
- const recovered = recoverVerdictFromChildSession(audit.child)
1313
- if (recovered !== null && recovered.ok === true) {
1314
- const card = { schema_version: 'clearai.audit.v2', kind: audit.kind ?? 'evidence_audit', step_id: audit.step, auditor_run_id: String(audit.child), holds: recovered.verdict.holds, results: recovered.verdict.results, shortfalls: recovered.verdict.shortfalls, card: recovered.verdict.basis, created_at: Date.now() }
1405
+ const recovered = await recoverVerdictFromChildSession(audit.child)
1406
+ if (recovered !== null && recovered.ok === true && (!String(audit.capability).includes('outputSchema') || recovered.structured === true)) {
1407
+ const card = { schema_version: 'clearai.audit.v2', kind: audit.kind ?? 'evidence_audit', step_id: audit.step, auditor_run_id: String(audit.child), holds: recovered.verdict.holds, rechecks: recovered.verdict.rechecks, reuse: recovered.verdict.reuse, results: recovered.verdict.results, anomalies: recovered.verdict.anomalies, lessons: recovered.verdict.lessons, shortfalls: recovered.verdict.shortfalls, card: recovered.verdict.basis, created_at: Date.now() }
1315
1408
  const cardPath = writeAuditCard(sessionId, audit.step, card)
1316
- mutations.push({ t: 'audit/settled', id: audit.id, step: audit.step, verdict: recovered.verdict.holds, holds: recovered.verdict.holds, results: recovered.verdict.results, anomalies: recovered.verdict.anomalies, basis: recovered.verdict.basis, shortfalls: recovered.verdict.shortfalls, card_path: cardPath, digest: audit.digest ?? null })
1409
+ mutations.push({ t: 'audit/settled', id: audit.id, step: audit.step, verdict: cardPath === null ? 'unknown' : recovered.verdict.holds, holds: cardPath === null ? 'unknown' : recovered.verdict.holds, rechecks: recovered.verdict.rechecks, reuse: recovered.verdict.reuse, results: recovered.verdict.results, anomalies: recovered.verdict.anomalies, basis: recovered.verdict.basis, shortfalls: cardPath === null ? ['card_persist_failed'] : recovered.verdict.shortfalls, card_path: cardPath, digest: audit.digest ?? null })
1317
1410
  lines.push(tr(`${audit.step}:裁决从子会话日志取回(交付成立:${recovered.verdict.holds})`, `${audit.step}: verdict recovered from the child session log (holds: ${recovered.verdict.holds})`))
1318
1411
  continue
1319
1412
  }
@@ -1334,12 +1427,12 @@ export function apply(ctx, config = {}) {
1334
1427
  * 返回三档:`{ok:true, verdict}` 取回了;`{ok:false, stopReason}` 它结束了但未正常完成;
1335
1428
  * `null` 连它的日志都读不到。三档都只是**读数**,判断留给调用方如实分档。
1336
1429
  */
1337
- function recoverVerdictFromChildSession(childId) {
1338
- const settled = recoverFromChildSession(childId)
1430
+ async function recoverVerdictFromChildSession(childId) {
1431
+ const settled = await recoverFromChildSession(childId)
1339
1432
  if (settled === null) return null
1340
1433
  if (settled.ok !== true) return { ok: false, stopReason: settled.stopReason }
1341
- const verdict = normalizeVerdict(parseLooseJson([{ type: 'text', text: settled.conclusion }]))
1342
- return { ok: true, verdict }
1434
+ const verdict = normalizeVerdict(settled.structured ?? parseLooseJson([{ type: 'text', text: settled.conclusion }]))
1435
+ return { ok: true, verdict, structured: settled.structured !== undefined }
1343
1436
  }
1344
1437
 
1345
1438
  /**
@@ -1357,61 +1450,8 @@ export function apply(ctx, config = {}) {
1357
1450
  * 只有**落定过的裁决**才可复用(`verdict` 非 null 且不是 unknown):
1358
1451
  * `unknown` 不是裁决,它只说明"那一次没成",那正是应该重派的理由。
1359
1452
  */
1360
- function auditDigest(kind, step, plan, state, gate) {
1361
- /**
1362
- * **digest 只盖「材料」,不盖「上一次裁决留下的东西」。**
1363
- *
1364
- * 为什么这一条是这套复用能不能用的分水岭:一次不确定的结案自己会落一条
1365
- * `evidence/recorded`(`anchor:'auditor'`)。原来 digest 把证据集合整个算进去,
1366
- * 于是**每重试一次 digest 就变一次**,复用永远命中不了——模型每喊一次结案就再烧两三分钟,
1367
- * 而两次之间它什么都没改。这不是"新证据",是同一条评审自己的回声。
1368
- *
1369
- * 所以这里只取**可能改变结论的材料**:
1370
- * · 目标修订号(判据/假设换了内容才会变);
1371
- * · 计划的步与产物(交付了什么);
1372
- * · 观测(state.materials);
1373
- * · 原始假设(claim / status / 断言)——**刻意不用派生读数**:
1374
- * `supportedLevel` / `refutations` / `inconclusive` 都是证据算出来的,
1375
- * 而审计留下的那条证据会把它们改掉,用它就等于把回声又算进来一次;
1376
- * · 已升格事实;
1377
- * · **非审计来源**的证据(自判的 L0–L2 是真材料,保留)。
1378
- *
1379
- * 于是语义变成:材料变了 ⇒ 必然重审;材料没变 ⇒ 复用上次裁决,并把这件事说明白。
1380
- */
1381
- const material = (Array.isArray(state?.evidence) ? state.evidence : [])
1382
- .filter((item) => String(item?.anchor ?? '') !== 'auditor')
1383
- .map((item) => `${String(item?.id ?? '')}:${String(item?.verdict ?? '')}:${String(item?.level ?? '')}`)
1384
- const hypotheses = (Array.isArray(state?.hypotheses) ? state.hypotheses : []).map((item) =>
1385
- [String(item?.id ?? ''), String(item?.status ?? ''), String(item?.claim ?? '').replace(/\s+/g, ' '), JSON.stringify(item?.assertions ?? null)].join(':'),
1386
- )
1387
- const materials = (Array.isArray(state?.materials) ? state.materials : []).map((item) => `${String(item?.id ?? '')}:${String(item?.digest ?? '')}`)
1388
- /** 做的人登记与消解的未解释项是材料;评估者自己报的是回声,不算。 */
1389
- const anomalies = [...(Array.isArray(state?.anomalies) ? state.anomalies : []), ...(Array.isArray(gate?.anomalies) ? gate.anomalies : [])].filter((item) => item?.by !== 'evaluator').map((item) => `${String(item?.id ?? '')}:${String(item?.status ?? 'open')}`)
1390
- const facts = (Array.isArray(state?.facts) ? state.facts : []).map((item) => `${String(item?.id ?? '')}:${String(item?.level ?? '')}:${JSON.stringify(item?.assertions ?? null)}`)
1391
- /**
1392
- * 步的**判据**与产物一起算材料:判据一变,"这一步算不算做完"就是另一个问题
1393
- * (`evaluatorPrompt` 会把判据逐字交给评估者)——不把它算进来会出现
1394
- * "改了判据却复用旧裁决"这种明显错的复用。
1395
- */
1396
- const steps = (Array.isArray(plan?.steps) ? plan.steps : []).map((item) => `${String(item?.id ?? '')}:${String(item?.status ?? '')}:${String(item?.done_criteria ?? '')}:${(Array.isArray(item?.artifacts) ? item.artifacts : []).join('|')}`)
1397
- const goal = `${String(state?.goal?.id ?? '')}:${Number(state?.goal?.revision ?? 0)}`
1398
- /**
1399
- * **准入坐标里只有"产物"算材料**。
1400
- *
1401
- * `gate.confirmed` 在两条路上形状不同:证据审计那一侧是**产物路径 + 字节数 + 内容摘要**
1402
- * (文件内容一变,digest 就变——这是"交付的东西真的改了吗"的唯一硬信号);
1403
- * 目标审计那一侧是 `evidence:` / `hypothesis:` 两类引用(证据集合与派生读数)——
1404
- * 把它们算进来,就等于又把上一次评审的回声算进来一次。
1405
- * 所以:留下产物,去掉回声。
1406
- */
1407
- const artifacts = (Array.isArray(gate?.confirmed) ? gate.confirmed : [])
1408
- .filter((item) => {
1409
- const ref = String(item?.ref ?? '')
1410
- return !ref.startsWith('evidence:') && !ref.startsWith('hypothesis:')
1411
- })
1412
- .map((item) => `${String(item?.ref ?? '')}:${String(item?.bytes ?? '')}:${String(item?.digest ?? '')}`)
1413
- const root = createHash('sha256').update(JSON.stringify([kind, step.id, goal, steps, materials, hypotheses, facts, material, artifacts, ...(anomalies.length > 0 ? [anomalies] : [])])).digest('hex')
1414
- return root.slice(0, 16)
1453
+ function auditDigest(kind, step, plan, state, gate, sessionId) {
1454
+ return auditMaterialDigest({ kind, step, plan, state, gate, cwd: sessionCwd(sessionId) })
1415
1455
  }
1416
1456
 
1417
1457
  /**
@@ -1433,7 +1473,7 @@ export function apply(ctx, config = {}) {
1433
1473
  const matched = (state?.audits ?? []).filter((audit) => String(audit?.step ?? '') === String(stepId) && String(audit?.digest ?? '') === digest)
1434
1474
  for (let index = matched.length - 1; index >= 0; index -= 1) {
1435
1475
  const audit = matched[index]
1436
- if (!['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1476
+ if (!digest.startsWith('v5:') || !audit.card_path || !existsSync(audit.card_path) || !['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1437
1477
  return audit
1438
1478
  }
1439
1479
  return null
@@ -1443,7 +1483,10 @@ export function apply(ctx, config = {}) {
1443
1483
  const mutations = []
1444
1484
  const auditKey = `a-${step.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1445
1485
  const key = `${sessionId}:${kind}:${step.id}`
1446
- const digest = auditDigest(kind, step, plan, stateOf(sessionId), gate)
1486
+ const initialSync = syncWorkspace(sessionId, stateOf(sessionId))
1487
+ if (initialSync !== null) mutations.push(initialSync)
1488
+ const initialState = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state ?? stateOf(sessionId)
1489
+ const digest = auditDigest(kind, step, plan, initialState, gate, sessionId)
1447
1490
  let entry = pendingAudits.get(key)
1448
1491
  /**
1449
1492
  * **同态复用**:先看在飞的(pendingAudits),再看**已经落定的**(投影里 digest 相同且给出了裁决的那一条)。
@@ -1459,6 +1502,17 @@ export function apply(ctx, config = {}) {
1459
1502
  * 材料没变就重来 ⇒ 计数 +1,达阈值把计划置 blocked 停下等人。
1460
1503
  * 于是"每次交付都被记下来"与"不重复花钱"两件事同时成立。
1461
1504
  */
1505
+ if (entry === undefined) {
1506
+ const durable = (stateOf(sessionId).audits ?? []).find((audit) => audit.step === step.id && audit.verdict === null)
1507
+ if (durable) {
1508
+ const swept = await sweepEndedAudits(sessionId, stateOf(sessionId))
1509
+ mutations.push(...swept.mutations)
1510
+ const recoveredState = previewOf(host(), sessionId, mutations)?.state ?? stateOf(sessionId)
1511
+ if ((recoveredState.audits ?? []).some((audit) => audit.id === durable.id && audit.verdict === null)) return { holds: 'pending', results: [], basis: '已有持久派发,等待关联评估者恢复', shortfalls: ['audit_pending'], cardPath: null, mutations }
1512
+ const recovered = reuseAudit(recoveredState, step.id, digest)
1513
+ if (recovered) return { holds: auditHolds(recovered), results: recovered.results ?? [], basis: recovered.basis ?? '', shortfalls: recovered.shortfalls ?? [], cardPath: recovered.card_path, reuse: recovered.reuse ?? [], reused: true, digest, mutations }
1514
+ }
1515
+ }
1462
1516
  if (entry === undefined) {
1463
1517
  const reused = reuseAudit(stateOf(sessionId), step.id, digest)
1464
1518
  if (reused !== null) {
@@ -1479,6 +1533,7 @@ export function apply(ctx, config = {}) {
1479
1533
  holds: auditHolds(reused),
1480
1534
  results: Array.isArray(reused.results) ? reused.results : [],
1481
1535
  basis: String(reused.basis ?? ''),
1536
+ reuse: reused.reuse ?? [],
1482
1537
  shortfalls: Array.isArray(reused.shortfalls) ? reused.shortfalls : [],
1483
1538
  cardPath: reused.card_path ?? null,
1484
1539
  /**
@@ -1501,18 +1556,21 @@ export function apply(ctx, config = {}) {
1501
1556
  * 而"我派过一个评估者"是**已经发生的事实**。把它写在 await 之后,等于把事实寄存在
1502
1557
  * 一个会被撤销的栈帧里:`hold` 不触发、`sweepEndedAudits` 看不见,模型只会原样重试。
1503
1558
  *
1504
- * `id` 取一个与裁决 digest 绑定的**稳定键**:同一个状态反复结案得到同一个键,
1505
- * 于是下面那次"带上子会话 id 的完整事实"按 id 覆盖它,而不是在账上留两条。
1559
+ * 每次派发使用独立尝试 id;补齐子会话时按同 id 更新。已落定的有效裁决按材料 digest 复用。
1506
1560
  */
1507
- const pendingId = `audit:pending:${kind}:${step.id}:${digest}`
1561
+ const pendingId = `audit:pending:${auditPathComponent(`${sessionId}:${kind}:${step.id}:${digest}:${auditKey}`).slice(0, 32)}`
1508
1562
  landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, capability: null, evaluator_session: null, status: 'dispatching' })
1563
+ try { await flushFacts(sessionId) } catch (error) {
1564
+ mutations.push({ t: 'audit/settled', id: pendingId, step: step.id, verdict: 'unknown', holds: 'unknown', basis: String(error.message), shortfalls: ['audit_dispatch_not_durable'], card_path: null, digest })
1565
+ return { holds: 'unknown', results: [], basis: '派发记录未持久保存,未派发评估者', shortfalls: ['audit_dispatch_not_durable'], cardPath: null, digest, mutations }
1566
+ }
1509
1567
  const rerunDir = CFG.auditRerun ? rerunCopy(sessionId, auditKey) : null
1510
1568
  const dispatched = await dispatchSubRun({
1511
- label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id}`,
1569
+ label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id} · ${pendingId}`,
1512
1570
  persona: evaluatorDiscipline(),
1513
- prompt: evaluatorPrompt(stateOf(sessionId), step, gate, sessionId, rerunDir),
1571
+ prompt: evaluatorPrompt(initialState, step, gate, sessionId, rerunDir),
1514
1572
  outputSchema: verdictSchema(),
1515
- toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, 'bash']) },
1573
+ toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, process.platform === 'win32' ? 'pwsh' : 'bash']) },
1516
1574
  parent: agent,
1517
1575
  signal,
1518
1576
  })
@@ -1526,8 +1584,14 @@ export function apply(ctx, config = {}) {
1526
1584
  mutations.push({ t: 'audit/settled', id: pendingId, step: step.id, verdict: 'unknown', holds: 'unknown', basis: tr(`独立评估者无法派遣(${dispatched.reason})`, `The independent evaluator could not be dispatched (${dispatched.reason})`), shortfalls: ['audit_dispatch_failed'], card_path: null, digest })
1527
1585
  return { holds: 'unknown', results: [], basis: tr(`独立评估者无法派遣(${dispatched.reason})`, `The independent evaluator could not be dispatched (${dispatched.reason})`), shortfalls: ['audit_dispatch_failed'], cardPath: null, mutations }
1528
1586
  }
1529
- mutations.push({ t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, evaluator_session: String(dispatched.run.id), capability: dispatched.capability, digest, status: 'dispatched' })
1530
- entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined }
1587
+ mutations.push(landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, evaluator_session: String(dispatched.run.id), capability: dispatched.capability, digest, status: 'dispatched' }))
1588
+ try { await flushFacts(sessionId) } catch (error) {
1589
+ try { await dispatched.run.dispose?.() } catch {}
1590
+ dropRerunCopy(rerunDir)
1591
+ mutations.push({ t: 'audit/settled', id: pendingId, step: step.id, verdict: 'unknown', holds: 'unknown', basis: String(error.message), shortfalls: ['audit_child_not_durable'], card_path: null, digest })
1592
+ return { holds: 'unknown', results: [], basis: '子会话关联未持久保存,已停止评估', shortfalls: ['audit_child_not_durable'], cardPath: null, digest, mutations }
1593
+ }
1594
+ entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined, startedAt: Date.now() }
1531
1595
  pendingAudits.set(key, entry)
1532
1596
  entry.settled = dispatched.run.result.then(
1533
1597
  (value) => ({ ok: true, value }),
@@ -1542,12 +1606,32 @@ export function apply(ctx, config = {}) {
1542
1606
  }),
1543
1607
  ])
1544
1608
  if (outcome === null) {
1609
+ /**
1610
+ * **超过硬上限就放开**:一次挂住的评估会拖住整个目标(出现过挂数小时的情形)。
1611
+ * 超时如实结成「未知」(与评估者失败同一种结局),释放这次派遣;下一次结案或交付重新派。
1612
+ */
1613
+ if (Date.now() - (entry.startedAt ?? Date.now()) >= CFG.auditHardTimeoutMs) {
1614
+ pendingAudits.delete(key)
1615
+ try {
1616
+ await entry.run.dispose?.()
1617
+ } catch {
1618
+ // 收不掉也不影响结算:这次派遣在账上已经结了。
1619
+ }
1620
+ dropRerunCopy(entry.rerunDir ?? null)
1621
+ const basis = tr(`评估者超过 ${Math.round(CFG.auditHardTimeoutMs / 60000)} 分钟没有给出裁决,如实记为未知`, `The evaluator gave no verdict within ${Math.round(CFG.auditHardTimeoutMs / 60000)} minutes; recorded honestly as unknown`)
1622
+ mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls: ['audit_timeout'], card_path: null, digest })
1623
+ return { holds: 'unknown', results: [], basis, shortfalls: ['audit_timeout'], cardPath: null, digest, mutations }
1624
+ }
1545
1625
  // 仍在跑:条目留着,下一次交付继续等同一次派遣(不重复派遣)。派发事实已经在上面的 mutations 里。
1546
1626
  return { holds: 'pending', results: [], basis: tr(`评估者仍在跑(${Math.round(CFG.auditTimeoutMs / 1000)}s 未回)`, `The evaluator is still running (no reply after ${Math.round(CFG.auditTimeoutMs / 1000)}s)`), shortfalls: ['audit_pending'], cardPath: null, mutations }
1547
1627
  }
1548
1628
  // 已落定:这次派遣的生命周期到此为止。下一次交付是**新的一次评估**(新证据),必须重新派遣。
1549
1629
  pendingAudits.delete(key)
1550
1630
  dropRerunCopy(entry.rerunDir ?? null)
1631
+ const settleUnknown = (basis, shortfalls) => {
1632
+ mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls, card_path: null, digest })
1633
+ return { holds: 'unknown', results: [], basis, shortfalls, cardPath: null, digest, mutations }
1634
+ }
1551
1635
  if (outcome.ok !== true) {
1552
1636
  return settleUnknown(tr(`评估者失败:${String(outcome.error?.message ?? outcome.error)}`, `The evaluator failed: ${String(outcome.error?.message ?? outcome.error)}`), ['audit_failed'])
1553
1637
  }
@@ -1559,27 +1643,31 @@ export function apply(ctx, config = {}) {
1559
1643
  * 结局不好也是结局,如实落下来——不然那条派发事实会在账上挂到天荒地老,
1560
1644
  * 而"评估者没有悬空"这条不变量也只能红着,连解释都拿不出证据。
1561
1645
  */
1562
- const settleUnknown = (basis, shortfalls) => {
1563
- mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls, card_path: null, digest })
1564
- return { holds: 'unknown', results: [], basis, shortfalls, cardPath: null, digest, mutations }
1565
- }
1646
+
1566
1647
  const settled = outcome.value
1567
1648
  const stopReason = String(settled?.stopReason ?? 'completed')
1568
1649
  if (stopReason !== 'completed' && settled?.structured === undefined) {
1569
1650
  return settleUnknown(tr(`评估者未正常结束(${stopReason})`, `The evaluator did not end normally (${stopReason})`), ['audit_incomplete'])
1570
1651
  }
1652
+ if (settled?.structured === undefined && entry.capability.includes('outputSchema')) return settleUnknown('原生结构化审计结果缺失,文本不作为新裁决', ['audit_structured_missing'])
1571
1653
  const verdict = settled?.structured !== undefined ? normalizeVerdict(settled.structured) : normalizeVerdict(parseLooseJson(settled?.output))
1572
1654
  try {
1573
1655
  await entry.run.dispose?.()
1574
1656
  } catch {
1575
1657
  /* dispose 失败不影响裁决事实 */
1576
1658
  }
1577
- const card = { schema_version: 'clearai.audit.v2', kind, step_id: step.id, auditor_run_id: String(entry.run.id), holds: verdict.holds, results: verdict.results, anomalies: verdict.anomalies, ...(verdict.lessons.length > 0 ? { lessons: verdict.lessons } : {}), shortfalls: verdict.shortfalls, card: verdict.basis, created_at: Date.now() }
1659
+ const card = { schema_version: 'clearai.audit.v2', kind, step_id: step.id, auditor_run_id: String(entry.run.id), holds: verdict.holds, rechecks: verdict.rechecks, reuse: verdict.reuse, results: verdict.results, anomalies: verdict.anomalies, ...(verdict.lessons.length > 0 ? { lessons: verdict.lessons } : {}), shortfalls: verdict.shortfalls, card: verdict.basis, created_at: Date.now() }
1578
1660
  const cardPath = writeAuditCard(sessionId, step.id, card)
1579
1661
  if (cardPath === null) {
1580
1662
  return settleUnknown(tr('评估卡落盘失败:裁决降级', 'Could not save the evaluation card: verdict downgraded'), ['card_persist_failed'])
1581
1663
  }
1582
- mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: verdict.holds, holds: verdict.holds, results: verdict.results, anomalies: verdict.anomalies, basis: verdict.basis, shortfalls: verdict.shortfalls, card_path: cardPath, digest })
1664
+ mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: verdict.holds, holds: verdict.holds, rechecks: verdict.rechecks, reuse: verdict.reuse, results: verdict.results, anomalies: verdict.anomalies, basis: verdict.basis, shortfalls: verdict.shortfalls, card_path: cardPath, digest })
1665
+ const synced = syncWorkspace(sessionId, stateOf(sessionId))
1666
+ if (synced !== null) mutations.push(synced)
1667
+ const fresh = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state
1668
+ if (fresh === undefined || auditDigest(kind, step, plan, fresh, gate, sessionId) !== digest) {
1669
+ return { ...verdict, holds: 'unknown', shortfalls: [...verdict.shortfalls, 'audit_material_changed'], cardPath, digest, mutations }
1670
+ }
1583
1671
  return { ...verdict, cardPath, digest, mutations }
1584
1672
  }
1585
1673
 
@@ -1593,7 +1681,7 @@ export function apply(ctx, config = {}) {
1593
1681
  function rerunCopy(sessionId, auditKey) {
1594
1682
  const cwd = sessionCwd(sessionId)
1595
1683
  if (cwd === null) return null
1596
- const target = join(tmpdir(), `clearai-rerun-${auditKey}`)
1684
+ const target = join(tmpdir(), `clearai-rerun-${auditPathComponent(auditKey)}`)
1597
1685
  const skip = new Set([join(cwd, 'clear'), join(cwd, '.git'), join(cwd, 'node_modules')])
1598
1686
  try {
1599
1687
  cpSync(cwd, target, { recursive: true, filter: (source) => !skip.has(source) })
@@ -1616,10 +1704,10 @@ export function apply(ctx, config = {}) {
1616
1704
 
1617
1705
  /** 评估卡落盘(系统的面)。写不进 → 返回 null,调用方 fail-closed。 */
1618
1706
  function writeAuditCard(sessionId, stepId, card) {
1619
- const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', String(stepId), `${String(card.auditor_run_id)}.json`)
1707
+ const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', auditPathComponent(stepId), `${auditPathComponent(card.auditor_run_id)}.json`)
1620
1708
  if (file === null) return null
1621
1709
  try {
1622
- writeTextFile(file, `${JSON.stringify(card, null, 2)}\n`)
1710
+ writeTextFile(file, `${JSON.stringify({ ...card, evaluator: 'independent' }, null, 2)}\n`)
1623
1711
  return file
1624
1712
  } catch (error) {
1625
1713
  ctx.logger?.warn?.(`clearai kernel: 评估卡落盘失败 ${String(error?.message ?? error)}`)
@@ -1866,16 +1954,26 @@ export function apply(ctx, config = {}) {
1866
1954
 
1867
1955
  /** 问人时的选项文字(按会话语言给);答案两种语言都认。 */
1868
1956
  const CHOICES = {
1957
+ releaseYes: ['批准此次交付', 'Approve this delivery'],
1958
+ releaseNo: ['暂不批准', 'Not now'],
1959
+ releaseCommand: ['批准执行此命令', 'Approve this command'],
1960
+ stallContinue: ['按缺口继续修改', 'Let it fix the gaps'],
1961
+ stallVoid: ['作废此步骤', 'Void this step'],
1962
+ factRetract: ['撤回此事实', 'Retract this fact'],
1963
+ factKeep: ['维持原事实', 'Keep the fact'],
1964
+ }
1965
+ /** 0.5.1 前的选项文字:旧剧本(`--answers`)与旧会话里人已选过的答案照样认。 */
1966
+ const LEGACY_CHOICES = {
1869
1967
  releaseYes: ['放行这次交付', 'Release this delivery'],
1870
- releaseNo: ['先不放行', 'Not now'],
1968
+ releaseNo: ['先不放行'],
1871
1969
  releaseCommand: ['放行这条命令', 'Release this command'],
1872
- stallContinue: ['让它按缺口再改', 'Let it fix the gaps'],
1873
- stallVoid: ['作废这一步', 'Void this step'],
1874
- factRetract: ['撤回这条事实', 'Retract this fact'],
1875
- factKeep: ['维持原事实', 'Keep the fact'],
1970
+ stallContinue: ['让它按缺口再改'],
1971
+ stallVoid: ['作废这一步'],
1972
+ factRetract: ['撤回这条事实'],
1973
+ factKeep: [],
1876
1974
  }
1877
1975
  const choiceLabel = (key) => tr(...CHOICES[key])
1878
- const chose = (asked, key) => CHOICES[key].includes(asked?.choice)
1976
+ const chose = (asked, key) => CHOICES[key].includes(asked?.choice) || LEGACY_CHOICES[key].includes(asked?.choice)
1879
1977
  /** 没问到人的原因,一句人话。 */
1880
1978
  const unanswered = (asked) => (asked.reason === 'cancelled' ? tr('人把问题撤下了', 'the person withdrew the question') : tr('没有人能回答', 'nobody can answer'))
1881
1979
 
@@ -1887,8 +1985,8 @@ export function apply(ctx, config = {}) {
1887
1985
  async function escalateBlocked(exec, plan, step, attempts, reason, mutations) {
1888
1986
  const asked = await askHuman(exec, {
1889
1987
  id: `blocked-${plan.id}-${step.id}`,
1890
- header: tr('这一步卡住了', 'This step is stuck'),
1891
- question: tr(`步骤 ${step.id}(${clip(step.do, 60)})连续 ${attempts} 次没过:${clip(reason, 200)}。怎么办?`, `Step ${step.id} (${clip(step.do, 60)}) failed ${attempts} times in a row: ${clip(reason, 200)}. What should happen?`),
1988
+ header: tr('此步骤受阻', 'This step is stuck'),
1989
+ question: tr(`步骤 ${step.id}(${clip(step.do, 60)})连续 ${attempts} 次未通过:${clip(reason, 200)}。请选择处理方式。`, `Step ${step.id} (${clip(step.do, 60)}) failed ${attempts} times in a row: ${clip(reason, 200)}. What should happen?`),
1892
1990
  options: [
1893
1991
  { label: choiceLabel('stallContinue'), description: tr('模型按缺口改判据或换做法后再交;你可以补一句方向。', 'The model revises the criteria or the approach against the gaps and delivers again; you can add a hint.') },
1894
1992
  { label: choiceLabel('stallVoid'), description: tr('这一步不做了,带原因作废(记录保留)。', 'Drop this step and void it with a reason (the record stays).') },
@@ -1930,13 +2028,59 @@ export function apply(ctx, config = {}) {
1930
2028
  if (fact !== null) pending.push(fact)
1931
2029
  }
1932
2030
  const open = pending.filter((fact) => fact.review === undefined || fact.review === null)
1933
- if (open.length === 0) return ''
1934
2031
  const notes = []
2032
+ /**
2033
+ * **反驳回到被引用的条目**:被推翻的判断在 `uses` 里引用过的事实(不是它复检的那条)。
2034
+ * 判断错了不等于它引用的事实错了,所以不问人撤回;但按范围比一次:检验落在事实范围之外 ⇒
2035
+ * 记一处边界(`fact/bounded`);范围之内或说不清 ⇒ 事实回到「待核验」(`fact/questioned`)。
2036
+ */
2037
+ const handled = new Set(pending.map((fact) => fact.id))
2038
+ for (const refuter of state.hypotheses.filter((item) => refutedHypotheses.includes(item.id) && Array.isArray(item.uses))) {
2039
+ for (const use of refuter.uses) {
2040
+ if (use?.kind !== 'fact' || handled.has(use.id)) continue
2041
+ handled.add(use.id)
2042
+ const fact = findFact(sessionId, state, use.id)
2043
+ if (fact === null || fact.review?.decision === 'retracted') continue
2044
+ const fit = compareScope(fact.scope_spec ?? null, mergeScope(refuter.scope, { conditions: state.goal?.conditions ?? {} }))
2045
+ const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2046
+ if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2047
+ mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter.id, basis: clip(basis, 300) })
2048
+ markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2049
+ notes.push(tr(`${fact.id}(被引用):推翻落在它的范围之外(${where}),事实保持成立,这处边界已记下`, `${fact.id} (cited): the refutation fell outside its scope (${where}); the fact still holds, and this boundary is recorded`))
2050
+ continue
2051
+ }
2052
+ mutations.push({ t: 'fact/questioned', fact: fact.id, hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2053
+ markFactQuestioned(sessionCwd(sessionId), fact, { hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2054
+ notes.push(tr(`${fact.id}(被引用):引用它的判断被推翻(${where}),它回到待核验;要继续用它,先复检(retests)`, `${fact.id} (cited): a judgment that relied on it was refuted (${where}); it is back to pending re-check. Re-test it (retests) before relying on it again`))
2055
+ }
2056
+ }
2057
+ if (open.length === 0) return notes.length === 0 ? '' : tr(`\n复核:${notes.join(';')}`, `\nReview: ${notes.join('; ')}`)
1935
2058
  for (const fact of open) {
2059
+ /**
2060
+ * **先比范围,再谈撤回**:推翻它的那条判断是在什么条件下检验的(判断自己的范围,缺的维度取立题的
2061
+ * conditions)。检验落在这条事实的适用范围之外,说明「换了范围不成立」,不是「被推翻」:
2062
+ * 事实保持成立,只记下这处边界,不去问人撤回。0.5.1 里九月数据撤回八月事实就是缺了这一步。
2063
+ */
2064
+ const refuter = state.hypotheses.find((item) => refutedHypotheses.includes(item.id) && (item.retests === fact.id || item.id === fact.hypothesis)) ?? null
2065
+ const tested = mergeScope(refuter?.scope, { conditions: state.goal?.conditions ?? {} })
2066
+ const fit = compareScope(fact.scope_spec ?? null, tested)
2067
+ if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2068
+ const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2069
+ mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter?.id ?? null, basis: clip(basis, 300) })
2070
+ markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2071
+ notes.push(tr(`${fact.id}:推翻它的检验${where},事实在原范围内保持成立,这处边界已记下`, `${fact.id}: the refuting test was ${where}; the fact still holds within its scope, and this boundary is recorded`))
2072
+ continue
2073
+ }
2074
+ const scopeNote =
2075
+ fit.verdict === 'undeclared'
2076
+ ? tr(`(注意:${scopeVerdictText(fit, 'zh')},无法确定本次证据是否落在它的适用范围内)`, ` (Note: ${scopeVerdictText(fit, 'en')}, so it is unclear whether this evidence falls within its scope.)`)
2077
+ : fit.verdict === 'unscoped'
2078
+ ? tr('(这条事实没有声明适用范围)', ' (This fact has no declared scope.)')
2079
+ : ''
1936
2080
  const asked = await askHuman(exec, {
1937
2081
  id: `fact-${fact.id}`,
1938
- header: tr('已确立的结论被推翻了', 'An established conclusion was refuted'),
1939
- question: tr(`「${clip(fact.text, 120)}」出现了推翻证据:${clip(basis, 200)}。撤回它,还是判这次证据不可靠、维持原事实?`, `Refuting evidence arrived for "${clip(fact.text, 120)}": ${clip(basis, 200)}. Retract it, or judge this evidence unreliable and keep the fact?`),
2082
+ header: tr('已确立的结论出现推翻证据', 'An established conclusion was refuted'),
2083
+ question: tr(`「${clip(fact.text, 120)}」出现推翻证据:${clip(basis, 200)}。${scopeNote}请选择撤回此事实,或判定本次证据不可靠并维持原事实。`, `Refuting evidence arrived for "${clip(fact.text, 120)}": ${clip(basis, 200)}.${scopeNote} Retract it, or judge this evidence unreliable and keep the fact?`),
1940
2084
  options: [
1941
2085
  { label: choiceLabel('factRetract'), description: tr('它不再算已确立的结论(记录保留)。', 'It no longer counts as an established conclusion (the record stays).') },
1942
2086
  { label: choiceLabel('factKeep'), description: tr('这次证据不可靠,事实保留;推翻证据照样留在账上。', 'This evidence is unreliable and the fact stays; the refuting evidence stays on record too.') },
@@ -2005,25 +2149,27 @@ export function apply(ctx, config = {}) {
2005
2149
  [
2006
2150
  '# 本体内容(已确立条目,可作为「已知」引用;未结构化的旧条目照旧在架)',
2007
2151
  '',
2008
- '> 每条都带**边界**(推翻条件)与**支持等级**:引用它之前先看边界还在不在。',
2152
+ '> 每条都带**适用范围**、**推翻条件**与**支持等级**:引用之前先看这次的情形是否在它的适用范围内。',
2009
2153
  '> 这一份由系统维护(做的人不能写 `clear/knowledge/facts`);新的在前。',
2010
2154
  '',
2011
2155
  ],
2012
2156
  [
2013
2157
  '# Established knowledge (entries you can cite as known; older unstructured entries stay listed)',
2014
2158
  '',
2015
- '> Each entry carries its **boundary** (refutation condition) and **support level**: check the boundary still holds before citing it.',
2159
+ '> Each entry carries its **scope**, **refutation condition** and **support level**: before citing it, check that this situation is within its scope.',
2016
2160
  '> This file is maintained by the system (the worker cannot write `clear/knowledge/facts`); newest first.',
2017
2161
  '',
2018
2162
  ],
2019
2163
  )
2020
2164
  for (const fact of [...facts].reverse()) {
2021
- const scope = fact.scope === null || fact.scope === undefined || String(fact.scope).trim() === '' ? tr('(未写——引用前请谨慎)', '(not written; cite with care)') : String(fact.scope)
2165
+ const scope = tr(scopeText(fact.scope_spec, 'zh'), scopeText(fact.scope_spec, 'en')) || String(fact.scope ?? '').trim() || tr('范围未声明(引用前请谨慎)', 'scope not declared (cite with care)')
2022
2166
  const evidence = listOf(fact.evidence ?? []) || tr('(无)', '(none)')
2023
2167
  const at = fact.at === undefined || fact.at === null ? '—' : new Date(fact.at).toISOString()
2024
2168
  lines.push(`## ${fact.id} · ${fact.text}`)
2025
2169
  lines.push('')
2026
- lines.push(tr(`- 边界:${scope}`, `- Boundary: ${scope}`))
2170
+ lines.push(tr(`- 适用范围:${scope}`, `- Scope: ${scope}`))
2171
+ if (typeof fact.refute_when === 'string' && fact.refute_when !== '') lines.push(tr(`- 推翻条件:${fact.refute_when}`, `- Refuted if: ${fact.refute_when}`))
2172
+ for (const bound of Array.isArray(fact.boundaries) ? fact.boundaries : []) lines.push(tr(`- 已知不适用:${scopeVerdictText(bound, 'zh')}`, `- Known not to apply: ${scopeVerdictText(bound, 'en')}`))
2027
2173
  lines.push(tr(`- 支持到:${fact.level ?? '(未记等级)'} · 证据:${evidence}`, `- Supported to: ${fact.level ?? '(no level recorded)'} · evidence: ${evidence}`))
2028
2174
  lines.push(tr(`- 来源目标:${fact.goal ?? '—'} · 升格时间:${at}`, `- From goal: ${fact.goal ?? '—'} · promoted at: ${at}`))
2029
2175
  /**
@@ -2055,8 +2201,15 @@ export function apply(ctx, config = {}) {
2055
2201
 
2056
2202
  const FACTS_REL = ['clear', 'knowledge', 'facts']
2057
2203
  const LESSONS_REL = ['clear', 'knowledge', 'lessons']
2204
+ /** 负向条目(已排除、未解、缺陷):系统随发生随写,见 `writeBack`。 */
2205
+ const NEGATIVES_REL = ['clear', 'knowledge', 'negatives']
2058
2206
  /** 经验的四类(与 `domain-language.js` 的 `LESSON_KINDS` 同值):坑、要先核的、会骗人的捷径、先验。 */
2059
2207
  const LESSON_KINDS = ['trap', 'check', 'shortcut', 'prior']
2208
+ /** 工作方式(与 `fold.js` 读的同值):广度调研 / 定向求解 / 先调研后求解。 */
2209
+ const FRAME_MODES = ['survey', 'solve', 'survey_then_solve']
2210
+ /** 问题的三种状态(与 `fold.js` 同值):在回答 / 新发现待决定 / 暂缓。 */
2211
+ const QUESTION_STATUS = ['open', 'emergent', 'parked']
2212
+
2060
2213
  const ONTOLOGY_REL = ['clear', 'ontology']
2061
2214
  const ONTOLOGY_BRANCH_DIRS = ['concepts', 'relations', 'entities']
2062
2215
  /** 读面有界(与 `domain-language.js` 的 `WORKSPACE_LIMITS` 同值):超出的如实报成读不成,不静默截断。 */
@@ -2085,6 +2238,7 @@ export function apply(ctx, config = {}) {
2085
2238
  }
2086
2239
  walk(FACTS_REL, false)
2087
2240
  walk(LESSONS_REL, false)
2241
+ walk(NEGATIVES_REL, false)
2088
2242
  for (const branch of ONTOLOGY_BRANCH_DIRS) walk([...ONTOLOGY_REL, branch], true)
2089
2243
  return out
2090
2244
  }
@@ -2099,12 +2253,12 @@ export function apply(ctx, config = {}) {
2099
2253
  return null
2100
2254
  }
2101
2255
  const cached = workspaceReads.get(file)
2102
- if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.change
2103
- let change
2256
+ let change
2104
2257
  if (stat.size > WORKSPACE_MAX_BYTES) change = { path, digest: `size:${stat.size}:${stat.mtimeMs}`, error: tr(`文件太大(${stat.size} 字节,上限 ${WORKSPACE_MAX_BYTES})`, `File too large (${stat.size} bytes, limit ${WORKSPACE_MAX_BYTES})`) }
2105
2258
  else {
2106
2259
  const raw = readFileSync(file, 'utf8')
2107
- const digest = createHash('sha1').update(raw).digest('hex').slice(0, 16)
2260
+ const digest = contentDigest(raw)
2261
+ if (cached?.change?.digest === digest) return cached.change
2108
2262
  try {
2109
2263
  change = { path, digest, data: JSON.parse(raw) }
2110
2264
  } catch (error) {
@@ -2204,6 +2358,9 @@ export function apply(ctx, config = {}) {
2204
2358
  for (const hypothesis of hypotheses) {
2205
2359
  lines.push(`- \`${hypothesis.id}\` [${hypothesis.status}] ${hypothesis.claim}`)
2206
2360
  lines.push(tr(` - 推翻条件:${hypothesis.refute_when}`, ` - Refuted if: ${hypothesis.refute_when}`))
2361
+ lines.push(` - scope: ${JSON.stringify(mergeScope(hypothesis.scope, { conditions: goal.conditions ?? {} }))}`)
2362
+ lines.push(` - uses (framing declarations): ${JSON.stringify(hypothesis.uses ?? [])}`)
2363
+ if (hypothesis.retests) lines.push(` - retests: ${hypothesis.retests}`)
2207
2364
  if (Array.isArray(hypothesis.assertions) && hypothesis.assertions.length > 0) lines.push(tr(` - 断言:${hypothesis.assertions.length} 条`, ` - Assertions: ${hypothesis.assertions.length}`))
2208
2365
  }
2209
2366
  if (history.length > 0) {
@@ -2345,6 +2502,25 @@ export function apply(ctx, config = {}) {
2345
2502
  * 而工具自己的 `mutations` 是这一拍的结算。两者同形、同一个折法,
2346
2503
  * 所以并起来交给宿主不会多一条通道,只是让"事实比工具结果活得更久"。
2347
2504
  */
2505
+ /**
2506
+ * 工具结果出去之前,把这一拍的变更折一遍、写负向条目:这一拍之后会话若就此中断,条目也已在盘上。
2507
+ * 写不出来不影响工具结果。
2508
+ */
2509
+ function afterTool(exec, value) {
2510
+ const mutations = Array.isArray(value?.mutations) ? value.mutations : []
2511
+ if (mutations.length === 0) return value
2512
+ try {
2513
+ const sessionId = String(exec?.agent?.id ?? 'unknown')
2514
+ const hostService = host()
2515
+ if (hostService === undefined) return value
2516
+ const preview = previewOf(hostService, sessionId, mutations)
2517
+ if (preview !== null) writeBack(sessionId, preview.state, preview.derived ?? null)
2518
+ } catch (error) {
2519
+ ctx.logger?.warn?.(`clearai kernel: 负向条目回写失败 ${String(error?.message ?? error).slice(0, 160)}`)
2520
+ }
2521
+ return value
2522
+ }
2523
+
2348
2524
  function withPendingFacts(exec, value) {
2349
2525
  const sessionId = String(exec?.agent?.id ?? 'unknown')
2350
2526
  const pending = drainPendingFacts(sessionId)
@@ -2368,61 +2544,216 @@ export function apply(ctx, config = {}) {
2368
2544
  return { ...value, mutations: merged }
2369
2545
  }
2370
2546
 
2547
+ // ── 取用:立题时定位已有条目,引用时判定是否适用 ─────────────────────────
2548
+
2549
+ /** 工作区里的已有条目(事实、经验、负向条目)摊成一张表:`{id, kind, status, about, scope_spec, path, …}`。 */
2550
+ function knowledgeRows(derived) {
2551
+ const facts = (derived?.factRows ?? []).map((row) => ({ ...row, kind: 'fact', status: row.review?.decision === 'retracted' ? 'retracted' : row.refuted === true && row.review === null ? 'pending' : (row.questioned ?? []).length > 0 ? 'pending' : 'established', path: row.path ?? `clear/knowledge/facts/${row.id}.json` }))
2552
+ const lessons = (derived?.lessonRows ?? []).map((row) => ({ ...row, kind: 'lesson', status: 'active', path: row.path ?? `clear/knowledge/lessons/${row.id}.json` }))
2553
+ const negatives = (derived?.negativeRows ?? []).map((row) => ({ ...row, kind: 'negative' }))
2554
+ return [...facts, ...lessons, ...negatives]
2555
+ }
2556
+
2557
+ const ROW_STATUS_TEXT = {
2558
+ 'fact:established': ['成立', 'holding'],
2559
+ 'fact:pending': ['待核验', 'pending re-check'],
2560
+ 'fact:retracted': ['已撤回', 'retracted'],
2561
+ 'lesson:active': ['经验', 'lessons'],
2562
+ 'negative:excluded': ['已排除', 'excluded'],
2563
+ 'negative:preliminary_excluded': ['初步排除', 'preliminarily excluded'],
2564
+ 'negative:unresolved': ['未解', 'unresolved'],
2565
+ 'negative:defect': ['缺陷', 'defects'],
2566
+ 'negative:explained': ['已解释的反常', 'explained anomalies'],
2567
+ 'negative:ruled_out': ['排除的反常', 'ruled-out anomalies'],
2568
+ 'negative:escalated': ['交给人的反常', 'escalated anomalies'],
2569
+ }
2570
+
2571
+ /** 引用判定 → 一句话(含该怎么办)。 */
2572
+ function citeText(verdict) {
2573
+ switch (verdict.verdict) {
2574
+ case 'unknown':
2575
+ return tr('未找到', 'not found')
2576
+ case 'retracted':
2577
+ return tr('已撤回,不能作为已知引用', 'retracted; do not cite it as known')
2578
+ case 'definition_changed':
2579
+ return tr(`口径已变(${verdict.reasons.map((item) => item.key).join('、')} 的定义改过):先按新口径复核`, `definition changed (${verdict.reasons.map((item) => item.key).join(', ')}): re-check it under the new definition first`)
2580
+ case 'pending':
2581
+ if (verdict.drift !== undefined) return tr(`待核验:它的核算 ${verdict.drift.model} 用新数据重跑,结果超出容差(${deviationText(verdict.drift.deviations, 'zh')}),已登记未解释项;先复检(retests)再用`, `pending re-check: its computation ${verdict.drift.model} re-ran on new data outside tolerance (${deviationText(verdict.drift.deviations, 'en')}); an unexplained item was recorded; re-test it (retests) before relying on it`)
2582
+ return tr('待核验(有推翻证据或开着的疑问):先复检(retests)再用', 'pending re-check (refuting evidence or an open question): re-test it (retests) before relying on it')
2583
+ case 'out_of_scope':
2584
+ case 'out_of_range':
2585
+ return tr(`${scopeVerdictText(verdict, 'zh')}:先检验再用`, `${scopeVerdictText(verdict, 'en')}: test it before relying on it`)
2586
+ case 'undeclared':
2587
+ return tr(`${scopeVerdictText(verdict, 'zh')}:在立题的 conditions 或判断的 scope 里写明这些维度`, `${scopeVerdictText(verdict, 'en')}: state these in the framing conditions or the judgment's scope`)
2588
+ default:
2589
+ return tr(scopeVerdictText(verdict, 'zh'), scopeVerdictText(verdict, 'en'))
2590
+ }
2591
+ }
2592
+
2593
+ /** 核算重跑的结果(没偏差、或没能跑)附在判定后面;没跑(输入没变)不说。 */
2594
+ function runText(run, lang) {
2595
+ if (run === undefined || run === null) return ''
2596
+ const zh = lang === 'zh'
2597
+ switch (run.status) {
2598
+ case 'rerun':
2599
+ return run.against === 'none' ? (zh ? `;核算 ${run.model} 已用新数据重跑,结果记为之后比对的基准` : `; computation ${run.model} re-ran on new data and the result is kept as the reference`) : zh ? `;核算 ${run.model} 已用新数据重跑,结果在容差内` : `; computation ${run.model} re-ran on new data within tolerance`
2600
+ case 'failed':
2601
+ return zh ? `;核算 ${run.model} 复检未完成(${run.detail}),保持待核验` : `; computation ${run.model} re-check incomplete (${run.detail}); remains pending`
2602
+ case 'unavailable':
2603
+ return zh ? `;这个宿主不能执行命令,核算 ${run.model} 没有重跑` : `; this host cannot run commands, so computation ${run.model} was not re-run`
2604
+ case 'invalid':
2605
+ return zh ? `;核算登记 clear/models/${run.model}.json 不合格(${run.detail}),没有重跑` : `; the registration clear/models/${run.model}.json is not usable (${run.detail}); not re-run`
2606
+ case 'missing':
2607
+ return zh ? `;条目挂的核算 ${run.model} 找不到登记文件,没有重跑` : `; the computation ${run.model} named by the item has no registration file; not re-run`
2608
+ default:
2609
+ return ''
2610
+ }
2611
+ }
2612
+
2613
+ /** 负向条目被引用时,先说它是什么。 */
2614
+ function negativeLead(row) {
2615
+ if (row?.kind !== 'negative') return ''
2616
+ const word = ROW_STATUS_TEXT[`negative:${row.status}`]
2617
+ const strength = row.status === 'preliminary_excluded' ? tr('(依据较弱,可以重验)', ' (weak grounds; may be re-tested)') : ''
2618
+ return word === undefined ? '' : tr(`${word[0]}${strength};`, `${word[1]}${strength}; `)
2619
+ }
2620
+
2621
+ /**
2622
+ * 立题时关于已有知识的那几句:相关条目的计数与位置(不给内容)、`about` 里可能指同一实体的名字、
2623
+ * 每条判断 `uses` 的适用性判定。都是读数,不拦立题。
2624
+ */
2625
+ function frameKnowledgeNote({ about, resolved, related, cites, rows }) {
2626
+ const lines = []
2627
+ if (about.length > 0) {
2628
+ if (related.total === 0) lines.push(tr(`工作区里没有与 about(${about.join('、')})相关的已有条目。`, `No existing items in the workspace concern the about ids (${about.join(', ')}).`))
2629
+ else {
2630
+ const parts = Object.entries(related.counts).map(([bucket, count]) => {
2631
+ const word = ROW_STATUS_TEXT[bucket] ?? [bucket, bucket]
2632
+ return tr(`${word[0]} ${count}`, `${count} ${word[1]}`)
2633
+ })
2634
+ lines.push(
2635
+ tr(
2636
+ `工作区里与 about(${about.join('、')})相关的已有条目 ${related.total} 条(${parts.join('、')}),位于 ${related.dirs.join('、')}。先查找读过再定判断;用到的写进判断的 uses,系统会判定它是否适用。`,
2637
+ `${related.total} existing item(s) in the workspace concern the about ids (${about.join(', ')}): ${parts.join(', ')}, under ${related.dirs.join(', ')}. Look them up before settling the judgments; list those you rely on in the judgment's uses, and the system checks whether they apply.`,
2638
+ ),
2639
+ )
2640
+ }
2641
+ } else if (rows.length > 0) {
2642
+ lines.push(tr(`工作区里有 ${rows.length} 条已有条目;立题写上 about(涉及的实体或量),才能定位相关的。`, `The workspace holds ${rows.length} existing item(s); give about (the entities or quantities involved) to locate the relevant ones.`))
2643
+ }
2644
+ for (const item of resolved) {
2645
+ if (item.match !== null && item.match !== item.name) lines.push(tr(`about 中「${item.name}」已认作实体 ${item.match}(名称或别名相同)。`, `"${item.name}" in about was taken as entity ${item.match} (same name or alias).`))
2646
+ else if (item.match === null && item.similar.length > 0) lines.push(tr(`about 中「${item.name}」可能与已有的 ${item.similar.join('、')} 相同:是同一个就改用它的 id 并把这个叫法加进它的 aliases,不是就另建。`, `"${item.name}" in about may be the same as existing ${item.similar.join(', ')}: if so, use its id and add this name to its aliases; if not, create a new one.`))
2647
+ }
2648
+ for (const cite of cites) lines.push(tr(`「${cite.handle}」引用 ${cite.id}:${cite.lead}${citeText(cite.verdict)}${runText(cite.verdict.run, 'zh')}。`, `"${cite.handle}" uses ${cite.id}: ${cite.lead}${citeText(cite.verdict)}${runText(cite.verdict.run, 'en')}.`))
2649
+ return lines.length === 0 ? '' : `\n${lines.join('\n')}`
2650
+ }
2651
+
2371
2652
  // ── Frame ────────────────────────────────────────────────────────────
2372
2653
 
2373
2654
  defineTool({
2374
2655
  name: 'Frame',
2375
2656
  description:
2376
- '立约或修订:往当前原生 goal 上挂一份「怎样算回答了」的判据(done_criteria)与候选判断(每条一句话主张 + 一句「什么结果会推翻它」)。没有原生 goal 时会建一个,目标那一句话(headline)就是它的说法;续跑、暂停由原生 goal 管。修订必须带 reason,版本 +1,旧值全部留痕;改判据文本要带一份独立裁决。不可逆的动作写进 irreversible(匹配的命令执行前要人放行)。同一时间只开一个目标;它跨计划存在,一张 Plan 只承载它的一个阶段。',
2657
+ '立题或修订目标:判据(done_criteria)与候选判断(一句主张 + 推翻条件)。修订须带 reason,旧值留痕;改判据文本须带独立裁决(criteria_verdict)。同一时间只开一个目标。',
2377
2658
  parameters: {
2378
2659
  type: 'object',
2379
2660
  properties: {
2380
- headline: { type: 'string', maxLength: 120, description: '一句话目标(≤120 字):卡上 / 面板 / 续跑文案反复出现的那一句。首次立约必填' },
2381
- claim: { type: 'string', description: '目标:项目要回答的问题(可以长;身份与判据的落点)' },
2382
- done_criteria: { type: 'string', description: '怎样算回答了——必须是可核对的判据,至少含一处能清点的形态(数字 / 条数 / "存在一份文件")' },
2383
- legacy: { type: 'boolean', description: '旧会话迁移:一次性放行长文本与缺 headline(新目标不要用)' },
2661
+ headline: { type: 'string', maxLength: 120, description: '一句话目标(≤120 字),首次立题必填' },
2662
+ claim: { type: 'string', description: '目标要回答的问题' },
2663
+ done_criteria: { type: 'string', description: '怎样算回答了:可核对,至少一处能清点(数字、条数、存在某文件)' },
2664
+ legacy: { type: 'boolean', description: '仅旧会话迁移用' },
2384
2665
  criteria: {
2385
2666
  type: 'array',
2386
2667
  items: { type: 'string' },
2387
- description: '判据逐条写(每条一句话,含可清点数或"存在一份文件"这类能核的形态)。给了它就按条记,不给则用 done_criteria 的全文',
2668
+ description: '可选:判据逐条写;不给就用 done_criteria 全文',
2388
2669
  },
2389
- criteria_note: { type: 'string', description: '判据的背景说明(不参与判定,只解释为什么这么定)' },
2670
+ criteria_note: { type: 'string', description: '判据的背景说明,不参与判定' },
2390
2671
  criteria_verdict: {
2391
2672
  type: 'string',
2392
- description: '改判据文本时要带的独立裁决 auditKey:改「怎样算完成」不能被顺手做掉',
2673
+ description: '改判据文本时的独立裁决 auditKey',
2393
2674
  },
2394
2675
  promote_at_level: { type: 'string', enum: MODEL_LEVELS, description: '升格门槛(默认 L3)' },
2395
2676
  irreversible: {
2396
2677
  type: 'array',
2397
- description: '不可逆的动作:做了就收不回、或结果不可重复的那几件(跑中试、下单、发出去的消息……)。每件写一句说明和它的命令特征(命令里一定会出现的一段原文)。匹配的命令执行前要人放行。修订目标时不传 = 不变',
2678
+ description: '计划实际执行的不可撤销或不可重复动作;匹配的命令执行前须人批准。禁止事项、判据与只读检查不填这里;没有这类动作写 []。修订时不传 = 不变',
2398
2679
  items: {
2399
2680
  type: 'object',
2400
2681
  properties: {
2401
- action: { type: 'string', description: '一句话:这是什么动作' },
2402
- command: { type: 'string', description: '命令特征:这类命令里一定出现的一段原文(如 "reactor.mjs state.json pilot")' },
2682
+ action: { type: 'string', description: '这是什么动作' },
2683
+ command: { type: 'string', description: '能区分该动作的命令原文(含操作及参数);不要仅用目录路径或通用解释器名,以免误拦只读检查' },
2403
2684
  },
2404
2685
  required: ['action', 'command'],
2405
2686
  additionalProperties: false,
2406
2687
  },
2407
2688
  },
2689
+ mode: { type: 'string', enum: FRAME_MODES, description: 'survey 广度调研;solve 定向求解;survey_then_solve 先调研后求解' },
2690
+ questions: {
2691
+ type: 'array',
2692
+ description: '可选:要回答的问题。调研中新发现的写 status="emergent",人决定后改 open 或 parked。修订时传了就是完整清单',
2693
+ items: {
2694
+ type: 'object',
2695
+ properties: {
2696
+ id: { type: 'string', description: '短 id(如 q1)' },
2697
+ text: { type: 'string', description: '一句话问题' },
2698
+ status: { type: 'string', enum: QUESTION_STATUS, description: 'open 在回答;emergent 待决定;parked 暂缓' },
2699
+ area: { type: 'string', description: '可选:所属调研板块 id' },
2700
+ },
2701
+ required: ['id', 'text'],
2702
+ additionalProperties: false,
2703
+ },
2704
+ },
2705
+ about: {
2706
+ type: 'array',
2707
+ items: { type: 'string' },
2708
+ description: '涉及的实体或量的 id(如 "R-2"、"yield"):据此定位已有条目,留下的条目也挂在这里',
2709
+ },
2710
+ conditions: {
2711
+ type: 'object',
2712
+ additionalProperties: { type: 'string' },
2713
+ description: '本次所处的条件,如 {"产线": "L2", "月份": "2026-09"};判断范围的缺省,也是引用判定的依据',
2714
+ },
2715
+ areas: {
2716
+ type: 'array',
2717
+ description: '调研板块(广度调研用)',
2718
+ items: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: ['id', 'name'], additionalProperties: false },
2719
+ },
2720
+ ontology: {
2721
+ type: 'object',
2722
+ description: '可选:本体条目,校验后写进 clear/ontology/(字段见 SCHEMA.json);同 id 替换',
2723
+ properties: {
2724
+ concepts: { type: 'array', items: { type: 'object' }, description: '{id, label, gloss, kind: category|measure|phenomenon, unit?}' },
2725
+ relations: { type: 'array', items: { type: 'object' }, description: '{id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape?, check?}' },
2726
+ },
2727
+ additionalProperties: false,
2728
+ },
2408
2729
  hypotheses: {
2409
2730
  type: 'array',
2410
2731
  description:
2411
- '候选假设:每条一句话主张 + 一句推翻条件,一条只说一件事(「A,且 B」拆成两条);可带**类型化断言**(可选,提供即严校:谓词与概念必须已登记、宾语形态要合值域、同一事实里不许自相矛盾)。不写断言照旧成立——断言是加法,不是门槛。修订目标时不传这一项 = 判断不变;传了就是这一版的完整清单,没列出的会记成「已替换」。',
2732
+ '候选判断,一条只说一件事。修订时不传 = 不变;传了就是完整清单,没列出的记成已替换',
2412
2733
  items: {
2413
2734
  type: 'object',
2414
2735
  properties: {
2415
- name: { type: 'string', description: '短名,十二个汉字或二十来个字母以内,你自己起(如「python3 能跑」)。之后说起这条判断、在别的工具里引用它,都用这个名字' },
2736
+ name: { type: 'string', description: '短名(≤12 字),之后用它引用这条判断' },
2416
2737
  claim: { type: 'string' },
2738
+ question: { type: 'string', description: '可选:所属问题或板块 id' },
2417
2739
  refute_when: { type: 'string' },
2740
+ about: { type: 'array', items: { type: 'string' }, description: '可选:涉及的实体或量 id;缺省取立题的 about' },
2741
+ uses: { type: 'array', items: { type: 'string' }, description: '可选:用到的已有条目 id(clear/knowledge/ 下的文件名);系统当场判定是否适用' },
2742
+ use: { type: 'string', description: '可选:支撑它的可重跑核算 id,先写 clear/models/<id>.json(command、inputs、output、tolerance,可选 baseline);输入或方法变了,引用时系统重跑;偏差与失败保持待核验' },
2743
+ scope: {
2744
+ type: 'object',
2745
+ description: '可选:在哪里成立。conditions 写条件,ranges 写取值范围(如 {"温度": [150, 175]}),units 写单位(如 {"温度":"°C"}),note 补一句;缺省取立题的 conditions',
2746
+ properties: { conditions: { type: 'object' }, ranges: { type: 'object' }, units: { type: 'object' }, note: { type: 'string' } },
2747
+ additionalProperties: false,
2748
+ },
2418
2749
  retests: {
2419
2750
  type: 'string',
2420
2751
  description:
2421
- '这条判断在复检哪条已写进长期知识的事实:写那条事实的 id(clear/knowledge/facts/<id>.json 的文件名)。claim 照抄那条事实原来的说法、拿新数据再验一遍,不要写成「它被推翻了」:这条判断被推翻,系统才会当场问人撤回还是维持那条事实——别的会话留下的事实也一样',
2752
+ '可选:复检哪条已有事实(事实 id)。claim 照抄原说法;被推翻时系统会问人撤回还是维持',
2422
2753
  },
2423
2754
  assertions: {
2424
2755
  type: 'array',
2425
- description: '断言:主词–谓词–宾语(引用领域词汇里的 id)',
2756
+ description: '可选:主词–谓词–宾语断言(引用本体 id),提供即严校',
2426
2757
  items: {
2427
2758
  type: 'object',
2428
2759
  properties: {
@@ -2445,7 +2776,7 @@ export function apply(ctx, config = {}) {
2445
2776
  additionalProperties: false,
2446
2777
  },
2447
2778
  },
2448
- reason: { type: 'string', description: '修订目标时必须写一句原因(首次立目标不需要)' },
2779
+ reason: { type: 'string', description: '修订时必填:改了什么、为什么' },
2449
2780
  },
2450
2781
  required: ['claim', 'done_criteria'],
2451
2782
  additionalProperties: false,
@@ -2458,7 +2789,7 @@ export function apply(ctx, config = {}) {
2458
2789
  const done = finish(hostService, sessionId, mutations)
2459
2790
  const criteria = String(args.done_criteria ?? '').trim()
2460
2791
  if (criteria.length < 4) return fail('done_criteria_required', tr('判据不能为空:目标是「项目要回答的问题」,判据是「怎样算回答了」。', 'Criteria cannot be empty: the goal is the question the project answers; the criteria say what counts as answered.'))
2461
- const selfRef = SELF_REFERENCE.find(([pattern]) => pattern.test(criteria))
2792
+ const selfRef = SELF_REFERENCE.find(([pattern]) => [criteria, ...(Array.isArray(args.criteria) ? args.criteria : [])].some(value => pattern.test(String(value))))
2462
2793
  if (selfRef !== undefined) return fail('criteria_self_reference', tr(...selfRef[1]))
2463
2794
  if (typeof args.claim !== 'string' || args.claim.trim() === '') return fail('claim_required', tr('目标要有主张。', 'The goal needs a claim.'))
2464
2795
  // 迁移开关要在假设校验**之前**就有值:下面那条「主体必须可指认」对它放行。
@@ -2476,8 +2807,25 @@ export function apply(ctx, config = {}) {
2476
2807
  : carried
2477
2808
  ? state.hypotheses
2478
2809
  .filter((item) => item.goal === state.goal.id && item.status !== 'superseded')
2479
- .map((item) => ({ claim: item.claim, refute_when: item.refute_when, ...(item.name ? { name: item.name } : {}), ...(item.retests ? { retests: item.retests } : {}), ...(Array.isArray(item.assertions) ? { assertions: item.assertions } : {}) }))
2810
+ .map((item) => ({ claim: item.claim, refute_when: item.refute_when, ...(item.name ? { name: item.name } : {}), ...(item.retests ? { retests: item.retests } : {}), ...(Array.isArray(item.assertions) ? { assertions: item.assertions } : {}), ...(item.question ? { question: item.question } : {}), ...(item.scope ? { scope: item.scope } : {}), ...(Array.isArray(item.about) ? { about: item.about } : {}), ...(Array.isArray(item.uses) ? { uses: item.uses.map((use) => use.id) } : {}) }))
2480
2811
  : []
2812
+ /**
2813
+ * **取用的上下文**:工作区里的已有条目、本体里的实体与概念(按名称与别名对 `about`)、
2814
+ * 这次的条件(引用判定按它比范围)。只读,不拦立题。
2815
+ */
2816
+ let knownRows = []
2817
+ try {
2818
+ knownRows = knowledgeRows(call.derived ?? hostService.derive(sessionId))
2819
+ } catch {
2820
+ knownRows = []
2821
+ }
2822
+ const ontologyEntries = [...(Array.isArray(state.entities) ? state.entities : []), ...(Array.isArray(state.lexicon?.terms) ? state.lexicon.terms : [])]
2823
+ const openGoal = state.goal !== null && state.goal.status === 'open' ? state.goal : null
2824
+ const conditionsNow = normalizeScope({ conditions: args.conditions })?.conditions ?? openGoal?.conditions ?? {}
2825
+ /** 名称或别名完全相同的,直接认作那个实体或概念的 id;相似的只提示。 */
2826
+ const canonicalAbout = (names) => mergeAbout(resolveAbout(names, ontologyEntries).map((item) => item.match ?? item.name))
2827
+ const aboutGiven = Array.isArray(args.about) ? mergeAbout(args.about) : []
2828
+ const goalAbout = Array.isArray(args.about) ? canonicalAbout(args.about) : (openGoal?.about ?? [])
2481
2829
  const names = hypotheses.map((hypothesis) => (typeof hypothesis?.name === 'string' ? hypothesis.name.trim() : '')).filter((name) => name !== '')
2482
2830
  if (new Set(names).size !== names.length) return fail('hypothesis_name_duplicate', tr('两条判断用了同一个短名:短名是用来区分判断的,换一个。', 'Two judgments share a short name; short names tell judgments apart, so pick another.'))
2483
2831
  for (const hypothesis of hypotheses) {
@@ -2487,6 +2835,24 @@ export function apply(ctx, config = {}) {
2487
2835
  if (hypothesis?.retests !== undefined && hypothesis.retests !== null && findFact(sessionId, state, hypothesis.retests) === null) {
2488
2836
  return fail('retests_unknown', tr(`retests 指向的事实「${String(hypothesis.retests).slice(0, 40)}」不在 clear/knowledge/facts/ 里:写那条事实文件名里的 id(如 f-ab12cd),或者去掉 retests。`, `The fact retests points to ("${String(hypothesis.retests).slice(0, 40)}") is not in clear/knowledge/facts/: use the id from that fact's file name (such as f-ab12cd), or drop retests.`))
2489
2837
  }
2838
+ const unknownUses = (Array.isArray(hypothesis?.uses) ? hypothesis.uses : []).map((id) => String(id ?? '').trim()).filter((id) => id !== '' && !knownRows.some((row) => row.id === id))
2839
+ if (unknownUses.length > 0) {
2840
+ return fail('uses_unknown', tr(`uses 里的 ${unknownUses.join('、')} 不在 clear/knowledge/ 的 facts、lessons、negatives 里:写条目文件名里的 id(如 f-ab12cd),或者去掉。`, `${unknownUses.join(', ')} in uses is not among clear/knowledge/ facts, lessons or negatives: use the id from the item's file name (such as f-ab12cd), or drop it.`))
2841
+ }
2842
+ /** `use`:可重跑核算的 id;登记文件要在、要合格,升格时才带得上。 */
2843
+ if (typeof hypothesis?.use === 'string' && hypothesis.use.trim() !== '') {
2844
+ const modelId = hypothesis.use.trim()
2845
+ const cwd = sessionCwd(sessionId)
2846
+ let spec = null
2847
+ try {
2848
+ spec = cwd === null || !MODEL_ID.test(modelId) ? null : JSON.parse(readFileSync(join(cwd, 'clear', 'models', `${modelId}.json`), 'utf8'))
2849
+ } catch {
2850
+ spec = null
2851
+ }
2852
+ if (spec === null) return fail('use_unknown', tr(`use 指向的核算 ${modelId} 没有登记:先写 clear/models/${modelId}.json(command、inputs、output、tolerance)。`, `The computation ${modelId} named in use is not registered: write clear/models/${modelId}.json first (command, inputs, output, tolerance).`))
2853
+ const problems = checkModelSpec(spec, modelId)
2854
+ if (problems.length > 0) return fail('use_invalid', tr(`clear/models/${modelId}.json 不合格:${problems.join(';')}`, `clear/models/${modelId}.json is not usable: ${problems.join('; ')}`))
2855
+ }
2490
2856
  /**
2491
2857
  * **宽松+校验**:不写断言放行(断言是加法),写了就在**落账之前**严校——
2492
2858
  * 引用不存在的谓词 / 概念、宾语形态不合值域、同一事实自相矛盾,一律当场拒。
@@ -2590,6 +2956,40 @@ export function apply(ctx, config = {}) {
2590
2956
  if (Array.isArray(args.irreversible) && irreversible.length !== args.irreversible.length) {
2591
2957
  return fail('irreversible_invalid', tr('每件不可逆动作都要有一句说明(action)和命令特征(command,至少 3 个字符,是这类命令里一定出现的一段原文)。', 'Each irreversible action needs a one-line description (action) and a command signature (command, at least 3 characters of text that always appears in such a command).'))
2592
2958
  }
2959
+ /**
2960
+ * **问题与板块**:修订时不传 = 不变(与判断同一条纪律)。id 不许重复;判断的 `question`
2961
+ * 要指向这一版里存在的问题或板块,写错了当场说清可选的有哪些。
2962
+ */
2963
+ const questions = Array.isArray(args.questions) ? args.questions.map((item) => ({ id: String(item?.id ?? '').trim(), text: String(item?.text ?? '').trim(), status: QUESTION_STATUS.includes(item?.status) ? item.status : 'open', ...(typeof item?.area === 'string' && item.area.trim() !== '' ? { area: item.area.trim() } : {}) })) : null
2964
+ const areas = Array.isArray(args.areas) ? args.areas.map((item) => ({ id: String(item?.id ?? '').trim(), name: String(item?.name ?? '').trim() })) : null
2965
+ if ((questions ?? []).some((item) => item.id === '' || item.text === '') || (areas ?? []).some((item) => item.id === '' || item.name === '')) return fail('questions_invalid', tr('每个问题要有 id 与一句话(text);每个板块要有 id 与名字(name)。', 'Each question needs an id and one sentence (text); each area needs an id and a name.'))
2966
+ const homeIds = [...(questions ?? (isRevision ? (state.goal.questions ?? []) : [])), ...(areas ?? (isRevision ? (state.goal.areas ?? []) : []))].map((item) => item.id)
2967
+ if (new Set(homeIds).size !== homeIds.length) return fail('questions_duplicate', tr('问题与板块的 id 不能重复。', 'Question and area ids must be unique.'))
2968
+ const strayHome = hypotheses.find((hypothesis) => typeof hypothesis?.question === 'string' && hypothesis.question.trim() !== '' && !homeIds.includes(hypothesis.question.trim()))
2969
+ if (strayHome !== undefined) return fail('question_unknown', tr(`判断「${handleOf(strayHome)}」的 question「${strayHome.question}」不是这一版里的问题或板块。可选:${homeIds.join('、') || '(还没有问题或板块:先在 questions / areas 里写)'}`, `Judgment "${handleOf(strayHome)}" has question "${strayHome.question}", which is not a question or area in this version. Options: ${homeIds.join(', ') || '(none yet: write them in questions / areas first)'}`))
2970
+ /**
2971
+ * **本体随立题写入**(`ontology`):逐个文件用宿主半的 `domain.checkFile` 校验,全部过了才写盘。
2972
+ * 为什么放进 Frame:模型要另写文件时,本体总被排到最后、最后没写;立题时写,预测和候选才有出处。
2973
+ */
2974
+ const ontologyFiles = []
2975
+ for (const [branch, list] of [['concepts', args.ontology?.concepts], ['relations', args.ontology?.relations]]) {
2976
+ for (const item of Array.isArray(list) ? list : []) {
2977
+ const id = String(item?.id ?? '').trim()
2978
+ const rel = `clear/ontology/${branch}/${id}.json`
2979
+ const problems = id === '' ? [tr('要有 id(就是文件名)', 'needs an id (the file name)')] : typeof hostService.domain?.checkFile === 'function' ? hostService.domain.checkFile(rel, item) : []
2980
+ if (problems.length > 0) return fail('ontology_rejected', tr(`本体条目 ${rel} 不能写入:\n${problems.map((line) => `- ${line}`).join('\n')}`, `Ontology entry ${rel} cannot be written:\n${problems.map((line) => `- ${line}`).join('\n')}`))
2981
+ ontologyFiles.push({ branch, id, rel, data: item })
2982
+ }
2983
+ }
2984
+ for (const file of ontologyFiles) {
2985
+ const target = sessionFile(sessionId, 'clear', 'ontology', file.branch, `${file.id}.json`)
2986
+ if (target === null) return fail('workspace_unavailable', tr('这一刻拿不到会话的工作目录,本体条目没有写入。', 'The session workspace is unavailable right now; the ontology entries were not written.'))
2987
+ writeTextFile(target, `${JSON.stringify({ ...file.data, id: file.id }, null, 2)}\n`)
2988
+ }
2989
+ if (ontologyFiles.length > 0) {
2990
+ const synced = syncWorkspace(sessionId, state)
2991
+ if (synced !== null) mutations.push(synced)
2992
+ }
2593
2993
  /**
2594
2994
  * **修订不许给同一句话发新身份。**
2595
2995
  *
@@ -2606,6 +3006,41 @@ export function apply(ctx, config = {}) {
2606
3006
  const claimKey = (text) => String(text ?? '').trim().replace(/\s+/g, ' ')
2607
3007
  const idByClaim = new Map(existing.map((item) => [claimKey(item.claim), item.id]))
2608
3008
  const reused = new Set()
3009
+ /**
3010
+ * **引用时判定是否适用**:判断 `uses` 里的每条已有条目,按条目自己的状态与适用范围
3011
+ * (对这条判断的范围,缺的维度取这次的条件)判一次;判定随判断落账,也随结果说给模型。
3012
+ */
3013
+ const cites = []
3014
+ /**
3015
+ * **引用前先重跑核算**:被引用的事实挂着 `use`(可重跑的核算)且输入变了,先跑一次再判定;
3016
+ * 结果超出容差,这条事实判为待核验,同时登记一条未解释项(反常不依赖模型自己留意)。
3017
+ */
3018
+ const modelRuns = new Map()
3019
+ for (const hypothesis of CFG.applicabilityFeedback ? hypotheses : []) {
3020
+ for (const id of mergeAbout(hypothesis?.uses)) {
3021
+ const row = knownRows.find((item) => item.id === id) ?? null
3022
+ if (['out_of_scope', 'out_of_range'].includes(compareScope(row?.scope_spec, mergeScope(hypothesis.scope, { conditions: conditionsNow })).verdict)) continue
3023
+ if (typeof row?.use === 'string' && row.use !== '' && !modelRuns.has(row.id)) modelRuns.set(row.id, await rerunModel(sessionId, row.use, row, exec))
3024
+ }
3025
+ }
3026
+ const driftOpened = new Set()
3027
+ for (const [factId, run] of modelRuns) {
3028
+ if (run.status !== 'rerun' || run.deviations.length === 0) continue
3029
+ for (const row of knownRows.filter((item) => item.id === factId)) {
3030
+ if (driftOpened.has(row.id)) continue
3031
+ driftOpened.add(row.id)
3032
+ mutations.push({ t: 'anomaly/opened', id: uniqueId('a'), what: tr(`核算 ${run.model} 重跑结果超出容差:${deviationText(run.deviations, 'zh')}`, `Computation ${run.model} re-ran outside tolerance: ${deviationText(run.deviations, 'en')}`), anchor: `clear/evidence/models/${run.model}.json`, touches: [row.id], by: 'system' })
3033
+ }
3034
+ }
3035
+ const usesOf = (hypothesis) =>
3036
+ mergeAbout(hypothesis?.uses).map((id) => {
3037
+ const row = knownRows.find((item) => item.id === id) ?? null
3038
+ const run = typeof row?.use === 'string' ? (modelRuns.get(row.id) ?? null) : null
3039
+ const drifted = run?.pending === true
3040
+ const verdict = !CFG.applicabilityFeedback ? { verdict: 'unchecked', reasons: [] } : drifted ? { verdict: 'pending', reasons: [], ...(run?.deviations?.length ? { drift: run } : { run }) } : { ...citeVerdict(row, mergeScope(hypothesis.scope, { conditions: conditionsNow })), ...(run !== null && run.status !== 'current' ? { run } : {}) }
3041
+ if (!cites.some((cite) => cite.id === id && cite.claim === hypothesis.claim)) cites.push({ id, claim: hypothesis.claim, handle: handleOf({ name: hypothesis.name, claim: hypothesis.claim }), lead: negativeLead(row), verdict })
3042
+ return { id, kind: row?.kind ?? null, verdict: verdict.verdict }
3043
+ })
2609
3044
  const nextHypotheses = hypotheses.map((hypothesis, index) => {
2610
3045
  const claim = hypothesis.claim.trim()
2611
3046
  const carried = idByClaim.get(claimKey(claim))
@@ -2620,8 +3055,15 @@ export function apply(ctx, config = {}) {
2620
3055
  refute_when: hypothesis.refute_when.trim(),
2621
3056
  /** 复检哪条已有事实(跨会话的身份是事实 id;判断 id 只活在本目标里)。 */
2622
3057
  ...(typeof hypothesis.retests === 'string' && hypothesis.retests.trim() !== '' ? { retests: hypothesis.retests.trim() } : {}),
3058
+ /** 可重跑的核算(`clear/models/<id>.json`):升格时随事实写进文件,之后引用时据它重跑。 */
3059
+ ...(typeof hypothesis.use === 'string' && hypothesis.use.trim() !== '' ? { use: hypothesis.use.trim() } : {}),
2623
3060
  /** 断言随假设落账;没写就是 null(加法,不是门槛)。 */
2624
3061
  assertions: Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null,
3062
+ ...(typeof hypothesis.question === 'string' && hypothesis.question.trim() !== '' ? { question: hypothesis.question.trim() } : {}),
3063
+ /** 适用范围(在哪里成立),与推翻条件分开;没写就在升格时取立题的 conditions。 */
3064
+ ...(normalizeScope(hypothesis.scope) !== null ? { scope: normalizeScope(hypothesis.scope) } : {}),
3065
+ ...(canonicalAbout(hypothesis.about).length > 0 ? { about: canonicalAbout(hypothesis.about) } : {}),
3066
+ ...(usesOf(hypothesis).length > 0 ? { uses: usesOf(hypothesis) } : {}),
2625
3067
  version: index + 1,
2626
3068
  }
2627
3069
  })
@@ -2639,6 +3081,11 @@ export function apply(ctx, config = {}) {
2639
3081
  revision,
2640
3082
  reason: isRevision ? String(args.reason).trim() : null,
2641
3083
  hypotheses: nextHypotheses,
3084
+ ...(FRAME_MODES.includes(args.mode) ? { mode: args.mode } : {}),
3085
+ ...(questions !== null ? { questions } : {}),
3086
+ ...(areas !== null ? { areas } : {}),
3087
+ ...(normalizeScope({ conditions: args.conditions }) !== null ? { conditions: normalizeScope({ conditions: args.conditions }).conditions } : {}),
3088
+ ...(Array.isArray(args.about) ? { about: goalAbout } : {}),
2642
3089
  })
2643
3090
  for (const dropped of existing) {
2644
3091
  if (reused.has(dropped.id)) continue
@@ -2650,7 +3097,8 @@ export function apply(ctx, config = {}) {
2650
3097
  ok: true,
2651
3098
  code: isRevision ? 'goal_revised' : 'goal_set',
2652
3099
  message:
2653
- tr(`${isRevision ? `目标已修订(第 ${revision} 版)` : '目标已立'},${carried ? '判断沿用上一版,' : ''}登记了 ${hypotheses.length} 条判断${nextHypotheses.length === 0 ? '' : `:${nextHypotheses.map((item) => `「${handleOf(item)}」`).join('、')}`}。`, `${isRevision ? `Goal revised (version ${revision})` : 'Goal set'}; ${carried ? 'judgments carried over from the last version; ' : ''}${hypotheses.length} judgment(s) registered${nextHypotheses.length === 0 ? '' : `: ${nextHypotheses.map((item) => `"${handleOf(item)}"`).join(', ')}`}.`) +
3100
+ tr(`${isRevision ? `目标已修订(第 ${revision} 版)` : '目标已立'},${carried ? '判断沿用上一版,' : ''}登记了 ${hypotheses.length} 条判断${nextHypotheses.length === 0 ? '' : `:${nextHypotheses.map((item) => `「${handleOf(item)}」`).join('、')}`}。${ontologyFiles.length > 0 ? `写入本体条目 ${ontologyFiles.length} 个。` : ''}`, `${isRevision ? `Goal revised (version ${revision})` : 'Goal set'}; ${carried ? 'judgments carried over from the last version; ' : ''}${hypotheses.length} judgment(s) registered${nextHypotheses.length === 0 ? '' : `: ${nextHypotheses.map((item) => `"${handleOf(item)}"`).join(', ')}`}.${ontologyFiles.length > 0 ? ` ${ontologyFiles.length} ontology entr${ontologyFiles.length === 1 ? 'y' : 'ies'} written.` : ''}`) +
3101
+ frameKnowledgeNote({ about: goalAbout, resolved: resolveAbout(aboutGiven, ontologyEntries), related: relatedKnowledge(knownRows, goalAbout), cites: CFG.applicabilityFeedback ? cites : [], rows: knownRows }) +
2654
3102
  // 原生 goal 上那一句给人看:用目标的一句话,不写 id。
2655
3103
  attachNativeGoal(exec.agent, clip(headline === '' ? String(args.claim ?? '') : headline, 120)),
2656
3104
  })
@@ -2677,6 +3125,81 @@ export function apply(ctx, config = {}) {
2677
3125
  }
2678
3126
 
2679
3127
  /** 交给结案评估者的那一段:待核的经验,编号 L1……,判法写在一起。 */
3128
+ /** 结论四部分的唯一形状:结论 / 依据 / 尚未确定的事项(各写涉及什么、对答案的影响)/ 待您决策。 */
3129
+ function normalizeAnswers(raw) {
3130
+ if (!Array.isArray(raw)) return []
3131
+ const lines = (list, width) => (Array.isArray(list) ? list : []).map((item) => String(item ?? '').trim()).filter((item) => item !== '')
3132
+ return raw
3133
+ .map((item) => ({
3134
+ question: String(item?.question ?? '').trim(),
3135
+ uses: mergeAbout(item?.uses),
3136
+ scope: normalizeScope(item?.scope),
3137
+ conclusion: String(item?.conclusion ?? '').trim(),
3138
+ basis: lines(item?.basis, 300).slice(0, 12),
3139
+ open: (Array.isArray(item?.open) ? item.open : [])
3140
+ .map((entry) => ({ about: lines(entry?.about, 80).slice(0, 8), effect: String(entry?.effect ?? '').trim().slice(0, 300) }))
3141
+ .filter((entry) => entry.effect !== '')
3142
+ .slice(0, 12),
3143
+ decide: lines(item?.decide, 300).slice(0, 6),
3144
+ ...(typeof item?.unanswered === 'string' && item.unanswered.trim() !== '' ? { unanswered: item.unanswered.trim().slice(0, 300) } : {}),
3145
+ }))
3146
+ .filter((item) => item.conclusion !== '' || item.unanswered !== undefined)
3147
+ }
3148
+
3149
+ /**
3150
+ * **停止检查**(`CFG.requireAnswers`,只在 achieved 时):决策稳健了才结案。
3151
+ *
3152
+ * 只查有没有写,不判断写得对不对(与「产物存在且格式正确」同类):
3153
+ * · 每个在回答的问题都有结论,或写明 `unanswered` 的原因;
3154
+ * · 还在考察中、从未得到支持的候选,还开着的未解释项,都要出现在某条结论的
3155
+ * 「尚未确定的事项」里(`open[].about` 写它的 id 或短名),并写明若它成立答案会如何改变。
3156
+ *
3157
+ * 为什么:真跑里漂移被量化、登记成未解释项,答案仍按设定温度交付并以 achieved 结案。
3158
+ * 返回缺项清单(每行一项);齐了返回空数组。
3159
+ */
3160
+ function unsettledForAnswers(state, derived, answers) {
3161
+ const goal = state.goal
3162
+ const exploration = derived?.exploration ?? null
3163
+ const missing = []
3164
+ const declared = (goal.questions ?? []).filter((question) => question.status === 'open')
3165
+ const implicit = (goal.questions ?? []).length === 0 && (goal.areas ?? []).length === 0
3166
+ const answered = (id) => answers.some((answer) => answer.question === id) || (implicit && answers.length > 0)
3167
+ if (implicit && answers.length === 0) missing.push(tr('目标还没有结论:`answers` 至少写一条(结论 / 依据 / 尚未确定的事项 / 待您决策)。', 'The goal has no conclusion yet: write at least one entry in `answers` (conclusion / basis / open points / decisions for the user).'))
3168
+ for (const question of declared) if (!answered(question.id)) missing.push(tr(`问题 ${question.id}「${clip(question.text, 60)}」没有结论:写结论,或用 \`unanswered\` 写明为何未能回答。`, `Question ${question.id} "${clip(question.text, 60)}" has no conclusion: write one, or say why it could not be answered in \`unanswered\`.`))
3169
+ const about = new Set(answers.flatMap((answer) => answer.open.flatMap((entry) => entry.about)))
3170
+ for (const question of exploration?.questions ?? []) {
3171
+ for (const candidate of question.candidates ?? []) {
3172
+ if (candidate.state !== 'examining' || candidate.supportedLevel !== null) continue
3173
+ if (about.has(candidate.id) || about.has(candidate.name)) continue
3174
+ missing.push(tr(`候选假设「${candidate.name}」仍在考察中、未得到支持:写进「尚未确定的事项」(about 写「${candidate.name}」),说明若它成立答案会如何改变;或先检验它。`, `Candidate hypothesis "${candidate.name}" is still being examined and has no support: put it in the open points (about: "${candidate.name}") and say how the answer would change if it holds; or test it first.`))
3175
+ }
3176
+ }
3177
+ for (const anomaly of (state.anomalies ?? []).filter((item) => item?.status === 'open' && !(item.by === 'evaluator' && item.matters === 'no'))) {
3178
+ if (about.has(anomaly.id)) continue
3179
+ missing.push(tr(`未解释项 ${anomaly.id}「${clip(anomaly.what, 60)}」还开着:写进「尚未确定的事项」(about 写 ${anomaly.id}),说明它对答案的影响,或答案已据此改写;也可以先用 Anomaly 给它一个去处。`, `Unexplained item ${anomaly.id} "${clip(anomaly.what, 60)}" is still open: put it in the open points (about: ${anomaly.id}) and say how it affects the answer, or that the answer was rewritten for it; or resolve it first with Anomaly.`))
3180
+ }
3181
+ for (const question of (goal.questions ?? []).filter((item) => item.status === 'emergent' || item.status === 'parked')) {
3182
+ if (about.has(question.id) || answered(question.id)) continue
3183
+ missing.push(tr(`问题 ${question.id}「${clip(question.text, 60)}」${question.status === 'parked' ? '已暂缓' : '待决定'}:写进「尚未确定的事项」(about 写 ${question.id})。`, `Question ${question.id} "${clip(question.text, 60)}" is ${question.status === 'parked' ? 'parked' : 'awaiting a decision'}: put it in the open points (about: ${question.id}).`))
3184
+ }
3185
+ return missing
3186
+ }
3187
+
3188
+ /** 交给结案评估者读的结论四部分(核它与记录是否一致)。 */
3189
+ function answersBrief(answers) {
3190
+ if (answers.length === 0) return []
3191
+ return [
3192
+ tr('# 结论(做的人按问题写的四部分;请核它与记录是否一致,依据是否真在记录里)', '# Conclusions (written by the worker per question; check they match the record and that the basis is really in it)'),
3193
+ ...answers.flatMap((answer) => [
3194
+ `## ${answer.question || tr('目标', 'goal')}:${answer.conclusion || tr(`未回答(${answer.unanswered})`, `unanswered (${answer.unanswered})`)}`,
3195
+ ...(answer.uses.length ? [`- 实际采用 / actual uses: ${answer.uses.join(', ')}; scope: ${JSON.stringify(answer.scope)}`] : []),
3196
+ ...answer.basis.map((line) => tr(`- 依据:${line}`, `- basis: ${line}`)),
3197
+ ...answer.open.map((entry) => tr(`- 尚未确定(${entry.about.join('、') || '—'}):${entry.effect}`, `- open (${entry.about.join(', ') || '—'}): ${entry.effect}`)),
3198
+ ...answer.decide.map((line) => tr(`- 待您决策:${line}`, `- for the user to decide: ${line}`)),
3199
+ ]),
3200
+ ]
3201
+ }
3202
+
2680
3203
  function lessonBrief(lessons) {
2681
3204
  if (lessons.length === 0) return []
2682
3205
  const kindWord = { trap: tr('坑', 'trap'), check: tr('要核的', 'check'), shortcut: tr('会骗人的捷径', 'misleading shortcut'), prior: tr('先验', 'prior') }
@@ -2693,24 +3216,46 @@ export function apply(ctx, config = {}) {
2693
3216
  defineTool({
2694
3217
  name: 'Conclude',
2695
3218
  description:
2696
- '结案:交目标验收——这是完成目标的唯一路径(原生「完成目标」会被拒)。系统**无条件**派独立评估者,拿目标判据与转写忠实度逐条核对;判据达成才结案为 achieved:原生 goal 置为完成;评估者同时逐条判还活着的判断,判为支持的(或中途已达门槛的)升格为事实;各步收下的产物声明为交付卡片;随结案提议的经验(`lessons`)由评估者逐条核,支持的写进 clear/knowledge/lessons/。否则目标保持开放并回注缺口。**顺序**:achieved 之前必须先把计划收尾(`ClosePlan`)。放弃(`abandoned`)不受此限:原生 goal 置为阻塞,写明原因,由人决定结束。',
3219
+ '结案,完成目标的唯一路径。独立评估者逐条核判据:达成才结案为 achieved,它支持的判断升格为事实、支持的经验写入;否则返回缺口。achieved 之前先 ClosePlan;abandoned 写明阻塞,由人决定结束。',
2697
3220
  parameters: {
2698
3221
  type: 'object',
2699
3222
  properties: {
2700
- outcome: { type: 'string', enum: ['achieved', 'abandoned'], description: 'achieved=判据已达成;abandoned=如实说清阻塞后放弃' },
3223
+ outcome: { type: 'string', enum: ['achieved', 'abandoned'], description: 'achieved 判据已达成;abandoned 说清阻塞后放弃' },
2701
3224
  note: { type: 'string', description: '结案说明' },
3225
+ answers: {
3226
+ type: 'array',
3227
+ description: 'achieved 时按问题各写一条。还在考察的候选与开着的未解释项写进 open 并说明影响',
3228
+ items: {
3229
+ type: 'object',
3230
+ properties: {
3231
+ question: { type: 'string', description: '问题 id;目标没列问题时省略' },
3232
+ conclusion: { type: 'string', description: '一两句结论,带数值与适用条件' },
3233
+ uses: { type: 'array', items: { type: 'string' }, description: '最终答案直接使用的知识条目 id,不自动继承立题引用' },
3234
+ scope: { type: 'object', description: '此答案的适用范围,数值范围须带 units' },
3235
+ basis: { type: 'array', items: { type: 'string' }, description: '每个采纳、排除的候选或核验的读数一行,注明来源' },
3236
+ open: {
3237
+ type: 'array',
3238
+ description: '尚未确定的事项:about 写候选短名、未解释项或问题 id,effect 写若它成立结论如何变',
3239
+ items: { type: 'object', properties: { about: { type: 'array', items: { type: 'string' } }, effect: { type: 'string' } }, required: ['effect'], additionalProperties: false },
3240
+ },
3241
+ decide: { type: 'array', items: { type: 'string' }, description: '待人决策的事项' },
3242
+ unanswered: { type: 'string', description: '未能回答的原因(此时可省 conclusion)' },
3243
+ },
3244
+ additionalProperties: false,
3245
+ },
3246
+ },
2702
3247
  lessons: {
2703
3248
  type: 'array',
2704
3249
  maxItems: 5,
2705
- description: '经验(可选,只在 achieved 时核):这次摸出的、下次在同类现场改变做法的东西,不是这次结论的复述。评估者逐条对照记录核,判为支持的写进 clear/knowledge/lessons/,之后的会话在立题和定计划时会看到',
3250
+ description: '可选:下次在同类现场会改变做法的经验,评估者核过才写入',
2706
3251
  items: {
2707
3252
  type: 'object',
2708
3253
  properties: {
2709
- text: { type: 'string', description: '一句话,下次怎么做(「这台装置的温度读数先拿参考温度核一次」)' },
2710
- kind: { type: 'string', enum: LESSON_KINDS, description: 'trap=会踩的坑;check=要先核的读数或假设;shortcut=省事但会骗人的做法;prior=对这类体系的先验(例如「两个因素常常耦合,先做斜向扫描」)' },
2711
- about: { type: 'array', items: { type: 'string' }, description: '涉及的装置、量或概念(短名,用来下次匹配)' },
2712
- evidence: { type: 'string', description: '这次记录里哪处表明了它(步骤、文件)' },
2713
- boundary: { type: 'string', description: '在什么条件下不适用' },
3254
+ text: { type: 'string', description: '一句话,下次怎么做' },
3255
+ kind: { type: 'string', enum: LESSON_KINDS, description: 'trap 坑;check 要先核的;shortcut 会骗人的捷径;prior 先验' },
3256
+ about: { type: 'array', items: { type: 'string' }, description: '涉及的装置、量或概念 id' },
3257
+ evidence: { type: 'string', description: '记录里哪处表明了它' },
3258
+ boundary: { type: 'string', description: '什么条件下不适用' },
2714
3259
  },
2715
3260
  required: ['text', 'kind'],
2716
3261
  additionalProperties: false,
@@ -2808,6 +3353,17 @@ export function apply(ctx, config = {}) {
2808
3353
  )
2809
3354
  }
2810
3355
  }
3356
+ const answers = normalizeAnswers(args.answers)
3357
+ if (CFG.requireAnswers) {
3358
+ const missing = unsettledForAnswers(state, derived, answers)
3359
+ if (missing.length > 0) {
3360
+ return fail(
3361
+ 'answers_incomplete',
3362
+ tr(`结论还不完整,不能以 achieved 结案(只检查是否写了,不判断写得对不对):\n${missing.map((line) => `- ${line}`).join('\n')}\n探索到结论不再改变为止:未排除的可能与未解释的读数,要么检验掉,要么在结论里写明它们的影响。`, `The conclusion is incomplete and cannot close as achieved (this only checks that things are written, not whether they are right):\n${missing.map((line) => `- ${line}`).join('\n')}\nExplore until the conclusion stops changing: possibilities not ruled out and unexplained readings are either tested away or written into the conclusion with their effect.`),
3363
+ { mutations },
3364
+ )
3365
+ }
3366
+ }
2811
3367
  const unfinished = plan === null ? [] : plan.steps.filter((step) => step.status === 'open')
2812
3368
  const syntheticStep = {
2813
3369
  id: `goal:${goal.id}`,
@@ -2817,18 +3373,37 @@ export function apply(ctx, config = {}) {
2817
3373
  artifacts: [],
2818
3374
  tests: candidates.length === 0 ? null : { hypotheses: candidates.map((hypothesis) => hypothesis.id), level: goal.promote_at_level },
2819
3375
  }
3376
+ let finalRows = knowledgeRows(derived)
3377
+ for (const id of new Set(answers.flatMap((answer) => answer.uses))) {
3378
+ const fact = finalRows.find((row) => row.id === id)
3379
+ if (fact?.use && CFG.applicabilityFeedback) {
3380
+ const run = await rerunModel(sessionId, fact.use, fact, exec)
3381
+ if (run.pending && run.persisted === false) return fail('recheck_persist_failed', '引用复核状态未能保存,保持开放', { mutations })
3382
+ }
3383
+ }
3384
+ const finalSync = syncWorkspace(sessionId, state)
3385
+ if (finalSync !== null) mutations.push(finalSync)
3386
+ const finalView = previewOf(hostService, sessionId, mutations)
3387
+ if (finalView !== null) finalRows = knowledgeRows(finalView.derived)
3388
+ const invalidUses = answers.flatMap((answer) => answer.uses.map((id) => ({ id, ...citeVerdict(finalRows.find((row) => row.id === id), mergeScope(answer.scope, { conditions: goal.conditions ?? {} })) }))).filter((cite) => ['unknown', 'retracted', 'definition_changed', 'pending', 'out_of_scope', 'out_of_range'].includes(cite.verdict))
3389
+ if (CFG.applicabilityFeedback && invalidUses.length) return fail('answer_uses_invalid', `最终引用尚不可使用: ${invalidUses.map((cite) => `${cite.id}: ${cite.verdict}`).join('; ')}。复检后再引用;如采用独立新证据,直接列出它,不要声明旧知识已恢复。`, { mutations })
2820
3390
  const proposedLessons = proposedLessonsOf(args.lessons)
2821
3391
  const gate = {
2822
3392
  confirmed: [
2823
3393
  ...state.evidence.map((item) => ({ ref: `evidence:${item.id}`, bytes: 0, digest: `verdict=${item.verdict}` })),
2824
3394
  ...derived.hypotheses.map((item) => ({ ref: `hypothesis:${item.id}`, bytes: 0, digest: `${item.status}/支持到${item.supportedLevel ?? '—'}` })),
2825
3395
  ],
2826
- extra: lessonBrief(proposedLessons),
3396
+ answers, lessons: proposedLessons,
3397
+ extra: [...answersBrief(answers), ...lessonBrief(proposedLessons)],
2827
3398
  }
2828
3399
  const audit = await runEvaluator(sessionId, exec.agent, plan, syntheticStep, gate, 'goal_audit', exec.signal)
2829
3400
  mutations.push(...audit.mutations)
2830
3401
  if (audit.holds === 'pending') return fail('audit_pending', tr(`目标评估者仍在跑:${plainIds(sessionId, audit.basis)}。先观察当前事实,再谈重试。`, `The goal evaluator is still running: ${plainIds(sessionId, audit.basis)}. Look at the current facts before retrying.`), { mutations: audit.mutations })
2831
3402
  if (audit.holds !== 'yes') {
3403
+ const failureStep = `goal:${goal.id}:${audit.digest ?? 'unknown'}`
3404
+ const failures = (state.blocks[`goal:${failureStep}`] ?? 0) + 1
3405
+ mutations.push({ t: 'block/counted', plan: 'goal', step: failureStep, count: failures, reason: `goal_audit:${audit.holds}` })
3406
+ if (failures >= CFG.blockedThreshold) blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, `目标审查连续失败 ${failures} 次,保持开放并停止续跑`)
2832
3407
  /**
2833
3408
  * **复用来的裁决不落第二条证据**。
2834
3409
  *
@@ -2884,6 +3459,22 @@ export function apply(ctx, config = {}) {
2884
3459
  { mutations },
2885
3460
  )
2886
3461
  }
3462
+ /**
3463
+ * **停止检查在审计之后再做一次**:评估者这次审计里新报的未解释项(做的人没登记、或排除理由站不住),
3464
+ * 只要它没说「不影响结论」,也要在结论里有交代。审计结算已经落账,这些项会挂在卡上;
3465
+ * 补写 `answers` 后再结案,材料没变,裁决复用,不再花一次评估。
3466
+ * 只在审计之前看的话,评估者指出的问题从不经过停止检查。
3467
+ */
3468
+ const afterAudit = previewOf(hostService, sessionId, mutations)
3469
+ if (afterAudit === null) return fail('host_unavailable', '审计后无法重新核对材料,保持开放', { mutations })
3470
+ if (CFG.requireAnswers) {
3471
+ const missing = unsettledForAnswers(afterAudit.state, afterAudit.derived, answers)
3472
+ if (missing.length) return fail('answers_incomplete', `审计后仍有未处理事项:\n${missing.join('\n')}`, { mutations })
3473
+ }
3474
+ const afterUses = answers.flatMap((answer) => answer.uses.map((id) => ({ id, ...citeVerdict(knowledgeRows(afterAudit.derived).find((row) => row.id === id), mergeScope(answer.scope, { conditions: goal.conditions ?? {} })) }))).filter((cite) => ['unknown', 'retracted', 'definition_changed', 'pending', 'out_of_scope', 'out_of_range'].includes(cite.verdict))
3475
+ if (CFG.applicabilityFeedback && afterUses.length) return fail('answer_uses_invalid', '审计期间引用状态发生变化,保持开放', { mutations })
3476
+ for (const answer of answers) answer.uses_review = answer.uses.map((id) => ({ id, confirmed: answer.basis.length > 0 && (audit.reuse ?? []).some((row) => row.id === id && row.verdict === 'support' && row.basis !== ''), card_path: audit.cardPath, digest: audit.digest }))
3477
+
2887
3478
  /**
2888
3479
  * **没被任何证据触及的假设**,结案时如实记一笔。
2889
3480
  *
@@ -2931,7 +3522,7 @@ export function apply(ctx, config = {}) {
2931
3522
  (hypothesis) =>
2932
3523
  !judged.has(hypothesis.id) && (hypothesis.supportedLevel === null || hypothesis.supportedLevel === undefined) && (hypothesis.refutations ?? 0) === 0 && (hypothesis.inconclusive ?? 0) === 0,
2933
3524
  )
2934
- mutations.push({ t: 'goal/closed', id: goal.id, status: 'achieved', verdict: 'support', note: args.note ?? null, unjudged: untouched.map((hypothesis) => hypothesis.id) })
3525
+ mutations.push({ t: 'goal/closed', id: goal.id, status: 'achieved', verdict: 'support', note: args.note ?? null, unjudged: untouched.map((hypothesis) => hypothesis.id), ...(answers.length > 0 ? { answers } : {}) })
2935
3526
  const continuationNote = completeNativeGoal(exec.agent)
2936
3527
  /** 这个目标下各步经准入收下的产物(按路径去重),结案时一次声明成交付卡片。 */
2937
3528
  const delivered = []
@@ -2991,17 +3582,28 @@ export function apply(ctx, config = {}) {
2991
3582
  */
2992
3583
  let definitions = null
2993
3584
  try {
2994
- const said = `${hypothesis.claim ?? ''}\n${hypothesis.refute_when ?? ''}`
3585
+ const aboutIds = mergeAbout(hypothesis.about, goal.about)
3586
+ const entityTypes = (state.entities ?? []).filter((entity) => aboutIds.includes(entity.id)).map((entity) => entity.type)
3587
+ const said = `${hypothesis.claim ?? ''}\n${hypothesis.refute_when ?? ''}\n${[...aboutIds, ...entityTypes].join(' ')}`
2995
3588
  const found = hostService.domain?.definitions?.(sessionId, assertions ?? [], mutations, said) ?? null
2996
3589
  definitions = found !== null && Object.keys(found).length > 0 ? found : null
2997
3590
  } catch {
2998
3591
  definitions = null
2999
3592
  }
3000
- const record = { id: factId, goal: goal.id, hypothesis: hypothesis.id, text: hypothesis.claim, scope: hypothesis.refute_when ?? null, level: factLevel ?? null, evidence, assertions, definitions }
3593
+ /**
3594
+ * **适用范围与推翻条件分开存**:范围取判断自己写的,缺的维度用立题的 conditions 补;
3595
+ * 都没有就如实是 null(「范围未声明」)。推翻条件另存在 `refute_when`。
3596
+ */
3597
+ const scopeSpec = mergeScope(hypothesis.scope, { conditions: goal.conditions ?? {} })
3598
+ const scope = scopeSpec === null ? null : tr(scopeText(scopeSpec, 'zh'), scopeText(scopeSpec, 'en'))
3599
+ /** 涉及的实体或量:判断自己写的加上立题的,文件查找按它们取到这条事实。 */
3600
+ const about = mergeAbout(hypothesis.about, goal.about)
3601
+ const evidenceRecords = [...state.evidence, ...mutations.filter((item) => item.t === 'evidence/recorded')].filter((item) => evidence.includes(item.id))
3602
+ const record = { id: factId, goal: goal.id, hypothesis: hypothesis.id, text: hypothesis.claim, about, scope, scope_spec: scopeSpec, refute_when: hypothesis.refute_when ?? null, level: factLevel ?? null, evidence, evidence_records: evidenceRecords, assertions, definitions, ...(typeof hypothesis.use === 'string' ? { use: hypothesis.use, calculation: calculationSnapshot(sessionId, hypothesis.use) } : {}) }
3001
3603
  const path = persistFact(sessionId, record)
3002
3604
  /**
3003
- * 事实带上**边界**(`scope` = 这条假设的推翻条件):没有边界的事实,下一轮没人敢用;
3004
- * 有边界才算「已知」而不是「口号」。它与出处(证据 id)、等级一起进事实库与货架。
3605
+ * 事实带上**适用范围**(`scope` 是给人读的一行,`scope_spec` 是可比较的形状)与**推翻条件**:
3606
+ * 没有范围的事实,下一轮无从判断是否适用。它们与出处(证据 id)、等级一起进事实库与货架。
3005
3607
  */
3006
3608
  mutations.push({
3007
3609
  t: 'fact/promoted',
@@ -3014,11 +3616,15 @@ export function apply(ctx, config = {}) {
3014
3616
  */
3015
3617
  hypothesis: hypothesis.id,
3016
3618
  text: hypothesis.claim,
3017
- scope: hypothesis.refute_when ?? null,
3619
+ about,
3620
+ scope,
3621
+ scope_spec: scopeSpec,
3622
+ refute_when: hypothesis.refute_when ?? null,
3018
3623
  level: factLevel ?? null,
3019
3624
  evidence,
3020
3625
  assertions,
3021
3626
  definitions,
3627
+ ...(typeof hypothesis.use === 'string' ? { use: hypothesis.use } : {}),
3022
3628
  path,
3023
3629
  })
3024
3630
  promoted.push({ id: factId, claim: hypothesis.claim })
@@ -3033,9 +3639,11 @@ export function apply(ctx, config = {}) {
3033
3639
  droppedLessons.push(`${quote(lesson.text)}${tr(':', ': ')}${verdict === null ? tr('评估者没判', 'the evaluator gave no verdict') : `${verdict.verdict === 'refute' ? tr('被推翻', 'refuted') : tr('说不清', 'inconclusive')}${verdict.basis ? `(${verdict.basis})` : ''}`}`)
3034
3640
  return
3035
3641
  }
3036
- const record = { id: `l-${Math.random().toString(36).slice(2, 8)}`, goal: goal.id, ...lesson, basis: verdict.basis }
3642
+ /** 经验也带适用范围(立题的 conditions)与涉及对象(经验自己写的加上立题的),与事实同形。 */
3643
+ const lessonScope = mergeScope({ conditions: goal.conditions ?? {} }, null)
3644
+ const record = { id: `l-${Math.random().toString(36).slice(2, 8)}`, goal: goal.id, ...lesson, about: mergeAbout(lesson.about, goal.about), ...(lessonScope === null ? {} : { scope_spec: lessonScope }), basis: verdict.basis }
3037
3645
  const path = persistLesson(sessionId, record)
3038
- mutations.push({ t: 'lesson/recorded', id: record.id, goal: goal.id, text: lesson.text, kind: lesson.kind, about: lesson.about, evidence: lesson.evidence, boundary: lesson.boundary, basis: verdict.basis, path })
3646
+ mutations.push({ t: 'lesson/recorded', id: record.id, goal: goal.id, text: lesson.text, kind: lesson.kind, about: record.about, scope_spec: record.scope_spec, evidence: lesson.evidence, boundary: lesson.boundary, basis: verdict.basis, path })
3039
3647
  keptLessons.push(record)
3040
3648
  })
3041
3649
  return done({
@@ -3102,15 +3710,211 @@ export function apply(ctx, config = {}) {
3102
3710
  }
3103
3711
  }
3104
3712
 
3713
+ /**
3714
+ * **可重跑的核算**(`clear/models/<id>.json`,见 `models.js`):引用一条带 `use` 的事实时调用。
3715
+ * 输入与方法的内容摘要没变就不跑;变了就在工作区里用宿主的 `shell` 跑一次,读输出、与上次
3716
+ * (第一次则与登记的 `baseline`)比对,写运行记录(`clear/evidence/models/<id>.json`)。
3717
+ * 拿不到 shell、登记不对、命令失败,都如实返回状态,不当成偏差。
3718
+ */
3719
+ const MODEL_TIMEOUT_MS = 60000
3720
+ function calculationSnapshot(sessionId, modelId) {
3721
+ const cwd = sessionCwd(sessionId)
3722
+ if (!cwd || !MODEL_ID.test(String(modelId))) return null
3723
+ try {
3724
+ const path = `clear/models/${modelId}.json`
3725
+ const spec = JSON.parse(readFileSync(join(cwd, path), 'utf8'))
3726
+ let reference = numericOutputs(spec.baseline)
3727
+ try { reference = numericOutputs(JSON.parse(readFileSync(join(cwd, spec.output), 'utf8'))) } catch {}
3728
+ return { model: modelId, reference: Object.keys(reference).length ? reference : null, inputs: Object.fromEntries(spec.inputs.map((path) => [path, fileDigest(cwd, path)])), method: methodSnapshot(cwd, spec, path), at: Date.now() }
3729
+ } catch { return null }
3730
+ }
3731
+
3732
+ function persistRechecks(sessionId, fact, reasons) {
3733
+ if (!fact || !/^[A-Za-z0-9_-]+$/.test(fact.id)) return false
3734
+ const file = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
3735
+ if (!file) return false
3736
+ try {
3737
+ const data = JSON.parse(readFileSync(file, 'utf8'))
3738
+ const rechecks = [...(data.rechecks ?? [])]
3739
+ for (const reason of reasons) {
3740
+ const id = contentDigest({ kind: reason.kind, model: reason.model, inputs: reason.inputs, method: reason.method, source: reason.source }).slice(0, 32)
3741
+ if (!rechecks.some((row) => row.id === id)) rechecks.push({ ...reason, id, status: 'pending', scope_spec: data.scope_spec ?? null, at: Date.now() })
3742
+ }
3743
+ data.rechecks = rechecks
3744
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3745
+ fact.rechecks = rechecks
3746
+ return true
3747
+ } catch (error) { ctx.logger?.warn?.(`clearai: recheck persistence failed: ${error.message}`); return false }
3748
+ }
3749
+
3750
+ async function rerunModel(sessionId, modelId, fact, exec) {
3751
+ const cwd = sessionCwd(sessionId)
3752
+ const resultFile = `clear/evidence/models/${modelId}.json`
3753
+ const incomplete = (status, detail, snapshot = {}) => {
3754
+ const reason = { kind: 'recheck_incomplete', model: modelId, evidence: resultFile, detail, ...snapshot }
3755
+ const persisted = persistRechecks(sessionId, fact, [reason])
3756
+ return { status, model: modelId, detail, pending: true, persisted, deviations: [] }
3757
+ }
3758
+ if (!cwd || !MODEL_ID.test(String(modelId))) return incomplete('missing', 'workspace or model id unavailable')
3759
+ let spec
3760
+ try { spec = JSON.parse(readFileSync(join(cwd, 'clear', 'models', `${modelId}.json`), 'utf8')) } catch { return incomplete('missing', 'registration missing') }
3761
+ const problems = checkModelSpec(spec, modelId)
3762
+ if (problems.length) return incomplete('invalid', problems.join(';'))
3763
+ const method = methodSnapshot(cwd, spec, `clear/models/${modelId}.json`)
3764
+ const stamp = Object.fromEntries(spec.inputs.map((path) => [path, fileDigest(cwd, path)]))
3765
+ const snapshot = { inputs: stamp, method }
3766
+ const reference = fact?.calculation?.reference ?? null
3767
+ const reasons = []
3768
+ if (fact?.calculation?.method && fact.calculation.method !== method) reasons.push({ kind: 'method_changed', model: modelId, ...snapshot, evidence: resultFile })
3769
+ if (!reference || !Object.keys(numericOutputs(reference)).length) reasons.push({ kind: 'reference_missing', model: modelId, ...snapshot, evidence: resultFile })
3770
+ let record = null
3771
+ try { record = JSON.parse(readFileSync(join(cwd, resultFile), 'utf8')) } catch {}
3772
+ const lastRun = record?.runs?.at(-1) ?? null
3773
+ let outputs = lastRun?.outputs
3774
+ let status = 'current'
3775
+ if (lastRun && fileDigest(cwd, spec.output) === 'missing-or-unreadable') return incomplete('failed', 'output missing', snapshot)
3776
+ if (needsRerun(lastRun, stamp) || lastRun?.method !== method) {
3777
+ if (Object.values(stamp).some((value) => value === 'missing-or-unreadable')) return incomplete('failed', 'input missing', snapshot)
3778
+ if (typeof ctx.tools?.execute !== 'function' || !ctx.get('shell')) return incomplete('unavailable', 'native tool registry or shell unavailable', snapshot)
3779
+ let execution
3780
+ try {
3781
+ execution = await ctx.tools.execute({ name: process.platform === 'win32' ? 'pwsh' : 'bash', arguments: { command: spec.command, description: 'Recheck registered calculation against accepted evidence', workdir: cwd, timeoutMs: MODEL_TIMEOUT_MS, run_in_background: false }, agent: exec.agent, signal: exec.signal, callId: `${exec.callId}:model:${modelId}`, parent: exec })
3782
+ } catch (error) { return incomplete('failed', String(error?.message ?? error).slice(0, 200), snapshot) }
3783
+ const result = execution?.value
3784
+ if (execution?.isError || result?.timedOut || result?.aborted || result?.exitCode !== 0) return incomplete('failed', String(execution?.error?.message ?? result?.stderr?.text ?? 'execution incomplete').slice(-200), snapshot)
3785
+ try { outputs = numericOutputs(JSON.parse(readFileSync(join(cwd, spec.output), 'utf8'))) } catch { return incomplete('failed', `cannot read ${spec.output}`, snapshot) }
3786
+ status = 'rerun'
3787
+ }
3788
+ const deviations = compareOutputs(reference, outputs ?? {}, spec.tolerance)
3789
+ if (deviations.length) reasons.push({ kind: 'output_deviation', model: modelId, ...snapshot, evidence: resultFile, reference, outputs, deviations })
3790
+ if (status === 'rerun') {
3791
+ try { writeTextFile(join(cwd, resultFile), `${JSON.stringify({ id: modelId, ...appendRun(record, { at: Date.now(), inputs: stamp, method, outputs, deviations }) }, null, 2)}\n`) }
3792
+ catch { return incomplete('failed', 'observation persistence failed', snapshot) }
3793
+ }
3794
+ if (reasons.length && !persistRechecks(sessionId, fact, reasons)) return incomplete('failed', 'pending reasons could not be persisted', snapshot)
3795
+ return { status, model: modelId, deviations, pending: (fact?.rechecks ?? []).some((row) => row.status === 'pending'), against: 'baseline' }
3796
+ }
3797
+
3798
+ function confirmRechecks(sessionId, factId, hypothesis, audit, state) {
3799
+ if (audit.reused || audit.holds !== 'yes') return
3800
+ const row = knowledgeRows(host().derive(sessionId)).find((row) => row.id === factId)
3801
+ if (!row || compareScope(row.scope_spec, mergeScope(hypothesis.scope, { conditions: state.goal?.conditions ?? {} })).verdict !== 'applies') return
3802
+ const file = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${factId}.json`)
3803
+ try {
3804
+ const data = JSON.parse(readFileSync(file, 'utf8'))
3805
+ const approved = new Set((audit.rechecks ?? []).filter((item) => item.fact === factId && item.basis.trim() !== '').map((item) => item.id))
3806
+ let observed = null, spec = null
3807
+ if (data.use) {
3808
+ observed = JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'evidence', 'models', `${data.use}.json`), 'utf8')).runs.at(-1)
3809
+ spec = JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'models', `${data.use}.json`), 'utf8'))
3810
+ if (!observed || observed.method !== methodSnapshot(sessionCwd(sessionId), spec, `clear/models/${data.use}.json`) || spec.inputs.some((path) => observed.inputs[path] !== fileDigest(sessionCwd(sessionId), path))) return
3811
+ }
3812
+ data.rechecks = (data.rechecks ?? []).map((reason) => {
3813
+ if (reason.status !== 'pending' || !approved.has(reason.id)) return reason
3814
+ if (reason.model && (!observed || !data.calculation?.reference || compareOutputs(data.calculation.reference, observed.outputs, spec.tolerance).length)) return reason
3815
+ return { ...reason, status: 'resolved', resolution: { by: 'independent', card_path: audit.cardPath, hypothesis: hypothesis.id, at: Date.now() } }
3816
+ })
3817
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3818
+ confirmLinkedNegatives(sessionId, data, hypothesis, state)
3819
+ } catch (error) { ctx.logger?.warn?.(`clearai: confirmation incomplete: ${error.message}`) }
3820
+ }
3821
+
3822
+ /** Keep the original anomaly and evidence; close only its independently rechecked, matching scope. */
3823
+ function confirmLinkedNegatives(sessionId, fact, hypothesis, state) {
3824
+ const scope = mergeScope(hypothesis.scope, { conditions: state.goal?.conditions ?? {} })
3825
+ for (const source of new Set((fact.rechecks ?? []).filter(reason => reason.kind === 'anomaly' && reason.status === 'resolved').map(reason => reason.source).filter(Boolean))) {
3826
+ if (!/^[A-Za-z0-9_-]+$/.test(source)) continue
3827
+ const file = sessionFile(sessionId, ...NEGATIVES_REL, `${source}.json`)
3828
+ if (!file || !existsSync(file)) continue
3829
+ const item = JSON.parse(readFileSync(file, 'utf8'))
3830
+ if (!['unresolved', 'escalated'].includes(item.status) || item.review || !item.touches?.length) continue
3831
+ if (compareScope(item.scope, scope).verdict !== 'applies' || compareScope(scope, item.scope).verdict !== 'applies') continue
3832
+ const confirmations = []
3833
+ for (const id of item.touches) {
3834
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) break
3835
+ const path = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${id}.json`)
3836
+ if (!path || !existsSync(path)) break
3837
+ const linked = JSON.parse(readFileSync(path, 'utf8'))
3838
+ const reasons = (linked.rechecks ?? []).filter(reason => reason.source === source)
3839
+ if (!reasons.length || reasons.some(reason => reason.status !== 'resolved' || reason.resolution?.by !== 'independent' || !reason.resolution.card_path)) break
3840
+ confirmations.push({ fact: id, reasons: reasons.map(reason => ({ id: reason.id, ...reason.resolution })) })
3841
+ }
3842
+ if (confirmations.length !== item.touches.length) continue
3843
+ item.status = 'explained'
3844
+ item.resolution = { outcome: 'explained', by: 'independent', scope, confirmations, reason: tr('同范围内涉及事实的这条复核原因已逐条独立确认;保留原始异常观测,不外推到其他范围。', 'The linked cause was independently rechecked for every affected fact in this scope. Original anomalous observations remain; no claim is made outside this scope.'), at: Date.now() }
3845
+ item.evidence = [...(item.evidence ?? [])]
3846
+ for (const confirmation of confirmations) for (const reason of confirmation.reasons) {
3847
+ const ref = relative(sessionCwd(sessionId), reason.card_path).split('\\').join('/')
3848
+ if (!item.evidence.some(row => row.ref === ref)) item.evidence.push({ ref })
3849
+ }
3850
+ writeTextFile(file, `${JSON.stringify(item, null, 2)}\n`)
3851
+ }
3852
+ }
3853
+
3854
+ /**
3855
+ * **负向条目随发生随写**(`clear/knowledge/negatives/<id>.json`,只有系统写)。
3856
+ *
3857
+ * 判断被推翻、反常被登记或被解释为缺陷,都在那一刻落盘,不等结案:会话因预算或 token 限制中断、
3858
+ * 以放弃结束时,这些信息照样留下。条目从当前状态整份算出(`negativeItems`),所以重写是幂等的;
3859
+ * 只有内容变了才写。别的会话写的同名文件不动;人加在文件上的 `review` 保留。
3860
+ * 两个调用点:每个工具结果之后(这一拍的变更先折一遍)与每一拍的 pre-step(兜底)。
3861
+ */
3862
+ const negativeWrites = new Map()
3863
+ function writeBack(sessionId, state, derived) {
3864
+ if (isSpawnedChild(sessionId) || !CFG.negativeWriteback) return []
3865
+ if (state === null || state === undefined) return []
3866
+ const written = []
3867
+ for (const item of negativeItems(state, derived, { session: sessionId })) {
3868
+ if (['unresolved', 'defect', 'escalated'].includes(item.status)) for (const id of item.touches ?? []) {
3869
+ const fact = findFact(sessionId, state, id)
3870
+ if (!fact) continue
3871
+ const fit = compareScope(fact.scope_spec, item.scope)
3872
+ if (['out_of_scope', 'out_of_range'].includes(fit.verdict)) continue
3873
+ persistRechecks(sessionId, fact, [{ kind: 'anomaly', source: item.id, detail: item.statement, evidence: item.about?.find((ref) => ref.includes('/')) ?? null }])
3874
+ }
3875
+ const file = sessionFile(sessionId, ...NEGATIVES_REL, `${item.id}.json`)
3876
+ if (file === null) return written
3877
+ const body = JSON.stringify(item)
3878
+ if (negativeWrites.get(file) === body) continue
3879
+ try {
3880
+ let existing = null
3881
+ if (existsSync(file)) {
3882
+ try {
3883
+ existing = JSON.parse(readFileSync(file, 'utf8'))
3884
+ } catch {
3885
+ existing = null
3886
+ }
3887
+ }
3888
+ if (existing !== null && typeof existing.source?.session === 'string' && existing.source.session !== sessionId) {
3889
+ negativeWrites.set(file, body)
3890
+ continue
3891
+ }
3892
+ const at = typeof existing?.at === 'number' ? existing.at : Date.now()
3893
+ const record = { ...item, source: existing?.source ?? item.source, review: existing?.review ?? null, at, updated: Date.now() }
3894
+ if (existing?.resolution?.by === 'independent' && existing.resolution.confirmations?.length && ['unresolved', 'escalated'].includes(item.status)) {
3895
+ record.status = existing.status
3896
+ record.resolution = existing.resolution
3897
+ record.evidence = existing.evidence
3898
+ }
3899
+ writeTextFile(file, `${JSON.stringify(record, null, 2)}\n`)
3900
+ negativeWrites.set(file, body)
3901
+ written.push(item.id)
3902
+ } catch (error) {
3903
+ ctx.logger?.warn?.(`clearai kernel: 负向条目落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
3904
+ }
3905
+ }
3906
+ return written
3907
+ }
3908
+
3105
3909
  // ── 计划六件 ───────────────────────────────────────────────────────────
3106
3910
 
3107
3911
  const STEP_SCHEMA = {
3108
3912
  type: 'object',
3109
3913
  properties: {
3110
- id: { type: 'string', description: '稳定 id(字母/数字/下划线/短横)' },
3111
- do: { type: 'string', description: '这一步做什么' },
3112
- artifacts: { type: 'array', items: { type: 'string' }, description: '以何物为证:相对 workspace 的具体产物文件路径(目录不是物证)' },
3113
- done_criteria: { type: 'string', description: '判定标准:在结果出现之前写下,必须可核对' },
3914
+ id: { type: 'string', description: '稳定 id' },
3915
+ do: { type: 'string', description: '做什么' },
3916
+ artifacts: { type: 'array', items: { type: 'string' }, description: '作为物证的产物文件路径(相对工作区,不是目录)' },
3917
+ done_criteria: { type: 'string', description: '判据:结果出现前写下,可核对' },
3114
3918
  tests: {
3115
3919
  type: 'object',
3116
3920
  properties: {
@@ -3118,16 +3922,22 @@ export function apply(ctx, config = {}) {
3118
3922
  type: 'array',
3119
3923
  minItems: 1,
3120
3924
  items: { type: 'string' },
3121
- description: '这一步检验哪几条判断:填判断的短名(也认主张原文)。一次观测同时判几条竞争的判断时(比较那一步),把它们都列上',
3925
+ description: '检验哪几条判断(短名);比较竞争判断的一步全列上',
3122
3926
  },
3123
- level: { type: 'string', enum: MODEL_LEVELS, description: 'L2 = 自判(你写结果与依据);L3 = 独立评估(系统派评估者判);L4 = 人放行(不可重复或来自外部的证据,先过人)' },
3927
+ level: { type: 'string', enum: MODEL_LEVELS, description: 'L2 自判;L3 独立评估;L4 人工批准(不可重复或外部证据)' },
3124
3928
  },
3125
3929
  required: ['hypotheses', 'level'],
3126
3930
  additionalProperties: false,
3127
3931
  },
3128
3932
  expect: {
3129
3933
  type: 'string',
3130
- description: '可选,动手前写:这一步预计看到什么(尽量给数或方向),以及预期从哪来(本体里的哪条关系 / 哪条经验 / 哪条判断,或直说是直觉)。写下来,落空才看得见',
3934
+ description: '可选,执行前写:预计看到什么(数值或方向)',
3935
+ },
3936
+ serves: { type: 'string', description: '可选:服务哪个问题或板块 id' },
3937
+ predictions: {
3938
+ type: 'array',
3939
+ description: '可选,执行前写:各候选成立时预计看到什么;都一样就换检验',
3940
+ items: { type: 'object', properties: { hypothesis: { type: 'string', description: '判断短名' }, expect: { type: 'string', description: '预计看到什么' } }, required: ['hypothesis', 'expect'], additionalProperties: false },
3131
3941
  },
3132
3942
  },
3133
3943
  required: ['id', 'do', 'done_criteria'],
@@ -3138,7 +3948,7 @@ export function apply(ctx, config = {}) {
3138
3948
  defineTool({
3139
3949
  name: 'CreatePlan',
3140
3950
  description:
3141
- '立约:把复杂任务立成一份计划。每步一句话说清做什么(do)、以何物为证(artifacts)、以及判定标准(done_criteria,在结果出现之前写下);可带预期(expect:预计看到什么、从哪来)。检验判断的步骤用 tests:{hypotheses, level} 声明验哪几条、什么等级(比较竞争路线的那一步,把竞争的几条都列上)。最多 25 步。约立起便锁定:局部挫折改当前步,不要推倒重来。',
3951
+ '立计划:每步写做什么、以哪个文件为证、判据(结果出现前写下);检验判断的步用 tests。最多 25 步;局部挫折改当前步,不推倒重来。',
3142
3952
  parameters: {
3143
3953
  type: 'object',
3144
3954
  properties: {
@@ -3163,6 +3973,12 @@ export function apply(ctx, config = {}) {
3163
3973
  if (resolved.ok !== true) return fail('unknown_hypothesis', tr(`步骤 ${step.id} 声明的判断「${resolved.wanted}」对不上任何一条已登记的判断。`, `Step ${step.id} names the judgment "${resolved.wanted}", which matches no registered judgment. `) + hypothesisMenu(state.hypotheses))
3164
3974
  resolvedTests.set(step.id, resolved.tests)
3165
3975
  }
3976
+ const resolvedExtras = new Map()
3977
+ for (const step of args.steps) {
3978
+ const resolved = resolveStepExtras(state, step)
3979
+ if (resolved.ok !== true) return fail(resolved.code, resolved.message)
3980
+ resolvedExtras.set(step.id, resolved.extra)
3981
+ }
3166
3982
  const warnings = []
3167
3983
  if (typeof args.brief !== 'string' || args.brief.length < CFG.minBriefChars) warnings.push(tr(`brief 偏短(建议 ≥${CFG.minBriefChars} 字),它是给人读的计划说明`, `brief is short (suggested ≥${CFG.minBriefChars} characters); it is the plan description people read`))
3168
3984
  const goal = state.goal !== null && state.goal.status === 'open' ? state.goal : null
@@ -3174,7 +3990,7 @@ export function apply(ctx, config = {}) {
3174
3990
  goal: goal?.id ?? null,
3175
3991
  phase_id: goal?.id ?? null,
3176
3992
  brief,
3177
- steps: args.steps.map((step) => ({ id: step.id, do: step.do, artifacts: step.artifacts ?? [], done_criteria: step.done_criteria, tests: resolvedTests.get(step.id) ?? null, ...(typeof step.expect === 'string' && step.expect.trim() !== '' ? { expect: step.expect.trim() } : {}) })),
3993
+ steps: args.steps.map((step) => ({ id: step.id, do: step.do, artifacts: step.artifacts ?? [], done_criteria: step.done_criteria, tests: resolvedTests.get(step.id) ?? null, ...(typeof step.expect === 'string' && step.expect.trim() !== '' ? { expect: step.expect.trim() } : {}), ...resolvedExtras.get(step.id) })),
3178
3994
  })
3179
3995
  return done({
3180
3996
  ok: true,
@@ -3193,16 +4009,17 @@ export function apply(ctx, config = {}) {
3193
4009
  defineTool({
3194
4010
  name: 'RevisePlan',
3195
4011
  description:
3196
- '改当前计划,不动进度(返回 progress_changed=false),四种动作:`action="expect"` 给还没做的一步写下预期(给 `step_id` 与 `expect`:动手前写,落空才看得见);`action="add"` 补一步(漏了活就补上,给 `step`);`action="refine"` 精化一步的判定标准(给 `step_id` 与新的 `done_criteria`,旧判据留在日志里);`action="void"` 带因作废一步(给 `step_id` 与 `reason`:发现某步本不该存在就作废并说明缘由——作废留痕光明正大,为凑完成而造证是大忌;已交付的步不能作废)。',
4012
+ '改计划,不动进度。expect:给未执行的步写预测(step_id + expect 或 predictions);add:补一步(step);refine:改一步的判据(step_id + done_criteria);void:带因作废一步(step_id + reason,已交付的不能作废)。',
3197
4013
  parameters: {
3198
4014
  type: 'object',
3199
4015
  properties: {
3200
- action: { type: 'string', enum: ['expect', 'add', 'refine', 'void'], description: 'expect=写预期;add=补一步;refine=改判据;void=带因作废' },
3201
- step: { ...STEP_SCHEMA, description: 'action=add:新步' },
3202
- step_id: { type: 'string', description: 'action=expect / refine / void:哪一步' },
3203
- expect: { type: 'string', description: 'action=expect:预计看到什么,以及预期从哪来(关系 / 经验 / 判断,或直觉)' },
3204
- done_criteria: { type: 'string', description: 'action=refine:新的判定标准' },
3205
- reason: { type: 'string', description: '为什么改(action=void 必填)' },
4016
+ action: { type: 'string', enum: ['expect', 'add', 'refine', 'void'], description: 'expect / add / refine / void' },
4017
+ step: { type: 'object', description: 'action=add:新步,字段同 CreatePlan 的步骤' },
4018
+ step_id: { type: 'string', description: '哪一步' },
4019
+ expect: { type: 'string', description: 'action=expect:预计看到什么' },
4020
+ predictions: { ...STEP_SCHEMA.properties.predictions, description: 'action=expect:各候选的预测' },
4021
+ done_criteria: { type: 'string', description: 'action=refine:新判据' },
4022
+ reason: { type: 'string', description: '为什么改(void 必填)' },
3206
4023
  },
3207
4024
  required: ['action'],
3208
4025
  additionalProperties: false,
@@ -3223,7 +4040,9 @@ export function apply(ctx, config = {}) {
3223
4040
  if (plan.steps.some((step) => step.id === args.step.id)) return fail('duplicate_step', tr(`步骤 id 已存在:${args.step.id}`, `Step id already exists: ${args.step.id}`))
3224
4041
  const resolved = resolveTests(state.hypotheses, args.step.tests)
3225
4042
  if (resolved.ok !== true) return fail('unknown_hypothesis', tr(`步骤 ${args.step.id} 声明的判断「${resolved.wanted}」对不上任何一条已登记的判断。`, `Step ${args.step.id} names the judgment "${resolved.wanted}", which matches no registered judgment. `) + hypothesisMenu(state.hypotheses))
3226
- const amended = { id: args.step.id, do: args.step.do, artifacts: args.step.artifacts ?? [], done_criteria: args.step.done_criteria, tests: resolved.tests, ...(typeof args.step.expect === 'string' && args.step.expect.trim() !== '' ? { expect: args.step.expect.trim() } : {}) }
4043
+ const extras = resolveStepExtras(state, args.step)
4044
+ if (extras.ok !== true) return fail(extras.code, extras.message)
4045
+ const amended = { id: args.step.id, do: args.step.do, artifacts: args.step.artifacts ?? [], done_criteria: args.step.done_criteria, tests: resolved.tests, ...(typeof args.step.expect === 'string' && args.step.expect.trim() !== '' ? { expect: args.step.expect.trim() } : {}), ...extras.extra }
3227
4046
  mutations.push({ t: 'plan/amended', plan: plan.id, step: amended })
3228
4047
  if (plan.blocked !== undefined) mutations.push({ t: 'block/cleared', plan: plan.id, step: plan.blocked.step })
3229
4048
  return done({ ok: true, code: 'plan_amended', progress_changed: false, message: tr(`已补一步 ${args.step.id}(进度不变)。`, `Added step ${args.step.id} (progress unchanged).`) })
@@ -3232,11 +4051,14 @@ export function apply(ctx, config = {}) {
3232
4051
  const step = plan.steps.find((item) => item.id === args.step_id)
3233
4052
  if (step === undefined) return fail('unknown_step', tr(`没有这一步:${args.step_id}`, `No such step: ${args.step_id}`))
3234
4053
  if (args.action === 'expect') {
3235
- if (step.status !== 'open') return fail('step_settled', tr(`步骤 ${step.id} 已落定(${step.status}):预期要在动手前写。`, `Step ${step.id} is settled (${step.status}); expectations are written before acting.`))
4054
+ if (step.status !== 'open') return fail('step_settled', tr(`步骤 ${step.id} 已结束(${step.status}):预测须在执行前写下。`, `Step ${step.id} is settled (${step.status}); expectations are written before acting.`))
3236
4055
  const expect = String(args.expect ?? '').trim()
3237
- if (expect.length < 4) return fail('expect_required', tr('预期不能为空:写预计看到什么,以及它从哪来。', 'The expectation cannot be empty: say what you expect to see and where that comes from.'))
3238
- mutations.push({ t: 'step/expected', plan: plan.id, step: step.id, expect })
3239
- return done({ ok: true, code: 'step_expected', progress_changed: false, message: tr(`步骤 ${step.id} 的预期已记下。交付时拿结果对它:对不上的地方写进 AdvancePlan 的 anomalies。`, `Expectation recorded for step ${step.id}. When you deliver, compare the result with it: whatever does not match goes in AdvancePlan's anomalies.`) })
4056
+ const extras = resolveStepExtras(state, { id: step.id, predictions: args.predictions })
4057
+ if (extras.ok !== true) return fail(extras.code, extras.message)
4058
+ const predictions = extras.extra.predictions ?? []
4059
+ if (expect.length < 4 && predictions.length === 0) return fail('expect_required', tr('预测不能为空:写明预计观察到什么及其来源;或按候选假设分别填写 predictions。', 'The expectation cannot be empty: say what you expect to see and where that comes from, or write predictions per candidate hypothesis.'))
4060
+ mutations.push({ t: 'step/expected', plan: plan.id, step: step.id, ...(expect.length >= 4 ? { expect } : {}), ...(predictions.length > 0 ? { predictions } : {}) })
4061
+ return done({ ok: true, code: 'step_expected', progress_changed: false, message: tr(`步骤 ${step.id} 的预测已记录。交付时将结果与之对照,不符之处写入 AdvancePlan 的 anomalies。`, `Expectation recorded for step ${step.id}. When you deliver, compare the result with it: whatever does not match goes in AdvancePlan's anomalies.`) })
3240
4062
  }
3241
4063
  if (args.action === 'refine') {
3242
4064
  if (step.status !== 'open') return fail('step_settled', tr(`步骤 ${step.id} 已落定(${step.status}),判据不再可改。`, `Step ${step.id} is settled (${step.status}); its criteria can no longer change.`))
@@ -3258,8 +4080,8 @@ export function apply(ctx, config = {}) {
3258
4080
 
3259
4081
  defineTool({
3260
4082
  name: 'ClosePlan',
3261
- description: '收束当前阶段:把这一张计划归档。目标若未达成,系统会叫醒你开下一阶段。',
3262
- parameters: { type: 'object', properties: { summary: { type: 'string', description: '收束之辞:这一阶段拿到了什么' } }, additionalProperties: false },
4083
+ description: '收束当前计划并归档;目标未达成时开下一阶段。',
4084
+ parameters: { type: 'object', properties: { summary: { type: 'string', description: '这一阶段拿到了什么' } }, additionalProperties: false },
3263
4085
  output: CARD_OUTPUT,
3264
4086
  async execute(args, exec) {
3265
4087
  const call = open(exec)
@@ -3305,31 +4127,31 @@ export function apply(ctx, config = {}) {
3305
4127
  defineTool({
3306
4128
  name: 'AdvancePlan',
3307
4129
  description:
3308
- '交付一步(唯一完成动词):把观测交上来。系统先做观测准入——声明的产物存在、非空、结构合法;准入只看收不收,不做裁决。交付成立这一步就完成——它检验的判断被支持、被推翻还是说不清,**都算完成**,结果单独记成证据。结果和预期对不上的地方写进 anomalies。L2(自判)由你给 basis(交付凭什么成立,必须能被复查)与 results(这一步检验的每条判断各一格);L3 以上两项都由系统派独立评估者判,你写 results 会被拒绝。没有物证,就还没有完成——没有手动标记这回事。',
4130
+ '交付一步,唯一的完成动作。声明的产物须存在、非空、结构合法。交付成立即完成,判断的结果另记为证据。L2 由你给 basis 与 results;L3 以上由独立评估者判。',
3309
4131
  parameters: {
3310
4132
  type: 'object',
3311
4133
  properties: {
3312
- step_id: { type: 'string', description: '交付哪一步(只能落在第一个未落定的步,这里是防手滑的确认,不是选择器)' },
4134
+ step_id: { type: 'string', description: '交付哪一步(须是第一个未完成的步)' },
3313
4135
  observations: {
3314
4136
  type: 'array',
3315
- description: '观测:这一步拿到的原始结果(相对 workspace 的路径 + 一句说明)',
4137
+ description: '原始结果:路径 + 一句说明',
3316
4138
  items: { type: 'object', properties: { ref: { type: 'string' }, note: { type: 'string' } }, required: ['ref'], additionalProperties: false },
3317
4139
  },
3318
4140
  anomalies: {
3319
4141
  type: 'array',
3320
- description: '未解释:这一步的结果里和预期或本体对不上的地方、说不通的读数(一条一句,写哪里不符)。它们挂在卡上,直到被解释、写明理由排除、或交给人(用 Anomaly 工具)。不要把它们解释过去',
3321
- items: { type: 'object', properties: { what: { type: 'string', description: '哪里不符:预期什么、实际什么' }, anchor: { type: 'string', description: '可选:在哪个实体或装置上(实体 id 或名字)' } }, required: ['what'], additionalProperties: false },
4142
+ description: '与预测或本体不符、说不通的读数,每条一句;不要强行解释',
4143
+ items: { type: 'object', properties: { what: { type: 'string', description: '预测为何、实际为何' }, anchor: { type: 'string', description: '可选:在哪个实体或装置上' }, touches: { type: 'array', items: { type: 'string' }, description: '可选:涉及的量、判断或事实 id;点名的事实回到待核验' } }, required: ['what'], additionalProperties: false },
3322
4144
  },
3323
- basis: { type: 'string', description: '交付凭什么成立:引用了哪个产物里的哪个事实(必须可复查)。仅自判(L2)由你写' },
4145
+ basis: { type: 'string', description: '仅 L2:交付成立的依据,引到产物里的具体事实' },
3324
4146
  results: {
3325
4147
  type: 'array',
3326
- description: '仅自判(L2):这一步检验的每条判断各一格,对照它的推翻条件读结果:没碰到推翻条件是「支持」,碰到了是「推翻」,这次观测区分不了是「不确定」。推翻和不确定都不妨碍这一步完成',
4148
+ description: '仅 L2:每条受检判断一格:支持(没碰到推翻条件)/ 推翻 / 不确定',
3327
4149
  items: {
3328
4150
  type: 'object',
3329
4151
  properties: {
3330
- hypothesis: { type: 'string', description: '判断的短名(也认主张原文)' },
4152
+ hypothesis: { type: 'string', description: '判断短名' },
3331
4153
  verdict: { type: 'string', enum: ['支持', '推翻', '不确定', 'support', 'refute', 'inconclusive'] },
3332
- basis: { type: 'string', description: '一句话:这次观测对照推翻条件读出了什么(不写就用上面那句 basis)' },
4154
+ basis: { type: 'string', description: '对照推翻条件读出了什么' },
3333
4155
  },
3334
4156
  required: ['hypothesis', 'verdict'],
3335
4157
  additionalProperties: false,
@@ -3402,6 +4224,7 @@ export function apply(ctx, config = {}) {
3402
4224
 
3403
4225
  // ② 准入
3404
4226
  const gate = admission(cwd, step)
4227
+ gate.materialMutations = mutations.filter((row) => row.t === 'observation/recorded')
3405
4228
  gate.anomalies = opened
3406
4229
  mutations.push({
3407
4230
  t: 'admission/checked',
@@ -3454,8 +4277,8 @@ export function apply(ctx, config = {}) {
3454
4277
  if (releaseTarget !== null && !releaseTarget.released) {
3455
4278
  const asked = await askHuman(exec, {
3456
4279
  id: `release-${step.id}`,
3457
- header: tr('L4 要人放行', 'L4 needs release'),
3458
- question: tr(`步骤 ${step.id}(${clip(step.do, 60)})是 L4:新产生的、不可重复或来自外部的证据。放行这次交付吗?`, `Step ${step.id} (${clip(step.do, 60)}) is L4: new, unrepeatable or external evidence. Release this delivery?`),
4280
+ header: tr('L4 须经人工批准', 'L4 needs approval'),
4281
+ question: tr(`步骤 ${step.id}(${clip(step.do, 60)})属于 L4:新产生的、不可重复或来自外部的证据。是否批准此次交付?`, `Step ${step.id} (${clip(step.do, 60)}) is L4: new, unrepeatable or external evidence. Release this delivery?`),
3459
4282
  detail: tr(`判据:${step.done_criteria}`, `Criteria: ${step.done_criteria}`),
3460
4283
  options: [
3461
4284
  { label: choiceLabel('releaseYes'), description: tr('交给独立评估者判。', 'Hand it to the independent evaluator.') },
@@ -3466,8 +4289,8 @@ export function apply(ctx, config = {}) {
3466
4289
  const why = asked.ok !== true ? unanswered(asked) : tr(`人选了「${asked.choice ?? '没选'}」${asked.note === null ? '' : `:${asked.note}`}`, `the person chose "${asked.choice ?? 'nothing'}"${asked.note === null ? '' : `: ${asked.note}`}`)
3467
4290
  return fail(
3468
4291
  'human_release_missing',
3469
- tr(`L4 的交付要人放行,这一次没有放行(${why})。等级是事实的属性,放行是人的动作——不能推断。`, `An L4 delivery needs a person to release it, and this one was not released (${why}). The level is a property of the fact; release is a person's act and cannot be inferred. `) +
3470
- (asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`步骤 ${step.id} 是 L4,等人放行。`, `Step ${step.id} is L4 and waits for a person to release it.`))),
4292
+ tr(`L4 的交付须经人工批准,本次未获批准(${why})。等级是事实的属性,批准是人的行为,不能推断。`, `An L4 delivery needs a person to release it, and this one was not released (${why}). The level is a property of the fact; release is a person's act and cannot be inferred. `) +
4293
+ (asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`步骤 ${step.id} 是 L4,等待人工批准。`, `Step ${step.id} is L4 and waits for a person to release it.`))),
3471
4294
  mutations.length > 0 ? { mutations } : {},
3472
4295
  )
3473
4296
  }
@@ -3483,6 +4306,7 @@ export function apply(ctx, config = {}) {
3483
4306
  let results = []
3484
4307
  /** 独立裁决的两件凭据(自判路径下保持 null):评估卡文件与写它的**评估者子会话**。 */
3485
4308
  let auditCardPath = null
4309
+ let deliveredAudit = null
3486
4310
  let auditSessionId = null
3487
4311
  /** 复用说明(模型与人都看得到的那一句);不复用时为空串。 */
3488
4312
  let reuseNote = ''
@@ -3497,6 +4321,7 @@ export function apply(ctx, config = {}) {
3497
4321
  const beforeAudit = CFG.auditRerun ? digestsOf() : ''
3498
4322
  const audit = await runEvaluator(sessionId, exec.agent, plan, step, gate, 'evidence_audit', exec.signal)
3499
4323
  mutations.push(...audit.mutations)
4324
+ deliveredAudit = audit
3500
4325
  foundByEvaluator = audit.reused === true ? [] : Array.isArray(audit.anomalies) ? audit.anomalies : []
3501
4326
  if (CFG.auditRerun && audit.reused !== true && ['yes', 'no', 'unclear'].includes(audit.holds) && digestsOf() !== beforeAudit) {
3502
4327
  return fail('evaluator_touched_outputs', tr('评估期间,收下的产物被改动过(评估者应当只在副本里复跑):这份裁决不认。重新交付会再派一次评估。', 'The accepted outputs changed during evaluation (the evaluator should re-run only in the copy), so this verdict is not accepted. Delivering again dispatches a new evaluation.'), { mutations })
@@ -3552,7 +4377,7 @@ export function apply(ctx, config = {}) {
3552
4377
  }
3553
4378
  } else {
3554
4379
  if (typeof args.basis !== 'string' || args.basis.trim().length < 8) {
3555
- return fail('basis_required', tr(`${level ?? '未声明等级'} 的交付由你自己判:写清交付凭什么成立(basis)——引用了哪个产物里的哪个事实,必须能被复查。`, `At ${level ?? 'an undeclared level'} you judge the delivery yourself: write why it holds (basis), citing which fact in which output, so it can be checked.`))
4380
+ return fail('basis_required', tr(`${level ?? '未声明等级'} 的交付由你自己判:写清交付成立的依据(basis)——引用了哪个产物里的哪个事实,必须能被复查。`, `At ${level ?? 'an undeclared level'} you judge the delivery yourself: write why it holds (basis), citing which fact in which output, so it can be checked.`))
3556
4381
  }
3557
4382
  const given = Array.isArray(args.results) ? args.results : []
3558
4383
  const byId = new Map()
@@ -3632,6 +4457,10 @@ export function apply(ctx, config = {}) {
3632
4457
  * **交付成立 ⇒ 这一步完成**,不论结果是支持、推翻还是说不清。
3633
4458
  * 交付本身(谁判的、凭什么、出处)记在推进这条事实上;判断的状态由证据算。
3634
4459
  */
4460
+ if (deliveredAudit && evaluator === 'independent') for (const result of results) {
4461
+ const hypothesis = state.hypotheses.find((row) => row.id === result.hypothesis)
4462
+ if (result.verdict === 'support' && hypothesis?.retests) confirmRechecks(sessionId, hypothesis.retests, hypothesis, deliveredAudit, state)
4463
+ }
3635
4464
  mutations.push({ t: 'step/advanced', plan: plan.id, step: step.id, evidence: evidenceIds, evaluator, basis, refs: originInfo.paths, origins: originInfo.origins })
3636
4465
  mutations.push({ t: 'block/cleared', plan: plan.id, step: step.id })
3637
4466
  const outcome = results.length === 0 ? '' : `\n${tr('结果:', 'Results: ')}${results.map((item) => `${quote(handleById(state, item.hypothesis))}${tr('', ' ')}${verdictWord(item.verdict)}`).join(tr(';', '; '))}${tr('。', '.')}`
@@ -3674,17 +4503,19 @@ export function apply(ctx, config = {}) {
3674
4503
  defineTool({
3675
4504
  name: 'Anomaly',
3676
4505
  description:
3677
- '未解释项(反常):和预期或本体对不上的观测、说不通的读数。`action="open"` 登记一条(给 `what`,可选 `anchor`);`action="resolve"` 给它一个去处(给 `id`、`outcome` 与 `reason`):explained = 被一条判断、关系或新查到的原因解释了(`by` 写是哪条);ruled_out = 写明理由排除(比如证实是录入错误);escalated = 交给人。不要为了让卡干净而排除:评估者会核排除的理由。',
4506
+ '未解释项(反常)。open:登记一条;resolve:给去处(explained 被解释,ruled_out 写明理由排除,escalated 交给人)。评估者会核排除的理由。',
3678
4507
  parameters: {
3679
4508
  type: 'object',
3680
4509
  properties: {
3681
4510
  action: { type: 'string', enum: ['open', 'resolve'] },
3682
- what: { type: 'string', description: 'action=open:哪里不符——预期什么、实际什么' },
3683
- anchor: { type: 'string', description: 'action=open,可选:在哪个实体或装置上' },
3684
- id: { type: 'string', description: 'action=resolve:哪一条(u-… 的 id)' },
3685
- outcome: { type: 'string', enum: ANOMALY_OUTCOMES, description: 'explained=已解释;ruled_out=排除;escalated=交给人' },
3686
- reason: { type: 'string', description: 'action=resolve:凭什么(解释是什么 / 为什么能排除 / 要人定什么)' },
3687
- by: { type: 'string', description: 'action=resolve,可选:解释它的那条判断、关系或事实' },
4511
+ what: { type: 'string', description: '预测为何、实际为何' },
4512
+ anchor: { type: 'string', description: '可选:在哪个实体或装置上' },
4513
+ touches: { type: 'array', items: { type: 'string' }, description: '可选:涉及的量、判断或事实 id;点名的事实回到待核验' },
4514
+ id: { type: 'string', description: '哪一条(u-…)' },
4515
+ outcome: { type: 'string', enum: ANOMALY_OUTCOMES, description: 'explained / ruled_out / escalated' },
4516
+ reason: { type: 'string', description: '依据' },
4517
+ by: { type: 'string', description: '可选:解释它的判断、关系或事实' },
4518
+ defect: { type: 'boolean', description: '可选:解释是测量或方法缺陷(如探头漂移),记成该实体的缺陷条目' },
3688
4519
  },
3689
4520
  required: ['action'],
3690
4521
  additionalProperties: false,
@@ -3696,8 +4527,8 @@ export function apply(ctx, config = {}) {
3696
4527
  const { hostService, sessionId, state, mutations } = call
3697
4528
  const done = finish(hostService, sessionId, mutations)
3698
4529
  if (args.action === 'open') {
3699
- const opened = openAnomalies(sessionId, [{ what: args.what, anchor: args.anchor }], { step: firstOpenStep(activePlanOf(state))?.id ?? null, by: 'model' })
3700
- if (opened.length === 0) return fail('what_required', tr('要写哪里不符:预期什么、实际什么。', 'Say what does not fit: what was expected and what was seen.'))
4530
+ const opened = openAnomalies(sessionId, [{ what: args.what, anchor: args.anchor, touches: args.touches }], { step: firstOpenStep(activePlanOf(state))?.id ?? null, by: 'model' })
4531
+ if (opened.length === 0) return fail('what_required', tr('要写预测为何、实际为何。', 'Say what does not fit: what was expected and what was seen.'))
3701
4532
  mutations.push(...opened)
3702
4533
  return done({ ok: true, code: 'anomaly_opened', message: tr(`已登记未解释 ${opened[0].id}。它挂在卡上,直到被解释、排除或交给人。`, `Unexplained item ${opened[0].id} recorded. It stays on the card until explained, ruled out or handed to a person.`) })
3703
4534
  }
@@ -3708,9 +4539,10 @@ export function apply(ctx, config = {}) {
3708
4539
  if (target === undefined) return fail('unknown_anomaly', tr(`没有这条开着的未解释:${wanted || '(没给 id)'}。开着的:${known.map((item) => `${item.id}(${clip(item.what, 30)})`).join('、') || '(没有)'}`, `No open unexplained item ${wanted || '(no id given)'}. Open ones: ${known.map((item) => `${item.id} (${clip(item.what, 30)})`).join(', ') || '(none)'}`))
3709
4540
  if (!ANOMALY_OUTCOMES.includes(args.outcome)) return fail('outcome_required', tr('outcome 只能是 explained / ruled_out / escalated。', 'outcome must be explained, ruled_out or escalated.'))
3710
4541
  const reason = String(args.reason ?? '').trim()
3711
- if (reason.length < 4) return fail('reason_required', tr('要写凭什么:解释是什么、为什么能排除、或要人定什么。', 'Say on what grounds: the explanation, why it can be ruled out, or what a person must decide.'))
4542
+ if (reason.length < 4) return fail('reason_required', tr('须写明依据:解释是什么、为何可以排除,或需要人决定什么。', 'Say on what grounds: the explanation, why it can be ruled out, or what a person must decide.'))
3712
4543
  const by = String(args.by ?? '').trim()
3713
- mutations.push({ t: 'anomaly/resolved', id: target.id, outcome: args.outcome, reason: reason.slice(0, 600), ...(by === '' ? {} : { by: by.slice(0, 120) }) })
4544
+ const defect = args.outcome === 'explained' && args.defect === true
4545
+ mutations.push({ t: 'anomaly/resolved', id: target.id, outcome: args.outcome, reason: reason.slice(0, 600), ...(by === '' ? {} : { by: by.slice(0, 120) }), ...(defect ? { defect: true } : {}) })
3714
4546
  const word = { explained: tr('已解释', 'explained'), ruled_out: tr('已排除', 'ruled out'), escalated: tr('交给人', 'handed to a person') }[args.outcome]
3715
4547
  return done({
3716
4548
  ok: true,
@@ -3768,7 +4600,7 @@ export function apply(ctx, config = {}) {
3768
4600
  */
3769
4601
  if (factMutations.length > 0) sections.push({ name: 'clearai/mutations', text: JSON.stringify({ mutations: factMutations }) })
3770
4602
  return {
3771
- id: `clearai-notice-${payload.turn}-${payload.step}-${Date.now().toString(36)}`,
4603
+ id: `clearai-notice-${payload.turn}-${payload.step}-${randomUUID()}`,
3772
4604
  role: 'user',
3773
4605
  content: text(note),
3774
4606
  source: { kind: MESSAGE_SOURCE_KIND, form: 'snapshot', sections },
@@ -3789,18 +4621,56 @@ export function apply(ctx, config = {}) {
3789
4621
  const key = String(id ?? '').trim()
3790
4622
  if (!/^[A-Za-z0-9_-]+$/.test(key)) return null
3791
4623
  const own = (state.facts ?? []).find((fact) => fact.id === key)
3792
- if (own !== undefined) return own
4624
+ if (own !== undefined) {
4625
+ try { return { ...own, ...JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${key}.json`), 'utf8')) } } catch { return own }
4626
+ }
3793
4627
  const cwd = sessionCwd(sessionId)
3794
4628
  if (cwd === null) return null
3795
4629
  try {
3796
4630
  const data = JSON.parse(readFileSync(join(cwd, 'clear', 'knowledge', 'facts', `${key}.json`), 'utf8'))
3797
4631
  if (String(data?.id ?? '') !== key || typeof data?.text !== 'string') return null
3798
- return { id: key, text: data.text, hypothesis: data.hypothesis ?? null, review: data.review ?? null, foreign: true }
4632
+ return { ...data, id: key, text: data.text, hypothesis: data.hypothesis ?? null, review: data.review ?? null, scope: data.scope ?? null, scope_spec: normalizeScope(data.scope_spec), foreign: true }
3799
4633
  } catch {
3800
4634
  return null
3801
4635
  }
3802
4636
  }
3803
4637
 
4638
+ /** 事实文件上记一条疑问(引用它的判断被推翻):事实回到待核验,人复核后解除。 */
4639
+ function markFactQuestioned(cwd, fact, challenge) {
4640
+ if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4641
+ const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4642
+ try {
4643
+ if (!existsSync(file)) return null
4644
+ const data = JSON.parse(readFileSync(file, 'utf8'))
4645
+ const at = Date.now()
4646
+ data.challenges = [...(Array.isArray(data.challenges) ? data.challenges : []), { hypothesis: challenge.hypothesis ?? null, verdict: challenge.verdict ?? null, basis: challenge.basis ?? null, at }]
4647
+ data.history = [...(Array.isArray(data.history) ? data.history : []), { event: 'questioned', at, reason: challenge.basis ?? null }]
4648
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4649
+ return file
4650
+ } catch (error) {
4651
+ ctx.logger?.warn?.(`clearai kernel: 事实疑问记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
4652
+ return null
4653
+ }
4654
+ }
4655
+
4656
+ /** 事实文件上记一处边界(在哪里不成立),事实本身保持成立。 */
4657
+ function markFactBounded(cwd, fact, bound) {
4658
+ if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4659
+ const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4660
+ try {
4661
+ if (!existsSync(file)) return null
4662
+ const data = JSON.parse(readFileSync(file, 'utf8'))
4663
+ const at = Date.now()
4664
+ data.boundaries = [...(Array.isArray(data.boundaries) ? data.boundaries : []), { verdict: bound.verdict, reasons: bound.reasons, basis: bound.basis ?? null, at }]
4665
+ data.history = [...(Array.isArray(data.history) ? data.history : []), { event: bound.verdict, at, reason: bound.basis ?? null }]
4666
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4667
+ return file
4668
+ } catch (error) {
4669
+ ctx.logger?.warn?.(`clearai kernel: 事实边界记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
4670
+ return null
4671
+ }
4672
+ }
4673
+
3804
4674
  function markFactReviewed(cwd, fact, review) {
3805
4675
  if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
3806
4676
  const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
@@ -3812,6 +4682,7 @@ export function apply(ctx, config = {}) {
3812
4682
  const decision = review.retracted ? 'retracted' : 'kept'
3813
4683
  data.status = review.retracted ? 'retracted' : 'established'
3814
4684
  data.review = { decision, reason, at, by: 'user' }
4685
+ if (!review.retracted) data.rechecks = (data.rechecks ?? []).map((item) => item.status === 'pending' && (fact.rechecks ?? []).some((known) => known.id === item.id) ? { ...item, status: 'resolved', resolution: { by: 'user', reason, at } } : item)
3815
4686
  data.history = [...(Array.isArray(data.history) ? data.history : []), { event: decision, at, reason }]
3816
4687
  writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3817
4688
  return file
@@ -3863,7 +4734,7 @@ export function apply(ctx, config = {}) {
3863
4734
  * `ontology` 里**模型可写**的是三支本体目录(`concepts` / `relations` / `entities`);
3864
4735
  * 字段定义 `SCHEMA.json` 与过程本体那份货架仍归系统。
3865
4736
  */
3866
- const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'knowledge', 'lessons'], ['clear', 'goals'], ['clear', 'ontology']]
4737
+ const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'knowledge', 'lessons'], ['clear', 'knowledge', 'negatives'], ['clear', 'goals'], ['clear', 'ontology']]
3867
4738
  const OPEN_REL = ONTOLOGY_BRANCH_DIRS.map((branch) => ['clear', 'ontology', branch])
3868
4739
 
3869
4740
  /** 工作区内的相对路径(正斜杠);在工作区外或取不到工作区返回 null。 */
@@ -3975,8 +4846,8 @@ export function apply(ctx, config = {}) {
3975
4846
  const step = firstOpenStep(plan)
3976
4847
  const asked = await askHuman(exec, {
3977
4848
  id: `release-cmd-${String(exec.callId ?? Date.now().toString(36))}`,
3978
- header: tr('不可逆动作要人放行', 'Irreversible action needs release'),
3979
- question: tr(`这条命令是声明过的不可逆动作「${clip(action.action, 60)}」。放行吗?`, `This command is a declared irreversible action ("${clip(action.action, 60)}"). Release it?`),
4849
+ header: tr('不可逆动作须经人工批准', 'Irreversible action needs approval'),
4850
+ question: tr(`此命令属于已声明的不可逆动作「${clip(action.action, 60)}」。是否批准执行?`, `This command is a declared irreversible action ("${clip(action.action, 60)}"). Release it?`),
3980
4851
  detail: clip(command, 300),
3981
4852
  options: [
3982
4853
  { label: choiceLabel('releaseCommand'), description: tr('让它执行。', 'Let it run.') },
@@ -3991,8 +4862,8 @@ export function apply(ctx, config = {}) {
3991
4862
  return {
3992
4863
  kind: 'deny',
3993
4864
  reason:
3994
- tr(`「${action.action}」是不可逆动作,这次没有放行(${why})。不要换个写法绕过去:等人放行,或改计划。`, `"${action.action}" is irreversible and was not released this time (${why}). Do not rewrite the command to get around this: wait for a person, or change the plan.`) +
3995
- (asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`不可逆动作「${action.action}」等人放行。`, `The irreversible action "${action.action}" waits for a person to release it.`))),
4865
+ tr(`「${action.action}」是不可逆动作,本次未获批准(${why})。不要改写命令以绕过此限制:等待人工批准,或修改计划。`, `"${action.action}" is irreversible and was not released this time (${why}). Do not rewrite the command to get around this: wait for a person, or change the plan.`) +
4866
+ (asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`不可逆动作「${action.action}」等待人工批准。`, `The irreversible action "${action.action}" waits for a person to release it.`))),
3996
4867
  }
3997
4868
  }
3998
4869
 
@@ -4035,7 +4906,7 @@ export function apply(ctx, config = {}) {
4035
4906
  if (suspect !== null) {
4036
4907
  return {
4037
4908
  kind: 'deny',
4038
- reason: tr(`${suspect} 由系统所有,做的人不能写(clear/evidence、clear/knowledge/facts、clear/knowledge/lessons、clear/goals、clear/ontology 的 SCHEMA.json 与货架)。事实与经验只由独立评估之后的结案写;本体请写在 clear/ontology/concepts、relations、entities 下。`, `${suspect} is owned by the system and the worker cannot write it (clear/evidence, clear/knowledge/facts, clear/knowledge/lessons, clear/goals, and SCHEMA.json and the shelf in clear/ontology). Facts and lessons are written only when a goal concludes after independent evaluation; write the ontology under clear/ontology/concepts, relations and entities.`),
4909
+ reason: tr(`${suspect} 由系统所有,做的人不能写(clear/evidence、clear/knowledge/facts、clear/knowledge/lessons、clear/knowledge/negatives、clear/goals、clear/ontology 的 SCHEMA.json 与货架)。事实与经验只由独立评估之后的结案写,负向条目由系统从账本生成;本体请写在 clear/ontology/concepts、relations、entities 下。`, `${suspect} is owned by the system and the worker cannot write it (clear/evidence, clear/knowledge/facts, clear/knowledge/lessons, clear/knowledge/negatives, clear/goals, and SCHEMA.json and the shelf in clear/ontology). Facts and lessons are written only when a goal concludes after independent evaluation, and negative items are generated by the system from the ledger; write the ontology under clear/ontology/concepts, relations and entities.`),
4039
4910
  }
4040
4911
  }
4041
4912
  if (writing && hostService !== undefined) {
@@ -4061,6 +4932,29 @@ export function apply(ctx, config = {}) {
4061
4932
  // ═══ 每回合派生的运行态卡 ═══════════════════════════════════════════════
4062
4933
 
4063
4934
  const lastCard = new Map()
4935
+ /**
4936
+ * **卡只发变化**:卡变了,只发与上次不同的行(上次的卡还在上下文里);
4937
+ * 第一次、变化超过一半、或连续发了 `CARD_FULL_EVERY` 次差异之后,发整张——
4938
+ * 长会话里早先的整张卡可能已被压缩掉,隔一段补一张整的。
4939
+ */
4940
+ const CARD_FULL_EVERY = 6
4941
+ const cardDeltas = new Map()
4942
+ function cardText(sessionId, card, { full = false } = {}) {
4943
+ const previous = lastCard.get(sessionId)
4944
+ lastCard.set(sessionId, card)
4945
+ const lines = card.split('\n')
4946
+ const before = new Set(typeof previous === 'string' ? previous.split('\n') : [])
4947
+ const changed = lines.filter((line) => line.trim() !== '' && !before.has(line))
4948
+ const sent = cardDeltas.get(sessionId) ?? 0
4949
+ if (full || typeof previous !== 'string' || sent >= CARD_FULL_EVERY || changed.length * 2 > lines.length) {
4950
+ cardDeltas.set(sessionId, 0)
4951
+ return card
4952
+ }
4953
+ /** 只少了几行(例如一次性的判据全文):上次的卡已经说过,不必再发。 */
4954
+ if (changed.length === 0) return ''
4955
+ cardDeltas.set(sessionId, sent + 1)
4956
+ return `${tr('【状态卡变化】只列与上次不同的行,其余不变:', '[Status card changes] only lines that differ from last time; the rest is unchanged:')}\n${changed.join('\n')}`
4957
+ }
4064
4958
  /**
4065
4959
  * **判据全文只在修订后注入一次**(每个会话记最后一次发过的修订号)。
4066
4960
  *
@@ -4188,6 +5082,13 @@ export function apply(ctx, config = {}) {
4188
5082
  } catch (error) {
4189
5083
  ctx.logger?.warn?.(`clearai: 事实货架重写失败 ${String(error?.message ?? error).slice(0, 160)}`)
4190
5084
  }
5085
+ /** 负向条目的兜底:上一拍工具结果之后没写成的(读面掉线、工具抛错),这一拍补写。 */
5086
+ try {
5087
+ const preview = factMutations.length > 0 ? previewOf(hostService, sessionId, factMutations) : null
5088
+ writeBack(sessionId, preview?.state ?? hostService.state(sessionId), preview?.derived ?? hostService.derive(sessionId))
5089
+ } catch (error) {
5090
+ ctx.logger?.warn?.(`clearai: 负向条目回写失败 ${String(error?.message ?? error).slice(0, 160)}`)
5091
+ }
4191
5092
 
4192
5093
  /**
4193
5094
  * 无卡通道的注记 = 卡里那几句(工作区、本体、事实货架)。
@@ -4241,7 +5142,11 @@ export function apply(ctx, config = {}) {
4241
5142
  if (extraSections.length === 0 && ontologyPayload === null && factMutations.length === 0) return decision
4242
5143
  return { kind: 'enter', messages: [...decision.messages, pluginNotice(payload, noticeNote, factMutations, ontologyPayload)] }
4243
5144
  }
4244
- lastCard.set(sessionId, card)
5145
+ const shown = cardText(sessionId, card, { full: autoRound !== null })
5146
+ if (shown === '') {
5147
+ if (extraSections.length === 0 && ontologyPayload === null && factMutations.length === 0) return decision
5148
+ return { kind: 'enter', messages: [...decision.messages, pluginNotice(payload, noticeNote, factMutations, ontologyPayload)] }
5149
+ }
4245
5150
  return {
4246
5151
  kind: 'enter',
4247
5152
  messages: [
@@ -4249,7 +5154,7 @@ export function apply(ctx, config = {}) {
4249
5154
  {
4250
5155
  id: `clearai-card-${payload.turn}-${payload.step}-${Date.now().toString(36)}`,
4251
5156
  role: 'user',
4252
- content: text(card),
5157
+ content: text(shown),
4253
5158
  source: {
4254
5159
  kind: MESSAGE_SOURCE_KIND,
4255
5160
  form: 'snapshot',
@@ -4296,105 +5201,138 @@ export function apply(ctx, config = {}) {
4296
5201
  * 把这几件工具的说明换成下面这份。键是参数的路径(`items` 表示数组元素)。
4297
5202
  */
4298
5203
  const STEP_TEXT_EN = {
4299
- id: 'Stable id (letters, digits, underscore, hyphen)',
4300
- do: 'What this step does',
4301
- artifacts: 'What counts as proof: concrete output file paths relative to the workspace (a directory is not proof)',
4302
- done_criteria: 'Criterion: written before the result exists, and checkable',
4303
- 'tests.hypotheses': 'Which judgments this step tests: their short names (claim text also works). When one observation decides several competing judgments (a comparison step), list them all',
4304
- 'tests.level': 'L2 = self-judged (you write the results and basis); L3 = independent evaluation (the system dispatches an evaluator); L4 = released by a person (unrepeatable or external evidence, a person first)',
4305
- expect: 'Optional, written before acting: what you expect this step to show (a number or a direction if you can), and where the expectation comes from (which ontology relation, lesson or judgment, or plainly intuition). Written down, a miss becomes visible',
5204
+ id: 'Stable id',
5205
+ do: 'What it does',
5206
+ artifacts: 'Output file paths that serve as proof (relative to the workspace; not a directory)',
5207
+ done_criteria: 'Criterion: written before the result exists, checkable',
5208
+ 'tests.hypotheses': 'Which judgments it tests (short names); list all competing judgments in a comparison step',
5209
+ 'tests.level': 'L2 self-judged; L3 independent evaluation; L4 released by a person (unrepeatable or external evidence)',
5210
+ expect: 'Optional, before acting: what you expect to see (a number or a direction)',
5211
+ serves: 'Optional: which question or area id it serves',
5212
+ predictions: 'Optional, before acting: what each candidate predicts; if all predict the same, choose another test',
5213
+ 'predictions.items.hypothesis': 'Short name of the judgment',
5214
+ 'predictions.items.expect': 'What you expect to see',
4306
5215
  }
4307
5216
  const prefixed = (prefix, table) => Object.fromEntries(Object.entries(table).map(([key, value]) => [`${prefix}${key}`, value]))
4308
5217
  const TOOL_TEXT_EN = {
4309
5218
  Frame: {
4310
5219
  description:
4311
- 'Set or revise the contract: attach to the current native goal the criteria for "what counts as answered" (done_criteria) and candidate judgments (each a one-sentence claim plus "what result would refute it"). If there is no native goal, one is created, named by the goal headline; continuing and pausing are handled by the native goal. A revision needs a reason; the version goes up by one and every old value stays in the log; changing the criteria text needs an independent verdict. Irreversible actions go in irreversible (a matching command needs release by a person before it runs). Only one goal is open at a time; it spans plans, and each plan carries one phase of it.',
5220
+ 'Frame or revise the goal: criteria (done_criteria) and candidate judgments (a one-sentence claim plus a refutation condition). Creates a native goal if there is none. A revision needs a reason, bumps the version and keeps the old values; changing the criteria text needs an independent verdict (criteria_verdict). One goal at a time; it spans plans.',
4312
5221
  params: {
4313
- headline: 'One-sentence goal (≤120 CJK characters or about 240 letters): the line repeated on the card, the panel and continuation notes. Required the first time',
4314
- claim: 'Goal: the question the project answers (may be long; where identity and criteria attach)',
4315
- done_criteria: 'What counts as answered: checkable criteria with at least one countable form (a number, a count, "a file exists")',
4316
- legacy: 'Migrating an old session: lets long text and a missing headline through once (do not use for new goals)',
4317
- criteria: 'Criteria, one per line (each a sentence with a countable or checkable form such as "a file exists"). If given, they are recorded item by item; otherwise the full done_criteria text is used',
4318
- criteria_note: 'Background for the criteria (not part of the verdict; only explains why)',
4319
- criteria_verdict: 'Independent verdict auditKey required when changing the criteria text: "what counts as done" cannot be changed in passing',
5222
+ headline: 'The goal in one sentence (≤120 characters); required the first time',
5223
+ claim: 'The question the goal answers',
5224
+ done_criteria: 'What counts as answered: checkable, with at least one countable form (a number, a count, a file that exists)',
5225
+ legacy: 'Migration of old sessions only',
5226
+ criteria: 'Optional: the criteria one by one; otherwise the full done_criteria text is used',
5227
+ criteria_note: 'Background for the criteria; not part of the verdict',
5228
+ criteria_verdict: 'The independent verdict auditKey for changing the criteria text',
4320
5229
  promote_at_level: 'Promotion threshold (default L3)',
4321
- irreversible: 'Irreversible actions: the ones that cannot be taken back or whose results cannot be repeated (a pilot run, an order, a message sent out). For each, one line and its command signature (text that always appears in such a command). A matching command needs release by a person before it runs. Omitting this when revising keeps the previous list',
4322
- 'irreversible.items.action': 'One line: what this action is',
4323
- 'irreversible.items.command': 'Command signature: text that always appears in such a command (e.g. "reactor.mjs state.json pilot")',
4324
- hypotheses:
4325
- 'Candidate judgments: each a one-sentence claim plus a refutation condition, one thing per judgment (split "A, and B" into two); may carry **typed assertions** (optional, strictly checked when given: predicates and concepts must exist, object forms must fit the range, no contradiction within one fact). Leaving out assertions is fine; they add, they do not gate. When revising the goal, omitting this keeps the judgments; passing it gives this version\'s full list, and any judgment not listed is recorded as replaced.',
4326
- 'hypotheses.items.name': 'Short name, within about 12 CJK characters or 20-odd letters, chosen by you (e.g. "python3 runs"). Use this name whenever you mention or reference the judgment in other tools',
4327
- 'hypotheses.items.retests': 'Which fact already in long-term knowledge this judgment re-tests: the fact id (the file name in clear/knowledge/facts/<id>.json). Copy that fact\'s original statement as the claim and test it again on new data; do not write "it is refuted" as the claim. When this judgment is refuted, the system asks a person on the spot whether to retract or keep that fact, including facts left by other sessions',
4328
- 'hypotheses.items.assertions': 'Assertions: subject, predicate, object (ids from the domain vocabulary)',
4329
- reason: 'Required when revising the goal: one sentence on why (not needed the first time)',
5230
+ irreversible: 'Irreversible or unrepeatable actions you actually plan to execute; matching commands need human approval. Do not put prohibitions, criteria, or read-only checks here; use [] when there are no such actions. Omitted on revision = unchanged',
5231
+ 'irreversible.items.action': 'What the action is',
5232
+ 'irreversible.items.command': 'Distinctive command text including the operation and arguments; not a bare directory path or generic interpreter name, which would also match read-only checks',
5233
+ mode: 'survey = broad survey; solve = targeted solving; survey_then_solve = survey, then solve',
5234
+ questions: 'Optional: questions to answer. Questions found while surveying get status="emergent"; a person moves them to open or parked. On revision, a given list is the full list',
5235
+ 'questions.items.id': 'Short id (e.g. q1)',
5236
+ 'questions.items.text': 'The question in one sentence',
5237
+ 'questions.items.status': 'open = being answered; emergent = awaiting a decision; parked = deferred',
5238
+ 'questions.items.area': 'Optional: survey area id',
5239
+ areas: 'Survey areas (for a broad survey)',
5240
+ about: 'Ids of the entities or quantities involved (e.g. "R-2", "yield"): used to locate existing items, and items left by this run attach to them',
5241
+ conditions: 'This run\'s conditions, e.g. {"line": "L2", "month": "2026-09"}; the default scope of judgments and the basis of the applicability check',
5242
+ ontology: 'Optional: ontology entries, checked and written to clear/ontology/ (fields in SCHEMA.json); the same id replaces',
5243
+ 'ontology.concepts': '{id, label, gloss, kind: category|measure|phenomenon, unit?}',
5244
+ 'ontology.relations': '{id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape?, check?}',
5245
+ hypotheses: 'Candidate judgments, one thing each. Omitted on revision = unchanged; given = the full list, and any not listed is recorded as replaced',
5246
+ 'hypotheses.items.name': 'Short name (≤ about 20 letters); use it to refer to the judgment later',
5247
+ 'hypotheses.items.question': 'Optional: question or area id',
5248
+ 'hypotheses.items.about': 'Optional: entity or quantity ids; defaults to the framing about',
5249
+ 'hypotheses.items.uses': 'Optional: ids of existing items it relies on (file names under clear/knowledge/); the system checks on the spot whether they apply',
5250
+ 'hypotheses.items.use': 'Optional: id of the re-runnable computation behind it, registered at clear/models/<id>.json (command, inputs, output, tolerance, optional baseline); when its inputs change, the system re-runs it and compares when the item is cited',
5251
+ 'hypotheses.items.scope': 'Optional: where it holds. conditions gives conditions, ranges value ranges (e.g. {"temperature": [150, 175]}), note one sentence; defaults to the framing conditions',
5252
+ 'hypotheses.items.retests': 'Optional: which existing fact it re-tests (fact id). Copy the original claim; if refuted, the system asks a person to retract or keep the fact',
5253
+ 'hypotheses.items.assertions': 'Optional: subject–predicate–object assertions (ontology ids), strictly checked when given',
5254
+ reason: 'Required on revision: what changed and why',
4330
5255
  },
4331
5256
  },
4332
5257
  Conclude: {
4333
5258
  description:
4334
- 'Conclude: hand the goal in for acceptance. This is the only way to complete a goal (the native "complete goal" is refused). The system **always** dispatches an independent evaluator to check the goal criteria and transcription fidelity item by item; only when the criteria are met does the goal conclude as achieved: the native goal is marked complete; the evaluator also judges each live judgment, and those it supports (or that already reached the threshold) are promoted to facts; and the outputs accepted by each step are declared as a deliverables card; lessons proposed with the conclusion (`lessons`) are checked one by one, and supported ones are written to clear/knowledge/lessons/. Otherwise the goal stays open and the gaps come back. **Order**: before achieved, close the plan first (`ClosePlan`). Abandoning (`abandoned`) is not limited by this: the native goal is marked blocked with the reason, and a person decides whether to end it.',
5259
+ 'Conclude: the only way to complete the goal (the native "complete goal" is refused). The system dispatches an independent evaluator to check the criteria one by one: only if they are met does the goal conclude as achieved; judgments the evaluator supports are promoted to facts, and supported lessons are written to clear/knowledge/lessons/. Otherwise the goal stays open and the gaps come back. ClosePlan before achieved. On abandoned, state the blocker; a person decides whether to end it.',
4335
5260
  params: {
4336
- outcome: 'achieved = criteria met; abandoned = give up after stating the blocker honestly',
5261
+ outcome: 'achieved = criteria met; abandoned = give up after stating the blocker',
5262
+ answers: 'On achieved, one per question. Candidates still being examined and open unexplained items go in open with their effect',
5263
+ 'answers.items.question': 'Question id; omit when the goal lists no questions',
5264
+ 'answers.items.conclusion': 'One or two sentences with values and the conditions where they hold',
5265
+ 'answers.items.uses': 'Knowledge entry IDs directly used by this final answer; framing references are not inherited',
5266
+ 'answers.items.scope': 'Applicable scope of this answer; numeric ranges need units',
5267
+ 'answers.items.basis': 'One line per adopted or excluded candidate or checked reading, naming the source',
5268
+ 'answers.items.open': 'Open points: about = candidate short names, unexplained item ids or question ids; effect = how the conclusion changes if it holds',
5269
+ 'answers.items.decide': 'Decisions for the person',
5270
+ 'answers.items.unanswered': 'Why it could not be answered (conclusion may then be omitted)',
4337
5271
  note: 'Conclusion note',
4338
- lessons: 'Lessons (optional, checked only on achieved): what this run found that changes how to work next time in a similar setting, not a restatement of this run\'s conclusion. The evaluator checks each against the record; supported ones are written to clear/knowledge/lessons/, and later sessions see them when framing and planning',
4339
- 'lessons.items.text': 'One sentence on what to do next time ("check this rig\'s temperature against the reference reading first")',
4340
- 'lessons.items.kind': 'trap = a pitfall; check = a reading or assumption to check first; shortcut = a convenient method that misleads; prior = a prior about this kind of system (e.g. "two factors are often coupled; scan diagonally first")',
4341
- 'lessons.items.about': 'The equipment, quantities or concepts involved (short names, used to match next time)',
4342
- 'lessons.items.evidence': 'Where in this run\'s record it showed (step, file)',
5272
+ lessons: 'Optional: lessons that change how to work next time in a similar setting; written only after the evaluator checks them',
5273
+ 'lessons.items.text': 'One sentence on what to do next time',
5274
+ 'lessons.items.kind': 'trap = pitfall; check = check first; shortcut = misleading shortcut; prior = prior',
5275
+ 'lessons.items.about': 'Ids of the equipment, quantities or concepts involved',
5276
+ 'lessons.items.evidence': 'Where the record shows it',
4343
5277
  'lessons.items.boundary': 'When it does not apply',
4344
5278
  },
4345
5279
  },
4346
5280
  CreatePlan: {
4347
5281
  description:
4348
- 'Make a plan for a complex task. Each step says in one sentence what it does (do), what counts as proof (artifacts), and its criterion (done_criteria, written before the result exists); it may carry an expectation (expect: what you expect to see and where that comes from). Steps that test judgments declare tests: {hypotheses, level}: which judgments, at what level (for a step that compares competing routes, list all the competing judgments). At most 25 steps. Once made, the plan is locked: on a local setback change the current step, do not start over.',
5282
+ 'Make a plan: each step gives what it does (do), which file is its proof (artifacts) and its criterion (done_criteria, written before the result exists). Steps that test judgments use tests:{hypotheses, level}. At most 25 steps; after a local setback change the current step, do not start over.',
4349
5283
  params: {
4350
- brief: `Plan description for people (Markdown, suggested ≥${MIN_BRIEF_CHARS} characters, at least two ## sections)`,
5284
+ brief: `Plan description for people (Markdown, ≥${MIN_BRIEF_CHARS} characters, at least two ## sections)`,
4351
5285
  ...prefixed('steps.items.', STEP_TEXT_EN),
4352
5286
  },
4353
5287
  },
4354
5288
  RevisePlan: {
4355
5289
  description:
4356
- 'Change the current plan without moving progress (returns progress_changed=false). Four actions: `action="expect"` writes the expectation for a step not yet done (give `step_id` and `expect`: write it before acting, so a miss is visible); `action="add"` adds a step (add missing work; give `step`); `action="refine"` refines a step\'s criterion (give `step_id` and the new `done_criteria`; the old one stays in the log); `action="void"` voids a step with a reason (give `step_id` and `reason`: if a step should not exist, void it and say why. Voiding on the record is honest; fabricating evidence to finish is not. A delivered step cannot be voided).',
5290
+ 'Change the plan without moving progress. expect: write predictions for a step not yet run (step_id + expect or predictions); add: add a step (step); refine: change a step\'s criterion (step_id + done_criteria); void: void a step with a reason (step_id + reason; a delivered step cannot be voided).',
4357
5291
  params: {
4358
- action: 'expect = write the expectation; add = add a step; refine = change the criterion; void = void with a reason',
4359
- expect: 'action=expect: what you expect to see, and where it comes from (relation / lesson / judgment, or intuition)',
4360
- step: 'action=add: the new step',
4361
- ...prefixed('step.', STEP_TEXT_EN),
4362
- step_id: 'action=expect / refine / void: which step',
5292
+ action: 'expect / add / refine / void',
5293
+ expect: 'action=expect: what you expect to see',
5294
+ predictions: 'action=expect: per-candidate predictions',
5295
+ 'predictions.items.hypothesis': 'Short name of the judgment',
5296
+ 'predictions.items.expect': 'What you expect to see',
5297
+ step: 'action=add: the new step, same fields as a CreatePlan step',
5298
+ step_id: 'Which step',
4363
5299
  done_criteria: 'action=refine: the new criterion',
4364
- reason: 'Why (required for action=void)',
5300
+ reason: 'Why (required for void)',
4365
5301
  },
4366
5302
  },
4367
5303
  ClosePlan: {
4368
- description: 'Close the current phase: archive this plan. If the goal is not achieved yet, the system wakes you to start the next phase.',
4369
- params: { summary: 'Closing words: what this phase achieved' },
5304
+ description: 'Close and archive the current plan; if the goal is not achieved, start the next phase.',
5305
+ params: { summary: 'What this phase achieved' },
4370
5306
  },
4371
5307
  AdvancePlan: {
4372
5308
  description:
4373
- 'Deliver a step (the only completion verb): hand in the observations. The system first runs intake: declared outputs exist, are non-empty and well-formed; intake only accepts or rejects, it does not judge. If the delivery holds, the step is complete, whether the judgments it tests were supported, refuted or left unclear; **all count as complete**, and the results are recorded separately as evidence. Whatever does not match the expectation goes in anomalies. At L2 (self-judged) you give the basis (why the delivery holds, checkable) and results (one entry per judgment the step tests); at L3 and above both are judged by an independent evaluator the system dispatches, and results you write are refused. Without proof it is not complete; there is no manual marking.',
5309
+ 'Deliver a step: the only completion action. The system first checks that declared outputs exist, are non-empty and well-formed. If the delivery holds, the step is complete, whether the judgments were supported, refuted or left unclear; results are recorded separately as evidence. At L2 you give basis and results; from L3 an independent evaluator judges, and results you write are refused.',
4374
5310
  params: {
4375
- step_id: 'Which step to deliver (only the first unsettled step; this confirms against slips, it does not select)',
4376
- observations: 'Observations: the raw results of this step (path relative to the workspace plus one sentence)',
4377
- anomalies: 'Unexplained: where this step\'s result does not fit the expectation or the ontology, or a reading that makes no sense (one sentence each, saying what does not fit). They stay on the card until explained, ruled out with a reason, or handed to a person (with the Anomaly tool). Do not explain them away',
4378
- 'anomalies.items.what': 'What does not fit: what was expected, what was seen',
4379
- 'anomalies.items.anchor': 'Optional: on which entity or device (entity id or name)',
4380
- basis: 'Why the delivery holds: which fact in which output (must be checkable). Written by you only at L2 (self-judged)',
4381
- results:
4382
- 'L2 (self-judged) only: one entry per judgment this step tests, read against its refutation condition: not met is support, met is refute, and if this observation cannot tell, inconclusive. Refute and inconclusive do not stop the step from completing',
4383
- 'results.items.hypothesis': 'Short name of the judgment (claim text also works)',
4384
- 'results.items.basis': 'One sentence: what this observation shows against the refutation condition (defaults to the basis above)',
5311
+ step_id: 'Which step (must be the first unfinished one)',
5312
+ observations: 'Raw results: path plus one sentence',
5313
+ anomalies: 'Readings that contradict the prediction or the ontology or make no sense, one sentence each; do not explain them away',
5314
+ 'anomalies.items.what': 'What was expected, what was seen',
5315
+ 'anomalies.items.anchor': 'Optional: on which entity or device',
5316
+ 'anomalies.items.touches': 'Optional: quantity, judgment or fact ids; a named fact goes back to pending re-check',
5317
+ basis: 'L2 only: why the delivery holds, citing a specific fact in an output',
5318
+ results: 'L2 only: one entry per tested judgment: support (refutation condition not met) / refute / inconclusive',
5319
+ 'results.items.hypothesis': 'Short name of the judgment',
5320
+ 'results.items.basis': 'What the observation shows against the refutation condition',
4385
5321
  },
4386
5322
  },
4387
5323
  }
4388
5324
  TOOL_TEXT_EN.Anomaly = {
4389
5325
  description:
4390
- 'Unexplained items (anomalies): observations that do not fit the expectation or the ontology, readings that make no sense. `action="open"` records one (give `what`, optionally `anchor`); `action="resolve"` gives it a destination (give `id`, `outcome` and `reason`): explained = a judgment, relation or newly found cause explains it (say which in `by`); ruled_out = ruled out with a stated reason (for example, shown to be a transcription error); escalated = handed to a person. Do not rule things out to keep the card tidy: the evaluator checks the reasons.',
5326
+ 'Unexplained items (anomalies). open: record one (what; optionally anchor, touches); resolve: give it a destination (id, outcome, reason): explained (by = which one; add defect for a measurement or method defect), ruled_out with a stated reason, or escalated to a person. The evaluator checks the reasons for ruling out.',
4391
5327
  params: {
4392
- what: 'action=open: what does not fit: what was expected, what was seen',
4393
- anchor: 'action=open, optional: on which entity or device',
4394
- id: 'action=resolve: which one (the u-… id)',
4395
- outcome: 'explained / ruled_out / escalated (to a person)',
4396
- reason: 'action=resolve: on what grounds (the explanation, why it can be ruled out, what a person must decide)',
4397
- by: 'action=resolve, optional: the judgment, relation or fact that explains it',
5328
+ what: 'What was expected, what was seen',
5329
+ anchor: 'Optional: on which entity or device',
5330
+ touches: 'Optional: quantity, judgment or fact ids; a named fact goes back to pending re-check',
5331
+ id: 'Which one (u-…)',
5332
+ outcome: 'explained / ruled_out / escalated',
5333
+ reason: 'Grounds',
5334
+ by: 'Optional: the judgment, relation or fact that explains it',
5335
+ defect: 'Optional: the explanation is a measurement or method defect (e.g. a drifting probe); recorded as a defect item on that entity',
4398
5336
  },
4399
5337
  }
4400
5338
  /** 按路径把英文说明写进一份参数 schema 的副本。 */
@@ -4425,7 +5363,7 @@ export function apply(ctx, config = {}) {
4425
5363
  for (const toolName of CONTRIB.tools) {
4426
5364
  const definition = TOOL_DEFS.get(toolName)
4427
5365
  // 每一个工具的输出都过一遍统一出口:独立落账通道里的事实不会因为工具抛错/被 abort 而丢。
4428
- ctx.tools.register({ ...definition, execute: (args, exec) => inLanguage(languageOf(String(exec?.agent?.id)), async () => withPendingFacts(exec, await definition.execute(args, exec))) })
5366
+ ctx.tools.register({ ...definition, execute: (args, exec) => inLanguage(languageOf(String(exec?.agent?.id)), async () => afterTool(exec, withPendingFacts(exec, await definition.execute(args, exec)))) })
4429
5367
  }
4430
5368
 
4431
5369
  // 提示词段由当前 ClearAI DSH 预设提供,围绕认识论循环与事实边界组织。