clearai-dsh 0.5.3 → 0.5.4-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@ All notable changes to this project are recorded here. The format follows [Keep
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.5.4-rc.1] — 2026-10-10
8
+
9
+ **审计等待不再因四分钟阈值终止,裁决持久收尾并保留取消语义。**
10
+
11
+ ### Fixed
12
+
13
+ - 交付与结案持续等待同一个原生评估者,不因等待超过四分钟误记失败或重复派发;等待不产生主模型轮询。
14
+ - 正常完成与子会话恢复共用写卡和持久结算入口。裁决保存后再核对材料;暂停、取消或目标修订后不继续原调用的推进。
15
+ - 原调用丢失后的原生结束事件可恢复裁决;仅向仍获授权的同一原生目标发送一次结果通知。
16
+ - 允许复跑的评估者可通过原生后台任务工具等待和读取长命令结果,避免重复执行或睡眠轮询。
17
+ - 连续基础设施失败按目标累计,不再因改写答案重置失败计数;达到既有阈值后阻塞。
18
+
19
+ ### Changed
20
+
21
+ - `auditTimeoutMs` 仅为一次诊断提醒,`auditHardTimeoutMs` 废弃并忽略;宿主取消与外部运行预算继续有效。
22
+ - 投影版本从 21 升至 22,由旧账本重建,保留历史超时记录,不自动重启历史目标。
23
+ - RC 发布到 npm `next` 和 GitHub prerelease;不改变正式版 `latest`。原生团队融合将在 rc.2 交付。
24
+
7
25
  ## [0.5.3] — 2026-10-10
8
26
 
9
27
  **及时构建本体、保存阶段事实,并接入原生 todo 进度。**
package/README.md CHANGED
@@ -22,8 +22,8 @@ ClearAI is an **ontology discovery and exploration platform**, built on two core
22
22
 
23
23
  ```bash
24
24
  # Install (npm package, prebuilt — no build step, no allowBuilds prompt)
25
- dsh plugin --profile web add clearai-dsh@0.5.3
26
- # or in the app: Plugins → Add plugin → clearai-dsh@0.5.3
25
+ dsh plugin --profile web add clearai-dsh@0.5.4-rc.1
26
+ # or in the app: Plugins → Add plugin → clearai-dsh@0.5.4-rc.1
27
27
  ```
28
28
 
29
29
  Restart `dsh web`, then pick **ClearAI** in the preset picker at the top of a new session. That is the whole setup. [Full install notes ↓](#install-and-use)
@@ -86,12 +86,12 @@ ClearAI does **not** claim recursive self-improvement. It provides the epistemic
86
86
 
87
87
  **Recommended — install it in the app, with the version pinned:**
88
88
 
89
- In the sidebar open **Plugins → Add plugin**, enter `clearai-dsh@0.5.3`, and install. That is DSH's own plugin manager: it hands what you type to pnpm, checks that the package declares a bundle and is compatible with this host, and applies it live. (The Settings page **插件列表 / Plugins** is the read-only inventory — installing happens on the sidebar's Plugins page.)
89
+ In the sidebar open **Plugins → Add plugin**, enter `clearai-dsh@0.5.4-rc.1`, and install. That is DSH's own plugin manager: it hands what you type to pnpm, checks that the package declares a bundle and is compatible with this host, and applies it live. (The Settings page **插件列表 / Plugins** is the read-only inventory — installing happens on the sidebar's Plugins page.)
90
90
 
91
91
  **Or from a terminal — the same install:**
92
92
 
93
93
  ```bash
94
- dsh plugin --profile web add clearai-dsh@0.5.3
94
+ dsh plugin --profile web add clearai-dsh@0.5.4-rc.1
95
95
  ```
96
96
 
97
97
  This installs the prebuilt package from the npm registry. Nothing is compiled on your machine, so there is no `allowBuilds` grant to approve — the plugin is ready the moment the command returns.
package/README.zh-CN.md CHANGED
@@ -22,8 +22,8 @@ ClearAI 是一个**本体发现与探索平台**,核心由两个概念支撑
22
22
 
23
23
  ```bash
24
24
  # 安装(npm 包,预构建——无需构建步骤,不会触发 allowBuilds 授权)
25
- dsh plugin --profile web add clearai-dsh@0.5.3
26
- # 或在应用里:侧栏「插件」→ 添加插件 → clearai-dsh@0.5.3
25
+ dsh plugin --profile web add clearai-dsh@0.5.4-rc.1
26
+ # 或在应用里:侧栏「插件」→ 添加插件 → clearai-dsh@0.5.4-rc.1
27
27
  ```
28
28
 
