/** * ============================================================ * manualSchema.ts —— 应用说明书 schema v2:解析、校验、摘要 * ------------------------------------------------------------ * 说明书文件(`plugins//app/.md`)是**两层**结构: * * frontmatter 机器层 —— 引擎读它做匹配、不可逆判定、前置条件校验 * 正文 散文层 —— 给模型看的界面布局、控件语义、坑与恢复出口 * * 一个文件而不是两个,是因为第三件事同样重要:**agent 要能自己改**。 * 改 md 正文的一节是一次 Edit;改一份深层嵌套的 YAML 缩进是模型的高频 * 出错点。让它们共处一文件,agent 补充实测发现时不必碰机器层。 * * ★ v2 **向后兼容 v1**:v1 只有 `match` 与 `irreversible`(字符串数组)。 * 兼容不是好心 —— 它让「搬家」「换解析器」「升级内容」成为三步各自可 * 验证的动作,出问题时能一眼定位是哪一步。 * * ★ 每个条目自带 `verified`。渲染时**必须**把未验证如实标出来:说明书里 * 写的坐标和控件多数没实机验证过,丢掉这个限定词,模型会把猜测当事实。 * ============================================================ */ import { parse } from 'yaml'; import { containsFold, findByElementSpec, flattenAx, matchesRole, type AxSearchNode, } from './axSearch.js'; // ============================================================ // 类型 // ============================================================ /** 相对坐标矩形 [x, y, width, height],0–1000。 */ export type ManualRect = [number, number, number, number]; export interface ManualRegion { id: string; rect?: ManualRect; desc?: string; verified: boolean; } export interface ManualControl { id: string; /** 无障碍锚点。比坐标稳定得多,优先用它。 */ ax?: { role?: string; name?: string[] }; rect?: ManualRect; desc?: string; verified: boolean; } export interface ManualFlowStep { do: string; /** 引擎可独立验证的前置条件(见 PRECONDITION_PREDICATES)。 */ precondition?: string; /** 这一步会造成不可撤销的后果。 */ irreversible?: boolean; /** * 这一步属于本说明书 `irreversible:` 清单里的哪一类(如 `intent:send-message`)。 * * 它是把「作者写下的前置条件」和「引擎正在审批的这一次动作」对上号的**唯一 * 桥梁**:没有它,引擎只知道「模型正要做一件不可撤销的事」,不知道是哪一件, * 于是只能把整份说明书里所有不可逆步骤的前置条件一起检查(旧实现就是这样, * 见 `unmetPreconditionsFor` 头注)。 * * ★ 刻意与 `irreversible` **分成两个字段**,而不是把 `irreversible` 做成 * `boolean | string`。「是不是不可逆」和「属于哪一类」是两个正交事实: * 合成一个字段后,YAML 里写 `irreversible: intent:send-message` 与 * `irreversible: true` 需要解析器分支判别,人改说明书时也极容易把类别名 * 写成布尔(`irreversible: send-message` 是合法 YAML 字符串,不会报错)。 */ actionClass?: string; } export interface ManualFlow { id: string; goal?: string; steps: ManualFlowStep[]; pitfalls: string[]; verified: boolean; } export interface ManualVerification { environment?: string; verifiedAt?: string; verifiedItems: string[]; unverifiedItems: string[]; } /** 说明书的机器层。正文另存(见 AppGuide.body)。 */ /** * 应用自己声明的「该叫人来」信号。 * * 内核只认识**跨应用成立**的通用信号(密码框、验证码、二维码登录、权限弹窗…), * 那些靠正则扫 AX 文本就能判。但有些应用的边界只有它自己知道 —— 典型例子: * macOS 微信的登录小窗**不暴露「扫码登录」四个字**,AX 里只有「二维码」和 * 「仅传输文件」两个控件,得靠这两个一起出现才能判定,而单独一个「二维码」 * 可能只是聊天里别人发的图。 * * ⚠️ 这类知识**必须住在说明书里**。此前它是写死在 `humanBoundary.ts` 里的一段 * `/com\.tencent\.xinWeChat/` 判断 —— 通用内核里出现一个具体应用的 bundleId, * 等于「加一个应用就要改一次内核」,与「drop 一份说明书即扩展能力」的架构相反。 * * 语义:`allOf` 里的每条正则都要在 AX 节点的 `role name` 文本里命中,才算成立。 * 全部命中 → 按 `reason` 报人工介入。用 allOf 而不是单条,正是因为单个信号 * (「二维码」)容易误判。 */ export interface ManualHumanBoundary { /** 复用内核的 HumanInterventionReason 取值,如 qr_login / login / captcha。 */ reason: string; /** 给用户看的一句话。 */ summary: string; /** 全部命中才成立的正则(对 AX 的 `role name` 文本逐条 test)。 */ allOf: string[]; } export interface AppManual { schemaVersion: number; layout: ManualRegion[]; controls: ManualControl[]; flows: ManualFlow[]; /** 应用专属的人工介入信号,见 {@link ManualHumanBoundary}。 */ humanBoundary: ManualHumanBoundary[]; verification?: ManualVerification; } /** 「没有任何 v2 声明」的 manual。v1 说明书与合成 guide 都用它。 */ export const EMPTY_MANUAL: AppManual = { schemaVersion: 1, layout: [], controls: [], flows: [], humanBoundary: [], }; export interface ManualIssue { /** 'error' 会让条目被丢弃;'warn' 只是提醒。 */ level: 'error' | 'warn'; message: string; } // ============================================================ // 前置条件:只允许引擎能独立验证的谓词 // ============================================================ /** * 可用谓词。**刻意只有这几个** —— 每一个都能只用「当前这次观测」求值, * 不需要任何外部变量绑定。 * * 写不成这几种形状的约束(「确认收件人是本人要发的那个」)请写进 * `pitfalls` 当散文。把不可验证的东西写成 `precondition:` 会得到一个 * 永远通过的检查 —— 那比没有检查更糟,因为它看起来像有保护。 */ export const PRECONDITION_PREDICATES = [ /** 前台应用的 id 或名字包含给定文本(大小写不敏感) */ 'foreground_app_is', /** 任一窗口标题包含给定文本 */ 'window_title_contains', /** 当前焦点控件的 role 等于给定值 */ 'focused_role_is', /** 无障碍树可用且不残缺(没有参数) */ 'ax_available', /** 存在 role 为给定值的控件;可写 `role:名字片段` 追加名字约束 */ 'element_exists', ] as const; export type PreconditionPredicate = (typeof PRECONDITION_PREDICATES)[number]; const NO_ARG_PREDICATES = new Set(['ax_available']); export interface ParsedPrecondition { predicate: PreconditionPredicate; argument: string; } /** 解析一条前置条件。形状不合法返回 null —— 由调用方按「无效声明」报出。 */ export function parsePrecondition(raw: string): ParsedPrecondition | null { const trimmed = raw.trim(); const spaceIndex = trimmed.indexOf(' '); const head = spaceIndex < 0 ? trimmed : trimmed.slice(0, spaceIndex); const argument = spaceIndex < 0 ? '' : trimmed.slice(spaceIndex + 1).trim(); if (!(PRECONDITION_PREDICATES as readonly string[]).includes(head)) return null; const predicate = head as PreconditionPredicate; if (NO_ARG_PREDICATES.has(predicate)) return { predicate, argument: '' }; if (!argument) return null; return { predicate, argument }; } /** * 求值一条前置条件。 * * 三值而不是布尔:**「不满足」和「看不出来」必须分开**。前者是拒绝的理由, * 后者只能放行 —— 微信这类应用的 AX 树常常整棵是空的,把「拿不到信息」 * 当成「条件不成立」会让模型在一个它无力自证的条件上永远卡死。 */ export type PreconditionResult = true | false | 'unknown'; /** 求值所需的最小观测形状。刻意不绑 ComputerState,便于单测。 */ export interface PreconditionState { activeApp?: { id?: string; name?: string }; windows?: { title?: string }[]; accessibility?: { truncated?: boolean; root?: AxSearchNode; }; } export function evaluatePrecondition( raw: string, state: PreconditionState | undefined, ): PreconditionResult { const parsed = parsePrecondition(raw); // 解析不出来的谓词不能当成「不满足」—— 那是说明书写错了,不是现场不对。 // `validateManual` 会把它报成 error,这里放行。 if (!parsed || !state) return 'unknown'; const axUsable = state.accessibility !== undefined && state.accessibility.truncated !== true; const nodes = axUsable ? flattenAx(state.accessibility?.root) : []; switch (parsed.predicate) { case 'foreground_app_is': { const app = state.activeApp; if (!app?.id && !app?.name) return 'unknown'; return containsFold(app.id, parsed.argument) || containsFold(app.name, parsed.argument); } case 'window_title_contains': { const titles = (state.windows ?? []).map((w) => w.title).filter(Boolean); if (titles.length === 0) return 'unknown'; return titles.some((title) => containsFold(title, parsed.argument)); } case 'ax_available': return axUsable; case 'focused_role_is': { if (!axUsable) return 'unknown'; const focused = nodes.find((node) => node.focused === true); if (!focused) return 'unknown'; return matchesRole(focused, parsed.argument); } case 'element_exists': // ⚠️ AX 不可用时必须是 `unknown` 而不是 `false`。写成 // `axUsable && find(...)` 会把「看不见」判成「不存在」—— 那正是本函数 // 三值设计要防的那件事,而且写起来很自然,所以特意留这条注释。 if (!axUsable) return 'unknown'; // 与 wait_for_element / click-by-text 共用同一套查找(axSearch.ts)—— // 三者判据分叉会让「前提说成立、等待等不到」这类问题无从排查。 return findByElementSpec(nodes, parsed.argument).length > 0; default: return 'unknown'; } } /** 一条没能满足的前置条件,带出处(哪条流程的第几步)。 */ export interface UnmetPrecondition { flowId: string; stepIndex: number; step: string; precondition: string; } /** * 收集**指定动作类别**下没能满足的前置条件。 * * ★ 这个函数早先叫 `unmetIrreversiblePreconditions`,扫的是**整份说明书里所有 * 不可逆步骤**,并在注释里声称「模型正要做一件不可撤销的事,检查所有不可逆 * 步骤的前置条件,映射是精确的,不是猜的」。**那句话是错的。** 引擎并不知道 * 模型在执行哪条 flow:微信的「发消息」和「加好友」都是不可逆步骤,模型要发 * 消息时却会连「加好友」那一步的前提一起检查。今天没爆,只是因为微信四条不 * 可逆步骤的 precondition 碰巧全都是同一条(`foreground_app_is 微信`)—— * 任何一份说明书给两类动作写了不同前提,立刻就会出现误拦,而误拦会让模型卡在 * 一个它无力改变的条件上。 * * 现在的桥梁是 `step.actionClass`:审批时引擎已经算出了这次动作的**有效类别** * (见 `computeruse.ts::_authorizeIrreversibleAction` 的三级来源),拿它去挑 * 步骤,映射才真的是精确的。 * * 匹配只看 `actionClass` 相等,不再额外要求 `irreversible === true` —— 「有类别 * 却不是不可逆步骤」是说明书写错了,由 `validateManual` 报成 error,不在这里 * 二次判定(两处各判一次,迟早给出不一致的答案)。 * * 同一类别可以有多条 precondition(写在不同 flow 的不同步骤上),**全部检查、 * 全部必须成立**:它们是同一件事的不同前提,不是备选项。 * * 只返回**明确为 false** 的那些;`unknown` 一律放行(理由见 `evaluatePrecondition`)。 */ export function unmetPreconditionsFor( manual: AppManual, actionClass: string | undefined, state: PreconditionState | undefined, ): UnmetPrecondition[] { // 没有有效类别就一条都不查。这不是防御性编程,是语义:类别对不上的时候 // 我们**确实不知道**作者的哪条前提该管这次动作,凭空拦是猜。 if (!actionClass) return []; const unmet: UnmetPrecondition[] = []; for (const flow of manual.flows) { for (const [index, step] of flow.steps.entries()) { if (step.actionClass !== actionClass || !step.precondition) continue; if (evaluatePrecondition(step.precondition, state) !== false) continue; unmet.push({ flowId: flow.id, stepIndex: index + 1, step: step.do, precondition: step.precondition, }); } } return unmet; } // ============================================================ // 解析 // ============================================================ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/; export interface SplitManual { raw: Record; body: string; } /** * 切开 frontmatter 与正文。 * * 解析失败返回空 frontmatter 而**不是**抛错:一份写坏的说明书应该退化成 * 「这个应用没有说明书」,而不是让整个 ComputerUse 工具挂掉。写坏的事实 * 由 `validateManual` 报出来(`/computeruse app ` 能看到)。 */ export function splitManual(content: string): SplitManual { const match = FRONTMATTER.exec(content); if (!match) return { raw: {}, body: content.trim() }; const body = content.slice(match[0].length).trim(); try { const parsed = parse(match[1]!) as unknown; return { raw: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record) : {}, body, }; } catch { return { raw: {}, body }; } } const asString = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; const asStringList = (value: unknown): string[] => { if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean); const single = asString(value); return single ? [single] : []; }; const asBool = (value: unknown): boolean | undefined => typeof value === 'boolean' ? value : undefined; function asRect(value: unknown): ManualRect | undefined { if (!Array.isArray(value) || value.length !== 4) return undefined; const nums = value.map((n) => Number(n)); if (nums.some((n) => !Number.isFinite(n))) return undefined; return [nums[0]!, nums[1]!, nums[2]!, nums[3]!]; } const asRecord = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; /** * 归一化不可逆声明。v1 是字符串(`intent:send-message`),v2 允许写成 * 映射(`- key: Enter`)—— 后者对人更好读,对 YAML 更自然。两种都归一成 * 引擎既有的 `kind:value` 字符串,因为 `matchIrreversible` 认的是那个形状, * 而它不该为了书写风格改判定逻辑。 */ export function normalizeIrreversible(value: unknown): string[] { if (!Array.isArray(value)) return asStringList(value); const out: string[] = []; for (const entry of value) { if (typeof entry === 'string') { const trimmed = entry.trim(); if (trimmed) out.push(trimmed); continue; } for (const [kind, raw] of Object.entries(asRecord(entry))) { const argument = asString(raw); if (argument) out.push(`${kind}:${argument}`); } } return out; } /** * 归一化不可逆声明,并提取 critical 级别的条目。 * * 支持三种 frontmatter 写法: * 1. 旧格式一维列表 → 全部入 all,critical 为空(由全局黑名单事后兜底) * 2. 新格式带分级对象({critical: [...], normal: [...]}) * 3. 混合:一维列表里既有字符串也有带 critical/normal 键的映射 * * 返回值: * all —— 全部不可逆条目(去重) * critical —— 应用明确标为高危的条目(all 的子集) */ export function normalizeIrreversibleWithLevels(value: unknown): { all: string[]; critical: string[]; } { if (value == null) return { all: [], critical: [] }; const allSet = new Set(); const criticalSet = new Set(); // 情形 2:值本身是一个带 critical/normal 键的对象 if (typeof value === 'object' && !Array.isArray(value)) { const rec = asRecord(value); const criticalRaw = rec.critical; const normalRaw = rec.normal; for (const entry of normalizeIrreversible(criticalRaw)) { allSet.add(entry); criticalSet.add(entry); } for (const entry of normalizeIrreversible(normalRaw)) { allSet.add(entry); } return { all: [...allSet], critical: [...criticalSet] }; } // 情形 1 + 3:值是数组(或能转成数组的字符串) const arr = Array.isArray(value) ? value : [value]; for (const entry of arr) { if (typeof entry === 'string') { const trimmed = entry.trim(); if (trimmed) allSet.add(trimmed); continue; } if (entry && typeof entry === 'object') { const rec = asRecord(entry); // 带 critical/normal 键的映射条目 if ('critical' in rec || 'normal' in rec) { for (const e of normalizeIrreversible(rec.critical)) { allSet.add(e); criticalSet.add(e); } for (const e of normalizeIrreversible(rec.normal)) { allSet.add(e); } } else { // 普通的 key:value 映射条目(旧格式的另一种写法) for (const e of normalizeIrreversible([entry])) { allSet.add(e); } } } } return { all: [...allSet], critical: [...criticalSet] }; } export function toAppManual(raw: Record): AppManual { const schemaVersion = Number(raw.schemaVersion) || 1; const layout: ManualRegion[] = []; for (const entry of Array.isArray(raw.layout) ? raw.layout : []) { const record = asRecord(entry); const id = asString(record.id); if (!id) continue; layout.push({ id, ...(asRect(record.rect) ? { rect: asRect(record.rect)! } : {}), ...(asString(record.desc) ? { desc: asString(record.desc)! } : {}), verified: asBool(record.verified) ?? false, }); } const controls: ManualControl[] = []; for (const entry of Array.isArray(raw.controls) ? raw.controls : []) { const record = asRecord(entry); const id = asString(record.id); if (!id) continue; const ax = asRecord(record.ax); const role = asString(ax.role); const names = asStringList(ax.name); controls.push({ id, ...(role || names.length > 0 ? { ax: { ...(role ? { role } : {}), ...(names.length > 0 ? { name: names } : {}) } } : {}), ...(asRect(record.rect) ? { rect: asRect(record.rect)! } : {}), ...(asString(record.desc) ? { desc: asString(record.desc)! } : {}), verified: asBool(record.verified) ?? false, }); } const flows: ManualFlow[] = []; for (const [id, value] of Object.entries(asRecord(raw.flows))) { const record = asRecord(value); const steps: ManualFlowStep[] = []; for (const step of Array.isArray(record.steps) ? record.steps : []) { const stepRecord = asRecord(step); const action = asString(stepRecord.do); if (!action) continue; steps.push({ do: action, ...(asString(stepRecord.precondition) ? { precondition: asString(stepRecord.precondition)! } : {}), ...(asBool(stepRecord.irreversible) ? { irreversible: true } : {}), ...(asString(stepRecord.actionClass) ? { actionClass: asString(stepRecord.actionClass)! } : {}), }); } flows.push({ id, ...(asString(record.goal) ? { goal: asString(record.goal)! } : {}), steps, pitfalls: asStringList(record.pitfalls), verified: asBool(record.verified) ?? false, }); } // 应用专属的人工介入信号。写坏了就跳过(与其它段一致:静默失效比崩掉更糟, // 所以 validateManual 会另外把它报成 issue,让作者看得见)。 // ⚠️ **缺字段的条目不静默丢弃。** // // 丢掉它等于「作者写了一条,引擎当它不存在,谁都不知道」—— 正是 validateManual // 存在要防的那类静默失效。这里原样收下,由 validateManual 报成 error; // 运行时那边(humanBoundary.ts)本来就要求 allOf 全部命中,空 allOf 的条目 // `every` 恒真会误报,所以下面顺带把它挡在 `allOf.length > 0` 之后。 const humanBoundary: ManualHumanBoundary[] = []; for (const entry of Array.isArray(raw.humanBoundary) ? raw.humanBoundary : []) { const record = asRecord(entry); humanBoundary.push({ reason: asString(record.reason) ?? '', summary: asString(record.summary) ?? asString(record.reason) ?? '', allOf: asStringList(record.allOf), }); } const verificationRaw = asRecord(raw.verification); const verification: ManualVerification | undefined = Object.keys(verificationRaw).length > 0 ? { ...(asString(verificationRaw.environment) ? { environment: asString(verificationRaw.environment)! } : {}), ...(asString(verificationRaw.verifiedAt) ? { verifiedAt: asString(verificationRaw.verifiedAt)! } : {}), verifiedItems: asStringList(verificationRaw.verifiedItems), unverifiedItems: asStringList(verificationRaw.unverifiedItems), } : undefined; return { schemaVersion, layout, controls, flows, humanBoundary, ...(verification ? { verification } : {}), }; } // ============================================================ // 校验 // ============================================================ const IRREVERSIBLE_SHAPE = /^(key|region|intent):.+/; /** * `humanBoundary[].reason` 的合法取值,与 `humanIntervention.ts::HumanInterventionReason` 对齐。 * * ⚠️ 这里是**字符串副本**而不是 import 那个类型:说明书是运行时数据,类型在运行时 * 不存在,必须有一份能真的拿来比对的值表。两边漂移的代价是「说明书写了个宿主不认识的 * reason,加载期不报、运行期宿主收到也不认识」——`manualSchema.test.ts` 用一条断言 * 把两份表钉在一起。 */ const HUMAN_INTERVENTION_REASONS = new Set([ 'password', 'otp', 'captcha', 'qr_login', 'login', 'permission', 'security_warning', 'blocked', 'manual', ]); /** * 校验一份说明书。**这是 `/computeruse app ` 的产出**,也是防止 * 「写了声明但引擎认不出」这类静默失效的唯一手段 —— 写错格式不会报错, * 只会永远不命中。 */ export function validateManual(input: { manual: AppManual; irreversible: string[]; identifiers: number; }): ManualIssue[] { const issues: ManualIssue[] = []; if (input.identifiers === 0) { issues.push({ level: 'error', message: '没有任何 match 声明,这份说明书永远匹配不上' }); } for (const entry of input.irreversible) { if (!IRREVERSIBLE_SHAPE.test(entry)) { issues.push({ level: 'error', message: `不可逆声明「${entry}」格式不合法(要 key:/region:/intent: 开头)` }); } } // ── 应用专属的人工介入信号 ── // // 这一段是**引擎自己用**的(不进模型上下文),所以写错了在界面上完全看不出来: // 该叫人的时候不叫,任务就一路错下去。三类错都必须在这里拦住。 for (const [index, boundary] of input.manual.humanBoundary.entries()) { const where = `humanBoundary[${index}]`; if (!boundary.reason) { issues.push({ level: 'error', message: `${where} 缺 reason,这条声明永远不会生效` }); } else if (!HUMAN_INTERVENTION_REASONS.has(boundary.reason)) { issues.push({ level: 'error', message: `${where} 的 reason「${boundary.reason}」不是合法取值` + `(可选:${[...HUMAN_INTERVENTION_REASONS].join(' / ')})`, }); } if (boundary.allOf.length === 0) { issues.push({ level: 'error', message: `${where} 的 allOf 为空 —— 空条件恒成立,会把正常界面误报成需要人工介入` }); } for (const pattern of boundary.allOf) { try { new RegExp(pattern, 'i'); } catch (error) { // 坏正则在运行时被 catch 成「不成立」——**永远不触发且不报错**, // 是这一段最危险的失效方式,必须在加载期就红。 issues.push({ level: 'error', message: `${where} 的正则「${pattern}」编译失败(${String((error as Error).message).slice(0, 60)}),这条声明永远不会命中`, }); } } if (boundary.allOf.length === 1) { // 单信号极易误判:微信的「二维码」单独出现可能只是聊天里别人发的图, // 正是因此才要求「二维码」+「仅传输文件」两个一起。 issues.push({ level: 'warn', message: `${where} 只声明了一个信号 —— 单个关键词很容易把正常界面误判成人工介入边界,建议再加一个共现条件`, }); } } for (const region of input.manual.layout) { if (region.rect && region.rect.some((n) => n < 0 || n > 1000)) { issues.push({ level: 'error', message: `分区 ${region.id} 的 rect 超出 0–1000 相对坐标范围` }); } } for (const control of input.manual.controls) { if (!control.ax && !control.rect) { issues.push({ level: 'warn', message: `控件 ${control.id} 既没有 ax 锚点也没有 rect,模型无从定位` }); } if (control.rect && !control.ax) { issues.push({ level: 'warn', message: `控件 ${control.id} 只有坐标没有 ax 锚点 —— 换版本或换窗口尺寸就会失准` }); } } for (const flow of input.manual.flows) { if (flow.steps.length === 0) { issues.push({ level: 'warn', message: `流程 ${flow.id} 没有任何步骤` }); } for (const [index, step] of flow.steps.entries()) { const where = `流程 ${flow.id} 第 ${index + 1} 步`; // ① 类别只对不可逆步骤有意义:审批链只在判定「这一步不可撤销」之后才去 // 挑步骤,可逆步骤上的类别永远不会被读到,写了等于自欺。 if (step.actionClass && step.irreversible !== true) { issues.push({ level: 'error', message: `${where}声明了 actionClass「${step.actionClass}」却没有 irreversible: true` + ' —— 动作类别只对不可逆步骤有意义,可逆步骤上的类别引擎永远读不到', }); } // ② 不可逆步骤写了 precondition 却没有类别 = **写了但不会生效**。 // 这正是本次修复要根治的静默失效:作者以为自己加了一道防线, // 引擎却因为对不上号而从不检查它。 if (step.irreversible === true && step.precondition && !step.actionClass) { issues.push({ level: 'warn', message: `${where}是不可逆步骤且写了 precondition,但没有 actionClass —— ` + '引擎无从知道这条前提该管哪一次动作,**这条前置条件不会生效**;' + `请补一个来自本说明书 irreversible: 清单的类别名` + `(现有:${input.irreversible.join(' / ') || '(清单为空)'})`, }); } // ③ 类别必须来自本说明书的 irreversible: 清单。拼错一个字符就永远不命中, // 而不命中是**静默**的 —— 与 IRREVERSIBLE_SHAPE 那条校验同一个理由。 if (step.actionClass && !input.irreversible.includes(step.actionClass)) { issues.push({ level: 'error', message: `${where}的 actionClass「${step.actionClass}」不在本说明书的 irreversible: 清单里` + `(清单:${input.irreversible.join(' / ') || '空'}),永远不会命中,写了也是静默失效`, }); } // ④ 同一 actionClass 出现多条 precondition 是**允许**的,不报。 // 它们是同一类动作的不同前提(`unmetPreconditionsFor` 全部检查、 // 全部必须成立),不是重复声明。 if (!step.precondition) continue; if (!parsePrecondition(step.precondition)) { issues.push({ level: 'error', message: `${where}的 precondition「${step.precondition}」不是引擎能验证的谓词` + `(可用:${PRECONDITION_PREDICATES.join(' / ')})`, }); } } } return issues; } // ============================================================ // 实测回写(`/computeruse verify` 用) // ============================================================ /** * 把某条 flow 的 `verified` 翻成 true。**行级编辑,不重新序列化 YAML。** * * 用 `yaml` 库 parse → 改 → stringify 会把 frontmatter 里的注释全部抹掉,而 * 那些注释恰恰是说明书里最难重建的部分(「为什么这里不写坐标」「这条声明 * 是干什么的」)。只改目标那一行,其余字节不动。 * * 找不到目标(没有这条 flow / 它没有 verified 行 / 已经是 true)时返回 null, * 由调用方如实报告 —— 静默返回原文会让人以为写成功了。 */ export function markFlowVerified(markdown: string, flowId: string): string | null { const lines = markdown.split('\n'); const fenceEnds: number[] = []; for (const [index, line] of lines.entries()) { if (line.trim() === '---') fenceEnds.push(index); if (fenceEnds.length === 2) break; } if (fenceEnds.length < 2 || fenceEnds[0] !== 0) return null; const [, end] = fenceEnds as [number, number]; const flowsAt = lines.findIndex((line, index) => index < end && /^flows:\s*$/.test(line)); if (flowsAt < 0) return null; const flowAt = lines.findIndex((line, index) => index > flowsAt && index < end && line.trimEnd() === ` ${flowId}:`); if (flowAt < 0) return null; for (let index = flowAt + 1; index < end; index += 1) { const line = lines[index]!; // 缩进回到 2 格或更少 = 这条 flow 的块结束了 if (line.trim() && !/^\s{3,}/.test(line)) break; const match = /^(\s+)verified:\s*false\s*$/.exec(line); if (match) { lines[index] = `${match[1]}verified: true`; return lines.join('\n'); } } return null; } /** 实测记录小节的标题。写死是因为两端(capture 模板与 verify 回写)必须对齐。 */ export const FIELD_NOTES_HEADING = '## 实测记录'; /** * 往 `## 实测记录` 里追加几行。 * * 追加而不是覆盖:这一节是**时间序列**,「上次能用这次不能用」本身就是信息。 * 占位行 `- (暂无)` 会被第一次真实记录顶掉。 */ export function appendFieldNotes(markdown: string, notes: string[]): string { if (notes.length === 0) return markdown; const lines = markdown.split('\n'); const headingAt = lines.findIndex((line) => line.trim() === FIELD_NOTES_HEADING); if (headingAt < 0) { return [markdown.trimEnd(), '', FIELD_NOTES_HEADING, '', ...notes, ''].join('\n'); } // 找这一节的末尾:下一个 `## ` 标题,或文件结束。 let end = lines.length; for (let index = headingAt + 1; index < lines.length; index += 1) { if (/^## /.test(lines[index]!)) { end = index; break; } } const section = lines.slice(headingAt, end).filter((line) => line.trim() !== '- (暂无)'); while (section.length > 0 && section[section.length - 1]!.trim() === '') section.pop(); return [...lines.slice(0, headingAt), ...section, ...notes, '', ...lines.slice(end)].join('\n'); } // ============================================================ // 摘要渲染(注入用) // ============================================================ /** 未验证条目的统一标注。短,但不能省 —— 省了就等于把猜测说成事实。 */ const UNVERIFIED = '(未实机验证)'; function renderIrreversible(entries: string[]): string[] { if (entries.length === 0) return []; const checkable = entries.filter((e) => e.startsWith('key:') || e.startsWith('region:')); return [ '不可逆动作:' + entries.join('、'), checkable.length === 0 ? ' ⚠️ 以上全靠你自报 `intent:"submit"` 才能触发确认 —— 你不报,引擎就拦不住。' : ` 其中 ${checkable.length} 条引擎可独立验证。`, ]; } function renderLayout(regions: ManualRegion[]): string[] { if (regions.length === 0) return []; return ['界面分区:' + regions .map((r) => `${r.id}${r.rect ? `(${r.rect.join(',')})` : ''}${r.desc ? `=${r.desc}` : ''}${r.verified ? '' : UNVERIFIED}`) .join('、')]; } function renderControls(controls: ManualControl[]): string[] { if (controls.length === 0) return []; return ['关键控件:', ...controls.map((c) => { const anchor = c.ax ? `AX ${c.ax.role ?? '?'}${c.ax.name?.length ? ` 名称∈[${c.ax.name.join('|')}]` : ''}` : c.rect ? `坐标(${c.rect.join(',')})` : '无锚点'; return ` - ${c.id}:${c.desc ?? ''} → ${anchor}${c.verified ? '' : UNVERIFIED}`; })]; } function renderFlow(flow: ManualFlow, withPitfalls: boolean): string[] { const lines = [` ▸ ${flow.id}${flow.goal ? `:${flow.goal}` : ''}${flow.verified ? '' : UNVERIFIED}`]; for (const [index, step] of flow.steps.entries()) { const marks = [ step.irreversible ? '【不可逆】' : '', // 类别必须渲染出来:模型得知道这一步该自报哪个 actionClass,才能拿到 // 精确到这一类的授权与前置条件检查。不给它看,它只能瞎猜或干脆不报。 step.actionClass ? `【类别:${step.actionClass}】` : '', step.precondition ? `【前置:${step.precondition}】` : '', ].join(''); lines.push(` ${index + 1}. ${step.do}${marks}`); } if (withPitfalls) { for (const pitfall of flow.pitfalls) lines.push(` ⚠ ${pitfall}`); } return lines; } export interface ManualDigest { text: string; /** 因预算被丢弃的内容类别,如实报出。 */ dropped: string[]; } /** * 渲染注入用摘要,带确定性的降级阶梯。 * * 阶梯顺序照抄 `prompts/skillList.ts` 的语义:**先丢细节、再丢条目**。 * 理由相同 —— 一个只剩名字的条目仍然完成了「让模型知道它存在」的使命, * 整条丢弃则让它彻底隐身。丢了什么必须说出来,不静默截断。 */ export function renderManualDigest(input: { name: string; path: string; manual: AppManual; irreversible: string[]; matchedBy: string; budgetChars?: number; }): ManualDigest { const budget = input.budgetChars ?? 4_000; const header = [ `已匹配应用说明书 **${input.name}**(依据 ${input.matchedBy}):${input.path}`, ]; const verification = input.manual.verification; if (verification) { header.push( ` 验证状态:已验证 ${verification.verifiedItems.join('/') || '无'}` + ` · 未验证 ${verification.unverifiedItems.join('/') || '无'}` + (verification.environment ? ` · 环境 ${verification.environment}` : ''), ); } const irreversible = renderIrreversible(input.irreversible); const flowsFull = input.manual.flows.length > 0 ? ['典型流程:', ...input.manual.flows.flatMap((f) => renderFlow(f, true))] : []; const flowsNoPitfalls = input.manual.flows.length > 0 ? ['典型流程:', ...input.manual.flows.flatMap((f) => renderFlow(f, false))] : []; const flowsNamesOnly = input.manual.flows.length > 0 ? ['典型流程(仅名录,细节见文件):' + input.manual.flows.map((f) => f.id).join('、')] : []; const layout = renderLayout(input.manual.layout); const controls = renderControls(input.manual.controls); const ladder: { lines: string[]; dropped: string[] }[] = [ { lines: [...header, ...irreversible, ...layout, ...controls, ...flowsFull], dropped: [] }, { lines: [...header, ...irreversible, ...layout, ...controls, ...flowsNoPitfalls], dropped: ['流程中的坑'] }, { lines: [...header, ...irreversible, ...controls, ...flowsNoPitfalls], dropped: ['流程中的坑', '界面分区'] }, { lines: [...header, ...irreversible, ...flowsNamesOnly], dropped: ['流程中的坑', '界面分区', '关键控件', '流程步骤'] }, { lines: [...header, ...irreversible], dropped: ['界面分区', '关键控件', '典型流程'] }, ]; for (const level of ladder) { // 省略说明本身也算进预算 —— 否则「降级」会在最后一档反而把总长度顶回去。 const notice = level.dropped.length > 0 ? `\n (受预算限制,本次省略:${level.dropped.join('、')}。完整内容 Read 上面那个文件。)` : ''; const text = level.lines.join('\n') + notice; if (text.length <= budget || level === ladder[ladder.length - 1]) { return { text, dropped: level.dropped }; } } // 不可达:上面的循环在最后一档必定返回。 return { text: header.join('\n'), dropped: [] }; }