clearai-dsh 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,6 +20,7 @@
20
20
  */
21
21
 
22
22
  import { createTodoMirror } from './native-todos.js'
23
+ import { recoverToolArguments } from './tool-argument-stream.js'
23
24
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
24
25
  import { tmpdir } from 'node:os'
25
26
 
@@ -30,7 +31,11 @@ import { SECTION_TABLE } from './prompts.js'
30
31
  import { VERIFICATION_LOOP, describeOntology, validateOntology } from './ontology.js'
31
32
  import { compareScope, mergeScope, normalizeScope, scopeText, scopeVerdictText } from './scope.js'
32
33
  import { citeVerdict, mergeAbout, negativeItems, relatedKnowledge, resolveAbout } from './knowledge-items.js'
33
- import { auditMaterialDigest, auditPathComponent, contentDigest, fileDigest, methodSnapshot } from './audit-material.js'
34
+ import { auditMaterialDigest, auditRerunInputs, auditPathComponent, contentDigest, fileDigest, methodSnapshot } from './audit-material.js'
35
+ import { auditCriteria, validateAuditEvidence, citationsUnchanged } from './audit-evidence.js'
36
+ import { workspacePath } from './workspace-path.js'
37
+ import { integrityStore, protectedMaterial } from './integrity.js'
38
+ import { createRerunCopy } from './rerun-copy.js'
34
39
  import { nativeAuditSchema, recoveredStructuredOutput } from './audit-schema.js'
35
40
  import { MODEL_ID, appendRun, checkModelSpec, compareOutputs, deviationText, needsRerun, numericOutputs } from './models.js'
36
41
 
@@ -325,6 +330,7 @@ function resolveContributions(contributions) {
325
330
  // ── 插件主体 ────────────────────────────────────────────────────────────────
326
331
 
327
332
  export function apply(ctx, config = {}) {
333
+ ctx.on('llm/stream', (options, next) => recoverToolArguments(next(), TOOL_CATALOG, options.signal))
328
334
  // 配置面先校验:组合文件里写错一个键名,以前是静默无效(比如把一个键拼错),
329
335
  // 现在是装配期抛错——与贡献表同一套「表外的名字不许出现」的纪律。
330
336
  for (const key of Object.keys(config)) {
@@ -410,7 +416,7 @@ export function apply(ctx, config = {}) {
410
416
  {
411
417
  let probe
412
418
  try { probe = ctx.get('subagents') } catch { probe = undefined }
413
- if (probe !== undefined && subagentApi(probe) === null) ctx.logger?.warn?.('clearai: the host subagents service exposes neither start() nor startActivation(); independent evaluation will fail closed on this host version')
419
+ if (probe !== undefined && subagentApi(probe) === null) ctx.logger?.warn?.('clearai: the host subagents service exposes no startActivation(); independent evaluation will fail closed on this host version')
414
420
  }
415
421
 
416
422
  /** 贡献表:先校验(装配期炸),后登记(见文件末尾的装配段)。 */
@@ -476,6 +482,20 @@ export function apply(ctx, config = {}) {
476
482
  if (typeof sessions?.flush === 'function' && await sessions.flush(sessions.get(sessionId)) === false) throw new Error('session durability listener unavailable')
477
483
  failedFactAppends.delete(sessionId)
478
484
  }
485
+ function writeAuthorityFile(sessionId, file, content) {
486
+ const cwd = sessionCwd(sessionId)
487
+ const path = cwd ? relative(cwd, file).replaceAll('\\', '/') : ''
488
+ if (!protectedMaterial(path)) return writeTextFile(file, content)
489
+ const event = uniqueId('write')
490
+ const receipt = integrityStore(cwd).write(path, content, { session: sessionId, event })
491
+ landFact(sessionId, { t: 'integrity/recorded', id: event, receipt })
492
+ }
493
+ function checkIntegrity(sessionId) {
494
+ const cwd = sessionCwd(sessionId)
495
+ if (!cwd) return []
496
+ try { return integrityStore(cwd).check() } catch (error) { return [{ path: 'clear/', code: 'store-unavailable', detail: String(error.message) }] }
497
+ }
498
+
479
499
  /** 取出并清空这一拍的兜底事实(只有 pre-step 调;重复取到空数组是正常的)。 */
480
500
  function drainPendingFacts(sessionId) {
481
501
  const list = pendingFacts.get(sessionId) ?? []
@@ -778,7 +798,8 @@ export function apply(ctx, config = {}) {
778
798
  result.missing.push(artifact)
779
799
  continue
780
800
  }
781
- const absolute = isAbsolute(artifact) ? artifact : resolvePath(cwd, artifact)
801
+ let absolute
802
+ try { absolute = workspacePath(cwd, artifact, { mustExist: true }).absolute } catch { result.missing.push(artifact); continue }
782
803
  let stat = null
783
804
  try {
784
805
  stat = statSync(absolute)
@@ -894,7 +915,7 @@ export function apply(ctx, config = {}) {
894
915
  '',
895
916
  '**纪律:**',
896
917
  '- 只核对不发挥:你的职责是对照标准验收,不是重做方案、不是提改进建议。',
897
- '- 你没有写入权限:任何需要产出文件的事都不是你的事。',
918
+ '- 直接写工具已禁用。仅在提供的副本中复跑;不要改原材料。工具限制不是文件系统沙箱。',
898
919
  '- 本次裁决发生在系统收下交付/结案之前。本次评估卡、事实升格、目标完成标记都在裁决返回并复核后落盘,此刻尚未出现是正常时序,不是缺失证据。仍须核对已经声称存在的历史记录及实质产物。',
899
920
  '- 你给**两项**裁决,不要混在一起:',
900
921
  ' · **交付成立吗**(`holds`):yes = 判据逐条满足、观测真实;no = 有判据不满足,或观测与记录对不上;unclear = 凭现有材料判不了。',
@@ -902,7 +923,7 @@ export function apply(ctx, config = {}) {
902
923
  '- 交付成立与判断被推翻可以同时为真:推翻是有价值的结果,它不让交付失败。不要为了让步骤通过而写 support。',
903
924
  '- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。结论用到了 clear/knowledge/ 下的已有条目、却没在判断的 uses 里引用的,也写进来(它绕过了适用性判定)。没有就给空数组。',
904
925
  '',
905
- '**回包的形状就是你的动作空间(字段长度由 schema 校验,超了会被拒):**',
926
+ '**回包必须可复核(字符上限限制落账长度,不是生成 token 预算):**',
906
927
  '- `basis` 是**一句话结论**,≤1200 字。**不要在这里写论证**——论证放 `refs`:逐条 `{path, line}` 指到你实际读过的文件与行,让第三方照着就能复核。',
907
928
  '- `shortfalls` 每条**必须**写成三格:`{criterion, what, missing}`——`criterion` 指明**判据的哪一条**(引它的编号或原文前 20 字),`what` 是你实际读到的(带 `path:line`),`missing` 是还缺什么才算满足。**一段散文不算一条缺口**:读的人无法逐条对照。',
908
929
  '- 没有缺口就给空数组;有缺口却只写"整体不足"等于没写。',
@@ -918,7 +939,7 @@ export function apply(ctx, config = {}) {
918
939
  '',
919
940
  '**Discipline:**',
920
941
  '- Check, do not improvise: your job is to accept against the criteria, not to redo the work or suggest improvements.',
921
- '- You cannot write: anything that needs a file produced is not your job.',
942
+ '- Direct write tools are disabled. Re-run only in the supplied copy; do not change original materials. Tool restrictions are not a filesystem sandbox.',
922
943
  '- 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.',
923
944
  '- You give **two** verdicts; keep them apart:',
924
945
  ' · **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.',
@@ -926,7 +947,7 @@ export function apply(ctx, config = {}) {
926
947
  '- 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.',
927
948
  '- 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.',
928
949
  '',
929
- '**The shape of your reply is your action space (field lengths are checked by the schema; overruns are rejected):**',
950
+ '**Your reply must be checkable (character limits bound stored text, not generated tokens):**',
930
951
  '- `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.',
931
952
  '- Each `shortfalls` entry **must** have three cells: `{criterion, what, missing}`; `criterion` names **which criterion** (its number or its first 20 characters), `what` is what you actually read (with `path:line`), `missing` is what is still needed. **A paragraph of prose is not a shortfall**: the reader cannot check it item by item.',
932
953
  '- No shortfalls means an empty array; writing only "insufficient overall" is the same as writing nothing.',
@@ -1004,8 +1025,12 @@ export function apply(ctx, config = {}) {
1004
1025
  additionalProperties: false,
1005
1026
  },
1006
1027
  },
1007
- refs: {
1008
- type: 'array',
1028
+ criteria: {
1029
+ type: 'array', description: 'One evidence-based finding per numbered criterion C1, C2, …',
1030
+ items: { type: 'object', properties: { criterion: { type: 'string' }, result: { type: 'string', enum: ['pass', 'fail', 'not_applicable'] }, basis: { type: 'string', maxLength: 400 } }, required: ['criterion', 'result', 'basis'], additionalProperties: false },
1031
+ },
1032
+ refs: {
1033
+ type: 'array',
1009
1034
  description: tr('逐条证据引用:文件与行号。裁决要能被第三方照着复核。', 'Evidence references, one per file and line, so a third party can check the verdict.'),
1010
1035
  items: {
1011
1036
  type: 'object',
@@ -1013,21 +1038,12 @@ export function apply(ctx, config = {}) {
1013
1038
  path: { type: 'string', maxLength: 300 },
1014
1039
  line: { type: 'integer' },
1015
1040
  },
1016
- required: ['path'],
1041
+ required: ['path', 'line'],
1017
1042
  additionalProperties: false,
1018
1043
  },
1019
1044
  },
1020
1045
  },
1021
- /**
1022
- * `refs` **声明但不强制**。
1023
- *
1024
- * 它是我们想要的形状(逐条可复核),但把它写进 `required` 会让一份**完全可用**的裁决
1025
- * 因为少一个数组而被 runtime 丢掉——那时"有没有裁决"就变成了抛硬币。这不是假设:
1026
- * 一次真跑的评估者在正文里写清了 `verdict: support`,而结构化通道被 schema 拒收,
1027
- * 目标于是永远结不了案。**先保证裁决到得了,再要求它可复核**;没给 refs 时,
1028
- * 下面的正文兜底会把裁决从 markdown 卡片里取回来(并且如实标注它是被救回来的)。
1029
- */
1030
- required: ['holds', 'basis'],
1046
+ required: ['holds', 'basis', 'refs', 'criteria'],
1031
1047
  additionalProperties: false,
1032
1048
  })
1033
1049
 
@@ -1206,6 +1222,7 @@ export function apply(ctx, config = {}) {
1206
1222
  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 ?? '') })),
1207
1223
  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 ?? '') })),
