clearai-dsh 0.4.0 → 0.5.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 +68 -0
- package/README.md +38 -13
- package/README.zh-CN.md +38 -13
- package/bin/clearai.mjs +29 -231
- package/cordis.patch.yml +3 -3
- package/lib/client.js +575 -205
- package/lib/domain-language.js +71 -9
- package/lib/fold.js +271 -15
- package/lib/knowledge-view.js +135 -42
- package/package.json +2 -2
- package/presets/clearai/agent.cordis.yml +11 -3
- package/presets/clearai/clearai.patch.yml +11 -3
- package/presets/clearai/plugins/clearai-kernel.js +910 -77
- package/presets/clearai/plugins/ontology.js +21 -7
- package/presets/clearai/plugins/prompts.js +26 -22
- package/presets/clearai/skills/clearai-loop/SKILL.md +12 -4
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* P5 什么都不删 → 状态是可重放的投影;refine/void/superseded 的旧值都在
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
23
|
+
import { tmpdir } from 'node:os'
|
|
23
24
|
|
|
24
25
|
import { createHash } from 'node:crypto'
|
|
25
26
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
@@ -83,6 +84,15 @@ const canonicalVerdict = (value) => {
|
|
|
83
84
|
}
|
|
84
85
|
/** 自判等级上限:L0–L2 可自判,L3 以上拒绝。 */
|
|
85
86
|
const SELF_JUDGE_MAX_INDEX = 2
|
|
87
|
+
/**
|
|
88
|
+
* **给模型选的只有三档**:L2 自判、L3 独立评估、L4 人放行。L0 / L1 / L2 的细分从没改变过谁来判
|
|
89
|
+
* (模型一律自标 L1/L2),所以合并成「自判」:旧账照旧读(界面一律说「自判」),新写的 L0 / L1 当 L2 收。
|
|
90
|
+
*/
|
|
91
|
+
const MODEL_LEVELS = ['L2', 'L3', 'L4']
|
|
92
|
+
const normalizeLevel = (level) => {
|
|
93
|
+
const index = levelIndexOf(level)
|
|
94
|
+
return index < 0 ? level : index <= SELF_JUDGE_MAX_INDEX ? 'L2' : LEVELS[index]
|
|
95
|
+
}
|
|
86
96
|
/** `MAX_PLAN_STEPS`。 */
|
|
87
97
|
const MAX_PLAN_STEPS = 25
|
|
88
98
|
/**
|
|
@@ -202,10 +212,13 @@ export const CONFIG_KEYS = [
|
|
|
202
212
|
'minHypotheses',
|
|
203
213
|
'requireCriteriaVerdict',
|
|
204
214
|
'requireLandedEntities',
|
|
215
|
+
'requireMeasures',
|
|
216
|
+
'requireAnswers',
|
|
205
217
|
'bashDenyRules',
|
|
206
218
|
'auditProvider',
|
|
207
219
|
'auditTimeoutMs',
|
|
208
220
|
'auditToolFilter',
|
|
221
|
+
'auditRerun',
|
|
209
222
|
'runtimeCard',
|
|
210
223
|
'contributions',
|
|
211
224
|
]
|
|
@@ -216,7 +229,7 @@ export const CONFIG_KEYS = [
|
|
|
216
229
|
*/
|
|
217
230
|
export const MECHANISM_TOOLS = {
|
|
218
231
|
goal: ['Frame', 'Conclude'],
|
|
219
|
-
plan: ['CreatePlan', 'AdvancePlan', 'RevisePlan', 'ClosePlan'],
|
|
232
|
+
plan: ['CreatePlan', 'AdvancePlan', 'RevisePlan', 'ClosePlan', 'Anomaly'],
|
|
220
233
|
/**
|
|
221
234
|
* 领域本体没有工具:模型用原生文件工具直接写 `clear/ontology/{concepts,relations,entities}/**.json`,
|
|
222
235
|
* 写入时由 `tools/pre-execute` 查单个文件,读取时折法从文件折出图(见 `syncWorkspace`)。
|
|
@@ -327,6 +340,18 @@ export function apply(ctx, config = {}) {
|
|
|
327
340
|
* 出口两条:给主体写实体文件(`clear/ontology/entities/<id>.json`),或把断言从判断上拿掉 / 如实 abandoned。
|
|
328
341
|
*/
|
|
329
342
|
requireLandedEntities: config.requireLandedEntities === true,
|
|
343
|
+
/**
|
|
344
|
+
* **测量门**(立题;机制缺省关,preset 里开):首次立题时,本体里至少有一个度量,而且每个度量都有一条
|
|
345
|
+
* 「测量」关系写明由什么测量、读数如何核对(`check`)。真跑里唯一一条错误事实,正是把设定值回读
|
|
346
|
+
* 当成了釜温;卡上提醒了几十次「先写本体」也没有用。
|
|
347
|
+
*/
|
|
348
|
+
requireMeasures: config.requireMeasures === true,
|
|
349
|
+
/**
|
|
350
|
+
* **结论门**(结案;机制缺省关,preset 里开):`achieved` 要按问题给出结论四部分,而且每个还在考察、
|
|
351
|
+
* 从没得到支持的候选与每条开着的未解释项,都写进「尚未确定的事项」并说明它若成立答案会怎样变。
|
|
352
|
+
* 只查写没写,不判写得对不对(对不对由结案评估者核)。
|
|
353
|
+
*/
|
|
354
|
+
requireAnswers: config.requireAnswers === true,
|
|
330
355
|
bashDenyRules: config.bashDenyRules !== false,
|
|
331
356
|
auditProvider: config.auditProvider ?? 'spawn',
|
|
332
357
|
auditTimeoutMs: config.auditTimeoutMs ?? 240000,
|
|
@@ -334,6 +359,7 @@ export function apply(ctx, config = {}) {
|
|
|
334
359
|
// (见 resolveToolFace):`read_image` 只在挂了 `attachments` 的部署里存在,名单里写了它、
|
|
335
360
|
// 部署里没有,`tools.restrict` 会**直接抛**(未知工具名)→ 评估整条路 fail-closed。
|
|
336
361
|
auditToolFilter: config.auditToolFilter ?? ['read', 'glob', 'grep', 'read_image'],
|
|
362
|
+
auditRerun: config.auditRerun === true,
|
|
337
363
|
runtimeCard: config.runtimeCard !== false,
|
|
338
364
|
/** 贡献表。缺省 = 全开;要裁剪就从这里裁,而不是去改装配代码。 */
|
|
339
365
|
contributions: config.contributions ?? {},
|
|
@@ -383,6 +409,32 @@ export function apply(ctx, config = {}) {
|
|
|
383
409
|
return list
|
|
384
410
|
}
|
|
385
411
|
|
|
412
|
+
/**
|
|
413
|
+
* **未解释项**(认识论里的「反常」):和预期或本体对不上的观测。登记走独立落账通道——
|
|
414
|
+
* 它是观测那一刻的发现,后面的交付失败、工具被 abort 都不该把它丢掉。
|
|
415
|
+
*/
|
|
416
|
+
function openAnomalies(sessionId, items, { step = null, by = 'model' } = {}) {
|
|
417
|
+
const opened = []
|
|
418
|
+
for (const item of Array.isArray(items) ? items : []) {
|
|
419
|
+
const what = String(item?.what ?? '').trim()
|
|
420
|
+
if (what === '') continue
|
|
421
|
+
const anchor = String(item?.anchor ?? '').trim()
|
|
422
|
+
/** 涉及哪些量、候选假设或已升格的事实(id):点名事实的,那条事实回到「待核验」;结案时据此清点。 */
|
|
423
|
+
const touches = (Array.isArray(item?.touches) ? item.touches : []).map((ref) => String(ref ?? '').trim().slice(0, 80)).filter((ref) => ref !== '').slice(0, 12)
|
|
424
|
+
opened.push(landFact(sessionId, { t: 'anomaly/opened', id: `u-${Math.random().toString(36).slice(2, 8)}`, what: what.slice(0, 400), ...(anchor === '' ? {} : { anchor: anchor.slice(0, 80) }), ...(touches.length === 0 ? {} : { touches }), step, by }))
|
|
425
|
+
}
|
|
426
|
+
return opened
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 交付成立之后的那一句:这一步写过预期就提醒拿结果去对;登记了未解释就说它们挂在哪。 */
|
|
430
|
+
function expectationNote(step, opened, found = []) {
|
|
431
|
+
const lines = []
|
|
432
|
+
if (found.length > 0) lines.push(tr(`评估者看到 ${found.length} 处没登记的异常,已记成未解释项挂在卡上:${found.map((item) => clip(item.what, 80)).join(';')}。先弄清它们,再往下走。`, `The evaluator saw ${found.length} anomaly(ies) you did not record; they are now unexplained items on the card: ${found.map((item) => clip(item.what, 80)).join('; ')}. Sort them out before moving on.`))
|
|
433
|
+
if (opened.length > 0) lines.push(tr(`登记了 ${opened.length} 条未解释(${opened.map((item) => item.id).join('、')}):它们挂在卡上,直到被解释、写明理由排除、或交给人(Anomaly)。`, `${opened.length} unexplained item(s) recorded (${opened.map((item) => item.id).join(', ')}): they stay on the card until explained, ruled out with a reason, or handed to a person (Anomaly).`))
|
|
434
|
+
else if (typeof step?.expect === 'string' && step.expect !== '') lines.push(tr(`这一步的预测是「${clip(step.expect, 80)}」。结果与预测不符时,用 Anomaly 登记,不要强行解释。`, `This step expected "${clip(step.expect, 80)}". If the result does not match, record it with Anomaly; do not explain it away.`))
|
|
435
|
+
return lines.length === 0 ? '' : `\n${lines.join('\n')}`
|
|
436
|
+
}
|
|
437
|
+
|
|
386
438
|
function hasState(state) {
|
|
387
439
|
return state.goal !== null || state.plans.length > 0 || state.evidence.length > 0 || state.materials.length > 0
|
|
388
440
|
}
|
|
@@ -445,6 +497,8 @@ export function apply(ctx, config = {}) {
|
|
|
445
497
|
* 而当时只认 id,错误信息又不列出有效 id——它于是逐字猜哪里差了一个标点,白烧了三轮上下文。
|
|
446
498
|
* 「机制把模型逼进猜谜」是机制的问题,不是模型的问题。
|
|
447
499
|
*/
|
|
500
|
+
|
|
501
|
+
|
|
448
502
|
function matchHypothesis(hypotheses, wanted) {
|
|
449
503
|
const raw = String(wanted ?? '').trim()
|
|
450
504
|
if (raw === '') return null
|
|
@@ -479,7 +533,33 @@ export function apply(ctx, config = {}) {
|
|
|
479
533
|
if (found === null) return { ok: false, wanted: String(raw) }
|
|
480
534
|
if (!ids.includes(found.id)) ids.push(found.id)
|
|
481
535
|
}
|
|
482
|
-
return { ok: true, tests: { hypotheses: ids, level: tests.level } }
|
|
536
|
+
return { ok: true, tests: { hypotheses: ids, level: normalizeLevel(tests.level) } }
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 步骤的 `serves` 与按候选写的 `predictions`:判断名换成 id,问题 id 要真有。
|
|
541
|
+
* 返回 `{ ok, extra }`(extra 直接并进步骤),或 `{ ok: false, code, message }`。
|
|
542
|
+
*/
|
|
543
|
+
function resolveStepExtras(state, step) {
|
|
544
|
+
const extra = {}
|
|
545
|
+
const serves = String(step?.serves ?? '').trim()
|
|
546
|
+
if (serves !== '') {
|
|
547
|
+
const homes = [...(state.goal?.questions ?? []), ...(state.goal?.areas ?? [])].map((item) => item.id)
|
|
548
|
+
if (!homes.includes(serves)) return { ok: false, code: 'question_unknown', message: tr(`步骤 ${step.id} 的 serves「${serves}」不是当前目标里的问题或板块。可选:${homes.join('、') || '(目标还没有列问题:不写 serves 即归整个目标)'}`, `Step ${step.id} serves "${serves}", which is not a question or area of the current goal. Options: ${homes.join(', ') || '(the goal lists no questions: omit serves to attach to the whole goal)'}`) }
|
|
549
|
+
extra.serves = serves
|
|
550
|
+
}
|
|
551
|
+
if (Array.isArray(step?.predictions) && step.predictions.length > 0) {
|
|
552
|
+
const predictions = []
|
|
553
|
+
for (const item of step.predictions) {
|
|
554
|
+
const expect = String(item?.expect ?? '').trim()
|
|
555
|
+
if (expect === '') continue
|
|
556
|
+
const found = matchHypothesis(state.hypotheses, item?.hypothesis)
|
|
557
|
+
if (found === null) return { ok: false, code: 'unknown_hypothesis', message: tr(`步骤 ${step.id} 的预测指向的判断「${String(item?.hypothesis ?? '')}」对不上任何一条已登记的判断。`, `A prediction of step ${step.id} names the judgment "${String(item?.hypothesis ?? '')}", which matches no registered judgment. `) + hypothesisMenu(state.hypotheses) }
|
|
558
|
+
predictions.push({ hypothesis: found.id, expect: expect.slice(0, 300) })
|
|
559
|
+
}
|
|
560
|
+
if (predictions.length > 0) extra.predictions = predictions
|
|
561
|
+
}
|
|
562
|
+
return { ok: true, extra }
|
|
483
563
|
}
|
|
484
564
|
|
|
485
565
|
/** 一个已登记步骤检验的判断 id(兼容旧账本的单条写法)。 */
|
|
@@ -734,7 +814,7 @@ export function apply(ctx, config = {}) {
|
|
|
734
814
|
'你是独立评估者:拿着判定标准与产物,做冷静、可复核的评估,产出一张结构化评估卡。你没有参与探索,不背任何方案的立场——这正是你可信的原因。',
|
|
735
815
|
'',
|
|
736
816
|
'**三层信道(按幻觉风险):**',
|
|
737
|
-
'1. 硬信号(零幻觉,最可信)
|
|
817
|
+
'1. 硬信号(零幻觉,最可信):产物自带的客观数字、文件是否存在及字段是否齐、以及执行记录。直接读取已落盘的产物,照抄进评估卡;任务书给了工作区副本时,可以在副本里复跑产物自带的脚本,复跑读数同样是硬信号。不要在原工作区写文件或执行命令,不要润色或估计。',
|
|
738
818
|
'2. 领域信号(逐条核对):逐条对照判据给结论(通过/不通过/不适用 + 一句证据),不发挥、不新增标准。',
|
|
739
819
|
'3. 软判断(有幻觉风险,须隔离标注):报告完整性、方案合理性这类主观项可以给,但必须显式标注「主观评估」。',
|
|
740
820
|
'',
|
|
@@ -745,6 +825,7 @@ export function apply(ctx, config = {}) {
|
|
|
745
825
|
' · **交付成立吗**(`holds`):yes = 判据逐条满足、观测真实;no = 有判据不满足,或观测与记录对不上;unclear = 凭现有材料判不了。',
|
|
746
826
|
' · **每条判断的结果**(`results`,这一步检验几条就给几格):对照它的推翻条件读——support = 没碰到推翻条件,refute = 碰到了,inconclusive = 这次观测区分不了。',
|
|
747
827
|
'- 交付成立与判断被推翻可以同时为真:推翻是有价值的结果,它不让交付失败。不要为了让步骤通过而写 support。',
|
|
828
|
+
'- 你还要查**还有什么没解释**(`anomalies`):原始数据里有没有做的人没登记的异常——参考读数对不上、重复点漂移、不同装置或不同批次之间的差、和常识或本体不符的量级?数字复跑对得上不等于数据可信。每条做的人已排除的未解释项,理由站不站得住?站不住的也写进来。没有就给空数组。',
|
|
748
829
|
'',
|
|
749
830
|
'**回包的形状就是你的动作空间(字段长度由 schema 校验,超了会被拒):**',
|
|
750
831
|
'- `basis` 是**一句话结论**,≤1200 字。**不要在这里写论证**——论证放 `refs`:逐条 `{path, line}` 指到你实际读过的文件与行,让第三方照着就能复核。',
|
|
@@ -756,7 +837,7 @@ export function apply(ctx, config = {}) {
|
|
|
756
837
|
'You are an independent evaluator: with the criteria and the outputs in hand, make a calm, checkable evaluation and produce a structured evaluation card. You took no part in the work and hold no stake in any approach; that is why you can be trusted.',
|
|
757
838
|
'',
|
|
758
839
|
'**Three channels (by hallucination risk):**',
|
|
759
|
-
'1. Hard signals (no hallucination, most trusted): objective numbers in the outputs, whether files exist and have their fields, and the execution record. Read the outputs on disk and copy them into the card;
|
|
840
|
+
'1. Hard signals (no hallucination, most trusted): objective numbers in the outputs, whether files exist and have their fields, and the execution record. Read the outputs on disk and copy them into the card; when the brief gives a copy of the workspace, you may re-run the outputs\' own scripts there, and re-run readings are hard signals too. Do not write files or run commands in the original workspace, and do not polish or estimate.',
|
|
760
841
|
'2. Domain signals (check one by one): give a finding per criterion (pass / fail / not applicable + one line of evidence); do not improvise or add criteria.',
|
|
761
842
|
'3. Soft judgments (hallucination risk, keep them separate): subjective items such as report completeness or soundness may be given, but must be labelled "subjective".',
|
|
762
843
|
'',
|
|
@@ -767,6 +848,7 @@ export function apply(ctx, config = {}) {
|
|
|
767
848
|
' · **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.',
|
|
768
849
|
' · **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.',
|
|
769
850
|
'- 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.',
|
|
770
852
|
'',
|
|
771
853
|
'**The shape of your reply is your action space (field lengths are checked by the schema; overruns are rejected):**',
|
|
772
854
|
'- `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.',
|
|
@@ -817,6 +899,33 @@ export function apply(ctx, config = {}) {
|
|
|
817
899
|
additionalProperties: false,
|
|
818
900
|
},
|
|
819
901
|
},
|
|
902
|
+
anomalies: {
|
|
903
|
+
type: 'array',
|
|
904
|
+
description: tr('还没解释的异常:做的人没登记的,或排除理由站不住的。每条一句,带 path:line。没有就给空数组。', 'Anomalies still unexplained: ones the worker did not record, or whose ruling-out does not hold. One sentence each, with path:line. Empty array if none.'),
|
|
905
|
+
items: {
|
|
906
|
+
type: 'object',
|
|
907
|
+
properties: {
|
|
908
|
+
what: { type: 'string', maxLength: 400, description: tr('哪里不符(带 path:line)', 'what does not fit (with path:line)') },
|
|
909
|
+
matters: { type: 'string', enum: ['yes', 'no', 'unclear'], description: tr('它会不会动摇这次的结论', 'whether it could shake this conclusion') },
|
|
910
|
+
},
|
|
911
|
+
required: ['what'],
|
|
912
|
+
additionalProperties: false,
|
|
913
|
+
},
|
|
914
|
+
},
|
|
915
|
+
lessons: {
|
|
916
|
+
type: 'array',
|
|
917
|
+
description: tr('任务书列了待核的经验(L1、L2……)时,每条各一格;没列就给空数组。', 'When the brief lists lessons to check (L1, L2, ...), one entry each; otherwise an empty array.'),
|
|
918
|
+
items: {
|
|
919
|
+
type: 'object',
|
|
920
|
+
properties: {
|
|
921
|
+
lesson: { type: 'string', maxLength: 20, description: tr('经验编号,如 L1', 'the lesson number, e.g. L1') },
|
|
922
|
+
verdict: { type: 'string', enum: ['support', 'refute', 'inconclusive'] },
|
|
923
|
+
basis: { type: 'string', maxLength: 400, description: tr('一句话:记录里哪处支持或推翻它', 'One sentence: where in the record it is supported or refuted') },
|
|
924
|
+
},
|
|
925
|
+
required: ['lesson', 'verdict'],
|
|
926
|
+
additionalProperties: false,
|
|
927
|
+
},
|
|
928
|
+
},
|
|
820
929
|
refs: {
|
|
821
930
|
type: 'array',
|
|
822
931
|
description: tr('逐条证据引用:文件与行号。裁决要能被第三方照着复核。', 'Evidence references, one per file and line, so a third party can check the verdict.'),
|
|
@@ -844,7 +953,23 @@ export function apply(ctx, config = {}) {
|
|
|
844
953
|
additionalProperties: false,
|
|
845
954
|
})
|
|
846
955
|
|
|
847
|
-
|
|
956
|
+
/**
|
|
957
|
+
* 评估者要看的未解释项:还开着的、做的人排除了的(核它的理由)、交给人的,以及这次交付刚登记的。
|
|
958
|
+
* 这是评估者从「报告和数据一致吗」扩到「还有什么没解释」的那份材料。
|
|
959
|
+
*/
|
|
960
|
+
function anomalyBrief(state, gate) {
|
|
961
|
+
const known = [...(state?.anomalies ?? [])]
|
|
962
|
+
for (const item of Array.isArray(gate?.anomalies) ? gate.anomalies : []) if (!known.some((entry) => entry.id === item.id)) known.push({ ...item, status: 'open' })
|
|
963
|
+
if (known.length === 0) return ['', tr('# 未解释项\n- (做的人没登记任何未解释项:原始数据里有没有它漏掉的,由你查)', '# Unexplained items\n- (the worker recorded none: whether the raw data holds any it missed is for you to check)')]
|
|
964
|
+
const word = { open: tr('开着', 'open'), explained: tr('已解释', 'explained'), ruled_out: tr('已排除', 'ruled out'), escalated: tr('交给人', 'handed to a person') }
|
|
965
|
+
return [
|
|
966
|
+
'',
|
|
967
|
+
tr('# 未解释项(做的人登记的;已排除的要核理由站不站得住)', '# Unexplained items (recorded by the worker; for ruled-out ones, check whether the reason holds)'),
|
|
968
|
+
...known.map((item) => `- ${item.id} · ${word[item.status] ?? item.status} · ${item.what}${item.reason ? tr(` —— 理由:${item.reason}`, ` — reason: ${item.reason}`) : ''}`),
|
|
969
|
+
]
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
function evaluatorPrompt(state, step, gate, sessionId, rerunDir = null) {
|
|
848
973
|
const goal = state.goal
|
|
849
974
|
const tested = testedBy(step)
|
|
850
975
|
.map((id) => state.hypotheses.find((item) => item.id === id))
|
|
@@ -884,6 +1009,7 @@ export function apply(ctx, config = {}) {
|
|
|
884
1009
|
...(gate.confirmed.length === 0 ? ['- (none)'] : gate.confirmed.map((item) => `- ${item.ref} — ${item.bytes} bytes — ${item.digest ?? 'digest unavailable'}`)),
|
|
885
1010
|
],
|
|
886
1011
|
),
|
|
1012
|
+
...anomalyBrief(state, gate),
|
|
887
1013
|
...(Array.isArray(gate.extra) && gate.extra.length > 0 ? ['', ...gate.extra] : []),
|
|
888
1014
|
'',
|
|
889
1015
|
...tr(
|
|
@@ -892,14 +1018,18 @@ export function apply(ctx, config = {}) {
|
|
|
892
1018
|
'',
|
|
893
1019
|
'请只读上述坐标与执行记录,给出两项裁决:拿**已登记的判定标准**对照观测,判交付成立吗(`holds`);再拿每条判断的**推翻条件**对照观测,读出它的结果(`results`)。',
|
|
894
1020
|
'准入只核验了「坐标存在且非空」——齐备不等于这一步做完了;判据里的断言(数值、口径、一致性)必须由你逐条核对。',
|
|
895
|
-
|
|
1021
|
+
rerunDir === null
|
|
1022
|
+
? '你不得修改任何文件,不得执行写入命令,不得重做方案。'
|
|
1023
|
+
: `原工作区只读:不要在里面写文件或运行命令。要核对数字就复跑:工作区副本在 ${rerunDir}(不含 clear/),cd 进去运行产物自带的脚本,对照它打印的结果。复跑的读数是硬信号;不要重做方案。`,
|
|
896
1024
|
],
|
|
897
1025
|
[
|
|
898
1026
|
`Working directory: ${sessionCwdLabel(sessionId)}`,
|
|
899
1027
|
'',
|
|
900
1028
|
'Read only the outputs above and the execution record, and give two verdicts: check the observations against the **registered criteria** to decide whether the delivery holds (`holds`); then read each judgment against its **refutation condition** to give its result (`results`).',
|
|
901
1029
|
'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.',
|
|
902
|
-
|
|
1030
|
+
rerunDir === null
|
|
1031
|
+
? 'You may not modify any file, run write commands or redo the work.'
|
|
1032
|
+
: `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.`,
|
|
903
1033
|
],
|
|
904
1034
|
),
|
|
905
1035
|
].join('\n')
|
|
@@ -952,10 +1082,27 @@ export function apply(ctx, config = {}) {
|
|
|
952
1082
|
const line = Number.isInteger(item.line) ? item.line : null
|
|
953
1083
|
refs.push({ path: path.slice(0, 300), line })
|
|
954
1084
|
}
|
|
1085
|
+
const anomalies = []
|
|
1086
|
+
for (const item of Array.isArray(value?.anomalies) ? value.anomalies : []) {
|
|
1087
|
+
const what = typeof item === 'string' ? item.trim() : String(item?.what ?? '').trim()
|
|
1088
|
+
if (what === '') continue
|
|
1089
|
+
const matters = ['yes', 'no', 'unclear'].includes(item?.matters) ? item.matters : 'unclear'
|
|
1090
|
+
anomalies.push({ what: what.slice(0, 400), matters })
|
|
1091
|
+
}
|
|
1092
|
+
const lessons = []
|
|
1093
|
+
for (const item of Array.isArray(value?.lessons) ? value.lessons : []) {
|
|
1094
|
+
if (item === null || typeof item !== 'object') continue
|
|
1095
|
+
const lesson = String(item.lesson ?? '').trim().toUpperCase()
|
|
1096
|
+
const verdict = String(item.verdict ?? '').toLowerCase()
|
|
1097
|
+
if (!/^L\d+$/.test(lesson) || !['support', 'refute', 'inconclusive'].includes(verdict)) continue
|
|
1098
|
+
lessons.push({ lesson, verdict, basis: typeof item.basis === 'string' && item.basis.trim() !== '' ? item.basis.trim().slice(0, 400) : null })
|
|
1099
|
+
}
|
|
955
1100
|
const basis = typeof value?.basis === 'string' && value.basis.trim() !== '' ? value.basis.trim() : tr('评估者未给出依据', 'the evaluator gave no basis')
|
|
956
1101
|
return {
|
|
957
1102
|
holds,
|
|
958
1103
|
results,
|
|
1104
|
+
anomalies,
|
|
1105
|
+
lessons,
|
|
959
1106
|
// 截断是**兜底**:schema 已声明 maxLength,越界的产出本不该到这里;真到了也不能让账本吃下五千字。
|
|
960
1107
|
// 截断标记**算在预算内**:申报多少就必须是多少。
|
|
961
1108
|
basis: basis.length > 1200 ? tr(`${basis.slice(0, 1170)}…(裁到 1200 字;完整论证应由 refs 指认)`, `${basis.slice(0, 1170)}… (cut to 1200 characters; the full argument belongs in refs)`) : basis,
|
|
@@ -1208,7 +1355,7 @@ export function apply(ctx, config = {}) {
|
|
|
1208
1355
|
if (recovered !== null && recovered.ok === true) {
|
|
1209
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() }
|
|
1210
1357
|
const cardPath = writeAuditCard(sessionId, audit.step, card)
|
|
1211
|
-
mutations.push({ t: 'audit/settled', id: audit.id, step: audit.step, verdict: recovered.verdict.holds, holds: recovered.verdict.holds, results: recovered.verdict.results, basis: recovered.verdict.basis, shortfalls: recovered.verdict.shortfalls, card_path: cardPath, digest: audit.digest ?? null })
|
|
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 })
|
|
1212
1359
|
lines.push(tr(`${audit.step}:裁决从子会话日志取回(交付成立:${recovered.verdict.holds})`, `${audit.step}: verdict recovered from the child session log (holds: ${recovered.verdict.holds})`))
|
|
1213
1360
|
continue
|
|
1214
1361
|
}
|
|
@@ -1280,6 +1427,8 @@ export function apply(ctx, config = {}) {
|
|
|
1280
1427
|
[String(item?.id ?? ''), String(item?.status ?? ''), String(item?.claim ?? '').replace(/\s+/g, ' '), JSON.stringify(item?.assertions ?? null)].join(':'),
|
|
1281
1428
|
)
|
|
1282
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')}`)
|
|
1283
1432
|
const facts = (Array.isArray(state?.facts) ? state.facts : []).map((item) => `${String(item?.id ?? '')}:${String(item?.level ?? '')}:${JSON.stringify(item?.assertions ?? null)}`)
|
|
1284
1433
|
/**
|
|
1285
1434
|
* 步的**判据**与产物一起算材料:判据一变,"这一步算不算做完"就是另一个问题
|
|
@@ -1303,7 +1452,7 @@ export function apply(ctx, config = {}) {
|
|
|
1303
1452
|
return !ref.startsWith('evidence:') && !ref.startsWith('hypothesis:')
|
|
1304
1453
|
})
|
|
1305
1454
|
.map((item) => `${String(item?.ref ?? '')}:${String(item?.bytes ?? '')}:${String(item?.digest ?? '')}`)
|
|
1306
|
-
const root = createHash('sha256').update(JSON.stringify([kind, step.id, goal, steps, materials, hypotheses, facts, material, artifacts])).digest('hex')
|
|
1455
|
+
const root = createHash('sha256').update(JSON.stringify([kind, step.id, goal, steps, materials, hypotheses, facts, material, artifacts, ...(anomalies.length > 0 ? [anomalies] : [])])).digest('hex')
|
|
1307
1456
|
return root.slice(0, 16)
|
|
1308
1457
|
}
|
|
1309
1458
|
|
|
@@ -1399,16 +1548,18 @@ export function apply(ctx, config = {}) {
|
|
|
1399
1548
|
*/
|
|
1400
1549
|
const pendingId = `audit:pending:${kind}:${step.id}:${digest}`
|
|
1401
1550
|
landFact(sessionId, { t: 'audit/dispatched', id: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, digest, capability: null, evaluator_session: null, status: 'dispatching' })
|
|
1551
|
+
const rerunDir = CFG.auditRerun ? rerunCopy(sessionId, auditKey) : null
|
|
1402
1552
|
const dispatched = await dispatchSubRun({
|
|
1403
1553
|
label: `${kind === 'goal_audit' ? tr('目标评估者', 'Goal evaluator') : tr('评估者', 'Evaluator')} · ${step.id}`,
|
|
1404
1554
|
persona: evaluatorDiscipline(),
|
|
1405
|
-
prompt: evaluatorPrompt(stateOf(sessionId), step, gate, sessionId),
|
|
1555
|
+
prompt: evaluatorPrompt(stateOf(sessionId), step, gate, sessionId, rerunDir),
|
|
1406
1556
|
outputSchema: verdictSchema(),
|
|
1407
|
-
toolFilter: { allow: resolveToolFace(agent, CFG.auditToolFilter) },
|
|
1557
|
+
toolFilter: { allow: resolveToolFace(agent, rerunDir === null ? CFG.auditToolFilter : [...CFG.auditToolFilter, 'bash']) },
|
|
1408
1558
|
parent: agent,
|
|
1409
1559
|
signal,
|
|
1410
1560
|
})
|
|
1411
1561
|
if (dispatched.ok !== true) {
|
|
1562
|
+
dropRerunCopy(rerunDir)
|
|
1412
1563
|
/**
|
|
1413
1564
|
* 派不出去:把那条"正在派"如实结掉。结算与派发**同 id**,且上面那条 pending
|
|
1414
1565
|
* 走的是独立落账通道、在 `withPendingFacts` 的合并结果里排在前面,所以折法先建记录、
|
|
@@ -1418,7 +1569,7 @@ export function apply(ctx, config = {}) {
|
|
|
1418
1569
|
return { holds: 'unknown', results: [], basis: tr(`独立评估者无法派遣(${dispatched.reason})`, `The independent evaluator could not be dispatched (${dispatched.reason})`), shortfalls: ['audit_dispatch_failed'], cardPath: null, mutations }
|
|
1419
1570
|
}
|
|
1420
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' })
|
|
1421
|
-
entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, settled: undefined }
|
|
1572
|
+
entry = { sessionId, run: dispatched.run, capability: dispatched.capability, auditKey: pendingId, step: step.id, plan: plan?.id ?? 'goal', kind, rerunDir, settled: undefined }
|
|
1422
1573
|
pendingAudits.set(key, entry)
|
|
1423
1574
|
entry.settled = dispatched.run.result.then(
|
|
1424
1575
|
(value) => ({ ok: true, value }),
|
|
@@ -1438,6 +1589,7 @@ export function apply(ctx, config = {}) {
|
|
|
1438
1589
|
}
|
|
1439
1590
|
// 已落定:这次派遣的生命周期到此为止。下一次交付是**新的一次评估**(新证据),必须重新派遣。
|
|
1440
1591
|
pendingAudits.delete(key)
|
|
1592
|
+
dropRerunCopy(entry.rerunDir ?? null)
|
|
1441
1593
|
if (outcome.ok !== true) {
|
|
1442
1594
|
return settleUnknown(tr(`评估者失败:${String(outcome.error?.message ?? outcome.error)}`, `The evaluator failed: ${String(outcome.error?.message ?? outcome.error)}`), ['audit_failed'])
|
|
1443
1595
|
}
|
|
@@ -1464,15 +1616,46 @@ export function apply(ctx, config = {}) {
|
|
|
1464
1616
|
} catch {
|
|
1465
1617
|
/* dispose 失败不影响裁决事实 */
|
|
1466
1618
|
}
|
|
1467
|
-
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, shortfalls: verdict.shortfalls, card: verdict.basis, created_at: Date.now() }
|
|
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() }
|
|
1468
1620
|
const cardPath = writeAuditCard(sessionId, step.id, card)
|
|
1469
1621
|
if (cardPath === null) {
|
|
1470
1622
|
return settleUnknown(tr('评估卡落盘失败:裁决降级', 'Could not save the evaluation card: verdict downgraded'), ['card_persist_failed'])
|
|
1471
1623
|
}
|
|
1472
|
-
mutations.push({ t: 'audit/settled', id: entry.auditKey, step: step.id, verdict: verdict.holds, holds: verdict.holds, results: verdict.results, basis: verdict.basis, shortfalls: verdict.shortfalls, card_path: cardPath, digest })
|
|
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 })
|
|
1473
1625
|
return { ...verdict, cardPath, digest, mutations }
|
|
1474
1626
|
}
|
|
1475
1627
|
|
|
1628
|
+
/**
|
|
1629
|
+
* **复跑用的工作区副本**:评估者可以在这里跑脚本核数字,原工作区一个字节不碰。
|
|
1630
|
+
*
|
|
1631
|
+
* 为什么要它:L3 的定义是「新产生、可重跑」,而只能读文件的评估者从不重跑,只核对文件彼此是否一致——
|
|
1632
|
+
* 一份自洽但算错的结果照样过。副本不带 `clear/`(账本与评估卡不是复跑的材料)。复制失败就不给副本,
|
|
1633
|
+
* 评估照旧只读,不因此失败。
|
|
1634
|
+
*/
|
|
1635
|
+
function rerunCopy(sessionId, auditKey) {
|
|
1636
|
+
const cwd = sessionCwd(sessionId)
|
|
1637
|
+
if (cwd === null) return null
|
|
1638
|
+
const target = join(tmpdir(), `clearai-rerun-${auditKey}`)
|
|
1639
|
+
const skip = new Set([join(cwd, 'clear'), join(cwd, '.git'), join(cwd, 'node_modules')])
|
|
1640
|
+
try {
|
|
1641
|
+
cpSync(cwd, target, { recursive: true, filter: (source) => !skip.has(source) })
|
|
1642
|
+
return target
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
ctx.logger?.warn?.(`clearai kernel: 复跑副本没建成 ${String(error?.message ?? error).slice(0, 160)}`)
|
|
1645
|
+
dropRerunCopy(target)
|
|
1646
|
+
return null
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
function dropRerunCopy(dir) {
|
|
1651
|
+
if (dir === null) return
|
|
1652
|
+
try {
|
|
1653
|
+
rmSync(dir, { recursive: true, force: true })
|
|
1654
|
+
} catch {
|
|
1655
|
+
/* 删不掉留在临时目录里,不影响裁决 */
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1476
1659
|
/** 评估卡落盘(系统的面)。写不进 → 返回 null,调用方 fail-closed。 */
|
|
1477
1660
|
function writeAuditCard(sessionId, stepId, card) {
|
|
1478
1661
|
const file = sessionFile(sessionId, 'clear', 'evidence', 'audits', String(stepId), `${String(card.auditor_run_id)}.json`)
|
|
@@ -1725,15 +1908,26 @@ export function apply(ctx, config = {}) {
|
|
|
1725
1908
|
|
|
1726
1909
|
/** 问人时的选项文字(按会话语言给);答案两种语言都认。 */
|
|
1727
1910
|
const CHOICES = {
|
|
1728
|
-
releaseYes: ['
|
|
1729
|
-
releaseNo: ['
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1911
|
+
releaseYes: ['批准此次交付', 'Approve this delivery'],
|
|
1912
|
+
releaseNo: ['暂不批准', 'Not now'],
|
|
1913
|
+
releaseCommand: ['批准执行此命令', 'Approve this command'],
|
|
1914
|
+
stallContinue: ['按缺口继续修改', 'Let it fix the gaps'],
|
|
1915
|
+
stallVoid: ['作废此步骤', 'Void this step'],
|
|
1916
|
+
factRetract: ['撤回此事实', 'Retract this fact'],
|
|
1733
1917
|
factKeep: ['维持原事实', 'Keep the fact'],
|
|
1734
1918
|
}
|
|
1919
|
+
/** 0.5.1 前的选项文字:旧剧本(`--answers`)与旧会话里人已选过的答案照样认。 */
|
|
1920
|
+
const LEGACY_CHOICES = {
|
|
1921
|
+
releaseYes: ['放行这次交付', 'Release this delivery'],
|
|
1922
|
+
releaseNo: ['先不放行'],
|
|
1923
|
+
releaseCommand: ['放行这条命令', 'Release this command'],
|
|
1924
|
+
stallContinue: ['让它按缺口再改'],
|
|
1925
|
+
stallVoid: ['作废这一步'],
|
|
1926
|
+
factRetract: ['撤回这条事实'],
|
|
1927
|
+
factKeep: [],
|
|
1928
|
+
}
|
|
1735
1929
|
const choiceLabel = (key) => tr(...CHOICES[key])
|
|
1736
|
-
const chose = (asked, key) => CHOICES[key].includes(asked?.choice)
|
|
1930
|
+
const chose = (asked, key) => CHOICES[key].includes(asked?.choice) || LEGACY_CHOICES[key].includes(asked?.choice)
|
|
1737
1931
|
/** 没问到人的原因,一句人话。 */
|
|
1738
1932
|
const unanswered = (asked) => (asked.reason === 'cancelled' ? tr('人把问题撤下了', 'the person withdrew the question') : tr('没有人能回答', 'nobody can answer'))
|
|
1739
1933
|
|
|
@@ -1745,8 +1939,8 @@ export function apply(ctx, config = {}) {
|
|
|
1745
1939
|
async function escalateBlocked(exec, plan, step, attempts, reason, mutations) {
|
|
1746
1940
|
const asked = await askHuman(exec, {
|
|
1747
1941
|
id: `blocked-${plan.id}-${step.id}`,
|
|
1748
|
-
header: tr('
|
|
1749
|
-
question: tr(`步骤 ${step.id}(${clip(step.do, 60)})连续 ${attempts}
|
|
1942
|
+
header: tr('此步骤受阻', 'This step is stuck'),
|
|
1943
|
+
question: tr(`步骤 ${step.id}(${clip(step.do, 60)})连续 ${attempts} 次未通过:${clip(reason, 200)}。请选择处理方式。`, `Step ${step.id} (${clip(step.do, 60)}) failed ${attempts} times in a row: ${clip(reason, 200)}. What should happen?`),
|
|
1750
1944
|
options: [
|
|
1751
1945
|
{ label: choiceLabel('stallContinue'), description: tr('模型按缺口改判据或换做法后再交;你可以补一句方向。', 'The model revises the criteria or the approach against the gaps and delivers again; you can add a hint.') },
|
|
1752
1946
|
{ label: choiceLabel('stallVoid'), description: tr('这一步不做了,带原因作废(记录保留)。', 'Drop this step and void it with a reason (the record stays).') },
|
|
@@ -1775,14 +1969,26 @@ export function apply(ctx, config = {}) {
|
|
|
1775
1969
|
* 没人能答 ⇒ 事实标着「被推翻、待复核」,原生 goal 置为阻塞。
|
|
1776
1970
|
*/
|
|
1777
1971
|
async function reviewRefutedFacts(exec, sessionId, state, refutedHypotheses, basis, mutations) {
|
|
1778
|
-
|
|
1779
|
-
|
|
1972
|
+
/**
|
|
1973
|
+
* 两条路找到被推翻的事实:本目标里升格的(判断 id 对得上),以及被推翻的判断声明了
|
|
1974
|
+
* `retests` 的那条——它可能是别的会话留下的,判断 id 对不上,只有事实 id 跨会话不变。
|
|
1975
|
+
*/
|
|
1976
|
+
const retested = state.hypotheses.filter((item) => refutedHypotheses.includes(item.id) && typeof item.retests === 'string').map((item) => item.retests)
|
|
1977
|
+
const pending = []
|
|
1978
|
+
for (const fact of state.facts ?? []) if (refutedHypotheses.includes(fact.hypothesis) || retested.includes(fact.id)) pending.push(fact)
|
|
1979
|
+
for (const id of retested) {
|
|
1980
|
+
if (pending.some((fact) => fact.id === id)) continue
|
|
1981
|
+
const fact = findFact(sessionId, state, id)
|
|
1982
|
+
if (fact !== null) pending.push(fact)
|
|
1983
|
+
}
|
|
1984
|
+
const open = pending.filter((fact) => fact.review === undefined || fact.review === null)
|
|
1985
|
+
if (open.length === 0) return ''
|
|
1780
1986
|
const notes = []
|
|
1781
|
-
for (const fact of
|
|
1987
|
+
for (const fact of open) {
|
|
1782
1988
|
const asked = await askHuman(exec, {
|
|
1783
1989
|
id: `fact-${fact.id}`,
|
|
1784
|
-
header: tr('
|
|
1785
|
-
question: tr(`「${clip(fact.text, 120)}
|
|
1990
|
+
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?`),
|
|
1786
1992
|
options: [
|
|
1787
1993
|
{ label: choiceLabel('factRetract'), description: tr('它不再算已确立的结论(记录保留)。', 'It no longer counts as an established conclusion (the record stays).') },
|
|
1788
1994
|
{ label: choiceLabel('factKeep'), description: tr('这次证据不可靠,事实保留;推翻证据照样留在账上。', 'This evidence is unreliable and the fact stays; the refuting evidence stays on record too.') },
|
|
@@ -1900,6 +2106,49 @@ export function apply(ctx, config = {}) {
|
|
|
1900
2106
|
// 读盘按 (mtime, size) 记进程内缓存:没变的文件不重读、不重算摘要。
|
|
1901
2107
|
|
|
1902
2108
|
const FACTS_REL = ['clear', 'knowledge', 'facts']
|
|
2109
|
+
const LESSONS_REL = ['clear', 'knowledge', 'lessons']
|
|
2110
|
+
/** 经验的四类(与 `domain-language.js` 的 `LESSON_KINDS` 同值):坑、要先核的、会骗人的捷径、先验。 */
|
|
2111
|
+
const LESSON_KINDS = ['trap', 'check', 'shortcut', 'prior']
|
|
2112
|
+
/** 工作方式(与 `fold.js` 读的同值):广度调研 / 定向求解 / 先调研后求解。 */
|
|
2113
|
+
const FRAME_MODES = ['survey', 'solve', 'survey_then_solve']
|
|
2114
|
+
/** 问题的三种状态(与 `fold.js` 同值):在回答 / 新发现待决定 / 暂缓。 */
|
|
2115
|
+
const QUESTION_STATUS = ['open', 'emergent', 'parked']
|
|
2116
|
+
|
|
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
|
+
}
|
|
1903
2152
|
const ONTOLOGY_REL = ['clear', 'ontology']
|
|
1904
2153
|
const ONTOLOGY_BRANCH_DIRS = ['concepts', 'relations', 'entities']
|
|
1905
2154
|
/** 读面有界(与 `domain-language.js` 的 `WORKSPACE_LIMITS` 同值):超出的如实报成读不成,不静默截断。 */
|
|
@@ -1927,6 +2176,7 @@ export function apply(ctx, config = {}) {
|
|
|
1927
2176
|
}
|
|
1928
2177
|
}
|
|
1929
2178
|
walk(FACTS_REL, false)
|
|
2179
|
+
walk(LESSONS_REL, false)
|
|
1930
2180
|
for (const branch of ONTOLOGY_BRANCH_DIRS) walk([...ONTOLOGY_REL, branch], true)
|
|
1931
2181
|
return out
|
|
1932
2182
|
}
|
|
@@ -2215,7 +2465,7 @@ export function apply(ctx, config = {}) {
|
|
|
2215
2465
|
defineTool({
|
|
2216
2466
|
name: 'Frame',
|
|
2217
2467
|
description:
|
|
2218
|
-
'立约或修订:往当前原生 goal 上挂一份「怎样算回答了」的判据(done_criteria)与候选判断(每条一句话主张 + 一句「什么结果会推翻它」)。没有原生 goal 时会建一个,目标那一句话(headline)就是它的说法;续跑、暂停由原生 goal 管。修订必须带 reason,版本 +1
|
|
2468
|
+
'立约或修订:往当前原生 goal 上挂一份「怎样算回答了」的判据(done_criteria)与候选判断(每条一句话主张 + 一句「什么结果会推翻它」)。没有原生 goal 时会建一个,目标那一句话(headline)就是它的说法;续跑、暂停由原生 goal 管。修订必须带 reason,版本 +1,旧值全部留痕;改判据文本要带一份独立裁决。不可逆的动作写进 irreversible(匹配的命令执行前须经人工批准)。同一时间只开一个目标;它跨计划存在,一张 Plan 只承载它的一个阶段。',
|
|
2219
2469
|
parameters: {
|
|
2220
2470
|
type: 'object',
|
|
2221
2471
|
properties: {
|
|
@@ -2233,17 +2483,67 @@ export function apply(ctx, config = {}) {
|
|
|
2233
2483
|
type: 'string',
|
|
2234
2484
|
description: '改判据文本时要带的独立裁决 auditKey:改「怎样算完成」不能被顺手做掉',
|
|
2235
2485
|
},
|
|
2236
|
-
promote_at_level: { type: 'string', enum:
|
|
2486
|
+
promote_at_level: { type: 'string', enum: MODEL_LEVELS, description: '升格门槛(默认 L3)' },
|
|
2487
|
+
irreversible: {
|
|
2488
|
+
type: 'array',
|
|
2489
|
+
description: '不可逆的动作:做了就收不回、或结果不可重复的那几件(跑中试、下单、发出去的消息……)。每件写一句说明和它的命令特征(命令里一定会出现的一段原文)。匹配的命令执行前须经人工批准。修订目标时不传 = 不变',
|
|
2490
|
+
items: {
|
|
2491
|
+
type: 'object',
|
|
2492
|
+
properties: {
|
|
2493
|
+
action: { type: 'string', description: '一句话:这是什么动作' },
|
|
2494
|
+
command: { type: 'string', description: '命令特征:这类命令里一定出现的一段原文(如 "reactor.mjs state.json pilot")' },
|
|
2495
|
+
},
|
|
2496
|
+
required: ['action', 'command'],
|
|
2497
|
+
additionalProperties: false,
|
|
2498
|
+
},
|
|
2499
|
+
},
|
|
2500
|
+
mode: { type: 'string', enum: FRAME_MODES, description: '工作方式:survey = 广度调研(先铺调研板块,摸清后再看值得深入的问题);solve = 定向求解(问题下列出候选假设,用能区分它们的检验逐个排除);survey_then_solve = 先调研后求解。修订时不传 = 不变' },
|
|
2501
|
+
questions: {
|
|
2502
|
+
type: 'array',
|
|
2503
|
+
description: '要回答的问题(可选;一个目标可以有几个,不写就把整个目标当一个问题)。调研中新发现的问题写成 status="emergent" 并挂到板块(area)下;人决定深入就改成 open,决定暂缓就改成 parked。修订时不传 = 不变,传了就是完整清单',
|
|
2504
|
+
items: {
|
|
2505
|
+
type: 'object',
|
|
2506
|
+
properties: {
|
|
2507
|
+
id: { type: 'string', description: '短 id(如 q1),判断的 question 与步骤的 serves 用它' },
|
|
2508
|
+
text: { type: 'string', description: '一句话问题' },
|
|
2509
|
+
status: { type: 'string', enum: QUESTION_STATUS, description: 'open = 在回答;emergent = 新发现、待决定;parked = 暂缓(结案时列入尚未确定的事项)' },
|
|
2510
|
+
area: { type: 'string', description: '可选:属于哪个调研板块(板块 id)' },
|
|
2511
|
+
},
|
|
2512
|
+
required: ['id', 'text'],
|
|
2513
|
+
additionalProperties: false,
|
|
2514
|
+
},
|
|
2515
|
+
},
|
|
2516
|
+
areas: {
|
|
2517
|
+
type: 'array',
|
|
2518
|
+
description: '调研板块(广度调研用;如技术路线、主要企业、成本结构)。修订时不传 = 不变,传了就是完整清单',
|
|
2519
|
+
items: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' } }, required: ['id', 'name'], additionalProperties: false },
|
|
2520
|
+
},
|
|
2521
|
+
ontology: {
|
|
2522
|
+
type: 'object',
|
|
2523
|
+
description: '本体条目,由系统校验后写进 clear/ontology/(内容与文件同形,字段见 clear/ontology/SCHEMA.json)。立题时先写清相关的量:度量(kind=measure,gloss 写口径,unit 写单位)由什么测量、读数如何核对(kind=measures 的关系,domain 是仪表或来源,range 是被测的度量,check 写核对办法);量之间如何相互影响(kind=affects 的关系,shape 写大致形状)。同 id 的文件会被替换',
|
|
2524
|
+
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)}' },
|
|
2527
|
+
},
|
|
2528
|
+
additionalProperties: false,
|
|
2529
|
+
},
|
|
2237
2530
|
hypotheses: {
|
|
2238
2531
|
type: 'array',
|
|
2239
2532
|
description:
|
|
2240
|
-
'候选假设:每条一句话主张 +
|
|
2533
|
+
'候选假设:每条一句话主张 + 一句推翻条件,一条只说一件事(「A,且 B」拆成两条);可带**类型化断言**(可选,提供即严校:谓词与概念必须已登记、宾语形态要合值域、同一事实里不许自相矛盾)。不写断言照旧成立——断言是加法,不是门槛。修订目标时不传这一项 = 判断不变;传了就是这一版的完整清单,没列出的会记成「已替换」。',
|
|
2241
2534
|
items: {
|
|
2242
2535
|
type: 'object',
|
|
2243
2536
|
properties: {
|
|
2244
2537
|
name: { type: 'string', description: '短名,十二个汉字或二十来个字母以内,你自己起(如「python3 能跑」)。之后说起这条判断、在别的工具里引用它,都用这个名字' },
|
|
2245
2538
|
claim: { type: 'string' },
|
|
2539
|
+
question: { type: 'string', description: '可选:属于哪个问题或调研板块(id);不写就归第一个问题' },
|
|
2540
|
+
from: { type: 'string', description: '可选:由本体里哪条关系提出(关系 id,如有形状的 affects 关系);说不出来源就写「直觉」' },
|
|
2246
2541
|
refute_when: { type: 'string' },
|
|
2542
|
+
retests: {
|
|
2543
|
+
type: 'string',
|
|
2544
|
+
description:
|
|
2545
|
+
'这条判断在复检哪条已写进长期知识的事实:写那条事实的 id(clear/knowledge/facts/<id>.json 的文件名)。claim 照抄那条事实原来的说法、拿新数据再验一遍,不要写成「它被推翻了」:这条判断被推翻,系统才会当场问人撤回还是维持那条事实——别的会话留下的事实也一样',
|
|
2546
|
+
},
|
|
2247
2547
|
assertions: {
|
|
2248
2548
|
type: 'array',
|
|
2249
2549
|
description: '断言:主词–谓词–宾语(引用领域词汇里的 id)',
|
|
@@ -2300,7 +2600,7 @@ export function apply(ctx, config = {}) {
|
|
|
2300
2600
|
: carried
|
|
2301
2601
|
? state.hypotheses
|
|
2302
2602
|
.filter((item) => item.goal === state.goal.id && item.status !== 'superseded')
|
|
2303
|
-
.map((item) => ({ claim: item.claim, refute_when: item.refute_when, ...(item.name ? { name: item.name } : {}), ...(Array.isArray(item.assertions) ? { assertions: item.assertions } : {}) }))
|
|
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 } : {}) }))
|
|
2304
2604
|
: []
|
|
2305
2605
|
const names = hypotheses.map((hypothesis) => (typeof hypothesis?.name === 'string' ? hypothesis.name.trim() : '')).filter((name) => name !== '')
|
|
2306
2606
|
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.'))
|
|
@@ -2308,6 +2608,9 @@ export function apply(ctx, config = {}) {
|
|
|
2308
2608
|
if (typeof hypothesis?.claim !== 'string' || hypothesis.claim.trim() === '') return fail('hypothesis_claim_required', tr('每条假设要有一句话主张。', 'Each judgment needs a one-sentence claim.'))
|
|
2309
2609
|
if (typeof hypothesis?.refute_when !== 'string' || hypothesis.refute_when.trim() === '') return fail('hypothesis_refute_required', tr('每条假设必须写清「什么结果会推翻它」——没有推翻条件的假设无法被检验。', 'Each judgment must say what result would refute it; a judgment with no refutation condition cannot be tested.'))
|
|
2310
2610
|
if (hypothesis?.name !== undefined && (typeof hypothesis.name !== 'string' || textWidth(hypothesis.name.trim()) > (HANDLE_LIMIT + 4) * 2)) return fail('hypothesis_name_too_long', tr(`判断的短名要短:${HANDLE_LIMIT} 个汉字(或约 ${HANDLE_LIMIT * 2} 个字母)以内,能让人一眼认出是哪条就够。`, `Keep the short name short: within ${HANDLE_LIMIT} CJK characters (about ${HANDLE_LIMIT * 2} letters), just enough to recognize the judgment at a glance.`))
|
|
2611
|
+
if (hypothesis?.retests !== undefined && hypothesis.retests !== null && findFact(sessionId, state, hypothesis.retests) === null) {
|
|
2612
|
+
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
|
+
}
|
|
2311
2614
|
/**
|
|
2312
2615
|
* **宽松+校验**:不写断言放行(断言是加法),写了就在**落账之前**严校——
|
|
2313
2616
|
* 引用不存在的谓词 / 概念、宾语形态不合值域、同一事实自相矛盾,一律当场拒。
|
|
@@ -2401,7 +2704,54 @@ export function apply(ctx, config = {}) {
|
|
|
2401
2704
|
)
|
|
2402
2705
|
}
|
|
2403
2706
|
}
|
|
2404
|
-
const promoteAtLevel = LEVELS.includes(args.promote_at_level) ? args.promote_at_level : 'L3'
|
|
2707
|
+
const promoteAtLevel = LEVELS.includes(args.promote_at_level) ? normalizeLevel(args.promote_at_level) : 'L3'
|
|
2708
|
+
/** 不可逆动作:修订时没传就沿用上一版(与判断同一条纪律:「不提供」不等于「清空」)。 */
|
|
2709
|
+
const irreversible = Array.isArray(args.irreversible)
|
|
2710
|
+
? args.irreversible.map((item) => ({ action: String(item?.action ?? '').trim(), command: String(item?.command ?? '').trim() })).filter((item) => item.action !== '' && item.command.length >= 3)
|
|
2711
|
+
: isRevision
|
|
2712
|
+
? (state.goal.irreversible ?? [])
|
|
2713
|
+
: []
|
|
2714
|
+
if (Array.isArray(args.irreversible) && irreversible.length !== args.irreversible.length) {
|
|
2715
|
+
return fail('irreversible_invalid', tr('每件不可逆动作都要有一句说明(action)和命令特征(command,至少 3 个字符,是这类命令里一定出现的一段原文)。', 'Each irreversible action needs a one-line description (action) and a command signature (command, at least 3 characters of text that always appears in such a command).'))
|
|
2716
|
+
}
|
|
2717
|
+
/**
|
|
2718
|
+
* **问题与板块**:修订时不传 = 不变(与判断同一条纪律)。id 不许重复;判断的 `question`
|
|
2719
|
+
* 要指向这一版里存在的问题或板块,写错了当场说清可选的有哪些。
|
|
2720
|
+
*/
|
|
2721
|
+
const questions = Array.isArray(args.questions) ? args.questions.map((item) => ({ id: String(item?.id ?? '').trim(), text: String(item?.text ?? '').trim(), status: QUESTION_STATUS.includes(item?.status) ? item.status : 'open', ...(typeof item?.area === 'string' && item.area.trim() !== '' ? { area: item.area.trim() } : {}) })) : null
|
|
2722
|
+
const areas = Array.isArray(args.areas) ? args.areas.map((item) => ({ id: String(item?.id ?? '').trim(), name: String(item?.name ?? '').trim() })) : null
|
|
2723
|
+
if ((questions ?? []).some((item) => item.id === '' || item.text === '') || (areas ?? []).some((item) => item.id === '' || item.name === '')) return fail('questions_invalid', tr('每个问题要有 id 与一句话(text);每个板块要有 id 与名字(name)。', 'Each question needs an id and one sentence (text); each area needs an id and a name.'))
|
|
2724
|
+
const homeIds = [...(questions ?? (isRevision ? (state.goal.questions ?? []) : [])), ...(areas ?? (isRevision ? (state.goal.areas ?? []) : []))].map((item) => item.id)
|
|
2725
|
+
if (new Set(homeIds).size !== homeIds.length) return fail('questions_duplicate', tr('问题与板块的 id 不能重复。', 'Question and area ids must be unique.'))
|
|
2726
|
+
const strayHome = hypotheses.find((hypothesis) => typeof hypothesis?.question === 'string' && hypothesis.question.trim() !== '' && !homeIds.includes(hypothesis.question.trim()))
|
|
2727
|
+
if (strayHome !== undefined) return fail('question_unknown', tr(`判断「${handleOf(strayHome)}」的 question「${strayHome.question}」不是这一版里的问题或板块。可选:${homeIds.join('、') || '(还没有问题或板块:先在 questions / areas 里写)'}`, `Judgment "${handleOf(strayHome)}" has question "${strayHome.question}", which is not a question or area in this version. Options: ${homeIds.join(', ') || '(none yet: write them in questions / areas first)'}`))
|
|
2728
|
+
/**
|
|
2729
|
+
* **本体随立题写入**(`ontology`):逐个文件用宿主半的 `domain.checkFile` 校验,全部过了才写盘。
|
|
2730
|
+
* 为什么放进 Frame:模型要另写文件时,本体总被排到最后、最后没写;立题时写,预测和候选才有出处。
|
|
2731
|
+
*/
|
|
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
|
+
}
|
|
2746
|
+
for (const file of ontologyFiles) {
|
|
2747
|
+
const target = sessionFile(sessionId, 'clear', 'ontology', file.branch, `${file.id}.json`)
|
|
2748
|
+
if (target === null) return fail('workspace_unavailable', tr('这一刻拿不到会话的工作目录,本体条目没有写入。', 'The session workspace is unavailable right now; the ontology entries were not written.'))
|
|
2749
|
+
writeTextFile(target, `${JSON.stringify({ ...file.data, id: file.id }, null, 2)}\n`)
|
|
2750
|
+
}
|
|
2751
|
+
if (ontologyFiles.length > 0) {
|
|
2752
|
+
const synced = syncWorkspace(sessionId, state)
|
|
2753
|
+
if (synced !== null) mutations.push(synced)
|
|
2754
|
+
}
|
|
2405
2755
|
/**
|
|
2406
2756
|
* **修订不许给同一句话发新身份。**
|
|
2407
2757
|
*
|
|
@@ -2430,8 +2780,12 @@ export function apply(ctx, config = {}) {
|
|
|
2430
2780
|
...(given !== '' ? { name: given } : kept !== '' ? { name: kept } : {}),
|
|
2431
2781
|
claim,
|
|
2432
2782
|
refute_when: hypothesis.refute_when.trim(),
|
|
2783
|
+
/** 复检哪条已有事实(跨会话的身份是事实 id;判断 id 只活在本目标里)。 */
|
|
2784
|
+
...(typeof hypothesis.retests === 'string' && hypothesis.retests.trim() !== '' ? { retests: hypothesis.retests.trim() } : {}),
|
|
2433
2785
|
/** 断言随假设落账;没写就是 null(加法,不是门槛)。 */
|
|
2434
2786
|
assertions: Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null,
|
|
2787
|
+
...(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) } : {}),
|
|
2435
2789
|
version: index + 1,
|
|
2436
2790
|
}
|
|
2437
2791
|
})
|
|
@@ -2445,9 +2799,13 @@ export function apply(ctx, config = {}) {
|
|
|
2445
2799
|
criteria: criteriaList,
|
|
2446
2800
|
criteria_note: criteriaNote,
|
|
2447
2801
|
promote_at_level: promoteAtLevel,
|
|
2802
|
+
irreversible,
|
|
2448
2803
|
revision,
|
|
2449
2804
|
reason: isRevision ? String(args.reason).trim() : null,
|
|
2450
2805
|
hypotheses: nextHypotheses,
|
|
2806
|
+
...(FRAME_MODES.includes(args.mode) ? { mode: args.mode } : {}),
|
|
2807
|
+
...(questions !== null ? { questions } : {}),
|
|
2808
|
+
...(areas !== null ? { areas } : {}),
|
|
2451
2809
|
})
|
|
2452
2810
|
for (const dropped of existing) {
|
|
2453
2811
|
if (reused.has(dropped.id)) continue
|
|
@@ -2459,7 +2817,7 @@ export function apply(ctx, config = {}) {
|
|
|
2459
2817
|
ok: true,
|
|
2460
2818
|
code: isRevision ? 'goal_revised' : 'goal_set',
|
|
2461
2819
|
message:
|
|
2462
|
-
tr(`${isRevision ? `目标已修订(第 ${revision} 版)` : '目标已立'},${carried ? '判断沿用上一版,' : ''}登记了 ${hypotheses.length} 条判断${nextHypotheses.length === 0 ? '' : `:${nextHypotheses.map((item) => `「${handleOf(item)}」`).join('、')}`}
|
|
2820
|
+
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.` : ''}`) +
|
|
2463
2821
|
// 原生 goal 上那一句给人看:用目标的一句话,不写 id。
|
|
2464
2822
|
attachNativeGoal(exec.agent, clip(headline === '' ? String(args.claim ?? '') : headline, 120)),
|
|
2465
2823
|
})
|
|
@@ -2468,15 +2826,155 @@ export function apply(ctx, config = {}) {
|
|
|
2468
2826
|
|
|
2469
2827
|
// ── Conclude ──────────────────────────────────────────────────────────
|
|
2470
2828
|
|
|
2829
|
+
/** 结案时提议的经验:去掉空的、限 5 条,字段裁到能放进一张卡。 */
|
|
2830
|
+
function proposedLessonsOf(value) {
|
|
2831
|
+
const out = []
|
|
2832
|
+
for (const item of Array.isArray(value) ? value : []) {
|
|
2833
|
+
const text = typeof item?.text === 'string' ? item.text.trim() : ''
|
|
2834
|
+
if (text === '' || out.length >= 5) continue
|
|
2835
|
+
out.push({
|
|
2836
|
+
text: text.slice(0, 300),
|
|
2837
|
+
kind: LESSON_KINDS.includes(item.kind) ? item.kind : 'trap',
|
|
2838
|
+
about: Array.isArray(item.about) ? item.about.map((entry) => String(entry).trim()).filter((entry) => entry !== '').slice(0, 6) : [],
|
|
2839
|
+
evidence: typeof item.evidence === 'string' && item.evidence.trim() !== '' ? item.evidence.trim().slice(0, 300) : null,
|
|
2840
|
+
boundary: typeof item.boundary === 'string' && item.boundary.trim() !== '' ? item.boundary.trim().slice(0, 300) : null,
|
|
2841
|
+
})
|
|
2842
|
+
}
|
|
2843
|
+
return out
|
|
2844
|
+
}
|
|
2845
|
+
|
|
2846
|
+
/** 交给结案评估者的那一段:待核的经验,编号 L1……,判法写在一起。 */
|
|
2847
|
+
/** 结论四部分的唯一形状:结论 / 依据 / 尚未确定的事项(各写涉及什么、对答案的影响)/ 待您决策。 */
|
|
2848
|
+
function normalizeAnswers(raw) {
|
|
2849
|
+
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 !== '')
|
|
2851
|
+
return raw
|
|
2852
|
+
.map((item) => ({
|
|
2853
|
+
question: String(item?.question ?? '').trim(),
|
|
2854
|
+
conclusion: String(item?.conclusion ?? '').trim().slice(0, 600),
|
|
2855
|
+
basis: lines(item?.basis, 300).slice(0, 12),
|
|
2856
|
+
open: (Array.isArray(item?.open) ? item.open : [])
|
|
2857
|
+
.map((entry) => ({ about: lines(entry?.about, 80).slice(0, 8), effect: String(entry?.effect ?? '').trim().slice(0, 300) }))
|
|
2858
|
+
.filter((entry) => entry.effect !== '')
|
|
2859
|
+
.slice(0, 12),
|
|
2860
|
+
decide: lines(item?.decide, 300).slice(0, 6),
|
|
2861
|
+
...(typeof item?.unanswered === 'string' && item.unanswered.trim() !== '' ? { unanswered: item.unanswered.trim().slice(0, 300) } : {}),
|
|
2862
|
+
}))
|
|
2863
|
+
.filter((item) => item.conclusion !== '' || item.unanswered !== undefined)
|
|
2864
|
+
}
|
|
2865
|
+
|
|
2866
|
+
/**
|
|
2867
|
+
* **停止检查**(`CFG.requireAnswers`,只在 achieved 时):决策稳健了才结案。
|
|
2868
|
+
*
|
|
2869
|
+
* 只查有没有写,不判断写得对不对(与「产物存在且格式正确」同类):
|
|
2870
|
+
* · 每个在回答的问题都有结论,或写明 `unanswered` 的原因;
|
|
2871
|
+
* · 还在考察中、从未得到支持的候选,还开着的未解释项,都要出现在某条结论的
|
|
2872
|
+
* 「尚未确定的事项」里(`open[].about` 写它的 id 或短名),并写明若它成立答案会如何改变。
|
|
2873
|
+
*
|
|
2874
|
+
* 为什么:真跑里漂移被量化、登记成未解释项,答案仍按设定温度交付并以 achieved 结案。
|
|
2875
|
+
* 返回缺项清单(每行一项);齐了返回空数组。
|
|
2876
|
+
*/
|
|
2877
|
+
function unsettledForAnswers(state, derived, answers) {
|
|
2878
|
+
const goal = state.goal
|
|
2879
|
+
const exploration = derived?.exploration ?? null
|
|
2880
|
+
const missing = []
|
|
2881
|
+
const declared = (goal.questions ?? []).filter((question) => question.status === 'open')
|
|
2882
|
+
const implicit = (goal.questions ?? []).length === 0 && (goal.areas ?? []).length === 0
|
|
2883
|
+
const answered = (id) => answers.some((answer) => answer.question === id) || (implicit && answers.length > 0)
|
|
2884
|
+
if (implicit && answers.length === 0) missing.push(tr('目标还没有结论:`answers` 至少写一条(结论 / 依据 / 尚未确定的事项 / 待您决策)。', 'The goal has no conclusion yet: write at least one entry in `answers` (conclusion / basis / open points / decisions for the user).'))
|
|
2885
|
+
for (const question of declared) if (!answered(question.id)) missing.push(tr(`问题 ${question.id}「${clip(question.text, 60)}」没有结论:写结论,或用 \`unanswered\` 写明为何未能回答。`, `Question ${question.id} "${clip(question.text, 60)}" has no conclusion: write one, or say why it could not be answered in \`unanswered\`.`))
|
|
2886
|
+
const about = new Set(answers.flatMap((answer) => answer.open.flatMap((entry) => entry.about)))
|
|
2887
|
+
for (const question of exploration?.questions ?? []) {
|
|
2888
|
+
for (const candidate of question.candidates ?? []) {
|
|
2889
|
+
if (candidate.state !== 'examining' || candidate.supportedLevel !== null) continue
|
|
2890
|
+
if (about.has(candidate.id) || about.has(candidate.name)) continue
|
|
2891
|
+
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
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
for (const anomaly of (state.anomalies ?? []).filter((item) => item?.status === 'open')) {
|
|
2895
|
+
if (about.has(anomaly.id)) continue
|
|
2896
|
+
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
|
+
}
|
|
2898
|
+
for (const question of (goal.questions ?? []).filter((item) => item.status === 'emergent' || item.status === 'parked')) {
|
|
2899
|
+
if (about.has(question.id) || answered(question.id)) continue
|
|
2900
|
+
missing.push(tr(`问题 ${question.id}「${clip(question.text, 60)}」${question.status === 'parked' ? '已暂缓' : '待决定'}:写进「尚未确定的事项」(about 写 ${question.id})。`, `Question ${question.id} "${clip(question.text, 60)}" is ${question.status === 'parked' ? 'parked' : 'awaiting a decision'}: put it in the open points (about: ${question.id}).`))
|
|
2901
|
+
}
|
|
2902
|
+
return missing
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
/** 交给结案评估者读的结论四部分(核它与记录是否一致)。 */
|
|
2906
|
+
function answersBrief(answers) {
|
|
2907
|
+
if (answers.length === 0) return []
|
|
2908
|
+
return [
|
|
2909
|
+
tr('# 结论(做的人按问题写的四部分;请核它与记录是否一致,依据是否真在记录里)', '# Conclusions (written by the worker per question; check they match the record and that the basis is really in it)'),
|
|
2910
|
+
...answers.flatMap((answer) => [
|
|
2911
|
+
`## ${answer.question || tr('目标', 'goal')}:${answer.conclusion || tr(`未回答(${answer.unanswered})`, `unanswered (${answer.unanswered})`)}`,
|
|
2912
|
+
...answer.basis.map((line) => tr(`- 依据:${line}`, `- basis: ${line}`)),
|
|
2913
|
+
...answer.open.map((entry) => tr(`- 尚未确定(${entry.about.join('、') || '—'}):${entry.effect}`, `- open (${entry.about.join(', ') || '—'}): ${entry.effect}`)),
|
|
2914
|
+
...answer.decide.map((line) => tr(`- 待您决策:${line}`, `- for the user to decide: ${line}`)),
|
|
2915
|
+
]),
|
|
2916
|
+
]
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
function lessonBrief(lessons) {
|
|
2920
|
+
if (lessons.length === 0) return []
|
|
2921
|
+
const kindWord = { trap: tr('坑', 'trap'), check: tr('要核的', 'check'), shortcut: tr('会骗人的捷径', 'misleading shortcut'), prior: tr('先验', 'prior') }
|
|
2922
|
+
return [
|
|
2923
|
+
tr('# 待核的经验(做的人提议:下次在同类现场要怎么做)', '# Lessons to check (proposed by the worker: what to do differently next time in a similar setting)'),
|
|
2924
|
+
...lessons.map((item, index) => `- L${index + 1} · ${kindWord[item.kind]} · ${item.text}${item.evidence ? tr(`(凭据:${item.evidence})`, ` (evidence: ${item.evidence})`) : ''}${item.boundary ? tr(`(不适用:${item.boundary})`, ` (does not apply: ${item.boundary})`) : ''}`),
|
|
2925
|
+
tr(
|
|
2926
|
+
'每条在 `lessons` 里各给一格:support = 记录里确实发生过它说的事,而且照它做下次会更好;refute = 记录与它矛盾,或照它做会误导;inconclusive = 凭记录判不了,或它只是这次结论的复述。经验不影响 `holds`。',
|
|
2927
|
+
'Give one `lessons` entry each: support = the record shows what it says happened, and following it would do better next time; refute = the record contradicts it, or following it would mislead; inconclusive = the record cannot decide, or it only restates this run\'s conclusion. Lessons do not affect `holds`.',
|
|
2928
|
+
),
|
|
2929
|
+
]
|
|
2930
|
+
}
|
|
2931
|
+
|
|
2471
2932
|
defineTool({
|
|
2472
2933
|
name: 'Conclude',
|
|
2473
2934
|
description:
|
|
2474
|
-
'结案:交目标验收——这是完成目标的唯一路径(原生「完成目标」会被拒)。系统**无条件**派独立评估者,拿目标判据与转写忠实度逐条核对;判据达成才结案为 achieved:原生 goal
|
|
2935
|
+
'结案:交目标验收——这是完成目标的唯一路径(原生「完成目标」会被拒)。系统**无条件**派独立评估者,拿目标判据与转写忠实度逐条核对;判据达成才结案为 achieved:原生 goal 置为完成;评估者同时逐条判尚在考察中的判断,判为支持的(或中途已达门槛的)升格为事实;各步收下的产物声明为交付卡片;随结案提议的经验(`lessons`)由评估者逐条核,支持的写进 clear/knowledge/lessons/。否则目标保持开放并回注缺口。**顺序**:achieved 之前必须先把计划收尾(`ClosePlan`)。放弃(`abandoned`)不受此限:原生 goal 置为阻塞,写明原因,由人决定结束。',
|
|
2475
2936
|
parameters: {
|
|
2476
2937
|
type: 'object',
|
|
2477
2938
|
properties: {
|
|
2478
2939
|
outcome: { type: 'string', enum: ['achieved', 'abandoned'], description: 'achieved=判据已达成;abandoned=如实说清阻塞后放弃' },
|
|
2479
2940
|
note: { type: 'string', description: '结案说明' },
|
|
2941
|
+
answers: {
|
|
2942
|
+
type: 'array',
|
|
2943
|
+
description: '结论(achieved 时按问题各写一条;目标没列问题就写一条):结论 / 依据 / 尚未确定的事项 / 待您决策。中间判断与过程不写进来。还在考察中、未得到支持的候选假设,还开着的未解释项,都要写进「尚未确定的事项」并说明若它成立答案会如何改变',
|
|
2944
|
+
items: {
|
|
2945
|
+
type: 'object',
|
|
2946
|
+
properties: {
|
|
2947
|
+
question: { type: 'string', description: '哪个问题(id);目标没列问题时可省略' },
|
|
2948
|
+
conclusion: { type: 'string', description: '结论:一两句话,带数值与适用条件' },
|
|
2949
|
+
basis: { type: 'array', items: { type: 'string' }, description: '依据:每个已采纳、已排除的候选假设或已核验的读数各一行,注明对应的实验或来源' },
|
|
2950
|
+
open: {
|
|
2951
|
+
type: 'array',
|
|
2952
|
+
description: '尚未确定的事项:每项写涉及什么(about:候选假设短名、未解释项 id 或问题 id)与对结论的影响(effect:若它成立,结论如何改变)',
|
|
2953
|
+
items: { type: 'object', properties: { about: { type: 'array', items: { type: 'string' } }, effect: { type: 'string' } }, required: ['effect'], additionalProperties: false },
|
|
2954
|
+
},
|
|
2955
|
+
decide: { type: 'array', items: { type: 'string' }, description: '待您决策:需要人决定的事项(例如是否先复测再放大)' },
|
|
2956
|
+
unanswered: { type: 'string', description: '未能回答时写明原因(此时 conclusion 可省略)' },
|
|
2957
|
+
},
|
|
2958
|
+
additionalProperties: false,
|
|
2959
|
+
},
|
|
2960
|
+
},
|
|
2961
|
+
lessons: {
|
|
2962
|
+
type: 'array',
|
|
2963
|
+
maxItems: 5,
|
|
2964
|
+
description: '经验(可选,只在 achieved 时核):这次摸出的、下次在同类现场改变做法的东西,不是这次结论的复述。评估者逐条对照记录核,判为支持的写进 clear/knowledge/lessons/,之后的会话在立题和定计划时会看到',
|
|
2965
|
+
items: {
|
|
2966
|
+
type: 'object',
|
|
2967
|
+
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: '在什么条件下不适用' },
|
|
2973
|
+
},
|
|
2974
|
+
required: ['text', 'kind'],
|
|
2975
|
+
additionalProperties: false,
|
|
2976
|
+
},
|
|
2977
|
+
},
|
|
2480
2978
|
},
|
|
2481
2979
|
required: ['outcome'],
|
|
2482
2980
|
additionalProperties: false,
|
|
@@ -2543,15 +3041,22 @@ export function apply(ctx, config = {}) {
|
|
|
2543
3041
|
* 第四阶段删掉的两道门:「跳级没写理由」(`ExplainLevelSkip` 整套删除)与
|
|
2544
3042
|
* 「将升格的命题没有断言形态」(降为缺口)。依据见 `docs/less-is-more-plan.zh-CN.md` 第四阶段。
|
|
2545
3043
|
*/
|
|
3044
|
+
/**
|
|
3045
|
+
* **结案评估顺带判每条还活着的判断**(这一目标的、没被推翻过、还没成事实的)。
|
|
3046
|
+
*
|
|
3047
|
+
* 为什么:升格原来只看模型自己给步骤标的等级,而 L0–L2 允许自判——真跑里模型一律标 L1/L2,
|
|
3048
|
+
* 于是 9 次运行 0 条事实,跨会话复用与复检全部空转。结案这次独立评估是唯一必然发生的独立判断,
|
|
3049
|
+
* 让它逐条读判断:它判「支持」的,与中途到了门槛的一样升格。不加新机制、不多派一次评估者。
|
|
3050
|
+
*/
|
|
3051
|
+
const candidates = derived.hypotheses.filter(
|
|
3052
|
+
(hypothesis) =>
|
|
3053
|
+
(typeof hypothesis.goal !== 'string' || hypothesis.goal === goal.id) &&
|
|
3054
|
+
(hypothesis.status === 'alive' || hypothesis.status === 'proposed') &&
|
|
3055
|
+
(hypothesis.refutations ?? 0) === 0 &&
|
|
3056
|
+
!(state.facts ?? []).some((fact) => fact.hypothesis === hypothesis.id),
|
|
3057
|
+
)
|
|
2546
3058
|
if (CFG.requireLandedEntities && derived.knowledge.mode === 'knowledge') {
|
|
2547
|
-
const
|
|
2548
|
-
const promotable = derived.hypotheses.filter(
|
|
2549
|
-
(hypothesis) =>
|
|
2550
|
-
(hypothesis.status === 'alive' || hypothesis.status === 'proposed') &&
|
|
2551
|
-
(hypothesis.refutations ?? 0) === 0 &&
|
|
2552
|
-
levelIndexOf(hypothesis.supportedLevel) >= threshold,
|
|
2553
|
-
)
|
|
2554
|
-
const offGraph = promotable.filter((hypothesis) => (hypothesis.unlanded ?? []).length > 0)
|
|
3059
|
+
const offGraph = candidates.filter((hypothesis) => (hypothesis.unlanded ?? []).length > 0)
|
|
2555
3060
|
if (offGraph.length > 0) {
|
|
2556
3061
|
return fail(
|
|
2557
3062
|
'entities_unlanded',
|
|
@@ -2562,13 +3067,33 @@ export function apply(ctx, config = {}) {
|
|
|
2562
3067
|
)
|
|
2563
3068
|
}
|
|
2564
3069
|
}
|
|
3070
|
+
const answers = normalizeAnswers(args.answers)
|
|
3071
|
+
if (CFG.requireAnswers) {
|
|
3072
|
+
const missing = unsettledForAnswers(state, derived, answers)
|
|
3073
|
+
if (missing.length > 0) {
|
|
3074
|
+
return fail(
|
|
3075
|
+
'answers_incomplete',
|
|
3076
|
+
tr(`结论还不完整,不能以 achieved 结案(只检查是否写了,不判断写得对不对):\n${missing.map((line) => `- ${line}`).join('\n')}\n探索到结论不再改变为止:未排除的可能与未解释的读数,要么检验掉,要么在结论里写明它们的影响。`, `The conclusion is incomplete and cannot close as achieved (this only checks that things are written, not whether they are right):\n${missing.map((line) => `- ${line}`).join('\n')}\nExplore until the conclusion stops changing: possibilities not ruled out and unexplained readings are either tested away or written into the conclusion with their effect.`),
|
|
3077
|
+
{ mutations },
|
|
3078
|
+
)
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
2565
3081
|
const unfinished = plan === null ? [] : plan.steps.filter((step) => step.status === 'open')
|
|
2566
|
-
const syntheticStep = {
|
|
3082
|
+
const syntheticStep = {
|
|
3083
|
+
id: `goal:${goal.id}`,
|
|
3084
|
+
ordinal: 0,
|
|
3085
|
+
do: tr(`核验目标 ${goal.id} 的判据与转写忠实度`, `Check goal ${goal.id} against its criteria and transcription fidelity`),
|
|
3086
|
+
done_criteria: goal.done_criteria,
|
|
3087
|
+
artifacts: [],
|
|
3088
|
+
tests: candidates.length === 0 ? null : { hypotheses: candidates.map((hypothesis) => hypothesis.id), level: goal.promote_at_level },
|
|
3089
|
+
}
|
|
3090
|
+
const proposedLessons = proposedLessonsOf(args.lessons)
|
|
2567
3091
|
const gate = {
|
|
2568
3092
|
confirmed: [
|
|
2569
3093
|
...state.evidence.map((item) => ({ ref: `evidence:${item.id}`, bytes: 0, digest: `verdict=${item.verdict}` })),
|
|
2570
3094
|
...derived.hypotheses.map((item) => ({ ref: `hypothesis:${item.id}`, bytes: 0, digest: `${item.status}/支持到${item.supportedLevel ?? '—'}` })),
|
|
2571
3095
|
],
|
|
3096
|
+
extra: [...answersBrief(answers), ...lessonBrief(proposedLessons)],
|
|
2572
3097
|
}
|
|
2573
3098
|
const audit = await runEvaluator(sessionId, exec.agent, plan, syntheticStep, gate, 'goal_audit', exec.signal)
|
|
2574
3099
|
mutations.push(...audit.mutations)
|
|
@@ -2636,10 +3161,47 @@ export function apply(ctx, config = {}) {
|
|
|
2636
3161
|
* 三样全零 = **没人碰过它**。不强制证实/证伪——但「没看过」不能被写成「没问题」,
|
|
2637
3162
|
* 所以这里把它记进结案那条变更里,卡片与面板都说得出来。
|
|
2638
3163
|
*/
|
|
3164
|
+
/** 结案评估对每条判断的结果,各记一份独立证据(等级记成目标的升格门槛:判它的是独立评估者)。 */
|
|
3165
|
+
const goalOrigin = buildEvidenceOrigins({
|
|
3166
|
+
cwd: sessionCwd(sessionId),
|
|
3167
|
+
accepted: [],
|
|
3168
|
+
confirmed: [],
|
|
3169
|
+
cardPath: audit.cardPath ?? null,
|
|
3170
|
+
evaluatorSession: audit.mutations.find((mutation) => mutation.t === 'audit/dispatched')?.evaluator_session ?? null,
|
|
3171
|
+
basis: audit.basis,
|
|
3172
|
+
})
|
|
3173
|
+
const judged = new Map()
|
|
3174
|
+
for (const result of audit.results ?? []) {
|
|
3175
|
+
const hypothesis = candidates.find((item) => item.id === result.hypothesis || item.name === result.hypothesis)
|
|
3176
|
+
if (hypothesis === undefined || judged.has(hypothesis.id)) continue
|
|
3177
|
+
const evidenceId = `e-${Math.random().toString(36).slice(2, 8)}`
|
|
3178
|
+
judged.set(hypothesis.id, { verdict: result.verdict, evidence: evidenceId })
|
|
3179
|
+
mutations.push({
|
|
3180
|
+
t: 'evidence/recorded',
|
|
3181
|
+
id: evidenceId,
|
|
3182
|
+
step: syntheticStep.id,
|
|
3183
|
+
plan: plan?.id ?? 'goal',
|
|
3184
|
+
hypothesis: hypothesis.id,
|
|
3185
|
+
verdict: result.verdict,
|
|
3186
|
+
level: goal.promote_at_level,
|
|
3187
|
+
evaluator: 'independent',
|
|
3188
|
+
basis: result.basis ?? audit.basis,
|
|
3189
|
+
refs: goalOrigin.paths,
|
|
3190
|
+
origins: goalOrigin.origins,
|
|
3191
|
+
anchor: 'auditor',
|
|
3192
|
+
basis_reviewable: true,
|
|
3193
|
+
})
|
|
3194
|
+
}
|
|
3195
|
+
const refutedAtClose = [...judged].filter(([, item]) => item.verdict === 'refute').map(([id]) => id)
|
|
3196
|
+
const factReview =
|
|
3197
|
+
refutedAtClose.length === 0
|
|
3198
|
+
? ''
|
|
3199
|
+
: await reviewRefutedFacts(exec, sessionId, state, refutedAtClose, (audit.results ?? []).find((item) => item.verdict === 'refute')?.basis ?? audit.basis, mutations)
|
|
2639
3200
|
const untouched = derived.hypotheses.filter(
|
|
2640
|
-
(hypothesis) =>
|
|
3201
|
+
(hypothesis) =>
|
|
3202
|
+
!judged.has(hypothesis.id) && (hypothesis.supportedLevel === null || hypothesis.supportedLevel === undefined) && (hypothesis.refutations ?? 0) === 0 && (hypothesis.inconclusive ?? 0) === 0,
|
|
2641
3203
|
)
|
|
2642
|
-
mutations.push({ t: 'goal/closed', id: goal.id, status: 'achieved', verdict: 'support', note: args.note ?? null, unjudged: untouched.map((hypothesis) => hypothesis.id) })
|
|
3204
|
+
mutations.push({ t: 'goal/closed', id: goal.id, status: 'achieved', verdict: 'support', note: args.note ?? null, unjudged: untouched.map((hypothesis) => hypothesis.id), ...(answers.length > 0 ? { answers } : {}) })
|
|
2643
3205
|
const continuationNote = completeNativeGoal(exec.agent)
|
|
2644
3206
|
/** 这个目标下各步经准入收下的产物(按路径去重),结案时一次声明成交付卡片。 */
|
|
2645
3207
|
const delivered = []
|
|
@@ -2666,7 +3228,11 @@ export function apply(ctx, config = {}) {
|
|
|
2666
3228
|
if ((state.facts ?? []).some((fact) => fact.hypothesis === hypothesis.id)) continue
|
|
2667
3229
|
if (hypothesis.status !== 'alive' && hypothesis.status !== 'proposed') continue
|
|
2668
3230
|
if (hypothesis.refutations > 0) continue
|
|
2669
|
-
|
|
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
|
|
2670
3236
|
const assertions = Array.isArray(hypothesis.assertions) ? hypothesis.assertions : null
|
|
2671
3237
|
/**
|
|
2672
3238
|
* **第三道校验(升格时)**:断言涉及的谓词、类型、主体此刻都要在本体文件里成立。
|
|
@@ -2688,6 +3254,7 @@ export function apply(ctx, config = {}) {
|
|
|
2688
3254
|
const evidence = evidenceFor(state, hypothesis.id)
|
|
2689
3255
|
.filter((item) => item.verdict === 'support')
|
|
2690
3256
|
.map((item) => item.id)
|
|
3257
|
+
if (atClose?.verdict === 'support') evidence.push(atClose.evidence)
|
|
2691
3258
|
/**
|
|
2692
3259
|
* 升格这一刻它用到的词条的含义指纹:之后谁改了定义,这条事实就知道要复核。
|
|
2693
3260
|
* 「用到」= 断言引用的,加上主张与边界原文里按词面提到的(模型很少写断言,见 fingerprintDefinitions)。
|
|
@@ -2700,7 +3267,7 @@ export function apply(ctx, config = {}) {
|
|
|
2700
3267
|
} catch {
|
|
2701
3268
|
definitions = null
|
|
2702
3269
|
}
|
|
2703
|
-
const record = { id: factId, goal: goal.id, hypothesis: hypothesis.id, text: hypothesis.claim, scope: hypothesis.refute_when ?? null, level:
|
|
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 }
|
|
2704
3271
|
const path = persistFact(sessionId, record)
|
|
2705
3272
|
/**
|
|
2706
3273
|
* 事实带上**边界**(`scope` = 这条假设的推翻条件):没有边界的事实,下一轮没人敢用;
|
|
@@ -2718,7 +3285,7 @@ export function apply(ctx, config = {}) {
|
|
|
2718
3285
|
hypothesis: hypothesis.id,
|
|
2719
3286
|
text: hypothesis.claim,
|
|
2720
3287
|
scope: hypothesis.refute_when ?? null,
|
|
2721
|
-
level:
|
|
3288
|
+
level: factLevel ?? null,
|
|
2722
3289
|
evidence,
|
|
2723
3290
|
assertions,
|
|
2724
3291
|
definitions,
|
|
@@ -2726,6 +3293,21 @@ export function apply(ctx, config = {}) {
|
|
|
2726
3293
|
})
|
|
2727
3294
|
promoted.push({ id: factId, claim: hypothesis.claim })
|
|
2728
3295
|
}
|
|
3296
|
+
/** 评估者判为支持的经验写成文件;别的如实说出来,不写。 */
|
|
3297
|
+
const lessonVerdicts = new Map((audit.lessons ?? []).map((item) => [item.lesson, item]))
|
|
3298
|
+
const keptLessons = []
|
|
3299
|
+
const droppedLessons = []
|
|
3300
|
+
proposedLessons.forEach((lesson, index) => {
|
|
3301
|
+
const verdict = lessonVerdicts.get(`L${index + 1}`) ?? null
|
|
3302
|
+
if (verdict?.verdict !== 'support') {
|
|
3303
|
+
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
|
+
return
|
|
3305
|
+
}
|
|
3306
|
+
const record = { id: `l-${Math.random().toString(36).slice(2, 8)}`, goal: goal.id, ...lesson, basis: verdict.basis }
|
|
3307
|
+
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 })
|
|
3309
|
+
keptLessons.push(record)
|
|
3310
|
+
})
|
|
2729
3311
|
return done({
|
|
2730
3312
|
ok: true,
|
|
2731
3313
|
code: 'goal_achieved',
|
|
@@ -2740,6 +3322,9 @@ export function apply(ctx, config = {}) {
|
|
|
2740
3322
|
? tr(`\n结案时有 ${untouched.length} 条判断**一次都没检验过**:${untouched.map((hypothesis) => `「${handleOf(hypothesis)}」`).join('、')}——没检验不是「没问题」,是「没看过」;它们留在账上,随时可以补一次检验。`, `\nAt conclusion, ${untouched.length} judgment(s) were **never tested**: ${untouched.map((hypothesis) => `"${handleOf(hypothesis)}"`).join(', ')}. Untested does not mean fine; it means not looked at. They stay in the ledger and can be tested any time.`)
|
|
2741
3323
|
: '') +
|
|
2742
3324
|
tr('\n被推翻与被替换的判断都留在记录里。', '\nRefuted and replaced judgments stay in the record.') +
|
|
3325
|
+
(keptLessons.length > 0 ? tr(`\n写下的经验:${keptLessons.map((item) => `${item.text}(clear/knowledge/lessons/${item.id}.json)`).join(' / ')}。之后的会话立题和定计划时会看到。`, `\nLessons written: ${keptLessons.map((item) => `${item.text} (clear/knowledge/lessons/${item.id}.json)`).join(' / ')}. Later sessions see them when framing and planning.`) : '') +
|
|
3326
|
+
(droppedLessons.length > 0 ? tr(`\n没写下的经验:\n${droppedLessons.map((item) => `- ${item}`).join('\n')}`, `\nLessons not written:\n${droppedLessons.map((item) => `- ${item}`).join('\n')}`) : '') +
|
|
3327
|
+
factReview +
|
|
2743
3328
|
/** 「怎么做」也要攒下来:这次摸出的可复用做法写成原生技能,下次宿主会列出来。 */
|
|
2744
3329
|
tr('\n这次如果摸出了以后还会用的做法(怎么查、怎么算、怎么验),写成原生技能:.agents/skills/<名字>/SKILL.md(description 写清什么时候用)。', '\nIf this run found a method worth reusing (how to look up, compute or verify), write it as a native skill: .agents/skills/<name>/SKILL.md (with a description that says when to use it).') +
|
|
2745
3330
|
continuationNote +
|
|
@@ -2768,6 +3353,25 @@ export function apply(ctx, config = {}) {
|
|
|
2768
3353
|
}
|
|
2769
3354
|
}
|
|
2770
3355
|
|
|
3356
|
+
/**
|
|
3357
|
+
* **一条经验一个文件**(`clear/knowledge/lessons/<经验 id>.json`),只有系统写。
|
|
3358
|
+
*
|
|
3359
|
+
* 经验与事实分开放:事实改变信念(「T 与 cat 沿斜脊耦合」),经验改变下一次怎么做
|
|
3360
|
+
* (「这台装置的温度要拿参考读数核」)。两者都要过独立评估才写,写了下个会话就读得到。
|
|
3361
|
+
* 人要撤回一条,在文件上把 `status` 改成 `retracted`。
|
|
3362
|
+
*/
|
|
3363
|
+
function persistLesson(sessionId, record) {
|
|
3364
|
+
const file = sessionFile(sessionId, 'clear', 'knowledge', 'lessons', `${record.id}.json`)
|
|
3365
|
+
if (file === null) return null
|
|
3366
|
+
try {
|
|
3367
|
+
writeTextFile(file, `${JSON.stringify({ ...record, session: sessionId, status: 'active', at: Date.now() }, null, 2)}\n`)
|
|
3368
|
+
return file
|
|
3369
|
+
} catch (error) {
|
|
3370
|
+
ctx.logger?.warn?.(`clearai kernel: 经验落盘失败 ${String(error?.message ?? error)}`)
|
|
3371
|
+
return null
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
|
|
2771
3375
|
// ── 计划六件 ───────────────────────────────────────────────────────────
|
|
2772
3376
|
|
|
2773
3377
|
const STEP_SCHEMA = {
|
|
@@ -2786,11 +3390,21 @@ export function apply(ctx, config = {}) {
|
|
|
2786
3390
|
items: { type: 'string' },
|
|
2787
3391
|
description: '这一步检验哪几条判断:填判断的短名(也认主张原文)。一次观测同时判几条竞争的判断时(比较那一步),把它们都列上',
|
|
2788
3392
|
},
|
|
2789
|
-
level: { type: 'string', enum:
|
|
3393
|
+
level: { type: 'string', enum: MODEL_LEVELS, description: 'L2 = 自判(你写结果与依据);L3 = 独立评估(系统派评估者判);L4 = 人工批准(不可重复或来自外部的证据,须先经人工批准)' },
|
|
2790
3394
|
},
|
|
2791
3395
|
required: ['hypotheses', 'level'],
|
|
2792
3396
|
additionalProperties: false,
|
|
2793
3397
|
},
|
|
3398
|
+
expect: {
|
|
3399
|
+
type: 'string',
|
|
3400
|
+
description: '可选,执行前填写:这一步预计观察到什么(尽量给出数值或方向),以及预测的来源(本体中的哪条关系 / 哪条经验 / 哪条判断,或注明为直觉)。事先写下,预测落空时才能被发现',
|
|
3401
|
+
},
|
|
3402
|
+
serves: { type: 'string', description: '可选:这一步服务哪个问题或调研板块(id);不写即归当前问题' },
|
|
3403
|
+
predictions: {
|
|
3404
|
+
type: 'array',
|
|
3405
|
+
description: '可选,动手前写:按候选假设分别写预测(若「X」成立,预计看到什么)。各候选预测相同的一步区分不了它们,应改选能区分的检验',
|
|
3406
|
+
items: { type: 'object', properties: { hypothesis: { type: 'string', description: '判断的短名(也认 id)' }, expect: { type: 'string', description: '若它成立,预计看到什么(尽量给数或方向)' } }, required: ['hypothesis', 'expect'], additionalProperties: false },
|
|
3407
|
+
},
|
|
2794
3408
|
},
|
|
2795
3409
|
required: ['id', 'do', 'done_criteria'],
|
|
2796
3410
|
additionalProperties: false,
|
|
@@ -2800,7 +3414,7 @@ export function apply(ctx, config = {}) {
|
|
|
2800
3414
|
defineTool({
|
|
2801
3415
|
name: 'CreatePlan',
|
|
2802
3416
|
description:
|
|
2803
|
-
'立约:把复杂任务立成一份计划。每步一句话说清做什么(do)、以何物为证(artifacts)、以及判定标准(done_criteria,在结果出现之前写下)。检验判断的步骤用 tests:{hypotheses, level} 声明验哪几条、什么等级(比较竞争路线的那一步,把竞争的几条都列上)。最多 25 步。约立起便锁定:局部挫折改当前步,不要推倒重来。',
|
|
3417
|
+
'立约:把复杂任务立成一份计划。每步一句话说清做什么(do)、以何物为证(artifacts)、以及判定标准(done_criteria,在结果出现之前写下);可带预测(expect:预计观察到什么,以及预测的来源)。检验判断的步骤用 tests:{hypotheses, level} 声明验哪几条、什么等级(比较竞争路线的那一步,把竞争的几条都列上)。最多 25 步。约立起便锁定:局部挫折改当前步,不要推倒重来。',
|
|
2804
3418
|
parameters: {
|
|
2805
3419
|
type: 'object',
|
|
2806
3420
|
properties: {
|
|
@@ -2825,6 +3439,12 @@ export function apply(ctx, config = {}) {
|
|
|
2825
3439
|
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))
|
|
2826
3440
|
resolvedTests.set(step.id, resolved.tests)
|
|
2827
3441
|
}
|
|
3442
|
+
const resolvedExtras = new Map()
|
|
3443
|
+
for (const step of args.steps) {
|
|
3444
|
+
const resolved = resolveStepExtras(state, step)
|
|
3445
|
+
if (resolved.ok !== true) return fail(resolved.code, resolved.message)
|
|
3446
|
+
resolvedExtras.set(step.id, resolved.extra)
|
|
3447
|
+
}
|
|
2828
3448
|
const warnings = []
|
|
2829
3449
|
if (typeof args.brief !== 'string' || args.brief.length < CFG.minBriefChars) warnings.push(tr(`brief 偏短(建议 ≥${CFG.minBriefChars} 字),它是给人读的计划说明`, `brief is short (suggested ≥${CFG.minBriefChars} characters); it is the plan description people read`))
|
|
2830
3450
|
const goal = state.goal !== null && state.goal.status === 'open' ? state.goal : null
|
|
@@ -2836,7 +3456,7 @@ export function apply(ctx, config = {}) {
|
|
|
2836
3456
|
goal: goal?.id ?? null,
|
|
2837
3457
|
phase_id: goal?.id ?? null,
|
|
2838
3458
|
brief,
|
|
2839
|
-
steps: args.steps.map((step) => ({ id: step.id, do: step.do, artifacts: step.artifacts ?? [], done_criteria: step.done_criteria, tests: resolvedTests.get(step.id) ?? null })),
|
|
3459
|
+
steps: args.steps.map((step) => ({ id: step.id, do: step.do, artifacts: step.artifacts ?? [], done_criteria: step.done_criteria, tests: resolvedTests.get(step.id) ?? null, ...(typeof step.expect === 'string' && step.expect.trim() !== '' ? { expect: step.expect.trim() } : {}), ...resolvedExtras.get(step.id) })),
|
|
2840
3460
|
})
|
|
2841
3461
|
return done({
|
|
2842
3462
|
ok: true,
|
|
@@ -2855,13 +3475,15 @@ export function apply(ctx, config = {}) {
|
|
|
2855
3475
|
defineTool({
|
|
2856
3476
|
name: 'RevisePlan',
|
|
2857
3477
|
description:
|
|
2858
|
-
'改当前计划,不动进度(返回 progress_changed=false)
|
|
3478
|
+
'改当前计划,不动进度(返回 progress_changed=false),四种动作:`action="expect"` 为尚未执行的步骤写下预测(给 `step_id` 与 `expect`,或按候选假设给 `predictions`;须在执行前写,预测落空时才能被发现);`action="add"` 补一步(漏了活就补上,给 `step`);`action="refine"` 精化一步的判定标准(给 `step_id` 与新的 `done_criteria`,旧判据留在日志里);`action="void"` 带因作废一步(给 `step_id` 与 `reason`:发现某步本不该存在就作废并说明缘由——作废留痕光明正大,为凑完成而造证是大忌;已交付的步不能作废)。',
|
|
2859
3479
|
parameters: {
|
|
2860
3480
|
type: 'object',
|
|
2861
3481
|
properties: {
|
|
2862
|
-
action: { type: 'string', enum: ['add', 'refine', 'void'], description: 'add=补一步;refine=改判据;void=带因作废' },
|
|
3482
|
+
action: { type: 'string', enum: ['expect', 'add', 'refine', 'void'], description: 'expect=写预测;add=补一步;refine=改判据;void=带因作废' },
|
|
2863
3483
|
step: { ...STEP_SCHEMA, description: 'action=add:新步' },
|
|
2864
|
-
step_id: { type: 'string', description: 'action=refine / void:哪一步' },
|
|
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 二者至少给一个' },
|
|
2865
3487
|
done_criteria: { type: 'string', description: 'action=refine:新的判定标准' },
|
|
2866
3488
|
reason: { type: 'string', description: '为什么改(action=void 必填)' },
|
|
2867
3489
|
},
|
|
@@ -2884,14 +3506,26 @@ export function apply(ctx, config = {}) {
|
|
|
2884
3506
|
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}`))
|
|
2885
3507
|
const resolved = resolveTests(state.hypotheses, args.step.tests)
|
|
2886
3508
|
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))
|
|
2887
|
-
const
|
|
3509
|
+
const extras = resolveStepExtras(state, args.step)
|
|
3510
|
+
if (extras.ok !== true) return fail(extras.code, extras.message)
|
|
3511
|
+
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 }
|
|
2888
3512
|
mutations.push({ t: 'plan/amended', plan: plan.id, step: amended })
|
|
2889
3513
|
if (plan.blocked !== undefined) mutations.push({ t: 'block/cleared', plan: plan.id, step: plan.blocked.step })
|
|
2890
3514
|
return done({ ok: true, code: 'plan_amended', progress_changed: false, message: tr(`已补一步 ${args.step.id}(进度不变)。`, `Added step ${args.step.id} (progress unchanged).`) })
|
|
2891
3515
|
}
|
|
2892
|
-
if (
|
|
3516
|
+
if (!['expect', 'refine', 'void'].includes(args.action)) return fail('unknown_action', tr('action 只能是 expect / add / refine / void。', 'action must be expect, add, refine or void.'))
|
|
2893
3517
|
const step = plan.steps.find((item) => item.id === args.step_id)
|
|
2894
3518
|
if (step === undefined) return fail('unknown_step', tr(`没有这一步:${args.step_id}`, `No such step: ${args.step_id}`))
|
|
3519
|
+
if (args.action === 'expect') {
|
|
3520
|
+
if (step.status !== 'open') return fail('step_settled', tr(`步骤 ${step.id} 已结束(${step.status}):预测须在执行前写下。`, `Step ${step.id} is settled (${step.status}); expectations are written before acting.`))
|
|
3521
|
+
const expect = String(args.expect ?? '').trim()
|
|
3522
|
+
const extras = resolveStepExtras(state, { id: step.id, predictions: args.predictions })
|
|
3523
|
+
if (extras.ok !== true) return fail(extras.code, extras.message)
|
|
3524
|
+
const predictions = extras.extra.predictions ?? []
|
|
3525
|
+
if (expect.length < 4 && predictions.length === 0) return fail('expect_required', tr('预测不能为空:写明预计观察到什么及其来源;或按候选假设分别填写 predictions。', 'The expectation cannot be empty: say what you expect to see and where that comes from, or write predictions per candidate hypothesis.'))
|
|
3526
|
+
mutations.push({ t: 'step/expected', plan: plan.id, step: step.id, ...(expect.length >= 4 ? { expect } : {}), ...(predictions.length > 0 ? { predictions } : {}) })
|
|
3527
|
+
return done({ ok: true, code: 'step_expected', progress_changed: false, message: tr(`步骤 ${step.id} 的预测已记录。交付时将结果与之对照,不符之处写入 AdvancePlan 的 anomalies。`, `Expectation recorded for step ${step.id}. When you deliver, compare the result with it: whatever does not match goes in AdvancePlan's anomalies.`) })
|
|
3528
|
+
}
|
|
2895
3529
|
if (args.action === 'refine') {
|
|
2896
3530
|
if (step.status !== 'open') return fail('step_settled', tr(`步骤 ${step.id} 已落定(${step.status}),判据不再可改。`, `Step ${step.id} is settled (${step.status}); its criteria can no longer change.`))
|
|
2897
3531
|
const criteria = String(args.done_criteria ?? '').trim()
|
|
@@ -2959,7 +3593,7 @@ export function apply(ctx, config = {}) {
|
|
|
2959
3593
|
defineTool({
|
|
2960
3594
|
name: 'AdvancePlan',
|
|
2961
3595
|
description:
|
|
2962
|
-
'交付一步(唯一完成动词)
|
|
3596
|
+
'交付一步(唯一完成动词):把观测交上来。系统先做观测准入——声明的产物存在、非空、结构合法;准入只看收不收,不做裁决。交付成立这一步就完成——它检验的判断被支持、被推翻还是说不清,**都算完成**,结果单独记成证据。结果与预测不符之处写进 anomalies。L2(自判)由你给 basis(交付成立的依据,必须能被复查)与 results(这一步检验的每条判断各一格);L3 以上两项都由系统派独立评估者判,你写 results 会被拒绝。没有物证,就还没有完成——没有手动标记这回事。',
|
|
2963
3597
|
parameters: {
|
|
2964
3598
|
type: 'object',
|
|
2965
3599
|
properties: {
|
|
@@ -2969,10 +3603,15 @@ export function apply(ctx, config = {}) {
|
|
|
2969
3603
|
description: '观测:这一步拿到的原始结果(相对 workspace 的路径 + 一句说明)',
|
|
2970
3604
|
items: { type: 'object', properties: { ref: { type: 'string' }, note: { type: 'string' } }, required: ['ref'], additionalProperties: false },
|
|
2971
3605
|
},
|
|
2972
|
-
|
|
3606
|
+
anomalies: {
|
|
3607
|
+
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 },
|
|
3610
|
+
},
|
|
3611
|
+
basis: { type: 'string', description: '交付成立的依据:引用了哪个产物里的哪个事实(必须可复查)。仅自判(L2)由你写' },
|
|
2973
3612
|
results: {
|
|
2974
3613
|
type: 'array',
|
|
2975
|
-
description: '
|
|
3614
|
+
description: '仅自判(L2):这一步检验的每条判断各一格,对照它的推翻条件读结果:没碰到推翻条件是「支持」,碰到了是「推翻」,这次观测区分不了是「不确定」。推翻和不确定都不妨碍这一步完成',
|
|
2976
3615
|
items: {
|
|
2977
3616
|
type: 'object',
|
|
2978
3617
|
properties: {
|
|
@@ -3042,8 +3681,16 @@ export function apply(ctx, config = {}) {
|
|
|
3042
3681
|
accepted.push({ id: materialId, ref })
|
|
3043
3682
|
}
|
|
3044
3683
|
|
|
3684
|
+
/**
|
|
3685
|
+
* 未解释项在准入**之前**就落账(走独立通道):它是观测时的发现,交付成没成都不该丢。
|
|
3686
|
+
* 这一次登记的也随交付交给评估者(见 `evaluatorPrompt`)。
|
|
3687
|
+
*/
|
|
3688
|
+
const opened = openAnomalies(sessionId, args.anomalies, { step: step.id, by: 'model' })
|
|
3689
|
+
mutations.push(...opened)
|
|
3690
|
+
|
|
3045
3691
|
// ② 准入
|
|
3046
3692
|
const gate = admission(cwd, step)
|
|
3693
|
+
gate.anomalies = opened
|
|
3047
3694
|
mutations.push({
|
|
3048
3695
|
t: 'admission/checked',
|
|
3049
3696
|
step: step.id,
|
|
@@ -3095,8 +3742,8 @@ export function apply(ctx, config = {}) {
|
|
|
3095
3742
|
if (releaseTarget !== null && !releaseTarget.released) {
|
|
3096
3743
|
const asked = await askHuman(exec, {
|
|
3097
3744
|
id: `release-${step.id}`,
|
|
3098
|
-
header: tr('L4
|
|
3099
|
-
question: tr(`步骤 ${step.id}(${clip(step.do, 60)})
|
|
3745
|
+
header: tr('L4 须经人工批准', 'L4 needs approval'),
|
|
3746
|
+
question: tr(`步骤 ${step.id}(${clip(step.do, 60)})属于 L4:新产生的、不可重复或来自外部的证据。是否批准此次交付?`, `Step ${step.id} (${clip(step.do, 60)}) is L4: new, unrepeatable or external evidence. Release this delivery?`),
|
|
3100
3747
|
detail: tr(`判据:${step.done_criteria}`, `Criteria: ${step.done_criteria}`),
|
|
3101
3748
|
options: [
|
|
3102
3749
|
{ label: choiceLabel('releaseYes'), description: tr('交给独立评估者判。', 'Hand it to the independent evaluator.') },
|
|
@@ -3107,8 +3754,8 @@ export function apply(ctx, config = {}) {
|
|
|
3107
3754
|
const why = asked.ok !== true ? unanswered(asked) : tr(`人选了「${asked.choice ?? '没选'}」${asked.note === null ? '' : `:${asked.note}`}`, `the person chose "${asked.choice ?? 'nothing'}"${asked.note === null ? '' : `: ${asked.note}`}`)
|
|
3108
3755
|
return fail(
|
|
3109
3756
|
'human_release_missing',
|
|
3110
|
-
tr(`L4
|
|
3111
|
-
(asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`步骤 ${step.id} 是 L4
|
|
3757
|
+
tr(`L4 的交付须经人工批准,本次未获批准(${why})。等级是事实的属性,批准是人的行为,不能推断。`, `An L4 delivery needs a person to release it, and this one was not released (${why}). The level is a property of the fact; release is a person's act and cannot be inferred. `) +
|
|
3758
|
+
(asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`步骤 ${step.id} 是 L4,等待人工批准。`, `Step ${step.id} is L4 and waits for a person to release it.`))),
|
|
3112
3759
|
mutations.length > 0 ? { mutations } : {},
|
|
3113
3760
|
)
|
|
3114
3761
|
}
|
|
@@ -3127,12 +3774,21 @@ export function apply(ctx, config = {}) {
|
|
|
3127
3774
|
let auditSessionId = null
|
|
3128
3775
|
/** 复用说明(模型与人都看得到的那一句);不复用时为空串。 */
|
|
3129
3776
|
let reuseNote = ''
|
|
3777
|
+
/** 评估者报的、做的人没登记的异常(折法把它们记成未解释项)。 */
|
|
3778
|
+
let foundByEvaluator = []
|
|
3130
3779
|
if (levelIndex > SELF_JUDGE_MAX_INDEX) {
|
|
3131
3780
|
if (Array.isArray(args.results) && args.results.length > 0) {
|
|
3132
3781
|
return fail('verdict_not_accepted', tr(`${level} 的两项裁决只能由机器或独立评估者写:做的人不判自己。去掉 results 重新交付,系统会派评估者。`, `At ${level}, both verdicts can only be written by a machine check or an independent evaluator; the worker does not judge itself. Deliver again without results and the system will dispatch an evaluator.`))
|
|
3133
3782
|
}
|
|
3783
|
+
/** 评估者能跑命令之后,收下的产物在评估前后必须一字不差:改过就不认这份裁决。 */
|
|
3784
|
+
const digestsOf = () => gate.confirmed.map((item) => (readableCwd ? sha256File(isAbsolute(item.ref) ? item.ref : resolvePath(cwd, item.ref)) : null)).join('|')
|
|
3785
|
+
const beforeAudit = CFG.auditRerun ? digestsOf() : ''
|
|
3134
3786
|
const audit = await runEvaluator(sessionId, exec.agent, plan, step, gate, 'evidence_audit', exec.signal)
|
|
3135
3787
|
mutations.push(...audit.mutations)
|
|
3788
|
+
foundByEvaluator = audit.reused === true ? [] : Array.isArray(audit.anomalies) ? audit.anomalies : []
|
|
3789
|
+
if (CFG.auditRerun && audit.reused !== true && ['yes', 'no', 'unclear'].includes(audit.holds) && digestsOf() !== beforeAudit) {
|
|
3790
|
+
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 })
|
|
3791
|
+
}
|
|
3136
3792
|
if (audit.holds === 'pending') return fail('audit_pending', tr(`独立评估者仍在跑:${plainIds(sessionId, audit.basis)}。先观察当前事实,再谈重试——不要重复派遣。`, `The independent evaluator is still running: ${plainIds(sessionId, audit.basis)}. Look at the current facts before retrying; do not dispatch again.`), { mutations })
|
|
3137
3793
|
if (audit.holds === 'unknown') {
|
|
3138
3794
|
const count = countBlock('audit_unavailable', audit.basis)
|
|
@@ -3184,7 +3840,7 @@ export function apply(ctx, config = {}) {
|
|
|
3184
3840
|
}
|
|
3185
3841
|
} else {
|
|
3186
3842
|
if (typeof args.basis !== 'string' || args.basis.trim().length < 8) {
|
|
3187
|
-
return fail('basis_required', tr(`${level ?? '未声明等级'}
|
|
3843
|
+
return fail('basis_required', tr(`${level ?? '未声明等级'} 的交付由你自己判:写清交付成立的依据(basis)——引用了哪个产物里的哪个事实,必须能被复查。`, `At ${level ?? 'an undeclared level'} you judge the delivery yourself: write why it holds (basis), citing which fact in which output, so it can be checked.`))
|
|
3188
3844
|
}
|
|
3189
3845
|
const given = Array.isArray(args.results) ? args.results : []
|
|
3190
3846
|
const byId = new Map()
|
|
@@ -3287,6 +3943,7 @@ export function apply(ctx, config = {}) {
|
|
|
3287
3943
|
message:
|
|
3288
3944
|
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)'}.`) +
|
|
3289
3945
|
outcome +
|
|
3946
|
+
expectationNote(step, opened, foundByEvaluator) +
|
|
3290
3947
|
(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.') : '') +
|
|
3291
3948
|
factReview +
|
|
3292
3949
|
reuseNote,
|
|
@@ -3294,6 +3951,67 @@ export function apply(ctx, config = {}) {
|
|
|
3294
3951
|
},
|
|
3295
3952
|
})
|
|
3296
3953
|
|
|
3954
|
+
/**
|
|
3955
|
+
* ═══ 未解释项:登记与消解 ═══
|
|
3956
|
+
*
|
|
3957
|
+
* 失分最多的不是「没核」,而是**看见了异常却把它解释过去**(温度计偏 8 °C 被判成「两次读数存疑」)。
|
|
3958
|
+
* 所以未解释项是一等状态:登记了就挂在卡上,只有三个去处——被一条判断或关系解释、写明理由排除、交给人。
|
|
3959
|
+
* 它不阻塞结案,但结案时随交付交给评估者,由评估者判它动不动摇结论。
|
|
3960
|
+
*/
|
|
3961
|
+
const ANOMALY_OUTCOMES = ['explained', 'ruled_out', 'escalated']
|
|
3962
|
+
defineTool({
|
|
3963
|
+
name: 'Anomaly',
|
|
3964
|
+
description:
|
|
3965
|
+
'未解释项(反常):与预测或本体不符的观测、无法解释的读数。`action="open"` 登记一条(给 `what`,可选 `anchor`);`action="resolve"` 给它一个去处(给 `id`、`outcome` 与 `reason`):explained = 被一条判断、关系或新查到的原因解释了(`by` 写是哪条);ruled_out = 写明理由排除(比如证实是录入错误);escalated = 交给人。不要为了让卡干净而排除:评估者会核排除的理由。',
|
|
3966
|
+
parameters: {
|
|
3967
|
+
type: 'object',
|
|
3968
|
+
properties: {
|
|
3969
|
+
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,可选:解释它的那条判断、关系或事实' },
|
|
3977
|
+
},
|
|
3978
|
+
required: ['action'],
|
|
3979
|
+
additionalProperties: false,
|
|
3980
|
+
},
|
|
3981
|
+
output: CARD_OUTPUT,
|
|
3982
|
+
async execute(args, exec) {
|
|
3983
|
+
const call = open(exec)
|
|
3984
|
+
if (call.ok !== true) return call.response
|
|
3985
|
+
const { hostService, sessionId, state, mutations } = call
|
|
3986
|
+
const done = finish(hostService, sessionId, mutations)
|
|
3987
|
+
if (args.action === 'open') {
|
|
3988
|
+
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.'))
|
|
3990
|
+
mutations.push(...opened)
|
|
3991
|
+
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
|
+
}
|
|
3993
|
+
if (args.action !== 'resolve') return fail('unknown_action', tr('action 只能是 open / resolve。', 'action must be open or resolve.'))
|
|
3994
|
+
const wanted = String(args.id ?? '').trim()
|
|
3995
|
+
const known = (state.anomalies ?? []).filter((item) => item.status === 'open')
|
|
3996
|
+
const target = known.find((item) => item.id === wanted) ?? (wanted.length >= 3 ? known.filter((item) => item.id.startsWith(wanted)) : []).at(0)
|
|
3997
|
+
if (target === undefined) return fail('unknown_anomaly', tr(`没有这条开着的未解释:${wanted || '(没给 id)'}。开着的:${known.map((item) => `${item.id}(${clip(item.what, 30)})`).join('、') || '(没有)'}`, `No open unexplained item ${wanted || '(no id given)'}. Open ones: ${known.map((item) => `${item.id} (${clip(item.what, 30)})`).join(', ') || '(none)'}`))
|
|
3998
|
+
if (!ANOMALY_OUTCOMES.includes(args.outcome)) return fail('outcome_required', tr('outcome 只能是 explained / ruled_out / escalated。', 'outcome must be explained, ruled_out or escalated.'))
|
|
3999
|
+
const reason = String(args.reason ?? '').trim()
|
|
4000
|
+
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
|
+
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) }) })
|
|
4003
|
+
const word = { explained: tr('已解释', 'explained'), ruled_out: tr('已排除', 'ruled out'), escalated: tr('交给人', 'handed to a person') }[args.outcome]
|
|
4004
|
+
return done({
|
|
4005
|
+
ok: true,
|
|
4006
|
+
code: 'anomaly_resolved',
|
|
4007
|
+
message:
|
|
4008
|
+
tr(`${target.id}:${word}。`, `${target.id}: ${word}.`) +
|
|
4009
|
+
(args.outcome === 'explained' ? tr('这条解释如果改变了判断或计划,现在就改(Frame / RevisePlan);它说的若是一条一般规律,写进本体的关系。', ' If this explanation changes a judgment or the plan, change it now (Frame / RevisePlan); if it states a general regularity, write it into the ontology as a relation.') : '') +
|
|
4010
|
+
(args.outcome === 'escalated' ? tr('它会随交付交给评估者与人。', ' It goes with the delivery to the evaluator and the person.') : ''),
|
|
4011
|
+
})
|
|
4012
|
+
},
|
|
4013
|
+
})
|
|
4014
|
+
|
|
3297
4015
|
/**
|
|
3298
4016
|
* ═══ 当档(人在场 / 无人值守):人的事实,内核负责下发 ═══
|
|
3299
4017
|
*
|
|
@@ -3352,6 +4070,26 @@ export function apply(ctx, config = {}) {
|
|
|
3352
4070
|
* 为什么在文件里而不是只留在账本:别的会话与模型读的都是 `clear/knowledge/facts/`,
|
|
3353
4071
|
* 撤回过的若还原样躺在那里,下一轮会照旧引用一条已经作废的事实。
|
|
3354
4072
|
*/
|
|
4073
|
+
/**
|
|
4074
|
+
* 按事实 id 找一条事实:先看本会话的账,再看工作区里的事实文件(别的会话留下的)。
|
|
4075
|
+
* 找不到返回 null。读文件而不是只读同步进来的快照:Frame 那一拍的同步可能还没跑。
|
|
4076
|
+
*/
|
|
4077
|
+
function findFact(sessionId, state, id) {
|
|
4078
|
+
const key = String(id ?? '').trim()
|
|
4079
|
+
if (!/^[A-Za-z0-9_-]+$/.test(key)) return null
|
|
4080
|
+
const own = (state.facts ?? []).find((fact) => fact.id === key)
|
|
4081
|
+
if (own !== undefined) return own
|
|
4082
|
+
const cwd = sessionCwd(sessionId)
|
|
4083
|
+
if (cwd === null) return null
|
|
4084
|
+
try {
|
|
4085
|
+
const data = JSON.parse(readFileSync(join(cwd, 'clear', 'knowledge', 'facts', `${key}.json`), 'utf8'))
|
|
4086
|
+
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 }
|
|
4088
|
+
} catch {
|
|
4089
|
+
return null
|
|
4090
|
+
}
|
|
4091
|
+
}
|
|
4092
|
+
|
|
3355
4093
|
function markFactReviewed(cwd, fact, review) {
|
|
3356
4094
|
if (cwd === null || cwd === undefined || !/^[A-Za-z0-9_-]+$/.test(String(fact?.id ?? ''))) return null
|
|
3357
4095
|
const file = join(cwd, 'clear', 'knowledge', 'facts', `${fact.id}.json`)
|
|
@@ -3414,7 +4152,7 @@ export function apply(ctx, config = {}) {
|
|
|
3414
4152
|
* `ontology` 里**模型可写**的是三支本体目录(`concepts` / `relations` / `entities`);
|
|
3415
4153
|
* 字段定义 `SCHEMA.json` 与过程本体那份货架仍归系统。
|
|
3416
4154
|
*/
|
|
3417
|
-
const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'goals'], ['clear', 'ontology']]
|
|
4155
|
+
const PROTECTED_REL = [['clear', 'evidence'], ['clear', 'knowledge', 'facts'], ['clear', 'knowledge', 'lessons'], ['clear', 'goals'], ['clear', 'ontology']]
|
|
3418
4156
|
const OPEN_REL = ONTOLOGY_BRANCH_DIRS.map((branch) => ['clear', 'ontology', branch])
|
|
3419
4157
|
|
|
3420
4158
|
/** 工作区内的相对路径(正斜杠);在工作区外或取不到工作区返回 null。 */
|
|
@@ -3510,6 +4248,43 @@ export function apply(ctx, config = {}) {
|
|
|
3510
4248
|
}
|
|
3511
4249
|
|
|
3512
4250
|
|
|
4251
|
+
/**
|
|
4252
|
+
* **不可逆动作的人放行(L4),拦在命令上**。
|
|
4253
|
+
*
|
|
4254
|
+
* 从前那道门挂在 L4 步骤的交付上,而不可逆的动作往往就是一条命令:模型直接跑了它,
|
|
4255
|
+
* 门形同虚设。所以 Frame 里声明的不可逆动作(命令特征)在**执行之前**就问人:放行才跑,
|
|
4256
|
+
* 没放行或没人能答就拒。放行落一条 `human/released`;当前步是 L4 的,这次放行也算它的放行。
|
|
4257
|
+
* 返回 null = 放行(或与不可逆动作无关)。
|
|
4258
|
+
*/
|
|
4259
|
+
async function releaseIrreversible(exec, sessionId, state, command) {
|
|
4260
|
+
if (!CFG.l4RequiresHumanRelease || state?.goal === null || state?.goal === undefined || state.goal.status !== 'open') return null
|
|
4261
|
+
const action = (Array.isArray(state.goal.irreversible) ? state.goal.irreversible : []).find((item) => typeof item?.command === 'string' && item.command !== '' && command.includes(item.command))
|
|
4262
|
+
if (action === undefined) return null
|
|
4263
|
+
const plan = activePlanOf(state)
|
|
4264
|
+
const step = firstOpenStep(plan)
|
|
4265
|
+
const asked = await askHuman(exec, {
|
|
4266
|
+
id: `release-cmd-${String(exec.callId ?? Date.now().toString(36))}`,
|
|
4267
|
+
header: tr('不可逆动作须经人工批准', 'Irreversible action needs approval'),
|
|
4268
|
+
question: tr(`此命令属于已声明的不可逆动作「${clip(action.action, 60)}」。是否批准执行?`, `This command is a declared irreversible action ("${clip(action.action, 60)}"). Release it?`),
|
|
4269
|
+
detail: clip(command, 300),
|
|
4270
|
+
options: [
|
|
4271
|
+
{ label: choiceLabel('releaseCommand'), description: tr('让它执行。', 'Let it run.') },
|
|
4272
|
+
{ label: choiceLabel('releaseNo'), description: tr('不执行,模型停下等你。', 'Do not run it; the model stops and waits for you.') },
|
|
4273
|
+
],
|
|
4274
|
+
})
|
|
4275
|
+
if (asked.ok === true && chose(asked, 'releaseCommand')) {
|
|
4276
|
+
landFact(sessionId, { t: 'human/released', id: `r-${Math.random().toString(36).slice(2, 8)}`, plan: plan?.id ?? null, step: step !== null && levelIndexOf(step.tests?.level) === 4 ? step.id : null, action: action.action, call: String(exec.callId ?? ''), via: 'ask', note: asked.note })
|
|
4277
|
+
return null
|
|
4278
|
+
}
|
|
4279
|
+
const why = asked.ok !== true ? unanswered(asked) : tr(`人选了「${asked.choice ?? '没选'}」${asked.note === null ? '' : `:${asked.note}`}`, `the person chose "${asked.choice ?? 'nothing'}"${asked.note === null ? '' : `: ${asked.note}`}`)
|
|
4280
|
+
return {
|
|
4281
|
+
kind: 'deny',
|
|
4282
|
+
reason:
|
|
4283
|
+
tr(`「${action.action}」是不可逆动作,本次未获批准(${why})。不要改写命令以绕过此限制:等待人工批准,或修改计划。`, `"${action.action}" is irreversible and was not released this time (${why}). Do not rewrite the command to get around this: wait for a person, or change the plan.`) +
|
|
4284
|
+
(asked.ok === true ? '' : blockNativeGoal(exec.agent, BLOCK_CODES.needsHuman, tr(`不可逆动作「${action.action}」等待人工批准。`, `The irreversible action "${action.action}" waits for a person to release it.`))),
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
|
|
3513
4288
|
ctx.on('tools/pre-execute', (exec, next) => (exec.agent === undefined ? next() : inLanguage(languageOf(String(exec.agent.id)), () => guardTool(exec, next))))
|
|
3514
4289
|
async function guardTool(exec, next) {
|
|
3515
4290
|
{
|
|
@@ -3549,7 +4324,7 @@ export function apply(ctx, config = {}) {
|
|
|
3549
4324
|
if (suspect !== null) {
|
|
3550
4325
|
return {
|
|
3551
4326
|
kind: 'deny',
|
|
3552
|
-
reason: tr(`${suspect} 由系统所有,做的人不能写(clear/evidence、clear/knowledge/facts、clear/goals、clear/ontology 的 SCHEMA.json 与货架)
|
|
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.`),
|
|
3553
4328
|
}
|
|
3554
4329
|
}
|
|
3555
4330
|
if (writing && hostService !== undefined) {
|
|
@@ -3564,6 +4339,10 @@ export function apply(ctx, config = {}) {
|
|
|
3564
4339
|
if (test(args.command)) return { kind: 'deny', reason: tr(`危险的 bash 命令(${reason[0]}):改写命令避开这种写法(dangerous bash command)`, `dangerous bash command (${reason[1]}); rewrite the command to avoid this pattern`) }
|
|
3565
4340
|
}
|
|
3566
4341
|
}
|
|
4342
|
+
if (owned && exec.name === 'bash' && typeof args.command === 'string') {
|
|
4343
|
+
const denied = await releaseIrreversible(exec, sessionId, state, args.command)
|
|
4344
|
+
if (denied !== null) return denied
|
|
4345
|
+
}
|
|
3567
4346
|
}
|
|
3568
4347
|
return next()
|
|
3569
4348
|
}
|
|
@@ -3811,12 +4590,18 @@ export function apply(ctx, config = {}) {
|
|
|
3811
4590
|
artifacts: 'What counts as proof: concrete output file paths relative to the workspace (a directory is not proof)',
|
|
3812
4591
|
done_criteria: 'Criterion: written before the result exists, and checkable',
|
|
3813
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)',
|
|
3814
4599
|
}
|
|
3815
4600
|
const prefixed = (prefix, table) => Object.fromEntries(Object.entries(table).map(([key, value]) => [`${prefix}${key}`, value]))
|
|
3816
4601
|
const TOOL_TEXT_EN = {
|
|
3817
4602
|
Frame: {
|
|
3818
4603
|
description:
|
|
3819
|
-
'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. Only one goal is open at a time; it spans plans, and each plan carries one phase of it.',
|
|
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.',
|
|
3820
4605
|
params: {
|
|
3821
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',
|
|
3822
4607
|
claim: 'Goal: the question the project answers (may be long; where identity and criteria attach)',
|
|
@@ -3826,24 +4611,53 @@ export function apply(ctx, config = {}) {
|
|
|
3826
4611
|
criteria_note: 'Background for the criteria (not part of the verdict; only explains why)',
|
|
3827
4612
|
criteria_verdict: 'Independent verdict auditKey required when changing the criteria text: "what counts as done" cannot be changed in passing',
|
|
3828
4613
|
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")',
|
|
3829
4617
|
hypotheses:
|
|
3830
|
-
'Candidate judgments: each a one-sentence claim plus a refutation condition; 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.',
|
|
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.',
|
|
3831
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',
|
|
3832
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)}',
|
|
3833
4634
|
reason: 'Required when revising the goal: one sentence on why (not needed the first time)',
|
|
3834
4635
|
},
|
|
3835
4636
|
},
|
|
3836
4637
|
Conclude: {
|
|
3837
4638
|
description:
|
|
3838
|
-
'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,
|
|
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.',
|
|
3839
4640
|
params: {
|
|
3840
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)',
|
|
3841
4649
|
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)',
|
|
4655
|
+
'lessons.items.boundary': 'When it does not apply',
|
|
3842
4656
|
},
|
|
3843
4657
|
},
|
|
3844
4658
|
CreatePlan: {
|
|
3845
4659
|
description:
|
|
3846
|
-
'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). 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.',
|
|
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.',
|
|
3847
4661
|
params: {
|
|
3848
4662
|
brief: `Plan description for people (Markdown, suggested ≥${MIN_BRIEF_CHARS} characters, at least two ## sections)`,
|
|
3849
4663
|
...prefixed('steps.items.', STEP_TEXT_EN),
|
|
@@ -3851,12 +4665,14 @@ export function apply(ctx, config = {}) {
|
|
|
3851
4665
|
},
|
|
3852
4666
|
RevisePlan: {
|
|
3853
4667
|
description:
|
|
3854
|
-
'Change the current plan without moving progress (returns progress_changed=false).
|
|
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).',
|
|
3855
4669
|
params: {
|
|
3856
|
-
action: 'add = add a step; refine = change the criterion; void = void with a reason',
|
|
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',
|
|
3857
4673
|
step: 'action=add: the new step',
|
|
3858
4674
|
...prefixed('step.', STEP_TEXT_EN),
|
|
3859
|
-
step_id: 'action=refine / void: which step',
|
|
4675
|
+
step_id: 'action=expect / refine / void: which step',
|
|
3860
4676
|
done_criteria: 'action=refine: the new criterion',
|
|
3861
4677
|
reason: 'Why (required for action=void)',
|
|
3862
4678
|
},
|
|
@@ -3867,18 +4683,35 @@ export function apply(ctx, config = {}) {
|
|
|
3867
4683
|
},
|
|
3868
4684
|
AdvancePlan: {
|
|
3869
4685
|
description:
|
|
3870
|
-
'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. At
|
|
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.',
|
|
3871
4687
|
params: {
|
|
3872
4688
|
step_id: 'Which step to deliver (only the first unsettled step; this confirms against slips, it does not select)',
|
|
3873
4689
|
observations: 'Observations: the raw results of this step (path relative to the workspace plus one sentence)',
|
|
3874
|
-
|
|
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)',
|
|
3875
4695
|
results:
|
|
3876
|
-
'
|
|
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',
|
|
3877
4697
|
'results.items.hypothesis': 'Short name of the judgment (claim text also works)',
|
|
3878
4698
|
'results.items.basis': 'One sentence: what this observation shows against the refutation condition (defaults to the basis above)',
|
|
3879
4699
|
},
|
|
3880
4700
|
},
|
|
3881
4701
|
}
|
|
4702
|
+
TOOL_TEXT_EN.Anomaly = {
|
|
4703
|
+
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.',
|
|
4705
|
+
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',
|
|
4713
|
+
},
|
|
4714
|
+
}
|
|
3882
4715
|
/** 按路径把英文说明写进一份参数 schema 的副本。 */
|
|
3883
4716
|
function englishTool(tool) {
|
|
3884
4717
|
const text = TOOL_TEXT_EN[tool.name]
|