clearai-dsh 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,14 +19,20 @@
19
19
  * P5 什么都不删 → 状态是可重放的投影;refine/void/superseded 的旧值都在
20
20
  */
21
21
 
22
+ import { createTodoMirror } from './native-todos.js'
22
23
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
23
24
  import { tmpdir } from 'node:os'
24
25
 
25
- import { createHash } from 'node:crypto'
26
+ import { createHash, randomUUID } from 'node:crypto'
26
27
  import { AsyncLocalStorage } from 'node:async_hooks'
27
28
  import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
28
29
  import { SECTION_TABLE } from './prompts.js'
29
30
  import { VERIFICATION_LOOP, describeOntology, validateOntology } from './ontology.js'
31
+ import { compareScope, mergeScope, normalizeScope, scopeText, scopeVerdictText } from './scope.js'
32
+ import { citeVerdict, mergeAbout, negativeItems, relatedKnowledge, resolveAbout } from './knowledge-items.js'
33
+ import { auditMaterialDigest, auditPathComponent, contentDigest, fileDigest, methodSnapshot } from './audit-material.js'
34
+ import { nativeAuditSchema, recoveredStructuredOutput } from './audit-schema.js'
35
+ import { MODEL_ID, appendRun, checkModelSpec, compareOutputs, deviationText, needsRerun, numericOutputs } from './models.js'
30
36
 
31
37
  export const name = 'clearai-kernel'
32
38
  /** 宿主注册表 + `clearai` 读面(宿主包提供;缺了会在工具里明确报错,而不是静默不工作)。 */
@@ -121,7 +127,7 @@ const MESSAGE_SOURCE_KIND = 'plugin:clearai'
121
127
  const SELF_REFERENCE = [
122
128
  [/ClosePlan\s*(?:成功|succeed|success)/i, ['判据不得引用「ClosePlan 成功」——那是系统的动作,不是可核对的产物', 'Criteria cannot cite "ClosePlan succeeds": that is a system action, not a checkable output']],
123
129
  [/(?:计划状态|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']],
130
+ [/(?:目标|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
131
  [/(?:本步.{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
132
  [/记录在对话(?:中|里)|recorded in the (?:conversation|chat)/i, ['判据不得是「记录在对话中」——对话不是可复核的产物', 'Criteria cannot be "recorded in the conversation": the conversation is not a checkable output']],
127
133
  [/见上文|see above/i, ['判据不得是「见上文」——评估者读不到你的上下文', 'Criteria cannot be "see above": the evaluator cannot read your context']],
@@ -212,15 +218,19 @@ export const CONFIG_KEYS = [
212
218
  'minHypotheses',
213
219
  'requireCriteriaVerdict',
214
220
  'requireLandedEntities',
215
- 'requireMeasures',
216
221
  'requireAnswers',
217
222
  'bashDenyRules',
218
223
  'auditProvider',
219
224
  'auditTimeoutMs',
225
+ 'auditHardTimeoutMs',
220
226
  'auditToolFilter',
221
227
  'auditRerun',
222
228
  'runtimeCard',
223
229
  'contributions',
230
+ 'applicabilityFeedback',
231
+ 'negativeWriteback',
232
+ 'ontologyFeedback',
233
+ 'nativeTodoProgress',
224
234
  ]
225
235
 
226
236
  /**
@@ -321,6 +331,11 @@ export function apply(ctx, config = {}) {
321
331
  throw new Error('invalid_config:clearai-kernel:blockedThreshold')
322
332
  }
323
333
  const CFG = {
334
+ // Native experimental variants; published ClearAI keeps both enabled.
335
+ applicabilityFeedback: config.applicabilityFeedback !== false,
336
+ negativeWriteback: config.negativeWriteback !== false,
337
+ ontologyFeedback: config.ontologyFeedback === true,
338
+ nativeTodoProgress: config.nativeTodoProgress === true,
324
339
  /**
325
340
  * 连拦阈值:同一件事连续冲闸这么多次没过,计划置 blocked、停下等人。
326
341
  * **它不是预算**:它管的是证据质量,
@@ -345,7 +360,6 @@ export function apply(ctx, config = {}) {
345
360
  * 「测量」关系写明由什么测量、读数如何核对(`check`)。真跑里唯一一条错误事实,正是把设定值回读
346
361
  * 当成了釜温;卡上提醒了几十次「先写本体」也没有用。
347
362
  */
348
- requireMeasures: config.requireMeasures === true,
349
363
  /**
350
364
  * **结论门**(结案;机制缺省关,preset 里开):`achieved` 要按问题给出结论四部分,而且每个还在考察、
351
365
  * 从没得到支持的候选与每条开着的未解释项,都写进「尚未确定的事项」并说明它若成立答案会怎样变。
@@ -355,6 +369,8 @@ export function apply(ctx, config = {}) {
355
369
  bashDenyRules: config.bashDenyRules !== false,
356
370
  auditProvider: config.auditProvider ?? 'spawn',
357
371
  auditTimeoutMs: config.auditTimeoutMs ?? 240000,
372
+ /** 一次评估从派出起最多等多久:超过就如实结成「未知」并放开,不让一次评估拖住整个目标。 */
373
+ auditHardTimeoutMs: config.auditHardTimeoutMs ?? 240000,
358
374
  // 三张脸的**候选**工具名。真正的 face 还要过一道「这个部署里到底有没有这件工具」的过滤
359
375
  // (见 resolveToolFace):`read_image` 只在挂了 `attachments` 的部署里存在,名单里写了它、
360
376
  // 部署里没有,`tools.restrict` 会**直接抛**(未知工具名)→ 评估整条路 fail-closed。
@@ -391,17 +407,43 @@ export function apply(ctx, config = {}) {
391
407
  */
392
408
  const pendingFacts = new Map()
393
409
  const pendingFactIds = new Set()
410
+ const failedFactAppends = new Map()
411
+ function appendFact(sessionId, mutation) {
412
+ const session = ctx.get('sessions')?.get?.(sessionId)
413
+ if (typeof session?.append !== 'function') throw new Error('native session append unavailable')
414
+ const events = session.snapshotEvents?.() ?? session.ownEvents?.() ?? []
415
+ const turn = events.findLast?.((event) => event.type === 'turn/start')?.data?.turn ?? 0
416
+ const handlerId = `clearai-fact-${randomUUID()}`
417
+ // This plugin's internal fact hook is log-only. A user/message here
418
+ // would split an assistant tool-call from its result at the provider.
419
+ session.append('hook/invoked', { turn, point: 'ClearAIFact', dialect: 'clearai', handlerId })
420
+ session.append('hook/result', { turn, point: 'ClearAIFact', handlerId, decision: 'pass', durationMs: 0, notice: pluginNotice({ turn, step: 0 }, '', [mutation]) })
421
+ }
394
422
  /** 把一条事实推进独立落账通道(返回它自己,方便调用方同时塞进工具结果的 mutations)。 */
395
423
  function landFact(sessionId, mutation) {
396
424
  if (mutation === null || typeof mutation !== 'object') return mutation
397
- const key = `${sessionId}:${String(mutation.t)}:${String(mutation.id ?? mutation.step ?? '')}`
425
+ const key = `${sessionId}:${String(mutation.t)}:${String(mutation.id ?? mutation.step ?? '')}:${String(mutation.status ?? '')}`
398
426
  if (pendingFactIds.has(key)) return mutation
399
427
  pendingFactIds.add(key)
400
428
  const list = pendingFacts.get(sessionId) ?? []
401
429
  list.push(mutation)
402
430
  pendingFacts.set(sessionId, list)
431
+ try {
432
+ appendFact(sessionId, mutation)
433
+ } catch (error) {
434
+ const failures = failedFactAppends.get(sessionId) ?? []
435
+ failures.push(mutation); failedFactAppends.set(sessionId, failures)
436
+ ctx.logger?.warn?.(`clearai: fact append failed: ${String(error?.message ?? error)}`)
437
+ }
403
438
  return mutation
404
439
  }
440
+ async function flushFacts(sessionId) {
441
+ const sessions = ctx.get('sessions')
442
+ const failures = failedFactAppends.get(sessionId) ?? []
443
+ for (const mutation of failures) appendFact(sessionId, mutation)
444
+ if (typeof sessions?.flush === 'function' && await sessions.flush(sessions.get(sessionId)) === false) throw new Error('session durability listener unavailable')
445
+ failedFactAppends.delete(sessionId)
446
+ }
405
447
  /** 取出并清空这一拍的兜底事实(只有 pre-step 调;重复取到空数组是正常的)。 */
406
448
  function drainPendingFacts(sessionId) {
407
449
  const list = pendingFacts.get(sessionId) ?? []
@@ -643,8 +685,8 @@ export function apply(ctx, config = {}) {
643
685
  function cardTail(sessionId, preview) {
644
686
  const card = preview?.card ?? null
645
687
  if (card === null || lastCard.get(sessionId) === card) return ''
646
- lastCard.set(sessionId, card)
647
- return `\n\n${card}`
688
+ const shown = cardText(sessionId, card)
689
+ return shown === '' ? '' : `\n\n${shown}`
648
690
  }
649
691
 
650
692
  /** 一次工具调用的收尾:预演变更 → 卡片 → 返回值。 */
@@ -656,13 +698,13 @@ export function apply(ctx, config = {}) {
656
698
  * **卡没变就不附**(第六阶段):回合开头与工具返回共用「上次发过的那张」。
657
699
  * 同一张卡在一轮里重发几遍,只是把同样的话塞给模型几遍——它读得越多,照抄得越多。
658
700
  */
659
- const fresh = card !== null && lastCard.get(sessionId) !== card
660
- if (fresh) lastCard.set(sessionId, card)
701
+ const shown = card !== null && lastCard.get(sessionId) !== card ? cardText(sessionId, card) : ''
702
+ const fresh = shown !== ''
661
703
  const result = {
662
704
  ...value,
663
705
  mutations,
664
706
  card,
665
- 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.)')}`,
707
+ 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.)')}`,
666
708
  }
667
709
  // 输出**越界就裁掉并告警**:宿主会拿 output.schema 校验工具结果,多一个未声明的字段
668
710
  // 会让整个工具调用失败(CreatePlan 曾因此全军覆没)。
@@ -702,7 +744,7 @@ export function apply(ctx, config = {}) {
702
744
  */
703
745
  if (typeof cwd !== 'string' || cwd === '') {
704
746
  result.missing.push(artifact)
705
- continue
747
+ continue
706
748
  }
707
749
  const absolute = isAbsolute(artifact) ? artifact : resolvePath(cwd, artifact)
708
750
  let stat = null
@@ -713,7 +755,7 @@ export function apply(ctx, config = {}) {
713
755
  }
714
756
  if (stat === null) {
715
757
  result.missing.push(artifact)
716
- continue
758
+ continue
717
759
  }
718
760
  if (stat.isDirectory()) {
719
761
  let files = 0
@@ -734,11 +776,11 @@ export function apply(ctx, config = {}) {
734
776
  // 目录在读数期间变化时,仍如实说明它不能作为物证。
735
777
  }
736
778
  result.directories.push(tr(`${artifact}(目录不是物证,含 ${files} 个文件、${bytes} 字节)`, `${artifact} (a directory is not evidence; it holds ${files} files, ${bytes} bytes)`))
737
- continue
779
+ continue
738
780
  }
739
781
  if (stat.size === 0) {
740
782
  result.empty.push(tr(`${artifact}(空文件)`, `${artifact} (empty file)`))
741
- continue
783
+ continue
742
784
  }
743
785
  const lower = artifact.toLowerCase()
744
786
  if (lower.endsWith('.json')) {
@@ -821,11 +863,12 @@ export function apply(ctx, config = {}) {
821
863
  '**纪律:**',
822
864
  '- 只核对不发挥:你的职责是对照标准验收,不是重做方案、不是提改进建议。',
823
865
  '- 你没有写入权限:任何需要产出文件的事都不是你的事。',
866
+ '- 本次裁决发生在系统收下交付/结案之前。本次评估卡、事实升格、目标完成标记都在裁决返回并复核后落盘,此刻尚未出现是正常时序,不是缺失证据。仍须核对已经声称存在的历史记录及实质产物。',
824
867
  '- 你给**两项**裁决,不要混在一起:',
825
868
  ' · **交付成立吗**(`holds`):yes = 判据逐条满足、观测真实;no = 有判据不满足,或观测与记录对不上;unclear = 凭现有材料判不了。',
826
869
  ' · **每条判断的结果**(`results`,这一步检验几条就给几格):对照它的推翻条件读——support = 没碰到推翻条件,refute = 碰到了,inconclusive = 这次观测区分不了。',
827
870
  '- 交付成立与判断被推翻可以同时为真:推翻是有价值的结果,它不让交付失败。不要为了让步骤通过而写 support。',
828
- '- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。没有就给空数组。',
871
+ '- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。结论用到了 clear/knowledge/ 下的已有条目、却没在判断的 uses 里引用的,也写进来(它绕过了适用性判定)。没有就给空数组。',
829
872
  '',
830
873
  '**回包的形状就是你的动作空间(字段长度由 schema 校验,超了会被拒):**',
831
874
  '- `basis` 是**一句话结论**,≤1200 字。**不要在这里写论证**——论证放 `refs`:逐条 `{path, line}` 指到你实际读过的文件与行,让第三方照着就能复核。',
@@ -844,11 +887,12 @@ export function apply(ctx, config = {}) {
844
887
  '**Discipline:**',
845
888
  '- Check, do not improvise: your job is to accept against the criteria, not to redo the work or suggest improvements.',
846
889
  '- You cannot write: anything that needs a file produced is not your job.',
890
+ '- 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.',
847
891
  '- You give **two** verdicts; keep them apart:',
848
892
  ' · **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.',
849
893
  ' · **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.',
850
894
  '- 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.',
851
- '- 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.',
895
+ '- 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.',
852
896
  '',
853
897
  '**The shape of your reply is your action space (field lengths are checked by the schema; overruns are rejected):**',
854
898
  '- `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.',
@@ -912,6 +956,8 @@ export function apply(ctx, config = {}) {
912
956
  additionalProperties: false,
913
957
  },
914
958
  },
959
+ 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 } },
960
+ 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 } },
915
961
  lessons: {
916
962
  type: 'array',
917
963
  description: tr('任务书列了待核的经验(L1、L2……)时,每条各一格;没列就给空数组。', 'When the brief lists lessons to check (L1, L2, ...), one entry each; otherwise an empty array.'),
@@ -1010,6 +1056,8 @@ export function apply(ctx, config = {}) {
1010
1056
  ],
1011
1057
  ),
1012
1058
  ...anomalyBrief(state, gate),
1059
+ ...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.`),
1060
+ ...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.`),
1013
1061
  ...(Array.isArray(gate.extra) && gate.extra.length > 0 ? ['', ...gate.extra] : []),
1014
1062
  '',
1015
1063
  ...tr(
@@ -1065,7 +1113,7 @@ export function apply(ctx, config = {}) {
1065
1113
  const plain = item.trim()
1066
1114
  // 旧形状:一整段散文。**不丢**,但把它按"还没有结构"如实标注,而不是硬塞成三格。
1067
1115
  if (plain !== '') shortfalls.push({ criterion: tr('未结构化(旧式裁决)', 'unstructured (legacy verdict)'), what: plain.slice(0, 400), missing: '' })
1068
- continue
1116
+ continue
1069
1117
  }
1070
1118
  if (item === null || typeof item !== 'object') continue
1071
1119
  const criterion = String(item.criterion ?? '').trim()
@@ -1099,6 +1147,8 @@ export function apply(ctx, config = {}) {
1099
1147
  }
1100
1148
  const basis = typeof value?.basis === 'string' && value.basis.trim() !== '' ? value.basis.trim() : tr('评估者未给出依据', 'the evaluator gave no basis')
1101
1149
  return {
1150
+ 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 ?? '') })),
1151
+ 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 ?? '') })),
1102
1152
  holds,
1103
1153
  results,
1104
1154
  anomalies,
@@ -1222,16 +1272,11 @@ export function apply(ctx, config = {}) {
1222
1272
  if (subagents === undefined) return { ok: false, reason: tr('subagents 服务不可用', 'the subagents service is unavailable'), failures: [] }
1223
1273
  const base = { label: options.label, parent: options.parent, signal: options.signal, prompt: text(options.prompt) }
1224
1274
  const persona = options.persona
1225
- const schema = options.outputSchema ?? undefined
1275
+ const schema = options.outputSchema ? nativeAuditSchema(options.outputSchema) : undefined
1226
1276
  const toolFilter = options.toolFilter ?? null
1227
1277
  const failures = []
1228
- const attempts = []
1229
- if (toolFilter !== null) attempts.push({ variant: { persona, outputSchema: schema, toolFilter }, capability: 'persona+outputSchema+toolFilter' })
1230
- attempts.push({ variant: { persona, outputSchema: schema }, capability: 'persona+outputSchema' })
1231
- if (toolFilter !== null) attempts.push({ variant: { persona, toolFilter }, capability: 'persona+toolFilter' })
1232
- attempts.push({ variant: { persona }, capability: 'persona' })
1233
- if (schema !== undefined) attempts.push({ variant: { outputSchema: schema }, capability: 'outputSchema' })
1234
- attempts.push({ variant: {}, capability: 'prompt-only' })
1278
+ // These are required audit capabilities. An infrastructure rejection must not silently weaken the verdict channel.
1279
+ const attempts = [{ variant: { persona, outputSchema: schema, ...(toolFilter ? { toolFilter } : {}) }, capability: 'persona+outputSchema+toolFilter' }]
1235
1280
  for (const attempt of attempts) {
1236
1281
  try {
1237
1282
  const run = await subagents.start(CFG.auditProvider, { ...base, ...attempt.variant })
@@ -1257,7 +1302,7 @@ export function apply(ctx, config = {}) {
1257
1302
  * 平台边界:宿主的 `sessions` 服务只认**活在当前进程里**的会话(`get(id)`)。
1258
1303
  * 会话不在了就返回 null,由调用方如实记为 unknown——这一层我们不假装能读。
1259
1304
  */
1260
- function recoverFromChildSession(childId) {
1305
+ async function recoverFromChildSession(childId) {
1261
1306
  const sessions = ctx.get('sessions')
1262
1307
  if (sessions === undefined || typeof sessions.get !== 'function') return null
1263
1308
  let session = null
@@ -1274,10 +1319,15 @@ export function apply(ctx, config = {}) {
1274
1319
  session = null
1275
1320
  }
1276
1321
  }
1277
- if (session === null) return null
1278
1322
  let events = []
1279
1323
  try {
1280
- events = typeof session.ownEvents === 'function' ? session.ownEvents() : typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : []
1324
+ if (session !== null) events = typeof session.ownEvents === 'function' ? session.ownEvents() : typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : []
1325
+ else {
1326
+ const query = ctx.get('sessionQuery')
1327
+ if (typeof query?.observeSession !== 'function') return null
1328
+ const observation = await query.observeSession(childId, { projectionMode: 'none' })
1329
+ try { events = [...observation.events] } finally { observation[Symbol.dispose]?.() }
1330
+ }
1281
1331
  } catch {
1282
1332
  return null
1283
1333
  }
@@ -1303,7 +1353,7 @@ export function apply(ctx, config = {}) {
1303
1353
  * 半截文本被当成「回灌过的结论」是这里最危险的假话。两条路形状一致,
1304
1354
  * 「这句话是从哪条路来的」就不再影响账本的可读性。
1305
1355
  */
1306
- 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)}`) }
1356
+ 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)}`) }
1307
1357
  }
1308
1358
 
1309
1359
 
@@ -1327,7 +1377,7 @@ export function apply(ctx, config = {}) {
1327
1377
  * 拿不到目录(服务不在 / 查询失败)时**什么都不做**:不猜、不误伤正在跑的裁决。
1328
1378
  */
1329
1379
  async function sweepEndedAudits(sessionId, state) {
1330
- const pending = (state?.audits ?? []).filter((audit) => audit.verdict === null && typeof audit.child === 'string' && audit.child !== '')
1380
+ const pending = (state?.audits ?? []).filter((audit) => audit.verdict === null)
1331
1381
  if (pending.length === 0) return { mutations: [], lost: 0, lines: [] }
1332
1382
  // 这个进程里正攥着的那几次派遣:它们是活的,不问目录。
1333
1383
  const known = new Set([...pendingAudits.values()].map((entry) => String(entry.run?.id ?? '')))
@@ -1345,24 +1395,30 @@ export function apply(ctx, config = {}) {
1345
1395
  const running = new Set((Array.isArray(children) ? children : []).filter((item) => item?.kind === 'child' && item.activity === 'running').map((item) => String(item.id)))
1346
1396
  const mutations = []
1347
1397
  const lines = []
1348
- for (const audit of unresolved) {
1398
+ for (const pendingAudit of unresolved) {
1399
+ const audit = { ...pendingAudit }
1400
+ if (!audit.child) {
1401
+ const child = children.find((child) => String(child.label ?? child.name ?? '').includes(audit.id))
1402
+ 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 }) }
1403
+ else if (Date.now() - (audit.at ?? 0) < CFG.auditHardTimeoutMs) continue
1404
+ }
1349
1405
  if (running.has(String(audit.child))) continue
1350
1406
  /**
1351
1407
  * 宿主说已结束 ⇒ **先把它的结论取回来**(读它自己的会话日志)。
1352
1408
  * 跳过它就把「结束」误报成「死亡」,还会诱导重新交付 ⇒ 同一次评估被重做。
1353
1409
  */
1354
- const recovered = recoverVerdictFromChildSession(audit.child)
1355
- if (recovered !== null && recovered.ok === true) {
1356
- 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() }
1410
+ const recovered = await recoverVerdictFromChildSession(audit.child)
1411
+ if (recovered !== null && recovered.ok === true && (!String(audit.capability).includes('outputSchema') || recovered.structured === true)) {
1412
+ 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() }
1357
1413
  const cardPath = writeAuditCard(sessionId, audit.step, card)
1358
- 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 })
1414
+ 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 })
1359
1415
  lines.push(tr(`${audit.step}:裁决从子会话日志取回(交付成立:${recovered.verdict.holds})`, `${audit.step}: verdict recovered from the child session log (holds: ${recovered.verdict.holds})`))
1360
- continue
1416
+ continue
1361
1417
  }
1362
1418
  if (recovered !== null && recovered.ok !== true) {
1363
1419
  mutations.push({ t: 'audit/settled', id: audit.id, step: audit.step, verdict: 'unknown', basis: tr(`评估者已结束,但未正常完成(${recovered.stopReason})。`, `The evaluator ended but did not complete normally (${recovered.stopReason}).`), shortfalls: ['audit_incomplete'], card_path: null, digest: audit.digest ?? null })
1364
1420
  lines.push(tr(`${audit.step}:评估者已结束、未正常完成(记为 unknown)`, `${audit.step}: the evaluator ended without completing (recorded as unknown)`))
1365
- continue
1421
+ continue
1366
1422
  }
1367
1423
  mutations.push({ t: 'audit/settled', id: audit.id, step: audit.step, verdict: 'unknown', basis: tr('评估者已结束(宿主目录报告),但其结论未能从子会话日志取回。', 'The evaluator ended (per the host catalog), but its conclusion could not be recovered from the child session log.'), shortfalls: ['auditor_ended_uncollected'], card_path: null, digest: audit.digest ?? null })
1368
1424
  lines.push(tr(`${audit.step}:评估者已结束、结论未取回(记为 unknown)`, `${audit.step}: the evaluator ended and its conclusion was not recovered (recorded as unknown)`))