1208
1224
  holds,
1225
+ criteria: Array.isArray(value?.criteria) ? value.criteria : [],
1209
1226
  results,
1210
1227
  anomalies,
1211
1228
  lessons,
@@ -1316,6 +1333,8 @@ export function apply(ctx, config = {}) {
1316
1333
  const saved = stateOf(sessionId).audits?.find((item) => item.id === audit.id && item.verdict !== null)
1317
1334
  if (saved) return { holds: auditHolds(saved), basis: saved.basis, results: saved.results ?? [], shortfalls: saved.shortfalls ?? [], cardPath: saved.card_path, digest: saved.digest, mutations: [] }
1318
1335
  let verdict = result.verdict
1336
+ const savedAudit = stateOf(sessionId).audits?.find(item => item.id === audit.id)
1337
+ if (verdict) verdict = validateAuditEvidence(sessionCwd(sessionId), verdict, audit.criteria ?? savedAudit?.criteria ?? [])
1319
1338
  let cardPath = null
1320
1339
  if (verdict) {
1321
1340
  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() })
@@ -1391,33 +1410,10 @@ export function apply(ctx, config = {}) {
1391
1410
  * (评估者:这一步不推进)。绝不静默降级成"没有独立裁决也算过"。
1392
1411
  */
1393
1412
  async function dispatchSubRun(options) {
1394
- const subagents = ctx.get('subagents')
1395
- if (subagents === undefined) return { ok: false, reason: tr('subagents 服务不可用', 'the subagents service is unavailable'), failures: [] }
1396
- const api = subagentApi(subagents)
1397
- if (api === null) return { ok: false, reason: tr('宿主的 subagents 服务既没有 start 也没有 startActivation:这个宿主版本不受支持', 'the host subagents service has neither start nor startActivation; this host version is unsupported'), failures: [] }
1398
- if (api === 'activation') return dispatchActivation(subagents, options)
1399
- const base = { label: options.label, parent: options.parent, signal: options.signal, prompt: text(options.prompt) }
1400
- const persona = options.persona
1401
- const schema = options.outputSchema ? nativeAuditSchema(options.outputSchema) : undefined
1402
- const toolFilter = options.toolFilter ?? null
1403
- const failures = []
1404
- // These are required audit capabilities. An infrastructure rejection must not silently weaken the verdict channel.
1405
- const attempts = [{ variant: { persona, outputSchema: schema, ...(toolFilter ? { toolFilter } : {}) }, capability: 'persona+outputSchema+toolFilter' }]
1406
- for (const attempt of attempts) {
1407
- try {
1408
- const run = await subagents.start(CFG.auditProvider, { ...base, ...attempt.variant })
1409
- /**
1410
- * `native: false` = 结论不会由运行时投递,得靠收集那一刻的返回值带上(降级路径)。
1411
- * `degraded` 把**为什么降级**如实带出去(调用方落进账本):只说「能力不是 continuable」
1412
- * 不解释原因,读账的人无法判断这是部署限制还是代码 bug。
1413
- */
1414
- return { ok: true, run, capability: attempt.capability, native: false, degraded: failures[0] ?? null }
1415
- } catch (error) {
1416
- failures.push(`${attempt.capability}:${String(error?.message ?? error).slice(0, 100)}`)
1417
- }
1418
- }
1419
- return { ok: false, reason: failures.join(' | '), failures }
1420
- }
1413
+ const subagents = ctx.get('subagents')
1414
+ if (typeof subagents?.startActivation !== 'function') return { ok: false, reason: 'DSH startActivation is required', failures: [] }
1415
+ return dispatchActivation(subagents, options)
1416
+ }
1421
1417
 