29
29
  重启 `dsh web`,在新建会话顶部的模式选择器里选 **ClearAI** 即可。这就是全部步骤。[完整安装说明 ↓](#安装与使用)
@@ -86,12 +86,12 @@ ClearAI **不**声称递归自我改进。它提供的是自我改进系统所
86
86
 
87
87
  **推荐——在应用里装,并把版本钉住:**
88
88
 
89
- 侧栏打开**「插件」→ 添加插件**,填 `clearai-dsh@0.5.3`,安装。这就是 DSH 自己的插件管理器:它把你填的东西交给 pnpm,校验这个包声明了组合包、与当前宿主兼容,然后当场生效。(设置里的**插件列表**是**只读清单**;安装入口在侧栏那个「插件」页。)
89
+ 侧栏打开**「插件」→ 添加插件**,填 `clearai-dsh@0.5.4-rc.1`,安装。这就是 DSH 自己的插件管理器:它把你填的东西交给 pnpm,校验这个包声明了组合包、与当前宿主兼容,然后当场生效。(设置里的**插件列表**是**只读清单**;安装入口在侧栏那个「插件」页。)
90
90
 
91
91
  **或者开终端——同一次安装:**
92
92
 
93
93
  ```bash
94
- dsh plugin --profile web add clearai-dsh@0.5.3
94
+ dsh plugin --profile web add clearai-dsh@0.5.4-rc.1
95
95
  ```
96
96
 
97
97
  从 npm registry 装预构建产物。本机不跑任何编译,因此不需要批准 `allowBuilds` 授权——命令返回时插件就已经可用。
package/lib/fold.js CHANGED
@@ -79,7 +79,7 @@ export const MUTATION_KIND = 'clearai'
79
79
  * v20 → v21:持久核算复核、最终实际引用、幂等审计派发;旧日志原样重放。
80
80
  * 投影缓存按版本判定,所以旧缓存会被丢弃、从日志重折一遍。
81
81
  */
82
- export const STATE_VERSION = 21
82
+ export const STATE_VERSION = 22
83
83
 
84
84
  /**
85
85
  * **只留台账、不折进视图**的变更类型(词汇表的另一半)。
@@ -598,6 +598,8 @@ export function applyMutation(state, mutation) {
598
598
  evaluator: 'independent',
599
599
  child: mutation.evaluator_session ?? null,
600
600
  capability: mutation.capability ?? null,
601
+ goal_id: mutation.goal_id ?? null,
602
+ goal_revision: mutation.goal_revision ?? null,
601
603
  /**
602
604
  * **同态判据**:被裁决的那份产物/问题的摘要指纹。内核据此判断
603
605
  * 「这一次与上一次是同一件东西」并复用旧裁决——于是「这次没花钱」在账上看得见。
@@ -636,12 +638,20 @@ export function applyMutation(state, mutation) {
636
638
  })
637
639
  break
638
640
  }
641
+ case 'audit/notified': {
642
+ const audit = next.audits.find((item) => item.id === mutation.id)
643
+ if (audit) { audit.notifiedAt = at; audit.notificationId = mutation.message_id }
644
+ break
645
+ }
639
646
  case 'audit/settled': {
640
647
  const audit = next.audits.find((item) => item.id === mutation.id)
641
648
  if (audit !== undefined) {
642
649
  audit.verdict = mutation.verdict
643
650
  /** 两项裁决:交付成立吗 + 每条判断的结果。旧账没有这两格,`verdict` 那时说的就是交付成立吗。 */
644
651
  audit.holds = mutation.holds ?? null
652
+ audit.settledAt = mutation.settled_at ?? null
653
+ audit.rechecks = Array.isArray(mutation.rechecks) ? clone(mutation.rechecks) : []
654
+ audit.lessons = Array.isArray(mutation.lessons) ? clone(mutation.lessons) : []
645
655
  audit.reuse = Array.isArray(mutation.reuse) ? clone(mutation.reuse) : []
646
656
  audit.results = Array.isArray(mutation.results) ? mutation.results : []
647
657
  audit.shortfalls = mutation.shortfalls ?? []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clearai-dsh",
3
- "version": "0.5.3",
3
+ "version": "0.5.4-rc.1",
4
4
  "description": "ClearAI: an ontology-first DSH agent preset — evidence-checked research that grows into a domain ontology.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -369,8 +369,6 @@ export function apply(ctx, config = {}) {
369
369
  bashDenyRules: config.bashDenyRules !== false,
370
370
  auditProvider: config.auditProvider ?? 'spawn',
371
371
  auditTimeoutMs: config.auditTimeoutMs ?? 240000,
372
- /** 一次评估从派出起最多等多久:超过就如实结成「未知」并放开,不让一次评估拖住整个目标。 */
373
- auditHardTimeoutMs: config.auditHardTimeoutMs ?? 240000,
374
372
  // 三张脸的**候选**工具名。真正的 face 还要过一道「这个部署里到底有没有这件工具」的过滤
375
373
  // (见 resolveToolFace):`read_image` 只在挂了 `attachments` 的部署里存在,名单里写了它、
376
374
  // 部署里没有,`tools.restrict` 会**直接抛**(未知工具名)→ 评估整条路 fail-closed。
@@ -380,6 +378,7 @@ export function apply(ctx, config = {}) {
380
378
  /** 贡献表。缺省 = 全开;要裁剪就从这里裁,而不是去改装配代码。 */
381
379
  contributions: config.contributions ?? {},
382
380
  }
381
+ if (config.auditHardTimeoutMs !== undefined) ctx.logger?.warn?.('clearai: auditHardTimeoutMs is deprecated and ignored; auditTimeoutMs is diagnostic only. Cancellation and run budgets belong to the host.')
383
382
 
384
383
  /** 贡献表:先校验(装配期炸),后登记(见文件末尾的装配段)。 */
385
384
  const CONTRIB = resolveContributions(CFG.contributions)
@@ -393,8 +392,8 @@ export function apply(ctx, config = {}) {
393
392
  *
394
393
  * **要解决的问题**:`audit/dispatched` 原来只写在**工具结果的 `mutations` 数组**里。
395
394
  * 子代理是异步的:工具进入 `await` 之后,进程可能被 abort、宿主服务可能瞬态不可得。
396
- * 一旦这条路出问题,整批变更随栈帧一起消失——`turnDemand` 的「有裁决在飞 ⇒ hold」不触发,
397
- * `sweepEndedAudits` 也看不见,而模型只会原样重试。代价是一次已经算完的评审
395
+ * 一旦这条路出问题,整批变更随栈帧一起消失,
396
+ * `sweepEndedAudits` 看不见,而模型只会原样重试。代价是一次已经算完的评审
398
397
  * (耗时以分钟计)从账本上不存在。
399
398
  *
400
399
  * **修法的第一性原理**:事实不能寄存在"工具调用成功返回"这个易失载体上。
@@ -1068,7 +1067,7 @@ export function apply(ctx, config = {}) {
1068
1067
  '准入只核验了「坐标存在且非空」——齐备不等于这一步做完了;判据里的断言(数值、口径、一致性)必须由你逐条核对。',
1069
1068
  rerunDir === null
1070
1069
  ? '你不得修改任何文件,不得执行写入命令,不得重做方案。'
1071
- : `原工作区只读:不要在里面写文件或运行命令。要核对数字就复跑:工作区副本在 ${rerunDir}(不含 clear/),cd 进去运行产物自带的脚本,对照它打印的结果。复跑的读数是硬信号;不要重做方案。`,
1070
+ : `原工作区只读:不要在里面写文件或运行命令。要核对数字就复跑:工作区副本在 ${rerunDir}(不含 clear/),cd 进去运行产物自带的脚本,对照它打印的结果。命令转为后台 job 时,用 job_output({job_id,wait:true,timeout_ms:600000}) 等待并收取同一任务的结果;不要用 sleep 轮询、重跑相同命令或读取宿主私有日志找结果。不再需要的任务用 job_kill 取消。复跑的读数是硬信号;不要重做方案。`,
1072
1071
  ],
1073
1072
  [
1074
1073
  `Working directory: ${sessionCwdLabel(sessionId)}`,
@@ -1077,7 +1076,7 @@ export function apply(ctx, config = {}) {
1077
1076
  'Admission only checked that the outputs exist and are non-empty; that is not the same as the step being done. You must check the claims in the criteria (numbers, definitions, consistency) one by one.',
1078
1077
  rerunDir === null
1079
1078
  ? 'You may not modify any file, run write commands or redo the work.'
1080
- : `The original workspace is read-only: do not write files or run commands in it. To check numbers, re-run: a copy of the workspace is at ${rerunDir} (without clear/); cd into it and run the scripts the outputs came from, and compare what they print. Re-run readings are hard signals; do not redo the work.`,
1079
+ : `The original workspace is read-only: do not write files or run commands in it. To check numbers, re-run: a copy of the workspace is at ${rerunDir} (without clear/); cd into it and run the scripts the outputs came from, and compare what they print. When a command becomes a background job, collect that same job with job_output({job_id,wait:true,timeout_ms:600000}); do not sleep-poll, repeat the command, or search private host logs for its output. Cancel unnecessary jobs with job_kill. Re-run readings are hard signals; do not redo the work.`,
1081
1080
  ],
1082
1081
  ),
1083
1082
  ].join('\n')
@@ -1219,6 +1218,73 @@ export function apply(ctx, config = {}) {
1219
1218
  }
1220
1219
 
1221
1220
  const pendingAudits = new Map()
1221
+ const settlingAudits = new Map()
1222
+ const evaluatorCalls = new Map()
1223
+ const auditNotifications = new Set()
1224
+
1225
+ /** Native completion can outlive the tool invocation after a preset reload. */
1226
+ ctx.on('subagent/end', async ({ id } = {}) => {
1227
+ if (!id || [...pendingAudits.values()].some((entry) => String(entry.run.id) === String(id))) return
1228
+ for (const session of ctx.get('sessions')?.list?.() ?? []) {
1229
+ const sessionId = String(session.id)
1230
+ const audit = stateOf(sessionId).audits?.find((item) => item.child === String(id) && item.verdict === null)
1231
+ if (!audit) continue
1232
+ const recovered = await recoverVerdictFromChildSession(id)
1233
+ if (!recovered) continue // pre-step recovery retries once the native log is available
1234
+ const result = recovered.ok && (!String(audit.capability).includes('outputSchema') || recovered.structured)
1235
+ ? { verdict: recovered.verdict }
1236
+ : { basis: `Evaluator ended (${recovered.stopReason ?? 'missing structured output'})`, shortfalls: ['audit_incomplete'] }
1237
+ await settleAudit(sessionId, audit, result)
1238
+ const agent = ctx.get('agents')?.get?.(sessionId)
1239
+ const goal = agent && nativeGoal(agent)
1240
+ const key = `${sessionId}:${audit.id}`
1241
+ if (!goal || goal.phase !== 'active' || goal.activation !== 'armed' || goal.id !== audit.goal_id || goal.revision !== audit.goal_revision || evaluatorCalls.has(`${sessionId}:${audit.kind}:${audit.step}`) || auditNotifications.has(key)) continue
1242
+ const messageId = `clearai-audit-ready-${audit.id}`
1243
+ const events = session.snapshotEvents?.() ?? session.ownEvents?.() ?? []
1244
+ if (events.some((event) => event.type === 'user/message' && event.data?.message?.id === messageId) || [...(agent.inbox?.nextStep ?? []), ...(agent.inbox?.nextTurn ?? [])].some((message) => message.id === messageId)) continue
1245
+ auditNotifications.add(key)
1246
+ try {
1247
+ agent.followup({ id: messageId, role: 'user', content: text('独立评估已收回。读取当前裁决、材料与未决项,继续原目标;不要重复派发同一评估。'), source: { kind: MESSAGE_SOURCE_KIND, form: 'snapshot', sections: [] } })
1248
+ landFact(sessionId, { t: 'audit/notified', id: audit.id, message_id: messageId })
1249
+ await flushFacts(sessionId)
1250
+ } catch (error) { auditNotifications.delete(key); ctx.logger?.warn?.(`clearai: audit notification failed: ${String(error.message)}`) }
1251
+ }
1252
+ })
1253
+
1254
+ /** All completion paths save the same card and durable settlement before returning. */
1255
+ async function settleAudit(sessionId, audit, result) {
1256
+ const key = `${sessionId}:${audit.id}`
1257
+ if (settlingAudits.has(key)) return settlingAudits.get(key)
1258
+ const operation = (async () => {
1259
+ const saved = stateOf(sessionId).audits?.find((item) => item.id === audit.id && item.verdict !== null)
1260
+ if (saved) return { holds: auditHolds(saved), basis: saved.basis, results: saved.results ?? [], shortfalls: saved.shortfalls ?? [], cardPath: saved.card_path, digest: saved.digest, mutations: [] }
1261
+ let verdict = result.verdict
1262
+ let cardPath = null
1263
+ if (verdict) {
1264
+ cardPath = writeAuditCard(sessionId, audit.step, { schema_version: 'clearai.audit.v2', kind: audit.kind, step_id: audit.step, auditor_run_id: String(audit.child), ...verdict, card: verdict.basis, created_at: Date.now() })
1265
+ if (cardPath === null) verdict = null
1266
+ }
1267
+ const settled = verdict ?? { holds: 'unknown', results: [], basis: result.verdict ? 'Could not save the evaluation card' : result.basis, shortfalls: result.verdict ? ['card_persist_failed'] : result.shortfalls }
1268
+ const mutation = landFact(sessionId, { t: 'audit/settled', id: audit.id, step: audit.step, verdict: settled.holds, ...settled, card_path: cardPath, digest: audit.digest, settled_at: Date.now() })
1269
+ await flushFacts(sessionId)
1270
+ pendingFacts.set(sessionId, (pendingFacts.get(sessionId) ?? []).filter((item) => item !== mutation))
1271
+ return { ...settled, cardPath, digest: audit.digest, mutations: [mutation] }
1272
+ })()
1273
+ settlingAudits.set(key, operation)
1274
+ try { return await operation } catch (error) { settlingAudits.delete(key); throw error }
1275
+ }
1276
+
1277
+ /** Waiting is not a model turn or a failed audit. Abort only detaches this caller. */
1278
+ async function waitForAudit(entry, signal) {
1279
+ signal?.throwIfAborted()
1280
+ let abort
1281
+ try {
1282
+ return await Promise.race([entry.settled, new Promise((_, reject) => {
1283
+ abort = () => reject(signal.reason ?? new Error('Audit caller cancelled'))
1284
+ signal?.addEventListener('abort', abort, { once: true })
1285
+ })])
1286
+ } finally { if (abort) signal?.removeEventListener('abort', abort) }
1287
+ }
1222
1288
 
1223
1289
  /**
1224
1290
  * 把「候选工具名」解析成**这个部署里真的有**的那一张脸。
@@ -1361,10 +1427,7 @@ export function apply(ctx, config = {}) {
1361
1427
  * **已结束的评估者**。
1362
1428
  *
1363
1429
  * `pendingAudits` 是**进程内**的:重启之后它空了,而投影里那条 `audit/dispatched` 还在
1364
- * (`verdict === null`)。后果有两条,后一条更狠:
1365
- * ① 卡片与面板永远写「正在裁决」——一句等不到下文的承诺;
1366
- * ② `turnDemand` 见到未落定的裁决就 `hold`(**「机器等待,不推」**)——
1367
- * 一条永远不会回来的裁决,把整个目标按死在挂起上。
1430
+ * (`verdict === null`)。恢复必须查询宿主目录与子会话日志,不能凭内存猜测仍在运行。
1368
1431
  *
1369
1432
  * 判据不看内存,看**宿主的目录**:`subagents.listChildren(sessionId)` 给每个子会话一个
1370
1433
  * `activity: 'running' | 'inactive'`(还在跑 / 只剩日志)——**宿主是"还在不在跑"的唯一权威**。
@@ -1400,7 +1463,7 @@ export function apply(ctx, config = {}) {
1400
1463
  if (!audit.child) {
1401
1464
  const child = children.find((child) => String(child.label ?? child.name ?? '').includes(audit.id))
1402
1465
  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
1466
+ else if ([...pendingAudits.values()].some((entry) => entry.auditKey === audit.id)) continue
1404
1467
  }
1405
1468
  if (running.has(String(audit.child))) continue
1406
1469
  /**
@@ -1408,20 +1471,13 @@ export function apply(ctx, config = {}) {
1408
1471
  * 跳过它就把「结束」误报成「死亡」,还会诱导重新交付 ⇒ 同一次评估被重做。
1409
1472
  */
1410
1473
  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() }
