#!/usr/bin/env bun /** * record-evidence — the instrumented wrapper the fix/feature agents call INSTEAD * of driving devices by hand. It owns the capture lifecycle and writes one * structured line per attempt to `/manifest.jsonl`, so a capture * that ends too early, runs too long, or comes out empty leaves a diagnosable * trail instead of just a missing/bad file. See shared/src/evidence_capture.ts * for the manifest shape, the ffprobe thresholds, and the pass/warn/fail verdict * (the SSOT this shares with the monitoring Portal). * * TWO DEVICE BACKENDS, one command surface, chosen by the node's platform * ($AGENT_PLATFORM, the same variable the satellite registers with): * * - Android → `adb` (`screenrecord` on the device + pull, `exec-out screencap`). * - iOS → `catuse`. The app under test there is an iOS build installed as a * **cat-supervisor instance** (a Catalyst copy running as a host process), * which is not a device at all, and a phone that happens to be plugged into * the same Mac is never the target. So the iOS path never touches adb. * * The second backend exists because for months the iOS fleet silently had NO * pre-registration. `record-evidence start` died with 「未发现在线设备」, so every * agent fell back to raw `catuse record` / `catuse savescreenshot` — captures * that land bytes in evidence/ but never a manifest line, hence no `intent`, no * `expectMoment`, no verdict, nothing to audit a clip against afterwards. The * 2026-09 evidence audit measured the damage: 39 iOS tasks, 602 media files, 29 * of them through the manifest, ZERO real start/stop declarations — against * 49/49 on Android. Every "pre-registration improved X" claim was Android-only. * So the wrapper now drives catuse itself and iOS gets the same manifest * Android has. * * Why a wrapper and not a single blocking call: the agent has to drive the * device UI *while* recording, so capture is start → (agent performs steps) → * stop. `start` kicks off a detached recorder and stashes a sidecar; `stop` * SIGINTs it so the recorder finalizes the mp4 (adb: then pulls it off the * device), validates it and records the verdict. `catuse record` is a thin * client of the capture daemon and writes straight to the host evidence dir, * finalizing on EOF. On a `fail` verdict the agent is told to re-record once * (MAX_CAPTURE_ATTEMPTS) — the "warn agent, let it retry" policy — after which * retryAllowed goes false. * * iOS target resolution — which instance is "the app under test": * 1. `--instance ` (`--app` is accepted as an alias) → that instance. The * agent picked and started it, so it is the one that knows. * 2. else the only running instance on the machine. * Several running and no `--instance` → refuse and list them. * Recording the wrong window produces evidence that looks fine and proves * nothing, so this never guesses. The chosen instance must also have an * on-screen window in `catuse apps` (matched by its `instance` field). * Every catuse call then targets `--instance `. * * Android: --device (--serial is an alias), else $ANDROID_SERIAL, else * the only device `adb devices` reports ready. `--via adb|catuse` is accepted * but must match the node's platform. * * Binary resolution: adb via $ADB_PATH, else PATH, else the SDK's platform-tools; * catuse / cat-supervisor via $CATUSE_PATH / $CAT_SUPERVISOR_PATH, else PATH, * else the directories DeviceSim's install.sh links them into. * * Per-capture DECLARATIONS (shared/src/evidence_capture.ts::CaptureDeclaration), * all given before the outcome is known and all recorded in the manifest: * --static-scene "<为什么这段画面本就不该动>" motion FAILs → warn, reason kept * --scene "<语言/页面>" before/after pair identity * and a changed --intent/--expect-moment on a re-record is not silently taken: * it emits a `redeclare` event holding both texts. * * Commands: * start --dir D --out demo-1-slug.mp4 --intent "…" --expect-moment "…" [--steps "…"] [--scene "…"] [--static-scene "…"] [--device | --instance ] [--max-seconds 180] * stop --dir D --capture * shot --dir D --out before-1-slug.png --intent "…" [--scene "…"] [--device | --instance ] * compose --dir D --out demo-1-before-after-slug.mp4 --left before.mp4 --right after.mp4 --intent "…" [--static-scene "…"] * skip --dir D --out demo-1-slug.mp4 --reason "…" * * Exit codes: 0 ok (pass/warn) · 2 usage · 3 validation FAILED (re-capture) · 4 tool/device error. */ import { spawn as nodeSpawn, spawnSync } from "node:child_process"; import { mkdirSync, existsSync, readFileSync, writeFileSync, appendFileSync, statSync, rmSync, openSync, closeSync, renameSync, } from "node:fs"; import path from "node:path"; import { EVIDENCE_MANIFEST_FILE, EVIDENCE_SCHEMA_VERSION, MAX_CAPTURE_ATTEMPTS, CAPTURE_THRESHOLDS, BASELINE_CRITERIA, normalizeCriteria, evaluateCapture, parseEvidenceName, parseManifest, pairedEvidenceName, pairMismatchIssue, verdictFromIssues, type CaptureDeclaration, type CaptureIssue, type ManifestEntry, type ProbeResult, type CaptureKind, type CaptureCriteria, type Verdict, } from "../shared/src/evidence_capture"; import { CONTROL_INTERNAL, CLUSTER_SECRET_HEADER } from "../shared/src/protocol"; // ── tiny arg parser ────────────────────────────────────────────────────────── 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); } function run( cmd: string, args: string[], timeoutMs = 30_000, ): { code: number; stdout: string; stderr: string; timedOut: boolean } { const r = spawnSync(cmd, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }); // spawnSync signals a timeout inconsistently across runtimes (an ETIMEDOUT // `error` on node, a bare SIGTERM in some Bun builds) — and the exit status it // pairs with that is not trustworthy either, which is how a hung recorder // came to be reported as "exit 0". Detect it from both tells. const err = r.error ? String(r.error.message) : ""; const timedOut = /ETIMEDOUT/i.test(err) || (r.status == null && r.signal === "SIGTERM"); return { code: r.status ?? (r.error ? 127 : 0), stdout: r.stdout || "", stderr: r.stderr || err, timedOut, }; } const tail = (s: string, n = 800) => (s.length > n ? s.slice(-n) : s); // ── capture-time evidence mirror (via control plane) ──────────────────────────── // Push a *passing* capture to durable storage the instant it's validated, while // the file provably still exists on the node — so a later same-name overwrite or // workspace clean can't lose it (the control-plane mirror at manual_review only // ever sees whatever survived to that point). The satellite holds NO TOS key: it // relays the bytes to the control plane (sole key holder), which uploads to TOS // and returns the voffline URL. Best-effort and env-gated on owner identity // (injected by the satellite runner) — absent it, a no-op and the manual_review // mirror remains the backstop. Reuses CONTROL_PLANE_URL + CLUSTER_SECRET, which // every node already has for register/heartbeat (no new secret distributed). const TOS_CONTENT_TYPE: Record = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".bmp": "image/bmp", ".svg": "image/svg+xml", ".heic": "image/heic", ".avif": "image/avif", ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".m4v": "video/x-m4v", }; function tosContentType(name: string): string { const dot = name.lastIndexOf("."); return TOS_CONTENT_TYPE[dot >= 0 ? name.slice(dot).toLowerCase() : ""] || "application/octet-stream"; } /** * Relay `filePath` to the control plane for TOS upload and stamp `entry.tosUrl` * with the returned voffline URL. Never throws — a relay failure just leaves * tosUrl unset (the bytes are still on the node for the manual_review backstop). */ async function maybeMirrorToTos(entry: ManifestEntry, filePath: string): Promise { const kind = process.env.EVIDENCE_OWNER_KIND; // "bug" | "feature" | "security" const ownerId = process.env.EVIDENCE_OWNER_ID; if (!kind || !ownerId) return; // no owner identity → backstop handles it if (entry.verdict !== "pass" && entry.verdict !== "warn") return; // only durable-worthy captures if (!existsSync(filePath)) return; try { const bytes = readFileSync(filePath); const control = (process.env.CONTROL_PLANE_URL || "http://127.0.0.1:5173").replace(/\/+$/, ""); const headers: Record = { "content-type": tosContentType(entry.out) }; if (process.env.CLUSTER_SECRET) headers[CLUSTER_SECRET_HEADER] = process.env.CLUSTER_SECRET; const res = await fetch(control + CONTROL_INTERNAL.evidenceMirror(kind, ownerId, entry.out), { method: "POST", headers, body: bytes, }); if (!res.ok) { process.stderr.write(`⚠️ 证据镜像失败(将由复核态兜底):${res.status} ${res.statusText}\n`); return; } const { url } = (await res.json()) as { url: string | null }; if (url) entry.tosUrl = url; // null = control plane has no TOS configured → skip, backstop covers it } catch (e) { process.stderr.write(`⚠️ 证据镜像异常(将由复核态兜底):${(e as Error).message}\n`); } } // ── active judgement criteria ──────────────────────────────────────────────── /** * Fetch the criteria version the owner has approved, so a threshold/rule change * takes effect on the next capture instead of the next release. Cached for the * life of this (short) CLI process. Any failure — no control plane, timeout, * garbage payload — silently yields the compiled-in baseline: grading must never * depend on the network being reachable. */ let criteriaCache: CaptureCriteria | null = null; async function activeCriteria(): Promise { if (criteriaCache) return criteriaCache; criteriaCache = BASELINE_CRITERIA; try { const control = (process.env.CONTROL_PLANE_URL || "http://127.0.0.1:5173").replace(/\/+$/, ""); const headers: Record = {}; if (process.env.CLUSTER_SECRET) headers[CLUSTER_SECRET_HEADER] = process.env.CLUSTER_SECRET; const res = await fetch(control + CONTROL_INTERNAL.evidenceCriteria, { headers, signal: AbortSignal.timeout(4000), }); if (!res.ok) return criteriaCache; const { criteria } = (await res.json()) as { criteria?: Partial }; if (criteria && typeof criteria.version === "number") criteriaCache = normalizeCriteria(criteria); } catch { /* offline / timeout → baseline */ } return criteriaCache; } // ── paths ──────────────────────────────────────────────────────────────────── function evidenceDir(args: Record): string { const dir = args.dir; if (!dir) die(2, "缺少 --dir (通常是 ${workspaceDir}/evidence)"); mkdirSync(dir, { recursive: true }); mkdirSync(path.join(dir, ".tmp"), { recursive: true }); return dir; } const manifestPath = (dir: string) => path.join(dir, EVIDENCE_MANIFEST_FILE); const sidecarPath = (dir: string, id: string) => path.join(dir, ".tmp", `${id}.json`); function appendManifest(dir: string, entry: ManifestEntry): void { appendFileSync(manifestPath(dir), JSON.stringify(entry) + "\n"); } /** Terminal (stop/shot/compose) manifest entries for `out`, oldest first. */ function terminalEntriesFor(dir: string, out: string): ManifestEntry[] { const mp = manifestPath(dir); if (!existsSync(mp)) return []; return parseManifest(readFileSync(mp, "utf8")).filter( (e) => (e.event === "stop" || e.event === "shot" || e.event === "compose") && e.out === out, ); } /** 最近一次 `void` 之后的终态记录 —— 作废之前的那些不再挡住重拍。 */ function liveTerminalEntriesFor(dir: string, out: string): ManifestEntry[] { const mp = manifestPath(dir); if (!existsSync(mp)) return []; const all = parseManifest(readFileSync(mp, "utf8")).filter((e) => e.out === out); const lastVoid = all.map((e) => e.event).lastIndexOf("void"); return all.slice(lastVoid + 1).filter((e) => e.event === "stop" || e.event === "shot" || e.event === "compose"); } /** Count prior terminal (stop/shot/compose) attempts for `out` → this attempt#. */ function attemptNumberFor(dir: string, out: string): number { return terminalEntriesFor(dir, out).length + 1; } /** * Refuse to reuse a filename that already holds a PASSING (pass/warn) capture — * writing to it would silently destroy good evidence (and, with capture-time TOS * mirroring, overwrite the durable copy under the same key too). Retry-after-fail * is unaffected: a `fail` prior doesn't count as good, so the agent can re-record * the same name to replace a bad take. Distinct evidence must use distinct names * (naming规范 `-[-NN]-`; later rounds `r2/r3…`). Called before * any bytes are written, so a rejection never loses the existing file. */ function assertNameFree(dir: string, out: string, replaceReason?: string): void { const good = liveTerminalEntriesFor(dir, out).filter((e) => e.verdict === "pass" || e.verdict === "warn"); if (!good.length) return; const last = good[good.length - 1]; // `--replace "<原因>"`:平台的文件名就是契约(UI 走查按页面 id 命名、用例验证按检查点命名), // 拍错了一帧又不许同名重拍,这一格就只能空着。所以允许显式作废:旧文件改名保留、 // 原因记进 manifest,证据链照样追得回来 —— 不是静默覆盖。不带这个参数时行为不变。 if (replaceReason && replaceReason !== "true") { const ext = path.extname(out); const n = terminalEntriesFor(dir, out).length; const replacedAs = `${out.slice(0, out.length - ext.length)}.replaced-${n}${ext}`; const src = path.join(dir, out); if (existsSync(src)) renameSync(src, path.join(dir, replacedAs)); for (const side of [".ui.txt", ".controls.txt"]) { const sp = path.join(dir, out.slice(0, out.length - ext.length) + side); if (existsSync(sp)) renameSync(sp, path.join(dir, replacedAs.slice(0, replacedAs.length - ext.length) + side)); } appendManifest(dir, { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "void", captureId: `void-${Date.now()}`, out, reason: replaceReason, replacedAs, }); process.stderr.write(`已作废 ${out} 的既有证据(原因:${replaceReason}),旧文件改名为 ${replacedAs}\n`); return; } die(2, `文件名 ${out} 已有通过的证据(第 ${last.attempt ?? "?"} 次尝试,判定 ${last.verdict})——` + `请换一个语义化文件名,以免覆盖既有证据(命名规范 -[-NN]-.;` + `多轮证据用 r2/r3… 轮次段,或加 -02/-03 序号区分)。\n` + `(仅当上一次同名证据「未通过」时才允许沿用原名重录。文件名是平台契约、确实拍错了要重拍时,` + `加 \`--replace "<作废原因>"\`:旧文件改名保留,原因记进 manifest。)`); } /** Most recent declaring event (`start`/`shot`) for `out`, or null. */ function lastDeclarationFor(dir: string, out: string): ManifestEntry | null { const mp = manifestPath(dir); if (!existsSync(mp)) return null; const decls = parseManifest(readFileSync(mp, "utf8")).filter( (e) => (e.event === "start" || e.event === "shot") && e.out === out, ); return decls.length ? decls[decls.length - 1] : null; } /** * 声明改写即记录 —— a re-record that quietly rewrites what it is out to prove. * * Pre-registration is worth something only because the claim was fixed BEFORE * the outcome. The audit found 29% of Android tasks (14/49) changed `intent` or * `expectMoment` on attempt 2, and the rewrite always went the same direction: * `5386381692` went from 「从特效面板选图触发生成后被踢到编辑页」 (168s, over * budget, fail) to 「按返回键后拍摄页只闪现一瞬」 — a moment that is much easier * to catch. Nothing recorded that the goalposts moved; the new line simply * overwrote the old one in every reader's view. * * So a changed declaration is not blocked — sometimes the first one really was * wrong — it is WRITTEN DOWN as its own `redeclare` event carrying both texts, * the new attempt is flagged `redeclared`, and the agent is told the report has * to account for it. A retraction, not an overwrite. */ function noteRedeclare( dir: string, out: string, next: { intent?: string; expectMoment?: string }, ): boolean { const prev = lastDeclarationFor(dir, out); if (!prev) return false; const intentChanged = !!next.intent && !!prev.intent && next.intent !== prev.intent; const momentChanged = !!next.expectMoment && !!prev.expectMoment && next.expectMoment !== prev.expectMoment; if (!intentChanged && !momentChanged) return false; appendManifest(dir, { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "redeclare", captureId: newCaptureId(out), out, ...parseEvidenceName(out), intent: next.intent, expectMoment: next.expectMoment, prevIntent: prev.intent, prevExpectMoment: prev.expectMoment, // `reason` is the free-text column the ingest already persists; for a // redeclare it carries the superseded declaration so the Portal shows the // rewrite without a schema change. reason: `上一次声明 → intent:「${prev.intent ?? "(无)"}」/ expect:「${prev.expectMoment ?? "(无)"}」`, }); process.stdout.write( `📝 已记录一次「声明改写」:${out} 这一次要证明的东西和上一次不一样。\n` + (intentChanged ? ` intent: 「${prev.intent}」 → 「${next.intent}」\n` : "") + (momentChanged ? ` expect: 「${prev.expectMoment}」 → 「${next.expectMoment}」\n` : "") + ` 改声明本身是允许的(第一次可能就写错了),但**报告里必须说明为什么改**——\n` + ` 否则「先声明后对照」就退化成了「挑一个录得到的瞬间再补声明」。\n`, ); return true; } /** Per-capture declarations parsed off the command line. */ function parseDeclaration(args: Record): CaptureDeclaration { const d: CaptureDeclaration = {}; const st = args["static-scene"]; if (st != null) { if (st === "true") die(2, "--static-scene 需要带上理由(如 --static-scene \"长按 @全部 的按压态,画面本就静止\")。\n" + "理由会写进 manifest 并出现在报告里——这条豁免是要被复核的,不是一个开关。"); d.staticScene = st; } const scene = args.scene; if (scene && scene !== "true") d.scene = scene; return d; } /** * 同场景成对校验 —— append a `scene-mismatch` finding when this capture and its * before/after counterpart are not looking at the same thing. Returns the issue * list to record (unchanged when there is no counterpart or no objection). */ function withPairCheck( dir: string, self: { out: string; scene?: string; probe?: ProbeResult }, issues: CaptureIssue[], ): CaptureIssue[] { const mate = pairedEvidenceName(self.out); if (!mate) return issues; const counterpart = terminalEntriesFor(dir, mate) .filter((e) => e.verdict === "pass" || e.verdict === "warn") .pop(); if (!counterpart) return issues; const issue = pairMismatchIssue(self, counterpart); return issue ? [...issues, issue] : issues; } function newCaptureId(out: string): string { const slug = out.replace(/\.[^.]+$/, "").replace(/[^a-z0-9-]+/gi, "-").slice(0, 40); return `${slug}-${Date.now().toString(36)}-${Math.floor(process.hrtime()[1] % 1e6).toString(36)}`; } // ── device backends ────────────────────────────────────────────────────────── // Both backends supply the same three primitives the lifecycle needs: enumerate // a target, spawn a detached recorder that finalizes the mp4 when SIGINTed, and // take a full-resolution still. Everything downstream (sidecar, manifest, // ffprobe, verdict, TOS mirror) is backend-agnostic on purpose. type Backend = "adb" | "catuse"; interface Device { backend: Backend; /** adb: the device serial. catuse: `#` of the matched window. */ id: string; /** Prefix of the manifest `device` field: "android" | "catalyst". */ platform: string; /** catuse only: the cat-supervisor instance id — every catuse call targets `--instance`. */ instance?: string; } // ── adb (Android) ──────────────────────────────────────────────────────────── // `adb shell screenrecord` records ON the device, so a capture is: start it // under a detached adb client writing to /sdcard, SIGINT the on-device process // at `stop` so it finalizes the mp4, then pull and delete. The device-side path // carries the captureId, which is what lets `stop` signal exactly this // recording and not another one running on the same phone. function adbBin(): string { if (process.env.ADB_PATH) return process.env.ADB_PATH; const onPath = Bun.which("adb"); if (onPath) return onPath; const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT; const candidates = [ "/opt/homebrew/bin/adb", ...(sdk ? [path.join(sdk, "platform-tools", "adb")] : []), ]; for (const c of candidates) if (existsSync(c)) return c; die(4, "找不到 adb。请确认它在 PATH 上,或设置环境变量 ADB_PATH 指向它。"); } const adb = (serial: string, rest: string[], timeoutMs = 30_000) => run(adbBin(), ["-s", serial, ...rest], timeoutMs); /** --device/--serial, else $ANDROID_SERIAL, else the only device `adb devices` reports ready. */ function resolveAdb(explicit?: string): Device { const toDev = (serial: string): Device => ({ backend: "adb", id: serial, platform: "android" }); if (explicit && explicit !== "true") return toDev(explicit); if (process.env.ANDROID_SERIAL) return toDev(process.env.ANDROID_SERIAL); const r = run(adbBin(), ["devices"]); if (r.code !== 0) die(4, `无法执行 adb devices:\n${tail(r.stderr)}`); const ready = r.stdout .split("\n") .slice(1) .map((l) => l.trim()) .filter((l) => /\tdevice$/.test(l)) .map((l) => l.split("\t")[0]); if (ready.length === 0) die(4, "adb devices 里没有就绪的设备(离线 / 未授权的不算)。若确实无设备可录屏,请改用:record-evidence skip --dir … --out … --reason \"无可用设备\""); if (ready.length > 1) die(4, `adb 连着多台设备 [${ready.join(", ")}],请用 --device 指定其中一台`); return toDev(ready[0]); } /** * `exec-out screencap -p` streams raw PNG bytes (no shell CRLF mangling), so it * is read as a Buffer, not through `run`, which decodes stdout as text. */ function adbScreencap(serial: string, dest: string, timeoutMs: number) { const r = spawnSync(adbBin(), ["-s", serial, "exec-out", "screencap", "-p"], { timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, }); const err = r.error ? String(r.error.message) : ""; const timedOut = /ETIMEDOUT/i.test(err) || (r.status == null && r.signal === "SIGTERM"); const code = r.status ?? (r.error ? 127 : 0); if (code === 0 && r.stdout && r.stdout.length > 0) writeFileSync(dest, r.stdout); return { code, stdout: "", stderr: (r.stderr ? r.stderr.toString() : "") || err, timedOut }; } /** Where `screenrecord` writes on the device for this capture. */ const adbRecordPath = (captureId: string) => `/sdcard/record-evidence-${captureId}.mp4`; // ── catuse + cat-supervisor (iOS: a Catalyst instance on the host) ─────────── // On the iOS nodes the app under test is a cat-supervisor instance: one // installed copy of an iOS build with its own id, home and at most one live // process. cat-supervisor owns its lifecycle and knows which instances run and // who started them (`list`); catuse drives and captures the window. Capture // (`record` / `savescreenshot`) is served by a singleton daemon that owns // ScreenCaptureKit, which is why a still taken DURING a record is safe and why // several records can overlap. // // Two catuse contract details this wrapper leans on, both verified on fei-ios-02: // - `catuse record` finalizes the mp4 when its client connection drops, so a // SIGINT at `stop` yields a complete, probeable file (exit 0). // - failures exit non-zero and print their JSON (`ok:false`, `error`, `hint`) // on **stderr**, while successes print JSON on stdout. Both are checked: // `ok:false` is treated as failure even if some future build exits 0. const isIosNode = () => process.env.AGENT_PLATFORM === "ios"; /** * Locate a DeviceSim tool. PATH is the primary source; the fallbacks are the * directories DeviceSim's install.sh links into, for a caller whose PATH was * stripped. cat-supervisor additionally lives in the published runtime dir. */ function findDeviceSimTool(name: "catuse" | "cat-supervisor", envVar: string): string | null { if (process.env[envVar]) return process.env[envVar]!; const onPath = Bun.which(name); if (onPath) return onPath; const home = process.env.HOME || ""; const candidates = [ `/opt/homebrew/bin/${name}`, `/usr/local/bin/${name}`, ...(home ? [path.join(home, ".local/bin", name)] : []), ...(name === "cat-supervisor" ? ["/Users/Shared/DeviceSim/current/cat-supervisor"] : []), ]; for (const c of candidates) if (existsSync(c)) return c; return null; } function deviceSimTool(name: "catuse" | "cat-supervisor", envVar: string): string { const bin = findDeviceSimTool(name, envVar); if (bin) return bin; die(4, `找不到 ${name}。它应当在 PATH 上(由 DeviceSim 仓的 ./install.sh 安装),或设置环境变量 ${envVar} 指向它。`); } const catuseBin = () => deviceSimTool("catuse", "CATUSE_PATH"); const supervisorBin = () => deviceSimTool("cat-supervisor", "CAT_SUPERVISOR_PATH"); /** True when a catuse invocation failed — non-zero exit, or a JSON `ok:false`. */ function catuseFailed(r: { code: number; stdout: string; stderr: string }): boolean { if (r.code !== 0) return true; for (const text of [r.stdout, r.stderr]) { try { const j = JSON.parse(text); if (j && typeof j === "object" && j.ok === false) return true; } catch { /* not JSON — fall through */ } } return false; } /** * The human-readable half of an error payload: catuse prints `error` + `hint`, * cat-supervisor prints `code` + `message` + `hint`. */ function catuseError(r: { stdout: string; stderr: string }): string { for (const text of [r.stderr, r.stdout]) { try { const j = JSON.parse(text); if (j?.error) return [j.error, j.hint].filter(Boolean).join(" "); if (j?.ok === false && (j.code || j.message)) return [j.code, j.message, j.hint].filter(Boolean).join(" "); } catch { /* not JSON */ } } return tail(r.stderr || r.stdout); } interface SupervisorInstance { id: string; state: string; pid?: number; owner?: string } /** `cat-supervisor list` → its instances. */ function supervisorInstances(): SupervisorInstance[] { const r = run(supervisorBin(), ["list"], 20_000); if (catuseFailed(r)) die(4, `cat-supervisor list 失败:${catuseError(r)}`); let parsed: any; try { parsed = JSON.parse(r.stdout); } catch { die(4, `cat-supervisor list 输出无法解析:\n${tail(r.stdout)}`); } const all: any[] = Array.isArray(parsed?.instances) ? parsed.instances : []; return all .filter((i) => typeof i?.id === "string") .map((i) => ({ id: i.id, state: String(i.state ?? ""), pid: typeof i.pid === "number" ? i.pid : undefined, owner: typeof i.owner === "string" ? i.owner : undefined, })); } const describeInstance = (i: SupervisorInstance) => `${i.id}(${i.state}${i.pid ? ` pid ${i.pid}` : ""}${i.owner ? ` owner ${i.owner}` : ""})`; /** * Pick the instance under test (see the file header for the order) and confirm * catuse can see its window. Dies with the candidates instead of guessing. */ function resolveInstance(args: Record): Device { const flag = [args.instance, args.app].find((v) => v && v !== "true"); const instances = supervisorInstances(); const running = instances.filter((i) => i.state === "running" && i.pid); const runHint = "用 `cat-supervisor list` 看本机实例,`cat-supervisor run -- -skipForceLogin` 启动(见「设备驱动」一节)。"; let pick: SupervisorInstance; if (flag) { const hit = instances.find((i) => i.id === flag); if (!hit) die(4, `cat-supervisor 里没有实例「${flag}」(现有:${instances.map(describeInstance).join(", ") || "无"})。`); if (hit.state !== "running" || !hit.pid) die(4, `实例「${flag}」当前是 ${hit.state || "未知状态"},没有在跑。${runHint}`); pick = hit; } else { if (running.length === 0) die(4, `没有运行中的 cat-supervisor 实例(现有:${instances.map(describeInstance).join(", ") || "无"})。${runHint}`); if (running.length > 1) die(4, `有 ${running.length} 个运行中的实例,无法判断哪个是被测 App:${running.map(describeInstance).join(", ")}。` + `用 --instance 指定。`); pick = running[0]; } const r = run(catuseBin(), ["apps"], 20_000); if (catuseFailed(r)) die(4, `catuse apps 失败:${catuseError(r)}`); let parsed: any; try { parsed = JSON.parse(r.stdout); } catch { die(4, `catuse apps 输出无法解析:\n${tail(r.stdout)}`); } const windows: any[] = Array.isArray(parsed?.windows) ? parsed.windows : []; const win = windows.find((w) => w?.instance === pick.id && typeof w?.pid === "number"); if (!win) die(4, `实例「${pick.id}」在跑(pid ${pick.pid}),但 catuse 看不到它的窗口 —— 窗口最小化、锁屏或无显示器时都会这样。` + `先确认 \`catuse apps\` 里有 instance 为「${pick.id}」的窗口再采集。`); return { backend: "catuse", id: `${pick.id}#${win.pid}`, platform: "catalyst", instance: pick.id }; } // ── backend selection ──────────────────────────────────────────────────────── /** Pick the backend from the node's platform, then the target within it. */ function resolveDevice(args: Record): Device { const via = (args.via ?? "").toLowerCase(); const explicit = args.device ?? args.serial; const hasExplicit = explicit != null && explicit !== "true"; if (via && via !== "true" && via !== "adb" && via !== "catuse") die(2, `--via 只支持 adb | catuse(收到「${args.via}」)`); if (isIosNode()) { if (via === "adb" || hasExplicit) die(2, "iOS 节点只走 catuse:被测 App 是 cat-supervisor 实例,不是设备,--device/--serial/--via adb 都不适用。要指定实例用 --instance 。"); return resolveInstance(args); } if (via === "catuse") die(2, "--via catuse 只在 iOS 节点可用。"); return resolveAdb(explicit); } /** * argv for the detached recorder. catuse writes straight to `dest`; adb writes * to `devicePath` on the phone and `stop` pulls it. */ function recordArgv(dev: Device, dest: string, devicePath: string, maxSeconds: number): { bin: string; args: string[] } { if (dev.backend === "catuse") return { bin: catuseBin(), args: ["record", "--instance", dev.instance!, "-o", dest, "--duration", String(maxSeconds)] }; return { bin: adbBin(), args: ["-s", dev.id, "shell", "screenrecord", "--time-limit", String(maxSeconds), devicePath], }; } /** Human name of the recorder, for error messages that must be actionable. */ const recorderName = (backend: Backend) => backend === "catuse" ? "catuse record" : "adb screenrecord"; /** Block until `pid` exits (best-effort), SIGKILLing on timeout. */ function waitForPidExit(pid: number, timeoutMs: number): void { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { process.kill(pid, 0); } catch { return; } // ESRCH → already gone Bun.sleepSync(200); } try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ } Bun.sleepSync(300); } // ── ffprobe / scene detection ────────────────────────────────────────────────── function probeMedia(file: string, kind: CaptureKind): ProbeResult { const sizeBytes = existsSync(file) ? (() => { try { return statSync(file).size; } catch { return 0; } })() : 0; const base: ProbeResult = { ok: false, sizeBytes }; if (sizeBytes === 0) return base; const r = run("ffprobe", [ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,codec_name,nb_frames,r_frame_rate", "-show_entries", "format=duration", "-of", "json", file, ]); if (r.code !== 0) return base; let parsed: any; try { parsed = JSON.parse(r.stdout); } catch { return base; } const st = parsed?.streams?.[0]; if (!st) return base; const durationS = parsed?.format?.duration != null ? Number(parsed.format.duration) : undefined; let fps: number | undefined; if (typeof st.r_frame_rate === "string" && st.r_frame_rate.includes("/")) { const [n, d] = st.r_frame_rate.split("/").map(Number); if (d) fps = n / d; } const probe: ProbeResult = { ok: true, sizeBytes, durationS: Number.isFinite(durationS) ? durationS : undefined, width: st.width ? Number(st.width) : undefined, height: st.height ? Number(st.height) : undefined, nFrames: st.nb_frames && st.nb_frames !== "N/A" ? Number(st.nb_frames) : undefined, fps: fps && Number.isFinite(fps) ? Number(fps.toFixed(2)) : undefined, codec: st.codec_name || undefined, }; // Static-frame heuristic for videos long enough to matter. Best-effort: one // extra decode pass counting scene-change events. // // `sceneChanges` MUST stay undefined when the pass did not actually complete: // a timed-out or errored decode used to be recorded as a hard 0, which is // indistinguishable from "genuinely frozen" and made every large clip look // static. Only a clean exit (code 0) yields a count. The 60s budget is also // too tight for 100MB+ clips, so it scales with file size. if (kind === "video" && (probe.durationS ?? 0) >= CAPTURE_THRESHOLDS.staticProbeMinS) { const budgetMs = Math.min(300_000, Math.max(60_000, Math.round((sizeBytes / 1e6) * 2_000))); const sc = run( "ffmpeg", ["-nostats", "-i", file, "-vf", "select='gt(scene,0.1)',showinfo", "-an", "-f", "null", "-"], budgetMs, ); if (sc.code === 0) { const matches = sc.stderr.match(/pts_time:/g); probe.sceneChanges = matches ? matches.length : 0; } } return probe; } // ── verdict reporting ────────────────────────────────────────────────────────── function reportVerdict( dir: string, entry: ManifestEntry, verdict: Verdict, attempt: number, ): never { appendManifest(dir, entry); const issues = entry.issues ?? []; const p = entry.probe; const info = p?.ok ? `时长 ${(p.durationS ?? 0).toFixed(1)}s · ${p.width ?? "?"}x${p.height ?? "?"} · ${(p.sizeBytes / 1e6).toFixed(2)}MB${p.sceneChanges != null ? ` · 场景变化 ${p.sceneChanges}` : ""}` : `${((p?.sizeBytes ?? 0) / 1e6).toFixed(2)}MB`; if (verdict === "pass") { process.stdout.write(`✅ 证据校验通过 ${entry.out} (${info})\n`); process.exit(0); } if (verdict === "warn") { process.stdout.write(`⚠️ 证据已保存但有告警 ${entry.out} (${info})\n`); for (const i of issues) process.stdout.write(` - ${i.message}\n`); process.stdout.write(" 如条件允许可考虑重录以提升报告质量;否则可继续。\n"); process.exit(0); } // fail const retryAllowed = entry.retryAllowed ?? false; process.stdout.write(`❌ 证据校验未通过 ${entry.out} (${info}) — 第 ${attempt}/${MAX_CAPTURE_ATTEMPTS} 次尝试\n`); for (const i of issues) process.stdout.write(` - ${i.message}\n`); if (retryAllowed) { process.stdout.write( " 请重录一次:重新 start → 操作(务必截到关键瞬间、控制时长)→ stop。这是你仅有的 1 次重试机会。\n", ); } else { process.stdout.write( " 重试次数已用尽——不要再重录。请在报告「验证局限」里如实说明该证据未能达标及原因。\n", ); } process.exit(3); } // ── commands ──────────────────────────────────────────────────────────────────── function cmdStart(args: Record): never { const dir = evidenceDir(args); const out = args.out; if (!out) die(2, "缺少 --out (如 demo-1-slug.mp4)"); if (!args.intent || args.intent === "true") die(2, "缺少 --intent(这段视频要证明什么)"); if (!args["expect-moment"] || args["expect-moment"] === "true") die(2, "缺少 --expect-moment(必须录到的关键瞬间,便于失败时定位)"); assertNameFree(dir, out, args.replace); // guard before screenrecord starts writing to dest const declared = parseDeclaration(args); const redeclared = noteRedeclare(dir, out, { intent: args.intent, expectMoment: args["expect-moment"], }); const dev = resolveDevice(args); const maxSeconds = Math.min(180, Math.max(10, Number(args["max-seconds"] || 180) || 180)); const captureId = newCaptureId(out); const dest = path.join(dir, out); const devicePath = adbRecordPath(captureId); const attempt = attemptNumberFor(dir, out); const { phase, round } = parseEvidenceName(out); const errFile = path.join(dir, ".tmp", `${captureId}.rec.err`); const fd = openSync(errFile, "w"); const rec = recordArgv(dev, dest, devicePath, maxSeconds); const child = nodeSpawn(rec.bin, rec.args, { detached: true, stdio: ["ignore", "ignore", fd] }); child.unref(); closeSync(fd); if (!child.pid) die(4, `无法启动 ${recorderName(dev.backend)}`); writeFileSync( sidecarPath(dir, captureId), JSON.stringify({ captureId, out, device: dev.id, platform: dev.platform, backend: dev.backend, dest, devicePath: dev.backend === "adb" ? devicePath : undefined, pid: child.pid, attempt, startTs: Date.now(), intent: args.intent, expectMoment: args["expect-moment"], plannedSteps: args.steps && args.steps !== "true" ? args.steps : undefined, errFile, maxSeconds, declared, }), ); appendManifest(dir, { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "start", captureId, out, phase, round, kind: "video", device: `${dev.platform}:${dev.id}`, attempt, intent: args.intent, expectMoment: args["expect-moment"], plannedSteps: args.steps && args.steps !== "true" ? args.steps : undefined, staticScene: declared.staticScene, scene: declared.scene, redeclared: redeclared || undefined, }); process.stdout.write( `▶️ 录制已开始 captureId=${captureId} (设备 ${dev.platform}:${dev.id}, 安全上限 ${maxSeconds}s)。\n` + ` 现在在设备上完成操作,**确保录到关键瞬间**,然后运行:\n` + ` bun ${process.argv[1]} stop --dir ${dir} --capture ${captureId}\n`, ); process.exit(0); } async function cmdStop(args: Record): Promise { const dir = evidenceDir(args); const captureId = args.capture; if (!captureId || captureId === "true") die(2, "缺少 --capture (来自 start 的输出)"); const sc = sidecarPath(dir, captureId); if (!existsSync(sc)) die(2, `找不到 captureId=${captureId} 的录制会话(是否已 stop 过?)`); const s = JSON.parse(readFileSync(sc, "utf8")); // The declarations were fixed at `start`; re-reading them here (rather than // from argv) is what keeps them un-revisable once the outcome is in view. const declared: CaptureDeclaration = s.declared ?? {}; // SIGINT tells the recorder to finalize the mp4, then we wait for it to // actually exit before probing (the file may hit its own duration cap and // self-stop first, in which case the pid is already gone). catuse finalizes // because the capture daemon closes the writer as soon as its client // connection drops, and -o already wrote to the host. adb's local client is // only a pipe: the recorder is the on-device process, so that is the one to // SIGINT (matched by this capture's device path), and the file is pulled after. const dest = s.dest ?? path.join(dir, s.out); let pullErr = ""; if (s.backend === "adb" && s.devicePath) { adb(s.device, ["shell", "pkill", "-INT", "-f", s.devicePath], 8_000); Bun.sleepSync(1500); // screenrecord writes the moov atom on SIGINT } try { process.kill(s.pid, "SIGINT"); } catch { /* already exited (e.g. hit --time-limit) */ } waitForPidExit(s.pid, s.backend === "adb" ? 10_000 : 60_000); const durationS = (Date.now() - s.startTs) / 1000; if (s.backend === "adb" && s.devicePath) { const pull = adb(s.device, ["pull", s.devicePath, dest], 60_000); if (pull.code !== 0) pullErr = `adb pull 失败(exit ${pull.code}):${tail(pull.stderr || pull.stdout)}\n`; adb(s.device, ["shell", "rm", "-f", s.devicePath], 8_000); } Bun.sleepSync(300); // fs flush grace const mcErr = pullErr + (existsSync(s.errFile) ? readFileSync(s.errFile, "utf8") : ""); try { rmSync(s.errFile, { force: true }); } catch { /* ignore */ } const { phase, round } = parseEvidenceName(s.out); const base: ManifestEntry = { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "stop", captureId, out: s.out, phase, round, kind: "video", device: `${s.platform ?? "device"}:${s.device ?? s.serial}`, durationS: Number(durationS.toFixed(1)), attempt: s.attempt, intent: s.intent, expectMoment: s.expectMoment, staticScene: declared.staticScene, scene: declared.scene, }; if (!existsSync(dest) || (() => { try { return statSync(dest).size === 0; } catch { return true; } })()) { const entry: ManifestEntry = { ...base, fileBytes: 0, stderrTail: tail(mcErr), probe: { ok: false, sizeBytes: 0 }, verdict: "fail", issues: [{ code: "record-failed", severity: "fail", message: `录制未产出文件——${recorderName(s.backend === "catuse" ? "catuse" : "adb")} 可能失败、` + (s.backend === "catuse" ? "被测窗口已关闭 / 最小化" : "设备断开、录像没拉下来") + "或未正常结束录制", }], retryAllowed: s.attempt < MAX_CAPTURE_ATTEMPTS, }; try { rmSync(sc, { force: true }); } catch { /* ignore */ } reportVerdict(dir, entry, "fail", s.attempt); } const probe = probeMedia(dest, "video"); const criteria = await activeCriteria(); const graded = evaluateCapture("video", probe, criteria, "native", declared); const issues = withPairCheck(dir, { out: s.out, scene: declared.scene, probe }, graded.issues); const verdict = verdictFromIssues(issues); const entry: ManifestEntry = { ...base, fileBytes: probe.sizeBytes, probe, verdict, issues, criteriaVersion: criteria.version, stderrTail: verdict === "fail" ? tail(mcErr) : undefined, retryAllowed: verdict === "fail" ? s.attempt < MAX_CAPTURE_ATTEMPTS : undefined, }; try { rmSync(sc, { force: true }); } catch { /* ignore */ } await maybeMirrorToTos(entry, dest); reportVerdict(dir, entry, verdict, s.attempt); } async function cmdShot(args: Record): Promise { const dir = evidenceDir(args); const out = args.out; if (!out) die(2, "缺少 --out (如 before-1-slug.png)"); if (!args.intent || args.intent === "true") die(2, "缺少 --intent(这张截图要证明什么)"); assertNameFree(dir, out, args.replace); // guard before screenshot overwrites dest const declared = parseDeclaration(args); const redeclared = noteRedeclare(dir, out, { intent: args.intent }); const dev = resolveDevice(args); const attempt = attemptNumberFor(dir, out); const { phase, round } = parseEvidenceName(out); const dest = path.join(dir, out); // `savescreenshot` — the FULL-resolution catuse still. (`getscreenshot` is the // cheap downscaled one the agent uses to read the page; it is not evidence.) // takenAt: the moment of the frame, before the tool and the grading eat seconds — // it is what places this shot on a recording running at the same time. const takenAt = Date.now(); const shotTool = dev.backend === "catuse" ? "catuse savescreenshot" : "adb screencap"; const r = dev.backend === "catuse" ? run(catuseBin(), ["savescreenshot", "--instance", dev.instance!, "-o", dest], 30_000) : adbScreencap(dev.id, dest, 30_000); const toolFailed = dev.backend === "catuse" ? catuseFailed(r) : r.code !== 0; const ok = !toolFailed && existsSync(dest); const why = dev.backend === "catuse" ? catuseError(r) : ""; const probe = probeMedia(dest, "image"); const criteria = await activeCriteria(); const graded = ok ? evaluateCapture("image", probe, criteria, "native", declared) : { verdict: "fail" as Verdict, issues: [ r.timedOut ? { code: "screenshot-timeout", severity: "fail" as const, message: dev.backend === "catuse" ? `${shotTool} 超时(30s 未返回)——截图守护进程很可能卡住,先确认窗口仍在屏幕上(catuse apps)再继续` : `${shotTool} 超时(30s 未返回)——设备很可能已无响应,建议先检查设备连接再继续`, } : { code: "screenshot-failed", severity: "fail" as const, message: (existsSync(dest) ? `${shotTool} 失败(exit ${r.code})` : `${shotTool} 未产出文件(exit ${r.code})`) + (why ? `:${why}` : ""), }, ], }; // before/after 成对校验只对真的拍出来了的那张有意义。 const issues = ok ? withPairCheck(dir, { out, scene: declared.scene, probe }, graded.issues) : graded.issues; const verdict = verdictFromIssues(issues); const entry: ManifestEntry = { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), takenAt, event: "shot", captureId: newCaptureId(out), out, phase, round, kind: "image", device: `${dev.platform}:${dev.id}`, fileBytes: probe.sizeBytes, probe, verdict, issues, criteriaVersion: criteria.version, intent: args.intent, attempt, staticScene: declared.staticScene, scene: declared.scene, redeclared: redeclared || undefined, stderrTail: verdict === "fail" ? tail(r.stderr) : undefined, retryAllowed: verdict === "fail" ? attempt < MAX_CAPTURE_ATTEMPTS : undefined, }; await maybeMirrorToTos(entry, dest); reportVerdict(dir, entry, verdict, attempt); } async function cmdCompose(args: Record): Promise { const dir = evidenceDir(args); const out = args.out; if (!out) die(2, "缺少 --out (如 demo-1-before-after-slug.mp4)"); if (!args.left || !args.right || args.left === "true" || args.right === "true") die(2, "缺少 --left / --right(要并排对比的两段视频文件名)"); if (!args.intent || args.intent === "true") die(2, "缺少 --intent(这段对比视频要证明什么)"); assertNameFree(dir, out, args.replace); // guard before ffmpeg -y overwrites dest const left = path.join(dir, args.left); const right = path.join(dir, args.right); for (const [label, f] of [["--left", left], ["--right", right]] as const) if (!existsSync(f)) die(2, `${label} 文件不存在: ${f}`); const dest = path.join(dir, out); const attempt = attemptNumberFor(dir, out); const { phase, round } = parseEvidenceName(out); const ff = run( "ffmpeg", ["-i", left, "-i", right, "-filter_complex", "[0:v]scale=-2:1280[l];[1:v]scale=-2:1280[r];[l][r]hstack", "-y", dest], 120_000, ); const probe = probeMedia(dest, "video"); const criteria = await activeCriteria(); // source "composed": this clip is an ffmpeg re-encode of two takes, so its // data rate is legitimately an order of magnitude below native screenrecord — // the bitrate floor must not be applied to it. const declared = parseDeclaration(args); const { verdict, issues } = ff.code === 0 && existsSync(dest) ? evaluateCapture("video", probe, criteria, "composed", declared) : { verdict: "fail" as Verdict, issues: [{ code: "ffmpeg-failed", severity: "fail" as const, message: `ffmpeg 拼接失败(exit ${ff.code})——检查两段输入分辨率/编码是否可解;拼不出时回退单段演示` }] }; const entry: ManifestEntry = { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "compose", captureId: newCaptureId(out), out, phase, round, kind: "video", device: "host", fileBytes: probe.sizeBytes, probe, verdict, issues, criteriaVersion: criteria.version, intent: args.intent, left: args.left, right: args.right, ffmpegExit: ff.code, attempt, staticScene: declared.staticScene, stderrTail: verdict === "fail" ? tail(ff.stderr) : undefined, retryAllowed: verdict === "fail" ? attempt < MAX_CAPTURE_ATTEMPTS : undefined, }; await maybeMirrorToTos(entry, dest); reportVerdict(dir, entry, verdict, attempt); } function cmdSkip(args: Record): never { const dir = evidenceDir(args); const out = args.out || "(demo)"; if (!args.reason || args.reason === "true") die(2, "缺少 --reason(为何跳过录制)"); const { phase, round } = parseEvidenceName(out); appendManifest(dir, { v: EVIDENCE_SCHEMA_VERSION, ts: Date.now(), event: "skip", captureId: newCaptureId(out), out, phase, round, reason: args.reason, }); process.stdout.write(`📝 已记录跳过录制:${args.reason}\n`); process.exit(0); } // ── main ──────────────────────────────────────────────────────────────────────── /** * CLI entry, callable two ways: * * 1. directly — `bun bin/record-evidence.ts start --dir …` (dev / source tree) * 2. as the satellite bundle's `record-evidence` subcommand, via * satellite/src/entry.ts * * (2) exists because hot-deploy ships exactly one artifact, satellite.js. When * the wrapper lived only at /bin/, deploying a satellite left the capture * code on the node untouched — so a wrapper fix silently didn't land, and the * criteria a capture was graded against could lag the control plane's by weeks. * Routing through the bundle keeps the two in lockstep by construction. * * `argv` is the argument list AFTER the program name, i.e. ["start", "--dir", …]. */ export async function runRecordEvidence(argv: string[]): Promise { const [sub, ...rest] = argv; const args = parseArgs(rest); switch (sub) { case "start": return cmdStart(args); case "stop": return await cmdStop(args); case "shot": return await cmdShot(args); case "compose": return await cmdCompose(args); case "skip": return cmdSkip(args); default: return die(2, "用法: record-evidence --dir …"); } } // Auto-run only when this file IS the entrypoint. Bundled into the satellite it // is not, so importing it stays free of side effects and entry.ts calls the // export instead. if (import.meta.main) await runRecordEvidence(process.argv.slice(2));