1422
1418
  /**
1423
1419
  * 一次 L3+ 交付随交付带给评估者的未解释项,超限就说清怎么压(issue #36)。
@@ -1438,19 +1434,10 @@ export function apply(ctx, config = {}) {
1438
1434
  )
1439
1435
  }
1440
1436
 
1441
- /**
1442
- * 宿主的子代理入口是哪一代(issue #38)。
1443
- *
1444
- * DSH 0.2.1-alpha.2 把 `subagents.start(provider, request)` 换成了 `startActivation(spec)`,
1445
- * 而 `engines.dsh` 拦不住新宿主:装得上、跑得起,直到第一次派评估者才炸。
1446
- * 按**方法在不在**判,不按版本号判 —— 方法在场就是能力本身,版本号只是它的间接证据。
1447
- * 两个都在时走旧入口:那一代的 persona / toolFilter 是逐次请求给的,不依赖随包预设。
1448
- */
1437
+ /** This release requires the current DSH activation API. */
1449
1438
  function subagentApi(subagents) {
1450
- if (typeof subagents?.start === 'function') return 'start'
1451
- if (typeof subagents?.startActivation === 'function') return 'activation'
1452
- return null
1453
- }
1439
+ return typeof subagents?.startActivation === 'function' ? 'activation' : null
1440
+ }
1454
1441
 
1455
1442
  /**
1456
1443
  * 新一代入口(宿主 ≥0.2.1-alpha.2)。
@@ -1478,7 +1465,7 @@ export function apply(ctx, config = {}) {
1478
1465
  delivery: 'caller',
1479
1466
  signal: options.signal ?? new AbortController().signal,
1480
1467
  request: {
1481
- prompt: text(options.prompt),
1468
+ prompt: text(options.prompt + (options.criteria ? '\n# Criteria\n' + options.criteria.map(row => `[${row.id}] ${row.text}`).join('\n') : '')),
1482
1469
  parent: options.parent,
1483
1470
  agentPreset: CFG.auditPreset,
1484
1471
  ...(schema === undefined ? {} : { outputSchema: schema }),
@@ -1664,11 +1651,12 @@ export function apply(ctx, config = {}) {
1664
1651
  }
1665
1652
 
1666
1653
  /** 投影里最近一条与该 digest 相同、且**真的给出了裁决**的结算事实。 */
1667
- function reuseAudit(state, stepId, digest) {
1654
+ function reuseAudit(state, stepId, digest, sessionId) {
1668
1655
  const matched = (state?.audits ?? []).filter((audit) => String(audit?.step ?? '') === String(stepId) && String(audit?.digest ?? '') === digest)
1669
1656
  for (let index = matched.length - 1; index >= 0; index -= 1) {
1670
1657
  const audit = matched[index]
1671
- if (!digest.startsWith('v5:') || !audit.card_path || !existsSync(audit.card_path) || !['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1658
+ if (!digest?.startsWith('v6:') || !audit.card_path || !existsSync(audit.card_path) || !['yes', 'no', 'unclear'].includes(auditHolds(audit))) continue
1659
+ if (auditHolds(audit) === 'yes' && !citationsUnchanged(sessionCwd(sessionId), audit.refs)) continue
1672
1660
  return audit
1673
1661
  }
1674
1662
  return null
@@ -1695,7 +1683,11 @@ export function apply(ctx, config = {}) {
1695
1683
  const initialSync = syncWorkspace(sessionId, stateOf(sessionId))
1696
1684
  if (initialSync !== null) mutations.push(initialSync)
1697
1685
  const initialState = previewOf(host(), sessionId, [...mutations, ...(gate.materialMutations ?? [])])?.state ?? stateOf(sessionId)
1698
- const digest = auditDigest(kind, step, plan, initialState, gate, sessionId)
1686
+ const materialErrors = []
1687
+ const digest = auditMaterialDigest({ kind, step, plan, state: initialState, gate, cwd: sessionCwd(sessionId), errors: materialErrors })
1688
+ if (!digest) return { holds: 'unknown', results: [], basis: 'Audit materials unavailable: ' + materialErrors.map(row => row.path + ' (' + row.code + ')').join('; '), shortfalls: ['audit_material_unavailable'], cardPath: null, digest: null, mutations }
1689
+ const integrity = checkIntegrity(sessionId)
1690
+ if (integrity.some(item => item.code !== 'unregistered')) return { holds: 'unknown', results: [], basis: 'Protected material integrity failed', shortfalls: ['integrity_failed'], cardPath: null, digest, mutations }
1699
1691
  let entry = pendingAudits.get(key)
1700
1692
  /**
1701
1693
  * **同态复用**:先看在飞的(pendingAudits),再看**已经落定的**(投影里 digest 相同且给出了裁决的那一条)。
@@ -1730,12 +1722,12 @@ export function apply(ctx, config = {}) {
1730
1722
  if (auditDigest(kind, step, plan, recoveredState, gate, sessionId) !== digest) return { holds: 'unknown', results: [], basis: '恢复评估期间材料已变化,旧裁决不能推进', shortfalls: ['audit_material_changed'], cardPath: null, digest, mutations }
1731
1723
  const currentGoal = nativeGoal(agent)
1732
1724
  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 }
1733
- const recovered = reuseAudit(recoveredState, step.id, digest)
1725
+ const recovered = reuseAudit(recoveredState, step.id, digest, sessionId)
1734
1726
  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 }
1735
1727
  }
1736
1728
  }
1737
1729
  if (entry === undefined) {
1738
- const reused = reuseAudit(stateOf(sessionId), step.id, digest)
1730
+ const reused = reuseAudit(stateOf(sessionId), step.id, digest, sessionId)
1739
1731
  if (reused !== null) {
1740
1732
  /**
1741
1733
  * 落一条 `audit/reused` 而不是静默返回:**"这次没花钱"也要是账上的事实**,
@@ -1779,14 +1771,25 @@ export function apply(ctx, config = {}) {
1779
1771
  *
1780
1772
  * 每次派发使用独立尝试 id;补齐子会话时按同 id 更新。已落定的有效裁决按材料 digest 复用。
1781
1773
  */
1782
- const pendingId = `audit:pending:${auditPathComponent(`${sessionId}:${kind}:${step.id}:${digest}:${auditKey}`).slice(0, 32)}`
1783
- 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 })
1774
+ const criteria = auditCriteria(step.done_criteria)
1775
+ const pendingId = `audit:pending:${auditPathComponent(`${sessionId}:${kind}:${step.id}:${digest}:${auditKey}`).slice(0, 32)}`
1776
+ landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, criteria, capability: null, evaluator_session: null, status: 'dispatching', goal_id: nativeBefore?.id, goal_revision: nativeBefore?.revision })
1784
1777
  try { await flushFacts(sessionId) } catch (error) {
1785
1778
  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 })
