/** * `conditions` — the instrumented wrapper the executor agents call to record what * they established on the device. Replaces the old `spec-delta` wrapper; see the * header of shared/src/conditions.ts for why the record was inverted from * "deviations" to "conditions". * * Each invocation appends exactly one line to `/Conditions.jsonl`. * The agent never edits that file by hand, and never edits TestSpec.md — this * tool is the only write path, which is what makes the record trustworthy enough * to feed back into future spec drafting. * * Two verbs: * record — one condition (repeat as many times as needed) * done — close out the round; prints a summary and complains if the round * recorded nothing, which is nearly always a miss rather than a run * with genuinely zero preconditions. * * Callable directly (`bun bin/conditions.ts record …`) or as the satellite * bundle's `conditions` subcommand (see satellite/src/entry.ts), so a deployed * node runs the same version of this code as the runner that reads it back. */ import { existsSync, mkdirSync, appendFileSync, readFileSync } from "node:fs"; import path from "node:path"; import { CONDITIONS_FILE, CONDITIONS_SCHEMA_VERSION, CONDITION_KINDS, CONDITION_KIND_LABEL, SPEC_AGREEMENT_LABEL, conditionStats, matchKind, newConditionId, normalizeKbLabels, parseConditions, type ConditionEntry, type ConditionKind, type ConditionVerdict, type SpecAgreement, } from "../shared/src/conditions"; function parseArgs(argv: string[]): Record { const out: Record = {}; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (!a.startsWith("--")) continue; const key = a.slice(2); const next = argv[i + 1]; if (next == null || next.startsWith("--")) { out[key] = "true"; } else { out[key] = next; i++; } } return out; } function die(code: number, msg: string): never { process.stderr.write(msg.endsWith("\n") ? msg : msg + "\n"); process.exit(code); } /** A flag the parser filled with the placeholder "true" carries no real value. */ function val(args: Record, key: string): string | null { const v = args[key]; if (v == null || v === "true") return null; const t = v.trim(); return t ? t : null; } /** * Resolve the workspace directory. Tolerates being handed the `evidence/` * subdirectory — the agent has been trained by `record-evidence` to pass that * path, and bouncing it here would just cost a round trip for no reason. */ function workspaceDir(args: Record): string { const raw = val(args, "dir") || process.env.CONDITIONS_DIR || process.env.SPEC_DELTA_DIR || ""; if (!raw) die(2, "缺少 --dir <工作区目录>(或设置 $CONDITIONS_DIR)"); let dir = path.resolve(raw); if (path.basename(dir) === "evidence") dir = path.dirname(dir); if (!existsSync(dir)) die(2, `工作区目录不存在:${dir}`); return dir; } function resolveRound(args: Record): number { const raw = val(args, "round") || process.env.CONDITIONS_ROUND || process.env.SPEC_DELTA_ROUND || ""; const n = Number(raw); if (!Number.isFinite(n) || n < 1) { die(2, "缺少或非法的 --round <轮次>(或设置 $CONDITIONS_ROUND),应为 >= 1 的整数"); } return Math.floor(n); } const filePath = (dir: string) => path.join(dir, CONDITIONS_FILE); function append(dir: string, entry: ConditionEntry): void { mkdirSync(dir, { recursive: true }); appendFileSync(filePath(dir), JSON.stringify(entry) + "\n", "utf8"); } function readExisting(dir: string): ConditionEntry[] { const f = filePath(dir); if (!existsSync(f)) return []; try { return parseConditions(readFileSync(f, "utf8")); } catch { return []; } } const KIND_HELP = CONDITION_KINDS.map((k) => ` ${k.padEnd(12)} ${CONDITION_KIND_LABEL[k]}`).join("\n"); const USAGE = "用法:\n" + ` conditions record --kind <${CONDITION_KINDS.join("|")}> --scope "<业务模块>" --subject "<这条讲哪件事>" --statement "<条件是什么>" \\\n` + ` [--spec ] [--spec-said ""] \\\n` + " [--payload ''] [--evidence ] [--assumed]\n" + " conditions done # 本轮记录完毕,打印汇总\n\n" + "kind 可用值:\n" + KIND_HELP + "\n"; // ── commands ──────────────────────────────────────────────────────────────── function cmdRecord(args: Record): never { const dir = workspaceDir(args); const round = resolveRound(args); const statement = val(args, "statement"); if (!statement) die(2, `缺少 --statement "<条件是什么>"(写成将来别人能直接照做的形式)`); const scope = val(args, "scope"); if (!scope) die(2, `缺少 --scope "<业务模块>"(如 "Story 相机";要稳定、可复用,别写成本任务专有的描述)`); const subject = val(args, "subject"); if (!subject) { die(2, `缺少 --subject "<这条讲哪件事>"(如 "特效面板入口路径";同一件事在不同任务里必须写成同一个 subject)`); } const rawKind = val(args, "kind"); const kind: ConditionKind | null = matchKind(rawKind); if (!kind) { die(2, `缺少或无法识别的 --kind「${rawKind ?? ""}」。可用值:\n${KIND_HELP}`); } // How the drafted spec fared. Defaults to `absent` — the honest default when the // agent doesn't say, since "the spec never mentioned this" is both the most // common case and the one that understates rather than overstates spec quality. const rawSpec = val(args, "spec"); let spec: SpecAgreement = "absent"; if (rawSpec) { if (rawSpec === "predicted" || rawSpec === "contradicted" || rawSpec === "absent") { spec = rawSpec; } else { process.stderr.write(`⚠️ 无法识别的 --spec「${rawSpec}」,按 absent 记录。可用值:predicted / contradicted / absent\n`); } } const specSaid = val(args, "spec-said") || val(args, "specSaid"); if (spec === "contradicted" && !specSaid) { process.stderr.write("⚠️ --spec contradicted 建议同时给 --spec-said \"\",否则事后无法复盘 spec 错在哪。\n"); } let payload: Record | undefined; const rawPayload = val(args, "payload"); if (rawPayload) { try { const p = JSON.parse(rawPayload) as unknown; if (p && typeof p === "object" && !Array.isArray(p)) payload = p as Record; else process.stderr.write("⚠️ --payload 需要是一个 JSON 对象,已忽略。\n"); } catch { process.stderr.write("⚠️ --payload 不是合法 JSON,已忽略。\n"); } } const evidence = val(args, "evidence"); if (evidence) { const f = path.join(dir, "evidence", evidence.replace(/^evidence\//, "")); if (!existsSync(f)) { process.stderr.write(`⚠️ 证据文件不存在:${f}(本条仍会记录,但报告里会是死链)\n`); } } // Default `verified`: this tool is called from a real-device session, so the // common case is something actually exercised. `--assumed` is the explicit // downgrade for "I read this off the code but didn't run it". const verdict: ConditionVerdict = args.assumed ? "assumed" : "verified"; // Which injected knowledge this condition speaks about. A label the prompt // never showed is dropped with a warning rather than stored: the attribution // loop resolves labels by POSITION in that run's injected list, so a made-up // K9 would not fail — it would silently settle whichever claim happens to sit // at index 8, which is worse than recording no link at all. const kb = normalizeKbLabels([val(args, "kb") ?? ""]); const rawKb = val(args, "kb"); if (rawKb && !kb.length) { process.stderr.write(`⚠️ 无法识别的 --kb「${rawKb}」,已忽略。应为 prompt 里出现过的编号,如 --kb K1 或 --kb K1,K3\n`); } const entry: ConditionEntry = { v: CONDITIONS_SCHEMA_VERSION, ts: Date.now(), id: newConditionId(), round, source: "agent", kind, scope, subject, statement, ...(payload ? { payload } : {}), verdict, spec, ...(specSaid ? { specSaid } : {}), ...(evidence ? { evidence } : {}), ...(kb.length ? { kb } : {}), }; append(dir, entry); process.stdout.write( `✅ 已记录条件(round ${round}):[${CONDITION_KIND_LABEL[kind]}] ${scope} › ${subject}\n` + ` ${statement}\n` + ` ${verdict === "verified" ? "真机已验证" : "仅推断未验证"} · ${SPEC_AGREEMENT_LABEL[spec]}` + (kb.length ? ` · 关联知识 ${kb.join(",")}` : "") + "\n", ); process.exit(0); } function cmdDone(args: Record): never { const dir = workspaceDir(args); const round = resolveRound(args); const all = readExisting(dir); const mine = all.filter((e) => e.round === round); if (!mine.length) { // Not an error exit: failing here would tempt the agent into skipping the // tool entirely. But say plainly that this is almost certainly a miss. process.stdout.write( `⚠️ round ${round} 没有记录任何执行条件。\n` + " 几乎每次执行都至少有账号、构建方式、入口路径这类前置条件 —— 一条都没有,\n" + " 通常意味着漏记了,而不是真的没有。请回看本轮实际做了什么,补记后再执行 done。\n", ); process.exit(0); } const st = conditionStats(mine); const kinds = st.byKind.map((k) => `${CONDITION_KIND_LABEL[k.kind]}×${k.count}`).join(" · "); const specs = st.bySpec.map((s) => `${SPEC_AGREEMENT_LABEL[s.spec]}×${s.count}`).join(" · "); process.stdout.write( `✅ round ${round} 共记录 ${mine.length} 条执行条件(真机验证 ${st.verified} · 推断 ${st.assumed})\n` + ` 分类:${kinds}\n` + ` spec 命中:${specs}\n`, ); process.exit(0); } /** * CLI entry, callable two ways — directly (`bun bin/conditions.ts record …`) or as * the satellite bundle's `conditions` subcommand via satellite/src/entry.ts. */ export async function runConditions(argv: string[]): Promise { const sub = argv[0]; const args = parseArgs(argv.slice(1)); switch (sub) { case "record": case "add": return cmdRecord(args); case "done": case "confirm": return cmdDone(args); case "-h": case "--help": case undefined: return die(sub ? 0 : 2, USAGE); default: return die(2, `未知子命令「${sub}」\n\n${USAGE}`); } } if (import.meta.main) await runConditions(process.argv.slice(2));