@@ -1376,12 +1432,12 @@ export function apply(ctx, config = {}) {
1376
1432
  * 返回三档:`{ok:true, verdict}` 取回了;`{ok:false, stopReason}` 它结束了但未正常完成;
1377
1433
  * `null` 连它的日志都读不到。三档都只是**读数**,判断留给调用方如实分档。
1378
1434
  */
1379
- function recoverVerdictFromChildSession(childId) {
1380
- const settled = recoverFromChildSession(childId)
1435
+ async function recoverVerdictFromChildSession(childId) {
1436
+ const settled = await recoverFromChildSession(childId)
1381
1437
  if (settled === null) return null
1382
1438
  if (settled.ok !== true) return { ok: false, stopReason: settled.stopReason }
1383
- const verdict = normalizeVerdict(parseLooseJson([{ type: 'text', text: settled.conclusion }]))
1384
- return { ok: true, verdict }
1439
+ const verdict = normalizeVerdict(settled.structured ?? parseLooseJson([{ type: 'text', text: settled.conclusion }]))
1440
+ return { ok: true, verdict, structured: settled.structured !== undefined }
1385
1441
  }
1386
1442
 
1387
1443
  /**
@@ -1399,61 +1455,8 @@ export function apply(ctx, config = {}) {
1399
1455
  * 只有**落定过的裁决**才可复用(`verdict` 非 null 且不是 unknown):
1400
1456
  * `unknown` 不是裁决,它只说明"那一次没成",那正是应该重派的理由。
1401
1457
  */
1402
- function auditDigest(kind, step, plan, state, gate) {
1403
- /**
1404
- * **digest 只盖「材料」,不盖「上一次裁决留下的东西」。**
1405
- *
1406
- * 为什么这一条是这套复用能不能用的分水岭:一次不确定的结案自己会落一条
1407
- * `evidence/recorded`(`anchor:'auditor'`)。原来 digest 把证据集合整个算进去,
1408
- * 于是**每重试一次 digest 就变一次**,复用永远命中不了——模型每喊一次结案就再烧两三分钟,
1409
- * 而两次之间它什么都没改。这不是"新证据",是同一条评审自己的回声。
1410
- *
1411
- * 所以这里只取**可能改变结论的材料**:
1412
- * · 目标修订号(判据/假设换了内容才会变);
1413
- * · 计划的步与产物(交付了什么);
1414
- * · 观测(state.materials);
1415
- * · 原始假设(claim / status / 断言)——**刻意不用派生读数**:
1416
- * `supportedLevel` / `refutations` / `inconclusive` 都是证据算出来的,
1417
- * 而审计留下的那条证据会把它们改掉,用它就等于把回声又算进来一次;
1418
- * · 已升格事实;
1419
- * · **非审计来源**的证据(自判的 L0–L2 是真材料,保留)。
1420
- *
1421
- * 于是语义变成:材料变了 ⇒ 必然重审;材料没变 ⇒ 复用上次裁决,并把这件事说明白。
1422
- */
1423
- const material = (Array.isArray(state?.evidence) ? state.evidence : [])
1424
- .filter((item) => String(item?.anchor ?? '') !== 'auditor')
1425
- .map((item) => `${String(item?.id ?? '')}:${String(item?.verdict ?? '')}:${String(item?.level ?? '')}`)
1426
- const hypotheses = (Array.isArray(state?.hypotheses) ? state.hypotheses : []).map((item) =>
1427
- [String(item?.id ?? ''), String(item?.status ?? ''), String(item?.claim ?? '').replace(/\s+/g, ' '), JSON.stringify(item?.assertions ?? null)].join(':'),
1428
- )
1429
- const materials = (Array.isArray(state?.materials) ? state.materials : []).map((item) => `${String(item?.id ?? '')}:${String(item?.digest ?? '')}`)
1430
- /** 做的人登记与消解的未解释项是材料;评估者自己报的是回声,不算。 */
1431
- 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')}`)
1432
- const facts = (Array.isArray(state?.facts) ? state.facts : []).map((item) => `${String(item?.id ?? '')}:${String(item?.level ?? '')}:${JSON.stringify(item?.assertions ?? null)}`)
1433
- /**
1434
- * 步的**判据**与产物一起算材料:判据一变,"这一步算不算做完"就是另一个问题
1435
- * (`evaluatorPrompt` 会把判据逐字交给评估者)——不把它算进来会出现
1436
- * "改了判据却复用旧裁决"这种明显错的复用。
1437
- */
1438
- 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('|')}`)
1439
- const goal = `${String(state?.goal?.id ?? '')}:${Number(state?.goal?.revision ?? 0)}`
1440
- /**
1441
- * **准入坐标里只有"产物"算材料**。
1442
- *
1443
- * `gate.confirmed` 在两条路上形状不同:证据审计那一侧是**产物路径 + 字节数 + 内容摘要**
1444
- * (文件内容一变,digest 就变——这是"交付的东西真的改了吗"的唯一硬信号);
1445
- * 目标审计那一侧是 `evidence:` / `hypothesis:` 两类引用(证据集合与派生读数)——
1446
- * 把它们算进来,就等于又把上一次评审的回声算进来一次。
1447
- * 所以:留下产物,去掉回声。
1448
- */
1449
- const artifacts = (Array.isArray(gate?.confirmed) ? gate.confirmed : [])
1450
- .filter((item) => {
1451
- const ref = String(item?.ref ?? '')
1452
- return !ref.startsWith('evidence:') && !ref.startsWith('hypothesis:')
1453
- })
1454
- .map((item) => `${String(item?.ref ?? '')}:${String(item?.bytes ?? '')}:${String(item?.digest ?? '')}`)
1455
- const root = createHash('sha256').update(JSON.stringify([kind, step.id, goal, steps, materials, hypotheses, facts, material, artifacts, ...(anomalies.length > 0 ? [anomalies] : [])])).digest('hex')
1456
- return root.slice(0, 16)
1458
+ function auditDigest(kind, step, plan, state, gate, sessionId) {
1459
+ return auditMaterialDigest({ kind, step, plan, state, gate, cwd: sessionCwd(sessionId) })
1457
1460
  }
1458
1461
 
1459
1462
  /**
@@ -1475,7 +1478,7 @@ export function apply(ctx, config = {}) {
1475
1478
  const matched = (state?.audits ?? []).filter((audit) => String(audit?.step ?? '') === String(stepId) && String(audit?.digest ?? '') === digest)
1476
1479
  for (let index = matched.length - 1; index >= 0; index -= 1) {
1477
1480
  const audit = matched[index]
1478
- if (!['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1481
+ if (!digest.startsWith('v5:') || !audit.card_path || !existsSync(audit.card_path) || !['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1479
1482
  return audit
1480
1483
  }
1481
1484
  return null
@@ -1485,7 +1488,10 @@ export function apply(ctx, config = {}) {
1485
1488
  const mutations = []
1486
1489
  const auditKey = `a-${step.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1487
1490
  const key = `${sessionId}:${kind}:${step.id}`
1488
- const digest = auditDigest(kind, step, plan, stateOf(sessionId), gate)
1491
+ const initialSync = syncWorkspace(sessionId, stateOf(sessionId))
1492
+ if (initialSync !== null) mutations.push(initialSync)
1493
+ const initialState = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state ?? stateOf(sessionId)
1494
+ const digest = auditDigest(kind, step, plan, initialState, gate, sessionId)
1489
1495
  let entry = pendingAudits.get(key)
1490
1496
  /**
1491
1497
  * **同态复用**:先看在飞的(pendingAudits),再看**已经落定的**(投影里 digest 相同且给出了裁决的那一条)。
@@ -1501,6 +1507,17 @@ export function apply(ctx, config = {}) {
1501
1507
  * 材料没变就重来 ⇒ 计数 +1,达阈值把计划置 blocked 停下等人。
1502
1508
  * 于是"每次交付都被记下来"与"不重复花钱"两件事同时成立。
1503
1509
  */
1510
+ if (entry === undefined) {
1511
+ const durable = (stateOf(sessionId).audits ?? []).find((audit) => audit.step === step.id && audit.verdict === null)
1512
+ if (durable) {
1513
+ const swept = await sweepEndedAudits(sessionId, stateOf(sessionId))
1514
+ mutations.push(...swept.mutations)
1515
+ const recoveredState = previewOf(host(), sessionId, mutations)?.state ?? stateOf(sessionId)
1516
+ if ((recoveredState.audits ?? []).some((audit) => audit.id === durable.id && audit.verdict === null)) return { holds: 'pending', results: [], basis: '已有持久派发,等待关联评估者恢复', shortfalls: ['audit_pending'], cardPath: null, mutations }
1517
+ const recovered = reuseAudit(recoveredState, step.id, digest)
1518
+ 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 }
1519
+ }
1520
+ }
1504
1521
  if (entry === undefined) {
1505
1522
  const reused = reuseAudit(stateOf(sessionId), step.id, digest)
1506
1523
  if (reused !== null) {
@@ -1521,6 +1538,7 @@ export function apply(ctx, config = {}) {
1521
1538
  holds: auditHolds(reused),
1522
1539
  results: Array.isArray(reused.results) ? reused.results : [],
1523
1540
  basis: String(reused.basis ?? ''),
1541
+ reuse: reused.reuse ?? [],
1524
1542
  shortfalls: Array.isArray(reused.shortfalls) ? reused.shortfalls : [],
1525
1543
  cardPath: reused.card_path ?? null,
1526
1544
  /**
@@ -1543,18 +1561,21 @@ export function apply(ctx, config = {}) {
1543
1561
  * 而"我派过一个评估者"是**已经发生的事实**。把它写在 await 之后,等于把事实寄存在
1544
1562
  * 一个会被撤销的栈帧里:`hold` 不触发、`sweepEndedAudits` 看不见,模型只会原样重试。
1545
1563
  *
1546
- * `id` 取一个与裁决 digest 绑定的**稳定键**:同一个状态反复结案得到同一个键,
1547
- * 于是下面那次"带上子会话 id 的完整事实"按 id 覆盖它,而不是在账上留两条。
1564
+ * 每次派发使用独立尝试 id;补齐子会话时按同 id 更新。已落定的有效裁决按材料 digest 复用。
1548
1565
  */
1549
- const pendingId = `audit:pending:${kind}:${step.id}:${digest}`
1566
+ const pendingId = `audit:pending:${auditPathComponent(`${sessionId}:${kind}:${step.id}:${digest}:${auditKey}`).slice(0, 32)}`
1550
1567
  landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, capability: null, evaluator_session: null, status: 'dispatching' })
1568
+ try { await flushFacts(sessionId) } catch (error) {
1569
+ 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 })
1570
+ return { holds: 'unknown', results: [], basis: '派发记录未持久保存,未派发评估者', shortfalls: ['audit_dispatch_not_durable'], cardPath: null, digest, mutations }
1571
+ }
1551
1572
  const rerunDir = CFG.auditRerun ? rerunCopy(sessionId, auditKey) : null
1552
1573
  const dispatched = await dispatchSubRun({
1553
- label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id}`,
1574
+ label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id} · ${pendingId}`,
1554
1575
  persona: evaluatorDiscipline(),
1555
- prompt: evaluatorPrompt(stateOf(sessionId), step, gate, sessionId, rerunDir),
1576
+ prompt: evaluatorPrompt(initialState, step, gate, sessionId, rerunDir),
1556
1577
  outputSchema: verdictSchema(),
1557
- toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, 'bash']) },
1578
+ toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, process.platform === 'win32' ? 'pwsh' : 'bash']) },
1558
1579
  parent: agent,
1559
1580
  signal,
1560
1581
  })
@@ -1568,8 +1589,14 @@ export function apply(ctx, config = {}) {
1568
1589
  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 })
1569
1590
  return { holds: 'unknown', results: [], basis: tr(`独立评估者无法派遣(${dispatched.reason})`, `The independent evaluator could not be dispatched (${dispatched.reason})`), shortfalls: ['audit_dispatch_failed'], cardPath: null, mutations }
1570
1591
  }
1571
- 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' })
1572
- entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined }
1592
+ 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' }))
1593
+ try { await flushFacts(sessionId) } catch (error) {
1594
+ try { await dispatched.run.dispose?.() } catch {}
1595
+ dropRerunCopy(rerunDir)
1596
+ 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 })
1597
+ return { holds: 'unknown', results: [], basis: '子会话关联未持久保存,已停止评估', shortfalls: ['audit_child_not_durable'], cardPath: null, digest, mutations }
1598
+ }
1599
+ entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined, startedAt: Date.now() }
1573
1600
  pendingAudits.set(key, entry)
1574
1601
  entry.settled = dispatched.run.result.then(
1575
1602
  (value) => ({ ok: true, value }),
@@ -1584,12 +1611,32 @@ export function apply(ctx, config = {}) {
1584
1611
  }),
1585
1612
  ])
1586
1613
  if (outcome === null) {
1614
+ /**
1615
+ * **超过硬上限就放开**:一次挂住的评估会拖住整个目标(出现过挂数小时的情形)。
1616
+ * 超时如实结成「未知」(与评估者失败同一种结局),释放这次派遣;下一次结案或交付重新派。
1617
+ */
1618
+ if (Date.now() - (entry.startedAt ?? Date.now()) >= CFG.auditHardTimeoutMs) {
1619
+ pendingAudits.delete(key)
1620
+ try {
1621
+ await entry.run.dispose?.()
1622
+ } catch {
1623
+ // 收不掉也不影响结算:这次派遣在账上已经结了。
1624
+ }
1625
+ dropRerunCopy(entry.rerunDir ?? null)
1626
+ const basis = tr(`评估者超过 ${Math.round(CFG.auditHardTimeoutMs / 60000)} 分钟没有给出裁决,如实记为未知`, `The evaluator gave no verdict within ${Math.round(CFG.auditHardTimeoutMs / 60000)} minutes; recorded honestly as unknown`)
1627
+ mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls: ['audit_timeout'], card_path: null, digest })
1628
+ return { holds: 'unknown', results: [], basis, shortfalls: ['audit_timeout'], cardPath: null, digest, mutations }
1629
+ }
1587
1630
  // 仍在跑:条目留着,下一次交付继续等同一次派遣(不重复派遣)。派发事实已经在上面的 mutations 里。
1588
1631
  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 }
1589
1632
  }
1590
1633
  // 已落定:这次派遣的生命周期到此为止。下一次交付是**新的一次评估**(新证据),必须重新派遣。
1591
1634
  pendingAudits.delete(key)
1592
1635
  dropRerunCopy(entry.rerunDir ?? null)
1636
+ const settleUnknown = (basis, shortfalls) => {
1637
+ mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls, card_path: null, digest })
1638
+ return { holds: 'unknown', results: [], basis, shortfalls, cardPath: null, digest, mutations }
1639
+ }
1593
1640
  if (outcome.ok !== true) {
1594
1641
  return settleUnknown(tr(`评估者失败:${String(outcome.error?.message ?? outcome.error)}`, `The evaluator failed: ${String(outcome.error?.message ?? outcome.error)}`), ['audit_failed'])
1595
1642
  }
@@ -1601,27 +1648,31 @@ export function apply(ctx, config = {}) {
1601
1648
  * 结局不好也是结局,如实落下来——不然那条派发事实会在账上挂到天荒地老,
1602
1649
  * 而"评估者没有悬空"这条不变量也只能红着,连解释都拿不出证据。
1603
1650
  */
1604
- const settleUnknown = (basis, shortfalls) => {
1605
- mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: 'unknown', holds: 'unknown', basis, shortfalls, card_path: null, digest })
1606
- return { holds: 'unknown', results: [], basis, shortfalls, cardPath: null, digest, mutations }
1607
- }
1651
+
1608
1652
  const settled = outcome.value
1609
1653
  const stopReason = String(settled?.stopReason ?? 'completed')
1610
1654
  if (stopReason !== 'completed' && settled?.structured === undefined) {
1611
1655
  return settleUnknown(tr(`评估者未正常结束(${stopReason})`, `The evaluator did not end normally (${stopReason})`), ['audit_incomplete'])
1612
1656
  }
1657
+ if (settled?.structured === undefined && entry.capability.includes('outputSchema')) return settleUnknown('原生结构化审计结果缺失,文本不作为新裁决', ['audit_structured_missing'])
1613
1658
  const verdict = settled?.structured !== undefined ? normalizeVerdict(settled.structured) : normalizeVerdict(parseLooseJson(settled?.output))
1614
1659
  try {
1615
1660
  await entry.run.dispose?.()
1616
1661
  } catch {
1617
1662
  /* dispose 失败不影响裁决事实 */
1618
1663
  }
1619
- 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() }
1664
+ 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() }
1620
1665
  const cardPath = writeAuditCard(sessionId, step.id, card)
1621
1666
  if (cardPath === null) {
1622
1667
  return settleUnknown(tr('评估卡落盘失败:裁决降级', 'Could not save the evaluation card: verdict downgraded'), ['card_persist_failed'])
1623
1668
  }
1624
- 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 })
1669
+ 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 })
1670
+ const synced = syncWorkspace(sessionId, stateOf(sessionId))
1671
+ if (synced !== null) mutations.push(synced)
1672
+ const fresh = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state
1673
+ if (fresh === undefined || auditDigest(kind, step, plan, fresh, gate, sessionId) !== digest) {
1674
+ return { ...verdict, holds: 'unknown', shortfalls: [...verdict.shortfalls, 'audit_material_changed'], cardPath, digest, mutations }
1675
+ }
1625
1676
  return { ...verdict, cardPath, digest, mutations }
1626
1677
  }
1627
1678
 
@@ -1635,7 +1686,7 @@ export function apply(ctx, config = {}) {
1635
1686
  function rerunCopy(sessionId, auditKey) {
1636
1687
  const cwd = sessionCwd(sessionId)
1637
1688
  if (cwd === null) return null
1638
- const target = join(tmpdir(), `clearai-rerun-${auditKey}`)
1689
+ const target = join(tmpdir(), `clearai-rerun-${auditPathComponent(auditKey)}`)
1639
1690
  const skip = new Set([join(cwd, 'clear'), join(cwd, '.git'), join(cwd, 'node_modules')])
1640
1691
  try {
1641
1692
  cpSync(cwd, target, { recursive: true, filter: (source) => !skip.has(source) })
@@ -1658,10 +1709,10 @@ export function apply(ctx, config = {}) {
1658
1709
 
1659
1710
  /** 评估卡落盘(系统的面)。写不进 → 返回 null,调用方 fail-closed。 */
1660
1711
  function writeAuditCard(sessionId, stepId, card) {
1661
- const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', String(stepId), `${String(card.auditor_run_id)}.json`)
1712
+ const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', auditPathComponent(stepId), `${auditPathComponent(card.auditor_run_id)}.json`)
1662
1713
  if (file === null) return null
1663
1714
  try {
1664
- writeTextFile(file, `${JSON.stringify(card, null, 2)}\n`)
1715
+ writeTextFile(file, `${JSON.stringify({ ...card, evaluator: 'independent' }, null, 2)}\n`)
1665
1716
  return file
1666
1717
  } catch (error) {
1667
1718
  ctx.logger?.warn?.(`clearai kernel: 评估卡落盘失败 ${String(error?.message ?? error)}`)
@@ -1982,13 +2033,59 @@ export function apply(ctx, config = {}) {
1982
2033
  if (fact !== null) pending.push(fact)
1983
2034
  }
1984
2035
  const open = pending.filter((fact) => fact.review === undefined || fact.review === null)
1985
- if (open.length === 0) return ''
1986
2036
  const notes = []
2037
+ /**
2038
+ * **反驳回到被引用的条目**:被推翻的判断在 `uses` 里引用过的事实(不是它复检的那条)。
2039
+ * 判断错了不等于它引用的事实错了,所以不问人撤回;但按范围比一次:检验落在事实范围之外 ⇒
2040
+ * 记一处边界(`fact/bounded`);范围之内或说不清 ⇒ 事实回到「待核验」(`fact/questioned`)。
2041
+ */
2042
+ const handled = new Set(pending.map((fact) => fact.id))
2043
+ for (const refuter of state.hypotheses.filter((item) => refutedHypotheses.includes(item.id) && Array.isArray(item.uses))) {
2044
+ for (const use of refuter.uses) {
2045
+ if (use?.kind !== 'fact' || handled.has(use.id)) continue
2046
+ handled.add(use.id)
2047
+ const fact = findFact(sessionId, state, use.id)
2048
+ if (fact === null || fact.review?.decision === 'retracted') continue
2049
+ const fit = compareScope(fact.scope_spec ?? null, mergeScope(refuter.scope, { conditions: state.goal?.conditions ?? {} }))
2050
+ const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2051
+ if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2052
+ mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter.id, basis: clip(basis, 300) })
2053
+ markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2054
+ 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`))
2055
+ continue
2056
+ }
2057
+ mutations.push({ t: 'fact/questioned', fact: fact.id, hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2058
+ markFactQuestioned(sessionCwd(sessionId), fact, { hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2059
+ 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`))
2060
+ }
2061
+ }
2062
+ if (open.length === 0) return notes.length === 0 ? '' : tr(`\n复核:${notes.join(';')}`, `\nReview: ${notes.join('; ')}`)
1987
2063
  for (const fact of open) {
2064
+ /**
2065
+ * **先比范围,再谈撤回**:推翻它的那条判断是在什么条件下检验的(判断自己的范围,缺的维度取立题的
2066
+ * conditions)。检验落在这条事实的适用范围之外,说明「换了范围不成立」,不是「被推翻」:
2067
+ * 事实保持成立,只记下这处边界,不去问人撤回。0.5.1 里九月数据撤回八月事实就是缺了这一步。
2068
+ */
2069
+ const refuter = state.hypotheses.find((item) => refutedHypotheses.includes(item.id) && (item.retests === fact.id || item.id === fact.hypothesis)) ?? null
2070
+ const tested = mergeScope(refuter?.scope, { conditions: state.goal?.conditions ?? {} })
2071
+ const fit = compareScope(fact.scope_spec ?? null, tested)
2072
+ if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2073
+ const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2074
+ mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter?.id ?? null, basis: clip(basis, 300) })
2075
+ markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2076
+ 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`))
2077
+ continue
2078
+ }
2079
+ const scopeNote =
2080
+ fit.verdict === 'undeclared'
2081
+ ? tr(`(注意:${scopeVerdictText(fit, 'zh')},无法确定本次证据是否落在它的适用范围内)`, ` (Note: ${scopeVerdictText(fit, 'en')}, so it is unclear whether this evidence falls within its scope.)`)
2082
+ : fit.verdict === 'unscoped'
2083
+ ? tr('(这条事实没有声明适用范围)', ' (This fact has no declared scope.)')
2084
+ : ''
1988
2085
  const asked = await askHuman(exec, {
1989
2086
  id: `fact-${fact.id}`,
1990
2087
  header: tr('已确立的结论出现推翻证据', 'An established conclusion was refuted'),
1991
- 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?`),
2088
+ 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?`),
1992
2089
  options: [
1993
2090
  { label: choiceLabel('factRetract'), description: tr('它不再算已确立的结论(记录保留)。', 'It no longer counts as an established conclusion (the record stays).') },
1994
2091
  { label: choiceLabel('factKeep'), description: tr('这次证据不可靠,事实保留;推翻证据照样留在账上。', 'This evidence is unreliable and the fact stays; the refuting evidence stays on record too.') },
@@ -1997,7 +2094,7 @@ export function apply(ctx, config = {}) {
1997
2094
  if (asked.ok !== true || (!chose(asked, 'factRetract') && !chose(asked, 'factKeep'))) {
1998
2095
  const why = asked.ok === true ? tr('没选', 'no choice made') : unanswered(asked)
1999
2096
  notes.push(tr(`${fact.id} 待人复核(${why})`, `${fact.id} awaits review by a person (${why})`) + blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`事实 ${fact.id} 出现了推翻证据,等人决定撤回还是维持。`, `Fact ${fact.id} met refuting evidence; waiting for a person to retract or keep it.`)))
2000
- continue
2097
+ continue
2001
2098
  }
2002
2099
  const review = { decision: chose(asked, 'factRetract') ? 'retracted' : 'kept', reason: asked.note }
2003
2100
  mutations.push({ t: 'fact/reviewed', fact: fact.id, decision: review.decision, reason: review.reason, by: 'user' })
@@ -2057,25 +2154,27 @@ export function apply(ctx, config = {}) {
2057
2154
  [
2058
2155
  '# 本体内容(已确立条目,可作为「已知」引用;未结构化的旧条目照旧在架)',
2059
2156
  '',
2060
- '> 每条都带**边界**(推翻条件)与**支持等级**:引用它之前先看边界还在不在。',
2157
+ '> 每条都带**适用范围**、**推翻条件**与**支持等级**:引用之前先看这次的情形是否在它的适用范围内。',
2061
2158
  '> 这一份由系统维护(做的人不能写 `clear/knowledge/facts`);新的在前。',
2062
2159
  '',
2063
2160
  ],
2064
2161
  [
2065
2162
  '# Established knowledge (entries you can cite as known; older unstructured entries stay listed)',
2066
2163
  '',
2067
- '> Each entry carries its **boundary** (refutation condition) and **support level**: check the boundary still holds before citing it.',
2164
+ '> Each entry carries its **scope**, **refutation condition** and **support level**: before citing it, check that this situation is within its scope.',
2068
2165
  '> This file is maintained by the system (the worker cannot write `clear/knowledge/facts`); newest first.',
2069
2166
  '',
2070
2167
  ],
2071
2168
  )
2072
2169
  for (const fact of [...facts].reverse()) {
2073
- const scope = fact.scope === null || fact.scope === undefined || String(fact.scope).trim() === '' ? tr('(未写——引用前请谨慎)', '(not written; cite with care)') : String(fact.scope)
2170
+ const scope = tr(scopeText(fact.scope_spec, 'zh'), scopeText(fact.scope_spec, 'en')) || String(fact.scope ?? '').trim() || tr('范围未声明(引用前请谨慎)', 'scope not declared (cite with care)')
2074
2171
  const evidence = listOf(fact.evidence ?? []) || tr('(无)', '(none)')
2075
2172
  const at = fact.at === undefined || fact.at === null ? '—' : new Date(fact.at).toISOString()
2076
2173
  lines.push(`## ${fact.id} · ${fact.text}`)