1786
1779
  return { holds: 'unknown', results: [], basis: '派发记录未持久保存,未派发评估者', shortfalls: ['audit_dispatch_not_durable'], cardPath: null, digest, mutations }
1787
1780
  }
1788
- const rerunDir = CFG.auditRerun ? rerunCopy(sessionId, auditKey) : null
1781
+ const copy = CFG.auditRerun ? await rerunCopy(sessionId, auditKey, auditRerunInputs(sessionCwd(sessionId), initialState, step), signal) : { directory: null, status: 'disabled' }
1782
+ const rerunDir = copy.directory
1783
+ mutations.push(landFact(sessionId, { t: 'audit/copy', id: pendingId, ...copy }))
1784
+ if (CFG.auditRerun && copy.status !== 'ready') {
1785
+ const stopped = { holds: 'unknown', results: [], basis: copy.error ?? 'Rerun snapshot unavailable', shortfalls: ['audit_rerun_unavailable'], cardPath: null, digest, mutations }
1786
+ mutations.push(landFact(sessionId, { t: 'audit/settled', id: pendingId, step: step.id, verdict: 'unknown', holds: 'unknown', basis: stopped.basis, shortfalls: stopped.shortfalls, digest }))
1787
+ await flushFacts(sessionId)
1788
+ return stopped
1789
+ }
1790
+ signal?.throwIfAborted()
1789
1791
  const dispatched = await dispatchSubRun({
1792
+ criteria,
1790
1793
  label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id} · ${pendingId}`,
1791
1794
  persona: evaluatorDiscipline(),
1792
1795
  prompt: evaluatorPrompt(initialState, step, gate, sessionId, rerunDir),
@@ -1796,7 +1799,7 @@ export function apply(ctx, config = {}) {
1796
1799
  signal,
1797
1800
  })
1798
1801
  if (dispatched.ok !== true) {
1799
- dropRerunCopy(rerunDir)
1802
+ await dropRerunCopy(sessionId, pendingId, rerunDir)
1800
1803
  /**
1801
1804
  * 派不出去:把那条"正在派"如实结掉。结算与派发**同 id**,且上面那条 pending
1802
1805
  * 走的是独立落账通道、在 `withPendingFacts` 的合并结果里排在前面,所以折法先建记录、
@@ -1808,11 +1811,11 @@ export function apply(ctx, config = {}) {
1808
1811
  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' }))
1809
1812
  try { await flushFacts(sessionId) } catch (error) {
1810
1813
  try { await dispatched.run.dispose?.() } catch {}
1811
- dropRerunCopy(rerunDir)
1814
+ await dropRerunCopy(sessionId, pendingId, rerunDir)
1812
1815
  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 })
1813
1816
  return { holds: 'unknown', results: [], basis: '子会话关联未持久保存,已停止评估', shortfalls: ['audit_child_not_durable'], cardPath: null, digest, mutations }
1814
1817
  }
1815
- entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined, startedAt: Date.now() }
1818
+ entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, criteria, rerunDir, settled: undefined, startedAt: Date.now() }
1816
1819
  pendingAudits.set(key, entry)
1817
1820
  const diagnostic = setTimeout(() => ctx.logger?.warn?.(`clearai: evaluator ${entry.run.id} is still running; continuing to wait without restarting it`), CFG.auditTimeoutMs)
1818
1821
  diagnostic.unref?.()
@@ -1824,10 +1827,10 @@ export function apply(ctx, config = {}) {
1824
1827
  return { verdict: normalizeVerdict(value?.structured ?? parseLooseJson(value?.output)) }
1825
1828
  },
1826
1829
  (error) => ({ basis: `Evaluator failed: ${String(error?.message ?? error)}`, shortfalls: [signal?.aborted ? 'audit_cancelled' : 'audit_failed'] }),
1827
- ).then((result) => settleAudit(sessionId, { id: entry.auditKey, step: entry.step, kind: entry.kind, child: entry.run.id, digest }, result)).finally(async () => {
1830
+ ).then((result) => settleAudit(sessionId, { id: entry.auditKey, step: entry.step, kind: entry.kind, child: entry.run.id, digest, criteria }, result)).finally(async () => {
1828
1831
  clearTimeout(diagnostic)
1829
1832
  pendingAudits.delete(key)
1830
- dropRerunCopy(entry.rerunDir)
1833
+ await dropRerunCopy(sessionId, entry.auditKey, entry.rerunDir)
1831
1834
  try { await entry.run.dispose?.() } catch { /* The completed result is already durable. */ }
1832
1835
  })
1833
1836
  // A cancelled caller may no longer await settlement; keep failures observable.
@@ -1840,6 +1843,7 @@ export function apply(ctx, config = {}) {
1840
1843
  const nativeAfter = nativeGoal(agent)
1841
1844
  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 }
1842
1845
  if (verdict.holds === 'unknown') return { ...verdict, mutations }
1846
+ if (checkIntegrity(sessionId).some(item => item.code !== 'unregistered')) return { ...verdict, holds: 'unknown', results: [], shortfalls: [...verdict.shortfalls, 'integrity_failed'], mutations }
1843
1847
 
1844
1848
  const synced = syncWorkspace(sessionId, stateOf(sessionId))
1845
1849
  if (synced !== null) mutations.push(synced)
@@ -1851,28 +1855,21 @@ export function apply(ctx, config = {}) {
1851
1855
  }
1852
1856
 
1853
1857
  /**
1854
- * **复跑用的工作区副本**:评估者可以在这里跑脚本核数字,原工作区一个字节不碰。
1858
+ * **复跑用的工作区副本**:评估者应在副本中跑脚本核数字;这不是阻止任意 shell 写入原文件的隔离保证。
1855
1859
  *
1856
1860
  * 为什么要它:L3 的定义是「新产生、可重跑」,而只能读文件的评估者从不重跑,只核对文件彼此是否一致——
1857
- * 一份自洽但算错的结果照样过。副本不带 `clear/`(账本与评估卡不是复跑的材料)。复制失败就不给副本,
1858
- * 评估照旧只读,不因此失败。
1861
+ * 一份自洽但算错的结果照样过。副本在工作区的专用临时目录内,使宿主的路径隔离仍能访问它。递归排除工具缓存和副本目录自身;复制失败阻止需要复跑的裁决。
1859
1862
  */
1860
- function rerunCopy(sessionId, auditKey) {
1861
- const cwd = sessionCwd(sessionId)
1862
- if (cwd === null) return null
1863
- const target = join(tmpdir(), `clearai-rerun-${auditPathComponent(auditKey)}`)
1864
- const skip = new Set([join(cwd, 'clear'), join(cwd, '.git'), join(cwd, 'node_modules')])
1865
- try {
1866
- cpSync(cwd, target, { recursive: true, filter: (source) => !skip.has(source) })
1867
- // 记号写不进不影响复跑本身:任务书照样说明这是副本。
1868
- try { markRerunCopy(cwd, target) } catch (error) { ctx.logger?.warn?.(`clearai kernel: 复跑副本记号没写成 ${String(error?.message ?? error).slice(0, 160)}`) }
1869
- return target
1870
- } catch (error) {
1871
- ctx.logger?.warn?.(`clearai kernel: 复跑副本没建成 ${String(error?.message ?? error).slice(0, 160)}`)
1872
- dropRerunCopy(target)
1873
- return null
1874
- }
1875
- }
1863
+ async function rerunCopy(sessionId, auditKey, required, signal) {
1864
+ const cwd = sessionCwd(sessionId)
1865
+ if (cwd === null) return { directory: null, status: 'unavailable', error: 'workspace unavailable' }
1866
+ const copyRoot = join(cwd, '.clearai-reruns')
1867
+ mkdirSync(copyRoot, { recursive: true })
1868
+ const target = join(copyRoot, auditPathComponent(auditKey))
1869
+ const result = await createRerunCopy(cwd, target, { required, signal })
1870
+ if (result.directory) { try { markRerunCopy(cwd, target) } catch (error) { await import('node:fs/promises').then(fs => fs.rm(target, { recursive: true, force: true })); return { ...result, directory: null, status: 'unavailable', error: String(error.message) } } }
1871
+ return result
1872
+ }
1876
1873
 
1877
1874
  /** 副本 → 项目声明的复跑环境变量(任务书要列给评估者)。副本删掉时一起丢。 */
1878
1875
  const rerunEnvironments = new Map()
@@ -1908,22 +1905,25 @@ export function apply(ctx, config = {}) {
1908
1905
  if (Object.keys(environment).length > 0) rerunEnvironments.set(target, environment)
1909
1906
  }
1910
1907
 
1911
- function dropRerunCopy(dir) {
1912
- if (dir === null) return
1913
- rerunEnvironments.delete(dir)
1914
- try {
1915
- rmSync(dir, { recursive: true, force: true })
1916
- } catch {
1917
- /* 删不掉留在临时目录里,不影响裁决 */
1918
- }
1919
- }
1908
+ async function dropRerunCopy(sessionId, id, dir) {
1909
+ if (dir === null) return
1910
+ rerunEnvironments.delete(dir)
1911
+ const started = performance.now()
1912
+ let cleanup = 'removed'
1913
+ try {
1914
+ const {rm, rmdir} = await import('node:fs/promises')
1915
+ await rm(dir, {recursive:true,force:true})
1916
+ try { await rmdir(dirname(dir)) } catch {} // another audit may still own a copy
1917
+ } catch (error) { cleanup = String(error.message) }
1918
+ landFact(sessionId, {t:'audit/copy',id,cleanup,cleanupElapsedMs:performance.now()-started})
1919
+ }
1920
1920
 
1921
1921
  /** 评估卡落盘(系统的面)。写不进 → 返回 null,调用方 fail-closed。 */
1922
1922
  function writeAuditCard(sessionId, stepId, card) {
1923
1923
  const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', auditPathComponent(stepId), `${auditPathComponent(card.auditor_run_id)}.json`)
1924
1924
  if (file === null) return null
1925
1925
  try {
1926
- writeTextFile(file, `${JSON.stringify({ ...card, evaluator: 'independent' }, null, 2)}\n`)
1926
+ writeAuthorityFile(sessionId, file, `${JSON.stringify({ ...card, evaluator: 'independent' }, null, 2)}\n`)
1927
1927
  return file
1928
1928
  } catch (error) {
1929
1929
  ctx.logger?.warn?.(`clearai kernel: 评估卡落盘失败 ${String(error?.message ?? error)}`)
@@ -2009,6 +2009,8 @@ export function apply(ctx, config = {}) {
2009
2009
  return { ok: false, response: fail('host_missing', tr('宿主包 clearai-dsh 没有挂载:状态机不在(它是会话日志的投影)。先装上它,再谈工具。', 'The host package clearai-dsh is not loaded: there is no state machine (it is a projection of the session log). Install it before using these tools.')) }
2010
2010
  }
2011
2011
  const sessionId = String(exec.agent?.id ?? 'unknown')
2012
+ const integrity = checkIntegrity(sessionId)
2013
+ if (integrity.some(item => item.code !== 'unregistered')) return { ok: false, response: fail('integrity_failed', 'Protected files changed (' + integrity.map(item => item.path + ':' + item.code).join(', ') + '); restore the registered content or re-verify in a clean workspace. Original files have been preserved.', { integrity }) }
2012
2014
  /**
2013
2015
  * **入口检查宿主的两件纯读面**(`state` / `derive`)。宿主 fiber 可以在一次调用的
2014
2016
  * `await` 期间瞬态掉出 ACTIVE:`derive` 在派发前成功、评估者跑完之后再读宿主就抛,
@@ -2261,12 +2263,12 @@ export function apply(ctx, config = {}) {
2261
2263
  const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2262
2264
  if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2263
2265
  mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter.id, basis: clip(basis, 300) })
2264
- markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2266
+ markFactBounded(sessionId, sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2265
2267
  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`))