1413
- const cardPath = writeAuditCard(sessionId, audit.step, card)
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 })
1415
- lines.push(tr(`${audit.step}:裁决从子会话日志取回(交付成立:${recovered.verdict.holds})`, `${audit.step}: verdict recovered from the child session log (holds: ${recovered.verdict.holds})`))
1416
- continue
1417
- }
1418
- if (recovered !== null && recovered.ok !== true) {
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 })
1420
- lines.push(tr(`${audit.step}:评估者已结束、未正常完成(记为 unknown)`, `${audit.step}: the evaluator ended without completing (recorded as unknown)`))
1421
- continue
1422
- }
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 })
1424
- lines.push(tr(`${audit.step}:评估者已结束、结论未取回(记为 unknown)`, `${audit.step}: the evaluator ended and its conclusion was not recovered (recorded as unknown)`))
1474
+ let result
1475
+ if (recovered?.ok && (!String(audit.capability).includes('outputSchema') || recovered.structured)) result = { verdict: recovered.verdict }
1476
+ else if (recovered && !recovered.ok) result = { basis: tr(`评估者已结束,但未正常完成(${recovered.stopReason})。`, `The evaluator ended without completing (${recovered.stopReason})`), shortfalls: ['audit_incomplete'] }
1477
+ else result = { basis: tr('评估者已结束,但其结论未能从子会话日志取回。', 'The evaluator ended but no valid verdict was recovered'), shortfalls: ['auditor_ended_uncollected'] }
1478
+ const settled = await settleAudit(sessionId, audit, result)
1479
+ mutations.push(...settled.mutations)
1480
+ lines.push(`${audit.step}: ${settled.holds}`)
1425
1481
  }