2077
2174
  lines.push('')
2078
- lines.push(tr(`- 边界:${scope}`, `- Boundary: ${scope}`))
2175
+ lines.push(tr(`- 适用范围:${scope}`, `- Scope: ${scope}`))
2176
+ if (typeof fact.refute_when === 'string' && fact.refute_when !== '') lines.push(tr(`- 推翻条件:${fact.refute_when}`, `- Refuted if: ${fact.refute_when}`))
2177
+ for (const bound of Array.isArray(fact.boundaries) ? fact.boundaries : []) lines.push(tr(`- 已知不适用:${scopeVerdictText(bound, 'zh')}`, `- Known not to apply: ${scopeVerdictText(bound, 'en')}`))
2079
2178
  lines.push(tr(`- 支持到:${fact.level ?? '(未记等级)'} · 证据:${evidence}`, `- Supported to: ${fact.level ?? '(no level recorded)'} · evidence: ${evidence}`))
2080
2179
  lines.push(tr(`- 来源目标:${fact.goal ?? '—'} · 升格时间:${at}`, `- From goal: ${fact.goal ?? '—'} · promoted at: ${at}`))
2081
2180
  /**
@@ -2107,6 +2206,8 @@ export function apply(ctx, config = {}) {
2107
2206
 
2108
2207
  const FACTS_REL = ['clear', 'knowledge', 'facts']
2109
2208
  const LESSONS_REL = ['clear', 'knowledge', 'lessons']
2209
+ /** 负向条目(已排除、未解、缺陷):系统随发生随写,见 `writeBack`。 */
2210
+ const NEGATIVES_REL = ['clear', 'knowledge', 'negatives']
2110
2211
  /** 经验的四类(与 `domain-language.js` 的 `LESSON_KINDS` 同值):坑、要先核的、会骗人的捷径、先验。 */
2111
2212
  const LESSON_KINDS = ['trap', 'check', 'shortcut', 'prior']
2112
2213
  /** 工作方式(与 `fold.js` 读的同值):广度调研 / 定向求解 / 先调研后求解。 */
@@ -2114,41 +2215,6 @@ export function apply(ctx, config = {}) {
2114
2215
  /** 问题的三种状态(与 `fold.js` 同值):在回答 / 新发现待决定 / 暂缓。 */
2115
2216
  const QUESTION_STATUS = ['open', 'emergent', 'parked']
2116
2217
 
2117
- /**
2118
- * **测量门槛**(`CFG.requireMeasures`):首次立题时,本体里(已有文件 + 这次随立题写的)
2119
- * 至少要有一个度量概念,且每个度量概念都是某条 `measures` 关系的 range、这条关系写了 `check`。
2120
- *
2121
- * 为什么要求:真跑里唯一一条错误事实,来自"控制器回读值被当成釜温"——缺的正是"哪个仪表测哪个量、
2122
- * 怎么核对"这一条。只要求把测量说清,不要求编造对手假设。返回缺什么的说明;齐了返回 null。
2123
- */
2124
- function unmeasured(state, ontologyFiles) {
2125
- const entries = { concepts: new Map(), relations: new Map() }
2126
- for (const [path, file] of Object.entries(state?.workspace?.files ?? {})) {
2127
- const hit = /^clear\/ontology\/(concepts|relations)\/(?:.+\/)?([^/]+)\.json$/.exec(path)
2128
- if (hit === null || file?.data === null || typeof file?.data !== 'object') continue
2129
- entries[hit[1]].set(String(file.data.id ?? hit[2]), file.data)
2130
- }
2131
- for (const file of ontologyFiles) entries[file.branch].set(file.id, { ...file.data, id: file.id })
2132
- const measures = [...entries.concepts.values()].filter((concept) => concept.kind === 'measure').map((concept) => String(concept.id))
2133
- if (measures.length === 0) {
2134
- return tr(
2135
- '首次立题要在 `ontology` 里写出答案涉及的量:至少一个度量概念(`kind: "measure"`),并为每个度量写一条 `measures` 关系(domain 是仪表或方法,range 是这个量,`check` 写怎样核对读数确实是这个量)。\n本体不是收尾时补的:候选假设与预测要从它出发。',
2136
- 'The first Frame must write the quantities the answer involves in `ontology`: at least one measure concept (`kind: "measure"`), and for each measure a `measures` relation (domain = instrument or method, range = the quantity, `check` = how to confirm the reading really is that quantity).\nThe ontology is not an afterthought: candidates and predictions start from it.',
2137
- )
2138
- }
2139
- const rangeOf = (relation) => (typeof relation.range === 'string' ? relation.range : String(relation.range?.term ?? relation.range?.id ?? ''))
2140
- const covered = new Set(
2141
- [...entries.relations.values()]
2142
- .filter((relation) => relation.kind === 'measures' && String(relation.check ?? '').trim() !== '')
2143
- .map(rangeOf),
2144
- )
2145
- const missing = measures.filter((id) => !covered.has(id))
2146
- if (missing.length === 0) return null
2147
- return tr(
2148
- `这些度量还没有写测量方式:${missing.join('、')}。\n每个度量要有一条 \`measures\` 关系(domain 是仪表或方法,range 是这个量,\`check\` 写怎样核对读数确实是这个量,例如「与参考探头比对」)。读数是不是那个量,是事实能否成立的前提。`,
2149
- `These measures have no measurement method yet: ${missing.join(', ')}.\nEach measure needs a \`measures\` relation (domain = instrument or method, range = the quantity, \`check\` = how to confirm the reading really is that quantity, e.g. "compare against the reference probe"). Whether a reading is that quantity is a precondition for any fact built on it.`,
2150
- )
2151
- }
2152
2218
  const ONTOLOGY_REL = ['clear', 'ontology']
2153
2219
  const ONTOLOGY_BRANCH_DIRS = ['concepts', 'relations', 'entities']
2154
2220
  /** 读面有界(与 `domain-language.js` 的 `WORKSPACE_LIMITS` 同值):超出的如实报成读不成,不静默截断。 */
@@ -2177,6 +2243,7 @@ export function apply(ctx, config = {}) {
2177
2243
  }
2178
2244
  walk(FACTS_REL, false)
2179
2245
  walk(LESSONS_REL, false)
2246
+ walk(NEGATIVES_REL, false)
2180
2247
  for (const branch of ONTOLOGY_BRANCH_DIRS) walk([...ONTOLOGY_REL, branch], true)
2181
2248
  return out
2182
2249
  }
@@ -2191,12 +2258,12 @@ export function apply(ctx, config = {}) {
2191
2258
  return null
2192
2259
  }
2193
2260
  const cached = workspaceReads.get(file)
2194
- if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.change
2195
- let change
2261
+ let change
2196
2262
  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})`) }
2197
2263
  else {
2198
2264
  const raw = readFileSync(file, 'utf8')
2199
- const digest = createHash('sha1').update(raw).digest('hex').slice(0, 16)
2265
+ const digest = contentDigest(raw)
2266
+ if (cached?.change?.digest === digest) return cached.change
2200
2267
  try {
2201
2268
  change = { path, digest, data: JSON.parse(raw) }
2202
2269
  } catch (error) {
@@ -2296,6 +2363,9 @@ export function apply(ctx, config = {}) {
2296
2363
  for (const hypothesis of hypotheses) {
2297
2364
  lines.push(`- \`${hypothesis.id}\` [${hypothesis.status}] ${hypothesis.claim}`)
2298
2365
  lines.push(tr(` - 推翻条件:${hypothesis.refute_when}`, ` - Refuted if: ${hypothesis.refute_when}`))
2366
+ lines.push(` - scope: ${JSON.stringify(mergeScope(hypothesis.scope, { conditions: goal.conditions ?? {} }))}`)
2367
+ lines.push(` - uses (framing declarations): ${JSON.stringify(hypothesis.uses ?? [])}`)
2368
+ if (hypothesis.retests) lines.push(` - retests: ${hypothesis.retests}`)
2299
2369
  if (Array.isArray(hypothesis.assertions) && hypothesis.assertions.length > 0) lines.push(tr(` - 断言:${hypothesis.assertions.length} 条`, ` - Assertions: ${hypothesis.assertions.length}`))
2300
2370
  }
2301
2371
  if (history.length > 0) {
@@ -2437,6 +2507,30 @@ export function apply(ctx, config = {}) {
2437
2507
  * 而工具自己的 `mutations` 是这一拍的结算。两者同形、同一个折法,
2438
2508
  * 所以并起来交给宿主不会多一条通道,只是让"事实比工具结果活得更久"。
2439
2509
  */
2510
+ /**
2511
+ * 工具结果出去之前,把这一拍的变更折一遍、写负向条目:这一拍之后会话若就此中断,条目也已在盘上。
2512
+ * 写不出来不影响工具结果。
2513
+ */
2514
+ const syncNativeTodos = createTodoMirror({ session: id => ctx.get('sessions')?.get?.(id), isChild: isSpawnedChild, warn: message => ctx.logger?.warn?.(message) })
2515
+
2516
+ function afterTool(exec, value) {
2517
+ const mutations = Array.isArray(value?.mutations) ? value.mutations : []
2518
+ if (mutations.length === 0) return value
2519
+ try {
2520
+ const sessionId = String(exec?.agent?.id ?? 'unknown')
2521
+ const hostService = host()
2522
+ if (hostService === undefined) return value
2523
+ const preview = previewOf(hostService, sessionId, mutations)
2524
+ if (preview !== null) {
2525
+ writeBack(sessionId, preview.state, preview.derived ?? null)
2526
+ if (CFG.nativeTodoProgress) syncNativeTodos(sessionId, preview.state)
2527
+ }
2528
+ } catch (error) {
2529
+ ctx.logger?.warn?.(`clearai kernel: 负向条目回写失败 ${String(error?.message ?? error).slice(0, 160)}`)
2530
+ }
2531
+ return value
2532
+ }
2533
+
2440
2534
  function withPendingFacts(exec, value) {
2441
2535
  const sessionId = String(exec?.agent?.id ?? 'unknown')
2442
2536
  const pending = drainPendingFacts(sessionId)
@@ -2460,93 +2554,217 @@ export function apply(ctx, config = {}) {
2460
2554
  return { ...value, mutations: merged }
2461
2555
  }
2462
2556
 
2557
+ // ── 取用:立题时定位已有条目,引用时判定是否适用 ─────────────────────────
2558
+
2559
+ /** 工作区里的已有条目(事实、经验、负向条目)摊成一张表:`{id, kind, status, about, scope_spec, path, …}`。 */
2560
+ function knowledgeRows(derived) {
2561
+ 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` }))
2562
+ const lessons = (derived?.lessonRows ?? []).map((row) => ({ ...row, kind: 'lesson', status: 'active', path: row.path ?? `clear/knowledge/lessons/${row.id}.json` }))
2563
+ const negatives = (derived?.negativeRows ?? []).map((row) => ({ ...row, kind: 'negative' }))
2564
+ return [...facts, ...lessons, ...negatives]
2565
+ }
2566
+
2567
+ const ROW_STATUS_TEXT = {
2568
+ 'fact:established': ['成立', 'holding'],
2569
+ 'fact:pending': ['待核验', 'pending re-check'],
2570
+ 'fact:retracted': ['已撤回', 'retracted'],
2571
+ 'lesson:active': ['经验', 'lessons'],
2572
+ 'negative:excluded': ['已排除', 'excluded'],
2573
+ 'negative:preliminary_excluded': ['初步排除', 'preliminarily excluded'],
2574
+ 'negative:unresolved': ['未解', 'unresolved'],
2575
+ 'negative:defect': ['缺陷', 'defects'],
2576
+ 'negative:explained': ['已解释的反常', 'explained anomalies'],
2577
+ 'negative:ruled_out': ['排除的反常', 'ruled-out anomalies'],
2578
+ 'negative:escalated': ['交给人的反常', 'escalated anomalies'],
2579
+ }
2580
+
2581
+ /** 引用判定 → 一句话(含该怎么办)。 */
2582
+ function citeText(verdict) {
2583
+ switch (verdict.verdict) {
2584
+ case 'unknown':
2585
+ return tr('未找到', 'not found')
2586
+ case 'retracted':
2587
+ return tr('已撤回,不能作为已知引用', 'retracted; do not cite it as known')
2588
+ case 'definition_changed':
2589
+ 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`)
2590
+ case 'pending':
2591
+ 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`)
2592
+ return tr('待核验(有推翻证据或开着的疑问):先复检(retests)再用', 'pending re-check (refuting evidence or an open question): re-test it (retests) before relying on it')
2593
+ case 'out_of_scope':
2594
+ case 'out_of_range':
2595
+ return tr(`${scopeVerdictText(verdict, 'zh')}:先检验再用`, `${scopeVerdictText(verdict, 'en')}: test it before relying on it`)
2596
+ case 'undeclared':
2597
+ return tr(`${scopeVerdictText(verdict, 'zh')}:在立题的 conditions 或判断的 scope 里写明这些维度`, `${scopeVerdictText(verdict, 'en')}: state these in the framing conditions or the judgment's scope`)
2598
+ default:
2599
+ return tr(scopeVerdictText(verdict, 'zh'), scopeVerdictText(verdict, 'en'))
2600
+ }
2601
+ }
2602
+
2603
+ /** 核算重跑的结果(没偏差、或没能跑)附在判定后面;没跑(输入没变)不说。 */
2604
+ function runText(run, lang) {
2605
+ if (run === undefined || run === null) return ''
2606
+ const zh = lang === 'zh'
2607
+ switch (run.status) {
2608
+ case 'rerun':
2609
+ 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`
2610
+ case 'failed':
2611
+ return zh ? `;核算 ${run.model} 复检未完成(${run.detail}),保持待核验` : `; computation ${run.model} re-check incomplete (${run.detail}); remains pending`
2612
+ case 'unavailable':
2613
+ return zh ? `;这个宿主不能执行命令,核算 ${run.model} 没有重跑` : `; this host cannot run commands, so computation ${run.model} was not re-run`
2614
+ case 'invalid':
2615
+ return zh ? `;核算登记 clear/models/${run.model}.json 不合格(${run.detail}),没有重跑` : `; the registration clear/models/${run.model}.json is not usable (${run.detail}); not re-run`
2616
+ case 'missing':
2617
+ return zh ? `;条目挂的核算 ${run.model} 找不到登记文件,没有重跑` : `; the computation ${run.model} named by the item has no registration file; not re-run`
2618
+ default:
2619
+ return ''
2620
+ }
2621
+ }
2622
+
2623
+ /** 负向条目被引用时,先说它是什么。 */
2624
+ function negativeLead(row) {
2625
+ if (row?.kind !== 'negative') return ''
2626
+ const word = ROW_STATUS_TEXT[`negative:${row.status}`]
2627
+ const strength = row.status === 'preliminary_excluded' ? tr('(依据较弱,可以重验)', ' (weak grounds; may be re-tested)') : ''
2628
+ return word === undefined ? '' : tr(`${word[0]}${strength};`, `${word[1]}${strength}; `)
2629
+ }
2630
+
2631
+ /**
2632
+ * 立题时关于已有知识的那几句:相关条目的计数与位置(不给内容)、`about` 里可能指同一实体的名字、
2633
+ * 每条判断 `uses` 的适用性判定。都是读数,不拦立题。
2634
+ */
2635
+ function frameKnowledgeNote({ about, resolved, related, cites, rows }) {
2636
+ const lines = []
2637
+ if (about.length > 0) {
2638
+ if (related.total === 0) lines.push(tr(`工作区里没有与 about(${about.join('、')})相关的已有条目。`, `No existing items in the workspace concern the about ids (${about.join(', ')}).`))
2639
+ else {
2640
+ const parts = Object.entries(related.counts).map(([bucket, count]) => {
2641
+ const word = ROW_STATUS_TEXT[bucket] ?? [bucket, bucket]
2642
+ return tr(`${word[0]} ${count}`, `${count} ${word[1]}`)
2643
+ })
2644
+ lines.push(
2645
+ tr(
2646
+ `工作区里与 about(${about.join('、')})相关的已有条目 ${related.total} 条(${parts.join('、')}),位于 ${related.dirs.join('、')}。先查找读过再定判断;用到的写进判断的 uses,系统会判定它是否适用。`,
2647
+ `${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.`,
2648
+ ),
2649
+ )
2650
+ }
2651
+ } else if (rows.length > 0) {
2652
+ 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.`))
2653
+ }
2654
+ for (const item of resolved) {
2655
+ 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).`))
2656
+ 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.`))
2657
+ }
2658
+ 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')}.`))
2659
+ return lines.length === 0 ? '' : `\n${lines.join('\n')}`
2660
+ }
2661
+
2463
2662
  // ── Frame ────────────────────────────────────────────────────────────
2464
2663
 