2266
2268
  continue
2267
2269
  }
2268
2270
  mutations.push({ t: 'fact/questioned', fact: fact.id, hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2269
- markFactQuestioned(sessionCwd(sessionId), fact, { hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2271
+ markFactQuestioned(sessionId, sessionCwd(sessionId), fact, { hypothesis: refuter.id, verdict: fit.verdict, basis: clip(basis, 300) })
2270
2272
  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`))
2271
2273
  }
2272
2274
  }
@@ -2283,7 +2285,7 @@ export function apply(ctx, config = {}) {
2283
2285
  if (fit.verdict === 'out_of_scope' || fit.verdict === 'out_of_range') {
2284
2286
  const where = tr(scopeVerdictText(fit, 'zh'), scopeVerdictText(fit, 'en'))
2285
2287
  mutations.push({ t: 'fact/bounded', fact: fact.id, verdict: fit.verdict, reasons: fit.reasons, hypothesis: refuter?.id ?? null, basis: clip(basis, 300) })
2286
- markFactBounded(sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2288
+ markFactBounded(sessionId, sessionCwd(sessionId), fact, { verdict: fit.verdict, reasons: fit.reasons, basis: clip(basis, 300) })
2287
2289
  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`))
2288
2290
  continue
2289
2291
  }
@@ -2309,7 +2311,7 @@ export function apply(ctx, config = {}) {
2309
2311
  }
2310
2312
  const review = { decision: chose(asked, 'factRetract') ? 'retracted' : 'kept', reason: asked.note }
2311
2313
  mutations.push({ t: 'fact/reviewed', fact: fact.id, decision: review.decision, reason: review.reason, by: 'user' })
2312
- markFactReviewed(sessionCwd(sessionId), fact, { retracted: review.decision === 'retracted', reason: review.reason })
2314
+ markFactReviewed(sessionId, sessionCwd(sessionId), fact, { retracted: review.decision === 'retracted', reason: review.reason })
2313
2315
  notes.push(
2314
2316
  review.decision === 'retracted'
2315
2317
  ? tr(`${fact.id}:人决定**撤回**(记录保留,不再作为已知引用)`, `${fact.id}: the person chose to **retract** it (the record stays; it is no longer cited as known)`)
@@ -2494,18 +2496,21 @@ export function apply(ctx, config = {}) {
2494
2496
  const cwd = sessionCwd(sessionId)
2495
2497
  if (cwd === null) return null
2496
2498
  const known = state?.workspace?.files ?? {}
2499
+ const integrity = checkIntegrity(sessionId)
2500
+ const issues = new Map(integrity.map(item => [item.path, item]))
2497
2501
  const changes = []
2498
2502
  const seen = new Set()
2499
2503
  for (const path of listWorkspaceFiles(cwd)) {
2500
2504
  seen.add(path)
2501
- const change = readWorkspaceFile(cwd, path)
2505
+ const issue = issues.get(path)
2506
+ const change = issue ? { path, error: 'integrity:' + issue.code, digest: null } : readWorkspaceFile(cwd, path)
2502
2507
  if (change === null) continue
2503
2508
  if (known[path]?.digest !== change.digest) changes.push(change)
2504
2509
  }
2505
2510
  for (const path of Object.keys(known)) if (!seen.has(path)) changes.push({ path, removed: true })
2506
- if (changes.length === 0) return null
2511
+ if (changes.length === 0 && JSON.stringify(state?.workspace?.integrity ?? []) === JSON.stringify(integrity)) return null
2507
2512
  const id = `ws-${createHash('sha1').update(JSON.stringify(changes.map((change) => [change.path, change.digest ?? 'removed']))).digest('hex').slice(0, 12)}`
2508
- return { t: 'workspace/synced', id, changes }
2513
+ return { t: 'workspace/synced', id, changes, integrity }
2509
2514
  }
2510
2515
 
2511
2516
  /** 写货架;内容没变就返回 null(调用方据此决定要不要在卡里提一句)。 */
@@ -2527,7 +2532,7 @@ export function apply(ctx, config = {}) {
2527
2532
  if (file === null) return null
2528
2533
  try {
2529
2534
  if (existsSync(file) && readFileSync(file, 'utf8') === body) return null
2530
- writeTextFile(file, body)
2535
+ writeAuthorityFile(sessionId, file, body)
2531
2536
  return `clear/knowledge/facts/INDEX.md`
2532
2537
  } catch (error) {
2533
2538
  ctx.logger?.warn?.(`clearai facts: 货架写入失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -2587,7 +2592,7 @@ export function apply(ctx, config = {}) {
2587
2592
  const file = sessionFile(sessionId, 'clear', 'goals', `${goal.id}.md`)
2588
2593
  if (file === null) return ''
2589
2594
  if (existsSync(file) && readFileSync(file, 'utf8') === body) return ''
2590
- writeTextFile(file, body)
2595
+ writeAuthorityFile(sessionId, file, body)
2591
2596
  return join('clear', 'goals', `${goal.id}.md`)
2592
2597
  } catch (error) {
2593
2598
  ctx.logger?.warn?.(`clearai goal doc: 写入失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -2620,7 +2625,7 @@ export function apply(ctx, config = {}) {
2620
2625
  const file = join(cwd, ...ONTOLOGY_REL, 'SCHEMA.json')
2621
2626
  const body = `${JSON.stringify(hostService.domain.schema(), null, 2)}\n`
2622
2627
  if (existsSync(file) && readFileSync(file, 'utf8') === body) return null
2623
- writeTextFile(file, body)
2628
+ writeAuthorityFile(sessionId, file, body)
2624
2629
  return file
2625
2630
  } catch (error) {
2626
2631
  ctx.logger?.warn?.(`clearai ontology: 字段定义写入失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -3919,7 +3924,7 @@ export function apply(ctx, config = {}) {
3919
3924
  if (file === null) return null
3920
3925
  const at = Date.now()
3921
3926
  try {
3922
- writeTextFile(file, `${JSON.stringify({ ...record, session: sessionId, status: 'established', review: null, at, history: [{ event: 'promoted', at, level: record.level ?? null }] }, null, 2)}\n`)
3927
+ writeAuthorityFile(sessionId, file, `${JSON.stringify({ ...record, session: sessionId, status: 'established', review: null, at, history: [{ event: 'promoted', at, level: record.level ?? null }] }, null, 2)}\n`)
3923
3928
  return file
3924
3929
  } catch (error) {
3925
3930
  ctx.logger?.warn?.(`clearai kernel: 事实落盘失败 ${String(error?.message ?? error)}`)
@@ -3938,7 +3943,7 @@ export function apply(ctx, config = {}) {
3938
3943
  const file = sessionFile(sessionId, 'clear', 'knowledge', 'lessons', `${record.id}.json`)
3939
3944
  if (file === null) return null
3940
3945
  try {
3941
- writeTextFile(file, `${JSON.stringify({ ...record, session: sessionId, status: 'active', at: Date.now() }, null, 2)}\n`)
3946
+ writeAuthorityFile(sessionId, file, `${JSON.stringify({ ...record, session: sessionId, status: 'active', at: Date.now() }, null, 2)}\n`)
3942
3947
  return file
3943
3948
  } catch (error) {
3944
3949
  ctx.logger?.warn?.(`clearai kernel: 经验落盘失败 ${String(error?.message ?? error)}`)
@@ -3977,7 +3982,7 @@ export function apply(ctx, config = {}) {
3977
3982
  if (!rechecks.some((row) => row.id === id)) rechecks.push({ ...reason, id, status: 'pending', scope_spec: data.scope_spec ?? null, at: Date.now() })
3978
3983
  }
3979
3984
  data.rechecks = rechecks
3980
- writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
3985
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(data, null, 2)}\n`)
3981
3986
  fact.rechecks = rechecks
3982
3987
  return true
3983
3988
  } catch (error) { ctx.logger?.warn?.(`clearai: recheck persistence failed: ${error.message}`); return false }
@@ -4024,7 +4029,7 @@ export function apply(ctx, config = {}) {
4024
4029
  const deviations = compareOutputs(reference, outputs ?? {}, spec.tolerance)
4025
4030
  if (deviations.length) reasons.push({ kind: 'output_deviation', model: modelId, ...snapshot, evidence: resultFile, reference, outputs, deviations })
4026
4031
  if (status === 'rerun') {
4027
- try { writeTextFile(join(cwd, resultFile), `${JSON.stringify({ id: modelId, ...appendRun(record, { at: Date.now(), inputs: stamp, method, outputs, deviations }) }, null, 2)}\n`) }
4032
+ try { writeAuthorityFile(sessionId, join(cwd, resultFile), `${JSON.stringify({ id: modelId, ...appendRun(record, { at: Date.now(), inputs: stamp, method, outputs, deviations }) }, null, 2)}\n`) }
4028
4033
  catch { return incomplete('failed', 'observation persistence failed', snapshot) }
4029
4034
  }
4030
4035
  if (reasons.length && !persistRechecks(sessionId, fact, reasons)) return incomplete('failed', 'pending reasons could not be persisted', snapshot)
@@ -4050,7 +4055,7 @@ export function apply(ctx, config = {}) {
4050
4055
  if (reason.model && (!observed || !data.calculation?.reference || compareOutputs(data.calculation.reference, observed.outputs, spec.tolerance).length)) return reason
4051
4056
  return { ...reason, status: 'resolved', resolution: { by: 'independent', card_path: audit.cardPath, hypothesis: hypothesis.id, at: Date.now() } }
4052
4057
  })
4053
- writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4058
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(data, null, 2)}\n`)
4054
4059
  confirmLinkedNegatives(sessionId, data, hypothesis, state)
4055
4060
  } catch (error) { ctx.logger?.warn?.(`clearai: confirmation incomplete: ${error.message}`) }
4056
4061
  }
@@ -4083,7 +4088,7 @@ export function apply(ctx, config = {}) {
4083
4088
  const ref = relative(sessionCwd(sessionId), reason.card_path).split('\\').join('/')
4084
4089
  if (!item.evidence.some(row => row.ref === ref)) item.evidence.push({ ref })
4085
4090
  }
4086
- writeTextFile(file, `${JSON.stringify(item, null, 2)}\n`)
4091
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(item, null, 2)}\n`)
4087
4092
  }
4088
4093
  }
4089
4094
 
@@ -4143,7 +4148,7 @@ export function apply(ctx, config = {}) {
4143
4148
  record.resolution = existing.resolution
4144
4149
  record.evidence = existing.evidence
4145
4150
  }
4146
- writeTextFile(file, `${JSON.stringify(record, null, 2)}\n`)
4151
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(record, null, 2)}\n`)
4147
4152
  negativeWrites.set(file, body)
4148
4153
  written.push(item.id)
4149
4154
  } catch (error) {
@@ -4228,7 +4233,8 @@ export function apply(ctx, config = {}) {
4228
4233
  const { hostService, sessionId, state, mutations } = call
4229
4234
  const done = finish(hostService, sessionId, mutations)
4230
4235
  if (activePlanOf(state) !== null) return fail('active_plan_exists', tr('已经有一份活动计划。改它用 RevisePlan,收它用 ClosePlan。', 'There is already an active plan. Change it with RevisePlan; close it with ClosePlan.'))
4231
- const problem = validateSteps(args.steps)
4236
+ try { args = { ...args, steps: args.steps?.map(step => ({ ...step, artifacts: (step.artifacts ?? []).map(path => workspacePath(sessionCwd(sessionId), path).relative) })) } } catch (error) { return fail('invalid_material_path', String(error.message)) }
4237
+ const problem = validateSteps(args.steps)
4232
4238
  if (problem !== null) return fail('invalid_steps', problem)
4233
4239
  const resolvedTests = new Map()
4234
4240
  for (const step of args.steps) {
@@ -4300,7 +4306,8 @@ export function apply(ctx, config = {}) {
4300
4306
  if (args.action === 'add') {
4301
4307
  if (args.step === undefined || args.step === null) return fail('step_required', tr('action="add" 要给 `step`(id / do / done_criteria,可选 artifacts 与 tests)。', 'action="add" needs `step` (id / do / done_criteria, optional artifacts and tests).'))
4302
4308
  if (plan.steps.length >= MAX_PLAN_STEPS) return fail('plan_too_long', tr(`计划已有 ${plan.steps.length} 步,上限 ${MAX_PLAN_STEPS}。`, `The plan already has ${plan.steps.length} steps; the limit is ${MAX_PLAN_STEPS}.`))
4303
- const problem = validateSteps([args.step], plan.steps)
4309
+ try { args = { ...args, step: { ...args.step, artifacts: (args.step.artifacts ?? []).map(path => workspacePath(sessionCwd(sessionId), path).relative) } } } catch (error) { return fail('invalid_material_path', String(error.message)) }
4310
+ const problem = validateSteps([args.step], plan.steps)
4304
4311
  if (problem !== null) return fail('invalid_step', problem)
4305
4312
  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}`))