1426
1482
  return { mutations, settled: mutations.length, lines }
1427
1483
  }
@@ -1485,6 +1541,20 @@ export function apply(ctx, config = {}) {
1485
1541
  }
1486
1542
 
1487
1543
  async function runEvaluator(sessionId, agent, plan, step, gate, kind, signal) {
1544
+ const key = `${sessionId}:${kind}:${step.id}`
1545
+ const previous = evaluatorCalls.get(key)
1546
+ const operation = (async () => {
1547
+ if (previous) await previous.catch(() => {})
1548
+ signal?.throwIfAborted()
1549
+ return runEvaluatorOnce(sessionId, agent, plan, step, gate, kind, signal)
1550
+ })()
1551
+ evaluatorCalls.set(key, operation)
1552
+ try { return await operation } finally { if (evaluatorCalls.get(key) === operation) evaluatorCalls.delete(key) }
1553
+ }
1554
+
1555
+ async function runEvaluatorOnce(sessionId, agent, plan, step, gate, kind, signal) {
1556
+ const nativeBefore = nativeGoal(agent)
1557
+ await flushFacts(sessionId)
1488
1558
  const mutations = []
1489
1559
  const auditKey = `a-${step.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1490
1560
  const key = `${sessionId}:${kind}:${step.id}`
@@ -1510,10 +1580,22 @@ export function apply(ctx, config = {}) {
1510
1580
  if (entry === undefined) {
1511
1581
  const durable = (stateOf(sessionId).audits ?? []).find((audit) => audit.step === step.id && audit.verdict === null)
1512
1582
  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 }
1583
+ let recoveredState
1584
+ do {
1585
+ signal?.throwIfAborted()
1586
+ const swept = await sweepEndedAudits(sessionId, stateOf(sessionId))
1587
+ mutations.push(...swept.mutations)
1588
+ recoveredState = previewOf(host(), sessionId, mutations)?.state ?? stateOf(sessionId)
1589
+ if (!(recoveredState.audits ?? []).some((audit) => audit.id === durable.id && audit.verdict === null)) break
1590
+ // Observe the host catalog without returning another polling turn to the model.
1591
+ await waitForAudit({ settled: new Promise(resolve => setTimeout(resolve, 1000)) }, signal)
1592
+ } while (true)
1593
+ const synced = syncWorkspace(sessionId, stateOf(sessionId))
1594
+ if (synced) mutations.push(synced)
1595
+ recoveredState = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state ?? stateOf(sessionId)
1596
+ if (auditDigest(kind, step, plan, recoveredState, gate, sessionId) !== digest) return { holds: 'unknown', results: [], basis: '恢复评估期间材料已变化,旧裁决不能推进', shortfalls: ['audit_material_changed'], cardPath: null, digest, mutations }
1597
+ const currentGoal = nativeGoal(agent)
1598
+ if (nativeBefore && (!currentGoal || currentGoal.id !== nativeBefore.id || currentGoal.revision !== nativeBefore.revision || currentGoal.phase !== nativeBefore.phase)) return { holds: 'pending', results: [], basis: '原生目标已变化,仅保存裁决', shortfalls: ['audit_goal_changed'], cardPath: null, digest, mutations }
1517
1599
  const recovered = reuseAudit(recoveredState, step.id, digest)
1518
1600
  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
1601
  }
@@ -1564,7 +1646,7 @@ export function apply(ctx, config = {}) {
1564
1646
  * 每次派发使用独立尝试 id;补齐子会话时按同 id 更新。已落定的有效裁决按材料 digest 复用。
1565
1647
  */
1566
1648
  const pendingId = `audit:pending:${auditPathComponent(`${sessionId}:${kind}:${step.id}:${digest}:${auditKey}`).slice(0, 32)}`
1567
- landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, capability: null, evaluator_session: null, status: 'dispatching' })
1649
+ landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, capability: null, evaluator_session: null, status: 'dispatching', goal_id: nativeBefore?.id, goal_revision: nativeBefore?.revision })
1568
1650
  try { await flushFacts(sessionId) } catch (error) {
1569
1651
  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
1652
  return { holds: 'unknown', results: [], basis: '派发记录未持久保存,未派发评估者', shortfalls: ['audit_dispatch_not_durable'], cardPath: null, digest, mutations }
@@ -1575,7 +1657,7 @@ export function apply(ctx, config = {}) {
1575
1657
  persona: evaluatorDiscipline(),
1576
1658
  prompt: evaluatorPrompt(initialState, step, gate, sessionId, rerunDir),
1577
1659
  outputSchema: verdictSchema(),
1578
- toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, process.platform === 'win32' ? 'pwsh' : 'bash']) },
1660
+ toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, process.platform === 'win32' ? 'pwsh' : 'bash', 'job_output', 'job_list', 'job_kill']) },
1579
1661
  parent: agent,
1580
1662
  signal,
1581
1663
  })
@@ -1598,75 +1680,33 @@ export function apply(ctx, config = {}) {
1598
1680
  }
1599
1681
  entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined, startedAt: Date.now() }
1600
1682
  pendingAudits.set(key, entry)
1683
+ const diagnostic = setTimeout(() => ctx.logger?.warn?.(`clearai: evaluator ${entry.run.id} is still running; continuing to wait without restarting it`), CFG.auditTimeoutMs)
1684
+ diagnostic.unref?.()
1601
1685
  entry.settled = dispatched.run.result.then(
1602
- (value) => ({ ok: true, value }),
1603
- (error) => ({ ok: false, error }),
1604
- )
1605
- }
1606
- const outcome = await Promise.race([
1607
- entry.settled,
1608
- new Promise((resolve) => {
1609
- const timer = setTimeout(() => resolve(null), CFG.auditTimeoutMs)
1610
- if (typeof timer?.unref === 'function') timer.unref()
1611
- }),
1612
- ])
1613
- if (outcome === null) {
1614
- /**
1615
- * **超过硬上限就放开**:一次挂住的评估会拖住整个目标(出现过挂数小时的情形)。
1616
- * 超时如实结成「未知」(与评估者失败同一种结局),释放这次派遣;下一次结案或交付重新派。
1617
- */
1618
- if (Date.now() - (entry.startedAt ?? Date.now()) >= CFG.auditHardTimeoutMs) {
1686
+ (value) => {
1687
+ const stopReason = String(value?.stopReason ?? 'completed')
1688
+ if (stopReason !== 'completed') return { basis: `Evaluator did not complete (${stopReason})`, shortfalls: ['audit_incomplete'] }
1689
+ if (value?.structured === undefined && entry.capability.includes('outputSchema')) return { basis: 'Native structured audit result missing', shortfalls: ['audit_structured_missing'] }
1690
+ return { verdict: normalizeVerdict(value?.structured ?? parseLooseJson(value?.output)) }
1691
+ },
1692
+ (error) => ({ basis: `Evaluator failed: ${String(error?.message ?? error)}`, shortfalls: [signal?.aborted ? 'audit_cancelled' : 'audit_failed'] }),
1693
+ ).then((result) => settleAudit(sessionId, { id: entry.auditKey, step: entry.step, kind: entry.kind, child: entry.run.id, digest }, result)).finally(async () => {
1694
+ clearTimeout(diagnostic)
1619
1695
  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
- }
1630
- // 仍在跑:条目留着,下一次交付继续等同一次派遣(不重复派遣)。派发事实已经在上面的 mutations 里。
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 }
1632
- }
1633
- // 已落定:这次派遣的生命周期到此为止。下一次交付是**新的一次评估**(新证据),必须重新派遣。
1634
- pendingAudits.delete(key)
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
- }
1640
- if (outcome.ok !== true) {
1641
- return settleUnknown(tr(`评估者失败:${String(outcome.error?.message ?? outcome.error)}`, `The evaluator failed: ${String(outcome.error?.message ?? outcome.error)}`), ['audit_failed'])
1696
+ dropRerunCopy(entry.rerunDir)
1697
+ try { await entry.run.dispose?.() } catch { /* The completed result is already durable. */ }
1698
+ })
1699
+ // A cancelled caller may no longer await settlement; keep failures observable.
1700
+ entry.settled.catch((error) => ctx.logger?.warn?.(`clearai: audit settlement failed: ${String(error?.message ?? error)}`))
1642
1701
  }
1643
- /**
1644
- * **裁决一旦结束,就要落一条结算事实**——不管结局是什么。
1645
- *
1646
- * 三条路原来直接 `return unknown`(评估者失败 / 没正常结束 / 评估卡落盘失败),
1647
- * 账上只剩 `audit/dispatched`:看上去像"它还在跑",而它**已经结束了**。
1648
- * 结局不好也是结局,如实落下来——不然那条派发事实会在账上挂到天荒地老,
1649
- * 而"评估者没有悬空"这条不变量也只能红着,连解释都拿不出证据。
1650
- */
1702
+ const verdict = await waitForAudit(entry, signal)
1703
+ signal?.throwIfAborted()
1704
+ mutations.push(...verdict.mutations)
1705
+ const cardPath = verdict.cardPath
1706
+ const nativeAfter = nativeGoal(agent)
1707
+ if (nativeBefore && (!nativeAfter || nativeAfter.id !== nativeBefore.id || nativeAfter.revision !== nativeBefore.revision || nativeAfter.phase !== nativeBefore.phase)) return { ...verdict, holds: 'pending', basis: '裁决已保存;原生目标已暂停、结束或修订,本次不再推进', shortfalls: ['audit_goal_changed'], mutations }
1708
+ if (verdict.holds === 'unknown') return { ...verdict, mutations }
1651
1709
 
1652
- const settled = outcome.value
1653
- const stopReason = String(settled?.stopReason ?? 'completed')
1654
- if (stopReason !== 'completed' && settled?.structured === undefined) {
1655
- return settleUnknown(tr(`评估者未正常结束(${stopReason})`, `The evaluator did not end normally (${stopReason})`), ['audit_incomplete'])
1656
- }
1657
- if (settled?.structured === undefined && entry.capability.includes('outputSchema')) return settleUnknown('原生结构化审计结果缺失,文本不作为新裁决', ['audit_structured_missing'])
1658
- const verdict = settled?.structured !== undefined ? normalizeVerdict(settled.structured) : normalizeVerdict(parseLooseJson(settled?.output))
1659
- try {
1660
- await entry.run.dispose?.()
1661
- } catch {
1662
- /* dispose 失败不影响裁决事实 */
1663
- }
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() }
1665
- const cardPath = writeAuditCard(sessionId, step.id, card)
1666
- if (cardPath === null) {
1667
- return settleUnknown(tr('评估卡落盘失败:裁决降级', 'Could not save the evaluation card: verdict downgraded'), ['card_persist_failed'])
1668
- }
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
1710
  const synced = syncWorkspace(sessionId, stateOf(sessionId))
1671
1711
  if (synced !== null) mutations.push(synced)
1672
1712
  const fresh = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state
@@ -3416,7 +3456,8 @@ export function apply(ctx, config = {}) {
3416
3456
  mutations.push(...audit.mutations)
3417
3457
  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 })
3418
3458
  if (audit.holds !== 'yes') {
3419
- const failureStep = `goal:${goal.id}:${audit.digest ?? 'unknown'}`
3459
+ // Changing an answer cannot reset a repeatedly unavailable audit service.
3460
+ const failureStep = `goal:${goal.id}:${audit.holds === 'unknown' && !audit.shortfalls?.includes('audit_material_changed') ? 'infrastructure' : audit.digest ?? 'unknown'}`
3420
3461
  const failures = (state.blocks[`goal:${failureStep}`] ?? 0) + 1
3421
3462
  mutations.push({ t: 'block/counted', plan: 'goal', step: failureStep, count: failures, reason: `goal_audit:${audit.holds}` })
3422
3463
  if (failures >= CFG.blockedThreshold) blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, `目标审查连续失败 ${failures} 次,保持开放并停止续跑`)
@@ -5110,7 +5151,7 @@ export function apply(ctx, config = {}) {
5110
5151
  // 写不出来不影响这一拍:卡里的指针会指向一个还不存在的文件,下拍再试。
5111
5152
  }
5112
5153
  /**
5113
- * **独立落账通道的兜底**:上一步在 `await` 之前落下的派发/派遣事实,如果没赶上
5154
+ * **独立落账通道的兜底**:上一步在 `await` 之前落下的派发/裁决事实,如果没赶上
5114
5155
  * 那一次工具结果(工具抛错、被 abort、或结果丢失),在这里补折一次。
5115
5156
  * 放在 `factMutations` 初始化之后、别的事实之前——它是**已经发生**的事,
5116
5157
  * 语义上早于这一拍新收上来的结论。
@@ -5128,7 +5169,7 @@ export function apply(ctx, config = {}) {
5128
5169
  }
5129
5170
  /**
5130
5171
  * 失联的评估者:重启之后 `pendingAudits` 空了,而投影里那条裁决还停在「在跑」——
5131
- * 它会把目标按在 hold 上。这里问一次宿主的子代理目录,把「它已经不在跑」如实落成一条事实。
5172
+ * 这里问一次宿主的子代理目录,把「它已经不在跑」如实落成一条事实。
5132
5173
  */
5133
5174
  try {
5134
5175
  const audits = await sweepEndedAudits(sessionId, hostService.state(sessionId))