2465
2664
  defineTool({
2466
2665
  name: 'Frame',
2467
2666
  description:
2468
- '立约或修订:往当前原生 goal 上挂一份「怎样算回答了」的判据(done_criteria)与候选判断(每条一句话主张 + 一句「什么结果会推翻它」)。没有原生 goal 时会建一个,目标那一句话(headline)就是它的说法;续跑、暂停由原生 goal 管。修订必须带 reason,版本 +1,旧值全部留痕;改判据文本要带一份独立裁决。不可逆的动作写进 irreversible(匹配的命令执行前须经人工批准)。同一时间只开一个目标;它跨计划存在,一张 Plan 只承载它的一个阶段。',
2667
+ '立题或修订目标:判据(done_criteria)与候选判断(一句主张 + 推翻条件)。修订须带 reason,旧值留痕;改判据文本须带独立裁决(criteria_verdict)。同一时间只开一个目标。',
2469
2668
  parameters: {
2470
2669
  type: 'object',
2471
2670
  properties: {
2472
- headline: { type: 'string', maxLength: 120, description: '一句话目标(≤120 字):卡上 / 面板 / 续跑文案反复出现的那一句。首次立约必填' },
2473
- claim: { type: 'string', description: '目标:项目要回答的问题(可以长;身份与判据的落点)' },
2474
- done_criteria: { type: 'string', description: '怎样算回答了——必须是可核对的判据,至少含一处能清点的形态(数字 / 条数 / "存在一份文件")' },
2475
- legacy: { type: 'boolean', description: '旧会话迁移:一次性放行长文本与缺 headline(新目标不要用)' },
2671
+ headline: { type: 'string', maxLength: 120, description: '一句话目标(≤120 字),首次立题必填' },
2672
+ claim: { type: 'string', description: '目标要回答的问题' },
2673
+ done_criteria: { type: 'string', description: '怎样算回答了:可核对,至少一处能清点(数字、条数、存在某文件)' },
2674
+ legacy: { type: 'boolean', description: '仅旧会话迁移用' },
2476
2675
  criteria: {
2477
2676
  type: 'array',
2478
2677
  items: { type: 'string' },
2479
- description: '判据逐条写(每条一句话,含可清点数或"存在一份文件"这类能核的形态)。给了它就按条记,不给则用 done_criteria 的全文',
2678
+ description: '可选:判据逐条写;不给就用 done_criteria 全文',
2480
2679
  },
2481
- criteria_note: { type: 'string', description: '判据的背景说明(不参与判定,只解释为什么这么定)' },
2680
+ criteria_note: { type: 'string', description: '判据的背景说明,不参与判定' },
2482
2681
  criteria_verdict: {
2483
2682
  type: 'string',
2484
- description: '改判据文本时要带的独立裁决 auditKey:改「怎样算完成」不能被顺手做掉',
2683
+ description: '改判据文本时的独立裁决 auditKey',
2485
2684
  },
2486
2685
  promote_at_level: { type: 'string', enum: MODEL_LEVELS, description: '升格门槛(默认 L3)' },
2487
2686
  irreversible: {
2488
2687
  type: 'array',
2489
- description: '不可逆的动作:做了就收不回、或结果不可重复的那几件(跑中试、下单、发出去的消息……)。每件写一句说明和它的命令特征(命令里一定会出现的一段原文)。匹配的命令执行前须经人工批准。修订目标时不传 = 不变',
2688
+ description: '计划实际执行的不可撤销或不可重复动作;匹配的命令执行前须人批准。禁止事项、判据与只读检查不填这里;没有这类动作写 []。修订时不传 = 不变',
2490
2689
  items: {
2491
2690
  type: 'object',
2492
2691
  properties: {
2493
- action: { type: 'string', description: '一句话:这是什么动作' },
2494
- command: { type: 'string', description: '命令特征:这类命令里一定出现的一段原文(如 "reactor.mjs state.json pilot")' },
2692
+ action: { type: 'string', description: '这是什么动作' },
2693
+ command: { type: 'string', description: '能区分该动作的命令原文(含操作及参数);不要仅用目录路径或通用解释器名,以免误拦只读检查' },
2495
2694
  },
2496
2695
  required: ['action', 'command'],
2497
2696
  additionalProperties: false,
2498
2697
  },
2499
2698
  },
2500
- mode: { type: 'string', enum: FRAME_MODES, description: '工作方式:survey = 广度调研(先铺调研板块,摸清后再看值得深入的问题);solve = 定向求解(问题下列出候选假设,用能区分它们的检验逐个排除);survey_then_solve = 先调研后求解。修订时不传 = 不变' },
2699
+ mode: { type: 'string', enum: FRAME_MODES, description: 'survey 广度调研;solve 定向求解;survey_then_solve 先调研后求解' },
2501
2700
  questions: {
2502
2701
  type: 'array',
2503
- description: '要回答的问题(可选;一个目标可以有几个,不写就把整个目标当一个问题)。调研中新发现的问题写成 status="emergent" 并挂到板块(area)下;人决定深入就改成 open,决定暂缓就改成 parked。修订时不传 = 不变,传了就是完整清单',
2702
+ description: '可选:要回答的问题。调研中新发现的写 status="emergent",人决定后改 open 或 parked。修订时传了就是完整清单',
2504
2703
  items: {
2505
2704
  type: 'object',
2506
2705
  properties: {
2507
- id: { type: 'string', description: '短 id(如 q1),判断的 question 与步骤的 serves 用它' },
2706
+ id: { type: 'string', description: '短 id(如 q1)' },
2508
2707
  text: { type: 'string', description: '一句话问题' },
2509
- status: { type: 'string', enum: QUESTION_STATUS, description: 'open = 在回答;emergent = 新发现、待决定;parked = 暂缓(结案时列入尚未确定的事项)' },
2510
- area: { type: 'string', description: '可选:属于哪个调研板块(板块 id)' },
2708
+ status: { type: 'string', enum: QUESTION_STATUS, description: 'open 在回答;emergent 待决定;parked 暂缓' },
2709
+ area: { type: 'string', description: '可选:所属调研板块 id' },
2511
2710
  },
2512
2711
  required: ['id', 'text'],
2513
2712
  additionalProperties: false,
2514
2713
  },
2515
2714
  },
2715
+ about: {
2716
+ type: 'array',
2717
+ items: { type: 'string' },
2718
+ description: '涉及的实体或量的 id(如 "R-2"、"yield"):据此定位已有条目,留下的条目也挂在这里',
2719
+ },
2720
+ conditions: {
2721
+ type: 'object',
2722
+ additionalProperties: { type: 'string' },
2723
+ description: '本次所处的条件,如 {"产线": "L2", "月份": "2026-09"};判断范围的缺省,也是引用判定的依据',
2724
+ },
2516
2725
  areas: {
2517
2726
  type: 'array',
2518
- description: '调研板块(广度调研用;如技术路线、主要企业、成本结构)。修订时不传 = 不变,传了就是完整清单',
2727
+ description: '调研板块(广度调研用)',
2519
2728
  items: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: ['id', 'name'], additionalProperties: false },
2520
2729
  },
2521
2730
  ontology: {
2522
2731
  type: 'object',
2523
- description: '本体条目,由系统校验后写进 clear/ontology/(内容与文件同形,字段见 clear/ontology/SCHEMA.json)。立题时先写清相关的量:度量(kind=measure,gloss 写口径,unit 写单位)由什么测量、读数如何核对(kind=measures 的关系,domain 是仪表或来源,range 是被测的度量,check 写核对办法);量之间如何相互影响(kind=affects 的关系,shape 写大致形状)。同 id 的文件会被替换',
2732
+ description: '可选:本体条目,校验后写进 clear/ontology/(字段见 SCHEMA.json);同 id 替换',
2524
2733
  properties: {
2525
- concepts: { type: 'array', items: { type: 'object' }, description: '概念:{id, label, gloss, kind: category|measure|phenomenon, unit?}' },
2526
- relations: { type: 'array', items: { type: 'object' }, description: '关系:{id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape?(affects), check?(measures)}' },
2734
+ concepts: { type: 'array', items: { type: 'object' }, description: '{id, label, gloss, kind: category|measure|phenomenon, unit?}' },
2735
+ relations: { type: 'array', items: { type: 'object' }, description: '{id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape?, check?}' },
2736
+ entities: { type: 'array', items: { type: 'object' }, description: '{id, type, label, basis, provenance: {kind: named, ref}}; definitions and assertions may be submitted together' },
2527
2737
  },
2528
2738
  additionalProperties: false,
2529
2739
  },
2530
2740
  hypotheses: {
2531
2741
  type: 'array',
2532
2742
  description:
2533
- '候选假设:每条一句话主张 + 一句推翻条件,一条只说一件事(「A,且 B」拆成两条);可带**类型化断言**(可选,提供即严校:谓词与概念必须已登记、宾语形态要合值域、同一事实里不许自相矛盾)。不写断言照旧成立——断言是加法,不是门槛。修订目标时不传这一项 = 判断不变;传了就是这一版的完整清单,没列出的会记成「已替换」。',
2743
+ '候选判断,一条只说一件事。修订时不传 = 不变;传了就是完整清单,没列出的记成已替换',
2534
2744
  items: {
2535
2745
  type: 'object',
2536
2746
  properties: {
2537
- name: { type: 'string', description: '短名,十二个汉字或二十来个字母以内,你自己起(如「python3 能跑」)。之后说起这条判断、在别的工具里引用它,都用这个名字' },
2747
+ name: { type: 'string', description: '短名(≤12 字),之后用它引用这条判断' },
2538
2748
  claim: { type: 'string' },
2539
- question: { type: 'string', description: '可选:属于哪个问题或调研板块(id);不写就归第一个问题' },
2540
- from: { type: 'string', description: '可选:由本体里哪条关系提出(关系 id,如有形状的 affects 关系);说不出来源就写「直觉」' },
2749
+ question: { type: 'string', description: '可选:所属问题或板块 id' },
2541
2750
  refute_when: { type: 'string' },
2751
+ about: { type: 'array', items: { type: 'string' }, description: '可选:涉及的实体或量 id;缺省取立题的 about' },
2752
+ uses: { type: 'array', items: { type: 'string' }, description: '可选:用到的已有条目 id(clear/knowledge/ 下的文件名);系统当场判定是否适用' },
2753
+ use: { type: 'string', description: '可选:支撑它的可重跑核算 id,先写 clear/models/<id>.json(command、inputs、output、tolerance,可选 baseline);输入或方法变了,引用时系统重跑;偏差与失败保持待核验' },
2754
+ scope: {
2755
+ type: 'object',
2756
+ description: '可选:在哪里成立。conditions 写条件,ranges 写取值范围(如 {"温度": [150, 175]}),units 写单位(如 {"温度":"°C"}),note 补一句;缺省取立题的 conditions',
2757
+ properties: { conditions: { type: 'object' }, ranges: { type: 'object' }, units: { type: 'object' }, note: { type: 'string' } },
2758
+ additionalProperties: false,
2759
+ },
2542
2760
  retests: {
2543
2761
  type: 'string',
2544
2762
  description:
2545
- '这条判断在复检哪条已写进长期知识的事实:写那条事实的 id(clear/knowledge/facts/<id>.json 的文件名)。claim 照抄那条事实原来的说法、拿新数据再验一遍,不要写成「它被推翻了」:这条判断被推翻,系统才会当场问人撤回还是维持那条事实——别的会话留下的事实也一样',
2763
+ '可选:复检哪条已有事实(事实 id)。claim 照抄原说法;被推翻时系统会问人撤回还是维持',
2546
2764
  },
2547
2765
  assertions: {
2548
2766
  type: 'array',
2549
- description: '断言:主词–谓词–宾语(引用领域词汇里的 id)',
2767
+ description: '可选:主词–谓词–宾语断言(引用本体 id),提供即严校',
2550
2768
  items: {
2551
2769
  type: 'object',
2552
2770
  properties: {
@@ -2569,7 +2787,7 @@ export function apply(ctx, config = {}) {
2569
2787
  additionalProperties: false,
2570
2788
  },
2571
2789
  },
2572
- reason: { type: 'string', description: '修订目标时必须写一句原因(首次立目标不需要)' },
2790
+ reason: { type: 'string', description: '修订时必填:改了什么、为什么' },
2573
2791
  },
2574
2792
  required: ['claim', 'done_criteria'],
2575
2793
  additionalProperties: false,
@@ -2582,7 +2800,7 @@ export function apply(ctx, config = {}) {
2582
2800
  const done = finish(hostService, sessionId, mutations)
2583
2801
  const criteria = String(args.done_criteria ?? '').trim()
2584
2802
  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.'))
2585
- const selfRef = SELF_REFERENCE.find(([pattern]) => pattern.test(criteria))
2803
+ const selfRef = SELF_REFERENCE.find(([pattern]) => [criteria, ...(Array.isArray(args.criteria) ? args.criteria : [])].some(value => pattern.test(String(value))))
2586
2804
  if (selfRef !== undefined) return fail('criteria_self_reference', tr(...selfRef[1]))
2587
2805
  if (typeof args.claim !== 'string' || args.claim.trim() === '') return fail('claim_required', tr('目标要有主张。', 'The goal needs a claim.'))
2588
2806
  // 迁移开关要在假设校验**之前**就有值:下面那条「主体必须可指认」对它放行。
@@ -2594,14 +2812,44 @@ export function apply(ctx, config = {}) {
2594
2812
  * 只改判据的修订若把缺省读成空清单,已被支持的判断会一起落成「已替换」,
2595
2813
  * 而替换是终态,按原文补登也回不来。要撤掉判断就显式列出留下的那几条。
2596
2814
  */
2815
+ const ontologyFiles = []
2816
+ for (const [branch, list] of [['concepts', args.ontology?.concepts], ['relations', args.ontology?.relations], ['entities', args.ontology?.entities]]) {
2817
+ for (const item of Array.isArray(list) ? list : []) {
2818
+ const id = String(item?.id ?? '').trim()
2819
+ const rel = `clear/ontology/${branch}/${id}.json`
2820
+ const problems = id === '' ? [tr('要有 id(就是文件名)', 'needs an id (the file name)')] : typeof hostService.domain?.checkFile === 'function' ? hostService.domain.checkFile(rel, item) : []
2821
+ 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')}`))
2822
+ ontologyFiles.push({ branch, id, rel, data: item })
2823
+ }
2824
+ }
2825
+ const ontologyDraft = ontologyFiles.length ? { t: 'workspace/synced', changes: ontologyFiles.map(file => ({ path: file.rel, data: file.data, digest: contentDigest(JSON.stringify(file.data)) })) } : null
2826
+ const assertionMutations = [...mutations, ...(ontologyDraft ? [ontologyDraft] : [])]
2597
2827
  const carried = args.hypotheses === undefined && state.goal !== null && state.goal.status === 'open'
2598
2828
  const hypotheses = Array.isArray(args.hypotheses)
2599
2829
  ? args.hypotheses
2600
2830
  : carried
2601
2831
  ? state.hypotheses
2602
2832
  .filter((item) => item.goal === state.goal.id && item.status !== 'superseded')
2603
- .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.from ? { from: item.from } : {}) }))
2833
+ .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) } : {}) }))
2604
2834
  : []
2835
+ /**
2836
+ * **取用的上下文**:工作区里的已有条目、本体里的实体与概念(按名称与别名对 `about`)、
2837
+ * 这次的条件(引用判定按它比范围)。只读,不拦立题。
2838
+ */
2839
+ let knownRows = []
2840
+ try {
2841
+ knownRows = knowledgeRows(call.derived ?? hostService.derive(sessionId))
2842
+ } catch {
2843
+ knownRows = []
2844
+ }
2845
+ const ontologyState = previewOf(hostService, sessionId, assertionMutations)?.state ?? state
2846
+ const ontologyEntries = [...(ontologyState.entities ?? []), ...(ontologyState.lexicon?.terms ?? []), ...(ontologyState.lexicon?.predicates ?? [])]
2847
+ const openGoal = state.goal !== null && state.goal.status === 'open' ? state.goal : null
2848
+ const conditionsNow = normalizeScope({ conditions: args.conditions })?.conditions ?? openGoal?.conditions ?? {}
2849
+ /** 名称或别名完全相同的,直接认作那个实体或概念的 id;相似的只提示。 */
2850
+ const canonicalAbout = (names) => mergeAbout(resolveAbout(names, ontologyEntries).map((item) => item.match ?? item.name))
2851
+ const aboutGiven = Array.isArray(args.about) ? mergeAbout(args.about) : []
2852
+ const goalAbout = Array.isArray(args.about) ? canonicalAbout(args.about) : (openGoal?.about ?? [])
2605
2853
  const names = hypotheses.map((hypothesis) => (typeof hypothesis?.name === 'string' ? hypothesis.name.trim() : '')).filter((name) => name !== '')
2606
2854
  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.'))
2607
2855
  for (const hypothesis of hypotheses) {
@@ -2611,6 +2859,24 @@ export function apply(ctx, config = {}) {
2611
2859
  if (hypothesis?.retests !== undefined && hypothesis.retests !== null && findFact(sessionId, state, hypothesis.retests) === null) {
2612
2860
  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.`))
2613
2861
  }
2862
+ const unknownUses = (Array.isArray(hypothesis?.uses) ? hypothesis.uses : []).map((id) => String(id ?? '').trim()).filter((id) => id !== '' && !knownRows.some((row) => row.id === id))
2863
+ if (unknownUses.length > 0) {
2864
+ 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.`))
2865
+ }
2866
+ /** `use`:可重跑核算的 id;登记文件要在、要合格,升格时才带得上。 */
2867
+ if (typeof hypothesis?.use === 'string' && hypothesis.use.trim() !== '') {
2868
+ const modelId = hypothesis.use.trim()
2869
+ const cwd = sessionCwd(sessionId)
2870
+ let spec = null
2871
+ try {
2872
+ spec = cwd === null || !MODEL_ID.test(modelId) ? null : JSON.parse(readFileSync(join(cwd, 'clear', 'models', `${modelId}.json`), 'utf8'))
2873
+ } catch {
2874
+ spec = null
2875
+ }
2876
+ 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).`))
2877
+ const problems = checkModelSpec(spec, modelId)
2878
+ if (problems.length > 0) return fail('use_invalid', tr(`clear/models/${modelId}.json 不合格:${problems.join(';')}`, `clear/models/${modelId}.json is not usable: ${problems.join('; ')}`))
2879
+ }
2614
2880
  /**
2615
2881
  * **宽松+校验**:不写断言放行(断言是加法),写了就在**落账之前**严校——
2616
2882
  * 引用不存在的谓词 / 概念、宾语形态不合值域、同一事实自相矛盾,一律当场拒。
@@ -2621,7 +2887,7 @@ export function apply(ctx, config = {}) {
2621
2887
  if (judge === null) return fail('domain_unavailable', tr('这一层的宿主没有提供领域判据(domain facade):无法校验断言。请检查宿主半与预设是否同版本。', 'The host did not provide the domain facade, so assertions cannot be checked. Check that the host half and the preset are the same version.'))
2622
2888
  // `legacy`:迁移期一次性放行「主体还没登记」这条(`Frame` 的 `legacy:true`)——
2623
2889
  // 旧会话的断言主体在登记实例这条路存在之前就写下了,不该因为补上了机制而追溯失败。
2624
- const problems = judge.validateAssertions(sessionId, hypothesis.assertions, { legacy, mutations })
2890
+ const problems = judge.validateAssertions(sessionId, hypothesis.assertions, { legacy, mutations: assertionMutations })
2625
2891
  if (problems.length > 0) {
2626
2892
  return fail('assertions_rejected', tr(`这条假设的断言不能成立(先在 clear/ontology/ 下写好用到的概念、关系与主体实体文件,或改断言):\n${problems.map((item) => `- ${item}`).join('\n')}`, `This judgment's assertions do not hold (first write the concepts, relations and subject entity files they use under clear/ontology/, or change the assertions):\n${problems.map((item) => `- ${item}`).join('\n')}`))
2627
2893
  }
@@ -2729,20 +2995,7 @@ export function apply(ctx, config = {}) {
2729
2995
  * **本体随立题写入**(`ontology`):逐个文件用宿主半的 `domain.checkFile` 校验,全部过了才写盘。
2730
2996
  * 为什么放进 Frame:模型要另写文件时,本体总被排到最后、最后没写;立题时写,预测和候选才有出处。
2731
2997
  */
2732
- const ontologyFiles = []
2733
- for (const [branch, list] of [['concepts', args.ontology?.concepts], ['relations', args.ontology?.relations]]) {
2734
- for (const item of Array.isArray(list) ? list : []) {
2735
- const id = String(item?.id ?? '').trim()
2736
- const rel = `clear/ontology/${branch}/${id}.json`
2737
- const problems = id === '' ? [tr('要有 id(就是文件名)', 'needs an id (the file name)')] : typeof hostService.domain?.checkFile === 'function' ? hostService.domain.checkFile(rel, item) : []
2738
- 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')}`))
2739
- ontologyFiles.push({ branch, id, rel, data: item })
2740
- }
2741
- }
2742
- if (CFG.requireMeasures && !isRevision && !legacy) {
2743
- const missing = unmeasured(state, ontologyFiles)
2744
- if (missing !== null) return fail('measures_required', missing)
2745
- }
2998
+
2746
2999
  for (const file of ontologyFiles) {
2747
3000
  const target = sessionFile(sessionId, 'clear', 'ontology', file.branch, `${file.id}.json`)
2748
3001
  if (target === null) return fail('workspace_unavailable', tr('这一刻拿不到会话的工作目录,本体条目没有写入。', 'The session workspace is unavailable right now; the ontology entries were not written.'))
@@ -2768,10 +3021,46 @@ export function apply(ctx, config = {}) {
2768
3021
  const claimKey = (text) => String(text ?? '').trim().replace(/\s+/g, ' ')
2769
3022
  const idByClaim = new Map(existing.map((item) => [claimKey(item.claim), item.id]))
2770
3023
  const reused = new Set()
3024
+ /**
3025
+ * **引用时判定是否适用**:判断 `uses` 里的每条已有条目,按条目自己的状态与适用范围
3026
+ * (对这条判断的范围,缺的维度取这次的条件)判一次;判定随判断落账,也随结果说给模型。
3027
+ */
3028
+ const cites = []
3029
+ /**
3030
+ * **引用前先重跑核算**:被引用的事实挂着 `use`(可重跑的核算)且输入变了,先跑一次再判定;
3031
+ * 结果超出容差,这条事实判为待核验,同时登记一条未解释项(反常不依赖模型自己留意)。
3032
+ */
3033
+ const modelRuns = new Map()
3034
+ for (const hypothesis of CFG.applicabilityFeedback ? hypotheses : []) {
3035
+ for (const id of mergeAbout(hypothesis?.uses)) {
3036
+ const row = knownRows.find((item) => item.id === id) ?? null
3037
+ if (['out_of_scope', 'out_of_range'].includes(compareScope(row?.scope_spec, mergeScope(hypothesis.scope, { conditions: conditionsNow })).verdict)) continue
3038
+ if (typeof row?.use === 'string' && row.use !== '' && !modelRuns.has(row.id)) modelRuns.set(row.id, await rerunModel(sessionId, row.use, row, exec))
3039
+ }
3040
+ }
3041
+ const driftOpened = new Set()
3042
+ for (const [factId, run] of modelRuns) {
3043
+ if (run.status !== 'rerun' || run.deviations.length === 0) continue
3044
+ for (const row of knownRows.filter((item) => item.id === factId)) {
3045
+ if (driftOpened.has(row.id)) continue
3046
+ driftOpened.add(row.id)
3047
+ 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' })
3048
+ }
3049
+ }
3050
+ const usesOf = (hypothesis) =>
3051
+ mergeAbout(hypothesis?.uses).map((id) => {
3052
+ const row = knownRows.find((item) => item.id === id) ?? null
3053
+ const run = typeof row?.use === 'string' ? (modelRuns.get(row.id) ?? null) : null
3054
+ const drifted = run?.pending === true
3055
+ 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 } : {}) }
3056
+ 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 })
3057
+ return { id, kind: row?.kind ?? null, verdict: verdict.verdict }
3058
+ })
2771
3059
  const nextHypotheses = hypotheses.map((hypothesis, index) => {
2772
3060
  const claim = hypothesis.claim.trim()
2773
3061
  const carried = idByClaim.get(claimKey(claim))
2774
3062
  if (carried !== undefined) reused.add(carried)
3063
+ const hAbout = canonicalAbout(mergeAbout(hypothesis.about, CFG.ontologyFeedback ? (hypothesis.assertions ?? []).flatMap(a => [a.subject?.id, a.subject?.type, a.predicate, ...(a.object?.kind === 'instance' ? [a.object.value] : [])]).filter(Boolean) : []))
2775
3064
  const given = typeof hypothesis.name === 'string' ? hypothesis.name.trim() : ''
2776
3065
  const kept = carried === undefined ? '' : String(existing.find((item) => item.id === carried)?.name ?? '')
2777
3066
  return {
@@ -2782,10 +3071,15 @@ export function apply(ctx, config = {}) {
2782
3071
  refute_when: hypothesis.refute_when.trim(),
2783
3072
  /** 复检哪条已有事实(跨会话的身份是事实 id;判断 id 只活在本目标里)。 */
2784
3073
  ...(typeof hypothesis.retests === 'string' && hypothesis.retests.trim() !== '' ? { retests: hypothesis.retests.trim() } : {}),
3074
+ /** 可重跑的核算(`clear/models/<id>.json`):升格时随事实写进文件,之后引用时据它重跑。 */
3075
+ ...(typeof hypothesis.use === 'string' && hypothesis.use.trim() !== '' ? { use: hypothesis.use.trim() } : {}),
2785
3076
  /** 断言随假设落账;没写就是 null(加法,不是门槛)。 */
2786
3077
  assertions: Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null,
2787
3078
  ...(typeof hypothesis.question === 'string' && hypothesis.question.trim() !== '' ? { question: hypothesis.question.trim() } : {}),
2788
- ...(typeof hypothesis.from === 'string' && hypothesis.from.trim() !== '' ? { from: hypothesis.from.trim().slice(0, 80) } : {}),
3079
+ /** 适用范围(在哪里成立),与推翻条件分开;没写就在升格时取立题的 conditions。 */
3080
+ ...(normalizeScope(hypothesis.scope) !== null ? { scope: normalizeScope(hypothesis.scope) } : {}),
3081
+ ...(hAbout.length > 0 ? { about: hAbout } : {}),
3082
+ ...(usesOf(hypothesis).length > 0 ? { uses: usesOf(hypothesis) } : {}),
2789
3083
  version: index + 1,
2790
3084
  }
2791
3085
  })
@@ -2806,6 +3100,8 @@ export function apply(ctx, config = {}) {
2806
3100
  ...(FRAME_MODES.includes(args.mode) ? { mode: args.mode } : {}),
2807
3101
  ...(questions !== null ? { questions } : {}),
2808
3102
  ...(areas !== null ? { areas } : {}),
3103
+ ...(normalizeScope({ conditions: args.conditions }) !== null ? { conditions: normalizeScope({ conditions: args.conditions }).conditions } : {}),
3104
+ ...(Array.isArray(args.about) ? { about: goalAbout } : {}),
2809
3105
  })
2810
3106
  for (const dropped of existing) {
2811
3107
  if (reused.has(dropped.id)) continue
@@ -2818,6 +3114,7 @@ export function apply(ctx, config = {}) {
2818
3114
  code: isRevision ? 'goal_revised' : 'goal_set',
2819
3115
  message:
2820
3116
  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.` : ''}`) +
3117
+ frameKnowledgeNote({ about: goalAbout, resolved: resolveAbout(aboutGiven, ontologyEntries), related: relatedKnowledge(knownRows, goalAbout), cites: CFG.applicabilityFeedback ? cites : [], rows: knownRows }) +
2821
3118
  // 原生 goal 上那一句给人看:用目标的一句话,不写 id。
2822
3119
  attachNativeGoal(exec.agent, clip(headline === '' ? String(args.claim ?? '') : headline, 120)),
2823
3120
  })