4306
4313
  const resolved = resolveTests(state.hypotheses, args.step.tests)
@@ -4383,7 +4390,7 @@ export function apply(ctx, config = {}) {
4383
4390
  lines.push(`- [${step.status}] ${step.ordinal}. ${step.do} → ${step.artifacts.join(', ') || tr('(未声明)', '(none declared)')}${step.voidReason === null ? '' : tr(` (作废:${step.voidReason})`, ` (voided: ${step.voidReason})`)}`)
4384
4391
  }
4385
4392
  try {
4386
- writeTextFile(file, `${lines.join('\n')}\n`)
4393
+ writeAuthorityFile(sessionId, file, `${lines.join('\n')}\n`)
4387
4394
  } catch (error) {
4388
4395
  ctx.logger?.warn?.(`clearai kernel: 阶段归档失败 ${String(error?.message ?? error)}`)
4389
4396
  }
@@ -4903,6 +4910,7 @@ export function apply(ctx, config = {}) {
4903
4910
  */
4904
4911
  function findFact(sessionId, state, id) {
4905
4912
  const key = String(id ?? '').trim()
4913
+ if (checkIntegrity(sessionId).some(item => item.path === `clear/knowledge/facts/${key}.json`)) return null
4906
4914
  if (!/^[A-Za-z0-9_-]+$/.test(key)) return null
4907
4915
  const own = (state.facts ?? []).find((fact) => fact.id === key)
4908
4916
  if (own !== undefined) {
@@ -4920,7 +4928,7 @@ export function apply(ctx, config = {}) {
4920
4928
  }
4921
4929
 
4922
4930
  /** 事实文件上记一条疑问(引用它的判断被推翻):事实回到待核验,人复核后解除。 */
4923
- function markFactQuestioned(cwd, fact, challenge) {
4931
+ function markFactQuestioned(sessionId, cwd, fact, challenge) {
4924
4932
  if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4925
4933
  const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4926
4934
  try {
@@ -4929,7 +4937,7 @@ export function apply(ctx, config = {}) {
4929
4937
  const at = Date.now()
4930
4938
  data.challenges = [...(Array.isArray(data.challenges) ? data.challenges : []), { hypothesis: challenge.hypothesis ?? null, verdict: challenge.verdict ?? null, basis: challenge.basis ?? null, at }]
4931
4939
  data.history = [...(Array.isArray(data.history) ? data.history : []), { event: 'questioned', at, reason: challenge.basis ?? null }]
4932
- writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4940
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(data, null, 2)}\n`)
4933
4941
  return file
4934
4942
  } catch (error) {
4935
4943
  ctx.logger?.warn?.(`clearai kernel: 事实疑问记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -4938,7 +4946,7 @@ export function apply(ctx, config = {}) {
4938
4946
  }
4939
4947
 
4940
4948
  /** 事实文件上记一处边界(在哪里不成立),事实本身保持成立。 */
4941
- function markFactBounded(cwd, fact, bound) {
4949
+ function markFactBounded(sessionId, cwd, fact, bound) {
4942
4950
  if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4943
4951
  const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4944
4952
  try {
@@ -4947,7 +4955,7 @@ export function apply(ctx, config = {}) {
4947
4955
  const at = Date.now()
4948
4956
  data.boundaries = [...(Array.isArray(data.boundaries) ? data.boundaries : []), { verdict: bound.verdict, reasons: bound.reasons, basis: bound.basis ?? null, at }]
4949
4957
  data.history = [...(Array.isArray(data.history) ? data.history : []), { event: bound.verdict, at, reason: bound.basis ?? null }]
4950
- writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4958
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(data, null, 2)}\n`)
4951
4959
  return file
4952
4960
  } catch (error) {
4953
4961
  ctx.logger?.warn?.(`clearai kernel: 事实边界记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -4955,7 +4963,7 @@ export function apply(ctx, config = {}) {
4955
4963
  }
4956
4964
  }
4957
4965
 
4958
- function markFactReviewed(cwd, fact, review) {
4966
+ function markFactReviewed(sessionId, cwd, fact, review) {
4959
4967
  if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
4960
4968
  const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
4961
4969
  try {
@@ -4968,7 +4976,7 @@ export function apply(ctx, config = {}) {
4968
4976
  data.review = { decision, reason, at, by: 'user' }
4969
4977
  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)
4970
4978
  data.history = [...(Array.isArray(data.history) ? data.history : []), { event: decision, at, reason }]
4971
- writeTextFile(file, `${JSON.stringify(data, null, 2)}\n`)
4979
+ writeAuthorityFile(sessionId, file, `${JSON.stringify(data, null, 2)}\n`)
4972
4980
  return file
4973
4981
  } catch (error) {
4974
4982
  ctx.logger?.warn?.(`clearai kernel: 事实复核记录落盘失败 ${String(error?.message ?? error).slice(0, 160)}`)
@@ -5201,6 +5209,7 @@ export function apply(ctx, config = {}) {
5201
5209
 
5202
5210
  ctx.on('tools/pre-execute', (exec, next) => (exec.agent === undefined ? next() : inLanguage(languageOf(String(exec.agent.id)), () => guardTool(exec, next))))
5203
5211
  async function guardTool(exec, next) {
5212
+ if (TOOL_CATALOG.has(exec.name) && typeof exec.arguments === 'string') return { kind: 'deny', reason: 'Invalid tool arguments: submit one valid JSON object. No action was executed; correct the JSON and resubmit the tool call.' }
5204
5213
  {
5205
5214
  const sessionId = String(exec.agent.id)
5206
5215
  const hostService = host()