@@ -2847,11 +3144,13 @@ export function apply(ctx, config = {}) {
2847
3144
  /** 结论四部分的唯一形状:结论 / 依据 / 尚未确定的事项(各写涉及什么、对答案的影响)/ 待您决策。 */
2848
3145
  function normalizeAnswers(raw) {
2849
3146
  if (!Array.isArray(raw)) return []
2850
- const lines = (list, width) => (Array.isArray(list) ? list : []).map((item) => String(item ?? '').trim().slice(0, width)).filter((item) => item !== '')
3147
+ const lines = (list, width) => (Array.isArray(list) ? list : []).map((item) => String(item ?? '').trim()).filter((item) => item !== '')
2851
3148
  return raw
2852
3149
  .map((item) => ({
2853
3150
  question: String(item?.question ?? '').trim(),
2854
- conclusion: String(item?.conclusion ?? '').trim().slice(0, 600),
3151
+ uses: mergeAbout(item?.uses),
3152
+ scope: normalizeScope(item?.scope),
3153
+ conclusion: String(item?.conclusion ?? '').trim(),
2855
3154
  basis: lines(item?.basis, 300).slice(0, 12),
2856
3155
  open: (Array.isArray(item?.open) ? item.open : [])
2857
3156
  .map((entry) => ({ about: lines(entry?.about, 80).slice(0, 8), effect: String(entry?.effect ?? '').trim().slice(0, 300) }))
@@ -2891,7 +3190,7 @@ export function apply(ctx, config = {}) {
2891
3190
  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.`))
2892
3191
  }
2893
3192
  }
2894
- for (const anomaly of (state.anomalies ?? []).filter((item) => item?.status === 'open')) {
3193
+ for (const anomaly of (state.anomalies ?? []).filter((item) => item?.status === 'open' && !(item.by === 'evaluator' && item.matters === 'no'))) {
2895
3194
  if (about.has(anomaly.id)) continue
2896
3195
  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.`))
2897
3196
  }
@@ -2909,6 +3208,7 @@ export function apply(ctx, config = {}) {
2909
3208
  tr('# 结论(做的人按问题写的四部分;请核它与记录是否一致,依据是否真在记录里)', '# Conclusions (written by the worker per question; check they match the record and that the basis is really in it)'),
2910
3209
  ...answers.flatMap((answer) => [
2911
3210
  `## ${answer.question || tr('目标', 'goal')}:${answer.conclusion || tr(`未回答(${answer.unanswered})`, `unanswered (${answer.unanswered})`)}`,
3211
+ ...(answer.uses.length ? [`- 实际采用 / actual uses: ${answer.uses.join(', ')}; scope: ${JSON.stringify(answer.scope)}`] : []),
2912
3212
  ...answer.basis.map((line) => tr(`- 依据:${line}`, `- basis: ${line}`)),
2913
3213
  ...answer.open.map((entry) => tr(`- 尚未确定(${entry.about.join('、') || '—'}):${entry.effect}`, `- open (${entry.about.join(', ') || '—'}): ${entry.effect}`)),
2914
3214
  ...answer.decide.map((line) => tr(`- 待您决策:${line}`, `- for the user to decide: ${line}`)),
@@ -2932,28 +3232,30 @@ export function apply(ctx, config = {}) {
2932
3232
  defineTool({
2933
3233
  name: 'Conclude',
2934
3234
  description:
2935
- '结案:交目标验收——这是完成目标的唯一路径(原生「完成目标」会被拒)。系统**无条件**派独立评估者,拿目标判据与转写忠实度逐条核对;判据达成才结案为 achieved:原生 goal 置为完成;评估者同时逐条判尚在考察中的判断,判为支持的(或中途已达门槛的)升格为事实;各步收下的产物声明为交付卡片;随结案提议的经验(`lessons`)由评估者逐条核,支持的写进 clear/knowledge/lessons/。否则目标保持开放并回注缺口。**顺序**:achieved 之前必须先把计划收尾(`ClosePlan`)。放弃(`abandoned`)不受此限:原生 goal 置为阻塞,写明原因,由人决定结束。',
3235
+ '结案,完成目标的唯一路径。独立评估者逐条核判据:达成才结案为 achieved,它支持的判断升格为事实、支持的经验写入;否则返回缺口。achieved 之前先 ClosePlan;abandoned 写明阻塞,由人决定结束。',
2936
3236
  parameters: {
2937
3237
  type: 'object',
2938
3238
  properties: {
2939
- outcome: { type: 'string', enum: ['achieved', 'abandoned'], description: 'achieved=判据已达成;abandoned=如实说清阻塞后放弃' },
3239
+ outcome: { type: 'string', enum: ['achieved', 'abandoned'], description: 'achieved 判据已达成;abandoned 说清阻塞后放弃' },
2940
3240
  note: { type: 'string', description: '结案说明' },
2941
3241
  answers: {
2942
3242
  type: 'array',
2943
- description: '结论(achieved 时按问题各写一条;目标没列问题就写一条):结论 / 依据 / 尚未确定的事项 / 待您决策。中间判断与过程不写进来。还在考察中、未得到支持的候选假设,还开着的未解释项,都要写进「尚未确定的事项」并说明若它成立答案会如何改变',
3243
+ description: 'achieved 时按问题各写一条。还在考察的候选与开着的未解释项写进 open 并说明影响',
2944
3244
  items: {
2945
3245
  type: 'object',
2946
3246
  properties: {
2947
- question: { type: 'string', description: '哪个问题(id);目标没列问题时可省略' },
2948
- conclusion: { type: 'string', description: '结论:一两句话,带数值与适用条件' },
2949
- basis: { type: 'array', items: { type: 'string' }, description: '依据:每个已采纳、已排除的候选假设或已核验的读数各一行,注明对应的实验或来源' },
3247
+ question: { type: 'string', description: '问题 id;目标没列问题时省略' },
3248
+ conclusion: { type: 'string', description: '一两句结论,带数值与适用条件' },
3249
+ uses: { type: 'array', items: { type: 'string' }, description: '最终答案直接使用的知识条目 id,不自动继承立题引用' },
3250
+ scope: { type: 'object', description: '此答案的适用范围,数值范围须带 units' },
3251
+ basis: { type: 'array', items: { type: 'string' }, description: '每个采纳、排除的候选或核验的读数一行,注明来源' },
2950
3252
  open: {
2951
3253
  type: 'array',
2952
- description: '尚未确定的事项:每项写涉及什么(about:候选假设短名、未解释项 id 或问题 id)与对结论的影响(effect:若它成立,结论如何改变)',
3254
+ description: '尚未确定的事项:about 写候选短名、未解释项或问题 id,effect 写若它成立结论如何变',
2953
3255
  items: { type: 'object', properties: { about: { type: 'array', items: { type: 'string' } }, effect: { type: 'string' } }, required: ['effect'], additionalProperties: false },
2954
3256
  },
2955
- decide: { type: 'array', items: { type: 'string' }, description: '待您决策:需要人决定的事项(例如是否先复测再放大)' },
2956
- unanswered: { type: 'string', description: '未能回答时写明原因(此时 conclusion 可省略)' },
3257
+ decide: { type: 'array', items: { type: 'string' }, description: '待人决策的事项' },
3258
+ unanswered: { type: 'string', description: '未能回答的原因(此时可省 conclusion)' },
2957
3259
  },
2958
3260
  additionalProperties: false,
2959
3261
  },
@@ -2961,15 +3263,15 @@ export function apply(ctx, config = {}) {
2961
3263
  lessons: {
2962
3264
  type: 'array',
2963
3265
  maxItems: 5,
2964
- description: '经验(可选,只在 achieved 时核):这次摸出的、下次在同类现场改变做法的东西,不是这次结论的复述。评估者逐条对照记录核,判为支持的写进 clear/knowledge/lessons/,之后的会话在立题和定计划时会看到',
3266
+ description: '可选:下次在同类现场会改变做法的经验,评估者核过才写入',
2965
3267
  items: {
2966
3268
  type: 'object',
2967
3269
  properties: {
2968
- text: { type: 'string', description: '一句话,下次怎么做(「这类装置的关键读数先用独立来源核一次」)' },
2969
- kind: { type: 'string', enum: LESSON_KINDS, description: 'trap=会踩的坑;check=要先核的读数或假设;shortcut=省事但会骗人的做法;prior=对这类体系的先验(例如「两个因素常常耦合,先做斜向扫描」)' },
2970
- about: { type: 'array', items: { type: 'string' }, description: '涉及的装置、量或概念(短名,用来下次匹配)' },
2971
- evidence: { type: 'string', description: '这次记录里哪处表明了它(步骤、文件)' },
2972
- boundary: { type: 'string', description: '在什么条件下不适用' },
3270
+ text: { type: 'string', description: '一句话,下次怎么做' },
3271
+ kind: { type: 'string', enum: LESSON_KINDS, description: 'trap 坑;check 要先核的;shortcut 会骗人的捷径;prior 先验' },
3272
+ about: { type: 'array', items: { type: 'string' }, description: '涉及的装置、量或概念 id' },
3273
+ evidence: { type: 'string', description: '记录里哪处表明了它' },
3274
+ boundary: { type: 'string', description: '什么条件下不适用' },
2973
3275
  },
2974
3276
  required: ['text', 'kind'],
2975
3277
  additionalProperties: false,
@@ -3087,18 +3389,37 @@ export function apply(ctx, config = {}) {
3087
3389
  artifacts: [],
3088
3390
  tests: candidates.length === 0 ? null : { hypotheses: candidates.map((hypothesis) => hypothesis.id), level: goal.promote_at_level },
3089
3391
  }
3392
+ let finalRows = knowledgeRows(derived)
3393
+ for (const id of new Set(answers.flatMap((answer) => answer.uses))) {
3394
+ const fact = finalRows.find((row) => row.id === id)
3395
+ if (fact?.use && CFG.applicabilityFeedback) {
3396
+ const run = await rerunModel(sessionId, fact.use, fact, exec)
3397
+ if (run.pending && run.persisted === false) return fail('recheck_persist_failed', '引用复核状态未能保存,保持开放', { mutations })
3398
+ }
3399
+ }
3400
+ const finalSync = syncWorkspace(sessionId, state)
3401
+ if (finalSync !== null) mutations.push(finalSync)
3402
+ const finalView = previewOf(hostService, sessionId, mutations)
3403
+ if (finalView !== null) finalRows = knowledgeRows(finalView.derived)
3404
+ 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))
3405
+ if (CFG.applicabilityFeedback && invalidUses.length) return fail('answer_uses_invalid', `最终引用尚不可使用: ${invalidUses.map((cite) => `${cite.id}: ${cite.verdict}`).join('; ')}。复检后再引用;如采用独立新证据,直接列出它,不要声明旧知识已恢复。`, { mutations })
3090
3406
  const proposedLessons = proposedLessonsOf(args.lessons)
3091
3407
  const gate = {
3092
3408
  confirmed: [
3093
3409
  ...state.evidence.map((item) => ({ ref: `evidence:${item.id}`, bytes: 0, digest: `verdict=${item.verdict}` })),
3094
3410
  ...derived.hypotheses.map((item) => ({ ref: `hypothesis:${item.id}`, bytes: 0, digest: `${item.status}/支持到${item.supportedLevel ?? '—'}` })),
3095
3411
  ],
3412
+ answers, lessons: proposedLessons,
3096
3413
  extra: [...answersBrief(answers), ...lessonBrief(proposedLessons)],
3097
3414
  }
3098
3415
  const audit = await runEvaluator(sessionId, exec.agent, plan, syntheticStep, gate, 'goal_audit', exec.signal)
3099
3416
  mutations.push(...audit.mutations)
3100
3417
  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 })
3101
3418
  if (audit.holds !== 'yes') {
3419
+ const failureStep = `goal:${goal.id}:${audit.digest ?? 'unknown'}`
3420
+ const failures = (state.blocks[`goal:${failureStep}`] ?? 0) + 1
3421
+ mutations.push({ t: 'block/counted', plan: 'goal', step: failureStep, count: failures, reason: `goal_audit:${audit.holds}` })
3422
+ if (failures >= CFG.blockedThreshold) blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, `目标审查连续失败 ${failures} 次,保持开放并停止续跑`)
3102
3423
  /**
3103
3424
  * **复用来的裁决不落第二条证据**。
3104
3425
  *
@@ -3154,6 +3475,22 @@ export function apply(ctx, config = {}) {
3154
3475
  { mutations },
3155
3476
  )
3156
3477
  }
3478
+ /**
3479
+ * **停止检查在审计之后再做一次**:评估者这次审计里新报的未解释项(做的人没登记、或排除理由站不住),
3480
+ * 只要它没说「不影响结论」,也要在结论里有交代。审计结算已经落账,这些项会挂在卡上;
3481
+ * 补写 `answers` 后再结案,材料没变,裁决复用,不再花一次评估。
3482
+ * 只在审计之前看的话,评估者指出的问题从不经过停止检查。
3483
+ */
3484
+ const afterAudit = previewOf(hostService, sessionId, mutations)
3485
+ if (afterAudit === null) return fail('host_unavailable', '审计后无法重新核对材料,保持开放', { mutations })
3486
+ if (CFG.requireAnswers) {
3487
+ const missing = unsettledForAnswers(afterAudit.state, afterAudit.derived, answers)
3488
+ if (missing.length) return fail('answers_incomplete', `审计后仍有未处理事项:\n${missing.join('\n')}`, { mutations })
3489
+ }
3490
+ 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))
3491
+ if (CFG.applicabilityFeedback && afterUses.length) return fail('answer_uses_invalid', '审计期间引用状态发生变化,保持开放', { mutations })
3492
+ 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 }))
3493
+
3157
3494
  /**
3158
3495
  * **没被任何证据触及的假设**,结案时如实记一笔。
3159
3496
  *
@@ -3215,84 +3552,7 @@ export function apply(ctx, config = {}) {
3215
3552
  }
3216
3553
  }
3217
3554
  }
3218
- const threshold = levelIndexOf(goal.promote_at_level)
3219
- const promoted = []
3220
- /** 升格时第三道校验没过的判断:不升格,回执里写清卡在哪。 */
3221
- const held = []
3222
- for (const hypothesis of derived.hypotheses) {
3223
- /**
3224
- * 只升格**这个目标**的判断,且每条只升格一次:上一个目标的判断状态仍是 alive,
3225
- * 不挡的话下一次结案会把它再写一遍(同一条结论两个事实文件)。
3226
- */
3227
- if (typeof hypothesis.goal === 'string' && hypothesis.goal !== goal.id) continue
3228
- if ((state.facts ?? []).some((fact) => fact.hypothesis === hypothesis.id)) continue
3229
- if (hypothesis.status !== 'alive' && hypothesis.status !== 'proposed') continue
3230
- if (hypothesis.refutations > 0) continue
3231
- const atClose = judged.get(hypothesis.id)
3232
- if (atClose?.verdict === 'refute') continue
3233
- const reached = levelIndexOf(hypothesis.supportedLevel) >= threshold
3234
- if (!reached && atClose?.verdict !== 'support') continue
3235
- const factLevel = reached ? hypothesis.supportedLevel : goal.promote_at_level
3236
- const assertions = Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null
3237
- /**
3238
- * **第三道校验(升格时)**:断言涉及的谓词、类型、主体此刻都要在本体文件里成立。
3239
- * 平时跨文件的问题只提示(模型改一组文件时中间态必然不一致);写进长期知识这一刻不行。
3240
- */
3241
- if (assertions !== null && assertions.length > 0) {
3242
- let problems = []
3243
- try {
3244
- problems = hostService.domain?.validateAssertions?.(sessionId, assertions, { mutations }) ?? []
3245
- } catch (error) {
3246
- problems = [tr(`校验这一刻做不了:${String(error?.message ?? error).slice(0, 160)}`, `Could not check right now: ${String(error?.message ?? error).slice(0, 160)}`)]
3247
- }
3248
- if (problems.length > 0) {
3249
- held.push(`${quote(handleOf(hypothesis))}${tr(':', ': ')}${problems.map(String).join(tr(';', '; '))}`)
3250
- continue
3251
- }
3252
- }
3253
- const factId = `f-${Math.random().toString(36).slice(2, 8)}`
3254
- const evidence = evidenceFor(state, hypothesis.id)
3255
- .filter((item) => item.verdict === 'support')
3256
- .map((item) => item.id)
3257
- if (atClose?.verdict === 'support') evidence.push(atClose.evidence)
3258
- /**
3259
- * 升格这一刻它用到的词条的含义指纹:之后谁改了定义,这条事实就知道要复核。
3260
- * 「用到」= 断言引用的,加上主张与边界原文里按词面提到的(模型很少写断言,见 fingerprintDefinitions)。
3261
- */
3262
- let definitions = null
3263
- try {
3264
- const said = `${hypothesis.claim ?? ''}\n${hypothesis.refute_when ?? ''}`
3265
- const found = hostService.domain?.definitions?.(sessionId, assertions ?? [], mutations, said) ?? null
3266
- definitions = found !== null && Object.keys(found).length > 0 ? found : null
3267
- } catch {
3268
- definitions = null
3269
- }
3270
- const record = { id: factId, goal: goal.id, hypothesis: hypothesis.id, text: hypothesis.claim, scope: hypothesis.refute_when ?? null, level: factLevel ?? null, evidence, assertions, definitions }
3271
- const path = persistFact(sessionId, record)
3272
- /**
3273
- * 事实带上**边界**(`scope` = 这条假设的推翻条件):没有边界的事实,下一轮没人敢用;
3274
- * 有边界才算「已知」而不是「口号」。它与出处(证据 id)、等级一起进事实库与货架。
3275
- */
3276
- mutations.push({
3277
- t: 'fact/promoted',
3278
- id: factId,
3279
- goal: goal.id,
3280
- /**
3281
- * **身份与内容一起定型**:`hypothesis` 是产出它的那条假设(按 id 关联,
3282
- * 措辞改了也认得出),`assertions` 是这条事实的类型化内容(没写就是 null)。
3283
- * 断言只在**升格这一刻**落地——旧事实不会被回溯改写。
3284
- */
3285
- hypothesis: hypothesis.id,
3286
- text: hypothesis.claim,
3287
- scope: hypothesis.refute_when ?? null,
3288
- level: factLevel ?? null,
3289
- evidence,
3290
- assertions,
3291
- definitions,
3292
- path,
3293
- })
3294
- promoted.push({ id: factId, claim: hypothesis.claim })
3295
- }
3555
+ const { promoted, held } = promoteFacts(hostService, sessionId, state, derived, goal, judged, mutations)
3296
3556
  /** 评估者判为支持的经验写成文件;别的如实说出来,不写。 */
3297
3557
  const lessonVerdicts = new Map((audit.lessons ?? []).map((item) => [item.lesson, item]))
3298
3558
  const keptLessons = []
@@ -3303,9 +3563,11 @@ export function apply(ctx, config = {}) {
3303
3563
  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})` : ''}`}`)
3304
3564
  return
3305
3565
  }
3306
- const record = { id: `l-${Math.random().toString(36).slice(2, 8)}`, goal: goal.id, ...lesson, basis: verdict.basis }
3566
+ /** 经验也带适用范围(立题的 conditions)与涉及对象(经验自己写的加上立题的),与事实同形。 */
3567
+ const lessonScope = mergeScope({ conditions: goal.conditions ?? {} }, null)
3568
+ 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 }
3307
3569
  const path = persistLesson(sessionId, record)
3308
- 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 })
3570
+ 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 })
3309
3571
  keptLessons.push(record)
3310
3572
  })
3311
3573
  return done({
@@ -3340,6 +3602,106 @@ export function apply(ctx, config = {}) {
3340
3602
  * 每个会话每一拍把这个目录同步进自己的账(`workspace/synced`),于是别的会话升格的事实
3341
3603
  * 在这里也是「已知」,复核结论(撤回 / 维持)也写在同一个文件上。
3342
3604
  */
3605
+ function promoteFacts(hostService, sessionId, state, derived, goal, judged, mutations, { partial = false, eligible = new Set() } = {}) {
3606
+ const threshold = levelIndexOf(goal.promote_at_level)
3607
+ const promoted = []
3608
+ /** 升格时第三道校验没过的判断:不升格,回执里写清卡在哪。 */
3609
+ const held = []
3610
+ for (const hypothesis of derived.hypotheses) {
3611
+ /**
3612
+ * 只升格**这个目标**的判断,且每条只升格一次:上一个目标的判断状态仍是 alive,
3613
+ * 不挡的话下一次结案会把它再写一遍(同一条结论两个事实文件)。
3614
+ */
3615
+ if (typeof hypothesis.goal === 'string' && hypothesis.goal !== goal.id) continue
3616
+ if ((state.facts ?? []).some((fact) => fact.hypothesis === hypothesis.id)) continue
3617
+ if (hypothesis.status !== 'alive' && hypothesis.status !== 'proposed') continue
3618
+ if (hypothesis.refutations > 0) continue
3619
+ const atClose = judged.get(hypothesis.id)
3620
+ if (partial && ((hypothesis.unlanded?.length ?? 0) > 0 || !eligible.has(hypothesis.id) || !(hypothesis.assertions?.length) ||
3621
+ !evidenceFor(state, hypothesis.id).some(e => e.verdict === 'support' && e.evaluator === 'independent' && levelIndexOf(e.level) >= Math.max(3, threshold)))) continue
3622
+ if (atClose?.verdict === 'refute') continue
3623
+ const reached = levelIndexOf(hypothesis.supportedLevel) >= threshold
3624
+ if (!reached && atClose?.verdict !== 'support') continue
3625
+ const factLevel = reached ? hypothesis.supportedLevel : goal.promote_at_level
3626
+ const assertions = Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null
3627
+ /**
3628
+ * **第三道校验(升格时)**:断言涉及的谓词、类型、主体此刻都要在本体文件里成立。
3629
+ * 平时跨文件的问题只提示(模型改一组文件时中间态必然不一致);写进长期知识这一刻不行。
3630
+ */
3631
+ if (assertions !== null && assertions.length > 0) {
3632
+ let problems = []
3633
+ try {
3634
+ problems = hostService.domain?.validateAssertions?.(sessionId, assertions, { mutations }) ?? ['domain unavailable']
3635
+ } catch (error) {
3636
+ problems = [tr(`校验这一刻做不了:${String(error?.message ?? error).slice(0, 160)}`, `Could not check right now: ${String(error?.message ?? error).slice(0, 160)}`)]
3637
+ }
3638
+ if (problems.length > 0) {
3639
+ held.push(`${quote(handleOf(hypothesis))}${tr(':', ': ')}${problems.map(String).join(tr(';', '; '))}`)
3640
+ continue
3641
+ }
3642
+ }
3643
+ const factId = `f-${Math.random().toString(36).slice(2, 8)}`
3644
+ const evidence = evidenceFor(state, hypothesis.id)
3645
+ .filter((item) => item.verdict === 'support')
3646
+ .map((item) => item.id)
3647
+ if (atClose?.verdict === 'support') evidence.push(atClose.evidence)
3648
+ /**
3649
+ * 升格这一刻它用到的词条的含义指纹:之后谁改了定义,这条事实就知道要复核。
3650
+ * 「用到」= 断言引用的,加上主张与边界原文里按词面提到的(模型很少写断言,见 fingerprintDefinitions)。
3651
+ */
3652
+ let definitions = null
3653
+ try {
3654
+ const aboutIds = mergeAbout(hypothesis.about, goal.about)
3655
+ const entityTypes = (state.entities ?? []).filter((entity) => aboutIds.includes(entity.id)).map((entity) => entity.type)
3656
+ const said = `${hypothesis.claim ?? ''}\n${hypothesis.refute_when ?? ''}\n${[...aboutIds, ...entityTypes].join(' ')}`
3657
+ const found = hostService.domain?.definitions?.(sessionId, assertions ?? [], mutations, said) ?? null
3658
+ definitions = found !== null && Object.keys(found).length > 0 ? found : null
3659
+ } catch {
3660
+ definitions = null
3661
+ }
3662
+ /**
3663
+ * **适用范围与推翻条件分开存**:范围取判断自己写的,缺的维度用立题的 conditions 补;
3664
+ * 都没有就如实是 null(「范围未声明」)。推翻条件另存在 `refute_when`。
3665
+ */
3666
+ const scopeSpec = mergeScope(hypothesis.scope, { conditions: goal.conditions ?? {} })
3667
+ const scope = scopeSpec === null ? null : tr(scopeText(scopeSpec, 'zh'), scopeText(scopeSpec, 'en'))
3668
+ /** 涉及的实体或量:判断自己写的加上立题的,文件查找按它们取到这条事实。 */
3669
+ const about = mergeAbout(hypothesis.about, goal.about)
3670
+ const evidenceRecords = [...state.evidence, ...mutations.filter((item) => item.t === 'evidence/recorded')].filter((item) => evidence.includes(item.id))
3671
+ 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) } : {}) }
3672
+ const path = persistFact(sessionId, record)
3673
+ if (path === null) { held.push(`${handleOf(hypothesis)}: fact persistence failed`); continue }
3674
+ /**
3675
+ * 事实带上**适用范围**(`scope` 是给人读的一行,`scope_spec` 是可比较的形状)与**推翻条件**:
3676
+ * 没有范围的事实,下一轮无从判断是否适用。它们与出处(证据 id)、等级一起进事实库与货架。
3677
+ */
3678
+ mutations.push({
3679
+ t: 'fact/promoted',
3680
+ id: factId,
3681
+ goal: goal.id,
3682
+ /**
3683
+ * **身份与内容一起定型**:`hypothesis` 是产出它的那条假设(按 id 关联,
3684
+ * 措辞改了也认得出),`assertions` 是这条事实的类型化内容(没写就是 null)。
3685
+ * 断言只在**升格这一刻**落地——旧事实不会被回溯改写。
3686
+ */
3687
+ hypothesis: hypothesis.id,
3688
+ text: hypothesis.claim,
3689
+ about,
3690
+ scope,
3691
+ scope_spec: scopeSpec,
3692
+ refute_when: hypothesis.refute_when ?? null,
3693
+ level: factLevel ?? null,
3694
+ evidence,
3695
+ assertions,
3696
+ definitions,
3697
+ ...(typeof hypothesis.use === 'string' ? { use: hypothesis.use } : {}),
3698
+ path,
3699
+ })
3700
+ promoted.push({ id: factId, claim: hypothesis.claim })
3701
+ }
3702
+ return { promoted, held }
3703
+ }
3704
+
3343
3705
  function persistFact(sessionId, record) {
3344
3706
  const file = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${record.id}.json`)
3345
3707
  if (file === null) return null
@@ -3372,15 +3734,222 @@ export function apply(ctx, config = {}) {
3372
3734
  }
3373
3735
  }
3374
3736
 
3737
+ /**
3738
+ * **可重跑的核算**(`clear/models/<id>.json`,见 `models.js`):引用一条带 `use` 的事实时调用。
3739
+ * 输入与方法的内容摘要没变就不跑;变了就在工作区里用宿主的 `shell` 跑一次,读输出、与上次
3740
+ * (第一次则与登记的 `baseline`)比对,写运行记录(`clear/evidence/models/<id>.json`)。
3741
+ * 拿不到 shell、登记不对、命令失败,都如实返回状态,不当成偏差。
3742
+ */
3743
+ const MODEL_TIMEOUT_MS = 60000
3744
+ function calculationSnapshot(sessionId, modelId) {
3745
+ const cwd = sessionCwd(sessionId)
3746
+ if (!cwd || !MODEL_ID.test(String(modelId))) return null
3747
+ try {
3748
+ const path = `clear/models/${modelId}.json`
3749
+ const spec = JSON.parse(readFileSync(join(cwd, path), 'utf8'))
3750
+ let reference = numericOutputs(spec.baseline)
3751
+ try { reference = numericOutputs(JSON.parse(readFileSync(join(cwd, spec.output), 'utf8'))) } catch {}
3752
+ 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() }
3753
+ } catch { return null }
3754
+ }
3755
+
3756
+ function persistRechecks(sessionId, fact, reasons) {
3757
+ if (!fact || !/^[A-Za-z0-9_-]+$/.test(fact.id)) return false
3758
+ const file = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
3759
+ if (!file) return false
3760
+ try {
3761
+ const data = JSON.parse(readFileSync(file, 'utf8'))
3762
+ const rechecks = [...(data.rechecks ?? [])]
3763
+ for (const reason of reasons) {
3764
+ const id = contentDigest({ kind: reason.kind, model: reason.model, inputs: reason.inputs, method: reason.method, source: reason.source }).slice(0, 32)
3765
+ if (!rechecks.some((row) => row.id === id)) rechecks.push({ ...reason, id, status: 'pending', scope_spec: data.scope_spec ?? null, at: Date.now() })
3766
+ }
3767
+ data.rechecks = rechecks
3768
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3769
+ fact.rechecks = rechecks
3770
+ return true
3771
+ } catch (error) { ctx.logger?.warn?.(`clearai: recheck persistence failed: ${error.message}`); return false }
3772
+ }
3773
+
3774
+ async function rerunModel(sessionId, modelId, fact, exec) {
3775
+ const cwd = sessionCwd(sessionId)
3776
+ const resultFile = `clear/evidence/models/${modelId}.json`
3777
+ const incomplete = (status, detail, snapshot = {}) => {
3778
+ const reason = { kind: 'recheck_incomplete', model: modelId, evidence: resultFile, detail, ...snapshot }
3779
+ const persisted = persistRechecks(sessionId, fact, [reason])
3780
+ return { status, model: modelId, detail, pending: true, persisted, deviations: [] }
3781
+ }
3782
+ if (!cwd || !MODEL_ID.test(String(modelId))) return incomplete('missing', 'workspace or model id unavailable')
3783
+ let spec
3784
+ try { spec = JSON.parse(readFileSync(join(cwd, 'clear', 'models', `${modelId}.json`), 'utf8')) } catch { return incomplete('missing', 'registration missing') }
3785
+ const problems = checkModelSpec(spec, modelId)
3786
+ if (problems.length) return incomplete('invalid', problems.join(';'))
3787
+ const method = methodSnapshot(cwd, spec, `clear/models/${modelId}.json`)
3788
+ const stamp = Object.fromEntries(spec.inputs.map((path) => [path, fileDigest(cwd, path)]))
3789
+ const snapshot = { inputs: stamp, method }
3790
+ const reference = fact?.calculation?.reference ?? null
3791
+ const reasons = []
3792
+ if (fact?.calculation?.method && fact.calculation.method !== method) reasons.push({ kind: 'method_changed', model: modelId, ...snapshot, evidence: resultFile })
3793
+ if (!reference || !Object.keys(numericOutputs(reference)).length) reasons.push({ kind: 'reference_missing', model: modelId, ...snapshot, evidence: resultFile })
3794
+ let record = null
3795
+ try { record = JSON.parse(readFileSync(join(cwd, resultFile), 'utf8')) } catch {}
3796
+ const lastRun = record?.runs?.at(-1) ?? null
3797
+ let outputs = lastRun?.outputs
3798
+ let status = 'current'
3799
+ if (lastRun && fileDigest(cwd, spec.output) === 'missing-or-unreadable') return incomplete('failed', 'output missing', snapshot)
3800
+ if (needsRerun(lastRun, stamp) || lastRun?.method !== method) {
3801
+ if (Object.values(stamp).some((value) => value === 'missing-or-unreadable')) return incomplete('failed', 'input missing', snapshot)
3802
+ if (typeof ctx.tools?.execute !== 'function' || !ctx.get('shell')) return incomplete('unavailable', 'native tool registry or shell unavailable', snapshot)
3803
+ let execution
3804
+ try {
3805
+ 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 })
3806
+ } catch (error) { return incomplete('failed', String(error?.message ?? error).slice(0, 200), snapshot) }
3807
+ const result = execution?.value
3808
+ 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)
3809
+ try { outputs = numericOutputs(JSON.parse(readFileSync(join(cwd, spec.output), 'utf8'))) } catch { return incomplete('failed', `cannot read ${spec.output}`, snapshot) }
3810
+ status = 'rerun'
3811
+ }
3812
+ const deviations = compareOutputs(reference, outputs ?? {}, spec.tolerance)
3813
+ if (deviations.length) reasons.push({ kind: 'output_deviation', model: modelId, ...snapshot, evidence: resultFile, reference, outputs, deviations })
3814
+ if (status === 'rerun') {
3815
+ try { writeTextFile(join(cwd, resultFile), `${JSON.stringify({ id: modelId, ...appendRun(record, { at: Date.now(), inputs: stamp, method, outputs, deviations }) }, null, 2)}\n`) }
3816
+ catch { return incomplete('failed', 'observation persistence failed', snapshot) }
3817
+ }
3818
+ if (reasons.length && !persistRechecks(sessionId, fact, reasons)) return incomplete('failed', 'pending reasons could not be persisted', snapshot)
3819
+ return { status, model: modelId, deviations, pending: (fact?.rechecks ?? []).some((row) => row.status === 'pending'), against: 'baseline' }
3820
+ }
3821
+
3822
+ function confirmRechecks(sessionId, factId, hypothesis, audit, state) {
3823
+ if (audit.reused || audit.holds !== 'yes') return
3824
+ const row = knowledgeRows(host().derive(sessionId)).find((row) => row.id === factId)
3825
+ if (!row || compareScope(row.scope_spec, mergeScope(hypothesis.scope, { conditions: state.goal?.conditions ?? {} })).verdict !== 'applies') return
3826
+ const file = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${factId}.json`)
3827
+ try {
3828
+ const data = JSON.parse(readFileSync(file, 'utf8'))
3829
+ const approved = new Set((audit.rechecks ?? []).filter((item) => item.fact === factId && item.basis.trim() !== '').map((item) => item.id))
3830
+ let observed = null, spec = null
3831
+ if (data.use) {
3832
+ observed = JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'evidence', 'models', `${data.use}.json`), 'utf8')).runs.at(-1)
3833
+ spec = JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'models', `${data.use}.json`), 'utf8'))
3834
+ 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
3835
+ }
3836
+ data.rechecks = (data.rechecks ?? []).map((reason) => {
3837
+ if (reason.status !== 'pending' || !approved.has(reason.id)) return reason
3838
+ if (reason.model && (!observed || !data.calculation?.reference || compareOutputs(data.calculation.reference, observed.outputs, spec.tolerance).length)) return reason
3839
+ return { ...reason, status: 'resolved', resolution: { by: 'independent', card_path: audit.cardPath, hypothesis: hypothesis.id, at: Date.now() } }
3840
+ })
3841
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3842
+ confirmLinkedNegatives(sessionId, data, hypothesis, state)
3843
+ } catch (error) { ctx.logger?.warn?.(`clearai: confirmation incomplete: ${error.message}`) }
3844
+ }
3845
+
3846
+ /** Keep the original anomaly and evidence; close only its independently rechecked, matching scope. */
3847
+ function confirmLinkedNegatives(sessionId, fact, hypothesis, state) {
3848
+ const scope = mergeScope(hypothesis.scope, { conditions: state.goal?.conditions ?? {} })
3849
+ for (const source of new Set((fact.rechecks ?? []).filter(reason => reason.kind === 'anomaly' && reason.status === 'resolved').map(reason => reason.source).filter(Boolean))) {
3850
+ if (!/^[A-Za-z0-9_-]+$/.test(source)) continue
3851
+ const file = sessionFile(sessionId, ...NEGATIVES_REL, `${source}.json`)
3852
+ if (!file || !existsSync(file)) continue
3853
+ const item = JSON.parse(readFileSync(file, 'utf8'))
3854
+ if (!['unresolved', 'escalated'].includes(item.status) || item.review || !item.touches?.length) continue
3855
+ if (compareScope(item.scope, scope).verdict !== 'applies' || compareScope(scope, item.scope).verdict !== 'applies') continue
3856
+ const confirmations = []
3857
+ for (const id of item.touches) {
3858
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) break
3859
+ const path = sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${id}.json`)
3860
+ if (!path || !existsSync(path)) break
3861
+ const linked = JSON.parse(readFileSync(path, 'utf8'))
3862
+ const reasons = (linked.rechecks ?? []).filter(reason => reason.source === source)
3863
+ if (!reasons.length || reasons.some(reason => reason.status !== 'resolved' || reason.resolution?.by !== 'independent' || !reason.resolution.card_path)) break
3864
+ confirmations.push({ fact: id, reasons: reasons.map(reason => ({ id: reason.id, ...reason.resolution })) })
3865
+ }
3866
+ if (confirmations.length !== item.touches.length) continue
3867
+ item.status = 'explained'
3868
+ 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() }
3869
+ item.evidence = [...(item.evidence ?? [])]
3870
+ for (const confirmation of confirmations) for (const reason of confirmation.reasons) {
3871
+ const ref = relative(sessionCwd(sessionId), reason.card_path).split('\\').join('/')
3872
+ if (!item.evidence.some(row => row.ref === ref)) item.evidence.push({ ref })
3873
+ }
3874
+ writeTextFile(file, `${JSON.stringify(item, null, 2)}\n`)
3875
+ }
3876
+ }
3877
+
3878
+ /**
3879
+ * **负向条目随发生随写**(`clear/knowledge/negatives/<id>.json`,只有系统写)。
3880
+ *
3881
+ * 判断被推翻、反常被登记或被解释为缺陷,都在那一刻落盘,不等结案:会话因预算或 token 限制中断、
3882
+ * 以放弃结束时,这些信息照样留下。条目从当前状态整份算出(`negativeItems`),所以重写是幂等的;
3883
+ * 只有内容变了才写。别的会话写的同名文件不动;人加在文件上的 `review` 保留。
3884
+ * 两个调用点:每个工具结果之后(这一拍的变更先折一遍)与每一拍的 pre-step(兜底)。
3885
+ */
3886
+ const negativeWrites = new Map()
3887
+ function writeBack(sessionId, state, derived) {
3888
+ if (isSpawnedChild(sessionId) || !CFG.negativeWriteback) return []
3889
+ if (state === null || state === undefined) return []
3890
+ if (CFG.ontologyFeedback) for (const hypothesis of derived?.hypotheses ?? []) {
3891
+ if (!hypothesis.refutations) continue
3892
+ for (const saved of state.facts ?? []) {
3893
+ if (saved.hypothesis !== hypothesis.id) continue
3894
+ const fact = findFact(sessionId, state, saved.id)
3895
+ const scope = mergeScope(hypothesis.scope, { conditions: state.goal?.conditions ?? {} })
3896
+ if (!fact || ['out_of_scope', 'out_of_range'].includes(compareScope(fact.scope_spec, scope).verdict)) continue
3897
+ const evidence = evidenceFor(state, hypothesis.id).filter(e => e.verdict === 'refute').at(-1)
3898
+ persistRechecks(sessionId, fact, [{ kind: 'hypothesis_refuted', source: evidence?.id ?? hypothesis.id, detail: hypothesis.claim, evidence: evidence?.refs?.[0] ?? null }])
3899
+ }
3900
+ }
3901
+ const written = []
3902
+ for (const item of negativeItems(state, derived, { session: sessionId })) {
3903
+ if (['unresolved', 'defect', 'escalated'].includes(item.status)) for (const id of item.touches ?? []) {
3904
+ const fact = findFact(sessionId, state, id)
3905
+ if (!fact) continue
3906
+ const fit = compareScope(fact.scope_spec, item.scope)
3907
+ if (['out_of_scope', 'out_of_range'].includes(fit.verdict)) continue
3908
+ persistRechecks(sessionId, fact, [{ kind: 'anomaly', source: item.id, detail: item.statement, evidence: item.about?.find((ref) => ref.includes('/')) ?? null }])
3909
+ }
3910
+ const file = sessionFile(sessionId, ...NEGATIVES_REL, `${item.id}.json`)
3911
+ if (file === null) return written
3912
+ const body = JSON.stringify(item)
3913
+ if (negativeWrites.get(file) === body) continue
3914
+ try {
3915
+ let existing = null
3916
+ if (existsSync(file)) {
3917
+ try {
3918
+ existing = JSON.parse(readFileSync(file, 'utf8'))
3919
+ } catch {
3920
+ existing = null
3921
+ }
3922
+ }
3923
+ if (existing !== null && typeof existing.source?.session === 'string' && existing.source.session !== sessionId) {
3924
+ negativeWrites.set(file, body)
3925
+ continue
3926
+ }
3927
+ const at = typeof existing?.at === 'number' ? existing.at : Date.now()
3928
+ const record = { ...item, source: existing?.source ?? item.source, review: existing?.review ?? null, at, updated: Date.now() }
3929
+ if (existing?.resolution?.by === 'independent' && existing.resolution.confirmations?.length && ['unresolved', 'escalated'].includes(item.status)) {
3930
+ record.status = existing.status
3931
+ record.resolution = existing.resolution
3932
+ record.evidence = existing.evidence
3933
+ }
3934
+ writeTextFile(file, `${JSON.stringify(record, null, 2)}\n`)
3935
+ negativeWrites.set(file, body)
3936
+ written.push(item.id)
3937
+ } catch (error) {
3938
+ ctx.logger?.warn?.(`clearai kernel: 负向条目落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
3939
+ }
3940
+ }
3941
+ return written
3942
+ }
3943
+
3375
3944
  // ── 计划六件 ───────────────────────────────────────────────────────────
3376
3945
 
3377
3946
  const STEP_SCHEMA = {
3378
3947
  type: 'object',
3379
3948
  properties: {
3380
- id: { type: 'string', description: '稳定 id(字母/数字/下划线/短横)' },
3381
- do: { type: 'string', description: '这一步做什么' },
3382
- artifacts: { type: 'array', items: { type: 'string' }, description: '以何物为证:相对 workspace 的具体产物文件路径(目录不是物证)' },
3383
- done_criteria: { type: 'string', description: '判定标准:在结果出现之前写下,必须可核对' },
3949
+ id: { type: 'string', description: '稳定 id' },
3950
+ do: { type: 'string', description: '做什么' },
3951
+ artifacts: { type: 'array', items: { type: 'string' }, description: '作为物证的产物文件路径(相对工作区,不是目录)' },
3952
+ done_criteria: { type: 'string', description: '判据:结果出现前写下,可核对' },
3384
3953
  tests: {
3385
3954
  type: 'object',
3386
3955
  properties: {
@@ -3388,22 +3957,22 @@ export function apply(ctx, config = {}) {
3388
3957
  type: 'array',
3389
3958
  minItems: 1,
3390
3959
  items: { type: 'string' },
3391
- description: '这一步检验哪几条判断:填判断的短名(也认主张原文)。一次观测同时判几条竞争的判断时(比较那一步),把它们都列上',
3960
+ description: '检验哪几条判断(短名);比较竞争判断的一步全列上',
3392
3961
  },
3393
- level: { type: 'string', enum: MODEL_LEVELS, description: 'L2 = 自判(你写结果与依据);L3 = 独立评估(系统派评估者判);L4 = 人工批准(不可重复或来自外部的证据,须先经人工批准)' },
3962
+ level: { type: 'string', enum: MODEL_LEVELS, description: 'L2 自判;L3 独立评估;L4 人工批准(不可重复或外部证据)' },
3394
3963
  },
3395
3964
  required: ['hypotheses', 'level'],
3396
3965
  additionalProperties: false,
3397
3966
  },
3398
3967
  expect: {
3399
3968
  type: 'string',
3400
- description: '可选,执行前填写:这一步预计观察到什么(尽量给出数值或方向),以及预测的来源(本体中的哪条关系 / 哪条经验 / 哪条判断,或注明为直觉)。事先写下,预测落空时才能被发现',
3969
+ description: '可选,执行前写:预计看到什么(数值或方向)',
3401
3970
  },
3402
- serves: { type: 'string', description: '可选:这一步服务哪个问题或调研板块(id);不写即归当前问题' },
3971
+ serves: { type: 'string', description: '可选:服务哪个问题或板块 id' },
3403
3972
  predictions: {
3404
3973
  type: 'array',
3405
- description: '可选,动手前写:按候选假设分别写预测(若「X」成立,预计看到什么)。各候选预测相同的一步区分不了它们,应改选能区分的检验',
3406
- items: { type: 'object', properties: { hypothesis: { type: 'string', description: '判断的短名(也认 id)' }, expect: { type: 'string', description: '若它成立,预计看到什么(尽量给数或方向)' } }, required: ['hypothesis', 'expect'], additionalProperties: false },
3974
+ description: '可选,执行前写:各候选成立时预计看到什么;都一样就换检验',
3975
+ items: { type: 'object', properties: { hypothesis: { type: 'string', description: '判断短名' }, expect: { type: 'string', description: '预计看到什么' } }, required: ['hypothesis', 'expect'], additionalProperties: false },
3407
3976
  },
3408
3977
  },
3409
3978
  required: ['id', 'do', 'done_criteria'],
@@ -3411,10 +3980,26 @@ export function apply(ctx, config = {}) {
3411
3980
  }
3412
3981
 
3413
3982
 
3983
+ function groundingProblem(state, tested = [], hostService, sessionId, mutations) {
3984
+ if (!CFG.ontologyFeedback || tested.length === 0) return null
3985
+ const known = new Set([...(state.entities ?? []), ...(state.lexicon?.terms ?? []), ...(state.lexicon?.predicates ?? [])].map(row => row.id))
3986
+ const hypotheses = (state.hypotheses ?? []).filter(row => tested.includes(row.id))
3987
+ const missing = mergeAbout(state.goal?.about, ...hypotheses.map(row => row.about)).filter(id => !known.has(id))
3988
+ const untyped = hypotheses.filter(row => !row.assertions?.length).map(handleOf)
3989
+ for (const hypothesis of hypotheses.filter(row => row.assertions?.length)) {
3990
+ const problems = hostService.domain?.validateAssertions?.(sessionId, hypothesis.assertions, { mutations }) ?? ['domain unavailable']
3991
+ if (problems.length) untyped.push(`${handleOf(hypothesis)}: ${problems.join('; ')}`)
3992
+ }
3993
+ if (!missing.length && !untyped.length) return null
3994
+ return fail('ontology_grounding_required', tr(
3995
+ `检验前补齐本次实际使用的图引用。未登记 id:${missing.join(', ') || '无'};缺少 assertions 的判断:${untyped.join(', ') || '无'}。用一次 Frame 修订提交 ontology.concepts / relations / entities 和假设 assertions,也可先写 clear/ontology/ 下的文件。只定义当前对象、单位和检验谓词;候选关系仍是假设,不写成已证实的实体关系。无需额外假设或完整领域图。`,
3996
+ `Ground the graph references used by this test. Unknown ids: ${missing.join(', ') || 'none'}; judgments missing assertions: ${untyped.join(', ') || 'none'}. Submit ontology.concepts / relations / entities and hypothesis assertions together in one Frame revision, or write clear/ontology/ files first. Define only the current objects, units and test predicates; candidate relations remain hypotheses, not established entity relations. No extra hypotheses or full domain graph required.`))
3997
+ }
3998
+
3414
3999
  defineTool({
3415
4000
  name: 'CreatePlan',
3416
4001
  description:
3417
- '立约:把复杂任务立成一份计划。每步一句话说清做什么(do)、以何物为证(artifacts)、以及判定标准(done_criteria,在结果出现之前写下);可带预测(expect:预计观察到什么,以及预测的来源)。检验判断的步骤用 tests:{hypotheses, level} 声明验哪几条、什么等级(比较竞争路线的那一步,把竞争的几条都列上)。最多 25 步。约立起便锁定:局部挫折改当前步,不要推倒重来。',
4002
+ '立计划:每步写做什么、以哪个文件为证、判据(结果出现前写下);检验判断的步用 tests。最多 25 步;局部挫折改当前步,不推倒重来。',
3418
4003
  parameters: {
3419
4004
  type: 'object',
3420
4005
  properties: {
@@ -3426,7 +4011,7 @@ export function apply(ctx, config = {}) {
3426
4011
  },
3427
4012
  output: CARD_OUTPUT,
3428
4013
  async execute(args, exec) {
3429
- const call = open(exec)
4014
+ const call = open(exec, { sync: true })
3430
4015
  if (call.ok !== true) return call.response
3431
4016
  const { hostService, sessionId, state, mutations } = call
3432
4017
  const done = finish(hostService, sessionId, mutations)
@@ -3439,6 +4024,8 @@ export function apply(ctx, config = {}) {
3439
4024
  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))
3440
4025
  resolvedTests.set(step.id, resolved.tests)
3441
4026
  }
4027
+ const grounding = groundingProblem(state, [...resolvedTests.values()].flatMap(tests => tests?.hypotheses ?? []), hostService, sessionId, mutations)
4028
+ if (grounding) return grounding
3442
4029
  const resolvedExtras = new Map()
3443
4030
  for (const step of args.steps) {
3444
4031
  const resolved = resolveStepExtras(state, step)
@@ -3475,24 +4062,24 @@ export function apply(ctx, config = {}) {
3475
4062
  defineTool({
3476
4063
  name: 'RevisePlan',
3477
4064
  description:
3478
- '改当前计划,不动进度(返回 progress_changed=false),四种动作:`action="expect"` 为尚未执行的步骤写下预测(给 `step_id` 与 `expect`,或按候选假设给 `predictions`;须在执行前写,预测落空时才能被发现);`action="add"` 补一步(漏了活就补上,给 `step`);`action="refine"` 精化一步的判定标准(给 `step_id` 与新的 `done_criteria`,旧判据留在日志里);`action="void"` 带因作废一步(给 `step_id` 与 `reason`:发现某步本不该存在就作废并说明缘由——作废留痕光明正大,为凑完成而造证是大忌;已交付的步不能作废)。',
4065
+ '改计划,不动进度。expect:给未执行的步写预测(step_id + expect 或 predictions);add:补一步(step);refine:改一步的判据(step_id + done_criteria);void:带因作废一步(step_id + reason,已交付的不能作废)。',
3479
4066
  parameters: {
3480
4067
  type: 'object',
3481
4068
  properties: {
3482
- action: { type: 'string', enum: ['expect', 'add', 'refine', 'void'], description: 'expect=写预测;add=补一步;refine=改判据;void=带因作废' },
3483
- step: { ...STEP_SCHEMA, description: 'action=add:新步' },
3484
- step_id: { type: 'string', description: 'action=expect / refine / void:哪一步' },
3485
- expect: { type: 'string', description: 'action=expect:预计观察到什么,以及预测的来源(关系 / 经验 / 判断,或直觉)' },
3486
- predictions: { ...STEP_SCHEMA.properties.predictions, description: 'action=expect,可选:按候选假设分别写预测;与 expect 二者至少给一个' },
3487
- done_criteria: { type: 'string', description: 'action=refine:新的判定标准' },
3488
- reason: { type: 'string', description: '为什么改(action=void 必填)' },
4069
+ action: { type: 'string', enum: ['expect', 'add', 'refine', 'void'], description: 'expect / add / refine / void' },
4070
+ step: { type: 'object', description: 'action=add:新步,字段同 CreatePlan 的步骤' },
4071
+ step_id: { type: 'string', description: '哪一步' },
4072
+ expect: { type: 'string', description: 'action=expect:预计看到什么' },
4073
+ predictions: { ...STEP_SCHEMA.properties.predictions, description: 'action=expect:各候选的预测' },
4074
+ done_criteria: { type: 'string', description: 'action=refine:新判据' },
4075
+ reason: { type: 'string', description: '为什么改(void 必填)' },
3489
4076
  },
3490
4077
  required: ['action'],
3491
4078
  additionalProperties: false,
3492
4079
  },
3493
4080
  output: CARD_OUTPUT,
3494
4081
  async execute(args, exec) {
3495
- const call = open(exec)
4082
+ const call = open(exec, { sync: true })
3496
4083
  if (call.ok !== true) return call.response
3497
4084
  const { hostService, sessionId, state, mutations } = call
3498
4085
  const done = finish(hostService, sessionId, mutations)
@@ -3506,6 +4093,8 @@ export function apply(ctx, config = {}) {
3506
4093
  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}`))
3507
4094
  const resolved = resolveTests(state.hypotheses, args.step.tests)
3508
4095
  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))
4096
+ const grounding = groundingProblem(state, resolved.tests?.hypotheses ?? [], hostService, sessionId, mutations)
4097
+ if (grounding) return grounding
3509
4098
  const extras = resolveStepExtras(state, args.step)
3510
4099
  if (extras.ok !== true) return fail(extras.code, extras.message)
3511
4100
  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 }
@@ -3546,8 +4135,8 @@ export function apply(ctx, config = {}) {
3546
4135
 
3547
4136
  defineTool({
3548
4137
  name: 'ClosePlan',
3549
- description: '收束当前阶段:把这一张计划归档。目标若未达成,系统会叫醒你开下一阶段。',
3550
- parameters: { type: 'object', properties: { summary: { type: 'string', description: '收束之辞:这一阶段拿到了什么' } }, additionalProperties: false },
4138
+ description: '收束当前计划并归档;目标未达成时开下一阶段。',
4139
+ parameters: { type: 'object', properties: { summary: { type: 'string', description: '这一阶段拿到了什么' } }, additionalProperties: false },
3551
4140
  output: CARD_OUTPUT,
3552
4141
  async execute(args, exec) {
3553
4142
  const call = open(exec)
@@ -3593,31 +4182,31 @@ export function apply(ctx, config = {}) {
3593
4182
  defineTool({
3594
4183
  name: 'AdvancePlan',
3595
4184
  description:
3596
- '交付一步(唯一完成动词):把观测交上来。系统先做观测准入——声明的产物存在、非空、结构合法;准入只看收不收,不做裁决。交付成立这一步就完成——它检验的判断被支持、被推翻还是说不清,**都算完成**,结果单独记成证据。结果与预测不符之处写进 anomalies。L2(自判)由你给 basis(交付成立的依据,必须能被复查)与 results(这一步检验的每条判断各一格);L3 以上两项都由系统派独立评估者判,你写 results 会被拒绝。没有物证,就还没有完成——没有手动标记这回事。',
4185
+ '交付一步,唯一的完成动作。声明的产物须存在、非空、结构合法。交付成立即完成,判断的结果另记为证据。L2 由你给 basis 与 results;L3 以上由独立评估者判。',
3597
4186
  parameters: {
3598
4187
  type: 'object',
3599
4188
  properties: {
3600
- step_id: { type: 'string', description: '交付哪一步(只能落在第一个未落定的步,这里是防手滑的确认,不是选择器)' },
4189
+ step_id: { type: 'string', description: '交付哪一步(须是第一个未完成的步)' },
3601
4190
  observations: {
3602
4191
  type: 'array',
3603
- description: '观测:这一步拿到的原始结果(相对 workspace 的路径 + 一句说明)',
4192
+ description: '原始结果:路径 + 一句说明',
3604
4193
  items: { type: 'object', properties: { ref: { type: 'string' }, note: { type: 'string' } }, required: ['ref'], additionalProperties: false },
3605
4194
  },
3606
4195
  anomalies: {
3607
4196
  type: 'array',
3608
- description: '未解释:这一步结果中与预测或本体不符之处、无法解释的读数(每条一句,写明何处不符)。它们挂在卡上,直到被解释、写明理由排除、或交给人(用 Anomaly 工具)。不要强行解释',
3609
- items: { type: 'object', properties: { what: { type: 'string', description: '何处不符:预测为何、实际为何' }, anchor: { type: 'string', description: '可选:在哪个实体或装置上(实体 id 或名字)' }, touches: { type: 'array', items: { type: 'string' }, description: '可选:涉及的量(概念 id)、候选假设(判断 id)或已确立的事实(事实 id)。点名事实的,该事实回到「待核验」;结案时,涉及答案的未解释项须在「尚未确定的事项」中写明影响' } }, required: ['what'], additionalProperties: false },
4197
+ description: '与预测或本体不符、说不通的读数,每条一句;不要强行解释',
4198
+ items: { type: 'object', properties: { what: { type: 'string', description: '预测为何、实际为何' }, anchor: { type: 'string', description: '可选:在哪个实体或装置上' }, touches: { type: 'array', items: { type: 'string' }, description: '可选:涉及的量、判断或事实 id;点名的事实回到待核验' } }, required: ['what'], additionalProperties: false },
3610
4199
  },
3611
- basis: { type: 'string', description: '交付成立的依据:引用了哪个产物里的哪个事实(必须可复查)。仅自判(L2)由你写' },
4200
+ basis: { type: 'string', description: '仅 L2:交付成立的依据,引到产物里的具体事实' },
3612
4201
  results: {
3613
4202
  type: 'array',
3614
- description: '仅自判(L2):这一步检验的每条判断各一格,对照它的推翻条件读结果:没碰到推翻条件是「支持」,碰到了是「推翻」,这次观测区分不了是「不确定」。推翻和不确定都不妨碍这一步完成',
4203
+ description: '仅 L2:每条受检判断一格:支持(没碰到推翻条件)/ 推翻 / 不确定',
3615
4204
  items: {
3616
4205
  type: 'object',
3617
4206
  properties: {
3618
- hypothesis: { type: 'string', description: '判断的短名(也认主张原文)' },
4207
+ hypothesis: { type: 'string', description: '判断短名' },
3619
4208
  verdict: { type: 'string', enum: ['支持', '推翻', '不确定', 'support', 'refute', 'inconclusive'] },
3620
- basis: { type: 'string', description: '一句话:这次观测对照推翻条件读出了什么(不写就用上面那句 basis)' },
4209
+ basis: { type: 'string', description: '对照推翻条件读出了什么' },
3621
4210
  },
3622
4211
  required: ['hypothesis', 'verdict'],
3623
4212
  additionalProperties: false,
@@ -3629,7 +4218,7 @@ export function apply(ctx, config = {}) {
3629
4218
  },
3630
4219
  output: CARD_OUTPUT,
3631
4220
  async execute(args, exec) {
3632
- const call = open(exec)
4221
+ const call = open(exec, { sync: true })
3633
4222
  if (call.ok !== true) return call.response
3634
4223
  const { hostService, sessionId, state, mutations } = call
3635
4224
  const done = finish(hostService, sessionId, mutations)
@@ -3653,6 +4242,8 @@ export function apply(ctx, config = {}) {
3653
4242
  mutations.length > 0 ? { mutations } : {},
3654
4243
  )
3655
4244
  }
4245
+ const grounding = groundingProblem(state, step.tests?.hypotheses ?? [], hostService, sessionId, mutations)
4246
+ if (grounding) return grounding
3656
4247
  const level = step.tests?.level ?? null
3657
4248
  const levelIndex = levelIndexOf(level)
3658
4249
 
@@ -3690,6 +4281,7 @@ export function apply(ctx, config = {}) {
3690
4281
 
3691
4282
  // ② 准入
3692
4283
  const gate = admission(cwd, step)
4284
+ gate.materialMutations = mutations.filter((row) => row.t === 'observation/recorded')
3693
4285
  gate.anomalies = opened
3694
4286
  mutations.push({
3695
4287
  t: 'admission/checked',
@@ -3771,6 +4363,7 @@ export function apply(ctx, config = {}) {
3771
4363
  let results = []
3772
4364
  /** 独立裁决的两件凭据(自判路径下保持 null):评估卡文件与写它的**评估者子会话**。 */
3773
4365
  let auditCardPath = null
4366
+ let deliveredAudit = null
3774
4367
  let auditSessionId = null
3775
4368
  /** 复用说明(模型与人都看得到的那一句);不复用时为空串。 */
3776
4369
  let reuseNote = ''
@@ -3785,6 +4378,7 @@ export function apply(ctx, config = {}) {
3785
4378
  const beforeAudit = CFG.auditRerun ? digestsOf() : ''
3786
4379
  const audit = await runEvaluator(sessionId, exec.agent, plan, step, gate, 'evidence_audit', exec.signal)
3787
4380
  mutations.push(...audit.mutations)
4381
+ deliveredAudit = audit
3788
4382
  foundByEvaluator = audit.reused === true ? [] : Array.isArray(audit.anomalies) ? audit.anomalies : []
3789
4383
  if (CFG.auditRerun && audit.reused !== true && ['yes', 'no', 'unclear'].includes(audit.holds) && digestsOf() !== beforeAudit) {
3790
4384
  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 })
@@ -3920,8 +4514,22 @@ export function apply(ctx, config = {}) {
3920
4514
  * **交付成立 ⇒ 这一步完成**,不论结果是支持、推翻还是说不清。
3921
4515
  * 交付本身(谁判的、凭什么、出处)记在推进这条事实上;判断的状态由证据算。
3922
4516
  */
4517
+ if (deliveredAudit && evaluator === 'independent') for (const result of results) {
4518
+ const hypothesis = state.hypotheses.find((row) => row.id === result.hypothesis)
4519
+ if (result.verdict === 'support' && hypothesis?.retests) confirmRechecks(sessionId, hypothesis.retests, hypothesis, deliveredAudit, state)
4520
+ }
3923
4521
  mutations.push({ t: 'step/advanced', plan: plan.id, step: step.id, evidence: evidenceIds, evaluator, basis, refs: originInfo.paths, origins: originInfo.origins })
3924
4522
  mutations.push({ t: 'block/cleared', plan: plan.id, step: step.id })
4523
+ let partialNote = ''
4524
+ if (CFG.ontologyFeedback && evaluator === 'independent' && auditCardPath && !isSpawnedChild(sessionId)) {
4525
+ const preview = previewOf(hostService, sessionId, mutations)
4526
+ const current = preview?.state
4527
+ if (current?.goal?.status === 'open' && !(current.anomalies ?? []).some(a => ['open', 'escalated'].includes(a.status) && a.matters !== 'no')) {
4528
+ const saved = promoteFacts(hostService, sessionId, current, preview.derived, current.goal, new Map(), mutations, { partial: true, eligible: new Set(results.filter(r => r.verdict === 'support').map(r => r.hypothesis)) })
4529
+ if (saved.promoted.length) partialNote = tr(`\n阶段事实已保存到实体图与 clear/knowledge/facts/:${saved.promoted.map(f => f.id).join(', ')};目标仍开放。`, `\nPartial facts saved in the entity graph and clear/knowledge/facts/: ${saved.promoted.map(f => f.id).join(', ')}; the goal remains open.`)
4530
+ if (saved.held.length) partialNote += `\n${saved.held.join('; ')}`
4531
+ }
4532
+ }
3925
4533
  const outcome = results.length === 0 ? '' : `\n${tr('结果:', 'Results: ')}${results.map((item) => `${quote(handleById(state, item.hypothesis))}${tr('', ' ')}${verdictWord(item.verdict)}`).join(tr(';', '; '))}${tr('。', '.')}`
3926
4534
  const refuted = results.some((item) => item.verdict === 'refute')
3927
4535
  const factReview = refuted
@@ -3942,7 +4550,7 @@ export function apply(ctx, config = {}) {
3942
4550
  blocked: false,
3943
4551
  message:
3944
4552
  tr(`第 ${step.ordinal} 步(${step.id})已交付(${evaluator === 'independent' ? '独立评估者判的' : '你自己判的,依据已记下'})。收下的观测:${gate.confirmed.map((item) => item.ref).join(', ') || '(无)'}。`, `Step ${step.ordinal} (${step.id}) delivered (${evaluator === 'independent' ? 'judged by the independent evaluator' : 'judged by you; the basis is recorded'}). Observations accepted: ${gate.confirmed.map((item) => item.ref).join(', ') || '(none)'}.`) +
3945
- outcome +
4553
+ outcome + partialNote +
3946
4554
  expectationNote(step, opened, foundByEvaluator) +
3947
4555
  (refuted ? tr('\n推翻也是有价值的结果:它和支持一样记进证据,判断的状态由证据算。', '\nA refutation is a valuable result too: it is recorded as evidence just like support, and the judgment status is computed from the evidence.') : '') +
3948
4556
  factReview +
@@ -3962,18 +4570,19 @@ export function apply(ctx, config = {}) {
3962
4570
  defineTool({
3963
4571
  name: 'Anomaly',
3964
4572
  description:
3965
- '未解释项(反常):与预测或本体不符的观测、无法解释的读数。`action="open"` 登记一条(给 `what`,可选 `anchor`);`action="resolve"` 给它一个去处(给 `id`、`outcome` 与 `reason`):explained = 被一条判断、关系或新查到的原因解释了(`by` 写是哪条);ruled_out = 写明理由排除(比如证实是录入错误);escalated = 交给人。不要为了让卡干净而排除:评估者会核排除的理由。',
4573
+ '未解释项(反常)。open:登记一条;resolve:给去处(explained 被解释,ruled_out 写明理由排除,escalated 交给人)。评估者会核排除的理由。',
3966
4574
  parameters: {
3967
4575
  type: 'object',
3968
4576
  properties: {
3969
4577
  action: { type: 'string', enum: ['open', 'resolve'] },
3970
- what: { type: 'string', description: 'action=open:何处不符——预测为何、实际为何' },
3971
- anchor: { type: 'string', description: 'action=open,可选:在哪个实体或装置上' },
3972
- touches: { type: 'array', items: { type: 'string' }, description: 'action=open,可选:涉及的量(概念 id)、候选假设(判断 id)或已确立的事实(事实 id)。点名事实的,该事实回到「待核验」' },
3973
- id: { type: 'string', description: 'action=resolve:哪一条(u-… 的 id)' },
3974
- outcome: { type: 'string', enum: ANOMALY_OUTCOMES, description: 'explained=已解释;ruled_out=排除;escalated=交给人' },
3975
- reason: { type: 'string', description: 'action=resolve:依据(解释是什么 / 为何可以排除 / 需要人决定什么)' },
3976
- by: { type: 'string', description: 'action=resolve,可选:解释它的那条判断、关系或事实' },
4578
+ what: { type: 'string', description: '预测为何、实际为何' },
4579
+ anchor: { type: 'string', description: '可选:在哪个实体或装置上' },
4580
+ touches: { type: 'array', items: { type: 'string' }, description: '可选:涉及的量、判断或事实 id;点名的事实回到待核验' },
4581
+ id: { type: 'string', description: '哪一条(u-…)' },
4582
+ outcome: { type: 'string', enum: ANOMALY_OUTCOMES, description: 'explained / ruled_out / escalated' },
4583
+ reason: { type: 'string', description: '依据' },
4584
+ by: { type: 'string', description: '可选:解释它的判断、关系或事实' },
4585
+ defect: { type: 'boolean', description: '可选:解释是测量或方法缺陷(如探头漂移),记成该实体的缺陷条目' },
3977
4586
  },
3978
4587
  required: ['action'],
3979
4588
  additionalProperties: false,
@@ -3986,7 +4595,7 @@ export function apply(ctx, config = {}) {
3986
4595
  const done = finish(hostService, sessionId, mutations)
3987
4596
  if (args.action === 'open') {
3988
4597
  const opened = openAnomalies(sessionId, [{ what: args.what, anchor: args.anchor, touches: args.touches }], { step: firstOpenStep(activePlanOf(state))?.id ?? null, by: 'model' })
3989
- if (opened.length === 0) return fail('what_required', tr('要写何处不符:预测为何、实际为何。', 'Say what does not fit: what was expected and what was seen.'))
4598
+ if (opened.length === 0) return fail('what_required', tr('要写预测为何、实际为何。', 'Say what does not fit: what was expected and what was seen.'))
3990
4599
  mutations.push(...opened)
3991
4600
  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.`) })
3992
4601
  }
@@ -3999,7 +4608,8 @@ export function apply(ctx, config = {}) {
3999
4608
  const reason = String(args.reason ?? '').trim()
4000
4609
  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.'))
4001
4610
  const by = String(args.by ?? '').trim()
4002
- mutations.push({ t: 'anomaly/resolved', id: target.id, outcome: args.outcome, reason: reason.slice(0, 600), ...(by === '' ? {} : { by: by.slice(0, 120) }) })
4611
+ const defect = args.outcome === 'explained' && args.defect === true
4612
+ 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 } : {}) })
4003
4613
  const word = { explained: tr('已解释', 'explained'), ruled_out: tr('已排除', 'ruled out'), escalated: tr('交给人', 'handed to a person') }[args.outcome]
4004
4614
  return done({
4005
4615
  ok: true,
@@ -4057,7 +4667,7 @@ export function apply(ctx, config = {}) {
4057
4667
  */
4058
4668
  if (factMutations.length > 0) sections.push({ name: 'clearai/mutations', text: JSON.stringify({ mutations: factMutations }) })
4059
4669
  return {
4060
- id: `clearai-notice-${payload.turn}-${payload.step}-${Date.now().toString(36)}`,
4670
+ id: `clearai-notice-${payload.turn}-${payload.step}-${randomUUID()}`,
4061
4671
  role: 'user',
4062
4672
  content: text(note),
4063
4673
  source: { kind: MESSAGE_SOURCE_KIND, form: 'snapshot', sections },
@@ -4078,18 +4688,56 @@ export function apply(ctx, config = {}) {
4078
4688
  const key = String(id ?? '').trim()
4079
4689
  if (!/^[A-Za-z0-9_-]+$/.test(key)) return null
4080
4690
  const own = (state.facts ?? []).find((fact) => fact.id === key)
4081
- if (own !== undefined) return own
4691
+ if (own !== undefined) {
4692
+ try { return { ...own, ...JSON.parse(readFileSync(sessionFile(sessionId, 'clear', 'knowledge', 'facts', `${key}.json`), 'utf8')) } } catch { return own }
4693
+ }
4082
4694
  const cwd = sessionCwd(sessionId)
4083
4695
  if (cwd === null) return null
4084
4696
  try {
4085
4697
  const data = JSON.parse(readFileSync(join(cwd, 'clear', 'knowledge', 'facts', `${key}.json`), 'utf8'))
4086
4698
  if (String(data?.id ?? '') !== key || typeof data?.text !== 'string') return null
4087
- return { id: key, text: data.text, hypothesis: data.hypothesis ?? null, review: data.review ?? null, foreign: true }
4699
+ 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 }
4088
4700
  } catch {
4089
4701
  return null
4090
4702
  }
4091
4703
  }
4092
4704
 
4705
+ /** 事实文件上记一条疑问(引用它的判断被推翻):事实回到待核验,人复核后解除。 */
4706
+ function markFactQuestioned(cwd, fact, challenge) {
4707
+ if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4708
+ const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4709
+ try {
4710
+ if (!existsSync(file)) return null
4711
+ const data = JSON.parse(readFileSync(file, 'utf8'))
4712
+ const at = Date.now()
4713
+ data.challenges = [...(Array.isArray(data.challenges) ? data.challenges : []), { hypothesis: challenge.hypothesis ?? null, verdict: challenge.verdict ?? null, basis: challenge.basis ?? null, at }]
4714
+ data.history = [...(Array.isArray(data.history) ? data.history : []), { event: 'questioned', at, reason: challenge.basis ?? null }]
4715
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4716
+ return file
4717
+ } catch (error) {
4718
+ ctx.logger?.warn?.(`clearai kernel: 事实疑问记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
4719
+ return null
4720
+ }
4721
+ }
4722
+
4723
+ /** 事实文件上记一处边界(在哪里不成立),事实本身保持成立。 */
4724
+ function markFactBounded(cwd, fact, bound) {
4725
+ if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4726
+ const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4727
+ try {
4728
+ if (!existsSync(file)) return null
4729
+ const data = JSON.parse(readFileSync(file, 'utf8'))
4730
+ const at = Date.now()
4731
+ data.boundaries = [...(Array.isArray(data.boundaries) ? data.boundaries : []), { verdict: bound.verdict, reasons: bound.reasons, basis: bound.basis ?? null, at }]
4732
+ data.history = [...(Array.isArray(data.history) ? data.history : []), { event: bound.verdict, at, reason: bound.basis ?? null }]
4733
+ writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4734
+ return file
4735
+ } catch (error) {
4736
+ ctx.logger?.warn?.(`clearai kernel: 事实边界记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
4737
+ return null
4738
+ }
4739
+ }
4740
+
4093
4741
  function markFactReviewed(cwd, fact, review) {
4094
4742
  if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4095
4743
  const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
@@ -4101,6 +4749,7 @@ export function apply(ctx, config = {}) {
4101
4749
  const decision = review.retracted ? 'retracted' : 'kept'
4102
4750
  data.status = review.retracted ? 'retracted' : 'established'
4103
4751
  data.review = { decision, reason, at, by: 'user' }
4752
+ 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)
4104
4753
  data.history = [...(Array.isArray(data.history) ? data.history : []), { event: decision, at, reason }]
4105
4754
  writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4106
4755
  return file
@@ -4152,7 +4801,7 @@ export function apply(ctx, config = {}) {
4152
4801
  * `ontology` 里**模型可写**的是三支本体目录(`concepts` / `relations` / `entities`);
4153
4802
  * 字段定义 `SCHEMA.json` 与过程本体那份货架仍归系统。
4154
4803
  */
4155
- const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'knowledge', 'lessons'], ['clear', 'goals'], ['clear', 'ontology']]
4804
+ const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'knowledge', 'lessons'], ['clear', 'knowledge', 'negatives'], ['clear', 'goals'], ['clear', 'ontology']]
4156
4805
  const OPEN_REL = ONTOLOGY_BRANCH_DIRS.map((branch) => ['clear', 'ontology', branch])
4157
4806
 
4158
4807
  /** 工作区内的相对路径(正斜杠);在工作区外或取不到工作区返回 null。 */
@@ -4292,6 +4941,7 @@ export function apply(ctx, config = {}) {
4292
4941
  const hostService = host()
4293
4942
  const state = hostService === undefined ? null : hostService.state(sessionId)
4294
4943
  const owned = state !== null && hasState(state)
4944
+ if (CFG.nativeTodoProgress && exec.name === 'todo_write' && state !== null && activePlanOf(state) !== null && !isSpawnedChild(sessionId)) return { kind: 'deny', reason: tr('当前计划的 todo 进度由系统自动同步。用 AdvancePlan 交付、RevisePlan 修改步骤;核验通过后才显示完成。', 'The current plan is mirrored to native todos automatically. Deliver with AdvancePlan or edit with RevisePlan; completion is displayed only after acceptance.') }
4295
4945
  const rawArgs = exec.arguments ?? {}
4296
4946
  let args = rawArgs
4297
4947
  if (typeof rawArgs === 'string') {
@@ -4324,7 +4974,7 @@ export function apply(ctx, config = {}) {
4324
4974
  if (suspect !== null) {
4325
4975
  return {
4326
4976
  kind: 'deny',
4327
- 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.`),
4977
+ 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 are written by the system after qualifying independent evaluation (at step delivery or goal conclusion); lessons are written after conclusion review, and negative items are generated by the system from the ledger; write the ontology under clear/ontology/concepts, relations and entities.`),
4328
4978
  }
4329
4979
  }
4330
4980
  if (writing && hostService !== undefined) {
@@ -4350,6 +5000,29 @@ export function apply(ctx, config = {}) {
4350
5000
  // ═══ 每回合派生的运行态卡 ═══════════════════════════════════════════════
4351
5001
 
4352
5002
  const lastCard = new Map()
5003
+ /**
5004
+ * **卡只发变化**:卡变了,只发与上次不同的行(上次的卡还在上下文里);
5005
+ * 第一次、变化超过一半、或连续发了 `CARD_FULL_EVERY` 次差异之后,发整张——
5006
+ * 长会话里早先的整张卡可能已被压缩掉,隔一段补一张整的。
5007
+ */
5008
+ const CARD_FULL_EVERY = 6
5009
+ const cardDeltas = new Map()
5010
+ function cardText(sessionId, card, { full = false } = {}) {
5011
+ const previous = lastCard.get(sessionId)
5012
+ lastCard.set(sessionId, card)
5013
+ const lines = card.split('\n')
5014
+ const before = new Set(typeof previous === 'string' ? previous.split('\n') : [])
5015
+ const changed = lines.filter((line) => line.trim() !== '' && !before.has(line))
5016
+ const sent = cardDeltas.get(sessionId) ?? 0
5017
+ if (full || typeof previous !== 'string' || sent >= CARD_FULL_EVERY || changed.length * 2 > lines.length) {
5018
+ cardDeltas.set(sessionId, 0)
5019
+ return card
5020
+ }
5021
+ /** 只少了几行(例如一次性的判据全文):上次的卡已经说过,不必再发。 */
5022
+ if (changed.length === 0) return ''
5023
+ cardDeltas.set(sessionId, sent + 1)
5024
+ return `${tr('【状态卡变化】只列与上次不同的行,其余不变:', '[Status card changes] only lines that differ from last time; the rest is unchanged:')}\n${changed.join('\n')}`
5025
+ }
4353
5026
  /**
4354
5027
  * **判据全文只在修订后注入一次**(每个会话记最后一次发过的修订号)。
4355
5028
  *
@@ -4477,6 +5150,14 @@ export function apply(ctx, config = {}) {
4477
5150
  } catch (error) {
4478
5151
  ctx.logger?.warn?.(`clearai: 事实货架重写失败 ${String(error?.message ?? error).slice(0, 160)}`)
4479
5152
  }
5153
+ /** 负向条目的兜底:上一拍工具结果之后没写成的(读面掉线、工具抛错),这一拍补写。 */
5154
+ try {
5155
+ const preview = factMutations.length > 0 ? previewOf(hostService, sessionId, factMutations) : null
5156
+ writeBack(sessionId, preview?.state ?? hostService.state(sessionId), preview?.derived ?? hostService.derive(sessionId))
5157
+ if (CFG.nativeTodoProgress) syncNativeTodos(sessionId, preview?.state ?? hostService.state(sessionId))
5158
+ } catch (error) {
5159
+ ctx.logger?.warn?.(`clearai: 负向条目回写失败 ${String(error?.message ?? error).slice(0, 160)}`)
5160
+ }
4480
5161
 
4481
5162
  /**
4482
5163
  * 无卡通道的注记 = 卡里那几句(工作区、本体、事实货架)。
@@ -4530,7 +5211,11 @@ export function apply(ctx, config = {}) {
4530
5211
  if (extraSections.length === 0 && ontologyPayload === null && factMutations.length === 0) return decision
4531
5212
  return { kind: 'enter', messages: [...decision.messages, pluginNotice(payload, noticeNote, factMutations, ontologyPayload)] }
4532
5213
  }
4533
- lastCard.set(sessionId, card)
5214
+ const shown = cardText(sessionId, card, { full: autoRound !== null })
5215
+ if (shown === '') {
5216
+ if (extraSections.length === 0 && ontologyPayload === null && factMutations.length === 0) return decision
5217
+ return { kind: 'enter', messages: [...decision.messages, pluginNotice(payload, noticeNote, factMutations, ontologyPayload)] }
5218
+ }
4534
5219
  return {
4535
5220
  kind: 'enter',
4536
5221
  messages: [
@@ -4538,7 +5223,7 @@ export function apply(ctx, config = {}) {
4538
5223
  {
4539
5224
  id: `clearai-card-${payload.turn}-${payload.step}-${Date.now().toString(36)}`,
4540
5225
  role: 'user',
4541
- content: text(card),
5226
+ content: text(shown),
4542
5227
  source: {
4543
5228
  kind: MESSAGE_SOURCE_KIND,
4544
5229
  form: 'snapshot',
@@ -4585,131 +5270,138 @@ export function apply(ctx, config = {}) {
4585
5270
  * 把这几件工具的说明换成下面这份。键是参数的路径(`items` 表示数组元素)。
4586
5271
  */
4587
5272
  const STEP_TEXT_EN = {
4588
- id: 'Stable id (letters, digits, underscore, hyphen)',
4589
- do: 'What this step does',
4590
- artifacts: 'What counts as proof: concrete output file paths relative to the workspace (a directory is not proof)',
4591
- done_criteria: 'Criterion: written before the result exists, and checkable',
4592
- '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',
4593
- '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)',
4594
- 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',
4595
- serves: 'Optional: which question or survey area this step serves (id); defaults to the current question',
4596
- predictions: 'Optional, written before acting: a prediction per candidate hypothesis (if "X" holds, what this step should show). A step where all candidates predict the same cannot tell them apart; choose a test that can',
4597
- 'predictions.items.hypothesis': 'Short name of the judgment (id also works)',
4598
- 'predictions.items.expect': 'If it holds, what you expect to see (a number or a direction if you can)',
5273
+ id: 'Stable id',
5274
+ do: 'What it does',
5275
+ artifacts: 'Output file paths that serve as proof (relative to the workspace; not a directory)',
5276
+ done_criteria: 'Criterion: written before the result exists, checkable',
5277
+ 'tests.hypotheses': 'Which judgments it tests (short names); list all competing judgments in a comparison step',
5278
+ 'tests.level': 'L2 self-judged; L3 independent evaluation; L4 released by a person (unrepeatable or external evidence)',
5279
+ expect: 'Optional, before acting: what you expect to see (a number or a direction)',
5280
+ serves: 'Optional: which question or area id it serves',
5281
+ predictions: 'Optional, before acting: what each candidate predicts; if all predict the same, choose another test',
5282
+ 'predictions.items.hypothesis': 'Short name of the judgment',
5283
+ 'predictions.items.expect': 'What you expect to see',
4599
5284
  }
4600
5285
  const prefixed = (prefix, table) => Object.fromEntries(Object.entries(table).map(([key, value]) => [`${prefix}${key}`, value]))
4601
5286
  const TOOL_TEXT_EN = {
4602
5287
  Frame: {
4603
5288
  description:
4604
- '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.',
5289
+ '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.',
4605
5290
  params: {
4606
- 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',
4607
- claim: 'Goal: the question the project answers (may be long; where identity and criteria attach)',
4608
- done_criteria: 'What counts as answered: checkable criteria with at least one countable form (a number, a count, "a file exists")',
4609
- legacy: 'Migrating an old session: lets long text and a missing headline through once (do not use for new goals)',
4610
- 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',
4611
- criteria_note: 'Background for the criteria (not part of the verdict; only explains why)',
4612
- criteria_verdict: 'Independent verdict auditKey required when changing the criteria text: "what counts as done" cannot be changed in passing',
5291
+ headline: 'The goal in one sentence (≤120 characters); required the first time',
5292
+ claim: 'The question the goal answers',
5293
+ done_criteria: 'What counts as answered: checkable, with at least one countable form (a number, a count, a file that exists)',
5294
+ legacy: 'Migration of old sessions only',
5295
+ criteria: 'Optional: the criteria one by one; otherwise the full done_criteria text is used',
5296
+ criteria_note: 'Background for the criteria; not part of the verdict',
5297
+ criteria_verdict: 'The independent verdict auditKey for changing the criteria text',
4613
5298
  promote_at_level: 'Promotion threshold (default L3)',
4614
- 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',
4615
- 'irreversible.items.action': 'One line: what this action is',
4616
- 'irreversible.items.command': 'Command signature: text that always appears in such a command (e.g. "reactor.mjs state.json pilot")',
4617
- hypotheses:
4618
- '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.',
4619
- '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',
4620
- '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',
4621
- 'hypotheses.items.assertions': 'Assertions: subject, predicate, object (ids from the domain vocabulary)',
4622
- 'hypotheses.items.question': 'Optional: which question or survey area it belongs to (id); defaults to the first question',
4623
- 'hypotheses.items.from': 'Optional: which ontology relation proposed it (relation id, e.g. an affects relation with a shape); if there is no such source, write "intuition"',
4624
- mode: 'Way of working: survey = broad survey (lay out survey areas, then pick the questions worth pursuing); solve = targeted solving (list candidate hypotheses under a question and eliminate them with tests that tell them apart); survey_then_solve = survey first, then solve. Omitted on revision = unchanged',
4625
- questions: 'Questions to answer (optional; a goal may have several; if none, the whole goal is one question). A question found during a survey is written with status="emergent" under its area; when a person decides to pursue it, it becomes open, and parked when deferred. Omitted on revision = unchanged; given = the full list',
4626
- 'questions.items.id': 'Short id (e.g. q1), used by a judgment\'s question and a step\'s serves',
4627
- 'questions.items.text': 'The question, in one sentence',
4628
- 'questions.items.status': 'open = being answered; emergent = newly found, awaiting a decision; parked = deferred (listed as an open point at conclusion)',
4629
- 'questions.items.area': 'Optional: which survey area it belongs to (area id)',
4630
- areas: 'Survey areas (for a broad survey; e.g. technology routes, main companies, cost structure). Omitted on revision = unchanged; given = the full list',
4631
- ontology: 'Ontology entries, checked by the system and written to clear/ontology/ (same shape as the files; fields in clear/ontology/SCHEMA.json). When framing, first state the quantities involved: each measure (kind=measure, gloss = its definition, unit) and how it is measured and how a reading is checked (a kind=measures relation: domain = the instrument or source, range = the measure, check = how to confirm the reading); and how the quantities affect each other (kind=affects relations, shape = rough shape). A file with the same id is replaced',
4632
- 'ontology.concepts': 'Concepts: {id, label, gloss, kind: category|measure|phenomenon, unit?}',
4633
- 'ontology.relations': 'Relations: {id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape? (affects), check? (measures)}',
4634
- reason: 'Required when revising the goal: one sentence on why (not needed the first time)',
5299
+ 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',
5300
+ 'irreversible.items.action': 'What the action is',
5301
+ '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',
5302
+ mode: 'survey = broad survey; solve = targeted solving; survey_then_solve = survey, then solve',
5303
+ 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',
5304
+ 'questions.items.id': 'Short id (e.g. q1)',
5305
+ 'questions.items.text': 'The question in one sentence',
5306
+ 'questions.items.status': 'open = being answered; emergent = awaiting a decision; parked = deferred',
5307
+ 'questions.items.area': 'Optional: survey area id',
5308
+ areas: 'Survey areas (for a broad survey)',
5309
+ 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',
5310
+ conditions: 'This run\'s conditions, e.g. {"line": "L2", "month": "2026-09"}; the default scope of judgments and the basis of the applicability check',
5311
+ ontology: 'Optional: ontology entries, checked and written to clear/ontology/ (fields in SCHEMA.json); the same id replaces',
5312
+ 'ontology.concepts': '{id, label, gloss, kind: category|measure|phenomenon, unit?}',
5313
+ 'ontology.relations': '{id, label, kind: affects|measures|defines|manifests_as, domain?, range, shape?, check?}',
5314
+ hypotheses: 'Candidate judgments, one thing each. Omitted on revision = unchanged; given = the full list, and any not listed is recorded as replaced',
5315
+ 'hypotheses.items.name': 'Short name (≤ about 20 letters); use it to refer to the judgment later',
5316
+ 'hypotheses.items.question': 'Optional: question or area id',
5317
+ 'hypotheses.items.about': 'Optional: entity or quantity ids; defaults to the framing about',
5318
+ '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',
5319
+ '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',
5320
+ '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',
5321
+ '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',
5322
+ 'hypotheses.items.assertions': 'Optional: subject–predicate–object assertions (ontology ids), strictly checked when given',
5323
+ reason: 'Required on revision: what changed and why',
4635
5324
  },
4636
5325
  },
4637
5326
  Conclude: {
4638
5327
  description:
4639
- '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.',
5328
+ '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.',
4640
5329
  params: {
4641
- outcome: 'achieved = criteria met; abandoned = give up after stating the blocker honestly',
4642
- answers: 'Conclusions (on achieved, one per question; one in total if the goal lists no questions): conclusion / basis / open points / decisions for the user. Intermediate judgments and process stay out. Candidate hypotheses still being examined without support, and open unexplained items, must go in the open points with how the conclusion would change if they hold',
4643
- 'answers.items.question': 'Which question (id); may be omitted when the goal lists no questions',
4644
- 'answers.items.conclusion': 'Conclusion: one or two sentences with values and the conditions under which they hold',
4645
- 'answers.items.basis': 'Basis: one line per adopted or excluded candidate hypothesis or verified reading, naming the experiment or source',
4646
- 'answers.items.open': 'Open points: what each concerns (about: candidate short names, unexplained item ids or question ids) and its effect on the conclusion (effect: if it holds, how the conclusion changes)',
4647
- 'answers.items.decide': 'For the user to decide (e.g. whether to re-test before scaling up)',
4648
- 'answers.items.unanswered': 'If it could not be answered, why (conclusion may then be omitted)',
5330
+ outcome: 'achieved = criteria met; abandoned = give up after stating the blocker',
5331
+ answers: 'On achieved, one per question. Candidates still being examined and open unexplained items go in open with their effect',
5332
+ 'answers.items.question': 'Question id; omit when the goal lists no questions',
5333
+ 'answers.items.conclusion': 'One or two sentences with values and the conditions where they hold',
5334
+ 'answers.items.uses': 'Knowledge entry IDs directly used by this final answer; framing references are not inherited',
5335
+ 'answers.items.scope': 'Applicable scope of this answer; numeric ranges need units',
5336
+ 'answers.items.basis': 'One line per adopted or excluded candidate or checked reading, naming the source',
5337
+ 'answers.items.open': 'Open points: about = candidate short names, unexplained item ids or question ids; effect = how the conclusion changes if it holds',
5338
+ 'answers.items.decide': 'Decisions for the person',
5339
+ 'answers.items.unanswered': 'Why it could not be answered (conclusion may then be omitted)',
4649
5340
  note: 'Conclusion note',
4650
- 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',
4651
- 'lessons.items.text': 'One sentence on what to do next time ("check this kind of rig\'s key readings against an independent source first")',
4652
- '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")',
4653
- 'lessons.items.about': 'The equipment, quantities or concepts involved (short names, used to match next time)',
4654
- 'lessons.items.evidence': 'Where in this run\'s record it showed (step, file)',
5341
+ lessons: 'Optional: lessons that change how to work next time in a similar setting; written only after the evaluator checks them',
5342
+ 'lessons.items.text': 'One sentence on what to do next time',
5343
+ 'lessons.items.kind': 'trap = pitfall; check = check first; shortcut = misleading shortcut; prior = prior',
5344
+ 'lessons.items.about': 'Ids of the equipment, quantities or concepts involved',
5345
+ 'lessons.items.evidence': 'Where the record shows it',
4655
5346
  'lessons.items.boundary': 'When it does not apply',
4656
5347
  },
4657
5348
  },
4658
5349
  CreatePlan: {
4659
5350
  description:
4660
- '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.',
5351
+ '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.',
4661
5352
  params: {
4662
- brief: `Plan description for people (Markdown, suggested ≥${MIN_BRIEF_CHARS} characters, at least two ## sections)`,
5353
+ brief: `Plan description for people (Markdown, ≥${MIN_BRIEF_CHARS} characters, at least two ## sections)`,
4663
5354
  ...prefixed('steps.items.', STEP_TEXT_EN),
4664
5355
  },
4665
5356
  },
4666
5357
  RevisePlan: {
4667
5358
  description:
4668
- '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).',
5359
+ '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).',
4669
5360
  params: {
4670
- action: 'expect = write the expectation; add = add a step; refine = change the criterion; void = void with a reason',
4671
- expect: 'action=expect: what you expect to see, and where it comes from (relation / lesson / judgment, or intuition)',
4672
- predictions: 'action=expect, optional: a prediction per candidate hypothesis; give expect, predictions, or both',
4673
- step: 'action=add: the new step',
4674
- ...prefixed('step.', STEP_TEXT_EN),
4675
- step_id: 'action=expect / refine / void: which step',
5361
+ action: 'expect / add / refine / void',
5362
+ expect: 'action=expect: what you expect to see',
5363
+ predictions: 'action=expect: per-candidate predictions',
5364
+ 'predictions.items.hypothesis': 'Short name of the judgment',
5365
+ 'predictions.items.expect': 'What you expect to see',
5366
+ step: 'action=add: the new step, same fields as a CreatePlan step',
5367
+ step_id: 'Which step',
4676
5368
  done_criteria: 'action=refine: the new criterion',
4677
- reason: 'Why (required for action=void)',
5369
+ reason: 'Why (required for void)',
4678
5370
  },
4679
5371
  },
4680
5372
  ClosePlan: {
4681
- description: 'Close the current phase: archive this plan. If the goal is not achieved yet, the system wakes you to start the next phase.',
4682
- params: { summary: 'Closing words: what this phase achieved' },
5373
+ description: 'Close and archive the current plan; if the goal is not achieved, start the next phase.',
5374
+ params: { summary: 'What this phase achieved' },
4683
5375
  },
4684
5376
  AdvancePlan: {
4685
5377
  description:
4686
- '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.',
5378
+ '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.',
4687
5379
  params: {
4688
- step_id: 'Which step to deliver (only the first unsettled step; this confirms against slips, it does not select)',
4689
- observations: 'Observations: the raw results of this step (path relative to the workspace plus one sentence)',
4690
- 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',
4691
- 'anomalies.items.what': 'What does not fit: what was expected, what was seen',
4692
- 'anomalies.items.anchor': 'Optional: on which entity or device (entity id or name)',
4693
- 'anomalies.items.touches': 'Optional: the quantities (concept ids), candidate hypotheses (judgment ids) or established facts (fact ids) it concerns. A named fact goes back to "pending re-check"; at conclusion, open items touching the answer must be written into its open points with their effect',
4694
- basis: 'Why the delivery holds: which fact in which output (must be checkable). Written by you only at L2 (self-judged)',
4695
- results:
4696
- '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',
4697
- 'results.items.hypothesis': 'Short name of the judgment (claim text also works)',
4698
- 'results.items.basis': 'One sentence: what this observation shows against the refutation condition (defaults to the basis above)',
5380
+ step_id: 'Which step (must be the first unfinished one)',
5381
+ observations: 'Raw results: path plus one sentence',
5382
+ anomalies: 'Readings that contradict the prediction or the ontology or make no sense, one sentence each; do not explain them away',
5383
+ 'anomalies.items.what': 'What was expected, what was seen',
5384
+ 'anomalies.items.anchor': 'Optional: on which entity or device',
5385
+ 'anomalies.items.touches': 'Optional: quantity, judgment or fact ids; a named fact goes back to pending re-check',
5386
+ basis: 'L2 only: why the delivery holds, citing a specific fact in an output',
5387
+ results: 'L2 only: one entry per tested judgment: support (refutation condition not met) / refute / inconclusive',
5388
+ 'results.items.hypothesis': 'Short name of the judgment',
5389
+ 'results.items.basis': 'What the observation shows against the refutation condition',
4699
5390
  },
4700
5391
  },
4701
5392
  }
4702
5393
  TOOL_TEXT_EN.Anomaly = {
4703
5394
  description:
4704
- '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.',
5395
+ '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.',
4705
5396
  params: {
4706
- what: 'action=open: what does not fit: what was expected, what was seen',
4707
- anchor: 'action=open, optional: on which entity or device',
4708
- touches: 'action=open, optional: the quantities (concept ids), candidate hypotheses (judgment ids) or established facts (fact ids) it concerns. A named fact goes back to "pending re-check"',
4709
- id: 'action=resolve: which one (the u-… id)',
4710
- outcome: 'explained / ruled_out / escalated (to a person)',
4711
- reason: 'action=resolve: on what grounds (the explanation, why it can be ruled out, what a person must decide)',
4712
- by: 'action=resolve, optional: the judgment, relation or fact that explains it',
5397
+ what: 'What was expected, what was seen',
5398
+ anchor: 'Optional: on which entity or device',
5399
+ touches: 'Optional: quantity, judgment or fact ids; a named fact goes back to pending re-check',
5400
+ id: 'Which one (u-…)',
5401
+ outcome: 'explained / ruled_out / escalated',
5402
+ reason: 'Grounds',
5403
+ by: 'Optional: the judgment, relation or fact that explains it',
5404
+ defect: 'Optional: the explanation is a measurement or method defect (e.g. a drifting probe); recorded as a defect item on that entity',
4713
5405
  },
4714
5406
  }
4715
5407
  /** 按路径把英文说明写进一份参数 schema 的副本。 */
@@ -4740,7 +5432,7 @@ export function apply(ctx, config = {}) {
4740
5432
  for (const toolName of CONTRIB.tools) {
4741
5433
  const definition = TOOL_DEFS.get(toolName)
4742
5434
  // 每一个工具的输出都过一遍统一出口:独立落账通道里的事实不会因为工具抛错/被 abort 而丢。
4743
- ctx.tools.register({ ...definition, execute: (args, exec) => inLanguage(languageOf(String(exec?.agent?.id)), async () => withPendingFacts(exec, await definition.execute(args, exec))) })
5435
+ ctx.tools.register({ ...definition, execute: (args, exec) => inLanguage(languageOf(String(exec?.agent?.id)), async () => afterTool(exec, withPendingFacts(exec, await definition.execute(args, exec)))) })
4744
5436
  }
4745
5437
 
4746
5438
  // 提示词段由当前 ClearAI DSH 预设提供,围绕认识论循环与事实边界组织。