Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(cli): make `lh acceptance` the home of the review loop (#17336)

Arvin Xu0100fb61fcdc
diff --git a/.agents/verify/PROJECT.md b/.agents/acceptance/PROJECT.md
similarity index 86%
rename from .agents/verify/PROJECT.md
rename to .agents/acceptance/PROJECT.md
index 76496df629f..6450dec9aaf 100644
--- a/.agents/verify/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -4,7 +4,7 @@ This is the LobeHub adapter for the generic `agent-testing` skill. The skill is
project-agnostic; every LobeHub-specific command, port, service, and probe lives
here. The skill reads this file — it never guesses LobeHub's commands.
-Scripts referenced below live under `.agents/verify/scripts/`. The generic skill
+Scripts referenced below live under `.agents/acceptance/scripts/`. The generic skill
and its own scripts (`report-init.sh`, `cdp-screenshot.sh`, `record-gif.sh`,
`check-screen-recording.sh`, …) are installed at `.agents/skills/agent-testing/`.
@@ -36,7 +36,7 @@ stale standalone install: a recently added workspace package fails to resolve
- With repo-root `.env` present: use the existing local config — `bun run dev`
(full-stack, needed for Web smoke) or `AGENT_RUNTIME_MODE=queue pnpm run dev:next`
(backend only). Do NOT call any `init-dev-env.sh` subcommand when `.env` exists.
- - Without `.env`: use the skill-owned bootstrap `.agents/verify/scripts/init-dev-env.sh`
+ - Without `.env`: use the skill-owned bootstrap `.agents/acceptance/scripts/init-dev-env.sh`
(Postgres, Redis, migrations, auth/key-vault/S3 test env, seed user, then the
repo's own dev server — not `e2e/scripts/setup.ts`). It hard-blocks when
root `.env` exists, so it can never override a user's local config.
@@ -45,10 +45,10 @@ stale standalone install: a recently added workspace package fails to resolve
if [[ -f .env ]]; then
bun run dev
else
- .agents/verify/scripts/init-dev-env.sh setup-db
- .agents/verify/scripts/init-dev-env.sh s3 # terminal B — keep running
- .agents/verify/scripts/init-dev-env.sh seed-user
- .agents/verify/scripts/init-dev-env.sh dev
+ .agents/acceptance/scripts/init-dev-env.sh setup-db
+ .agents/acceptance/scripts/init-dev-env.sh s3 # terminal B — keep running
+ .agents/acceptance/scripts/init-dev-env.sh seed-user
+ .agents/acceptance/scripts/init-dev-env.sh dev
fi
```
@@ -59,8 +59,8 @@ stale standalone install: a recently added workspace package fails to resolve
- **Stop dev server (must stop only what THIS run started):**
```bash
- .agents/verify/scripts/init-dev-env.sh clean # stop the recorded dev-server PID tree; keep DB/Redis
- .agents/verify/scripts/init-dev-env.sh stop-dev # just the server, no note
+ .agents/acceptance/scripts/init-dev-env.sh clean # stop the recorded dev-server PID tree; keep DB/Redis
+ .agents/acceptance/scripts/init-dev-env.sh stop-dev # just the server, no note
```
`clean` stops only the recorded dev-server PID tree after verifying its PID
@@ -93,15 +93,15 @@ stale standalone install: a recently added workspace package fails to resolve
curl -s -o /dev/null -w '%{http_code}' "$SERVER_URL/"
```
-- **Env / port resolution:** `.agents/verify/scripts/test-env.sh` is the source
+- **Env / port resolution:** `.agents/acceptance/scripts/test-env.sh` is the source
of truth for local test ports — do NOT hard-code a port table. It reads the
current shell plus `.env` files with the same precedence as
`scripts/runWithEnv.mts` and prints `APP_URL`, `PORT`, `SERVER_URL`,
`AUTH_TRUSTED_ORIGINS`, `SPA_PORT`, `MOBILE_SPA_PORT`, `DESKTOP_PORT`.
```bash
- .agents/verify/scripts/test-env.sh # print resolved env + ports
- eval "$(.agents/verify/scripts/test-env.sh --exports)" # export them
+ .agents/acceptance/scripts/test-env.sh # print resolved env + ports
+ eval "$(.agents/acceptance/scripts/test-env.sh --exports)" # export them
```
Default script env (no-`.env` bootstrap): `APP_URL=http://localhost:3010`,
@@ -117,12 +117,12 @@ stale standalone install: a recently added workspace package fails to resolve
`lobehub`→3010, `lobehub-cloud`→3020, `lobehub-cloud-N`→`3020+N`.
- **Cucumber note:** when running Cucumber against this dev server in the no-`.env`
- branch, pass the same script env into the test process (`eval "$(.agents/verify/scripts/init-dev-env.sh env)"`)
+ branch, pass the same script env into the test process (`eval "$(.agents/acceptance/scripts/init-dev-env.sh env)"`)
— Cucumber's own `BeforeAll` seed path must see `DATABASE_URL` or it silently
skips setup.
- **Ports/modes table, the per-path server-restart matrix, and env
- troubleshooting:** `.agents/verify/references/dev-server.md`.
+ troubleshooting:** `.agents/acceptance/references/dev-server.md`.
## 3. Auth
@@ -130,9 +130,9 @@ stale standalone install: a recently added workspace package fails to resolve
completed. Created by `init-dev-env.sh seed-user`, which also writes a local
CLI API key to `.records/env/agent-testing-cli.env`.
-- **Seeding command:** `.agents/verify/scripts/init-dev-env.sh seed-user`.
+- **Seeding command:** `.agents/acceptance/scripts/init-dev-env.sh seed-user`.
-- **Setup helper:** `.agents/verify/scripts/setup-auth.sh` — `status` (all
+- **Setup helper:** `.agents/acceptance/scripts/setup-auth.sh` — `status` (all
surfaces), `status --surface <cli|web|electron>`, `cli-seed`, `cli` (interactive
device-code, user runs it), `web-seed`, `open-chrome`, `web` (inject a copied
Cookie header), `web-verify`. Auth is a surface-scoped gate: pick the intended
@@ -153,10 +153,10 @@ stale standalone install: a recently added workspace package fails to resolve
HttpOnly cookies are invisible there), then `pbpaste | setup-auth.sh web`. Use
`localhost`, not `127.0.0.1` (better-auth cookies are stored for `localhost`).
Never do this against production. Full decision flow, seeded-login mechanics,
- and failure modes: `.agents/verify/references/auth.md`.
+ and failure modes: `.agents/acceptance/references/auth.md`.
- **Login-state check** is standardized — do NOT hand-roll a `window.__LOBE_STORES`
- eval; use `.agents/verify/scripts/app-probe.sh auth` (returns `{ isSignedIn, userId }`,
+ eval; use `.agents/acceptance/scripts/app-probe.sh auth` (returns `{ isSignedIn, userId }`,
works for Electron CDP and web sessions via `AB_TARGET`).
## 4. Surfaces
@@ -194,23 +194,23 @@ stale standalone install: a recently added workspace package fails to resolve
### Electron
-- Launch: `.agents/verify/scripts/electron-dev.sh start` — CDP port `9222`
+- Launch: `.agents/acceptance/scripts/electron-dev.sh start` — CDP port `9222`
(idempotent; `status` / `stop` / `restart`; env `CDP_PORT`, `ELECTRON_LOG`,
`ELECTRON_WAIT_S`, `RENDERER_WAIT_S`, `LOBE_LOGIN_STATE_DIR`, `KEEP_DATA`,
`SKIP_LOGIN_SAVE`). Connect with `agent-browser --cdp 9222 snapshot -i`.
-- Stop: `.agents/verify/scripts/electron-dev.sh stop` — always use this;
+- Stop: `.agents/acceptance/scripts/electron-dev.sh stop` — always use this;
`pkill -f "Electron"` leaves helper processes (GPU, renderer, network) alive.
- Login persistence: `stop` snapshots the login to
`~/.lobehub/agent-testing/electron-login`; `start` seeds each new instance
from it (`login-status` inspects it, `save-login <id>` captures a live one).
Sign in once, not once per run — and if an instance comes up signed out, drive
the sign-in yourself (the OAuth+PKCE recipe and the three token-rotation traps
- are in `.agents/verify/references/auth.md`); never ask the user to click it.
+ are in `.agents/acceptance/references/auth.md`); never ask the user to click it.
- Concurrent instances (N worktrees / parallel runs): `electron-dev.sh` drives a
pool — `start <id>` gives each its own CDP port, userData dir (with copied
login), Vite port, and IPC id. Drive each with a distinct
`agent-browser --session s<port> --cdp <port>`. Pool design, the collision
- matrix, and the login-copy recipe: `.agents/verify/references/multi-instance.md`.
+ matrix, and the login-copy recipe: `.agents/acceptance/references/multi-instance.md`.
### Bot channels (project skill)
@@ -222,13 +222,13 @@ macOS-only). Route bot tests there.
## 5. Project probes & quick navigation
-`.agents/verify/scripts/app-probe.sh` is the LobeHub fast path into app state —
+`.agents/acceptance/scripts/app-probe.sh` is the LobeHub fast path into app state —
use it instead of hand-rolling `window.__LOBE_STORES` eval snippets. Targets
default to Electron (`--cdp 9222`); set `AB_TARGET="--session <name>"` for web
sessions.
```bash
-PROBE=.agents/verify/scripts/app-probe.sh
+PROBE=.agents/acceptance/scripts/app-probe.sh
$PROBE auth # login check → { isSignedIn, userId }
$PROBE route # current SPA route
$PROBE ops # running chat operations (type / startTime)
@@ -253,8 +253,8 @@ The Zustand store is at `window.__LOBE_STORES` (not `__ZUSTAND_STORES__`); the
chat input is `contenteditable` (snapshot with `-C`). For deeper one-off state
inspection, fall back to raw `agent-browser --cdp 9222 eval`. The agent-gateway
closed-loop probe/dump/analyze tooling lives at
-`.agents/verify/scripts/agent-gateway/`; the closed-loop + JWKS setup workflow is
-in `.agents/verify/references/agent-gateway.md`.
+`.agents/acceptance/scripts/agent-gateway/`; the closed-loop + JWKS setup workflow is
+in `.agents/acceptance/references/agent-gateway.md`.
## 6. Known constraints
@@ -268,8 +268,8 @@ in `.agents/verify/references/agent-gateway.md`.
and gate before the first `agent run`:
```bash
- .agents/verify/scripts/init-dev-env.sh qstash # terminal B — keep running
- .agents/verify/scripts/init-dev-env.sh preflight # non-zero exit if QStash (or Redis) is down
+ .agents/acceptance/scripts/init-dev-env.sh qstash # terminal B — keep running
+ .agents/acceptance/scripts/init-dev-env.sh preflight # non-zero exit if QStash (or Redis) is down
```
`FEATURE_FLAGS=-agent_self_iteration` only drops the self-iteration workflow
@@ -311,16 +311,16 @@ in `.agents/verify/references/agent-gateway.md`.
Deeper LobeHub-specific notes kept alongside the moved scripts:
-- `.agents/verify/references/auth.md` — per-surface auth mechanics, the seeded
+- `.agents/acceptance/references/auth.md` — per-surface auth mechanics, the seeded
web-login flow, the Electron OAuth+PKCE sign-in recipe and token-rotation traps,
and the Chrome cookie-injection fallback + failure modes.
-- `.agents/verify/references/agent-gateway.md` — the local agent-gateway
+- `.agents/acceptance/references/agent-gateway.md` — the local agent-gateway
closed-loop setup / probe / dump / analyze workflow (scripts under
- `.agents/verify/scripts/agent-gateway/`).
-- `.agents/verify/references/multi-instance.md` — the concurrent Electron
+ `.agents/acceptance/scripts/agent-gateway/`).
+- `.agents/acceptance/references/multi-instance.md` — the concurrent Electron
instance pool (N worktrees / parallel runs): per-instance CDP port, userData,
Vite port, IPC id, the collision matrix, and the login-copy recipe.
-The living logs (`.agents/verify/common-mistakes.md`,
-`.agents/verify/probe-mock-patterns.md`) hold the LobeHub-specific probe/mock and
+The living logs (`.agents/acceptance/common-mistakes.md`,
+`.agents/acceptance/probe-mock-patterns.md`) hold the LobeHub-specific probe/mock and
mistake recipes; the generic layer lives in the installed skill's `references/`.
diff --git a/.agents/verify/common-mistakes.md b/.agents/acceptance/common-mistakes.md
similarity index 100%
rename from .agents/verify/common-mistakes.md
rename to .agents/acceptance/common-mistakes.md
diff --git a/.agents/verify/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
similarity index 99%
rename from .agents/verify/probe-mock-patterns.md
rename to .agents/acceptance/probe-mock-patterns.md
index 5d1ba75c94e..fff0373de52 100644
--- a/.agents/verify/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -732,7 +732,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
- **Situation**: a real Claude Code / Codex run in the local no-`.env` env fails immediately with `Failed to sign operation JWT for hetero agent` (`apps/server/src/services/aiAgent/index.ts`). Nothing in the UI explains it; the topic just fails.
- **Cause**: `signOperationJwt` → `getSigningKey()` → `getJwksKey()` needs the `JWKS_KEY` RSA JWK, and `init-dev-env.sh` does not export one.
-- **Works**: the repo ships a generator — `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/verify/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.
+- **Works**: the repo ships a generator — `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/acceptance/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.
- **Note the failure is downstream-honest**: with `JWKS_KEY` set, the run proceeds and then fails at the hetero _sandbox_ (`Hetero sandbox spawn failed / unauthorized`) unless the agent has a real Claude Code token. Those are two different walls — don't read the second as the first.
### E25. Electron `will-attach-webview` params carry NO custom attributes — identity via data-\* never arrives
@@ -962,7 +962,7 @@ server process env, not the client.
```bash
env -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy -u ALL_PROXY -u all_proxy \
- -u NO_PROXY -u no_proxy ./.agents/verify/scripts/init-dev-env.sh dev
+ -u NO_PROXY -u no_proxy ./.agents/acceptance/scripts/init-dev-env.sh dev
```
Symptom fingerprint: every auth POST answers 307 in \~25ms with `application-code` time present, and
diff --git a/.agents/verify/references/agent-gateway.md b/.agents/acceptance/references/agent-gateway.md
similarity index 94%
rename from .agents/verify/references/agent-gateway.md
rename to .agents/acceptance/references/agent-gateway.md
index a4b4a3d8b5d..37be4d98250 100644
--- a/.agents/verify/references/agent-gateway.md
+++ b/.agents/acceptance/references/agent-gateway.md
@@ -34,14 +34,14 @@ local JWT → `auth_success` → full local loop.
# reuse of AGENT_GATEWAY_SERVICE_TOKEN). Source resolves to
# .records/env/gateway.env by default, else .env.local; override with
# JWKS_SOURCE=<env file>. (Managed agent-testing runs have NO .env.local.)
-.agents/verify/scripts/agent-gateway/local-gateway-setup.sh
+.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh
# 2. Start the worker (separate terminal) → http://localhost:8787
cd ../agent-gateway && bun run dev
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/health # → 200
# 3. Decisive check — does the local gateway accept the app's JWT?
-node .agents/verify/scripts/agent-gateway/local-gateway-probe.mjs
+node .agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs
# → RECV: {"type":"auth_success"} ✅ feasible
# 4. Point the APP at the local gateway and RESTART its dev server:
@@ -80,13 +80,13 @@ exactly why the gateway must already trust the signing key via
```bash
# 1. Start Electron with CDP
-.agents/verify/scripts/electron-dev.sh start
+.agents/acceptance/scripts/electron-dev.sh start
# 2. Navigate to a chat, switch runtime to Cloud Sandbox (gateway mode)
# 3. Install the probe + helpers
agent-browser --cdp 9222 eval --stdin \
- < .agents/verify/scripts/agent-gateway/probe.js
+ < .agents/acceptance/scripts/agent-gateway/probe.js
# 4. Send a tool-call message — manually or via type+press
agent-browser --cdp 9222 eval "window.__PROBE_EVENT('SENT')"
@@ -95,15 +95,15 @@ agent-browser --cdp 9222 eval "window.__PROBE_EVENT('SENT')"
# rightmost inactive tab as AWAY — edit ROUND_TRIPS / DWELL_MS in the
# file if you want different timing)
agent-browser --cdp 9222 eval --stdin \
- < .agents/verify/scripts/agent-gateway/tab-switch.js
+ < .agents/acceptance/scripts/agent-gateway/tab-switch.js
# 6. Wait for streaming to finish, then dump
agent-browser --cdp 9222 eval --stdin \
- < .agents/verify/scripts/agent-gateway/probe-dump.js \
+ < .agents/acceptance/scripts/agent-gateway/probe-dump.js \
> /tmp/probe.json
# 7. Analyze
-node .agents/verify/scripts/agent-gateway/analyze.mjs /tmp/probe.json
+node .agents/acceptance/scripts/agent-gateway/analyze.mjs /tmp/probe.json
```
The analyzer prints three sections: EVENTS, TIMELINE, REGRESSIONS. If
diff --git a/.agents/verify/references/auth.md b/.agents/acceptance/references/auth.md
similarity index 96%
rename from .agents/verify/references/auth.md
rename to .agents/acceptance/references/auth.md
index 33da8a3dc56..0d42ab1aa31 100644
--- a/.agents/verify/references/auth.md
+++ b/.agents/acceptance/references/auth.md
@@ -8,8 +8,8 @@ step.
Initialize helpers first:
```bash
-SCRIPT=".agents/verify/scripts/setup-auth.sh"
-TEST_ENV=".agents/verify/scripts/test-env.sh"
+SCRIPT=".agents/acceptance/scripts/setup-auth.sh"
+TEST_ENV=".agents/acceptance/scripts/test-env.sh"
eval "$($TEST_ENV --exports)"
```
@@ -44,9 +44,9 @@ For the self-contained no-root-`.env` dev environment, seed the baseline user
and API key once:
```bash
-.agents/verify/scripts/init-dev-env.sh seed-user
+.agents/acceptance/scripts/init-dev-env.sh seed-user
source .records/env/agent-testing-cli.env
-.agents/verify/scripts/setup-auth.sh cli-seed
+.agents/acceptance/scripts/setup-auth.sh cli-seed
```
The seed step writes `LOBE_API_KEY` for humans and maps it to the CLI's current
@@ -88,8 +88,8 @@ is authenticated.
For the seeded local dev environment, use the automatic path:
```bash
-.agents/verify/scripts/init-dev-env.sh seed-user
-.agents/verify/scripts/setup-auth.sh web-seed
+.agents/acceptance/scripts/init-dev-env.sh seed-user
+.agents/acceptance/scripts/setup-auth.sh web-seed
```
`web-seed` posts the seeded email/password to
@@ -154,7 +154,7 @@ and `start` seeds every new instance from that snapshot. Sign in once, not once
per run.
```bash
-EDEV=.agents/verify/scripts/electron-dev.sh
+EDEV=.agents/acceptance/scripts/electron-dev.sh
$EDEV login-status # which source seeds the next instance, and its expiry
$EDEV save-login <id> # snapshot a live instance without stopping it
```
@@ -162,7 +162,7 @@ $EDEV save-login <id> # snapshot a live instance without stopping it
The standard check (do NOT hand-roll a store eval) once Electron is up with CDP:
```bash
-.agents/verify/scripts/app-probe.sh auth
+.agents/acceptance/scripts/app-probe.sh auth
# → {"ok":true,"isSignedIn":true,"userId":"user_xxx"}
```
diff --git a/.agents/verify/references/dev-server.md b/.agents/acceptance/references/dev-server.md
similarity index 94%
rename from .agents/verify/references/dev-server.md
rename to .agents/acceptance/references/dev-server.md
index ed98a7c2331..5492bb49e2c 100644
--- a/.agents/verify/references/dev-server.md
+++ b/.agents/acceptance/references/dev-server.md
@@ -52,22 +52,22 @@ curl -s -o /dev/null -w '%{http_code}' "$SERVER_URL/"
AGENT_RUNTIME_MODE=queue pnpm run dev:next
# Without root .env: use the self-contained agent-testing env.
-.agents/verify/scripts/init-dev-env.sh dev-next
+.agents/acceptance/scripts/init-dev-env.sh dev-next
# Full-stack SPA + backend. Required for Web smoke.
# With root .env:
AGENT_RUNTIME_MODE=queue bun run dev
# Without root .env:
-.agents/verify/scripts/init-dev-env.sh dev
+.agents/acceptance/scripts/init-dev-env.sh dev
# Local QStash. Run in a separate terminal only when testing workflow paths.
-.agents/verify/scripts/init-dev-env.sh qstash
+.agents/acceptance/scripts/init-dev-env.sh qstash
# Restart — required to pick up server-side code changes.
# For a no-.env server started by init-dev-env.sh, stop only its owned process tree:
-.agents/verify/scripts/init-dev-env.sh stop-dev
-.agents/verify/scripts/init-dev-env.sh dev-next
+.agents/acceptance/scripts/init-dev-env.sh stop-dev
+.agents/acceptance/scripts/init-dev-env.sh dev-next
```
## When a server restart is needed
diff --git a/.agents/verify/references/multi-instance.md b/.agents/acceptance/references/multi-instance.md
similarity index 100%
rename from .agents/verify/references/multi-instance.md
rename to .agents/acceptance/references/multi-instance.md
diff --git a/.agents/verify/scripts/agent-gateway/analyze-events.ts b/.agents/acceptance/scripts/agent-gateway/analyze-events.ts
similarity index 99%
rename from .agents/verify/scripts/agent-gateway/analyze-events.ts
rename to .agents/acceptance/scripts/agent-gateway/analyze-events.ts
index 3eda8a1be16..18c99ec39a2 100644
--- a/.agents/verify/scripts/agent-gateway/analyze-events.ts
+++ b/.agents/acceptance/scripts/agent-gateway/analyze-events.ts
@@ -11,7 +11,7 @@
// 6. ROLLBACKS — msgN / childN / role drops in the active-topic timeline
//
// Usage:
-// bun run .agents/verify/scripts/agent-gateway/analyze-events.ts <dump.json>
+// bun run .agents/acceptance/scripts/agent-gateway/analyze-events.ts <dump.json>
import { readFileSync } from 'node:fs';
diff --git a/.agents/verify/scripts/agent-gateway/analyze.mjs b/.agents/acceptance/scripts/agent-gateway/analyze.mjs
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/analyze.mjs
rename to .agents/acceptance/scripts/agent-gateway/analyze.mjs
diff --git a/.agents/verify/scripts/agent-gateway/local-gateway-probe.mjs b/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs
similarity index 96%
rename from .agents/verify/scripts/agent-gateway/local-gateway-probe.mjs
rename to .agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs
index 97ae712aaaa..642ebe6d4ac 100644
--- a/.agents/verify/scripts/agent-gateway/local-gateway-probe.mjs
+++ b/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs
@@ -15,7 +15,7 @@
// 3. .records/env/gateway.env (managed flow default)
//
// Run from the lobehub repo root (needs `jose` from its node_modules):
-// JWKS_KEY="$JWKS_KEY" node .agents/verify/scripts/agent-gateway/local-gateway-probe.mjs
+// JWKS_KEY="$JWKS_KEY" node .agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs
// JWKS_SOURCE=.env.local node .../local-gateway-probe.mjs # explicit file
// GATEWAY_WS=ws://localhost:8787 node .../local-gateway-probe.mjs # override ws
diff --git a/.agents/verify/scripts/agent-gateway/local-gateway-setup.sh b/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh
similarity index 98%
rename from .agents/verify/scripts/agent-gateway/local-gateway-setup.sh
rename to .agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh
index 8c520cc666c..4b823f0d037 100755
--- a/.agents/verify/scripts/agent-gateway/local-gateway-setup.sh
+++ b/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh
@@ -19,7 +19,7 @@
# It then prints the app-side env you must set + how to start the worker.
#
# Usage (from the lobehub repo root):
-# .agents/verify/scripts/agent-gateway/local-gateway-setup.sh
+# .agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh
set -euo pipefail
diff --git a/.agents/verify/scripts/agent-gateway/probe-dump.js b/.agents/acceptance/scripts/agent-gateway/probe-dump.js
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/probe-dump.js
rename to .agents/acceptance/scripts/agent-gateway/probe-dump.js
diff --git a/.agents/verify/scripts/agent-gateway/probe-dump.ts b/.agents/acceptance/scripts/agent-gateway/probe-dump.ts
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/probe-dump.ts
rename to .agents/acceptance/scripts/agent-gateway/probe-dump.ts
diff --git a/.agents/verify/scripts/agent-gateway/probe-events.ts b/.agents/acceptance/scripts/agent-gateway/probe-events.ts
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/probe-events.ts
rename to .agents/acceptance/scripts/agent-gateway/probe-events.ts
diff --git a/.agents/verify/scripts/agent-gateway/probe.js b/.agents/acceptance/scripts/agent-gateway/probe.js
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/probe.js
rename to .agents/acceptance/scripts/agent-gateway/probe.js
diff --git a/.agents/verify/scripts/agent-gateway/run.ts b/.agents/acceptance/scripts/agent-gateway/run.ts
similarity index 96%
rename from .agents/verify/scripts/agent-gateway/run.ts
rename to .agents/acceptance/scripts/agent-gateway/run.ts
index b6af7317320..5c4a7905380 100644
--- a/.agents/verify/scripts/agent-gateway/run.ts
+++ b/.agents/acceptance/scripts/agent-gateway/run.ts
@@ -5,16 +5,16 @@
// streaming-replay test fixtures.
//
// Commands:
-// bun run .agents/verify/scripts/agent-gateway/run.ts install
+// bun run .agents/acceptance/scripts/agent-gateway/run.ts install
// Bundle probe-events.ts and inject into the CDP-attached browser.
// Re-installing clears all buffers and re-patches WebSocket / fetch.
//
-// bun run .agents/verify/scripts/agent-gateway/run.ts dump [name]
+// bun run .agents/acceptance/scripts/agent-gateway/run.ts dump [name]
// Stop the timeline timer, fetch the capture as JSON, write it to
// `.agent-gateway/<name>-<YYYYMMDD-HHmmss>.json`. `name` defaults to
// `dump`. Prints the absolute path written.
//
-// bun run .agents/verify/scripts/agent-gateway/run.ts analyze [path]
+// bun run .agents/acceptance/scripts/agent-gateway/run.ts analyze [path]
// Run analyze-events.ts on the dump. `path` defaults to the most
// recently modified file in `.agent-gateway/`.
//
@@ -28,7 +28,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
-// .agents/verify/scripts/agent-gateway/ → 4 levels up
+// .agents/acceptance/scripts/agent-gateway/ → 4 levels up
const PROJECT_ROOT = path.resolve(SCRIPT_DIR, '../../../..');
const DUMP_DIR = path.join(PROJECT_ROOT, '.agent-gateway');
diff --git a/.agents/verify/scripts/agent-gateway/tab-switch.js b/.agents/acceptance/scripts/agent-gateway/tab-switch.js
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/tab-switch.js
rename to .agents/acceptance/scripts/agent-gateway/tab-switch.js
diff --git a/.agents/verify/scripts/agent-gateway/types.ts b/.agents/acceptance/scripts/agent-gateway/types.ts
similarity index 100%
rename from .agents/verify/scripts/agent-gateway/types.ts
rename to .agents/acceptance/scripts/agent-gateway/types.ts
diff --git a/.agents/verify/scripts/app-probe.sh b/.agents/acceptance/scripts/app-probe.sh
similarity index 100%
rename from .agents/verify/scripts/app-probe.sh
rename to .agents/acceptance/scripts/app-probe.sh
diff --git a/.agents/verify/scripts/check-s3.mjs b/.agents/acceptance/scripts/check-s3.mjs
similarity index 100%
rename from .agents/verify/scripts/check-s3.mjs
rename to .agents/acceptance/scripts/check-s3.mjs
diff --git a/.agents/verify/scripts/electron-dev.sh b/.agents/acceptance/scripts/electron-dev.sh
similarity index 100%
rename from .agents/verify/scripts/electron-dev.sh
rename to .agents/acceptance/scripts/electron-dev.sh
diff --git a/.agents/verify/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.sh
similarity index 99%
rename from .agents/verify/scripts/init-dev-env.sh
rename to .agents/acceptance/scripts/init-dev-env.sh
index 388982c9f21..6b970fd9234 100755
--- a/.agents/verify/scripts/init-dev-env.sh
+++ b/.agents/acceptance/scripts/init-dev-env.sh
@@ -503,7 +503,7 @@ cmd_status() {
else
note "QStash is not answering as QStash at $QSTASH_URL (needed for agent-runtime / queue mode)"
fi
- if node "$REPO_ROOT/.agents/verify/scripts/check-s3.mjs" > /dev/null 2>&1; then
+ if node "$REPO_ROOT/.agents/acceptance/scripts/check-s3.mjs" > /dev/null 2>&1; then
ok "S3 reachable and writable: $S3_ENDPOINT/$S3_BUCKET"
else
note "S3 is not ready at $S3_ENDPOINT (start it with: $0 s3)"
@@ -541,7 +541,7 @@ cmd_preflight() {
note "AGENT_RUNTIME_MODE=$AGENT_RUNTIME_MODE (not queue) — QStash not required"
fi
- if node "$REPO_ROOT/.agents/verify/scripts/check-s3.mjs" > /dev/null 2>&1; then
+ if node "$REPO_ROOT/.agents/acceptance/scripts/check-s3.mjs" > /dev/null 2>&1; then
ok "S3 read/write/delete passed: $S3_ENDPOINT/$S3_BUCKET"
else
bad "S3 preflight failed at $S3_ENDPOINT/$S3_BUCKET"
@@ -655,7 +655,7 @@ cmd_s3() {
note "starting local S3 server at $S3_ENDPOINT"
note "bucket=$S3_BUCKET; data=$S3_DATA_DIR"
note "keep this process running while testing file uploads"
- exec node .agents/verify/scripts/start-s3.mjs
+ exec node .agents/acceptance/scripts/start-s3.mjs
}
cmd_dev_next() {
diff --git a/.agents/verify/scripts/init-dev-env.test.sh b/.agents/acceptance/scripts/init-dev-env.test.sh
similarity index 100%
rename from .agents/verify/scripts/init-dev-env.test.sh
rename to .agents/acceptance/scripts/init-dev-env.test.sh
diff --git a/.agents/verify/scripts/record-electron-demo.sh b/.agents/acceptance/scripts/record-electron-demo.sh
similarity index 100%
rename from .agents/verify/scripts/record-electron-demo.sh
rename to .agents/acceptance/scripts/record-electron-demo.sh
diff --git a/.agents/verify/scripts/setup-auth.sh b/.agents/acceptance/scripts/setup-auth.sh
similarity index 98%
rename from .agents/verify/scripts/setup-auth.sh
rename to .agents/acceptance/scripts/setup-auth.sh
index aee9bfe0e85..def441d2e30 100755
--- a/.agents/verify/scripts/setup-auth.sh
+++ b/.agents/acceptance/scripts/setup-auth.sh
@@ -143,7 +143,7 @@ check_cli() {
bad "CLI API-key auth failed for $SERVER_URL (http_code='$code')"
note "seed the local API key first:"
- note "./.agents/verify/scripts/init-dev-env.sh seed-user"
+ note "./.agents/acceptance/scripts/init-dev-env.sh seed-user"
note "source $CLI_ENV_FILE"
rm -f "$body_file"
return 1
@@ -154,7 +154,7 @@ check_cli() {
else
bad "CLI not logged in to $SERVER_URL"
note "automated path:"
- note "./.agents/verify/scripts/init-dev-env.sh seed-user && source $CLI_ENV_FILE && $0 cli-seed"
+ note "./.agents/acceptance/scripts/init-dev-env.sh seed-user && source $CLI_ENV_FILE && $0 cli-seed"
note "interactive fallback:"
note "cd apps/cli && LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts login --server $SERVER_URL"
return 1
@@ -487,7 +487,7 @@ PY
note "Use Chrome Cookie injection instead: $0 open-chrome, then pbpaste | $0 web"
else
note "make sure the seed user exists:"
- note "./.agents/verify/scripts/init-dev-env.sh seed-user"
+ note "./.agents/acceptance/scripts/init-dev-env.sh seed-user"
fi
return 1
fi
diff --git a/.agents/verify/scripts/setup-auth.test.sh b/.agents/acceptance/scripts/setup-auth.test.sh
similarity index 100%
rename from .agents/verify/scripts/setup-auth.test.sh
rename to .agents/acceptance/scripts/setup-auth.test.sh
diff --git a/.agents/verify/scripts/start-s3.mjs b/.agents/acceptance/scripts/start-s3.mjs
similarity index 100%
rename from .agents/verify/scripts/start-s3.mjs
rename to .agents/acceptance/scripts/start-s3.mjs
diff --git a/.agents/verify/scripts/test-env.sh b/.agents/acceptance/scripts/test-env.sh
similarity index 100%
rename from .agents/verify/scripts/test-env.sh
rename to .agents/acceptance/scripts/test-env.sh
diff --git a/.agents/verify/scripts/test-env.test.sh b/.agents/acceptance/scripts/test-env.test.sh
similarity index 85%
rename from .agents/verify/scripts/test-env.test.sh
rename to .agents/acceptance/scripts/test-env.test.sh
index 5356e314cef..a6a43ace8a4 100755
--- a/.agents/verify/scripts/test-env.test.sh
+++ b/.agents/acceptance/scripts/test-env.test.sh
@@ -26,11 +26,11 @@ tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
mkdir -p "$tmp_dir/lobehub-cloud-1/.agents" "$tmp_dir/lobehub/.agents"
-ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub-cloud-1/.agents/verify"
-ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub/.agents/verify"
+ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub-cloud-1/.agents/acceptance"
+ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub/.agents/acceptance"
-cloud_script="$tmp_dir/lobehub-cloud-1/.agents/verify/scripts/test-env.sh"
-oss_script="$tmp_dir/lobehub/.agents/verify/scripts/test-env.sh"
+cloud_script="$tmp_dir/lobehub-cloud-1/.agents/acceptance/scripts/test-env.sh"
+oss_script="$tmp_dir/lobehub/.agents/acceptance/scripts/test-env.sh"
assert_eq "$("$cloud_script" --value SERVER_URL)" "http://localhost:3021"
assert_eq "$("$cloud_script" --value SPA_PORT)" "9801"
diff --git a/.agents/skills/agent-testing-bot/SKILL.md b/.agents/skills/agent-testing-bot/SKILL.md
index 68d816ecfa5..85d2919c2f7 100644
--- a/.agents/skills/agent-testing-bot/SKILL.md
+++ b/.agents/skills/agent-testing-bot/SKILL.md
@@ -20,12 +20,12 @@ PLAN (Steps 0–2) → EXECUTE (Steps 3–6) → FINISH (Step 7)
```
— and the same report + publish pipeline (`result.json` → `report-init.sh` →
-`lh verify ingest-report … --source agent-testing`). Read the generic skill's
+`lh acceptance run ingest … --source agent-testing`). Read the generic skill's
`SKILL.md` for target grounding, the living logs, the Phase-1 approval gate, the
report format, and teardown. This file only adds the bot-channel surface.
For LobeHub environment/auth/probe specifics (dev server, seeded account, ports),
-the adapter is `.agents/verify/PROJECT.md`.
+the adapter is `.agents/acceptance/PROJECT.md`.
## When this surface applies
diff --git a/.agents/skills/agent-testing-bot/imessage/index.md b/.agents/skills/agent-testing-bot/imessage/index.md
index fcf969ef438..088835de9c6 100644
--- a/.agents/skills/agent-testing-bot/imessage/index.md
+++ b/.agents/skills/agent-testing-bot/imessage/index.md
@@ -21,7 +21,7 @@ So the test surface is three layers:
curl -sS -m4 -o /dev/null -w '%{http_code}\n' \
"http://127.0.0.1:1234/api/v1/server/info?password=<PW>" # expect 200
```
-- **Electron dev running with CDP**: `.agents/verify/scripts/electron-dev.sh start`
+- **Electron dev running with CDP**: `.agents/acceptance/scripts/electron-dev.sh start`
- The **iMessage Desktop branch** checked out (the `imessageBridge` IPC group
and `@lobechat/chat-adapter-imessage` must be compiled into the main bundle).
Run `pnpm install --ignore-scripts` at the repo root **and** in `apps/desktop/`
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index e8f3efa7c84..523d13a815d 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -27,7 +27,7 @@ Finish unless the user explicitly asks to keep the environment running.
**Everything project-specific comes from an adapter, not from this skill.** The
concrete start/stop commands, ports, auth, surfaces, and probes for the project
-under test live in `.agents/verify/PROJECT.md`. This skill supplies the process,
+under test live in `.agents/acceptance/PROJECT.md`. This skill supplies the process,
the evidence discipline, and the surface methodology; `PROJECT.md` supplies the
commands. When a step below says "from `PROJECT.md`", read that file for the
actual command instead of guessing. See
@@ -77,16 +77,16 @@ target selection.
- **If the goal is verifying error/failure states, do NOT stop at happy-path
when injection is hard.** Escalate (see the pattern library) until you have
real failure-state evidence.
-- **Project layer** (writable, owned by the project): `.agents/verify/common-mistakes.md`
- and `.agents/verify/probe-mock-patterns.md`, when they exist. These carry what
+- **Project layer** (writable, owned by the project): `.agents/acceptance/common-mistakes.md`
+ and `.agents/acceptance/probe-mock-patterns.md`, when they exist. These carry what
earlier runs learned about THIS project.
**The project layer is a living log — append to it during the run**, in English:
-- User gives negative feedback → new case in `.agents/verify/common-mistakes.md`
+- User gives negative feedback → new case in `.agents/acceptance/common-mistakes.md`
(Wrong approach / Why / What it breaks / Correct approach).
- You hit any probe/mock that is blocked, bypassed, or needs a workaround → new
- item in `.agents/verify/probe-mock-patterns.md` (Situation / Doesn't work /
+ item in `.agents/acceptance/probe-mock-patterns.md` (Situation / Doesn't work /
Works).
Write project-specific learnings to the **project layer only**. Never edit the
@@ -99,7 +99,7 @@ project layer.
### Step 0.5 — Adapter check (mandatory when `PROJECT.md` is missing)
-If `.agents/verify/PROJECT.md` does not exist, run the first-run bootstrap in
+If `.agents/acceptance/PROJECT.md` does not exist, run the first-run bootstrap in
[references/project-adapter.md](./references/project-adapter.md) BEFORE anything
else: explore the repo (package.json / README / CI workflows / Makefile / compose
files), draft a `PROJECT.md` from the fixed section skeleton, present it to the
@@ -288,7 +288,7 @@ installed; `chmod +x` is applied on install):
| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` |
Project-specific probes and env scripts (the "jump straight to app state" fast
-paths) live in the project's own `.agents/verify/scripts/` and are described in
+paths) live in the project's own `.agents/acceptance/scripts/` and are described in
`PROJECT.md` §5 — not here.
#### Agent-browser interaction-cost tracing (optional, UI runs)
@@ -319,7 +319,7 @@ estimates recorded with the `mental` subcommand. Analyze before publishing:
--trace "$TRACE" --result "$DIR/result.json" --write
```
-This writes `result.json.interactionCost`; `verify ingest-report` stores it on the
+This writes `result.json.interactionCost`; `acceptance run ingest` stores it on the
run metadata so the report can render a separate interaction-cost section.
### Step 5 — Structured report (mandatory deliverable)
@@ -400,7 +400,7 @@ profile looks like:
```bash
# Strip local-dev CLI overrides so `lh` uses production defaults + the user's real login.
env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --open --json
+ lh acceptance run ingest "$DIR" --source agent-testing --open --json
```
Production auth is the user's own device-code login. Verify it first in the same
@@ -414,7 +414,7 @@ older and fails only at this final step (`unknown option '--subject'`). Run
`lh --version` first; when it is older than the marker version, publish through
`npx @lobehub/cli@latest` instead of the PATH binary.
-`verify ingest-report` reads `$DIR` and, in one call, creates a new immutable
+`acceptance run ingest` reads `$DIR` and, in one call, creates a new immutable
verification run, attaches it to the subject acceptance, and uploads everything:
- `result.json.plan[]` → the frozen check plan, with a business-scenario
@@ -434,14 +434,14 @@ latest cross-round state; the round-specific
Every run MUST be chained onto a task, topic, or document **acceptance aggregate**,
so every round lands on one auditable decision page. When the harness runs inside a
-LobeHub topic, `ingest-report` automatically uses `LOBEHUB_TOPIC_ID` as
+LobeHub topic, `acceptance run ingest` automatically uses `LOBEHUB_TOPIC_ID` as
`topic:<id>` — do not ask the user for it and do not omit the acceptance. Outside a
LobeHub topic, an explicit subject is required and publishing without one fails:
```bash
# SUBJECT is task:$TASK_ID, topic:$TOPIC_ID, or document:$DOC_ID
env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" \
+ lh acceptance run ingest "$DIR" --source agent-testing --subject "$SUBJECT" \
--requirement "$REQUIREMENT" --open --json
```
@@ -458,7 +458,7 @@ later round that supplies one.
The first ingest creates the acceptance and every ingest creates its next
immutable round. The user closes the loop on `/acceptance/<acceptanceId>`; the
same state is available through
-`lh verify acceptance view|accept|reject <id | type:id>`.
+`lh acceptance view|accept|reject <id | type:id>`.
When no subject exists yet (first verification in a repo, no tracked task),
create one with the CLI instead of asking the user for an id — a dedicated task
@@ -481,7 +481,7 @@ state rather than memory:
```bash
env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify acceptance view "$SUBJECT" --json
+ lh acceptance view "$SUBJECT" --json
```
- `checks[].userReview.action === "accept"`: user-settled; omit it from the new
@@ -494,7 +494,7 @@ env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME
#### Every verification run is an immutable snapshot
-One call to `ingest-report` creates one immutable `/verify/<id>` snapshot. Never
+One call to `acceptance run ingest` creates one immutable `/verify/<id>` snapshot. Never
overwrite, replace, prune, or re-ingest into an earlier run. A fix followed by
re-verification MUST create another run on the same acceptance, preserving the
earlier plan, results, evidence, and verdict exactly as observed. Use a fresh
@@ -505,11 +505,11 @@ Notes:
- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;
`evidence` is a path (or array) relative to `$DIR`. `result`/`verdict` map onto
`passed | failed | uncertain`.
-- Finer control is available through the atomic commands — `verify run create`,
- `verify result ingest`, `verify evidence upload` (`--file` or `--content`),
- `verify report upsert`.
+- Finer control is available through the atomic commands — `acceptance run create`,
+ `acceptance run result ingest`, `acceptance run evidence upload` (`--file` or `--content`),
+ `acceptance run report upsert`.
- File evidence uploads through the platform's storage. Against a stub or
- unreachable bucket (common in local dev) the PUT fails; `ingest-report` warns,
+ unreachable bucket (common in local dev) the PUT fails; `acceptance run ingest` warns,
**skips that one artifact**, and still finishes — so the published session is
real and openable but **missing the skipped evidence**. Publish against real
storage (production defaults) if the evidence must appear.
@@ -536,7 +536,7 @@ source file silently corrupts the next run (and the next agent's mental model).
the WRONG revert — it wipes the branch's edits too; snapshot the file first and
restore from the snapshot (probe-mock-patterns covers this).
- **Keep the report + evidence.** `.records/reports/**` is the deliverable — do NOT
- delete it in teardown; it is gitignored and the published verify run points at
+ delete it in teardown; it is gitignored and the published acceptance run points at
it.
- **Check `git status` before reporting the tree clean.** Some dev servers write
managed files on start; reverting them can make them look like per-start churn.
diff --git a/.agents/skills/agent-testing/references/agent-browser.md b/.agents/skills/agent-testing/references/agent-browser.md
index 3f0f4a3c501..4382c2c982e 100644
--- a/.agents/skills/agent-testing/references/agent-browser.md
+++ b/.agents/skills/agent-testing/references/agent-browser.md
@@ -4,7 +4,7 @@ Generic reference for the `agent-browser` CLI — automate Chromium-based apps
(Electron, Chrome, web) via Chrome DevTools Protocol. Surface-specific patterns
live in [../surfaces/web.md](../surfaces/web.md) and
[../surfaces/electron.md](../surfaces/electron.md); project auth recipes live in
-`.agents/verify/PROJECT.md`.
+`.agents/acceptance/PROJECT.md`.
Install via `npm i -g agent-browser`, `brew install agent-browser`, or
`cargo install agent-browser`. Run `agent-browser install` to download Chrome. Run
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index 8e395a1e983..73af1cea883 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -4,7 +4,7 @@
> repo and updated only by PR to the CLI repo that ships this skill. Every entry
> here must be **product-independent** — no project's packages, routes, schemas,
> env vars, service names, or business logic. Project-specific learnings go to
-> `.agents/verify/common-mistakes.md` (the writable project layer).
+> `.agents/acceptance/common-mistakes.md` (the writable project layer).
>
> **Mandatory:** read this file in full before every agent-testing run and
> self-check against each case. When the user gives negative feedback that is
@@ -180,7 +180,7 @@ signals the agent will cut corners on fidelity when the env is inconvenient.
**What it breaks**: wastes a round on a question the user doesn't want.
**Correct approach**: for any "run it and show me" request, default to the **full
-isolated run** that ends in a published verify report — spin up whatever dedicated
+isolated run** that ends in a published acceptance report — spin up whatever dedicated
instance and fixture data the surface needs (a throwaway repo, an isolated dev
instance, seeded data), capture the real rendered evidence, verify it by opening the
image, and publish. Only surface a plan-approval question when the _product decision_
@@ -482,7 +482,7 @@ diagnosing shared infrastructure.
## M23 — Stopping after a fix without publishing the next verification round
**Wrong approach**: implementing and locally validating a requested iteration, then
-ending the task without committing, pushing, or publishing a fresh immutable verify run
+ending the task without committing, pushing, or publishing a fresh immutable acceptance run
to the existing acceptance.
**Why it's wrong**: an acceptance is the cross-round audit trail. A local-only fix
diff --git a/.agents/skills/agent-testing/references/plan.md b/.agents/skills/agent-testing/references/plan.md
index 5e268238bf4..526d5f7e6fd 100644
--- a/.agents/skills/agent-testing/references/plan.md
+++ b/.agents/skills/agent-testing/references/plan.md
@@ -77,7 +77,7 @@ dedicated screenshot or recording for that exact claim — program output may
supplement it but cannot replace visual evidence.
On a follow-up round, seed the plan from
-`lh verify acceptance view <subject> --json` before writing any case:
+`lh acceptance view <subject> --json` before writing any case:
- Accepted checks are user-settled; omit them from the new plan.
- Rejected, non-stale checks are the primary repair items. Carry their comments
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index b0c5fc7201c..dc0da47b82e 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -4,7 +4,7 @@
> repo and updated only by PR to the CLI repo that ships this skill. Every recipe
> here must be **product-independent** — framework-level or tool-level, no project's
> stores, routes, tables, env vars, or file paths. Project-specific probes and mocks
-> go to `.agents/verify/probe-mock-patterns.md` (the writable project layer).
+> go to `.agents/acceptance/probe-mock-patterns.md` (the writable project layer).
>
> **Read this before any run that must force an error state or inspect runtime
> state.** Each item: Situation / Doesn't work / Works.
@@ -236,7 +236,7 @@ derive(item))`) captures the value at first render. When a persisted cache hydra
### C5. A successful ingest does not prove acceptance attachment when the CLI is stale
-- A globally installed CLI may accept `ingest-report` and return a run id while
+- A globally installed CLI may accept `acceptance run ingest` and return a run id while
lacking newer subject/acceptance behavior. The result is an orphan round even
though the command appears successful.
- Compare `lh --version` with the skill marker before publishing. If the branch
@@ -378,6 +378,6 @@ unquoted vars` — stashing `S="--session x --cdp 9226"` then `agent-browser $S`
moment containing none of its strings, every assertion `false`. It reads like a product bug;
it is two runs sharing one browser. **Works**: give every run its own session name, seed auth
into it, and confirm the tab is yours before asserting — `agent-browser --session <name> tab
- list` must print YOUR port and path. Same applies to ports: a worktree allocates its own
+list` must print YOUR port and path. Same applies to ports: a worktree allocates its own
`SERVER_PORT`/`SPA_PORT`, so re-run `test-env.sh` inside the worktree you are testing rather
than assuming another checkout's ports.
diff --git a/.agents/skills/agent-testing/references/project-adapter.md b/.agents/skills/agent-testing/references/project-adapter.md
index 267a180c6d9..5475961dd30 100644
--- a/.agents/skills/agent-testing/references/project-adapter.md
+++ b/.agents/skills/agent-testing/references/project-adapter.md
@@ -1,22 +1,22 @@
-# Project Adapter (`.agents/verify/PROJECT.md`)
+# Project Adapter (`.agents/acceptance/PROJECT.md`)
This skill is project-agnostic. Everything specific to the project under test — how
to start and stop it, which ports and services it needs, how auth works, which
surfaces it has, and how to jump straight into app state — lives in a per-project
-adapter at `.agents/verify/PROJECT.md`. The skill reads it; it never guesses the
+adapter at `.agents/acceptance/PROJECT.md`. The skill reads it; it never guesses the
project's commands.
## Where the adapter lives
```text
-<repo>/.agents/verify/ # committed — the adapter and project logs are team assets
+<repo>/.agents/acceptance/ # committed — the adapter and project logs are team assets
├── PROJECT.md # the adapter (this contract)
├── common-mistakes.md # PROJECT-layer living log (writable)
├── probe-mock-patterns.md # PROJECT-layer living log (writable)
└── scripts/ # optional: project env / probe scripts
```
-`.agents/verify/` is **committed** (the adapter and the project living logs are
+`.agents/acceptance/` is **committed** (the adapter and the project living logs are
shared, versioned team assets). The report output directory `.records/` is
**gitignored** — reports are per-run artifacts, published to the verify platform,
not committed.
@@ -49,7 +49,7 @@ to by number (`PROJECT.md §2`, `§3`, …), so keep the numbering.
the queue service up"), standalone sub-packages that need their own install,
surfaces that only work on macOS, or any repo-specific gotcha a run must respect.
-`PROJECT.md` may reference project scripts under `.agents/verify/scripts/` or
+`PROJECT.md` may reference project scripts under `.agents/acceptance/scripts/` or
anywhere in the repo.
## Copy-pasteable template
@@ -122,7 +122,7 @@ which directory/package is the server, the web app, the desktop shell, the CLI.>
## First-run bootstrap (SKILL.md Step 0.5)
-When `.agents/verify/PROJECT.md` is absent, build it before doing anything else:
+When `.agents/acceptance/PROJECT.md` is absent, build it before doing anything else:
1. **Explore the repo.** Read the signals that reveal how the project runs:
`package.json` scripts, `README`, CI workflows (`.github/workflows/**`),
@@ -136,8 +136,8 @@ When `.agents/verify/PROJECT.md` is absent, build it before doing anything else:
confirm or correct it — especially the start/stop commands, the required
services, and the auth path. Do not run a dev server or write test steps against
an unconfirmed adapter.
-4. **Write it only after approval**, to `.agents/verify/PROJECT.md`. Create
- `.agents/verify/` if it does not exist.
+4. **Write it only after approval**, to `.agents/acceptance/PROJECT.md`. Create
+ `.agents/acceptance/` if it does not exist.
`install` (the CLI's `lh verify install`) only places the skill files; it does no repo
exploration. The adapter draft needs a model, so the first verification run is what
@@ -155,7 +155,7 @@ next run should not rediscover the same divergence.
The skill's `references/common-mistakes.md` and `references/probe-mock-patterns.md`
are the **generic layer** — product-independent, read-only in consumer repos,
updated only by PR to the CLI repo. The project's own
-`.agents/verify/common-mistakes.md` and `.agents/verify/probe-mock-patterns.md` are
+`.agents/acceptance/common-mistakes.md` and `.agents/acceptance/probe-mock-patterns.md` are
the **project layer** — writable, and the only place a run records project-specific
learnings. At runtime the agent reads both layers and writes only the project layer.
When a project-layer entry turns out to be product-independent, genericize it (drop
diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.md
index fe0b46cbd41..78a732549d5 100644
--- a/.agents/skills/agent-testing/references/report.md
+++ b/.agents/skills/agent-testing/references/report.md
@@ -145,7 +145,7 @@ table — those double up on the page. It carries only the non-duplicate narrati
```bash
env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --open --json
+ lh acceptance run ingest "$DIR" --source agent-testing --open --json
```
This creates a new immutable verification run, attaches it to the required
@@ -154,7 +154,7 @@ table — those double up on the page. It carries only the non-duplicate narrati
production link in the final reply alongside the local report dir. See SKILL.md →
Step 6 for why production defaults (a localhost URL isn't shareable and a local
stub storage fails file-evidence uploads), the production login check, and the
- atomic commands (`verify run|result|evidence|report …`).
+ atomic commands (`acceptance run …` (plus `… result`, `… evidence`, `… report`)).
## Report language (hard rule)
@@ -299,7 +299,7 @@ reads first: `pass`, `fail`, or `partial`.
immutable run: either `"subject": "task:<id>"` (`task` | `topic` | `document`) or
`{ "type": "task", "id": "task_…", "requirement": "one-sentence acceptance bar" }`.
The `--subject` flag overrides this field. Inside a LobeHub conversation, both may
-be omitted because `ingest-report` defaults to `topic:$LOBEHUB_TOPIC_ID`; outside a
+be omitted because `acceptance run ingest` defaults to `topic:$LOBEHUB_TOPIC_ID`; outside a
topic, an explicit subject is mandatory. Every ingest creates a new immutable run;
never update a prior run after a fix, publish the re-verification as the next round.
@@ -307,7 +307,7 @@ never update a prior run after a fix, publish the re-verification as the next ro
`agent-browser`, create `interaction-trace.jsonl` with `scripts/agent-browser-klm.mjs`,
then run `scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`.
-When published, `verify ingest-report` maps each case onto a check result:
+When published, `acceptance run ingest` maps each case onto a check result:
`name`→title, `status`/`result`→verdict, `observation`→the result's key
observation, and `evidence` paths→uploaded artifacts. `summary.{total,passed,failed,blocked}`
and `verdict` become the report's stats + overall verdict; `report.md` becomes the
diff --git a/.agents/skills/agent-testing/scripts/fixture.mjs b/.agents/skills/agent-testing/scripts/fixture.mjs
index e859a18e7c2..d867d58edfd 100755
--- a/.agents/skills/agent-testing/scripts/fixture.mjs
+++ b/.agents/skills/agent-testing/scripts/fixture.mjs
@@ -30,7 +30,7 @@
* [--focus "..."] [--entry "..."] <check-id> [<check-id>...]
* Assemble a report-shaped round dir from the given checks:
* .records/reports/topic-tpc_xxx/<ts>-<slug>/ (ready for
- * `lh verify ingest-report <dir>`). Files referenced by case.evidence
+ * `lh acceptance run ingest <dir>`). Files referenced by case.evidence
* (seed/…) are copied into the round's assets/<check-id>/ and paths
* rewritten. Prints the dir path.
*
diff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/skills/agent-testing/scripts/report-init.sh
index d2ada73d3d9..dad20906a66 100755
--- a/.agents/skills/agent-testing/scripts/report-init.sh
+++ b/.agents/skills/agent-testing/scripts/report-init.sh
@@ -10,7 +10,7 @@
# under its acceptance:
# .records/reports/<type>-<id>/<YYYYMMDD-HHMMSS>-<slug>/
# and the group directory gets an acceptance.json marker. The subject is also
-# pre-filled into result.json so ingest-report attaches the run automatically.
+# pre-filled into result.json so acceptance run ingest attaches the run automatically.
#
# Run this from the CONSUMER repo root — the report is created relative to the
# current working directory, not relative to this script's own location.
diff --git a/.agents/skills/agent-testing/surfaces/cli.md b/.agents/skills/agent-testing/surfaces/cli.md
index d4650d9b20f..1028b866ea9 100644
--- a/.agents/skills/agent-testing/surfaces/cli.md
+++ b/.agents/skills/agent-testing/surfaces/cli.md
@@ -3,7 +3,7 @@
Default surface for verifying **backend changes** (routers, services, models,
migrations) end-to-end: fastest loop, text-assertable output, zero UI flakiness.
The project's CLI, its invocation, and its auth all come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) — this guide is the
+[`.agents/acceptance/PROJECT.md`](../references/project-adapter.md) — this guide is the
methodology, not the commands.
## When to use
diff --git a/.agents/skills/agent-testing/surfaces/electron.md b/.agents/skills/agent-testing/surfaces/electron.md
index e9f1d4587c2..8371f48069a 100644
--- a/.agents/skills/agent-testing/surfaces/electron.md
+++ b/.agents/skills/agent-testing/surfaces/electron.md
@@ -8,7 +8,7 @@ command reference.
The launch/stop of the desktop dev instance, its CDP port, its login persistence,
and any state probes all come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) §4/§5. This guide is
+[`.agents/acceptance/PROJECT.md`](../references/project-adapter.md) §4/§5. This guide is
the CDP methodology; the project supplies the commands.
## Auth
diff --git a/.agents/skills/agent-testing/surfaces/web.md b/.agents/skills/agent-testing/surfaces/web.md
index 9488555f89f..17801ed26a7 100644
--- a/.agents/skills/agent-testing/surfaces/web.md
+++ b/.agents/skills/agent-testing/surfaces/web.md
@@ -8,7 +8,7 @@ For pure-frontend changes in a project that ships a desktop shell, prefer
[electron.md](./electron.md); for backend-only changes prefer [cli.md](./cli.md).
The base URL, session name, and auth for the web surface come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) §4/§3. This guide is
+[`.agents/acceptance/PROJECT.md`](../references/project-adapter.md) §4/§3. This guide is
the methodology.
## Prerequisites
diff --git a/apps/cli/package.json b/apps/cli/package.json
index fb67013317c..4acce45a099 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -14,8 +14,7 @@
],
"files": [
"dist",
- "man",
- "skills"
+ "man"
],
"scripts": {
"build": "tsdown",
diff --git a/apps/cli/skills/agent-testing/SKILL.md b/apps/cli/skills/agent-testing/SKILL.md
deleted file mode 100644
index e8f3efa7c84..00000000000
--- a/apps/cli/skills/agent-testing/SKILL.md
+++ /dev/null
@@ -1,573 +0,0 @@
----
-name: agent-testing
-description: >
- Agentic end-to-end testing for any project: backend verification via the
- project CLI, frontend verification via agent-browser (web), and desktop
- verification via CDP (Electron). Drives the real surface, captures visually
- confirmed evidence, and publishes a structured report to the LobeHub verify
- platform. Triggers on 'cli test', 'test with cli', 'verify with cli',
- 'backend test with cli', 'local test', 'test in electron', 'test desktop',
- 'manual test', 'test report', or any local end-to-end verification task.
----
-
-# Agent Testing (Agentic End-to-End Verification)
-
-One skill for agentic end-to-end testing of any project — backend through the
-project CLI, web through a browser, desktop through Electron/CDP. Every session
-follows three phases:
-
-```text
-PLAN (Steps 0–2) → EXECUTE (Steps 3–6) → FINISH (Step 7)
-```
-
-Do not enter Execute until Plan has confirmed both the environment state and the
-execution plan. Treat Steps 3–6 as one continuous execution phase: select the
-surface, run the cases, produce the report, and publish it. Always end with
-Finish unless the user explicitly asks to keep the environment running.
-
-**Everything project-specific comes from an adapter, not from this skill.** The
-concrete start/stop commands, ports, auth, surfaces, and probes for the project
-under test live in `.agents/verify/PROJECT.md`. This skill supplies the process,
-the evidence discipline, and the surface methodology; `PROJECT.md` supplies the
-commands. When a step below says "from `PROJECT.md`", read that file for the
-actual command instead of guessing. See
-[references/project-adapter.md](./references/project-adapter.md).
-
-## Phase 1 — Plan
-
-Confirm what will run and whether the environment is ready before changing or
-starting anything.
-
-Skill-internal setup — loading this skill, reading the living logs and reference
-files — is silent preparation: never narrate it to the user ("I'll load the
-mandatory living logs first…" is noise). The first user-visible message of a
-session is about the user's test — the target confirmation (Step 0) or the
-Phase 1 approval gate — in one message, not a setup announcement followed by the
-same question again.
-
-### Step 0 — Ground the target, then read the two living-log layers (mandatory)
-
-**A test target must exist before anything else happens.** When the invocation
-carries none (bare skill invocation, no pending ask in the conversation), ground
-it first — do NOT read the living logs or touch the environment yet:
-
-1. Take the target from the user's words in this conversation when they exist —
- the task lives in their words, not in git (common-mistakes: task from the ask,
- not the branch).
-2. Otherwise, infer the most likely candidate from observable context (current
- branch, recent commits, working-tree changes) and confirm it with one
- structured question — the candidate as the recommended option, clearly labeled
- as a guess. Never start executing against an unconfirmed guess.
-3. Only when nothing is inferable, ask one direct open question. Asking "what
- should I verify" is the one legitimate opening question — but asking it
- open-ended when a candidate was inferable wastes the user's turn.
-
-**Once the target is known**, read both layers of both living logs in full and
-hold them in mind for this run. Reading them before a target exists wastes
-context that may be compacted away before Execute — they inform execution, not
-target selection.
-
-- **Generic layer** (ships with this skill, read-only here):
- [references/common-mistakes.md](./references/common-mistakes.md) and
- [references/probe-mock-patterns.md](./references/probe-mock-patterns.md).
- Two mistakes that keep biting:
- - **Never declare a case `passed` from grep/skeleton-count heuristics — open the
- actual screenshot with Read and confirm it rendered the expected content.** A
- blank/white page also has 0 skeletons and still matches persistent nav text.
- - **If the goal is verifying error/failure states, do NOT stop at happy-path
- when injection is hard.** Escalate (see the pattern library) until you have
- real failure-state evidence.
-- **Project layer** (writable, owned by the project): `.agents/verify/common-mistakes.md`
- and `.agents/verify/probe-mock-patterns.md`, when they exist. These carry what
- earlier runs learned about THIS project.
-
-**The project layer is a living log — append to it during the run**, in English:
-
-- User gives negative feedback → new case in `.agents/verify/common-mistakes.md`
- (Wrong approach / Why / What it breaks / Correct approach).
-- You hit any probe/mock that is blocked, bypassed, or needs a workaround → new
- item in `.agents/verify/probe-mock-patterns.md` (Situation / Doesn't work /
- Works).
-
-Write project-specific learnings to the **project layer only**. Never edit the
-generic layer from a consumer repo — it is read-only and updated by PR to the CLI
-repo. **Confidentiality of the generic layer:** its entries must be
-product-independent. If a learning turns out to be product-independent and worth
-sharing, genericize it and open a PR upstream; keep anything naming a project's
-packages, routes, schemas, env vars, service names, or business logic in the
-project layer.
-
-### Step 0.5 — Adapter check (mandatory when `PROJECT.md` is missing)
-
-If `.agents/verify/PROJECT.md` does not exist, run the first-run bootstrap in
-[references/project-adapter.md](./references/project-adapter.md) BEFORE anything
-else: explore the repo (package.json / README / CI workflows / Makefile / compose
-files), draft a `PROJECT.md` from the fixed section skeleton, present it to the
-user for confirmation, and write it only after approval. Do not start a dev
-server or write test steps against an unconfirmed adapter.
-
-When `PROJECT.md` exists, read it now — every concrete command in Steps 1–7 comes
-from it. When observed reality diverges from it during the run, fix the adapter in
-place (adapter drift is a living-log entry: amend the file during the run).
-
-### Step 1 — Prepare the execution plan
-
-Skip directly to Step 2 if: the test is a single re-run after a fix, the plan was
-already agreed on, or the user gave exact commands.
-
-Prepare the proposed surface, cases, expected evidence, assumptions, and report
-deliverable. Do not ask for approval yet: Step 2 must establish the real
-environment state first so the user can approve one complete, evidence-backed plan
-instead of separate plan and environment prompts.
-
-### Step 2 — Confirm environment state and auth (mandatory)
-
-Step 2 is about getting the environment ready: **dependencies are healthy** and
-**auth is green**. A test run that dies halfway on a missing dependency or a login
-wall wastes the whole session — clear both gates BEFORE writing a single test
-step. The concrete commands for each check come from `PROJECT.md`; the rules below
-are the ones that hold for every project.
-
-#### 2.0 Resolve the current test environment
-
-Before starting a dev server, checking auth, opening agent-browser, or writing
-test steps, resolve and confirm the environment `PROJECT.md` describes — the base
-URLs, ports, and required services. Do not rely on a hard-coded port table: read
-the values from the project's own env resolver (per `PROJECT.md` §2). If the
-resolved values do not match a running dev server, fix/export the env first, then
-continue.
-
-#### 2.1 Dependencies are installed
-
-Install per `PROJECT.md` §2. **Universal rule: a monorepo root install does not
-always cover every app.** If the project has standalone sub-packages with their
-own `node_modules` (the adapter says which), install in each one the test will
-touch — a stale standalone install typically fails at build/launch with an
-unresolved workspace import.
-
-#### 2.2 Run long-lived scripts from the repo root
-
-Background commands inherit the current working directory. Relative paths in this
-skill and in `PROJECT.md` are repo-root-relative, so a script launched while `cwd`
-is a sub-package can fail with `No such file or directory`. Verify `pwd` is the
-repo root before launching long-running scripts.
-
-#### 2.3 Start the dev environment
-
-Start the environment per `PROJECT.md` §2 (dev server, plus any required services
-such as a database, cache, queue, or object store). **Universal rules:**
-
-- Prefer the project's own already-configured local environment when one exists;
- do not clobber a user's running config.
-- Any service the feature under test depends on is a **hard prerequisite**, not an
- "only when needed" nicety. If a run touches a code path that dispatches to a
- queue/worker/object store, that service must be up first or the run dies before
- reaching the code under test — and the failure often reads as unrelated to the
- env. `PROJECT.md` §6 lists these constraints; gate on them.
-
-#### 2.4 Auth is green for the selected surface
-
-**Auth is the gate for automated testing, but the gate is surface-scoped.** Pick
-the intended surface first when it is already clear from the task, then check only
-that surface. Do not block a web test on CLI auth or a desktop login state unless
-the test spans those surfaces. Run the per-surface status check from `PROJECT.md`
-§3. If a surface is signed out, **drive the sign-in yourself** — auth is
-environment mechanics the skill owns; never hand the user the sign-in click unless
-a step genuinely needs something only they can supply (a 2FA push), and then name
-the exact blocking step.
-
-#### 2.5 Screen-recording preflight (OS-capture surfaces only)
-
-macOS `screencapture` / osascript captures come out **entirely black** when Screen
-Recording (TCC) permission is missing OR — just as often — the **display is
-asleep / locked / on a screensaver** (permission is fine, but there is nothing lit
-to capture; this bites after a long idle run). A black PNG is easy to mistake for
-a real capture, so gate BEFORE any OS-capture step:
-
-```bash
-# $SKILL_DIR = wherever this skill is installed
-"$SKILL_DIR/scripts/check-screen-recording.sh" # exit 0 = OS capture will work
-```
-
-It checks both layers — permission and a real one-frame blackness probe — and
-prints the exact fix. `capture-app-window.sh` runs it automatically and refuses to
-write a black artifact (bypass with `SKIP_SCREEN_CHECK=1`). This gate is **only**
-for OS-capture surfaces. CDP-based evidence (`agent-browser screenshot`,
-`cdp-screenshot.sh`, `record-app-screen.sh`) renders from the browser engine and
-is unaffected. Because the display can sleep mid-run, keep it awake for the whole
-capture session:
-
-```bash
-caffeinate -dimsu & # prevent display/idle sleep for the run; kill when done
-```
-
-#### Phase 1 approval gate — report environment + plan to the user
-
-At the end of Step 2, always send one user-facing Plan feedback before entering
-Execute. Read and follow [references/plan.md](./references/plan.md). It requires:
-
-- an overall environment verdict with concrete checks and evidence;
-- emoji-prefixed status markers in the verdict and every table row
- (`✅ Ready`, `⚠️ Warning`, `❌ Blocked`, `⏳ Pending`);
-- the proposed execution plan, cases, and expected evidence;
-- every unresolved prerequisite, clearly assigned to the agent or the user;
-- an explicit statement that nothing is needed from the user when that is true;
-- one structured confirmation question after the feedback.
-
-Resolve safe, agent-owned environment mechanics before presenting the gate. Ask
-the user only for prerequisites that genuinely require their authority, secret,
-device action, or product decision. Do not enter Phase 2 until the user approves
-the plan and all blocking user-owned prerequisites are satisfied.
-
-## Phase 2 — Execute
-
-Carry the approved plan through surface selection, verification, reporting, and
-publication without reopening environment decisions unless observed state
-invalidates the plan.
-
-### Step 3 — Pick the surface by change scope
-
-| Change scope | Default surface | Why | Guide |
-| -------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------- |
-| **Backend** (router / service / model / migration) | **CLI** | Fastest loop, text-assertable output, zero UI flakiness | [surfaces/cli.md](./surfaces/cli.md) |
-| **Pure frontend** (components, store, styles, UX) | **Electron** (agent-browser + CDP) if the project ships a desktop shell, else **Web** | Primary product shape; live state introspection | [surfaces/electron.md](./surfaces/electron.md) |
-| **Full-stack** (new API + UI consuming it) | **Web** (browser + local dev server) | One surface where network requests and UI are observable together | [surfaces/web.md](./surfaces/web.md) |
-
-Which of these surfaces the project actually has, and how each one launches, comes
-from `PROJECT.md` §4. Escalate, don't duplicate: verify a backend change with the
-CLI first; only add a UI pass when the change actually affects the UI.
-
-**Verify the change runs where you think it does — confirm runtime, don't assume.**
-Some features have two execution paths and the UI silently picks one (e.g. a client
-runtime vs a server/queue runtime). A test that exercises the wrong path can pass
-green without ever touching the code under test. Before trusting a result, **prove
-which runtime ran** — a server-side operation row, a queue step, a server-only log
-line. If the UI won't take the intended path, drive it directly (call the server
-endpoint) so that runtime actually executes.
-
-#### Environment support (local macOS vs cloud Linux)
-
-The decisive constraint per surface is **how evidence (screenshots) is captured**:
-CDP-based capture (`agent-browser screenshot`) renders from the browser engine and
-needs no real display; OS-level capture (`screencapture`, osascript) is macOS-only.
-
-| Surface | macOS (local) | Linux / cloud (headless) | Screenshot mechanism |
-| -------- | ------------- | --------------------------------------------------------- | ------------------------------------------------------ |
-| CLI | ✅ | ✅ | n/a — text output |
-| Web | ✅ | ✅ headless Chromium works natively | CDP — no display needed |
-| Electron | ✅ | ⚠️ runs, but needs a display server: wrap with `xvfb-run` | CDP works under Xvfb; `capture-app-window.sh` does NOT |
-
-When a test must stay cloud-portable, prefer CDP-based evidence over OS-level
-capture wherever both exist.
-
-### Step 4 — Run
-
-Surface guides above carry the detailed workflows. Shared infrastructure:
-
-| Need | Where |
-| ---------------------------------- | -------------------------------------------------------------------- |
-| `agent-browser` command reference | [references/agent-browser.md](./references/agent-browser.md) |
-| osascript patterns (general macOS) | [references/osascript.md](./references/osascript.md) |
-| Screen recording | [references/record-app-screen.md](./references/record-app-screen.md) |
-
-#### Scripts
-
-All under `<skill-dir>/scripts/` (resolve `<skill-dir>` to wherever this skill is
-installed; `chmod +x` is applied on install):
-
-| Script | Usage |
-| ------------------------------- | ----------------------------------------------------------------------------------------------- |
-| `report-init.sh` | Scaffold a structured report grouped by acceptance subject (Step 5) |
-| `fixture.mjs` | Per-check fixtures: `init-check`, `list`, and `compose` an ingest-ready round (Step 5) |
-| `record-gif.sh` | Frame-sequence → GIF for time-based behavior (streaming, timers, animations) |
-| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |
-| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses the agent-browser daemon); `--check` preflight |
-| `capture-app-window.sh` | Screenshot a specific app window (general; macOS OS capture) |
-| `record-app-screen.sh` | Record app screen (CDP screenshots → video + gallery) |
-| `agent-browser-klm.mjs` | Wrap `agent-browser`, run the real action, append a GOMS-KLM interaction atom JSONL |
-| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` |
-
-Project-specific probes and env scripts (the "jump straight to app state" fast
-paths) live in the project's own `.agents/verify/scripts/` and are described in
-`PROJECT.md` §5 — not here.
-
-#### Agent-browser interaction-cost tracing (optional, UI runs)
-
-For UI verification runs, drive cost-bearing browser actions through the KLM
-wrapper so the same action also records a user-equivalent interaction atom:
-
-```bash
-TRACE="$DIR/interaction-trace.jsonl"
-SESSION=your-session # from PROJECT.md
-
-"$SKILL_DIR/scripts/agent-browser-klm.mjs" \
- --klm-trace "$TRACE" --klm-phase login --klm-check case-1 \
- --session "$SESSION" click @e3
-
-"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \
- --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \
- --confidence 0.75 --reason "First view requires understanding state and next action"
-```
-
-The wrapper forwards every non-`--klm-*` argument to `agent-browser`. Physical
-actions are inferred from the browser command (`click → P+K`, `fill/type →
-P+T(n)`, `press → K`, `wait → R`). Mental operators (`M`) are explicit agent
-estimates recorded with the `mental` subcommand. Analyze before publishing:
-
-```bash
-"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \
- --trace "$TRACE" --result "$DIR/result.json" --write
-```
-
-This writes `result.json.interactionCost`; `verify ingest-report` stores it on the
-run metadata so the report can render a separate interaction-cost section.
-
-### Step 5 — Structured report (mandatory deliverable)
-
-Every automated test session ends with a structured, evidence-backed report — not
-a chat-only summary. Scaffold it up front and fill it as you test:
-
-```bash
-# Pass the acceptance subject up front so every round is grouped correctly.
-DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-feature "Verify my feature")
-# ... test, saving screenshots / CLI transcripts into $DIR/assets/ ...
-# fill $DIR/result.json (scenario, context, plan[], cases[], summary.conclusion) — the report;
-# $DIR/report.md holds only the narrative tail (follow-ups / notes / score)
-```
-
-Reports live in `.records/reports/<subject-key>/<timestamp>-<slug>/` (instruct
-the project to gitignore `.records/`), grouped by acceptance. The subject
-directory contains an `acceptance.json` marker and one subdirectory per
-immutable round. Passing `--subject` also pre-fills `result.json.subject`.
-Format and evidence rules: [references/report.md](./references/report.md).
-
-#### Fixtures: reusable per-check inputs
-
-When a check needs reusable seed data or replay steps, keep it under
-`.records/fixtures/<subject-key>/<check-id>/`: `check.json` stores the plan and
-case template; `seed/` stores reusable inputs. Execution outputs such as
-screenshots and transcripts remain in the round's `assets/` and must never be
-copied back into a fixture.
-
-```bash
-F="$SKILL_DIR/scripts/fixture.mjs"
-$F init-check --subject topic:tpc_xxx palette-long-list
-$F list --subject topic:tpc_xxx
-DIR=$($F compose --subject topic:tpc_xxx --slug round4 --title "Full regression" \
- palette-open palette-long-list)
-```
-
-Hard rules worth front-loading:
-
-- **Report language = the user's conversation language.** Write `report.md` and
- every human-facing string in `result.json` (case `name`/`observation`,
- `summary.conclusion`, scope `focus`/`entry`) in the language the user is
- conversing in. `result.json` keys/status values stay English.
-- **`result.json` is the report; the verify page renders it.** Each tested
- behavior is one entry in `cases[]` (`{ name, result, observation, evidence }`);
- the page builds the scope header from `scenario`+`context`, the check list from
- `plan[]`+`cases[]`, and the verdict from `summary.conclusion`. Do NOT hand-build
- a case table or a scope block in `report.md` — they double up on the page.
-- **Visual evidence lives in `result.json`, NOT in `report.md`.** Attach each
- screenshot/GIF to its case via `cases[].evidence`; the page renders it next to
- the check. Do NOT embed images/GIFs in `report.md`.
-- **Final replies lead with the published `/acceptance/<id>` link; the round's
- `/verify/<id>` link may follow as the immutable record. Put no images or local
- file links in the chat reply.** The acceptance page is the stable cross-round
- decision surface; the verify page renders that round's evidence inline. You
- may mention the local report directory as plain text.
-- **Time-based behavior needs a GIF, not a screenshot.** Streaming output, a
- ticking timer, loading states, animations — record with `scripts/record-gif.sh`
- and attach the GIF as that case's evidence; a static screenshot cannot prove it.
-
-### Step 6 — Publish to the LobeHub verify platform (mandatory)
-
-The local report under `.records/reports/` is the working artifact; the
-**deliverable is the report opened on the verify platform**. Do not stop at local
-files — push the session up with the CLI so the user (and later reviewers) can open
-it at a stable URL with the evidence rendered inline.
-
-**Publish targets PRODUCTION defaults (`https://app.lobehub.com`), not a local-dev
-override profile.** When the product-under-test runs against a local env, the CLI
-may be pointed at that local server through override env vars — those overrides are
-for _running_ the test, and they are wrong for _publishing_: a localhost run yields
-a URL nobody else can open, and a local env's stub storage makes file-evidence
-uploads fail. Publish in a CLEAN environment that strips those overrides so `lh`
-falls back to its production defaults and the user's real login. Clear whatever
-override vars the project uses; for reference, clearing a local-server override
-profile looks like:
-
-```bash
-# Strip local-dev CLI overrides so `lh` uses production defaults + the user's real login.
-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --open --json
-```
-
-Production auth is the user's own device-code login. Verify it first in the same
-clean env; if it returns "No authentication found", have the user log in
-(`lh login` prints a URL + code), then re-run the publish.
-
-**Check the CLI version before publishing.** The publish flags this step relies on
-(`--subject`, `--source agent-testing`) require `lh` >= the version recorded in
-this skill's `.skill-meta.json`. The `lh` on PATH in a consumer repo is often
-older and fails only at this final step (`unknown option '--subject'`). Run
-`lh --version` first; when it is older than the marker version, publish through
-`npx @lobehub/cli@latest` instead of the PATH binary.
-
-`verify ingest-report` reads `$DIR` and, in one call, creates a new immutable
-verification run, attaches it to the subject acceptance, and uploads everything:
-
-- `result.json.plan[]` → the frozen check plan, with a business-scenario
- `category` on every item (categories name requirements or features, never
- execution surfaces such as Desktop / CLI / Backend);
-- `result.json.cases[]` → one check result each, paired to its plan item by `id`;
- a planned item with no case renders as **未执行** instead of silently vanishing;
-- each case's `evidence` file(s) → uploaded and attached to that result;
-- `report.md` → the report body, plus the `summary` stats.
-
-It prints the `verifyRunId`, `acceptanceId`, and their in-app paths. The final
-reply leads with `https://app.lobehub.com/acceptance/<acceptanceId>` as the
-latest cross-round state; the round-specific
-`https://app.lobehub.com/verify/<verifyRunId>` may follow as supporting detail.
-
-#### Every run belongs to a subject acceptance (mandatory)
-
-Every run MUST be chained onto a task, topic, or document **acceptance aggregate**,
-so every round lands on one auditable decision page. When the harness runs inside a
-LobeHub topic, `ingest-report` automatically uses `LOBEHUB_TOPIC_ID` as
-`topic:<id>` — do not ask the user for it and do not omit the acceptance. Outside a
-LobeHub topic, an explicit subject is required and publishing without one fails:
-
-```bash
-# SUBJECT is task:$TASK_ID, topic:$TOPIC_ID, or document:$DOC_ID
-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" \
- --requirement "$REQUIREMENT" --open --json
-```
-
-`--subject` accepts `task:<id> | topic:<id> | document:<id>`; `result.json` may
-instead use the string form or
-`{ "type": "task", "id": "<id>", "requirement": "<goal>" }`.
-
-**Always supply the acceptance requirement on the first ingest.** It is not
-generated automatically. Write the one-sentence business goal against which the
-whole acceptance is judged, not the current round's narrower scope. A recorded
-requirement is immutable; an initially empty value may be backfilled by the first
-later round that supplies one.
-
-The first ingest creates the acceptance and every ingest creates its next
-immutable round. The user closes the loop on `/acceptance/<acceptanceId>`; the
-same state is available through
-`lh verify acceptance view|accept|reject <id | type:id>`.
-
-When no subject exists yet (first verification in a repo, no tracked task),
-create one with the CLI instead of asking the user for an id — a dedicated task
-is the natural acceptance subject for the run:
-
-```bash
-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh task create -n "<project>: <what this run verifies>" -i "<one-line goal>"
-# prints: Task created: T-<n> <name> — the T-<n> identifier works directly:
-SUBJECT="task:T-<n>"
-```
-
-Tell the user which task was created. Reuse the same subject for every follow-up
-round in that repo so all rounds land on one acceptance page.
-
-#### Before a follow-up round: read user feedback
-
-When the subject already has an acceptance, planning starts from its current
-state rather than memory:
-
-```bash
-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify acceptance view "$SUBJECT" --json
-```
-
-- `checks[].userReview.action === "accept"`: user-settled; omit it from the new
- plan and do not re-run it.
-- `action === "reject"` with `stale: false`: address its comment and annotations,
- and reuse the exact stable check id so the next result lands on the same row.
-- For a semantic replacement, create a new id with `supersedes: ['old-id']`.
- A fresh id without `supersedes` creates an unrelated parallel check.
-- Treat `stale: true` feedback as history already consumed by a newer round.
-
-#### Every verification run is an immutable snapshot
-
-One call to `ingest-report` creates one immutable `/verify/<id>` snapshot. Never
-overwrite, replace, prune, or re-ingest into an earlier run. A fix followed by
-re-verification MUST create another run on the same acceptance, preserving the
-earlier plan, results, evidence, and verdict exactly as observed. Use a fresh
-report directory for every execution round.
-
-Notes:
-
-- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;
- `evidence` is a path (or array) relative to `$DIR`. `result`/`verdict` map onto
- `passed | failed | uncertain`.
-- Finer control is available through the atomic commands — `verify run create`,
- `verify result ingest`, `verify evidence upload` (`--file` or `--content`),
- `verify report upsert`.
-- File evidence uploads through the platform's storage. Against a stub or
- unreachable bucket (common in local dev) the PUT fails; `ingest-report` warns,
- **skips that one artifact**, and still finishes — so the published session is
- real and openable but **missing the skipped evidence**. Publish against real
- storage (production defaults) if the evidence must appear.
-
-## Phase 3 — Finish
-
-Close the run cleanly and leave behind only intentional, auditable artifacts.
-
-### Step 7 — Teardown and handoff (default: stop what you started)
-
-A test run leaves processes and code edits behind. Clean them up by default once
-the report is published — a dev server left listening or an injection left in a
-source file silently corrupts the next run (and the next agent's mental model).
-
-- **Stop what you started.** Stop the dev server and any services you started,
- using the stop commands from `PROJECT.md` §2. Stop only what THIS run started —
- never a global process-name kill, and never a listener you didn't launch. If the
- user started their own dev server, leave it.
-- **Revert every code injection.** Any fault-injection or debug global you added
- (see [references/probe-mock-patterns.md](./references/probe-mock-patterns.md))
- must be undone and verified: restore the file, then `grep -rn AGENT-TEST` returns
- nothing. Never leave an injection or a debug global behind. Note: when you
- injected into a file that already had uncommitted changes, `git checkout --` is
- the WRONG revert — it wipes the branch's edits too; snapshot the file first and
- restore from the snapshot (probe-mock-patterns covers this).
-- **Keep the report + evidence.** `.records/reports/**` is the deliverable — do NOT
- delete it in teardown; it is gitignored and the published verify run points at
- it.
-- **Check `git status` before reporting the tree clean.** Some dev servers write
- managed files on start; reverting them can make them look like per-start churn.
- Confirm what is dirty rather than assuming.
-
-Skip teardown only when the user explicitly wants the environment left up (e.g.
-"leave the dev server running, I'll keep poking at it").
-
-## Directory map
-
-```text
-agent-testing/
-├── SKILL.md # this router
-├── surfaces/
-│ ├── cli.md # backend verification via the project CLI
-│ ├── web.md # full-stack verification in the browser
-│ └── electron.md # desktop verification over CDP
-├── references/ # shared knowledge (generic, read-only in consumers)
-│ ├── plan.md # Phase 1 approval-gate format
-│ ├── report.md # result.json / report.md / evidence spec
-│ ├── agent-browser.md # agent-browser CLI reference
-│ ├── osascript.md # general macOS automation
-│ ├── record-app-screen.md # screen recording
-│ ├── project-adapter.md # PROJECT.md template + first-run bootstrap
-│ ├── common-mistakes.md # GENERIC living log — read-only, PR upstream
-│ └── probe-mock-patterns.md # GENERIC living log — read-only, PR upstream
-└── scripts/ # generic scripts
-```
-
-## Gotchas
-
-- agent-browser: see [references/agent-browser.md](./references/agent-browser.md#gotchas)
-- Electron: see [surfaces/electron.md](./surfaces/electron.md#electron-gotchas)
-- osascript: see [references/osascript.md](./references/osascript.md#gotchas)
diff --git a/apps/cli/skills/agent-testing/references/agent-browser.md b/apps/cli/skills/agent-testing/references/agent-browser.md
deleted file mode 100644
index 3f0f4a3c501..00000000000
--- a/apps/cli/skills/agent-testing/references/agent-browser.md
+++ /dev/null
@@ -1,276 +0,0 @@
-# agent-browser CLI Reference
-
-Generic reference for the `agent-browser` CLI — automate Chromium-based apps
-(Electron, Chrome, web) via Chrome DevTools Protocol. Surface-specific patterns
-live in [../surfaces/web.md](../surfaces/web.md) and
-[../surfaces/electron.md](../surfaces/electron.md); project auth recipes live in
-`.agents/verify/PROJECT.md`.
-
-Install via `npm i -g agent-browser`, `brew install agent-browser`, or
-`cargo install agent-browser`. Run `agent-browser install` to download Chrome. Run
-`agent-browser upgrade` to update.
-
-## Core Workflow
-
-Every browser automation follows this pattern:
-
-1. **Navigate**: `agent-browser open <url>`
-2. **Snapshot**: `agent-browser snapshot -i` (get element refs like `@e1`, `@e2`)
-3. **Interact**: Use refs to click, fill, select
-4. **Re-snapshot**: After navigation or DOM changes, get fresh refs
-
-```bash
-agent-browser open https://example.com/form
-agent-browser snapshot -i
-# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
-
-agent-browser fill @e1 "[email protected]"
-agent-browser fill @e2 "password123"
-agent-browser click @e3
-agent-browser wait --load networkidle
-agent-browser snapshot -i # Check result
-```
-
-## GOMS-KLM interaction tracing
-
-When a UI verification should report user-side interaction cost, run
-`agent-browser` through the agent-testing wrapper:
-
-```bash
-TRACE="$DIR/interaction-trace.jsonl"
-SESSION=your-session # from PROJECT.md; $SKILL_DIR = the skill's install dir
-
-"$SKILL_DIR/scripts/agent-browser-klm.mjs" \
- --klm-trace "$TRACE" --klm-phase settings --klm-check case-1 \
- --session "$SESSION" click @e4
-```
-
-The wrapper forwards the real command to `agent-browser` and appends one JSONL
-event. Physical actions are inferred from the command (`click → P+K`,
-`fill/type → P+T(n)`, `press → K`, `wait → R`). A click only counts the user
-activation; if it causes loading or async work, follow it with an explicit
-`agent-browser wait ...` so response time is counted as `R`.
-
-Mental effort is intentionally not guessed from DOM shape. After the first
-meaningful page view, add an explicit agent estimate:
-
-```bash
-"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \
- --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \
- --confidence 0.75 --reason "Need to understand current page state and choose the verify path"
-```
-
-Before publish, summarize the trace into the structured report:
-
-```bash
-"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \
- --trace "$TRACE" --result "$DIR/result.json" --write
-```
-
-This populates `result.json.interactionCost` with the `goms-klm@lobe-v1` summary.
-The raw trace stays in the local report directory for audit/debug.
-
-## Command Chaining
-
-```bash
-# Chain open + wait + snapshot in one call
-agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
-```
-
-Use `&&` when you don't need to read intermediate output. Run commands separately
-when you need to parse output first (e.g. snapshot to discover refs, then interact).
-
-## Essential Commands
-
-```bash
-# Navigation
-agent-browser open <url> # Navigate (aliases: goto, navigate)
-agent-browser close # Close browser
-agent-browser close --all # Close all active sessions
-
-# Snapshot
-agent-browser snapshot -i # Interactive elements with refs (recommended)
-agent-browser snapshot -s "#selector" # Scope to CSS selector
-
-# Interaction (use @refs from snapshot)
-agent-browser click @e1 # Click element
-agent-browser click @e1 --new-tab # Click and open in new tab
-agent-browser fill @e2 "text" # Clear and type text
-agent-browser type @e2 "text" # Type without clearing
-agent-browser select @e1 "option" # Select dropdown option
-agent-browser check @e1 # Check checkbox
-agent-browser press Enter # Press key
-agent-browser keyboard type "text" # Type at current focus (no selector)
-agent-browser keyboard inserttext "text" # Insert without key events
-agent-browser scroll down 500 # Scroll page
-agent-browser scroll down 500 --selector "div.content" # Scroll within container
-
-# Get information
-agent-browser get text @e1 # Get element text
-agent-browser get url # Get current URL
-agent-browser get title # Get page title
-agent-browser get cdp-url # Get CDP WebSocket URL
-
-# Wait
-agent-browser wait @e1 # Wait for element
-agent-browser wait --load networkidle # Wait for network idle
-agent-browser wait --url "**/page" # Wait for URL pattern
-agent-browser wait 2000 # Wait milliseconds
-agent-browser wait --text "Welcome" # Wait for text to appear
-agent-browser wait --fn "!document.body.innerText.includes('Loading...')" # Wait for text to disappear
-agent-browser wait "#spinner" --state hidden # Wait for element to disappear
-
-# Downloads
-agent-browser download @e1 ./file.pdf # Click element to trigger download
-agent-browser wait --download ./output.zip # Wait for any download to complete
-
-# Network
-agent-browser network requests # Inspect tracked requests
-agent-browser network requests --type xhr,fetch # Filter by resource type
-agent-browser network requests --method POST # Filter by HTTP method
-agent-browser network route "**/api/*" --abort # Block matching requests
-agent-browser network har start # Start HAR recording
-agent-browser network har stop ./capture.har # Stop and save HAR file
-
-# Viewport & Device Emulation
-agent-browser set viewport 1920 1080 # Set viewport size (default: 1280x720)
-agent-browser set viewport 1920 1080 2 # 2x retina
-agent-browser set device "iPhone 14" # Emulate device (viewport + user agent)
-agent-browser set offline on|off # Toggle offline (under `set`, not a top-level cmd)
-
-# Capture
-agent-browser screenshot # Screenshot to temp dir
-agent-browser screenshot --full # Full page screenshot
-agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
-agent-browser pdf output.pdf # Save as PDF
-
-# Diff (compare page states)
-agent-browser diff snapshot # Compare current vs last snapshot
-agent-browser diff screenshot --baseline before.png # Visual pixel diff
-agent-browser diff url <url1> <url2> # Compare two pages
-```
-
-## Batch Execution
-
-```bash
-echo '[
- ["open", "https://example.com"],
- ["snapshot", "-i"],
- ["click", "@e1"],
- ["screenshot", "result.png"]
-]' | agent-browser batch --json
-```
-
-## Authentication
-
-```bash
-# Option 1: Auth vault (credentials stored encrypted)
-echo "$PASSWORD" | agent-browser auth save myapp --url https://app.example.com/login --username user --password-stdin
-agent-browser auth login myapp
-
-# Option 2: Session name (auto-save/restore cookies + localStorage)
-agent-browser --session-name myapp open https://app.example.com/login
-agent-browser close # State auto-saved
-agent-browser --session-name myapp open https://app.example.com/dashboard # Auto-restored
-
-# Option 3: Persistent profile
-agent-browser --profile ~/.myapp open https://app.example.com/login
-
-# Option 4: State file
-agent-browser state save auth.json
-agent-browser state load auth.json
-```
-
-For a local dev server where a headed login is awkward, copy the session cookie out
-of a **Network request** in your own browser's DevTools and load it via
-`state load`. The exact cookie name and origin for the project under test come from
-`PROJECT.md` §3.
-
-## Semantic Locators (Alternative to Refs)
-
-```bash
-agent-browser find text "Sign In" click
-agent-browser find label "Email" fill "[email protected]"
-agent-browser find role button click --name "Submit"
-agent-browser find placeholder "Search" type "query"
-agent-browser find testid "submit-btn" click
-```
-
-## JavaScript Evaluation (eval)
-
-```bash
-# Simple expressions
-agent-browser eval 'document.title'
-
-# Complex JS: use --stdin with heredoc (RECOMMENDED)
-agent-browser eval --stdin << 'EVALEOF'
-JSON.stringify(
- Array.from(document.querySelectorAll("img"))
- .filter(i => !i.alt)
- .map(i => ({ src: i.src.split("/").pop(), width: i.width }))
-)
-EVALEOF
-
-# Base64 encoding (avoids all shell escaping issues)
-agent-browser eval -b "$(echo -n 'document.title' | base64)"
-```
-
-## Ref Lifecycle
-
-Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot
-after clicking links/buttons that navigate, form submissions, or dynamic content
-loading.
-
-## Parallel Sessions
-
-```bash
-agent-browser --session site1 open https://site-a.com
-agent-browser --session site2 open https://site-b.com
-agent-browser session list
-```
-
-Each session is a separate daemon socket, so a wedge in one session is scoped to
-that session, not the whole tool. Use distinct session names per target when driving
-more than one page.
-
-## Connect to Existing Chrome / Electron
-
-```bash
-agent-browser --auto-connect snapshot # Auto-discover running Chrome
-agent-browser --cdp 9222 snapshot # Explicit CDP port (Electron dev, remote-debugging Chrome)
-```
-
-## Gotchas
-
-- **Daemon can get stuck** — if commands hang, `agent-browser close --all` or
- `pkill -f agent-browser` to reset. A screenshot RPC that is interrupted can leave
- the session's socket half-consumed, after which every later `screenshot` fails
- (`CDP response channel closed` / `Resource temporarily unavailable`) while
- `eval` / `get url` keep working — reset with `close --all`, or bypass the daemon
- with `scripts/cdp-screenshot.sh` (raw CDP).
-- **HMR invalidates everything** — after code changes, refs break. Re-snapshot or
- restart.
-- **`snapshot -i` doesn't find contenteditable** — use `snapshot -i -C` for rich
- text editors.
-- **`fill` doesn't work on contenteditable** — use `type` for rich-text inputs.
-- **Screenshots go to `~/.agent-browser/tmp/screenshots/`** unless you pass a path —
- a relative path saves to the caller's cwd; pass an absolute path in longer scripts
- so a lost cwd doesn't misplace the file. Read them with the `Read` tool.
-- **`network requests` under-reports** — it is not ground truth for "did the request
- happen". To judge whether a fault landed, wrap `window.fetch` and record each
- request's own outcome (see probe-mock-patterns).
-- **`set offline` trips Chrome's own offline interstitial**, not the app's error
- state — its "Reconnect" copy also false-matches error-copy greps. Use it to break
- connectivity, not to assert an app-level error.
-- **`wait --load networkidle` HANGS during a retry loop** (the network never idles)
- and can blow the command timeout — use a fixed `wait <ms>` when a fetch is stuck
- retrying. (macOS has no `timeout(1)` to bound it.)
-- **Dialogs block all commands** — if commands time out, check
- `agent-browser dialog status`.
-- **Default timeout is 25s** — override with `AGENT_BROWSER_DEFAULT_TIMEOUT` (ms) or
- use explicit waits.
-- **Shell quoting corrupts eval** — use `eval --stdin <<'EVALEOF'` for complex JS.
-- **A blank page at `about:blank` with a 1280px viewport usually means the previous
- `open` failed** (exited non-zero without navigating). The session still answers
- every later probe — against the fresh page it was born with. Read the `open` exit
- code and stderr rather than assuming the page went blank.
diff --git a/apps/cli/skills/agent-testing/references/common-mistakes.md b/apps/cli/skills/agent-testing/references/common-mistakes.md
deleted file mode 100644
index 8e395a1e983..00000000000
--- a/apps/cli/skills/agent-testing/references/common-mistakes.md
+++ /dev/null
@@ -1,540 +0,0 @@
-# Common Mistakes (generic layer)
-
-> **This is the GENERIC layer of the living log.** It is read-only in a consumer
-> repo and updated only by PR to the CLI repo that ships this skill. Every entry
-> here must be **product-independent** — no project's packages, routes, schemas,
-> env vars, service names, or business logic. Project-specific learnings go to
-> `.agents/verify/common-mistakes.md` (the writable project layer).
->
-> **Mandatory:** read this file in full before every agent-testing run and
-> self-check against each case. When the user gives negative feedback that is
-> product-independent, genericize it and PR it here; otherwise record it in the
-> project layer. Each case: Wrong approach / Why it's wrong / What it breaks /
-> Correct approach.
-
----
-
-## M1 — Judging `passed` from heuristics instead of looking at the screenshot
-
-**Wrong approach**: after navigating to a surface, deciding "renders fine / passed"
-from only `innerText` keyword greps + a skeleton/element count, without ever opening
-the screenshot.
-
-**Why it's wrong**: the persistent nav / layout-shell text is always in the DOM, so
-an `innerText` grep almost always false-positives. A blank/white page also has 0
-skeletons, so `skeletons === 0` cannot tell "rendered successfully" from "rendered
-blank".
-
-**What it breaks**: publishes a **false `passed`** — a blank or watermark-only page
-reported as working, hiding a real regression.
-
-**Correct approach**: every screenshot destined for a report `evidence` **must first
-be opened with the Read tool and visually confirmed to render the expected content**
-before pass/fail. Greps/counts are supporting signals only, never the verdict. A
-blank page / watermark / layout-shell-only = fail or uncertain — go find the root
-cause.
-
----
-
-## M2 — Goal is verifying error states, but stopping at happy-path because injection is hard
-
-**Wrong approach**: after the first batch of fault-injection methods fails to force
-an error, giving up on the error-state screenshots and shipping only happy-path +
-unit tests, marking the core goal uncertain/blocked.
-
-**Why it's wrong**: the **entire point** of the task was verifying the error states.
-Abandoning that = task not done — especially when other viable methods exist
-unattempted.
-
-**What it breaks**: the deliverable doesn't cover what the user asked for — a wasted
-round that needs redoing.
-
-**Correct approach**: **do not stop until the core goal is met.** When the first
-batch of methods fails, immediately switch to the next known-working one — see
-[probe-mock-patterns.md](./probe-mock-patterns.md) for the escalation ladder (code
-injection via HMR, CDP `Network.setBlockedURLs`, server-side fault injection). Get
-the **real failure-state evidence** before writing the report.
-
----
-
-## M3 — Deriving the task from commit messages / branch name instead of the actual ask
-
-**Wrong approach**: on a resumed session with lost prior context, reading the branch
-name and top commits and concluding _that_ is the thing to verify — then building a
-whole test run around it — when the user's real task was a different feature.
-
-**Why it's wrong**: a branch's committed work is not necessarily the current ask.
-When context was summarized/lost, the commit history is a _hypothesis_, not the task.
-The task lives in the user's words.
-
-**What it breaks**: burns a full test run and clarifying rounds on the wrong feature
-before course-correcting.
-
-**Correct approach**: when the user references a task you don't have in context, say
-so plainly and RECOVER it before acting — check `.records/reports/` for prior
-sessions on this branch, read the live conversation's own messages (the first user
-turn is usually the task), or ask for a pointer. Only translate the ask into
-code/commits after it's grounded.
-
----
-
-## M4 — Asserting a capture/tooling root cause from plausibility instead of measuring it
-
-**Wrong approach**: when a screenshot came out black or a capture failed, declaring a
-root cause from what "sounds right" (missing permission, display sleep, tool bug) and
-publishing it — before running the experiment.
-
-**Why it's wrong**: each of these is falsifiable in seconds and often wrong. A black
-frame can be display sleep OR a wedged capture daemon OR a real blank page; guessing
-sends the next reader to fix the wrong thing.
-
-**What it breaks**: a published report with a wrong root cause, plus wasted
-round-trips retracting each claim.
-
-**Correct approach**: for any capture / permission / timing / "environment" failure,
-**reproduce and measure before asserting or publishing** — pixel brightness for
-blackness, the permission bit for TCC, an A/B with the variable toggled to isolate
-the cause. State "confirmed by X" vs "suspected", and never ship a root cause a
-one-line probe could have checked.
-
----
-
-## M5 — Attaching a stale "before" screenshot as a passed case's evidence (unlabeled)
-
-**Wrong approach**: putting BOTH the "after" and a stale "before" screenshot into the
-same `cases[].evidence` array, unlabeled. The verify page renders every evidence
-image with its filename as a heading, so the user opens the stale shots and concludes
-the fix didn't land.
-
-**Why it's wrong**: a passed case's evidence must show the PASSING (after) state. An
-unlabeled before-shot next to it reads as "the current result", making a correct fix
-look broken. Filenames are not captions.
-
-**What it breaks**: the user reads a green report as a failure, loses trust, and it
-takes another round to re-explain.
-
-**Correct approach**: never ship a raw stale/before screenshot as standalone
-evidence. When a contrast helps, use the report format's **native comparison
-pairing** — attach both raw screenshots tagged with a shared `comparison` id and the
-page renders them under Before / After bands (see
-[report.md](./report.md)). **Do NOT hand-compose the two shots into one image** — the
-page owns the labeling. Two more traps: one evidence item per case (don't reuse the
-same pair across cases), and a group needs **exactly one `before` and one `after`**
-or it silently degrades to unlabeled evidence.
-
----
-
-## M6 — Verifying against a stale build, not your working-tree code
-
-**Wrong approach**: driving an already-running app instance to verify a working-tree
-change, and eyeballing the first screenshot as "looks changed".
-
-**Why it's wrong**: a resident or packaged app serves a BUILT snapshot — it does not
-reflect uncommitted / HMR src changes. The change under test may not be running at
-all, so the screenshot proves nothing about your code.
-
-**What it breaks**: verifying against code that isn't your change → a false pass (or
-false fail) on the wrong bundle entirely.
-
-**Correct approach**: verify working-tree code in an instance that actually loads it
-(a dev instance with HMR/live reload), and **prove it's live by MEASURING a
-known-changed value** (a computed style, a new string) before trusting any
-screenshot. Don't disturb the user's resident instance — use a separate
-instance/port. Remember main-process / server / adapter code often does not
-hot-reload; restart the process and prove which code it runs before concluding a
-logic bug.
-
----
-
-## M7 — Embedding a local-path screenshot in the chat reply
-
-**Wrong approach**: ending the final reply with an inline image embed or link
-pointing at the local report dir, believing it will render as a picture in chat.
-
-**Why it's wrong**: the chat UI cannot load a local filesystem path. An image embed
-of a local path renders as an empty broken-image box, and a markdown link to a local
-path is an un-openable dead link. Local report paths only resolve on the machine,
-never inside the message.
-
-**What it breaks**: the reply looks like it has evidence but shows nothing — the user
-gets a broken box and has to go find the verify link anyway.
-
-**Correct approach**: put NO images and NO local-file links in the chat reply. The
-published `/verify/<id>` page already renders every screenshot inline — that URL is
-the only visual deliverable. Describe key visual outcomes in prose; mention the local
-report dir as a plain string (not a markdown link) if a reference is useful.
-
----
-
-## M8 — Asking the user "how should I run this?" instead of defaulting to a full isolated run
-
-**Wrong approach**: when a visual/screenshot request needs a non-trivial environment
-(the app must run a specific branch, a fixture must be built, an isolated instance is
-needed), stopping to ask the user which approach to take — full isolated run vs a
-lighter shot vs a static prototype.
-
-**Why it's wrong**: environment mechanics are the skill's job to own. Presenting env
-difficulty as a menu of shortcuts pushes setup decisions back onto the user and
-signals the agent will cut corners on fidelity when the env is inconvenient.
-
-**What it breaks**: wastes a round on a question the user doesn't want.
-
-**Correct approach**: for any "run it and show me" request, default to the **full
-isolated run** that ends in a published verify report — spin up whatever dedicated
-instance and fixture data the surface needs (a throwaway repo, an isolated dev
-instance, seeded data), capture the real rendered evidence, verify it by opening the
-image, and publish. Only surface a plan-approval question when the _product decision_
-is ambiguous (what to test), never for _environment mechanics_ (how to render it).
-
----
-
-## M9 — Handing the user the sign-in click when the app under test is signed out
-
-**Wrong approach**: an isolated instance came up signed out, so the run stopped and
-offered the user a choice: "I click Sign in and you authorize" vs "skip the
-screenshot".
-
-**Why it's wrong**: auth is environment mechanics, and the skill owns those end to
-end. "Log in once in the app" is addressed to the **agent**, not the user.
-
-**What it breaks**: burns a round on a question the user doesn't want, and stalls a
-UI-touching change one click short of its screenshot.
-
-**Correct approach**: drive the sign-in yourself — click the app's own "Sign in"
-entry, follow the OAuth flow in the browser it opens, and get back into the app. Only
-escalate when a step genuinely needs something you cannot supply (a 2FA push on their
-phone), and then name the exact blocking step instead of offering to drop the
-evidence. Corollary: never assume a profile is signed in because it exists — probe
-for a real signed-in state (a cheap authed call) before building a fixture on top of
-it; a rendered shell is not proof (a signed-out onboarding screen has text too).
-
----
-
-## M10 — Self-judging a screenshot as "too costly" and asking the user to picture the result
-
-**Wrong approach**: after a small user-facing UI change, skipping the rendered
-screenshot with "it's a trivial style change; restarting to screenshot costs more
-than it's worth — tell me if you want one." Deciding the cost/benefit for the user and
-shipping a diff they had to picture.
-
-**Why it's wrong**: whether a verification artifact is "worth it" is not the agent's
-to decide. The measuring stick is _whether the user can conveniently inspect the
-product_, not how much effort the agent spends rendering it. Making the user guess the
-visual effect from a diff is the actually-expensive outcome.
-
-**What it breaks**: the user can't check the deliverable, loses trust, and has to push
-back — burning a round to get the screenshot that should have been produced up front.
-
-**Correct approach**: for ANY user-facing change (even one line of padding/color),
-default to rendering it and attaching the screenshot as a record point — open the
-image to confirm, publish. Never offer the screenshot as an opt-in.
-
----
-
-## M11 — Reporting a UI-touching change with only CLI transcripts and no screenshot
-
-**Wrong approach**: when a change includes visible UI (copy, badges, alerts, a
-rejection state), treating the run as purely backend/service validation and
-publishing only command-output evidence.
-
-**Why it's wrong**: CLI transcripts prove code paths and tests passed, but they do not
-let the reviewer inspect the rendered UI. "The diff touches no UI file" does not mean
-"no UI surface" — a permission tightening, for instance, IS a UI-visible state (the
-blocked user still sees the affordance and now gets a rejection).
-
-**What it breaks**: the user opens the report expecting visual proof and finds none.
-
-**Correct approach**: if any UI surface changed, include a visual case in the same
-run. Drive the real UI and attach a screenshot of the changed/blocked state (and the
-success state where relevant), or explicitly mark the UI screenshot case blocked with
-the measured environment blocker. Do not present a UI-touching report as complete with
-only CLI evidence.
-
----
-
-## M12 — Verifying the UI state but not the final effect / payload
-
-**Wrong approach**: marking a "inject context / apply setting / send data" feature
-verified because the UI showed the expected chip/badge/state — without checking the
-actual payload or side effect the feature is supposed to produce.
-
-**Why it's wrong**: UI metadata can be saved and displayed while a later
-runtime/transport gate drops it before the real effect. The UI looks successful while
-the underlying behavior never happened.
-
-**What it breaks**: ships a feature that looks right in the UI but has no effect;
-the user must inspect the network/DB to discover it.
-
-**Correct approach**: for any feature that claims to change what the system _does_,
-verify the last mile — assert against the transformed request/payload or the observed
-side effect (a network body, a DB row, a downstream call), and treat the UI state as
-supporting evidence only.
-
----
-
-## M13 — GIF evidence ending on an expected-failure frame reads as "the page failed"
-
-**Wrong approach**: for a loading/streaming case, attaching a GIF that records the
-full timeline through to a terminal error state that the test data inevitably
-produces. The GIF loops and rests on its final frames, so the viewer opens the report
-and sees the error, not the asserted state.
-
-**Why it's wrong**: the LAST frame of a GIF is its de-facto headline. An
-expected-failure terminal state without explanation reads as the case failing, even
-when the asserted behavior passed.
-
-**What it breaks**: the user reads a passed case as a failure and a round is burned
-re-explaining.
-
-**Correct approach**: trim evidence to the asserted state — end the GIF on the phase
-you're asserting (cut frames after the terminal state), or attach a static shot of the
-asserted state as primary evidence. If the terminal state is worth showing, say so in
-the case's `observation` so the viewer is told before they see it.
-
----
-
-## M14 — Verifying only the entry surface when a shared component also renders deeper
-
-**Wrong approach**: after changing a shared UI component, publishing a passing report
-from one surface only, even though the same component also renders on other pages.
-
-**Why it's wrong**: shared components are composed with different wrappers, slots, and
-responsive containers across surfaces. A fix that looks correct in one place can still
-be misplaced elsewhere.
-
-**What it breaks**: the report goes green while a deeper product path still shows the
-old or awkward behavior, and the user has to point out the surface that was never
-checked.
-
-**Correct approach**: enumerate every product surface where the changed shared UI
-renders before publishing, attach separate screenshot evidence for each, and mark any
-skipped surface explicitly blocked or untested.
-
----
-
-## M15 — Verifying a UI change only in its default state, not its collapsed/overflow state
-
-**Wrong approach**: after changing something inside an action bar / toolbar / list
-row, checking only the normal expanded state and publishing, without forcing the
-collapsed / auto-collapsed / overflow state.
-
-**Why it's wrong**: bars and rows often have their own overflow behavior and saved
-user preference. A change can shrink the available width enough to trigger a collapse,
-or a previously saved collapsed preference can hide the exact affordance the change
-sits beside.
-
-**What it breaks**: the screenshot looks fine for a fresh profile while real users
-with a collapsed toolbar or narrower container see something different.
-
-**Correct approach**: for any UI change inside a bar/row with overflow behavior,
-verify both the default and the collapsed/overflow state, with evidence for each.
-
----
-
-## M16 — Publishing a component harness when the user asked for full product verification
-
-**Wrong approach**: when the product surface hit friction once, declaring it blocked
-and publishing a narrow component harness as the main answer — even though another
-live path (a running dev instance, a sibling worktree) was available.
-
-**Why it's wrong**: a component harness proves a narrow render contract; it does not
-prove the full product composition, layout, theming, or that the evidence is
-inspectable in the real surface. Environment friction is the skill's job to solve, not
-a reason to downgrade before exhausting known-working paths.
-
-**What it breaks**: the user opens a report expecting full product evidence and gets a
-partial proof.
-
-**Correct approach**: before marking a product surface blocked, inventory existing dev
-instances and running surfaces, measure the target to confirm it renders current code,
-and use that path if it does. Keep a harness only as supporting evidence; the primary
-UI evidence must come from the product surface, or the report must clearly fail/block
-after every known path is measured.
-
----
-
-## M17 — Turning a feature verification into an unbounded environment repair
-
-**Wrong approach**: after the normal surface fails to boot, repeatedly modifying
-shared dev configuration, reinstalling the whole workspace, and chasing unrelated
-dependency problems before running any assertion for the feature under test.
-
-**Why it's wrong**: environment readiness is a gate, not the test goal. A workaround
-that changes shared configuration can also make the verification less representative,
-while an open-ended repair loop produces no feature evidence.
-
-**What it breaks**: the user waits through a long sequence of setup experiments, the
-tree gains unrelated edits, and the run still has no reportable result.
-
-**Correct approach**: follow only recovery paths documented by this skill or the
-project adapter. If the failure mode is not covered, stop, revert any experimental
-changes, summarize the exact checks and evidence collected, and ask the user before
-continuing. Do not repair the environment, switch surfaces, or invent a fallback
-without direction.
-
----
-
-## M18 — Probing the wrong layer: asserting a fixture landed because the write succeeded
-
-**Wrong approach**: writing a fixture directly to the database, reloading the page, and
-reading what the UI shows — then treating a stale value as a product bug.
-
-**Why it's wrong**: a persisted client cache (SWR / IndexedDB / localStorage) can keep
-serving the old value. A successful DB write proves the row changed; it proves nothing
-about what the app is _running on_. A fixture bug wearing a product-bug costume is the
-most expensive kind.
-
-**What it breaks**: you nearly file your own fixture as a regression.
-
-**Correct approach**: after any direct-DB fixture write, cold-load (clear client
-storage/caches, re-seed auth, reopen) and then **assert the fixture in the store
-before asserting anything downstream of it**. The DB is where you _wrote_ it; the store
-is where the behavior _reads_ it — verify at the layer the behavior reads. See
-[probe-mock-patterns.md](./probe-mock-patterns.md) B.
-
----
-
-## M19 — Building an elaborate mock before checking whether the env already has the real thing
-
-**Wrong approach**: needing a capability (a working provider key, a service) and,
-finding none in the shell env, building a mock server and seeding it — then watching
-the mock receive **zero** requests while the run produces real output.
-
-**Why it's wrong**: the capability may already exist somewhere the runtime actually
-reads (a different config store than the one you checked). Two unmeasured assumptions
-stack: that no capability existed, and that you knew where it comes from.
-
-**What it breaks**: a chunk of the run spent building an apparatus the test didn't
-need, plus a fixture to tear down. Worse, had the mock _partially_ worked, the run
-would have silently verified a fake path.
-
-**Correct approach**: before constructing any mock, **probe the env for the real
-capability** — query the config the runtime reads, or fire one cheap real call and see
-whether it completes. Only mock what is provably absent. And when a mock records
-nothing while the feature clearly works, that is the signal the mock is _not in the
-path_ — everything "verified" through it is unverified.
-
----
-
-## M20 — Bare invocation: narrating skill setup, then asking an open "what should I test?"
-
-**Wrong approach**: invoked with no test target, the agent announces "I'm loading the
-mandatory living logs first", reads both logs in full, then asks an open "what should I
-verify?" that ignores the visible candidate (the current branch and its commits).
-
-**Why it's wrong**: the living logs inform execution, not target selection — reading
-them before a target exists burns context that may be compacted away before the run.
-Narrating internal setup is compliance-reporting the user never asked for. And an open
-question pushes work onto the user that observable context could have pre-filled.
-
-**What it breaks**: two user-visible turns whose combined value is one clarifying
-question, asked twice.
-
-**Correct approach**: ground the target first (SKILL.md Step 0): the user's words > an
-inferred candidate from branch/commits/working tree, confirmed via one structured
-question and labeled as a guess (never executed on unconfirmed) > an open question only
-as last resort. Read the living logs once the target is known, and never narrate
-skill-internal setup.
-
----
-
-## M21 — A status badge is not proof the error message rendered
-
-**Wrong approach**: marking an error-state UI case passed because the page showed a
-`Failed` badge, while the screenshot did not actually contain the error alert or its
-translated message.
-
-**Why it's wrong**: the badge proves only that a failed state reached the page. It does
-not prove the error was translated and presented to the user, which is the core
-assertion of an error-message verification.
-
-**What it breaks**: a report claims users receive an actionable explanation while its
-evidence shows none.
-
-**Correct approach**: for an error-presentation case, visually require all the signals
-in the same screenshot: the failed status AND the error alert containing the expected
-user-facing message. An unrelated warning or setup reminder does not satisfy the
-assertion.
-
----
-
-## M22 — Coordinator hand-driving a broken flow instead of re-delegating
-
-**Wrong approach**: after a delegated verification subagent dies mid-case, the
-coordinator takes over and drives the remaining flow inline — dozens of small steps
-plus a deep root-cause dig into a flapping shared dependency, all in the main loop.
-
-**Why it's wrong**: the coordinator's per-step latency and context cost are far higher
-than a subagent's, and inline grinding turns one recoverable failure into a long
-visible stall. Root-causing an env flake is also not the test's goal.
-
-**What it breaks**: the user watches minutes of micro-steps with no case progress;
-total wall-clock and token spend balloon for zero extra evidence value.
-
-**Correct approach**: when a delegated case dies, repackage the _remaining_ steps into
-a fresh, tightly-scoped subagent prompt (include everything already learned: working
-recipes, seeded fixtures, exact remaining assertions). Timebox any environment rabbit
-hole to a couple of probes, then switch to a disposable local substitute instead of
-diagnosing shared infrastructure.
-
----
-
-## M23 — Stopping after a fix without publishing the next verification round
-
-**Wrong approach**: implementing and locally validating a requested iteration, then
-ending the task without committing, pushing, or publishing a fresh immutable verify run
-to the existing acceptance.
-
-**Why it's wrong**: an acceptance is the cross-round audit trail. A local-only fix
-leaves the PR stale and makes the acceptance claim the previous round is still the
-latest result. Local tests are preparation, not delivery.
-
-**What it breaks**: reviewers can't inspect the updated code, the acceptance timeline
-misses the iteration, and the user has to ask whether anything shipped.
-
-**Correct approach**: after every requested iteration, complete the whole delivery loop
-unless told not to: validate the new state, commit and push the branch, create a fresh
-report directory, ingest exactly once as the next immutable run on the same subject
-acceptance, verify the new round appears, then return both the commit and the
-production link.
-
----
-
-## M24 — Labeling sequential flow steps as a before/after comparison
-
-**Wrong approach**: attaching two sequential steps of one flow as a `comparison`
-pair with `before` and `after` roles.
-
-**Why it is wrong**: comparison rendering means the same surface before and after
-a change. Sequential steps are neither a defect nor its remediation.
-
-**Correct approach**: reserve `comparison` for one view in two states. Attach
-flow steps as ordinary ordered evidence with a caption naming each step.
-
----
-
-## M25 — Publishing locally because the acceptance subject exists only locally
-
-**Wrong approach**: ingesting the primary report into a local instance because
-its task or topic is absent from production.
-
-**Why it is wrong**: localhost links disappear with the environment and cannot
-serve as shared deliverables. Subject convenience does not change the production
-publication requirement.
-
-**Correct approach**: create a production task or topic as the acceptance anchor,
-then publish in a clean environment against `app.lobehub.com`. A local ingest may
-supplement the run, but never replace the production deliverable.
-
----
-
-## M26 — Creating an acceptance without its requirement
-
-**Wrong approach**: using a bare subject string on the first ingest and assuming
-the acceptance goal is inferred automatically.
-
-**Why it is wrong**: the requirement is author-supplied. Omitting it leaves the
-decision page without the business goal against which all rounds are judged.
-
-**Correct approach**: supply `--requirement` or the object subject form on the
-first ingest. State the cross-round business goal, not the current round's scope.
diff --git a/apps/cli/skills/agent-testing/references/osascript.md b/apps/cli/skills/agent-testing/references/osascript.md
deleted file mode 100644
index 9d80a426f16..00000000000
--- a/apps/cli/skills/agent-testing/references/osascript.md
+++ /dev/null
@@ -1,202 +0,0 @@
-# osascript Common Patterns
-
-General macOS automation via AppleScript / `osascript` — activating apps, typing,
-pasting, keyboard shortcuts, clicking, screenshots, and accessibility reads. This is
-a general macOS-automation asset, not tied to any one app or surface. Use it when a
-test needs to drive a native macOS app that is not reachable over CDP.
-
-macOS only. See also [record-app-screen.md](./record-app-screen.md) for capture and
-the screen-recording preflight (`scripts/check-screen-recording.sh`) before any
-OS-level capture.
-
-## Core Patterns
-
-### Activate an App
-
-```bash
-osascript -e 'tell application "AppName" to activate'
-```
-
-### Type Text
-
-```bash
-# Type character by character (reliable, but slow for long text)
-osascript -e 'tell application "System Events" to keystroke "Hello world"'
-
-# Press Enter
-osascript -e 'tell application "System Events" to key code 36'
-
-# Press Tab
-osascript -e 'tell application "System Events" to key code 48'
-
-# Press Escape
-osascript -e 'tell application "System Events" to key code 53'
-```
-
-### Paste from Clipboard (fast, for long text)
-
-```bash
-# Set clipboard and paste — much faster than keystroke for long messages
-osascript -e 'set the clipboard to "Your long message here"'
-osascript -e 'tell application "System Events" to keystroke "v" using command down'
-```
-
-Or in one shot:
-
-```bash
-osascript -e '
-set the clipboard to "Your long message here"
-tell application "System Events" to keystroke "v" using command down
-'
-```
-
-### Keyboard Shortcuts
-
-```bash
-osascript -e 'tell application "System Events" to keystroke "k" using command down' # Cmd+K
-osascript -e 'tell application "System Events" to keystroke "f" using command down' # Cmd+F
-osascript -e 'tell application "System Events" to keystroke "n" using command down' # Cmd+N
-osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}' # multi-modifier
-```
-
-### Click at Position
-
-```bash
-osascript -e '
-tell application "System Events"
- click at {500, 300}
-end tell
-'
-```
-
-### Get Window Info
-
-```bash
-osascript -e '
-tell application "System Events"
- tell process "AppName"
- get {position, size} of window 1
- end tell
-end tell
-'
-```
-
-### Screenshot
-
-```bash
-screencapture /tmp/screenshot.png # Full screen
-screencapture -i /tmp/screenshot.png # Interactive region select
-screencapture -l "$WINDOW_ID" /tmp/shot.png # Specific window (id from CGWindowList)
-```
-
-To get the window id for a specific app:
-
-```bash
-osascript -e '
-tell application "System Events"
- tell process "AppName"
- get id of window 1
- end tell
-end tell
-'
-```
-
-### Read Accessibility Elements
-
-```bash
-# Get all UI elements of the frontmost window (can be slow/large)
-osascript -e '
-tell application "System Events"
- tell process "AppName"
- entire contents of window 1
- end tell
-end tell
-'
-
-# Get a specific element's value
-osascript -e '
-tell application "System Events"
- tell process "AppName"
- get value of text field 1 of window 1
- end tell
-end tell
-'
-```
-
-> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer
-> screenshots + the `Read` tool for visual verification.
-
-### Read Screen Text via Clipboard
-
-```bash
-osascript -e '
-tell application "System Events"
- keystroke "a" using command down
- keystroke "c" using command down
-end tell
-'
-sleep 0.5
-pbpaste
-```
-
-## General App-Automation Workflow
-
-```bash
-APP_NAME="AppName"
-TARGET="some-target"
-MESSAGE="Hello!"
-WAIT_SECONDS=10
-
-# 1. Activate
-osascript -e "tell application \"$APP_NAME\" to activate"
-sleep 1
-
-# 2. Navigate (via the app's own quick switcher / search shortcut)
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-sleep 0.5
-osascript -e "tell application \"System Events\" to keystroke \"$TARGET\""
-sleep 1
-osascript -e 'tell application "System Events" to key code 36'
-sleep 2
-
-# 3. Input (clipboard paste for long/non-ASCII text)
-osascript -e "set the clipboard to \"$MESSAGE\""
-osascript -e '
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-
-# 4. Wait for the app to react
-sleep "$WAIT_SECONDS"
-
-# 5. Screenshot for verification
-screencapture /tmp/app-test.png
-```
-
-### Tips
-
-- **Use clipboard paste** (`Cmd+V`) for messages with special characters or long
- text — `keystroke` can mangle non-ASCII.
-- **Add `delay`** between actions — apps need time to process UI events.
-- **Screenshot for verification** — `screencapture` + the `Read` tool.
-- **Accessibility permission required** — System Events automation requires
- Accessibility access for the driving app (Terminal / iTerm / the agent host) in
- System Settings > Privacy & Security > Accessibility.
-
-## Gotchas
-
-- **Accessibility permission required** — first run prompts for access; grant it in
- System Settings > Privacy & Security > Accessibility.
-- **`keystroke` is slow for long text** — use clipboard paste (`Cmd+V`) for anything
- over \~20 characters.
-- **`keystroke` can mangle non-ASCII** — use clipboard paste for CJK, emoji, or
- special characters.
-- **`key code 36` is Enter** — hardware key code, works regardless of keyboard
- layout.
-- **`entire contents` is extremely slow** — avoid for complex UIs; use screenshots.
-- **OS screenshots go BLACK when the display is asleep/locked/screensaver** — gate
- with `scripts/check-screen-recording.sh` and keep the display awake with
- `caffeinate -dimsu &` for the whole capture run.
diff --git a/apps/cli/skills/agent-testing/references/plan.md b/apps/cli/skills/agent-testing/references/plan.md
deleted file mode 100644
index 5e268238bf4..00000000000
--- a/apps/cli/skills/agent-testing/references/plan.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# Phase 1 Plan Feedback
-
-Use this template at the end of Phase 1. Match the user's conversation language.
-Keep it concrete and compact: report observed state, not generic readiness claims.
-
-## Readiness verdicts
-
-- **✅ Ready**: every prerequisite for the proposed run is verified.
-- **⚠️ Ready with warnings**: execution can proceed; list non-blocking limitations
- and their effect on evidence or scope.
-- **❌ Blocked**: execution cannot start until one or more prerequisites are
- resolved.
-- **⏳ Pending**: an agent-owned check is actively being resolved and has not
- reached a final readiness verdict yet.
-
-Always prefix the overall verdict and every Status cell with its emoji marker:
-`✅ Ready`, `⚠️ Warning`, `❌ Blocked`, or `⏳ Pending`. Do not use color words or
-bare status text without the marker; the table must remain scannable in clients
-that do not render semantic colors.
-
-Fix safe environment mechanics yourself before reporting. Separate remaining items
-by owner:
-
-- **Agent-owned**: dependencies, processes, ports, generated local env, seeded
- fixtures, navigation, retries, and other work possible within the task's scope.
-- **User-owned**: secrets the user must supply, device/2FA approval, permissions
- only the user can grant, destructive authorization, or an unresolved product
- choice that materially changes the plan.
-
-Never put an agent-owned item under "Needed from you." If none remain, write `None`
-explicitly.
-
-## Template
-
-```markdown
-Verification plan — Environment: <✅ Ready | ⚠️ Ready with warnings | ❌ Blocked>
-
-Environment
-
-| Check | Status | Observed state |
-| ------------------ | ------------------------------------------- | --------------------------------------------------- |
-| Workspace / branch | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <path, branch/worktree, relevant dirty-state note> |
-| Dependencies | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <root and selected standalone app status> |
-| Runtime / ports | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <resolved URLs/ports and ownership or availability> |
-| Required services | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <DB, cache, queue, dev server—only those in scope> |
-| Auth | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <selected surface and verified signed-in state> |
-| Evidence capture | <✅ Ready/⚠️ Warning/❌ Blocked/⏳ Pending> | <CDP or OS capture readiness> |
-
-Execution plan
-
-1. <Surface and entry point>
-2. <Case 1: behavior → expected result → evidence>
-3. <Case 2: behavior → expected result → evidence>
-4. <Report and publication deliverable>
-
-Scope and assumptions
-
-- In scope: <what this run proves>
-- Out of scope: <intentional exclusions, or None>
-- Assumptions / warnings: <items that may affect interpretation, or None>
-
-Needed before execution
-
-- Agent will resolve: <remaining non-blocking or in-progress agent-owned work, or None>
-- Needed from you: <exact user-owned prerequisite and why it is required, or None>
-```
-
-Do not include irrelevant environment rows. Add a row when the run has another hard
-prerequisite, such as a native app, gateway, fixture repository, or specific
-external account.
-
-When a check refines or replaces a requirement from an earlier Acceptance round,
-keep the old stable id if it is the same assertion. If the semantic assertion needs
-a new id, declare the replacement explicitly with `supersedes: ['old-check-id']`;
-title similarity is never a merge signal. For every user-visible UI case, plan a
-dedicated screenshot or recording for that exact claim — program output may
-supplement it but cannot replace visual evidence.
-
-On a follow-up round, seed the plan from
-`lh verify acceptance view <subject> --json` before writing any case:
-
-- Accepted checks are user-settled; omit them from the new plan.
-- Rejected, non-stale checks are the primary repair items. Carry their comments
- and annotations into the expected outcome, and reuse their exact stable ids.
-- Plan all remaining checks from their current state, again reusing stable ids.
- A semantic replacement requires a new id plus `supersedes: ['old-id']`.
-
-## Confirmation behavior
-
-After the feedback, use the runtime structured question tool
-(`request_user_input` / ask-user-question equivalent). Do not bury the question
-inside the template text.
-
-When the verdict is **Ready** or **Ready with warnings**, use:
-
-1. `Start (Recommended)` — approve the displayed environment and plan; enter Execute.
-2. `Discuss first` — revise scope, cases, assumptions, or environment handling.
-
-When the verdict is **Blocked**, do not offer Start. Use:
-
-1. `I'll provide it (Recommended)` — the user will supply or complete the listed
- user-owned prerequisite.
-2. `Revise the plan` — change the scope or approach to remove the blocker.
-
-Match button labels to the user's language. Wait for the user's response. If the
-user resolves a blocker, re-check the affected environment item and present an
-updated gate; do not rely only on the user's statement that it is fixed.
diff --git a/apps/cli/skills/agent-testing/references/probe-mock-patterns.md b/apps/cli/skills/agent-testing/references/probe-mock-patterns.md
deleted file mode 100644
index 67c1d716348..00000000000
--- a/apps/cli/skills/agent-testing/references/probe-mock-patterns.md
+++ /dev/null
@@ -1,372 +0,0 @@
-# Probe / Mock Pattern Library (generic layer)
-
-> **This is the GENERIC layer of the living log.** It is read-only in a consumer
-> repo and updated only by PR to the CLI repo that ships this skill. Every recipe
-> here must be **product-independent** — framework-level or tool-level, no project's
-> stores, routes, tables, env vars, or file paths. Project-specific probes and mocks
-> go to `.agents/verify/probe-mock-patterns.md` (the writable project layer).
->
-> **Read this before any run that must force an error state or inspect runtime
-> state.** Each item: Situation / Doesn't work / Works.
->
-> **Separate the observation from the explanation.** When you add an item, cite the
-> exact mechanism (a `file:line`, a measured A/B) — and if you only saw a symptom,
-> write "cause not established" instead of guessing. A wrong mechanism is worse than
-> none: it sends the next reader to fix the wrong thing.
-
----
-
-## A. Forcing a fetch to FAIL (error-state testing)
-
-### A1. Judge interception by the fetch's own outcome, not by the UI or the promise
-
-- Apps commonly **swallow** a failed fetch: a store action can resolve successfully
- even when its underlying request was aborted, so the UI and the action's promise
- both "look like" a 200. Never judge whether your fault landed by the action or the
- UI.
-- **Works**: wrap `window.fetch` post-load and record each request's own resolve /
- reject. Use a guard so a second `eval` doesn't wrap the wrapper (stack overflow):
- ```js
- if (!window.__W) {
- window.__W = 1;
- window.__R = [];
- const of = window.fetch;
- window.fetch = function (...a) {
- const p = of.apply(this, a);
- if (String(a[0]).includes('<url-fragment>'))
- p.then(
- (r) => window.__R.push('resolved_' + r.status),
- (e) => window.__R.push('REJECTED_' + e.message),
- );
- return p;
- };
- }
- ```
-- **`agent-browser network route --abort` glob matching is finicky.** A bare `**/x`
- or `*/path/*` can match nothing on a nested path; an absolute-URL prefix with a
- trailing `*` matches reliably (the trailing `*` also covers a `?query` string). And
- `agent-browser network requests` **under-reports** — it is not ground truth for
- "did the request happen"; trust the `window.fetch` wrapper instead.
-
-### A2. `set offline` shows the browser's page, not the component error
-
-- `agent-browser set offline on` trips Chrome's document-level offline interstitial
- ("Reconnect to Wi-Fi"), not the app's own error component. Its copy (and the dino
- game) also false-matches naive error-copy greps, and offline breaks lazy
- route-chunk loading → a hard-nav fallback to the browser page. Use it to break
- connectivity, not to assert an app-level error state.
-
-### A3. WORKS — force an error by injecting a throw into the code path via HMR
-
-- Add a throw at the top of the client method the data fetcher / mutation calls, let
- the dev server hot-apply it, capture, then revert:
- ```ts
- // <the service method the fetcher calls> — [AGENT-TEST] REMOVE
- list = async (params) => {
- if (true) throw Object.assign(new Error('injected'), { data: { httpStatus: 500 } });
- return realClient.list(params);
- };
- ```
-- Use a status the UI treats as **retryable** (commonly anything but 401/403) if you
- want the Retry affordance visible; a non-retryable status suppresses it. The same
- technique works on the **write side** — inject into the mutation method to exercise
- a failed-save state.
-- **Revert carefully.** `git checkout -- <file>` on a service file often triggers a
- FULL reload (not just HMR), resetting the SPA to a blank shell — after reverting,
- re-navigate and re-fetch element refs. And see A5: `git checkout --` is the WRONG
- revert when the file already had uncommitted changes.
-
-### A4. WORKS — alternatives when HMR injection isn't available
-
-- **CDP `Network.setBlockedURLs`** — blocks at the network stack (below `fetch`, so
- it catches requests a page-realm `fetch` override might miss). Needs a raw CDP ws
- connection.
-- **Server-side** — temporarily make the one endpoint return 500.
-
-### A5. `git checkout -- <file>` to revert an injection DESTROYS the branch's uncommitted changes in that file
-
-- When you inject a probe into a file that the branch has **already modified
- (uncommitted)** — the common case for a pre-PR review — `git checkout -- <file>`
- resets it to HEAD, silently wiping the very feature edits you were sent to verify,
- not just your probe. Nothing warns you: the residue check (`grep -rn AGENT-TEST`)
- comes back clean either way, because your marker is gone too.
-- **Works — snapshot the file yourself before injecting, restore from the snapshot:**
- ```bash
- cp <file> /tmp/probe-backup-$(basename <file>) # BEFORE the edit
- # ... inject, HMR, capture ...
- cp /tmp/probe-backup-$(basename <file>) <file> # restore — preserves uncommitted work
- ```
- Then prove the restore is exact (`git diff -- <file>` shows the same working-tree
- blob as before) and `grep -rn AGENT-TEST` is empty. Check `git status --short`
- before you start so you know which files are dirty; for a dirty file, `git checkout --` is never the revert. `git stash` has the same failure shape.
-
-### A6. WORKS — before/after visual diffing by checking out the OLD file, gated on a measured version signal
-
-- The clean way to produce a real "before" render is to write the pre-change version
- into the working tree (`git show <base>:<path> > <path>`), capture, then restore —
- **not** to trust that HMR applied the swap. HMR can silently fail to apply the
- second swap: the file on disk is old while the renderer keeps the new styles, and
- the screenshot is the AFTER state mislabeled BEFORE (an M5 failure no screenshot
- review catches).
-- **Works — gate every capture on a measured version signal, not a sleep.** Pick a
- property that differs between the two versions and read it back with
- `getComputedStyle` before shooting; if it's not the expected value, force a full
- reload and re-enter the surface. A full reload resets SPA state, so budget for
- re-establishing any fixture.
-- **Corollary — a layout change may be invisible at the default size.** A
- right-alignment / `flex` fix can render identically to the broken version in a
- narrow container (content already fills the row); drive the app's own resize
- affordance with real mouse events before concluding "no visual change".
-
----
-
-## B. Cache / stale state that MASKS the failure
-
-### B1. A failed revalidation cannot show an error once the data has settled
-
-- A surface that loaded successfully once caches the last-good value. On a later
- failed fetch, a well-behaved error boundary keeps the settled content and does NOT
- show the error (by design: a background error must not blow away loaded content). So
- your injected failure shows the old content, not the error.
-- **Works**: to see a genuine FIRST-LOAD error, clear all client storage, then
- cold-load. Clearing usually logs you out → re-seed auth after.
- ```js
- (async () => {
- try {
- localStorage.clear();
- sessionStorage.clear();
- } catch {}
- try {
- const d = await indexedDB.databases();
- await Promise.all(
- (d || []).map(
- (x) =>
- new Promise((r) => {
- const q = indexedDB.deleteDatabase(x.name);
- q.onsuccess = q.onerror = q.onblocked = () => r();
- }),
- ),
- );
- } catch {}
- try {
- const k = await caches.keys();
- await Promise.all(k.map((c) => caches.delete(c)));
- } catch {}
- return 1;
- })();
- ```
- then re-seed auth, then `open about:blank` → `open <target>`.
-
-### B2. SWR-style clients retry for \~30s before the error settles
-
-- A data client with retry/backoff keeps `isLoading` true during retries, so you
- screenshot a skeleton, not the error. A typical config (5 attempts, exponential
- backoff capped at 30s) settles the error only after \~30s.
-- **Works**: wait \~35s after load for retries to exhaust, THEN screenshot. (Or disable
- retries for the probe — but that can also hide the Retry button, since many clients
- mark a non-retrying error as non-retryable.)
-
-### B3. In-memory cache survives `open`; persisted cache survives everything
-
-- `open about:blank` then `open <target>` forces a fresh JS context (clears in-memory
- cache) but does NOT clear persisted storage — you still need B1 for a true cold
- load. Verify a marker set via `eval` (not from the page's own script, which re-runs
- on the second `open` and re-creates it, reading as "context preserved"). Persisted
- caches commonly live in **two tiers** — IndexedDB for big collections and
- localStorage for small shells — which is why B1 clears both plus the Cache API.
-
-### B4. Component-local state seeded from a cached item does NOT reset when fresh data arrives
-
-- A row component that initializes local state from its item (`useState(() =>
-derive(item))`) captures the value at first render. When a persisted cache hydrates
- the list with a stale item first, `useState` captures the stale value; when the
- fresh server response replaces the data, the row does not remount (same React key),
- so the stale local state sticks. No amount of waiting fixes it.
-- **Works**: for any assertion on an initial-render flag that flows through
- `useState(init)`, force a clean first frame by clearing only the persisted-cache
- tier and reloading (login usually survives if you don't touch the session cookie),
- and verify the underlying data separately so a stale render is attributed to cache,
- not to the change under test.
-
----
-
-## C. Probing app / runtime state
-
-### C1. WORKS — read live component state with a temporary debug global
-
-- The decisive way to read a component's live props / store / fetched values: add a
- debug global in the render, reload, read it, remove it.
- ```tsx
- // inside the component render, temporary — [AGENT-TEST] REMOVE
- if (typeof window !== 'undefined')
- (window as any).__DBG = { data: /* ... */, hasError: !!error, isLoading };
- ```
- ```bash
- agent-browser --session $S eval 'JSON.stringify(window.__DBG)'
- ```
- This surfaces cases where the data looks settled even on error — a discrepancy a
- screenshot can't show.
-
-### C2. `agent-browser console` capture works — use it for what console is for
-
-- Console capture is reliable on current agent-browser (a page-script `[log]` and one
- emitted later from `eval` both appear). An empty console means the page logged
- nothing, not that capture is broken. The debug-global (C1) is still the better tool
- for reading structured component state; use console for what console is for.
-
-### C3. `document.body.innerText` keyword grep false-positives on fixture text
-
-- Asserting a state via `body.innerText.includes('<phrase>')` matches your own fixture
- content if it happens to contain that substring (e.g. a fixture literally named
- "…failure…" when you assert on "failure") — a false pass on a state that never
- rendered.
-- **Works**: scope the check to the actual UI element (`querySelectorAll` on the
- specific tag/toast/alert), never `body.innerText`. And pick fixture names that do
- NOT contain any state keyword you'll assert on.
-
-### C4. `innerText` can be 0 on a rendered page — use it to tell a wedge from a blank
-
-- On some app shells `document.body.innerText` reads `""` even on a fully rendered
- page (some ancestor collapses the layout-dependent computation); probe a more
- specific container (e.g. the app root element) instead.
-- **Diagnostic**: `innerText` needs layout, `textContent` does not. When the root
- gives `innerText === 0` but `textContent > 0`, the DOM is fine and the RENDERER is
- not painting (a compositor wedge — see D9). When both are 0, the DOM is genuinely
- empty. This distinction tells a non-painting renderer from a blank page.
-
-### C5. A successful ingest does not prove acceptance attachment when the CLI is stale
-
-- A globally installed CLI may accept `ingest-report` and return a run id while
- lacking newer subject/acceptance behavior. The result is an orphan round even
- though the command appears successful.
-- Compare `lh --version` with the skill marker before publishing. If the branch
- under test changes the CLI contract, run that branch's CLI; otherwise use
- `npx @lobehub/cli@latest`. Confirm the returned acceptance id or inspect the
- acceptance page rather than treating a run id alone as proof.
-
----
-
-## D. agent-browser / CDP mechanics
-
-- **D1. `screenshot` honours a relative path — but still pass an absolute one.** A
- relative path saves to the caller's cwd; the cwd of a step in a longer script is
- easy to lose track of, so an absolute path is the right habit.
-- **D2. The CDP port can be ephemeral.** A browser launched with
- `--remote-debugging-port=0` picks a random port; read `DevToolsActivePort` in the
- user-data-dir, or use `agent-browser get cdp-url` (note: `cdp-url` is a `get`
- subject, not a top-level command). Electron dev instances usually pin a known port
- (e.g. 9222) — the project adapter says which.
-- **D3. `wait --load networkidle` HANGS during a retry loop** (the network never
- idles) and can blow the command timeout — use a fixed `wait <ms>` when a fetch is
- stuck retrying. (macOS has no `timeout(1)` to bound it.)
-- **D4. Portal toasts auto-dismiss (\~5s) and `snapshot -i` may miss their buttons.** A
- base-ui / portal-rendered toast lives outside the main tree and can be occluded by a
- dev overlay; `snapshot -i` does not reliably surface its action buttons. Read the
- toast via an `eval` DOM query, and because it dismisses in \~5s, re-trigger it
- immediately before the screenshot/query (or fire its button via `.click()` in the
- same `eval`) rather than relying on a timed hover-then-observe.
-- **D5. `agent-browser screenshot` can WEDGE the session; `eval`/`get` still work.**
- Each session is one daemon socket, so a wedge is scoped to that session. An
- interrupted screenshot RPC (a killed command, a bad flag, `--full` on a giant page)
- can leave the socket half-consumed, after which every later `screenshot` fails
- (`Resource temporarily unavailable` / `CDP response channel closed`) while
- `eval`/`get url` keep working — **not** a display-sleep or permission issue. Reset
- with `agent-browser close --all`, or skip the daemon entirely (D6).
-- **D6. WORKS — raw-CDP screenshot bypasses the daemon.** `scripts/cdp-screenshot.sh [--port <n>] [--out x.png] [--full] [--check]` opens its own ws to the target, does
- one `Page.captureScreenshot`, and closes (\~60ms). Immune to the D5 wedge and
- **robust when the display is asleep or the window is minimized/occluded** (the
- engine forces a compositor frame). Use it for Electron evidence and as a preflight
- (`--check` → exit 0 iff a real, non-black frame was captured).
-- **D7. OS `screencapture` is BLACK when the display is asleep/locked/screensaver.**
- Distinct from D5/D6: `screencapture` (and `capture-app-window.sh`, osascript grabs)
- captures the physical framebuffer, so an idle-slept display → a uniformly black PNG
- (mean/max = 0). Permission can be fine. Gate with `scripts/check-screen-recording.sh`
- (checks the permission bit + a real-frame blackness probe) and keep the display
- awake for the whole run: `caffeinate -dimsu &`. CDP capture (D6) does not have this
- problem.
-- **D8. The daemon serializes commands — `open` queues behind a screenshot loop.**
- While a recording loop (`record-gif.sh`) is running, `agent-browser open <url>`
- lands late/out of order, and your "during navigation" screenshot can show the
- PREVIOUS page (which may look identical to the expected end state — a false read).
- **Works**: during any recording loop, navigate with
- `agent-browser eval 'location.href="<url>"'` (fire-and-forget) instead of `open`.
-- **D9. A mid-session bundler dependency re-optimize can wedge the renderer
- compositor.** Symptom: capture returns black, the app root's `innerText` is 0 while
- `textContent` still holds the full DOM (C4), and `visibilityState` is `visible` with
- real dimensions — not display sleep or permission (D6/D7 would survive both). It
- often follows a "re-optimizing dependencies" / "failed to fetch dynamically imported
- module" log line. **Works**: restart the dev instance; `location.reload()` alone may
- not clear it.
-- **D10. Virtualized lists: driving `scrollTop` by hand blanks the pane — use a small
- fixture.** A virtualizer unmounts nodes as you scroll past (a `TreeWalker` search
- then "loses" a node that was there a second ago), and forcing `scrollTop` far
- outside the rendered window can make the scroll container itself disappear — reading
- exactly like a render bug. **Works**: pick a fixture small enough that the target is
- on the first screen; far cheaper and more reliable than fighting the virtualizer.
-- **D11. React controlled inputs ignore synthetic events — use `agent-browser click`
- (trusted CDP input).** `el.click()` and even a full synthetic
- `pointerdown/mousedown/pointerup/click` sequence are `isTrusted: false`, so a
- React-controlled checkbox/toggle never updates its state. **Works**: `snapshot -i`
- for the ref, then `agent-browser click <ref>` — it goes through CDP
- `Input.dispatchMouseEvent`, which the page sees as a real user click. The snapshot
- also reveals when a control is `[disabled]` (the app deliberately refusing), which a
- coordinate-click never would.
-- **D12. Disambiguate elements by geometry or an identifying attribute — don't
- singular-select.** A page can render a hidden zero-size duplicate of a subtree
- (e.g. an offscreen measurement copy) at `(0,0)`, first in DOM order, so a singular
- `querySelector` grabs the phantom: a `fill` reports success while the visible box
- stays empty, a click on the phantom button is a silent no-op, and an `innerText`/aria
- grep "finds" a control the user can't see. **Works**: enumerate and filter by a
- non-zero `getBoundingClientRect()`, or target by the component's own `aria-label`;
- tag the resolved element with a `data-probe` attribute and drive it with
- `agent-browser click '[data-probe=...]'`.
-- **D13. A blank page at `about:blank` with a 1280px viewport usually means the
- previous `open` failed** (exited non-zero without navigating — e.g. an unrecognized
- global flag). The session still exists and answers every later probe — against the
- fresh page it was born with, at the default viewport. Read the `open` exit code and
- stderr to learn _why_ rather than assuming the page went blank; treat the
- fingerprint as "the navigation failed".
-
----
-
-## E. Environment / shell gotchas
-
-- **E1. Not every layer hot-reloads — restart and prove which code the process runs.**
- A dev server's HMR typically covers the renderer/client only. Server code,
- main-process code, and adapters that run out-of-process are often NOT recompiled on
- edit, so reloading the client verifies nothing — the old code is still running, and
- the failure looks exactly like a logic bug in your own diff. **Works**: after an
- edit to a non-client layer, restart before drawing a conclusion, and prove the
- process has your code before debugging it — e.g. curl the dev bundler for the source
- and grep for a marker (renderer), or grep the built bundle for the marker (server /
- main).
-- **E2. The shell's `grep` may honor `.gitignore` — "not found anywhere" can be a
- false negative.** Some environments alias `grep` to a wrapper (e.g. `ugrep --ignore-files`) that skips `.gitignore`d paths, silently omitting `node_modules`.
- Before asserting "X exists nowhere", name the ignored directory explicitly
- (`grep -rl X node_modules`) or call `/usr/bin/grep` directly.
-- **E3. In zsh, a loop variable named `path` overwrites the command search path.** zsh
- ties `path` to `PATH` as a special array; assigning it (e.g. parsing a cookie jar's
- path field) replaces the process command search path, and the next executable fails
- with `command not found`. Name the field something else (`cookie_path`); this is a
- shell failure, not an auth/browser failure. (Similarly, `zsh does NOT word-split
-unquoted vars` — stashing `S="--session x --cdp 9226"` then `agent-browser $S`
- fails; inline the flags or use an array.)
-- **E4. A curl "502" from a local port with nothing listening can be a shell proxy
- env.** If `HTTP_PROXY`/`HTTPS_PROXY` are set and `NO_PROXY` does not exempt
- localhost, a dead local host is forced through the proxy and returns the proxy's
- 502 — a "server up but broken" mirage. `curl --noproxy '*'` is a harmless
- belt-and-braces habit; if you actually see a 502 from a local port, check `NO_PROXY`
- before believing the server is up.
-- **E5. Dev servers can write managed files on start — check `git status` before
- reporting the tree clean.** Some frameworks append a managed block to a repo file on
- `dev` start (once, idempotently). Reverting it at teardown makes it look like
- per-start churn and causes it to be re-appended on the next start. Commit the block
- or opt out per the framework, and always check `git status` before claiming a clean
- tree.
-- **E6. Persistent resource exhaustion (e.g. Vite `EMFILE: too many open files`) is a
- stop-and-ask, not a workaround.** If a surface exits at startup with a
- file-watcher/resource-exhaustion error while the port is free, the likely cause is
- other running watchers (extra worktrees, surviving terminals, an editor window) that
- you must not kill. Terminate the run, report the exact error, and ask the user to
- clean up other processes — do not change watch mode, fall back to a static build, or
- publish a report from a degraded surface.
diff --git a/apps/cli/skills/agent-testing/references/project-adapter.md b/apps/cli/skills/agent-testing/references/project-adapter.md
deleted file mode 100644
index 267a180c6d9..00000000000
--- a/apps/cli/skills/agent-testing/references/project-adapter.md
+++ /dev/null
@@ -1,162 +0,0 @@
-# Project Adapter (`.agents/verify/PROJECT.md`)
-
-This skill is project-agnostic. Everything specific to the project under test — how
-to start and stop it, which ports and services it needs, how auth works, which
-surfaces it has, and how to jump straight into app state — lives in a per-project
-adapter at `.agents/verify/PROJECT.md`. The skill reads it; it never guesses the
-project's commands.
-
-## Where the adapter lives
-
-```text
-<repo>/.agents/verify/ # committed — the adapter and project logs are team assets
-├── PROJECT.md # the adapter (this contract)
-├── common-mistakes.md # PROJECT-layer living log (writable)
-├── probe-mock-patterns.md # PROJECT-layer living log (writable)
-└── scripts/ # optional: project env / probe scripts
-```
-
-`.agents/verify/` is **committed** (the adapter and the project living logs are
-shared, versioned team assets). The report output directory `.records/` is
-**gitignored** — reports are per-run artifacts, published to the verify platform,
-not committed.
-
-## Fixed section skeleton
-
-`PROJECT.md` always has these six sections, in this order. Sections the skill refers
-to by number (`PROJECT.md §2`, `§3`, …), so keep the numbering.
-
-1. **Project summary** — what the product is, and the repo layout relevant to
- testing (which package holds the server, the web app, the desktop shell, the
- CLI).
-2. **Environment** — how to start and stop the dev environment; the required
- services (database, cache, queue, object store) and how to start each; how to
- detect "already running" so a run does not clobber a user's server; how env and
- ports are resolved (the project's own env-resolver command, if any) so the skill
- never hard-codes a port table.
-3. **Auth** — test accounts, seeding commands, and a per-surface status check (one
- command per surface that answers "am I signed in on this surface?").
-4. **Surfaces** — which of CLI / Web / Electron apply, and for each that applies:
- launch command, base URL / port, agent-browser session name (web/electron), and
- which probe scripts drive it.
-5. **Project probes & quick navigation** — the fast paths into app state: an auth
- probe, a current-route probe, a running-operations probe, and a `goto <route>`
- quick-navigation, plus the routes worth jumping to. These are the project's
- equivalent of a state-introspection helper; the skill uses them instead of
- hand-rolling store-eval snippets.
-6. **Known constraints** — anything the generic gates must know before running:
- services that are hard prerequisites for a code path (e.g. "agent runs require
- the queue service up"), standalone sub-packages that need their own install,
- surfaces that only work on macOS, or any repo-specific gotcha a run must respect.
-
-`PROJECT.md` may reference project scripts under `.agents/verify/scripts/` or
-anywhere in the repo.
-
-## Copy-pasteable template
-
-```markdown
-# PROJECT.md — agent-testing adapter for <project name>
-
-## 1. Project summary
-
-<One paragraph: what the product is. Then the repo layout that matters for testing —
-which directory/package is the server, the web app, the desktop shell, the CLI.>
-
-## 2. Environment
-
-- **Start dev server:** `<command>` (base URL: `<url>`, port: `<port>`)
-- **Stop dev server:** `<command>` (must stop only what this run started)
-- **Required services:** <db / cache / queue / object store — with the start command
- for each, or "none">
-- **Already-running detection:** `<health-check command>` — how to tell the server is
- up before starting another one.
-- **Env / port resolution:** `<command or file>` — the source of truth for ports and
- URLs. Do NOT hard-code a port table; read it here.
-
-## 3. Auth
-
-- **Test account(s):** <how to obtain — seeded, fixture, or a real login>
-- **Seeding command:** `<command>` (or "n/a")
-- **Per-surface status check:**
- - CLI: `<command>` — signed-in when <...>
- - Web: `<command>` — signed-in when <...>
- - Electron: `<command>` — signed-in when <...>
-
-## 4. Surfaces
-
-<For each surface that applies. Delete the ones that don't.>
-
-### CLI
-
-- Invocation: `<how the CLI is run — from source or built binary>`
-- Auth: <see §3 CLI>
-- Standalone install: `<command>` or "covered by root install"
-
-### Web
-
-- Launch: `<dev server command>` (from §2)
-- Base URL: `<url>`
-- agent-browser session: `<session name>`
-
-### Electron
-
-- Launch: `<start command>` — CDP port `<port>`
-- Stop: `<command>`
-- Login persistence: <how login survives across runs>
-
-## 5. Project probes & quick navigation
-
-- Auth probe: `<command>` → `{ isSignedIn, userId }`
-- Route probe: `<command>` → current route
-- Operations probe: `<command>` → running operations
-- Quick navigation: `<command> goto <route>`
-- Routes worth jumping to: <list>
-
-## 6. Known constraints
-
-- <e.g. "agent runs require the queue service (§2) up, or the run dies before any
- real work">
-- <e.g. "the desktop and CLI packages are standalone — install inside each">
-- <e.g. "OS-capture surfaces are macOS-only">
-```
-
-## First-run bootstrap (SKILL.md Step 0.5)
-
-When `.agents/verify/PROJECT.md` is absent, build it before doing anything else:
-
-1. **Explore the repo.** Read the signals that reveal how the project runs:
- `package.json` scripts, `README`, CI workflows (`.github/workflows/**`),
- `Makefile` / `Justfile`, `docker-compose*.yml` / `compose.yaml`, `.env.example`,
- and any existing test/dev docs. Note the dev-server command, the services it
- needs, the ports, the auth story, and which surfaces exist.
-2. **Draft `PROJECT.md`** from the fixed skeleton above, filling every section from
- what you found. Where a value is uncertain, mark it explicitly as a guess rather
- than inventing a command.
-3. **Present it for confirmation.** Show the draft to the user and ask them to
- confirm or correct it — especially the start/stop commands, the required
- services, and the auth path. Do not run a dev server or write test steps against
- an unconfirmed adapter.
-4. **Write it only after approval**, to `.agents/verify/PROJECT.md`. Create
- `.agents/verify/` if it does not exist.
-
-`install` (the CLI's `lh verify install`) only places the skill files; it does no repo
-exploration. The adapter draft needs a model, so the first verification run is what
-bootstraps `PROJECT.md`.
-
-## Drift rule
-
-Treat the adapter like a living log: when observed reality diverges from it during a
-run (a port moved, a start command changed, a service is now required), **fix
-`PROJECT.md` in place during the run** rather than working around it silently. The
-next run should not rediscover the same divergence.
-
-## Two living-log layers
-
-The skill's `references/common-mistakes.md` and `references/probe-mock-patterns.md`
-are the **generic layer** — product-independent, read-only in consumer repos,
-updated only by PR to the CLI repo. The project's own
-`.agents/verify/common-mistakes.md` and `.agents/verify/probe-mock-patterns.md` are
-the **project layer** — writable, and the only place a run records project-specific
-learnings. At runtime the agent reads both layers and writes only the project layer.
-When a project-layer entry turns out to be product-independent, genericize it (drop
-every project-specific noun) and PR it to the generic layer upstream.
diff --git a/apps/cli/skills/agent-testing/references/record-app-screen.md b/apps/cli/skills/agent-testing/references/record-app-screen.md
deleted file mode 100644
index 3a74e361772..00000000000
--- a/apps/cli/skills/agent-testing/references/record-app-screen.md
+++ /dev/null
@@ -1,116 +0,0 @@
-# record-app-screen.sh
-
-General-purpose screen recording for a CDP-driven Electron/Chrome app. Captures CDP
-screenshots as video frames and gallery snapshots, then assembles them into an MP4
-on stop. Because it renders from the browser engine over CDP (not the OS screen), it
-works under Xvfb and is unaffected by display sleep.
-
-## Why CDP Screenshots Instead of ffmpeg Screen Capture
-
-- **Works on any screen** — CDP screenshots capture the browser viewport directly,
- so external monitors, Retina scaling, and window positioning are handled
- automatically.
-- **No signal-handling issues** — `ffmpeg-static` (npm) can produce corrupt MP4
- files when killed (missing moov atom). CDP screenshots avoid this entirely.
-- **Consistent output** — resolution-independent, no crop-coordinate math.
-
-## Commands
-
-```bash
-# $SKILL_DIR = the skill's install dir; the target app must be running with CDP
-"$SKILL_DIR/scripts/record-app-screen.sh" start [output_name] # start recording
-"$SKILL_DIR/scripts/record-app-screen.sh" stop # stop + assemble video
-"$SKILL_DIR/scripts/record-app-screen.sh" status # is recording active?
-```
-
-### Arguments
-
-| Argument | Default | Description |
-| ------------- | --------------------------- | -------------------------- |
-| `output_name` | `recording-YYYYMMDD-HHMMSS` | Base name for output files |
-
-### Environment Variables
-
-| Variable | Default | Description |
-| ---------------------- | ------- | -------------------------------------- |
-| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |
-| `SCREENSHOT_INTERVAL` | `3` | Seconds between gallery screenshots |
-| `VIDEO_FRAME_INTERVAL` | `0.5` | Seconds between video frames (\~2 fps) |
-
-## Output Structure
-
-```
-.records/
- <name>.mp4 # Video assembled from frames (~2 fps)
- <name>/ # Gallery screenshots (every 3s)
- 0000.png
- 0001.png
- ...
-```
-
-The `.records/` directory is at the repo root and is gitignored.
-
-## How It Works
-
-### Start
-
-1. Creates two background loops:
- - **Video frames** — `agent-browser screenshot` every `VIDEO_FRAME_INTERVAL`
- seconds into a temp directory.
- - **Gallery screenshots** — `agent-browser screenshot` every
- `SCREENSHOT_INTERVAL` seconds into `.records/<name>/`.
-2. Saves PIDs and paths to `/tmp/record-app-screen.pids` and
- `/tmp/record-app-screen.state`.
-
-### Stop
-
-1. Kills both background loops.
-2. Assembles video frames into MP4 with ffmpeg:
- ```
- ffmpeg -framerate 2 -i frame_%06d.png -c:v libx264 -crf 23 -pix_fmt yuv420p <output>.mp4
- ```
-3. Cleans up the temp frame directory.
-4. Reports file sizes and paths.
-
-## Usage Example
-
-```bash
-# 1. Start the Electron dev instance (launch command from PROJECT.md §4)
-
-# 2. Start recording
-"$SKILL_DIR/scripts/record-app-screen.sh" start my-test
-
-# 3. Drive the automation
-agent-browser --cdp 9222 click @e61
-agent-browser --cdp 9222 type @e42 "hello"
-agent-browser --cdp 9222 press Enter
-sleep 10
-
-# 4. Stop and get results
-"$SKILL_DIR/scripts/record-app-screen.sh" stop
-# → .records/my-test.mp4 + .records/my-test/*.png
-```
-
-## When to use a GIF instead
-
-For a short, time-based assertion (streaming output, a ticking timer, a loading
-state) attach a GIF from `scripts/record-gif.sh` to the case's evidence — it is
-lighter than a full recording and embeds inline on the verify page. Reach for a full
-MP4 recording only when a longer flow needs to be watched end to end.
-
-## Prerequisites
-
-- **ffmpeg** — for video assembly. Install via `bun add -g ffmpeg-static` or
- `brew install ffmpeg`.
-- **agent-browser** — for CDP screenshots. Install via `npm i -g agent-browser`.
-- **The app running with CDP enabled** — start the dev instance per `PROJECT.md`.
-
-## Troubleshooting
-
-| Problem | Solution |
-| ----------------------------------- | ----------------------------------------------------------------------------------------- |
-| "No active recording found" on stop | PID file was cleaned up; check for background loops with `ps aux \| grep agent-browser` |
-| "A recording is already active" | Run `stop` first, or clean: `rm /tmp/record-app-screen.pids /tmp/record-app-screen.state` |
-| Video is 0 bytes | No frames captured. Ensure the app is running and the CDP port is correct |
-| Screenshots are blank/white | The app may not have finished loading yet. Wait for renderer readiness first |
-| ffmpeg assembly fails | Check `/tmp/ffmpeg-assemble.log`; ensure ffmpeg is installed and frames exist |
diff --git a/apps/cli/skills/agent-testing/references/report.md b/apps/cli/skills/agent-testing/references/report.md
deleted file mode 100644
index fe0b46cbd41..00000000000
--- a/apps/cli/skills/agent-testing/references/report.md
+++ /dev/null
@@ -1,325 +0,0 @@
-# Structured Test Reports
-
-Every automated test session ends with a structured, evidence-backed report. A
-chat-only summary is not an acceptable deliverable: the report is what the user (or
-a reviewer, or a later agent) audits without replaying the session.
-
-## Location & layout
-
-Reports live under `.records/reports/` (gitignored, like all `.records/`
-output), grouped by acceptance subject. One subject directory contains one
-subdirectory per immutable verification round:
-
-```
-.records/reports/<subject-key>/
-├── acceptance.json
-├── <YYYYMMDD-HHMMSS>-<slug>/
-│ ├── report.md
-│ ├── result.json
-│ └── assets/
-└── <YYYYMMDD-HHMMSS>-<slug>/
-```
-
-`<subject-key>` is the ingest subject with `:` replaced by `-`. Scaffold with
-`report-init.sh --subject topic:tpc_xxx <slug> "<title>"`; this also pre-fills
-`result.json.subject`. The legacy flat layout remains readable, but new runs
-should always carry their subject.
-
-Reusable per-check inputs live separately under
-`.records/fixtures/<subject-key>/<check-id>/` as `check.json` plus `seed/`.
-Execution outputs remain in the round directory's `assets/`. See
-`scripts/fixture.mjs` and the skill's fixture workflow.
-
-**`result.json` is the report — `report.md` is just its tail.** The published
-verify page (`/verify/<id>`) renders itself from `result.json`: one line of
-provenance (PR / branch / commit / date / surfaces), the overall conclusion from
-`summary.conclusion` directly under the title, and the check list from `plan[]`
-paired with `cases[]`. So `report.md` must NOT repeat the scope block or a case
-table — those double up on the page. It carries only the non-duplicate narrative
-(follow-ups / this-round notes / score), rendered as the page's collapsible
-"Details".
-
-## Workflow
-
-1. **Scaffold up front** — before running the first test step:
-
- ```bash
- # $SKILL_DIR = the skill's install dir
- DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-slug "My title")
- ```
-
- The script creates the directory, pre-fills branch / commit / date in both
- files, and prints the directory path. Translate its headings and table labels to
- the user's language before delivery if needed.
-
-2. **Collect evidence as you test** — every asserted behavior gets one evidence
- item in `$DIR/assets/`:
- - UI (static state): `agent-browser screenshot` or `capture-app-window.sh`, then
- **verify the screenshot with the Read tool before citing it** — never cite an
- image you haven't looked at.
-
- - UI (time-based behavior): **screenshot vs GIF is a judgment you make per
- case.** If the assertion is about change over time — streaming output, a
- ticking timer, loading/progress states, animations, appear/disappear
- transitions — a static screenshot cannot prove it. Record a frame sequence and
- synthesize a GIF:
-
- ```bash
- # start recording (background), trigger the behavior, wait for it to finish
- "$SKILL_DIR/scripts/record-gif.sh" "$DIR/assets/case2-streaming.gif" 12 2 &
- GIF_PID=$!
- # ... drive the scenario ...
- wait $GIF_PID
- ```
-
- Verify at least the first/last frames visually (Read the GIF) before citing.
-
- - UI (before/after comparison): capture and visually verify both original
- screenshots. Do not compose them into a new image. In the case's `evidence`
- array, pair them with a shared comparison id.
-
- A comparison pair means the same view in two states. Sequential steps of a
- flow are not before/after states; attach those as ordinary ordered evidence
- items with captions naming each step.
-
- ```json
- "evidence": [
- {
- "path": "assets/before.png",
- "comparison": { "id": "topic-row", "role": "before", "layout": "vertical", "label": "before: 11px, line-height 40px" }
- },
- {
- "path": "assets/after.png",
- "comparison": { "id": "topic-row", "role": "after", "layout": "vertical", "label": "after: 12px, line-height 44px" }
- }
- ]
- ```
-
- The verify page renders a complete pair with each screenshot under its own
- tinted band — red for `before`, green for `after`. A group contains exactly one
- `before` and one `after`, and **both halves need the same string `id`**; a half
- without an `id` can never pair. Incomplete groups render as ordinary evidence.
-
- Two fields are worth setting on every pair:
-
- - **`layout`** — `horizontal` (default, side by side) or `vertical` (stacked).
- A tall, narrow crop (a sidebar, a form, a list) reads well side by side; a
- **wide, short strip** (a toolbar, a one-line footer) must be `vertical`,
- because two of them in a two-column grid become illegible slivers. Set it on
- both halves.
- - **`label`** — the caption shown next to the role word in the band. This is
- where the before/after contrast is actually _stated_: put the measured delta
- on each side, so the two captions read as a comparison rather than repeating
- the case title.
-
- - CLI: exact command + trimmed output (`<cli> <command> | tee "$DIR/assets/x.txt"`).
-
- - Network: `agent-browser network requests` dumps or HAR files.
-
-3. **Write `plan[]` BEFORE you run anything.** The approved plan from Step 1 is part
- of the report, not scaffolding you throw away: each item is
- `{ id, title, category, verifier, method, expected, requiredEvidence }` — what
- you will check, which requirement area it belongs to, how it is judged, how you
- will exercise it, what would make it pass, and the artifact it must produce.
- `verifier` and `requiredEvidence` are closed sets the pipeline acts on (schema
- below); `method` / `expected` are prose. `cases[]` later reuses the same `id`s,
- which is what lets the report pair intent against outcome. A planned item that
- never produces a case renders as **未执行** rather than vanishing, so cut coverage
- in the open.
-
-4. **Fill `result.json` as you go** — it is the report. Each tested behavior is one
- entry in `cases[]` (`{ id, name, result, observation, evidence }`), where
- `evidence` is a path under `assets/`. Set the scope fields (`scenario`, `branch`,
- `commit`, `surfaces`, `entry`) and write the one-paragraph verdict into
- `summary.conclusion`. The page pairs each check with its evidence inline, so you
- don't hand-build a table. `report.md` holds only the narrative tail.
-
-5. **Set the verdict** in both `report.md` and `result.json`. Describe key visual
- outcomes in prose; the published verify URL is the only visual pointer in the
- final chat reply.
-
-6. **Publish** (SKILL.md Step 6) — upload the finished session so it's viewable on
- the verify platform, not just on disk. **Publish to PRODUCTION defaults with the
- user's real login, NOT a local-dev CLI override** — strip the local dev overrides
- so `lh` uses its production defaults. Clearing an override profile looks like:
-
- ```bash
- env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
- lh verify ingest-report "$DIR" --source agent-testing --open --json
- ```
-
- This creates a new immutable verification run, attaches it to the required
- subject acceptance, uploads the cases, evidence, and report body, then prints
- both `/verify/<verifyRunId>` and `/acceptance/<acceptanceId>`. Include that full
- production link in the final reply alongside the local report dir. See SKILL.md →
- Step 6 for why production defaults (a localhost URL isn't shareable and a local
- stub storage fails file-evidence uploads), the production login check, and the
- atomic commands (`verify run|result|evidence|report …`).
-
-## Report language (hard rule)
-
-**`report.md` MUST be written in the language the user is conversing in** — the
-whole file, headings included. If the conversation is in Chinese, the report is in
-Chinese; do not mix English prose into it. The scaffold headings are placeholders —
-translate them when filling. Exceptions that stay as-is: code/commands,
-identifiers, log excerpts, and `result.json` (its keys and status values are
-machine-read and stay English; the `title` and case `name` fields follow the
-user's language).
-
-## report.md sections
-
-Default report shape (a case table doubles the page and is only for a purely
-non-visual run; for UI runs, leave the case list to `result.json`):
-
-| Section | Content |
-| ---------------- | ---------------------------------------------------------------------------------------- |
-| **Verdict** | Overall verdict first (`pass` / `partial` / `fail`), then concise reasons and follow-ups |
-| **Verification** | Commands or automated checks run in this session, with trimmed results |
-| **Score** | Pass/fail/blocked counts, optional 0–100 score |
-
-Status values: `pass` / `fail` / `blocked` (couldn't run — e.g. auth or env
-missing; a blocked case is not a pass).
-
-## result.json schema
-
-**Two fields are the report's identity in every list surface — treat them as
-REQUIRED on every ingest:**
-
-- `title` (top level) — without it the run lists as "未命名验证" forever.
-- `summary.verdict` (`pass` / `fail` / `partial`) — without it the list glyph is a
- permanent amber "?" instead of the green pass. The CLI derives a fallback from the
- cases, but an explicit verdict is still the author's job.
-- Every `comparison` pair side should carry a `label` — the role band renders it as
- the explanation; a pair without labels shows two bare role words and reads as
- unexplained.
-
-```json
-{
- "branch": "feat/task-tree",
- "cases": [
- {
- "category": "Task hierarchy",
- "id": "1",
- "name": "task tree returns nested children",
- "surface": "cli",
- "status": "pass",
- "observation": "root returned 3 nested children, depth 2",
- "evidence": ["assets/task-tree.txt"]
- }
- ],
- "commit": "abc1234",
- "createdAt": "2026-06-11T15:30:00+08:00",
- "interactionCost": {
- "model": "goms-klm@lobe-v1",
- "scope": "user-equivalent",
- "totalSeconds": 8.1,
- "activeSeconds": 6.1,
- "waitSeconds": 2,
- "operators": { "K": 1, "P": 2, "H": 0, "M": 2, "T_chars": 5, "R_ms": 2000 },
- "phases": []
- },
- "plan": [
- {
- "id": "1",
- "title": "task tree returns nested children",
- "category": "Task hierarchy",
- "verifier": "program",
- "method": "<cli> task list --tree against a 3-level fixture",
- "expected": "root shows 3 nested children at depth 2",
- "requiredEvidence": ["text"]
- }
- ],
- "pullRequest": {
- "number": 17152,
- "title": "feat(task): nested task tree",
- "url": "https://github.com/<org>/<repo>/pull/17152"
- },
- "summary": {
- "total": 1,
- "passed": 1,
- "failed": 0,
- "blocked": 0,
- "score": 100,
- "verdict": "pass"
- },
- "surfaces": ["cli"],
- "title": "Verify task tree API"
-}
-```
-
-`plan[]` is the checks you committed to **before running them**, and it shares
-`id`s with `cases[]`. Every plan item must carry a `category` that names its
-user-facing business scenario or requirement area (for example `Task hierarchy`,
-`Rate-limit recovery`, `Browser actions`). It must not name a technical surface such
-as `Desktop`, `CLI`, or `Backend`: Acceptance groups are organized by what the user
-is accepting, while `surface` separately records where the check ran. A plan item
-with no matching case renders as **未执行**: cutting coverage is allowed, hiding that
-you cut it is not.
-
-Two of its fields are a **closed vocabulary**, because the pipeline acts on them —
-they are not labels:
-
-| field | values | what it does |
-| ------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
-| `verifier` | `program` \| `agent` \| `llm` (default `agent`) | How the verdict is reached. A command-asserted check is `program`; calling it `agent` hides what actually judged it. |
-| `requiredEvidence` | `screenshot` \| `gif` \| `video` \| `text` \| `dom_snapshot` \| `transcript` | The artifact this check **must** produce. The coverage gate **fails** an item whose required medium is missing. |
-
-An out-of-vocabulary value in either fails the ingest — an unrecognized medium
-would silently gate on nothing, which is worse than no gate at all.
-
-`method` (how you would exercise it) and `expected` (what would make it pass) stay
-**free prose** — they carry intent no enum can, and both render under the check on
-the page next to the outcome.
-
-A plan item may also carry a per-item `surface` (same closed set as the run-level
-`surfaces`; `electron` normalizes to `desktop`). It says which product surface THIS
-check ran on. It is metadata, never an Acceptance grouping key.
-
-`surfaces` is a **closed set** — `web` | `desktop` | `cli` | `mobile` | `bot` — and
-names the product surface a check ran **on**. `electron` is accepted and normalized
-to `desktop`. Anything else fails the ingest:
-
-- A **test kind** is not a surface. `unit`, `backend`, `database`, `type-check` do
- not belong here; a backend change verified through the CLI has surface `cli`.
-- A **runtime mode** is not a surface. "packaged build", "CDP dev instance" — that
- detail belongs on the plan item's `method`.
-
-`entry` is the command or URL exercised (`<cli> task list --tree`, `/chat/settings`)
-— **not** a PR title and not a description of the change.
-
-`pullRequest` is optional: when absent, the ingest asks `gh` for the PR of `branch`
-and fills it in. Write it explicitly only when the report verifies a PR that isn't
-the branch's own.
-
-`score` is optional — use it when the verdict has a subjective component (UI polish,
-copy quality); omit it for purely binary runs. `verdict` is the single word the user
-reads first: `pass`, `fail`, or `partial`.
-
-`subject` identifies the business subject whose **acceptance aggregate** owns this
-immutable run: either `"subject": "task:<id>"` (`task` | `topic` | `document`) or
-`{ "type": "task", "id": "task_…", "requirement": "one-sentence acceptance bar" }`.
-The `--subject` flag overrides this field. Inside a LobeHub conversation, both may
-be omitted because `ingest-report` defaults to `topic:$LOBEHUB_TOPIC_ID`; outside a
-topic, an explicit subject is mandatory. Every ingest creates a new immutable run;
-never update a prior run after a fix, publish the re-verification as the next round.
-
-`interactionCost` is optional and run-level. For UI runs driven through
-`agent-browser`, create `interaction-trace.jsonl` with `scripts/agent-browser-klm.mjs`,
-then run `scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`.
-
-When published, `verify ingest-report` maps each case onto a check result:
-`name`→title, `status`/`result`→verdict, `observation`→the result's key
-observation, and `evidence` paths→uploaded artifacts. `summary.{total,passed,failed,blocked}`
-and `verdict` become the report's stats + overall verdict; `report.md` becomes the
-report body.
-
-## Rules
-
-- **No evidence, no claim** — every `pass`/`fail` in `cases[]` must link at least
- one asset. UI cases must attach their primary screenshot/GIF as evidence;
- non-visual CLI/network cases may link transcripts, HAR files, or logs.
-- **Screenshots must be visually verified** with the Read tool before being cited.
-- **Report failures faithfully** — a failing case with clear evidence is a good
- report; a vague green one is not.
-- If coverage was cut (cases skipped, surfaces not exercised), say so in the Verdict
- section — silent truncation reads as "covered everything".
diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs b/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs
deleted file mode 100755
index 1239ec826c1..00000000000
--- a/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs
+++ /dev/null
@@ -1,232 +0,0 @@
-#!/usr/bin/env node
-/**
- * Analyze agent-browser KLM trace JSONL into a compact interactionCost object.
- */
-
-import { readFile, writeFile } from 'node:fs/promises';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const MODEL = 'goms-klm@lobe-v1';
-const TIMING_SECONDS = {
- H: 0.4,
- K: 0.2,
- M: 1.35,
- P: 1.1,
- T_char: 0.2,
-};
-
-const emptyOperators = () => ({
- H: 0,
- K: 0,
- M: 0,
- P: 0,
- R_ms: 0,
- T_chars: 0,
-});
-
-const usage = () => {
- console.log(`Usage:
- agent-browser-klm-analyze.mjs --trace interaction-trace.jsonl [--result result.json --write] [--markdown]
-
-Options:
- --trace <file> JSONL trace from agent-browser-klm.mjs
- --result <file> result.json to patch with interactionCost
- --write overwrite --result with interactionCost
- --markdown print a markdown section instead of JSON
- --model <id> model id label (default: ${MODEL})`);
-};
-
-const parseArgs = (argv) => {
- const options = { markdown: false, model: MODEL, write: false };
-
- for (let index = 0; index < argv.length; index += 1) {
- const arg = argv[index];
- if (arg === '--help' || arg === '-h') {
- usage();
- process.exit(0);
- } else if (arg === '--trace') options.trace = argv[++index];
- else if (arg === '--result') options.result = argv[++index];
- else if (arg === '--model') options.model = argv[++index] ?? MODEL;
- else if (arg === '--write') options.write = true;
- else if (arg === '--markdown') options.markdown = true;
- else throw new Error(`Unknown option: ${arg}`);
- }
-
- if (!options.trace) throw new Error('--trace is required');
- if (options.write && !options.result) throw new Error('--write requires --result');
-
- return options;
-};
-
-const addOperators = (target, source = {}) => {
- target.H += Number(source.H ?? 0);
- target.K += Number(source.K ?? 0);
- target.M += Number(source.M ?? 0);
- target.P += Number(source.P ?? 0);
- target.R_ms += Number(source.R_ms ?? 0);
- target.T_chars += Number(source.T_chars ?? 0);
-};
-
-const round = (value) => Math.round(value * 100) / 100;
-
-const secondsFromOperators = (operators) =>
- round(
- operators.H * TIMING_SECONDS.H +
- operators.K * TIMING_SECONDS.K +
- operators.M * TIMING_SECONDS.M +
- operators.P * TIMING_SECONDS.P +
- operators.T_chars * TIMING_SECONDS.T_char +
- operators.R_ms / 1000,
- );
-
-const activeSecondsFromOperators = (operators) =>
- round(
- operators.H * TIMING_SECONDS.H +
- operators.K * TIMING_SECONDS.K +
- operators.M * TIMING_SECONDS.M +
- operators.P * TIMING_SECONDS.P +
- operators.T_chars * TIMING_SECONDS.T_char,
- );
-
-const phaseKey = (event) =>
- event.phase?.id || event.phase?.checkItemId || event.checkItemId || 'unscoped';
-
-const phaseLabel = (event, key) =>
- event.phase?.label || (key === 'unscoped' ? event.phase?.checkItemId : key) || 'Unscoped actions';
-
-const parseTrace = async (tracePath) => {
- const raw = await readFile(tracePath, 'utf8');
- return raw
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter(Boolean)
- .map((line, index) => {
- try {
- return JSON.parse(line);
- } catch (error) {
- throw new Error(`Invalid JSONL at line ${index + 1}: ${error.message}`, { cause: error });
- }
- });
-};
-
-const summarize = (events, { model, tracePath }) => {
- const operators = emptyOperators();
- const phases = new Map();
- const categoryCounts = {};
- const mentalEstimates = [];
- let actualAgentMs = 0;
-
- for (const event of events) {
- const eventOperators = event.klm?.operators ?? emptyOperators();
- addOperators(operators, eventOperators);
-
- const category = event.klm?.category ?? 'unknown';
- categoryCounts[category] = (categoryCounts[category] ?? 0) + 1;
- actualAgentMs += Number(event.durationMs ?? 0);
-
- if (event.type === 'mental_estimate' && event.mentalEstimate) {
- mentalEstimates.push({
- confidence: event.mentalEstimate.confidence,
- mOperators: event.mentalEstimate.mOperators,
- phaseId: event.phase?.id,
- reason: event.mentalEstimate.reason,
- score: event.mentalEstimate.score,
- });
- }
-
- const key = phaseKey(event);
- const existing = phases.get(key) ?? {
- actionCount: 0,
- actualAgentMs: 0,
- checkItemId: event.phase?.checkItemId,
- id: key,
- label: phaseLabel(event, key),
- operators: emptyOperators(),
- };
-
- addOperators(existing.operators, eventOperators);
- existing.actionCount += 1;
- existing.actualAgentMs += Number(event.durationMs ?? 0);
- phases.set(key, existing);
- }
-
- const phaseItems = [...phases.values()].map((phase) => ({
- ...phase,
- activeSeconds: activeSecondsFromOperators(phase.operators),
- actualAgentSeconds: round(phase.actualAgentMs / 1000),
- seconds: secondsFromOperators(phase.operators),
- waitSeconds: round(phase.operators.R_ms / 1000),
- }));
-
- return {
- actionCount: events.length,
- activeSeconds: activeSecondsFromOperators(operators),
- actualAgentSeconds: round(actualAgentMs / 1000),
- categoryCounts,
- generatedAt: new Date().toISOString(),
- mentalEstimates,
- model,
- operators,
- phases: phaseItems.sort((a, b) => b.seconds - a.seconds),
- scope: 'user-equivalent',
- sourceTrace: path.basename(tracePath),
- timingSeconds: TIMING_SECONDS,
- totalSeconds: secondsFromOperators(operators),
- waitSeconds: round(operators.R_ms / 1000),
- };
-};
-
-const toMarkdown = (summary) => {
- const topPhases = summary.phases.slice(0, 5);
- const phaseRows = topPhases
- .map(
- (phase) =>
- `| ${phase.label} | ${phase.seconds.toFixed(2)}s | ${phase.activeSeconds.toFixed(2)}s | ${phase.waitSeconds.toFixed(2)}s |`,
- )
- .join('\n');
-
- return `## GOMS-KLM 交互成本
-
-- 模型:\`${summary.model}\`
-- 用户等效总成本:${summary.totalSeconds.toFixed(2)}s
-- 主动操作成本:${summary.activeSeconds.toFixed(2)}s
-- 系统等待成本:${summary.waitSeconds.toFixed(2)}s
-- 操作符:K=${summary.operators.K}, P=${summary.operators.P}, H=${summary.operators.H}, M=${summary.operators.M}, T=${summary.operators.T_chars} chars, R=${summary.operators.R_ms}ms
-
-| 阶段 | 总成本 | 主动 | 等待 |
-| --- | ---: | ---: | ---: |
-${phaseRows || '| 无 | 0.00s | 0.00s | 0.00s |'}
-`;
-};
-
-const patchResult = async (resultPath, summary, write) => {
- const raw = await readFile(resultPath, 'utf8');
- const result = JSON.parse(raw);
- result.interactionCost = summary;
-
- if (write) {
- await writeFile(resultPath, `${JSON.stringify(result, null, 2)}\n`, 'utf8');
- }
-
- return result;
-};
-
-const main = async () => {
- const options = parseArgs(process.argv.slice(2));
- const tracePath = path.resolve(options.trace);
- const events = await parseTrace(tracePath);
- const summary = summarize(events, { model: options.model, tracePath });
-
- if (options.result) await patchResult(path.resolve(options.result), summary, options.write);
-
- if (options.markdown) console.log(toMarkdown(summary));
- else console.log(JSON.stringify(summary, null, 2));
-};
-
-if (process.argv[1] === fileURLToPath(import.meta.url)) {
- main().catch((error) => {
- console.error('[agent-browser-klm-analyze]', error.message);
- process.exit(1);
- });
-}
diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjs b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjs
deleted file mode 100755
index 671b0d8d35c..00000000000
--- a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjs
+++ /dev/null
@@ -1,494 +0,0 @@
-#!/usr/bin/env node
-/**
- * agent-browser-klm.mjs
- *
- * Thin wrapper around `agent-browser` that records each executed command as an
- * interaction atom for GOMS-KLM analysis. Unknown flags are forwarded.
- *
- * Browser output is captured through temp files rather than pipes: the
- * agent-browser daemon can inherit and hold the child's stdio descriptors, so a
- * pipe might never reach EOF and `spawnSync` would block on it. A file has no
- * such dependency. The output is attached to the trace atom, and on failure it
- * is echoed to stderr — a swallowed error reads exactly like a successful step
- * (the page simply never navigated), which is far worse than noisy output.
- */
-
-import { spawnSync } from 'node:child_process';
-import { randomUUID } from 'node:crypto';
-import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs';
-import { appendFile, mkdir } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const SCHEMA = 'lobehub.agentBrowserKlmTrace@1';
-const DEFAULT_TRACE = '.records/interaction-trace.jsonl';
-
-// Enough to carry an agent-browser diagnostic; keeps one JSONL atom on one line.
-const MAX_CAPTURED_CHARS = 4000;
-
-const optionValueFlags = new Set([
- '--browser',
- '--cdp',
- '--device',
- '--engine',
- '--args',
- '--host',
- '--port',
- '--profile',
- '--proxy',
- '--proxy-bypass',
- '--session',
- '--session-name',
- '--state',
- '--timeout',
- '--url',
- '--user-data-dir',
- '--executable-path',
- '--extension',
- '--headers',
- '--user-agent',
- '--screenshot-dir',
- '--screenshot-quality',
- '--screenshot-format',
- '--download-path',
- '--allowed-domains',
- '--action-policy',
- '--confirm-actions',
- '--config',
- '--model',
-]);
-
-const forwardedBooleanGlobalFlags = new Set([
- '--auto-connect',
- '--headless',
- '--headed',
- '--no-sandbox',
-]);
-
-const defaultOperators = () => ({
- H: 0,
- K: 0,
- M: 0,
- P: 0,
- R_ms: 0,
- T_chars: 0,
-});
-
-const usage = () => {
- console.log(`Usage:
- agent-browser-klm.mjs [--klm-trace file] [--klm-phase id] [--klm-check id] [--klm-command-timeout-ms ms] -- <agent-browser args...>
- agent-browser-klm.mjs mental [--m n] [--reason text] [--confidence n] [--score n] [--klm-trace file]
-
-Examples:
- AGENT_BROWSER_KLM_TRACE="$DIR/interaction-trace.jsonl" \\
- agent-browser-klm.mjs --klm-phase login --klm-check case-1 --session app-dev click @e3
-
- agent-browser-klm.mjs mental --m 2 --score 3 --confidence 0.75 \\
- --reason "First view requires understanding status and next action"`);
-};
-
-const parseNumber = (value, fallback) => {
- if (value === undefined) return fallback;
- const number = Number(value);
- return Number.isFinite(number) ? number : fallback;
-};
-
-const parseOwnFlags = (argv) => {
- const meta = {
- checkItemId: process.env.AGENT_BROWSER_KLM_CHECK || process.env.KLM_CHECK_ITEM_ID,
- label: process.env.AGENT_BROWSER_KLM_LABEL || process.env.KLM_LABEL,
- phaseId: process.env.AGENT_BROWSER_KLM_PHASE || process.env.KLM_PHASE_ID,
- surface: process.env.AGENT_BROWSER_KLM_SURFACE || process.env.KLM_SURFACE || 'web',
- commandTimeoutMs: parseNumber(process.env.AGENT_BROWSER_KLM_COMMAND_TIMEOUT_MS, undefined),
- trace:
- process.env.AGENT_BROWSER_KLM_TRACE ||
- process.env.INTERACTION_TRACE ||
- path.resolve(process.cwd(), DEFAULT_TRACE),
- };
- let binary = process.env.AGENT_BROWSER_BIN || 'agent-browser';
- const forwarded = [];
-
- for (let index = 0; index < argv.length; index += 1) {
- const arg = argv[index];
- if (arg === '--') {
- forwarded.push(...argv.slice(index + 1));
- break;
- }
-
- if (arg === '--klm-help' || arg === '-h') {
- usage();
- process.exit(0);
- }
-
- if (arg === '--klm-trace') meta.trace = path.resolve(argv[++index] ?? DEFAULT_TRACE);
- else if (arg === '--klm-phase') meta.phaseId = argv[++index];
- else if (arg === '--klm-label') meta.label = argv[++index];
- else if (arg === '--klm-check') meta.checkItemId = argv[++index];
- else if (arg === '--klm-surface') meta.surface = argv[++index] ?? meta.surface;
- else if (arg === '--klm-command-timeout-ms')
- meta.commandTimeoutMs = parseNumber(argv[++index], meta.commandTimeoutMs);
- else if (arg === '--klm-agent-browser') binary = argv[++index] ?? binary;
- else forwarded.push(arg);
- }
-
- return { binary, forwarded, meta };
-};
-
-const appendEvent = async (trace, event) => {
- await mkdir(path.dirname(path.resolve(trace)), { recursive: true });
- await appendFile(trace, `${JSON.stringify(event)}\n`, 'utf8');
-};
-
-const findCommandIndex = (args) => {
- for (let index = 0; index < args.length; index += 1) {
- const arg = args[index];
-
- if (arg === '--') continue;
- if (optionValueFlags.has(arg)) {
- index += 1;
- continue;
- }
- if (arg.startsWith('--')) {
- if (!forwardedBooleanGlobalFlags.has(arg) && arg.includes('=')) continue;
- continue;
- }
- if (arg.startsWith('-')) continue;
-
- return index;
- }
-
- return -1;
-};
-
-const normalizeCommand = (args) => {
- const index = findCommandIndex(args);
- if (index < 0) return { argsAfterCommand: [], command: null };
- return {
- argsAfterCommand: args.slice(index + 1),
- command: args[index],
- };
-};
-
-const textLength = (value) => (typeof value === 'string' ? [...value].length : 0);
-
-const lastNonFlag = (args) => {
- for (let index = args.length - 1; index >= 0; index -= 1) {
- const arg = args[index];
- if (!arg.startsWith('-')) return arg;
- }
-};
-
-const numericWaitMs = (args) => {
- const direct = args.find((arg) => /^\d+(?:\.\d+)?$/.test(arg));
- return direct ? Number(direct) : undefined;
-};
-
-const classifyFindCommand = (args) => {
- const action = [...args]
- .reverse()
- .find((arg) => ['check', 'click', 'fill', 'press', 'select', 'type'].includes(arg));
- if (!action)
- return {
- assumptions: ['Semantic lookup only; no user-equivalent action counted.'],
- category: 'probe',
- operators: defaultOperators(),
- };
-
- return classifyCommand(action, args.slice(args.indexOf(action) + 1), 0);
-};
-
-function classifyCommand(command, args, durationMs) {
- const operators = defaultOperators();
- const assumptions = [];
- let category = 'probe';
-
- switch (command) {
- case 'check':
- case 'click':
- case 'download':
- case 'select': {
- operators.P = 1;
- operators.K = 1;
- category = 'interaction';
- assumptions.push(`${command} maps to pointer acquisition plus one activation.`);
- break;
- }
-
- case 'dblclick': {
- operators.P = 1;
- operators.K = 2;
- category = 'interaction';
- assumptions.push('dblclick maps to pointer acquisition plus two activations.');
- break;
- }
-
- case 'fill':
- case 'type': {
- operators.P = 1;
- operators.T_chars = textLength(lastNonFlag(args));
- category = 'interaction';
- assumptions.push(`${command} maps to pointer acquisition plus user-equivalent text entry.`);
- break;
- }
-
- case 'keyboard': {
- const subcommand = args[0];
- if (subcommand === 'type' || subcommand === 'inserttext') {
- operators.T_chars = textLength(args.at(-1));
- category = 'interaction';
- assumptions.push(`keyboard ${subcommand} maps to user-equivalent text entry.`);
- } else if (subcommand === 'press') {
- operators.K = 1;
- category = 'interaction';
- assumptions.push('keyboard press maps to one keystroke.');
- }
- break;
- }
-
- case 'press': {
- operators.K = 1;
- category = 'interaction';
- assumptions.push('press maps to one keystroke.');
- break;
- }
-
- case 'scroll': {
- operators.P = 1;
- operators.K = 1;
- category = 'interaction';
- assumptions.push('scroll maps to target acquisition plus one wheel/gesture action.');
- break;
- }
-
- case 'open':
- case 'goto':
- case 'navigate': {
- operators.R_ms = Math.max(0, Math.round(durationMs));
- category = 'navigation';
- assumptions.push('Direct navigation is counted as system response time, not URL typing.');
- break;
- }
-
- case 'wait': {
- operators.R_ms = Math.max(0, Math.round(numericWaitMs(args) ?? durationMs));
- category = 'wait';
- assumptions.push('wait maps to system response time.');
- break;
- }
-
- case 'find': {
- return classifyFindCommand(args);
- }
-
- case 'screenshot':
- case 'pdf': {
- category = 'evidence';
- assumptions.push(
- `${command} is evidence capture and is not counted as user-side interaction.`,
- );
- break;
- }
-
- case 'snapshot':
- case 'eval':
- case 'get':
- case 'network':
- case 'stream': {
- category = 'probe';
- assumptions.push(
- `${command} is an agent probe and is not counted unless paired with a mental estimate.`,
- );
- break;
- }
-
- default: {
- category = 'unknown';
- assumptions.push('Unknown agent-browser command; no user-equivalent operators inferred.');
- }
- }
-
- return { assumptions, category, operators };
-}
-
-const buildPhase = (meta) => {
- if (!meta.phaseId && !meta.label && !meta.checkItemId) return undefined;
- return {
- checkItemId: meta.checkItemId,
- id: meta.phaseId ?? meta.checkItemId ?? 'unscoped',
- label: meta.label,
- };
-};
-
-const readCapture = (file) => {
- try {
- const text = readFileSync(file, 'utf8').trim();
- if (!text) return undefined;
- return text.length > MAX_CAPTURED_CHARS
- ? `${text.slice(0, MAX_CAPTURED_CHARS)}… [truncated]`
- : text;
- } catch {
- return undefined;
- }
-};
-
-const spawnCapturing = (binary, args, timeout) => {
- const captureDir = mkdtempSync(path.join(tmpdir(), 'agent-browser-klm-'));
- const stdoutPath = path.join(captureDir, 'stdout.log');
- const stderrPath = path.join(captureDir, 'stderr.log');
- const stdoutFd = openSync(stdoutPath, 'w');
- const stderrFd = openSync(stderrPath, 'w');
- let open = true;
- const closeBoth = () => {
- if (!open) return;
- open = false;
- closeSync(stdoutFd);
- closeSync(stderrFd);
- };
-
- try {
- const result = spawnSync(binary, args, {
- killSignal: 'SIGKILL',
- stdio: ['ignore', stdoutFd, stderrFd],
- timeout,
- });
- // Close before reading so a SIGKILLed child's last writes are flushed.
- closeBoth();
- return { result, stderr: readCapture(stderrPath), stdout: readCapture(stdoutPath) };
- } finally {
- closeBoth();
- rmSync(captureDir, { force: true, recursive: true });
- }
-};
-
-const runAgentBrowser = async (binary, args, meta) => {
- if (args.length === 0) {
- usage();
- process.exit(1);
- }
-
- const startedAtMs = Date.now();
- const startedAt = new Date(startedAtMs).toISOString();
- const { argsAfterCommand, command } = normalizeCommand(args);
-
- const { result, stderr, stdout } = spawnCapturing(
- binary,
- args,
- meta.commandTimeoutMs && meta.commandTimeoutMs > 0 ? meta.commandTimeoutMs : undefined,
- );
-
- if (result.error && result.error.code !== 'ETIMEDOUT') {
- console.error(`[agent-browser-klm] failed to start ${binary}:`, result.error.message);
- }
-
- const timedOut = result.error?.code === 'ETIMEDOUT';
- const exitCode = timedOut ? 124 : (result.status ?? (result.error ? 127 : 1));
-
- const completedAtMs = Date.now();
- const durationMs = completedAtMs - startedAtMs;
- const klm = classifyCommand(command, argsAfterCommand, durationMs);
- if (timedOut) {
- klm.category = 'blocked';
- klm.operators = defaultOperators();
- klm.assumptions.push('agent-browser command timed out; no user-equivalent cost counted.');
- } else if (exitCode !== 0) {
- // The action never happened, so charging it as a completed interaction (or
- // as navigation response time) would inflate the cost model with phantom work.
- klm.category = 'blocked';
- klm.operators = defaultOperators();
- klm.assumptions.push(
- `agent-browser exited ${exitCode}; the action did not happen, so no user-equivalent cost counted.`,
- );
- }
-
- if (exitCode !== 0) {
- const detail = stderr ?? stdout;
- console.error(
- `[agent-browser-klm] ${binary} ${command ?? '<no command>'} exited ${exitCode}` +
- (detail ? `:\n${detail}` : ' with no output.'),
- );
- }
-
- const event = {
- agentBrowser: { args, command },
- completedAt: new Date(completedAtMs).toISOString(),
- durationMs,
- exitCode,
- id: randomUUID(),
- klm,
- phase: buildPhase(meta),
- schema: SCHEMA,
- source: 'agent-browser',
- startedAt,
- stderr,
- stdout,
- surface: meta.surface,
- timedOut,
- type: 'agent_browser_action',
- };
-
- await appendEvent(meta.trace, event);
- process.exit(exitCode);
-};
-
-const recordMentalEstimate = async (argv, baseMeta) => {
- const mental = {
- confidence: undefined,
- mOperators: 1,
- reason: undefined,
- score: undefined,
- };
-
- const { meta } = parseOwnFlags(argv);
- const mergedMeta = { ...baseMeta, ...meta };
-
- for (let index = 0; index < argv.length; index += 1) {
- const arg = argv[index];
- if (arg === '--m') mental.mOperators = parseNumber(argv[++index], mental.mOperators);
- else if (arg === '--reason') mental.reason = argv[++index];
- else if (arg === '--confidence') mental.confidence = parseNumber(argv[++index], undefined);
- else if (arg === '--score') mental.score = parseNumber(argv[++index], undefined);
- }
-
- const operators = defaultOperators();
- operators.M = mental.mOperators;
- await appendEvent(mergedMeta.trace, {
- id: randomUUID(),
- klm: {
- assumptions: ['Mental operators are estimated by the agent from the observed page/context.'],
- category: 'mental',
- operators,
- },
- mentalEstimate: mental,
- phase: buildPhase(mergedMeta),
- recordedAt: new Date().toISOString(),
- schema: SCHEMA,
- source: 'agent',
- surface: mergedMeta.surface,
- type: 'mental_estimate',
- });
-};
-
-const main = async () => {
- const argv = process.argv.slice(2);
- if (argv[0] === '--klm-help' || argv[0] === '-h') {
- usage();
- return;
- }
-
- if (argv[0] === 'mental') {
- const { meta } = parseOwnFlags(argv.slice(1));
- await recordMentalEstimate(argv.slice(1), meta);
- return;
- }
-
- const { binary, forwarded, meta } = parseOwnFlags(argv);
- await runAgentBrowser(binary, forwarded, meta);
-};
-
-if (process.argv[1] === fileURLToPath(import.meta.url)) {
- main().catch((error) => {
- console.error('[agent-browser-klm]', error);
- process.exit(1);
- });
-}
diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.sh b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.sh
deleted file mode 100755
index db38f5a79dc..00000000000
--- a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.sh
+++ /dev/null
@@ -1,133 +0,0 @@
-#!/usr/bin/env bash
-# Smoke tests for agent-browser KLM wrapper + analyzer. Uses a stub
-# agent-browser, so no real browser is required.
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-WRAPPER="$SCRIPT_DIR/agent-browser-klm.mjs"
-ANALYZER="$SCRIPT_DIR/agent-browser-klm-analyze.mjs"
-
-fail() {
- echo "FAIL: $*" >&2
- exit 1
-}
-
-tmp_dir="$(mktemp -d)"
-trap 'rm -rf "$tmp_dir"' EXIT
-
-mkdir -p "$tmp_dir/bin"
-cat > "$tmp_dir/bin/agent-browser" << 'SH'
-#!/usr/bin/env bash
-set -euo pipefail
-printf '%s\n' "$*" >> "${AGENT_BROWSER_STUB_LOG:?}"
-SH
-chmod +x "$tmp_dir/bin/agent-browser"
-
-export PATH="$tmp_dir/bin:$PATH"
-export AGENT_BROWSER_STUB_LOG="$tmp_dir/agent-browser.log"
-
-trace="$tmp_dir/interaction-trace.jsonl"
-trace_flags="$tmp_dir/flags-trace.jsonl"
-result="$tmp_dir/result.json"
-
-node "$WRAPPER" --klm-trace "$trace" --klm-phase first --klm-check case-1 --session app click @e1
-node "$WRAPPER" --klm-trace "$trace" --klm-phase form --klm-check case-1 fill @e2 hello
-node "$WRAPPER" --klm-trace "$trace" --klm-phase wait --session app wait 2000
-node "$WRAPPER" mental --klm-trace "$trace" --klm-phase first --m 2 --score 3 --confidence 0.75 --reason "first view"
-node "$WRAPPER" --klm-trace "$trace_flags" --klm-phase nav --engine chrome --args --no-proxy-server open about:blank
-
-node "$ANALYZER" --trace "$trace" > "$tmp_dir/summary.json"
-
-node - "$tmp_dir/summary.json" << 'JS'
-const fs = require('fs');
-const summary = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
-
-function eq(actual, expected, label) {
- if (actual !== expected) {
- throw new Error(`${label}: expected ${expected}, got ${actual}`);
- }
-}
-
-eq(summary.operators.P, 2, 'P');
-eq(summary.operators.K, 1, 'K');
-eq(summary.operators.M, 2, 'M');
-eq(summary.operators.T_chars, 5, 'T_chars');
-eq(summary.operators.R_ms, 2000, 'R_ms');
-eq(summary.totalSeconds, 8.1, 'totalSeconds');
-eq(summary.activeSeconds, 6.1, 'activeSeconds');
-eq(summary.waitSeconds, 2, 'waitSeconds');
-eq(summary.phases[0].id, 'first', 'top phase');
-JS
-
-cat > "$result" << 'JSON'
-{
- "title": "KLM smoke",
- "cases": [],
- "summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending" }
-}
-JSON
-
-node "$ANALYZER" --trace "$trace" --result "$result" --write > /dev/null
-
-node - "$result" << 'JS'
-const fs = require('fs');
-const result = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
-if (!result.interactionCost) throw new Error('interactionCost missing');
-if (result.interactionCost.totalSeconds !== 8.1) {
- throw new Error(`unexpected patched total: ${result.interactionCost.totalSeconds}`);
-}
-JS
-
-grep -Fq -- "--session app click @e1" "$AGENT_BROWSER_STUB_LOG" || fail "wrapper did not forward click"
-grep -Fq -- "--engine chrome --args --no-proxy-server open about:blank" "$AGENT_BROWSER_STUB_LOG" ||
- fail "wrapper did not forward global flags"
-
-node - "$trace_flags" << 'JS'
-const fs = require('fs');
-const event = JSON.parse(fs.readFileSync(process.argv[2], 'utf8').trim());
-if (event.agentBrowser.command !== 'open') {
- throw new Error(`expected open command, got ${event.agentBrowser.command}`);
-}
-if (event.klm.category !== 'navigation') {
- throw new Error(`expected navigation category, got ${event.klm.category}`);
-}
-JS
-
-# A failing agent-browser must not look like a successful step: the wrapper has to
-# echo the browser's own diagnostic and charge the atom no interaction cost.
-cat > "$tmp_dir/bin/agent-browser" << 'SH'
-#!/usr/bin/env bash
-echo "✗ Element not found." >&2
-exit 1
-SH
-chmod +x "$tmp_dir/bin/agent-browser"
-
-trace_fail="$tmp_dir/fail-trace.jsonl"
-set +e
-fail_output="$(node "$WRAPPER" --klm-trace "$trace_fail" --klm-phase nav --session app click @e9 2>&1)"
-fail_code=$?
-set -e
-
-[ "$fail_code" -eq 1 ] || fail "expected exit 1 from failing agent-browser, got $fail_code"
-case "$fail_output" in
- *"Element not found"*) ;;
- *) fail "wrapper swallowed the agent-browser diagnostic: <$fail_output>" ;;
-esac
-
-node - "$trace_fail" << 'JS'
-const fs = require('fs');
-const event = JSON.parse(fs.readFileSync(process.argv[2], 'utf8').trim());
-if (event.exitCode !== 1) throw new Error(`expected exitCode 1, got ${event.exitCode}`);
-if (event.klm.category !== 'blocked') {
- throw new Error(`a failed command must be blocked, got ${event.klm.category}`);
-}
-if (event.klm.operators.P !== 0 || event.klm.operators.K !== 0) {
- throw new Error('a failed click must not be charged pointer/keystroke cost');
-}
-if (!String(event.stderr).includes('Element not found')) {
- throw new Error('captured stderr missing from the trace atom');
-}
-JS
-
-echo "agent-browser KLM tests passed"
diff --git a/apps/cli/skills/agent-testing/scripts/capture-app-window.sh b/apps/cli/skills/agent-testing/scripts/capture-app-window.sh
deleted file mode 100755
index 5a04cd19c2a..00000000000
--- a/apps/cli/skills/agent-testing/scripts/capture-app-window.sh
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env bash
-#
-# capture-app-window.sh — Capture a screenshot of a specific app window
-#
-# Uses CGWindowList via Swift to find the window by process name, then
-# screencapture -l <windowID> to capture only that window.
-# Falls back to full-screen capture if the window is not found.
-#
-# Usage:
-# ./capture-app-window.sh <process_name> <output_path>
-#
-# Arguments:
-# process_name — The process/owner name as shown in Activity Monitor
-# (e.g., "Discord", "Slack", "Telegram", "WeChat", "QQ", "Lark")
-# output_path — Path to save the screenshot (e.g., /tmp/screenshot.png)
-#
-# Examples:
-# ./capture-app-window.sh "Discord" /tmp/discord.png
-# ./capture-app-window.sh "Slack" /tmp/slack.png
-# ./capture-app-window.sh "微信" /tmp/wechat.png
-#
-set -euo pipefail
-
-PROCESS="${1:?Usage: capture-app-window.sh <process_name> <output_path>}"
-OUTPUT="${2:?Usage: capture-app-window.sh <process_name> <output_path>}"
-
-# Preflight: OS screen capture returns a fully-black image when Screen Recording
-# permission is missing OR the display is asleep/locked/screensavered. Fail fast with
-# remediation instead of silently writing a black artifact. Set SKIP_SCREEN_CHECK=1 to bypass.
-if [ "${SKIP_SCREEN_CHECK:-0}" != "1" ]; then
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
- if ! "$SCRIPT_DIR/check-screen-recording.sh"; then
- echo "[capture] Aborting: OS screen capture would be black. Fix the above, or wrap the run in 'caffeinate -dimsu' to keep the display awake." >&2
- exit 1
- fi
-fi
-
-# Find the CGWindowID for the target process using Swift + CGWindowList
-# Pass process name via environment variable (swift -e doesn't support -- args)
-WINDOW_ID=$(TARGET_PROCESS="$PROCESS" swift -e '
-import Cocoa
-import Foundation
-let target = ProcessInfo.processInfo.environment["TARGET_PROCESS"] ?? ""
-let windowList = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as! [[String: Any]]
-for w in windowList {
- let owner = w["kCGWindowOwnerName"] as? String ?? ""
- let layer = w["kCGWindowLayer"] as? Int ?? -1
- let bounds = w["kCGWindowBounds"] as? [String: Any] ?? [:]
- let ww = bounds["Width"] as? Double ?? 0
- let wh = bounds["Height"] as? Double ?? 0
- let wid = w["kCGWindowNumber"] as? Int ?? 0
- // Match process name, normal window layer (0), and reasonable size
- if owner == target && layer == 0 && ww > 200 && wh > 200 {
- print(wid)
- break
- }
-}
-' 2>/dev/null || true)
-
-if [ -n "$WINDOW_ID" ]; then
- screencapture -l "$WINDOW_ID" -x "$OUTPUT"
-else
- echo "[capture] Warning: Could not find window for '$PROCESS', falling back to full screen"
- screencapture -x "$OUTPUT"
-fi
diff --git a/apps/cli/skills/agent-testing/scripts/cdp-capture.cjs b/apps/cli/skills/agent-testing/scripts/cdp-capture.cjs
deleted file mode 100755
index cdbd16b0d60..00000000000
--- a/apps/cli/skills/agent-testing/scripts/cdp-capture.cjs
+++ /dev/null
@@ -1,166 +0,0 @@
-#!/usr/bin/env node
-// cdp-capture.cjs — capture a screenshot from a CDP target via RAW DevTools protocol,
-// bypassing the agent-browser daemon. Proven reliable against headful Electron/Chrome
-// regardless of display sleep or window minimization/occlusion (Page.captureScreenshot
-// forces a compositor frame). Every CDP call is hard-timeout guarded so a stall fails
-// fast instead of wedging anything.
-//
-// Usage: node cdp-capture.cjs --port 9222 --out shot.png [--full] [--target-url <substr>] [--timeout 12000]
-// Prints one line of JSON: {"ok":true,"bytes":N,"ms":N,"targetUrl":"..."} or {"ok":false,"error":"..."}
-// Exit 0 on success, non-zero on failure/timeout.
-//
-// Requires the `ws` package to be resolvable from this file's own location —
-// Node's require() walks up ancestor node_modules automatically, so this works
-// whether the skill ships inside @lobehub/cli's own node_modules or a hoisted
-// monorepo root; no manual NODE_PATH wiring needed. A `lh verify install`-copied
-// skill dir lives inside a consumer repo's harness skills dir, though, so the
-// ancestor walk from there never reaches @lobehub/cli's node_modules — fall
-// back to the `cliRoot` recorded in the sibling `.skill-meta.json`.
-
-const http = require('node:http');
-const fs = require('node:fs');
-const path = require('node:path');
-
-function resolveWs() {
- const attempted = [];
- try {
- return require('ws');
- } catch {
- attempted.push('ancestor node_modules walk from ' + __filename);
- }
-
- const markerDir = path.join(__dirname, '..');
- const metaPath = path.join(markerDir, '.skill-meta.json');
- let cliRoot;
- try {
- const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
- cliRoot = meta && meta.cliRoot;
- if (cliRoot && !path.isAbsolute(cliRoot)) {
- cliRoot = path.resolve(markerDir, cliRoot);
- }
- } catch {
- attempted.push(metaPath + ' (missing or unreadable)');
- }
-
- if (cliRoot) {
- // createRequire, not a hand-built <cliRoot>/node_modules/ws path: pnpm
- // links a package's deps NEXT TO it (.pnpm/<pkg>@<v>/node_modules/ws),
- // so only Node's real resolution walk anchored inside cliRoot finds ws
- // across both npm and pnpm layouts.
- try {
- return require('node:module').createRequire(path.join(cliRoot, 'package.json'))('ws');
- } catch {
- attempted.push("createRequire('ws') from " + cliRoot + ' (via .skill-meta.json cliRoot)');
- }
- }
-
- console.log(
- JSON.stringify({
- ok: false,
- error:
- "Cannot find module 'ws'. Tried: " +
- attempted.join('; ') +
- ". This script requires the 'ws' package to be resolvable " +
- 'from its own install location (a dependency of @lobehub/cli, or installed ' +
- "alongside it). Run 'npm install ws' in the consuming project if using this " +
- 'script standalone.',
- }),
- );
- process.exit(7);
-}
-
-const WebSocket = resolveWs();
-
-const arg = (k, d) => {
- const i = process.argv.indexOf(k);
- return i > -1 ? process.argv[i + 1] : d;
-};
-const has = (k) => process.argv.includes(k);
-const PORT = parseInt(arg('--port', '9222'), 10);
-const OUT = arg('--out', '/tmp/cdp-capture.png');
-const FULL = has('--full');
-const TURL = arg('--target-url', '');
-const TIMEOUT = parseInt(arg('--timeout', '12000'), 10);
-
-const done = (obj, code) => {
- console.log(JSON.stringify(obj));
- process.exit(code);
-};
-const httpGet = (path) =>
- new Promise((res, rej) => {
- const req = http.get({ host: '127.0.0.1', port: PORT, path }, (r) => {
- let d = '';
- r.on('data', (c) => (d += c));
- r.on('end', () => {
- try {
- res(JSON.parse(d));
- } catch (e) {
- rej(e);
- }
- });
- });
- req.on('error', rej);
- req.setTimeout(4000, () =>
- req.destroy(
- new Error(
- 'CDP HTTP timeout — is the app running with --remote-debugging-port=' + PORT + '?',
- ),
- ),
- );
- });
-
-function client(url) {
- const ws = new WebSocket(url, { maxPayload: 512 * 1024 * 1024 });
- const pending = new Map();
- let id = 0;
- const ready = new Promise((r, j) => {
- ws.on('open', r);
- ws.on('error', j);
- });
- ws.on('message', (m) => {
- const o = JSON.parse(m);
- if (o.id && pending.has(o.id)) {
- pending.get(o.id)(o);
- pending.delete(o.id);
- }
- });
- const send = (method, params = {}, timeout = TIMEOUT) =>
- new Promise((res, rej) => {
- const myid = ++id;
- pending.set(myid, (o) =>
- o.error ? rej(new Error(method + ': ' + o.error.message)) : res(o.result),
- );
- ws.send(JSON.stringify({ id: myid, method, params }));
- setTimeout(() => {
- if (pending.has(myid)) {
- pending.delete(myid);
- rej(new Error('TIMEOUT ' + method + ' after ' + timeout + 'ms'));
- }
- }, timeout);
- });
- return { ws, ready, send };
-}
-
-(async () => {
- const targets = await httpGet('/json');
- const pages = targets.filter((t) => t.type === 'page' && t.webSocketDebuggerUrl);
- const page = TURL ? pages.find((t) => (t.url || '').includes(TURL)) : pages[0];
- if (!page) throw new Error('no page target found' + (TURL ? ' matching "' + TURL + '"' : ''));
- const pg = client(page.webSocketDebuggerUrl);
- await pg.ready;
- let params = { format: 'png' };
- if (FULL) {
- const m = await pg.send('Page.getLayoutMetrics', {});
- const s = m.cssContentSize || m.contentSize;
- params = {
- format: 'png',
- captureBeyondViewport: true,
- clip: { x: 0, y: 0, width: Math.ceil(s.width), height: Math.ceil(s.height), scale: 1 },
- };
- }
- const t0 = Date.now();
- const r = await pg.send('Page.captureScreenshot', params);
- const buf = Buffer.from(r.data, 'base64');
- fs.writeFileSync(OUT, buf);
- done({ ok: true, bytes: buf.length, ms: Date.now() - t0, targetUrl: page.url }, 0);
-})().catch((e) => done({ ok: false, error: e.message }, 1));
diff --git a/apps/cli/skills/agent-testing/scripts/cdp-screenshot.sh b/apps/cli/skills/agent-testing/scripts/cdp-screenshot.sh
deleted file mode 100755
index cd37a93e844..00000000000
--- a/apps/cli/skills/agent-testing/scripts/cdp-screenshot.sh
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/env bash
-#
-# cdp-screenshot.sh — Reliable Electron/Chrome screenshot via RAW CDP (bypasses the
-# agent-browser daemon) + optional preflight verdict.
-#
-# Why this exists: agent-browser's `screenshot` goes through a long-lived daemon that
-# can wedge ("CDP response channel closed" / "daemon busy") after an interrupted or
-# mis-invoked capture — and once wedged, every later screenshot fails while eval/get
-# still work. Raw `Page.captureScreenshot` is fast (~60ms) and robust: it forces a
-# compositor frame, so it works even when the DISPLAY IS ASLEEP or the WINDOW IS
-# MINIMIZED/OCCLUDED (both verified). Use this instead of `agent-browser screenshot`
-# for Electron evidence, and as a preflight to prove capture works before relying on it.
-#
-# Usage:
-# ./cdp-screenshot.sh [--port 9222] [--out shot.png] [--full] [--target-url <substr>] [--check]
-#
-# --check preflight mode: capture a throwaway frame, verify it is non-black,
-# print a PASS/FAIL verdict. Exit 0 only if a real frame was captured.
-#
-# Exit codes: 0 ok · 5 capture failed/timeout · 6 captured but BLACK · 7 node/dependency missing
-set -uo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-PORT=9222; OUT=""; CHECK=0; PASS=()
-while [ $# -gt 0 ]; do
- case "$1" in
- --port) PORT="$2"; shift 2 ;;
- --out) OUT="$2"; shift 2 ;;
- --check) CHECK=1; shift ;;
- --full|--target-url) PASS+=("$1"); [ "$1" = "--target-url" ] && { PASS+=("$2"); shift; }; shift ;;
- *) PASS+=("$1"); shift ;;
- esac
-done
-[ -z "$OUT" ] && OUT="${TMPDIR:-/tmp}/cdp-shot-$PORT.png"
-
-command -v node >/dev/null 2>&1 || { echo "[cdp-shot] node not found"; exit 7; }
-
-# cdp-capture.cjs resolves the `ws` package itself via Node's normal ancestor
-# node_modules lookup from its own file location — no NODE_PATH plumbing needed.
-res="$(node "$SCRIPT_DIR/cdp-capture.cjs" --port "$PORT" --out "$OUT" --timeout 12000 ${PASS[@]+"${PASS[@]}"} 2>&1)"
-ok="$(printf '%s' "$res" | sed -n 's/.*"ok":\([a-z]*\).*/\1/p')"
-
-if [ "$ok" != "true" ]; then
- case "$res" in
- *"Cannot find module 'ws'"*)
- echo "[cdp-shot] MISSING DEPENDENCY: $res"
- exit 7
- ;;
- esac
- echo "[cdp-shot] CAPTURE FAILED: $res"
- echo "[cdp-shot] Fix: ensure the app runs with --remote-debugging-port=$PORT and CDP is reachable (curl 127.0.0.1:$PORT/json/version). If agent-browser wedged the session earlier, reset it: 'agent-browser close --all'. Raw CDP here does not use that daemon."
- exit 5
-fi
-
-# blackness verdict (sips + python3; skip silently if unavailable)
-verdict="unknown"; maxv=""
-if command -v sips >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
- sips -z 16 16 "$OUT" --out "$OUT.s.png" >/dev/null 2>&1
- sips -s format bmp "$OUT.s.png" --out "$OUT.bmp" >/dev/null 2>&1
- maxv="$(python3 - "$OUT.bmp" <<'PY' 2>/dev/null || echo -1
-import sys
-d=open(sys.argv[1],'rb').read();off=int.from_bytes(d[10:14],'little');w=int.from_bytes(d[18:22],'little');h=abs(int.from_bytes(d[22:26],'little',signed=True))
-bpp=int.from_bytes(d[28:30],'little') or 24;B=bpp//8;row=((w*bpp+31)//32)*4;mx=0
-for y in range(h):
- for x in range(w):
- q=off+y*row+x*B
- if q+2<len(d): mx=max(mx,d[q],d[q+1],d[q+2])
-print(mx)
-PY
-)"
- rm -f "$OUT.s.png" "$OUT.bmp" 2>/dev/null
- [[ "$maxv" =~ ^[0-9]+$ ]] && { (( maxv < 12 )) && verdict="black" || verdict="live"; }
-fi
-
-if [ "$verdict" = "black" ]; then
- echo "[cdp-shot] CAPTURED BUT BLACK ($res). Unusual for CDP — check the page actually rendered (not a blank route)."
- [ "$CHECK" = "1" ] && exit 6
- exit 6
-fi
-
-echo "[cdp-shot] OK ($res)${maxv:+ maxBrightness=$maxv}"
-[ "$CHECK" = "1" ] && { rm -f "$OUT" 2>/dev/null; echo "[cdp-shot] PREFLIGHT PASS — CDP screenshot works on port $PORT."; }
-exit 0
diff --git a/apps/cli/skills/agent-testing/scripts/check-screen-recording.sh b/apps/cli/skills/agent-testing/scripts/check-screen-recording.sh
deleted file mode 100755
index 0aa88278aca..00000000000
--- a/apps/cli/skills/agent-testing/scripts/check-screen-recording.sh
+++ /dev/null
@@ -1,144 +0,0 @@
-#!/usr/bin/env bash
-#
-# check-screen-recording.sh — Preflight gate for OS-level screen capture (macOS).
-#
-# OS screenshots (`screencapture`, osascript, bot-channel captures) come out
-# ENTIRELY BLACK when either:
-# 1. Screen Recording (TCC) permission is not granted to the responsible app, or
-# 2. the display is asleep / locked / running a screensaver (permission is fine
-# but there is nothing lit to capture — common after a long idle test run).
-# A black artifact is easy to mistake for a real capture, so gate on this BEFORE
-# any OS-capture step. CDP-based evidence (agent-browser screenshot, record-app-screen)
-# renders from the browser engine and is NOT affected — this check is only for the
-# OS-capture surfaces (bot tests, capture-app-window.sh, osascript screenshots).
-#
-# Usage:
-# ./check-screen-recording.sh # human-readable; exit 0 if OS capture will work
-# ./check-screen-recording.sh --json # machine-readable one-line JSON
-#
-# Exit codes:
-# 0 OS capture works (permission granted AND a live, non-black frame captured)
-# 0 non-macOS (OS capture N/A — use CDP evidence)
-# 3 permission NOT granted → grant Screen Recording, then restart the app
-# 4 permission ok but frame BLACK → wake/unlock display, quit screensaver, or restart app
-# 2 could not determine (no screencapture/toolchain)
-#
-set -uo pipefail
-
-JSON=0
-for a in "$@"; do case "$a" in --json) JSON=1 ;; esac; done
-
-emit() { # $1=ok(true/false) $2=perm $3=capture $4=exit $5=message [$6=app]
- if [[ $JSON == 1 ]]; then
- printf '{"platform":"%s","ok":%s,"permission":"%s","capture":"%s","responsibleApp":"%s","message":"%s"}\n' \
- "$(uname -s)" "$1" "${2:-unknown}" "${3:-unknown}" "${6:-}" "$5"
- else
- echo "[screen-recording] $5"
- fi
- exit "$4"
-}
-
-os=$(uname -s)
-if [[ "$os" != "Darwin" ]]; then
- emit true "n/a" "n/a" 0 "non-macOS ($os): OS screen capture N/A; CDP-based evidence is unaffected. OK."
-fi
-
-# --- responsible app: TCC attributes Screen Recording to the ancestor .app bundle ---
-responsible_app() {
- local pid=$$ ppid comm
- for _ in $(seq 1 12); do
- if ! read -r ppid comm < <(ps -o ppid=,comm= -p "$pid" 2>/dev/null); then break; fi
- [[ -z "${ppid:-}" ]] && break
- if [[ "$comm" == *.app/Contents/MacOS/* ]]; then
- local app="${comm%%.app/*}"; echo "${app##*/}.app"; return 0
- fi
- [[ "${ppid:-0}" -le 1 ]] && break
- pid=$ppid
- done
- echo "${TERM_PROGRAM:-your terminal app}"
-}
-APP="$(responsible_app)"
-
-# --- layer 1: TCC permission via CGPreflightScreenCaptureAccess (no prompt, no display) ---
-perm="unknown"
-bin="${TMPDIR:-/tmp}/lobehub-scrcheck"
-if [[ ! -x "$bin" ]] && command -v clang >/dev/null 2>&1; then
- src="${TMPDIR:-/tmp}/lobehub-scrcheck.c"
- cat > "$src" <<'EOF'
-#include <CoreGraphics/CoreGraphics.h>
-#include <stdio.h>
-int main(void){ bool ok = CGPreflightScreenCaptureAccess(); printf(ok?"granted\n":"denied\n"); return ok?0:1; }
-EOF
- clang -framework CoreGraphics -o "$bin" "$src" 2>/dev/null || rm -f "$bin"
-fi
-if [[ -x "$bin" ]]; then
- perm="$("$bin" 2>/dev/null || echo denied)"
-elif command -v swift >/dev/null 2>&1; then
- perm="$(swift - <<'EOF' 2>/dev/null || echo denied
-import CoreGraphics
-print(CGPreflightScreenCaptureAccess() ? "granted" : "denied")
-EOF
-)"
-fi
-
-# --- layer 2: liveness — capture one real frame and detect a fully-black image ---
-# Uses the brightest pixel across a downscaled grid: a live desktop always has some
-# lit chrome (menu bar / cursor / window), a blocked/asleep capture is uniformly ~0.
-capture="unknown"; maxv=""
-if command -v screencapture >/dev/null 2>&1; then
- shot="${TMPDIR:-/tmp}/lobehub-scrlive.png"
- small="${TMPDIR:-/tmp}/lobehub-scrlive.bmp"
- rm -f "$shot" "$small"
- screencapture -x "$shot" 2>/dev/null || true
- if [[ -s "$shot" ]] && command -v sips >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
- sips -z 16 16 "$shot" --out "${shot}.s.png" >/dev/null 2>&1
- sips -s format bmp "${shot}.s.png" --out "$small" >/dev/null 2>&1
- if [[ -s "$small" ]]; then
- maxv="$(python3 - "$small" <<'PY' 2>/dev/null || echo -1
-import sys
-d=open(sys.argv[1],'rb').read()
-off=int.from_bytes(d[10:14],'little')
-w=int.from_bytes(d[18:22],'little')
-h=abs(int.from_bytes(d[22:26],'little',signed=True))
-bpp=int.from_bytes(d[28:30],'little') or 24
-Bpp=bpp//8
-row=((w*bpp+31)//32)*4
-mx=0
-for y in range(h):
- base=off+y*row
- for x in range(w):
- p=base+x*Bpp
- if p+2 < len(d):
- mx=max(mx, d[p], d[p+1], d[p+2])
-print(mx)
-PY
-)"
- if [[ "${maxv:-}" =~ ^[0-9]+$ ]]; then
- # brightest channel < 12/255 across the whole screen ⇒ effectively black
- if (( maxv < 12 )); then capture="black"; else capture="live"; fi
- fi
- fi
- fi
- rm -f "$shot" "${shot}.s.png" "$small" 2>/dev/null || true
-fi
-
-# --- decision ---
-if [[ "$capture" == "live" ]]; then
- emit true "$perm" "$capture" 0 "OK — Screen Recording works (permission granted, display live). OS captures and bot tests will render real frames." "$APP"
-fi
-
-if [[ "$capture" == "black" ]]; then
- if [[ "$perm" == "denied" ]]; then
- emit false "$perm" "$capture" 3 "BLOCKED — Screen Recording permission is NOT granted to '$APP'. Enable it in: System Settings ▸ Privacy & Security ▸ Screen Recording ▸ turn ON '$APP', then FULLY QUIT & reopen '$APP' (TCC only takes effect on a fresh launch). Until then every OS screenshot/recording and bot test will be BLACK." "$APP"
- fi
- emit false "$perm" "$capture" 4 "BLACK FRAME — permission looks OK but the capture is black. The display is likely asleep / locked / on a screensaver, or '$APP' was just granted permission but not restarted. Wake & unlock the display, disable the screensaver for the test run (caffeinate -d), or restart '$APP', then re-run this check." "$APP"
-fi
-
-# capture couldn't be measured → fall back to the permission verdict
-if [[ "$perm" == "denied" ]]; then
- emit false "$perm" "$capture" 3 "BLOCKED — Screen Recording permission is NOT granted to '$APP'. Enable it: System Settings ▸ Privacy & Security ▸ Screen Recording ▸ turn ON '$APP', then fully quit & reopen '$APP'." "$APP"
-elif [[ "$perm" == "granted" ]]; then
- emit true "$perm" "$capture" 0 "Permission granted for '$APP'; could not verify a live frame (no screencapture/sips/python3). Proceeding — if OS captures come out black, wake/unlock the display." "$APP"
-else
- emit false "$perm" "$capture" 2 "UNDETERMINED — could not check Screen Recording permission or capture a test frame (missing clang/swift/screencapture). Verify manually in System Settings ▸ Privacy & Security ▸ Screen Recording for '$APP'." "$APP"
-fi
diff --git a/apps/cli/skills/agent-testing/scripts/fixture.mjs b/apps/cli/skills/agent-testing/scripts/fixture.mjs
deleted file mode 100755
index e859a18e7c2..00000000000
--- a/apps/cli/skills/agent-testing/scripts/fixture.mjs
+++ /dev/null
@@ -1,192 +0,0 @@
-#!/usr/bin/env node
-/**
- * fixture.mjs — reusable per-check fixture assets for agent-testing.
- *
- * Fixtures are the durable half of a verification: for each CHECK ITEM (the
- * business check that recurs across acceptance rounds) we keep one directory
- * holding its plan fragment, case template, seed inputs, and (optionally)
- * replayable steps. Rounds are then COMPOSED from checks instead of hand-writing
- * a fresh result.json every time.
- *
- * INPUTS vs OUTPUTS — only inputs are reusable. `seed/` holds what a run
- * CONSUMES (files to upload, DB seed fragments, config, stand-in evidence for
- * synthetic ingest rounds). What a run PRODUCES (screenshots, transcripts) is
- * tied to that one execution and lives only in the round dir's assets/ under
- * .records/reports/ — never copy it back into the fixture.
- *
- * Layout (gitignored, like all .records/ output):
- * .records/fixtures/<subject-key>/<check-id>/
- * ├── check.json # plan fragment + case template (+ steps for future replay)
- * └── seed/ # reusable INPUT assets referenced by check.json / steps
- *
- * <subject-key> = task-<id> | topic-<id> | document-<id> (subject with ':'→'-'),
- * matching the report group dirs under .records/reports/.
- *
- * Usage:
- * fixture.mjs init-check --subject topic:tpc_xxx <check-id>
- * Scaffold .records/fixtures/topic-tpc_xxx/<check-id>/{check.json,seed/}
- *
- * fixture.mjs compose --subject topic:tpc_xxx --slug <slug> [--title "..."]
- * [--focus "..."] [--entry "..."] <check-id> [<check-id>...]
- * Assemble a report-shaped round dir from the given checks:
- * .records/reports/topic-tpc_xxx/<ts>-<slug>/ (ready for
- * `lh verify ingest-report <dir>`). Files referenced by case.evidence
- * (seed/…) are copied into the round's assets/<check-id>/ and paths
- * rewritten. Prints the dir path.
- *
- * fixture.mjs list --subject topic:tpc_xxx
- * List the subject's check fixtures.
- */
-import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
-import path from 'node:path';
-
-const { basename, join } = path;
-
-// The generic skill is invoked from the consumer repository. Keep all
-// generated fixtures and reports anchored to that explicit working directory.
-const REPO_ROOT = process.cwd();
-
-const fail = (msg) => {
- console.error(`fixture.mjs: ${msg}`);
- process.exit(1);
-};
-
-const parseArgs = (argv) => {
- const opts = {};
- const positional = [];
- for (let i = 0; i < argv.length; i++) {
- const arg = argv[i];
- if (arg.startsWith('--')) {
- opts[arg.slice(2)] = argv[++i];
- } else {
- positional.push(arg);
- }
- }
- return { opts, positional };
-};
-
-const subjectKey = (subject) => {
- if (!/^(?:task|topic|document):.+$/.test(subject || '')) {
- fail(`--subject must be task:<id> | topic:<id> | document:<id>, got '${subject}'`);
- }
- return subject.replace(':', '-');
-};
-
-const [command, ...rest] = process.argv.slice(2);
-const { opts, positional } = parseArgs(rest);
-
-if (command === 'init-check') {
- const key = subjectKey(opts.subject);
- const checkId = positional[0] || fail('init-check needs a <check-id>');
- const dir = join(REPO_ROOT, '.records/fixtures', key, checkId);
- if (existsSync(join(dir, 'check.json'))) fail(`${dir}/check.json already exists`);
- mkdirSync(join(dir, 'seed'), { recursive: true });
- const template = {
- id: checkId,
- category: '',
- title: '',
- verifier: 'agent',
- method: '',
- expected: '',
- requiredEvidence: [],
- // Case template used by `compose`: the default verdict + observation this
- // fixture reproduces. Evidence paths point at reusable INPUTS under seed/
- // (relative to this check dir) — real execution outputs stay in the round.
- case: { result: 'passed', observation: '', evidence: [] },
- // Reserved for the JSON-replay runner: deterministic steps that set up and
- // verify this check without an agent improvising them each round.
- steps: [],
- notes: '',
- };
- writeFileSync(join(dir, 'check.json'), JSON.stringify(template, null, 2) + '\n');
- console.log(dir);
-} else if (command === 'list') {
- const key = subjectKey(opts.subject);
- const root = join(REPO_ROOT, '.records/fixtures', key);
- if (!existsSync(root)) fail(`no fixtures under ${root}`);
- for (const entry of readdirSync(root, { withFileTypes: true })) {
- if (!entry.isDirectory()) continue;
- const checkFile = join(root, entry.name, 'check.json');
- if (!existsSync(checkFile)) continue;
- const check = JSON.parse(readFileSync(checkFile, 'utf8'));
- console.log(`${entry.name}\t[${check.category}] ${check.title} → ${check.case?.result}`);
- }
-} else if (command === 'compose') {
- const key = subjectKey(opts.subject);
- const slug = opts.slug || fail('compose needs --slug');
- if (positional.length === 0) fail('compose needs at least one <check-id>');
-
- const fixturesRoot = join(REPO_ROOT, '.records/fixtures', key);
- const now = new Date();
- const pad = (n) => String(n).padStart(2, '0');
- const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
- const dir = join(REPO_ROOT, '.records/reports', key, `${ts}-${slug}`);
- mkdirSync(join(dir, 'assets'), { recursive: true });
-
- const plan = [];
- const cases = [];
- for (const checkId of positional) {
- const checkDir = join(fixturesRoot, checkId);
- const checkFile = join(checkDir, 'check.json');
- if (!existsSync(checkFile)) fail(`missing ${checkFile} (run init-check first)`);
- const check = JSON.parse(readFileSync(checkFile, 'utf8'));
-
- plan.push({
- id: check.id,
- category: check.category,
- title: check.title,
- verifier: check.verifier || 'agent',
- method: check.method,
- expected: check.expected,
- ...(check.requiredEvidence?.length ? { requiredEvidence: check.requiredEvidence } : {}),
- });
-
- const evidenceList = [check.case?.evidence ?? []].flat();
- const evidence = evidenceList.map((entry) => {
- const src = typeof entry === 'string' ? entry : entry.path;
- const target = join('assets', check.id, basename(src));
- mkdirSync(join(dir, 'assets', check.id), { recursive: true });
- cpSync(join(checkDir, src), join(dir, target));
- return typeof entry === 'string' ? target : { ...entry, path: target };
- });
-
- cases.push({
- id: check.id,
- name: check.title,
- result: check.case?.result ?? 'passed',
- observation: check.case?.observation ?? '',
- ...(evidence.length ? { evidence: evidence.length === 1 ? evidence[0] : evidence } : {}),
- });
- }
-
- const passed = cases.filter((c) => c.result === 'passed').length;
- const failed = cases.filter((c) => c.result === 'failed').length;
- const blocked = cases.filter((c) => c.result === 'blocked').length;
- const result = {
- title: opts.title || slug,
- scenario: 'coding',
- subject: opts.subject,
- context: {
- focus: opts.focus || '',
- entry: opts.entry || '',
- branch: '',
- commit: '',
- },
- surfaces: ['web'],
- plan,
- cases,
- summary: {
- total: cases.length,
- passed,
- failed,
- blocked,
- verdict: failed > 0 ? 'fail' : 'pass',
- conclusion: opts.conclusion || `${passed}/${cases.length} 通过`,
- },
- };
- writeFileSync(join(dir, 'result.json'), JSON.stringify(result, null, 2) + '\n');
- writeFileSync(join(dir, 'report.md'), `${opts.title || slug}\n`);
- console.log(dir);
-} else {
- fail(`unknown command '${command}' (init-check | compose | list)`);
-}
diff --git a/apps/cli/skills/agent-testing/scripts/record-app-screen.sh b/apps/cli/skills/agent-testing/scripts/record-app-screen.sh
deleted file mode 100755
index f5c4f1bd6f7..00000000000
--- a/apps/cli/skills/agent-testing/scripts/record-app-screen.sh
+++ /dev/null
@@ -1,188 +0,0 @@
-#!/usr/bin/env bash
-#
-# record-app-screen.sh — Record the Electron app window (video + screenshots)
-#
-# Captures screenshots via agent-browser (CDP), then assembles into video on stop.
-# Works on any screen (including external monitors) since it uses CDP, not screen capture.
-#
-# Usage:
-# ./record-app-screen.sh start [output_name] # Begin recording
-# ./record-app-screen.sh stop # Stop and save
-# ./record-app-screen.sh status # Check recording state
-#
-# Run this from the CONSUMER repo root — output goes to .records/ under the
-# current working directory, not relative to this script's own location.
-#
-# Outputs to .records/ directory:
-# .records/<name>.mp4 — Video assembled from screenshots (~2 fps)
-# .records/<name>/ — Screenshots every SCREENSHOT_INTERVAL seconds
-#
-# Prerequisites:
-# - ffmpeg installed (bun add -g ffmpeg-static, or brew install ffmpeg)
-# - agent-browser CLI installed
-# - Electron app already running with CDP enabled
-#
-# Environment variables:
-# CDP_PORT — Chrome DevTools Protocol port (default: 9222)
-# SCREENSHOT_INTERVAL — Seconds between gallery screenshots (default: 3)
-# VIDEO_FRAME_INTERVAL — Seconds between video frames (default: 0.5)
-#
-# Examples:
-# record-app-screen.sh start gateway-demo
-# # ... run automation via agent-browser ...
-# record-app-screen.sh stop
-#
-set -euo pipefail
-
-RECORDS_DIR="$(pwd)/.records"
-PID_FILE="/tmp/record-app-screen.pids"
-STATE_FILE="/tmp/record-app-screen.state"
-
-CDP_PORT="${CDP_PORT:-9222}"
-SCREENSHOT_INTERVAL="${SCREENSHOT_INTERVAL:-3}"
-VIDEO_FRAME_INTERVAL="${VIDEO_FRAME_INTERVAL:-0.5}"
-
-AB="agent-browser --cdp $CDP_PORT"
-
-# ─── Commands ───
-
-cmd_start() {
- local output_name="${1:-recording-$(date +%Y%m%d-%H%M%S)}"
- local output_video="$RECORDS_DIR/${output_name}.mp4"
- local screenshot_dir="$RECORDS_DIR/${output_name}"
- local frames_dir
- frames_dir=$(mktemp -d /tmp/record-frames-XXXXXX)
-
- if [ -f "$PID_FILE" ]; then
- echo "[record] A recording is already active. Run '$0 stop' first."
- exit 1
- fi
-
- mkdir -p "$RECORDS_DIR" "$screenshot_dir"
-
- # Video frames loop (~2 fps via agent-browser CDP screenshots)
- (
- local idx=0
- while true; do
- local fname
- fname=$(printf "%s/frame_%06d.png" "$frames_dir" "$idx")
- $AB screenshot "$fname" 2>/dev/null || true
- idx=$((idx + 1))
- sleep "$VIDEO_FRAME_INTERVAL"
- done
- ) &
- local frames_pid=$!
-
- # Gallery screenshots loop (every N seconds for human review)
- (
- local idx=0
- while true; do
- local fname
- fname=$(printf "%s/%04d.png" "$screenshot_dir" "$idx")
- $AB screenshot "$fname" 2>/dev/null || true
- idx=$((idx + 1))
- sleep "$SCREENSHOT_INTERVAL"
- done
- ) &
- local screenshot_pid=$!
-
- # Save state
- echo "$frames_pid $screenshot_pid" > "$PID_FILE"
- echo "$output_video $frames_dir $screenshot_dir" > "$STATE_FILE"
-
- echo "[record] Started!"
- echo " Video frames: every ${VIDEO_FRAME_INTERVAL}s (PID $frames_pid)"
- echo " Screenshots: every ${SCREENSHOT_INTERVAL}s → $screenshot_dir/"
- echo " Stop with: $0 stop"
-}
-
-cmd_stop() {
- if [ ! -f "$PID_FILE" ] || [ ! -f "$STATE_FILE" ]; then
- echo "[record] No active recording found."
- return 0
- fi
-
- local frames_pid screenshot_pid
- read -r frames_pid screenshot_pid < "$PID_FILE"
-
- local output_video frames_dir screenshot_dir
- read -r output_video frames_dir screenshot_dir < "$STATE_FILE"
-
- # Stop both capture loops
- kill "$frames_pid" 2>/dev/null || true
- kill "$screenshot_pid" 2>/dev/null || true
- wait "$frames_pid" 2>/dev/null || true
- wait "$screenshot_pid" 2>/dev/null || true
-
- # Assemble frames into video
- local frame_count
- frame_count=$(ls -1 "$frames_dir"/frame_*.png 2>/dev/null | wc -l | tr -d ' ')
-
- if [ "$frame_count" -gt 0 ]; then
- echo "[record] Assembling $frame_count frames into video..."
- ffmpeg -y -framerate 2 -i "$frames_dir/frame_%06d.png" \
- -c:v libx264 -crf 23 -pix_fmt yuv420p -an \
- "$output_video" > /tmp/ffmpeg-assemble.log 2>&1
-
- if [ ! -s "$output_video" ]; then
- echo " [warn] Video assembly failed. Check /tmp/ffmpeg-assemble.log"
- echo " Frames preserved in: $frames_dir/"
- fi
- else
- echo " [warn] No frames captured."
- fi
-
- rm -rf "$frames_dir" 2>/dev/null
- rm -f "$PID_FILE" "$STATE_FILE"
-
- local video_size screenshot_count
- video_size=$(ls -lh "$output_video" 2>/dev/null | awk '{print $5}' || echo "?")
- screenshot_count=$(ls -1 "$screenshot_dir"/*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")
-
- echo "[record] Stopped!"
- echo " Video: $output_video ($video_size)"
- echo " Screenshots: ${screenshot_count} files in $screenshot_dir/"
- echo " Play: open $output_video"
-}
-
-cmd_status() {
- if [ ! -f "$PID_FILE" ]; then
- echo "[record] No active recording."
- return 0
- fi
-
- local frames_pid screenshot_pid
- read -r frames_pid screenshot_pid < "$PID_FILE"
-
- local frames_ok="no" screenshot_ok="no"
- kill -0 "$frames_pid" 2>/dev/null && frames_ok="yes"
- kill -0 "$screenshot_pid" 2>/dev/null && screenshot_ok="yes"
-
- if [ -f "$STATE_FILE" ]; then
- local output_video frames_dir screenshot_dir
- read -r output_video frames_dir screenshot_dir < "$STATE_FILE"
- local frame_count ss_count
- frame_count=$(ls -1 "$frames_dir"/frame_*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")
- ss_count=$(ls -1 "$screenshot_dir"/*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")
- echo "[record] Active recording"
- echo " Frames: $frame_count captured (running: $frames_ok)"
- echo " Screenshots: $ss_count captured (running: $screenshot_ok)"
- echo " Output: $output_video"
- fi
-}
-
-# ─── Main ───
-
-case "${1:-}" in
- start) shift; cmd_start "$@" ;;
- stop) cmd_stop ;;
- status) cmd_status ;;
- *)
- echo "Usage: $0 {start [name] | stop | status}"
- echo ""
- echo " start [name] Start recording (default: recording-YYYYMMDD-HHMMSS)"
- echo " stop Stop recording and save outputs"
- echo " status Check if recording is active"
- exit 1
- ;;
-esac
diff --git a/apps/cli/skills/agent-testing/scripts/record-gif.sh b/apps/cli/skills/agent-testing/scripts/record-gif.sh
deleted file mode 100755
index d352c3c9e1b..00000000000
--- a/apps/cli/skills/agent-testing/scripts/record-gif.sh
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env bash
-# record-gif.sh — capture a frame sequence via agent-browser (CDP) and
-# synthesize a GIF for embedding in a test report.
-#
-# Use this whenever the asserted behavior is about CHANGE OVER TIME —
-# streaming output, a ticking timer, loading states, animations. A static
-# screenshot cannot prove those; a GIF can. Cloud-portable: frames come from
-# CDP rendering, no OS-level screen capture.
-#
-# Usage:
-# record-gif.sh <output.gif> <duration_seconds> [fps]
-#
-# AB_TARGET="--cdp 9222" # Electron (default; CDP_PORT honored)
-# AB_TARGET="--session your-session" # web agent-browser session
-# GIF_WIDTH=960 # output width (px), default 960
-#
-# Requires ffmpeg (`brew install ffmpeg`). Effective fps is capped by
-# screenshot latency (~0.3-0.5s per frame); 1-2 fps is the realistic range.
-#
-# Example — record a 12s run and embed it in the report:
-# ./record-gif.sh "$DIR/assets/case2-tray-running.gif" 12 2 &
-# GIF_PID=$!
-# # ... trigger the streaming behavior ...
-# wait $GIF_PID
-
-set -euo pipefail
-
-OUT="${1:?Usage: record-gif.sh <output.gif> <duration_seconds> [fps]}"
-DUR="${2:?Usage: record-gif.sh <output.gif> <duration_seconds> [fps]}"
-FPS="${3:-2}"
-AB_TARGET="${AB_TARGET:---cdp ${CDP_PORT:-9222}}"
-GIF_WIDTH="${GIF_WIDTH:-960}"
-
-command -v ffmpeg > /dev/null || {
- echo "ffmpeg not found — install with: brew install ffmpeg" >&2
- exit 1
-}
-
-TMP=$(mktemp -d)
-trap 'rm -rf "$TMP"' EXIT
-
-FRAMES=$((DUR * FPS))
-INTERVAL=$(python3 -c "print(1 / $FPS)")
-
-for i in $(seq -f '%04g' 1 "$FRAMES"); do
- # shellcheck disable=SC2086
- agent-browser $AB_TARGET screenshot "$TMP/frame-$i.png" > /dev/null 2>&1 || true
- sleep "$INTERVAL"
-done
-
-CAPTURED=$(find "$TMP" -name 'frame-*.png' | wc -l | tr -d ' ')
-[ "$CAPTURED" -gt 0 ] || {
- echo "no frames captured — is the app reachable via $AB_TARGET?" >&2
- exit 1
-}
-
-ffmpeg -y -loglevel error -framerate "$FPS" -pattern_type glob -i "$TMP/frame-*.png" \
- -vf "fps=$FPS,scale=$GIF_WIDTH:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \
- "$OUT"
-
-echo "$OUT ($CAPTURED frames @ ${FPS}fps)"
diff --git a/apps/cli/skills/agent-testing/scripts/report-init.sh b/apps/cli/skills/agent-testing/scripts/report-init.sh
deleted file mode 100755
index d2ada73d3d9..00000000000
--- a/apps/cli/skills/agent-testing/scripts/report-init.sh
+++ /dev/null
@@ -1,133 +0,0 @@
-#!/usr/bin/env bash
-# report-init.sh — scaffold a structured test report under .records/reports/.
-#
-# Format spec and evidence rules: ../references/report.md
-#
-# Usage:
-# report-init.sh [--subject <type:id>] <slug> [title]
-#
-# With --subject (task:<id> | topic:<id> | document:<id>) the run is grouped
-# under its acceptance:
-# .records/reports/<type>-<id>/<YYYYMMDD-HHMMSS>-<slug>/
-# and the group directory gets an acceptance.json marker. The subject is also
-# pre-filled into result.json so ingest-report attaches the run automatically.
-#
-# Run this from the CONSUMER repo root — the report is created relative to the
-# current working directory, not relative to this script's own location.
-#
-# Prints the report directory path (capture it: DIR=$(report-init.sh my-test)).
-
-set -euo pipefail
-
-SUBJECT=""
-if [[ "${1:-}" == "--subject" ]]; then
- SUBJECT="${2:?--subject requires a value like topic:tpc_xxx}"
- shift 2
-fi
-
-SLUG="${1:?Usage: report-init.sh [--subject <type:id>] <slug> [title]}"
-TITLE="${2:-$SLUG}"
-
-json_escape() {
- local s=$1
- s=${s//\\/\\\\}
- s=${s//\"/\\\"}
- s=${s//$'\n'/\\n}
- s=${s//$'\r'/\\r}
- s=${s//$'\t'/\\t}
- printf '%s' "$s"
-}
-
-REPO_ROOT="$(pwd)"
-TS="$(date +%Y%m%d-%H%M%S)"
-
-SUBJECT_JSON="null"
-if [[ -n "$SUBJECT" ]]; then
- if [[ ! "$SUBJECT" =~ ^(task|topic|document):.+$ ]]; then
- echo "report-init.sh: --subject must be task:<id> | topic:<id> | document:<id>, got '$SUBJECT'" >&2
- exit 1
- fi
- SUBJECT_KEY="${SUBJECT/:/-}"
- GROUP_DIR="$REPO_ROOT/.records/reports/$SUBJECT_KEY"
- DIR="$GROUP_DIR/$TS-$SLUG"
- SUBJECT_JSON="\"$(json_escape "$SUBJECT")\""
-else
- DIR="$REPO_ROOT/.records/reports/$TS-$SLUG"
-fi
-mkdir -p "$DIR/assets"
-
-BRANCH=$(git -C "$REPO_ROOT" branch --show-current 2> /dev/null || echo "unknown")
-COMMIT=$(git -C "$REPO_ROOT" rev-parse --short HEAD 2> /dev/null || echo "unknown")
-DATE_ISO=$(date '+%Y-%m-%dT%H:%M:%S%z')
-
-# acceptance.json records the group identity. The first title names the
-# acceptance; later runs update only the timestamp and latest round.
-if [[ -n "$SUBJECT" ]]; then
- ACCEPTANCE_JSON="$GROUP_DIR/acceptance.json"
- if [[ ! -f "$ACCEPTANCE_JSON" ]]; then
- cat > "$ACCEPTANCE_JSON" << EOF
-{
- "subject": "$(json_escape "$SUBJECT")",
- "title": "$(json_escape "$TITLE")",
- "createdAt": "$(json_escape "$DATE_ISO")",
- "updatedAt": "$(json_escape "$DATE_ISO")",
- "lastRun": "$(json_escape "$TS-$SLUG")"
-}
-EOF
- else
- node -e '
- const fs = require("fs");
- const [file, run, iso] = process.argv.slice(1);
- const data = JSON.parse(fs.readFileSync(file, "utf8"));
- data.updatedAt = iso;
- data.lastRun = run;
- fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
- ' "$ACCEPTANCE_JSON" "$TS-$SLUG" "$DATE_ISO"
- fi
-fi
-
-# report.md is rendered as the verify page's "Details" tail — free-form COMMENT.
-# The scope (范围), per-case table (用例), overall conclusion, and the score are
-# all STRUCTURED on the page now (result.json scenario/context + cases +
-# summary.conclusion + summary.score), so DON'T repeat any of them here or they
-# double up. Keep only non-duplicate detail: repro commands, caveats, follow-ups.
-cat > "$DIR/report.md" << EOF
-## 备注 / 说明
-
-<!-- 复现命令、注意事项、仍需跟进项;没有则写“无”。不要贴图片/GIF——视觉证据放在
- result.json 的 cases[].evidence 里,页面会渲染,report.md 里重复会重复展示。 -->
-
-\`\`\`bash
-# command
-\`\`\`
-EOF
-
-# result.json drives the structured page. \`summary.conclusion\` is the overall
-# conclusion shown at the top (under the title); \`summary.score\` (0-100) becomes
-# the \`score\` stat; branch/commit/surfaces/entry render the one-line provenance.
-#
-# \`plan\` is filled BEFORE the run: {id, title, method, expected} per check. It
-# shares ids with \`cases\`, so the page pairs intent against outcome and shows a
-# planned item that never ran as 未执行 rather than dropping it.
-#
-# \`surfaces\` is a closed set: web | desktop | cli | mobile | bot. It is where a
-# check RAN — not a test kind (unit/backend) and not a runtime mode (packaged
-# build / CDP dev instance; that goes on the plan item's \`method\`).
-cat > "$DIR/result.json" << EOF
-{
- "title": "$(json_escape "$TITLE")",
- "scenario": "coding",
- "createdAt": "$(json_escape "$DATE_ISO")",
- "subject": $SUBJECT_JSON,
- "branch": "$(json_escape "$BRANCH")",
- "commit": "$(json_escape "$COMMIT")",
- "surfaces": [],
- "entry": "",
- "plan": [],
- "cases": [],
- "interactionCost": null,
- "summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending", "conclusion": "", "score": null }
-}
-EOF
-
-echo "$DIR"
diff --git a/apps/cli/skills/agent-testing/surfaces/cli.md b/apps/cli/skills/agent-testing/surfaces/cli.md
deleted file mode 100644
index d4650d9b20f..00000000000
--- a/apps/cli/skills/agent-testing/surfaces/cli.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# CLI Backend Verification
-
-Default surface for verifying **backend changes** (routers, services, models,
-migrations) end-to-end: fastest loop, text-assertable output, zero UI flakiness.
-The project's CLI, its invocation, and its auth all come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) — this guide is the
-methodology, not the commands.
-
-## When to use
-
-- Verifying router / service / model changes end-to-end
-- Testing new API fields or response-structure changes
-- Validating CLI command output after backend modifications
-- Debugging data flow between server and client
-
-## Prerequisites
-
-| Requirement | Where it comes from |
-| ----------------- | --------------------------------------------------------------------------------------------------------------- |
-| Dev server | `PROJECT.md` §2 (base URL/port, start command, health check) |
-| Project CLI | `PROJECT.md` §4 (how the CLI is invoked — run-from-source or built binary — and its standalone install, if any) |
-| Auth | `PROJECT.md` §3 (test account / seeded key / device-code login) |
-| Required services | `PROJECT.md` §6 (any queue/worker/store a command path depends on) |
-
-If the CLI runs from source, code changes on the CLI side usually take effect
-immediately without a rebuild; if it is a built binary, rebuild per `PROJECT.md`
-before re-testing. Confirm which from the adapter.
-
-## Workflow
-
-### 1 — Server up?
-
-Health-check per `PROJECT.md` §2. Server-side code changes require a restart; the
-CLI keeps talking to the old process until you restart it.
-
-### 2 — Auth ready?
-
-Run the CLI auth status check from `PROJECT.md` §3. If it is not authed, follow the
-adapter's auth path (seeded credential first, interactive/device-code login as
-fallback). Drive the login yourself — do not hand the user the step unless it needs
-a secret or device action only they can supply.
-
-### 3 — Test with CLI commands
-
-Run the project's CLI commands for the behavior under test. Capture output for the
-report as you go:
-
-```bash
-# $CLI = the project's CLI invocation from PROJECT.md
-$CLI some-command | tee "$DIR/assets/case.txt"
-```
-
-CLI evidence for the report = the **exact command + trimmed output**. That is a
-non-visual artifact, so a link/transcript in the report is fine (unlike UI cases,
-which must inline a screenshot).
-
-### 4 — Clean up test data
-
-Delete any entities the run created (the adapter lists the CLI's delete commands if
-the project has them). Leaving fixtures behind pollutes the next run.
-
-### 5 — Report
-
-Finish with a structured report — [../references/report.md](../references/report.md).
-
-## Method notes (project-independent)
-
-- **A backend change is still often a UI-visible change.** A permission tightening,
- a new field, a changed error — the blocked/changed state is something a user
- sees. If the change alters product behavior a user can observe, add a UI case in
- the same run (see [web.md](./web.md) / [electron.md](./electron.md)); do not ship
- a UI-touching change with only CLI transcripts.
-- **Prove which runtime ran.** If a command can dispatch to more than one execution
- path (client vs server/queue), confirm the path you intended actually executed —
- a server operation row, a queue step, or a server-only log line — before trusting
- a green result.
-- **A required service down looks like a logic bug.** If a command path POSTs to a
- queue/worker/store that is not running, the run can fail before any real work
- happens, with an error that reads as unrelated. Gate on the services `PROJECT.md`
- §6 marks as prerequisites.
-
-## Dev-test cycle
-
-```
-1. Make code changes (service / model / router / type)
- |
-2. Run unit tests (fast feedback)
- |
-3. Restart dev server (if server-side changes)
- |
-4. CLI verification (end-to-end): <cli> <command>
- |
-5. Clean up test data + write the report
-```
-
-## Troubleshooting
-
-| Issue | Direction |
-| --------------------------- | ------------------------------------------------------------------------ |
-| `No authentication found` | Re-run the adapter's auth path (§3); source any generated credential env |
-| `UNAUTHORIZED` on API calls | Re-seed / re-login per §3 |
-| `ECONNREFUSED` | Dev server not running — start per §2 |
-| CLI shows old data/behavior | Server needs a restart to pick up code changes |
diff --git a/apps/cli/skills/agent-testing/surfaces/electron.md b/apps/cli/skills/agent-testing/surfaces/electron.md
deleted file mode 100644
index e9f1d4587c2..00000000000
--- a/apps/cli/skills/agent-testing/surfaces/electron.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Electron (Desktop) UI Testing
-
-Default surface for verifying **pure frontend changes** (components, store logic,
-styles, interactions) in a project that ships an Electron desktop shell. Drives the
-Electron renderer over CDP with `agent-browser` — see
-[../references/agent-browser.md](../references/agent-browser.md) for the full
-command reference.
-
-The launch/stop of the desktop dev instance, its CDP port, its login persistence,
-and any state probes all come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) §4/§5. This guide is
-the CDP methodology; the project supplies the commands.
-
-## Auth
-
-Sign in once, not once per run — the project's desktop dev tooling should persist
-login across runs (`PROJECT.md` §3 says how). If an instance still comes up signed
-out, **drive the sign-in yourself**; never ask the user to click it. Run the
-desktop auth status check from `PROJECT.md` §3 before testing.
-
-## Linux / headless (cloud)
-
-Electron runs on Linux but has no true headless mode — it needs a display server.
-In a headless environment wrap the launch with `xvfb-run` (virtual framebuffer).
-Everything CDP-based keeps working under Xvfb: the `agent-browser --cdp <port>`
-connection, snapshots, eval, and `agent-browser screenshot` (captured from the
-renderer via CDP, not the OS screen). What does NOT work on Linux:
-`capture-app-window.sh` (macOS `screencapture`), osascript, and OS-level recording.
-
-## Setup / Teardown
-
-Start and stop the desktop dev instance with the project's own script (per
-`PROJECT.md` §4) — it should handle process lifecycle and reliably kill all child
-processes (main + helpers + bundler). After start succeeds, connect with:
-
-```bash
-PORT=9222 # the CDP port from PROJECT.md
-agent-browser --cdp "$PORT" snapshot -i
-```
-
-**Always run the project's stop command when done** — a bare `pkill -f "Electron"`
-does not catch all helper processes (GPU, renderer, network), which survive and
-corrupt the next run.
-
-## Project probes & quick navigation
-
-A project may ship a **state probe** — a fast path into app state (auth check,
-current route, running operations, and a `goto <path>` quick-navigation that jumps
-straight to the state under test instead of clicking through the UI). If it does,
-`PROJECT.md` §5 documents it; use it instead of hand-rolling store-introspection
-eval snippets. When the project has no probe, fall back to raw `agent-browser eval`
-against the renderer, reading whatever store/global the app exposes for debugging.
-
-For one-off state inspection, `agent-browser eval` against the CDP target is always
-available:
-
-```bash
-agent-browser --cdp "$PORT" eval --stdin << 'EVALEOF'
-(function() { /* read app state here */ })()
-EVALEOF
-```
-
-## Method notes (project-independent)
-
-- **A running desktop instance may serve a STALE built bundle, not your working
- tree.** A resident/packaged app serves a built renderer snapshot; it does not
- reflect uncommitted or HMR src changes. Verify working-tree UI in an isolated dev
- instance that loads live code, and **prove it is live by measuring a
- known-changed value** (a computed style, a new string) before trusting any
- screenshot. Don't disturb the user's resident instance — use a separate dev
- instance/port.
-- **Main-process code changes need a restart; renderer HMR does not cover them.**
- If the change lives in the main process (or a package that runs there), reloading
- the renderer verifies nothing — the old main-process code is still running. Prove
- which code each process has (curl the dev bundler for the renderer source and
- grep for a marker; grep the built main bundle for the marker) before trusting a
- run.
-- **Distinguish a non-painting renderer from an empty DOM.** `innerText` needs
- layout, `textContent` does not. If a probe reads `innerText.length === 0` while
- `textContent` still holds the full DOM, the DOM is fine and the renderer is not
- compositing — often after a mid-session bundler dependency re-optimize; a restart
- of the instance clears it, a `location.reload()` alone may not.
-
-## Electron Gotchas
-
-- **`agent-browser screenshot` can wedge the daemon; prefer raw-CDP capture.**
- agent-browser routes captures through a long-lived daemon. An interrupted or
- mis-invoked screenshot can leave the daemon's CDP session half-open, after which
- **every** later screenshot fails (`CDP response channel closed` / `daemon busy`)
- even though `eval` / `get url` still work. This is **not** a display-sleep or
- permission problem: raw `Page.captureScreenshot` is fast and works even when the
- display is asleep or the window is minimized/occluded. Use the raw-CDP helper for
- Electron evidence and as a preflight:
-
- ```bash
- "$SKILL_DIR/scripts/cdp-screenshot.sh" --check # preflight: PASS ⇒ capture works
- "$SKILL_DIR/scripts/cdp-screenshot.sh" --out shot.png # viewport
- "$SKILL_DIR/scripts/cdp-screenshot.sh" --out full.png --full # full page (captureBeyondViewport)
- ```
-
- If agent-browser's own screenshot has already wedged, reset it with
- `agent-browser close --all` (raw-CDP does not use that daemon and is unaffected).
-
-- **Dev builds may auto-open DevTools, which hijacks the CDP target** —
- `agent-browser --cdp <port>` may attach to the DevTools page (`devtools://…`)
- instead of the app. Symptom: `get url` returns a `devtools://` URL. Fix: close the
- DevTools target and reconnect:
-
- ```bash
- DT_ID=$(curl -s "http://localhost:$PORT/json/list" | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")
- curl -s "http://localhost:$PORT/json/close/$DT_ID" > /dev/null
- agent-browser close --all && agent-browser --cdp "$PORT" get url # expect the app URL
- ```
-
-- **Don't resize the Electron window after load** — resizing can trigger a full SPA
- reload and lose your state.
-
-- **Streaming / ticking UI needs GIF evidence** — see `scripts/record-gif.sh`; a
- static screenshot cannot prove time-based behavior.
diff --git a/apps/cli/skills/agent-testing/surfaces/web.md b/apps/cli/skills/agent-testing/surfaces/web.md
deleted file mode 100644
index 9488555f89f..00000000000
--- a/apps/cli/skills/agent-testing/surfaces/web.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Web (Full-Stack) Testing
-
-Default surface for **full-stack changes** — a new/changed API plus the UI that
-consumes it. The browser is the one surface where network requests and UI state are
-observable together, so you can assert both sides of the contract in a single run.
-
-For pure-frontend changes in a project that ships a desktop shell, prefer
-[electron.md](./electron.md); for backend-only changes prefer [cli.md](./cli.md).
-
-The base URL, session name, and auth for the web surface come from
-[`.agents/verify/PROJECT.md`](../references/project-adapter.md) §4/§3. This guide is
-the methodology.
-
-## Prerequisites
-
-- Complete [Step 2.0](../SKILL.md#20-resolve-the-current-test-environment) (resolve
- ports) and the [Phase 1 approval gate](../SKILL.md#phase-1-approval-gate--report-environment--plan-to-the-user) first.
-- Local dev server running — start command from `PROJECT.md` §2.
-- Web auth verified in the agent-browser session — status check and seeding from
- `PROJECT.md` §3.
-
-## Option A — agent-browser with seeded auth (recommended)
-
-Seed/verify the web session per `PROJECT.md` §3, then drive it. Use one named
-session as the single evidence source:
-
-```bash
-SESSION=your-session # session name from PROJECT.md §4
-BASE_URL=http://localhost:3000 # base URL from PROJECT.md §4
-
-agent-browser --session $SESSION open "$BASE_URL/"
-agent-browser --session $SESSION snapshot -i
-# interact via refs — full command reference: ../references/agent-browser.md
-```
-
-Use this session as the evidence source. Do not use ordinary Chrome screenshots or
-Chrome Network records as proof; ordinary Chrome is only a fallback source for
-copying cookies into agent-browser when the seeded login is not available.
-
-### Watch the API while driving the UI
-
-```bash
-# After triggering the UI action under test:
-agent-browser --session $SESSION network requests --type xhr,fetch
-agent-browser --session $SESSION network requests --method POST
-
-# Record a full HAR for the report
-agent-browser --session $SESSION network har start
-# ... drive the scenario ...
-agent-browser --session $SESSION network har stop ./capture.har
-```
-
-Assert both layers: the request/response shape (network) and the rendered result
-(snapshot/screenshot). Both belong in the report as evidence — the network dump or
-HAR as a linked non-visual artifact, the rendered state as an inline screenshot.
-
-## Option B — real Chrome with remote debugging
-
-For flows that need a real, visible browser (e.g. exercising the login UI itself):
-
-```bash
-/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
- --remote-debugging-port=9222 \
- --user-data-dir=/tmp/chrome-test-profile \
- "<URL>" &
-sleep 5
-agent-browser --cdp 9222 snapshot -i
-
-# Or auto-discover a running Chrome with remote debugging
-agent-browser --auto-connect snapshot -i
-```
-
-## Method notes (project-independent)
-
-- **Prove the session is live before trusting an auth-scoped result.** An
- owner-only / permission-gated UI fails identically whether the gate is broken or
- the session is simply missing. `document.cookie` is not the probe — session
- cookies are often httpOnly, so it reads empty on a fully authenticated page.
- Instead call any authed endpoint from the page and read the status: `401` = no
- session reached the server (re-seed), `200` = you are really signed in. Only then
- conclude anything about the gate.
-- **The app can swallow an injected fetch failure.** A store action may resolve
- even when the underlying fetch was aborted, so the UI/promise is not a reliable
- signal that your fault landed. Judge interception by the **fetch's own outcome**
- (wrap `window.fetch` and record each request's resolve/reject) — see
- [../references/probe-mock-patterns.md](../references/probe-mock-patterns.md) A.
-- **A cached first-load can mask a failure.** A surface that loaded once caches the
- last-good value; a later failed fetch keeps showing the settled content instead
- of the error. To see a genuine first-load error, cold-load (clear
- localStorage / sessionStorage / IndexedDB / Cache API), which usually logs you
- out — re-seed auth after. See probe-mock-patterns B.
-- **Enumerate every surface a shared component renders on.** A shared input/toolbar
- can be composed differently on the home page vs an inner page; verify each place
- the changed component appears, with separate evidence, and mark any skipped
- surface explicitly.
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
new file mode 100644
index 00000000000..45c83712a52
--- /dev/null
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -0,0 +1,1060 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { acceptanceSubjectTypes } from '@lobechat/const/verify';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+import { uploadLocalFile } from '../utils/uploadLocalFile';
+import {
+ type Decision,
+ DECISIONS,
+ deriveReportVerdict,
+ evidenceTypeForFile,
+ genericContextFromResult,
+ inlineTextEvidenceForFile,
+ metadataForReport,
+ originFromEnv,
+ parseSubjectRef,
+ planFromResult,
+ printResults,
+ pullRequestFromBranch,
+ pullRequestFromResult,
+ reportEvidence,
+ scenarioFromResult,
+ subjectFromEnv,
+ subjectFromResult,
+ surfacesFromResult,
+ toVerdict,
+} from './verifyHelpers';
+
+// ── Actions ────────────────────────────────────────────────
+//
+// One implementation per command, shared by the canonical `lh acceptance run …`
+// tree and the deprecated `lh verify …` aliases. Both wire the same function, so
+// the two spellings never drift while the aliases live out their deprecation.
+
+// ── install ──
+
+interface InstallOptions {
+ dir?: string;
+ force?: boolean;
+ json?: boolean | string;
+ skill: string;
+}
+
+async function installAction(options: InstallOptions): Promise<void> {
+ const client = await getTrpcClient();
+ // Pulled live from the server's deployed builtin-skills — always the latest.
+ const bundle = await client.verify.getSkillBundle.query({ identifier: options.skill });
+
+ // The acceptance skeleton lands under `.agents/skills/<id>` — the harness dir
+ // the project's own `.agents/acceptance/` adapter sits beside. Invariant: this
+ // is a materialized artifact, re-installed to update, never hand-edited.
+ const baseDir = options.dir ? path.resolve(options.dir) : process.cwd();
+ const skillDir = path.join(baseDir, '.agents', 'skills', bundle.identifier);
+
+ // path → content for SKILL.md plus every resource file.
+ const entries: [string, string][] = [
+ ['SKILL.md', bundle.content],
+ ...Object.entries(bundle.files),
+ ];
+
+ const written: string[] = [];
+ const skipped: string[] = [];
+ for (const [rel, content] of entries) {
+ const dest = path.join(skillDir, rel);
+ if (existsSync(dest) && !options.force) {
+ skipped.push(rel);
+ continue;
+ }
+ mkdirSync(path.dirname(dest), { recursive: true });
+ writeFileSync(dest, content, 'utf8');
+ written.push(rel);
+ }
+
+ const result = { dir: skillDir, skill: bundle.identifier, skipped, written };
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(
+ `${pc.green('✓')} ${pc.bold(bundle.name)} skill → ${pc.dim(path.relative(process.cwd(), skillDir) || skillDir)}`,
+ );
+ console.log(` ${written.length} written${skipped.length ? `, ${skipped.length} skipped` : ''}`);
+ if (skipped.length > 0) console.log(pc.dim(` (skipped existing — pass --force to overwrite)`));
+}
+
+// ── run ──
+
+interface RunCreateOptions {
+ goal?: string;
+ json?: boolean | string;
+ operation?: string;
+ source?: string;
+ title?: string;
+}
+
+async function runCreateAction(options: RunCreateOptions): Promise<void> {
+ const client = await getTrpcClient();
+ const created = await client.verify.createRun.mutate({
+ goal: options.goal,
+ operationId: options.operation,
+ source: options.source as any,
+ title: options.title,
+ });
+ if (options.json !== undefined) {
+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Created run ${pc.bold(created.id)}`);
+}
+
+async function runListAction(options: { json?: boolean | string }): Promise<void> {
+ const client = await getTrpcClient();
+ const runs = await client.verify.listRuns.query();
+ if (options.json !== undefined) {
+ outputJson(runs, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (runs.length === 0) return void console.log('No runs found.');
+ printTable(
+ runs.map((r: any) => [
+ r.id,
+ truncate(r.title || '', 40),
+ r.source,
+ r.status ?? '',
+ r.operationId ? 'agent' : 'standalone',
+ r.createdAt ? timeAgo(r.createdAt) : '',
+ ]),
+ ['ID', 'TITLE', 'SOURCE', 'STATUS', 'KIND', 'CREATED'],
+ );
+}
+
+async function runGetAction(runId: string, options: { json?: boolean | string }): Promise<void> {
+ const client = await getTrpcClient();
+ const item = await client.verify.getRun.query({ verifyRunId: runId });
+ if (options.json !== undefined) {
+ outputJson(item, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (!item) return void console.log('Run not found.');
+ console.log(JSON.stringify(item, null, 2));
+}
+
+async function runDeleteAction(
+ runId: string,
+ options: { json?: boolean | string; yes?: boolean },
+): Promise<void> {
+ const client = await getTrpcClient();
+ if (!options.yes) {
+ const ok = await confirm(
+ `Delete run ${pc.bold(runId)} and all its results, evidence and report? This cannot be undone.`,
+ );
+ if (!ok) return void console.log('Aborted.');
+ }
+ const result = await client.verify.deleteRun.mutate({ verifyRunId: runId });
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Deleted run ${pc.bold(result.id)}`);
+}
+
+// ── result ──
+
+interface ResultIngestOptions {
+ check: string;
+ confidence?: string;
+ evidence?: string;
+ index?: string;
+ json?: boolean | string;
+ run: string;
+ soft?: boolean;
+ status?: string;
+ suggestion?: string;
+ title?: string;
+ verdict: string;
+}
+
+async function resultIngestAction(options: ResultIngestOptions): Promise<void> {
+ const client = await getTrpcClient();
+ const created = await client.verify.ingestResult.mutate({
+ checkItemId: options.check,
+ checkItemIndex: options.index ? Number.parseInt(options.index, 10) : undefined,
+ checkItemTitle: options.title,
+ confidence: options.confidence ? Number.parseFloat(options.confidence) : undefined,
+ required: options.soft ? false : undefined,
+ status: options.status as any,
+ suggestion: options.suggestion,
+ toulmin: options.evidence ? { evidence: options.evidence } : undefined,
+ verdict: options.verdict as any,
+ verifyRunId: options.run,
+ });
+ if (options.json !== undefined) {
+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Result ${pc.bold(created.id)} (${created.verdict})`);
+}
+
+async function resultListAction(options: {
+ json?: boolean | string;
+ operation?: string;
+ run?: string;
+}): Promise<void> {
+ if (!options.run && !options.operation) {
+ log.error('Provide either --run or --operation');
+ process.exit(1);
+ }
+ const client = await getTrpcClient();
+ const results = options.run
+ ? await client.verify.listResultsByRun.query({ verifyRunId: options.run })
+ : await client.verify.listResults.query({ operationId: options.operation! });
+ if (options.json !== undefined) {
+ outputJson(results, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (results.length === 0) return void console.log('No results yet.');
+ printResults(results);
+}
+
+interface SubmitOptions {
+ by?: string;
+ content?: string;
+ desc?: string;
+ file?: string;
+ item: string;
+ json?: boolean | string;
+ operation?: string;
+ run?: string;
+ title?: string;
+ type?: string;
+ verdict?: string;
+}
+
+async function submitAction(options: SubmitOptions): Promise<void> {
+ if (!options.run && !options.operation) {
+ log.error('Provide --run <verifyRunId> or --operation <operationId>');
+ process.exit(1);
+ }
+ const hasEvidence = Boolean(options.file) || Boolean(options.content);
+ if (Boolean(options.file) && Boolean(options.content)) {
+ log.error('Provide at most one of --file or --content');
+ process.exit(1);
+ }
+ if (hasEvidence && !options.type) {
+ log.error('--type is required when attaching evidence');
+ process.exit(1);
+ }
+ if (!hasEvidence && !options.verdict) {
+ log.error('Provide evidence (--file/--content) and/or a --verdict');
+ process.exit(1);
+ }
+ const client = await getTrpcClient();
+ let fileId: string | undefined;
+ let inlineContent = options.content;
+ if (options.file) {
+ inlineContent = inlineTextEvidenceForFile(options.file, options.type!);
+ if (inlineContent === undefined) {
+ const uploaded = await uploadLocalFile(client, options.file);
+ fileId = uploaded.id;
+ }
+ }
+ const evidence = hasEvidence
+ ? [
+ {
+ capturedBy: options.by as any,
+ content: inlineContent,
+ description: options.desc,
+ fileId,
+ type: options.type as any,
+ },
+ ]
+ : undefined;
+ const res = await client.verify.submitCheckEvidence.mutate({
+ checkItemId: options.item,
+ checkItemTitle: options.title,
+ evidence,
+ operationId: options.operation,
+ verdict: options.verdict as any,
+ verifyRunId: options.run,
+ });
+ if (options.json !== undefined) {
+ outputJson(res, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(
+ `${pc.green('✓')} Submitted ${pc.bold(res.checkResult.id)}` +
+ `${res.checkResult.verdict ? ` (${res.checkResult.verdict})` : ''}` +
+ `${res.evidence.length > 0 ? ` +${res.evidence.length} evidence` : ''}`,
+ );
+}
+
+async function decisionAction(resultId: string, decision: Decision): Promise<void> {
+ if (decision !== undefined && !DECISIONS.includes(decision)) {
+ log.error(`decision must be one of: ${DECISIONS.join(', ')}`);
+ process.exit(1);
+ }
+ const client = await getTrpcClient();
+ await client.verify.submitDecision.mutate({ decision, resultId });
+ console.log(`${pc.green('✓')} Recorded ${pc.bold(decision)} on result ${pc.bold(resultId)}`);
+}
+
+// ── evidence ──
+
+interface EvidenceUploadOptions {
+ by?: string;
+ check: string;
+ content?: string;
+ desc?: string;
+ file?: string;
+ json?: boolean | string;
+ type: string;
+}
+
+async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<void> {
+ if (Boolean(options.file) === Boolean(options.content)) {
+ log.error('Provide exactly one of --file or --content');
+ process.exit(1);
+ }
+ const client = await getTrpcClient();
+ let fileId: string | undefined;
+ let inlineContent = options.content;
+ if (options.file) {
+ inlineContent = inlineTextEvidenceForFile(options.file, options.type);
+ if (inlineContent === undefined) {
+ const uploaded = await uploadLocalFile(client, options.file);
+ fileId = uploaded.id;
+ }
+ }
+ const ev = await client.verify.uploadEvidence.mutate({
+ capturedBy: options.by as any,
+ checkResultId: options.check,
+ content: inlineContent,
+ description: options.desc,
+ fileId,
+ type: options.type as any,
+ });
+ if (options.json !== undefined) {
+ outputJson(ev, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Evidence ${pc.bold(ev.id)}${fileId ? ` (file ${fileId})` : ''}`);
+}
+
+async function evidenceListAction(
+ checkResultId: string,
+ options: { json?: boolean | string },
+): Promise<void> {
+ const client = await getTrpcClient();
+ const rows = await client.verify.listEvidence.query({ checkResultId });
+ if (options.json !== undefined) {
+ outputJson(rows, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (rows.length === 0) return void console.log('No evidence.');
+ printTable(
+ rows.map((e: any) => [
+ e.id,
+ e.type,
+ e.capturedBy ?? '',
+ e.fileId ? 'file' : 'inline',
+ truncate(e.description || '', 40),
+ ]),
+ ['ID', 'TYPE', 'BY', 'PAYLOAD', 'DESC'],
+ );
+}
+
+async function evidenceDeleteAction(
+ evidenceId: string,
+ options: { json?: boolean | string },
+): Promise<void> {
+ const client = await getTrpcClient();
+ const result = await client.verify.deleteEvidence.mutate({ id: evidenceId });
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Deleted evidence ${pc.bold(result.id)}`);
+}
+
+// ── report ──
+
+interface ReportUpsertOptions {
+ content?: string;
+ failed?: string;
+ json?: boolean | string;
+ passed?: string;
+ run: string;
+ summary?: string;
+ total?: string;
+ uncertain?: string;
+ verdict?: string;
+}
+
+async function reportUpsertAction(options: ReportUpsertOptions): Promise<void> {
+ const num = (s?: string) => (s === undefined ? undefined : Number.parseInt(s, 10));
+ const client = await getTrpcClient();
+ const created = await client.verify.upsertReport.mutate({
+ content: options.content,
+ failedChecks: num(options.failed),
+ passedChecks: num(options.passed),
+ summary: options.summary,
+ totalChecks: num(options.total),
+ uncertainChecks: num(options.uncertain),
+ verdict: options.verdict as any,
+ verifyRunId: options.run,
+ });
+ if (options.json !== undefined) {
+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Report ${pc.bold(created.id)} (${created.verdict ?? '—'})`);
+}
+
+async function reportGetAction(runId: string, options: { json?: boolean | string }): Promise<void> {
+ const client = await getTrpcClient();
+ const item = await client.verify.getReport.query({ verifyRunId: runId });
+ if (options.json !== undefined) {
+ outputJson(item, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (!item) return void console.log('No report.');
+ console.log(JSON.stringify(item, null, 2));
+}
+
+// ── ingest-report (aggregate convenience over the atomic commands) ──
+
+interface IngestReportOptions {
+ goal?: string;
+ json?: boolean | string;
+ open?: boolean;
+ operation?: string;
+ requirement?: string;
+ source?: string;
+ subject?: string;
+ title?: string;
+}
+
+async function ingestReportAction(reportDir: string, options: IngestReportOptions): Promise<void> {
+ const dir = path.resolve(reportDir);
+ const resultPath = path.join(dir, 'result.json');
+ if (!existsSync(resultPath)) {
+ log.error(`result.json not found in ${dir}`);
+ process.exit(1);
+ }
+
+ let result: any;
+ try {
+ result = JSON.parse(readFileSync(resultPath, 'utf8'));
+ } catch {
+ log.error('result.json is not valid JSON');
+ process.exit(1);
+ }
+
+ const cases: any[] = Array.isArray(result.cases) ? result.cases : [];
+ const summary = result.summary ?? {};
+ const reportMdPath = path.join(dir, 'report.md');
+ const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
+
+ // What kind of delivery this report verified (default: coding).
+ const scenario = scenarioFromResult(result);
+
+ // The scenario's context for the report's scope header. Coding lifts the
+ // well-known top-level fields (branch / commit / surfaces / PR); every
+ // other scenario passes result.json `context` through as its own bag.
+ // `pullRequest` is hoisted: the success output (text and --json) prints
+ // the PR link after the ingest, whatever the scenario resolved to.
+ let context: Record<string, unknown> | undefined;
+ let pullRequest: ReturnType<typeof pullRequestFromResult>;
+ if (scenario === 'coding') {
+ const branch = typeof result.branch === 'string' ? result.branch : undefined;
+ const surfaces = surfacesFromResult(result);
+ // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the
+ // report links to it without the author having to remember the field.
+ pullRequest = pullRequestFromResult(result) ?? pullRequestFromBranch(branch);
+ const contextEntries = Object.entries({
+ branch,
+ commit: typeof result.commit === 'string' ? result.commit : undefined,
+ entry: typeof result.entry === 'string' ? result.entry : undefined,
+ pullRequest,
+ surfaces,
+ testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,
+ }).filter(([, v]) => v !== undefined);
+ context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;
+ } else {
+ context = genericContextFromResult(result);
+ }
+
+ // What the run set out to check, written before it ran. Paired with the
+ // results by `id`, so the report can show a planned item that never ran.
+ const plan = planFromResult(result);
+
+ // Every agent-testing report belongs to an acceptance. Explicit CLI input
+ // wins, then result.json, then the authoring topic echoed by the runtime.
+ let subject = subjectFromResult(result);
+ if (options.subject) {
+ const ref = parseSubjectRef(options.subject);
+ if (!ref) {
+ log.error(
+ `--subject must be one of ${acceptanceSubjectTypes.map((t) => `${t}:<id>`).join(' | ')}`,
+ );
+ process.exit(1);
+ }
+ subject = { ref, requirement: subject?.requirement };
+ } else if (result.subject && !subject) {
+ log.error('result.json `subject` is malformed (expected "type:id" or {type,id})');
+ process.exit(1);
+ } else if (!subject) {
+ const ref = subjectFromEnv();
+ if (ref) subject = { ref };
+ }
+ if (!subject) {
+ log.error(
+ 'Acceptance subject is required: run inside a LobeHub topic or pass --subject task:<id> | topic:<id> | document:<id>',
+ );
+ process.exit(1);
+ }
+ const requirement = options.requirement ?? subject?.requirement;
+
+ const client = await getTrpcClient();
+ const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
+ const title = options.title ?? result.title;
+ // The title is the run's identity in every list surface — an untitled
+ // run renders as a placeholder forever, so say so before it ships.
+ if (!title) {
+ log.warn(
+ 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',
+ );
+ }
+ // The in-app conversation that ran this harness, if any (env-supplied).
+ // Strictly the authoring conversation. `--operation` names the Agent Run
+ // under test and is passed to `createRun` below — a different relation.
+ const origin = originFromEnv();
+ const newRunMetadata = metadataForReport(result, undefined, origin);
+
+ // Every ingest is a new immutable verification snapshot. A repair or
+ // re-verification is represented by another run on the same acceptance.
+ const run = await client.verify.createRun.mutate({
+ context,
+ goal,
+ metadata: newRunMetadata,
+ operationId: options.operation,
+ plan,
+ scenario,
+ source: options.source as any,
+ title,
+ });
+ const runId = run.id;
+
+ // 1c. Chain the session onto its subject's acceptance as the next round
+ // BEFORE the report lands, so the report-time status rollup already
+ // sees the aggregate.
+ const acceptance = await client.acceptance.ensure.mutate({
+ requirement,
+ subjectId: subject.ref.subjectId,
+ subjectType: subject.ref.subjectType,
+ });
+ const acceptanceId = acceptance.id;
+ await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: runId });
+
+ // 2. Ingest each case as a check result + its evidence. `checkItemId` is
+ // the stable key within this immutable run.
+ const seenCheckItemIds = new Set<string>();
+ let evidenceCount = 0;
+ let inlined = 0;
+ for (const [index, c] of cases.entries()) {
+ const checkItemId = String(c.id ?? c.checkItemId ?? `case-${index + 1}`);
+ seenCheckItemIds.add(checkItemId);
+ const verdict = toVerdict(c.result ?? c.status ?? c.verdict);
+ const observation = c.keyObservation ?? c.observation ?? c.note;
+ const checkResult = await client.verify.ingestResult.mutate({
+ checkItemId,
+ checkItemIndex: index,
+ checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
+ required: c.required ?? true,
+ // The case's key observation is recorded as Toulmin evidence; a real
+ // remediation hint (if the report provides one) goes to `suggestion`.
+ // Absent → explicit `null`, so this immutable snapshot records the
+ // absence instead of relying on upsert defaults.
+ suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,
+ toulmin: typeof observation === 'string' ? { evidence: observation } : null,
+ verdict,
+ verifierType: 'agent',
+ verifyRunId: runId,
+ });
+
+ for (const evidenceInput of reportEvidence(c.evidence)) {
+ const rel = evidenceInput.path;
+ const abs = path.isAbsolute(rel) ? rel : path.join(dir, rel);
+ if (!existsSync(abs)) {
+ log.warn(`evidence not found, skipping: ${rel}`);
+ continue;
+ }
+ try {
+ const type = evidenceTypeForFile(abs);
+ const inlineContent = inlineTextEvidenceForFile(abs, type);
+ const file = inlineContent === undefined ? await uploadLocalFile(client, abs) : undefined;
+ await client.verify.uploadEvidence.mutate({
+ capturedBy: 'cli',
+ checkResultId: checkResult.id,
+ // The filename, not the case title — the title already heads the
+ // check card, so reusing it here just triples the same text.
+ content: inlineContent,
+ description: evidenceInput.description ?? path.basename(abs),
+ fileId: file?.id,
+ metadata: evidenceInput.comparison ? { comparison: evidenceInput.comparison } : undefined,
+ type,
+ });
+ evidenceCount += 1;
+ if (inlineContent !== undefined) inlined += 1;
+ } catch (e) {
+ // A stub/unreachable storage bucket (common in local dev) fails the
+ // file PUT — don't abort the whole ingest over one artifact; the
+ // session, results, and report are the deliverable.
+ log.warn(`evidence upload failed, skipping ${path.basename(abs)}: ${String(e)}`);
+ }
+ }
+ }
+
+ // 3. Write the report. `summary` is the overall conclusion (rendered at
+ // the top of the report page); `content` is the full markdown detail.
+ const conclusion =
+ typeof summary.conclusion === 'string'
+ ? summary.conclusion
+ : typeof summary.note === 'string'
+ ? summary.note
+ : undefined;
+ // A 0-100 quality score lands on overallConfidence (0-1); the report page
+ // surfaces it as the `score` stat.
+ const score =
+ typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;
+ await client.verify.upsertReport.mutate({
+ content,
+ failedChecks: summary.failed,
+ overallConfidence: score,
+ passedChecks: summary.passed,
+ summary: conclusion,
+ totalChecks: summary.total ?? cases.length,
+ uncertainChecks: (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,
+ // An explicit summary.verdict wins; otherwise the headline is derived
+ // from the ingested cases (deriveReportVerdict) so no report ships
+ // verdict-less and lists as a permanent "?".
+ verdict: summary.verdict ? toVerdict(summary.verdict) : deriveReportVerdict(cases),
+ verifyRunId: runId,
+ });
+
+ // A case with no matching plan item means the run checked something it
+ // never planned — worth saying out loud, but not a failure. Only
+ // meaningful against a plan that actually names something: with no plan
+ // (or a cleared one) every case is trivially "unplanned", which is noise.
+ const unplanned = plan?.length
+ ? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))
+ : [];
+
+ if (options.json !== undefined) {
+ outputJson(
+ {
+ acceptanceId,
+ cases: cases.length,
+ evidence: evidenceCount,
+ inlined,
+ origin,
+ planItems: plan?.length ?? 0,
+ pullRequest,
+ scenario,
+ subject: subject.ref,
+ unplanned,
+ verifyRunId: runId,
+ },
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ return;
+ }
+
+ console.log(
+ `${pc.green('✓')} Ingested ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` +
+ `${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}`,
+ );
+ if (plan?.length) {
+ const unexecuted = plan.filter((item) => !seenCheckItemIds.has(item.id));
+ console.log(
+ `${pc.bold('plan')}: ${plan.length} item(s)` +
+ `${unexecuted.length > 0 ? pc.yellow(` — ${unexecuted.length} planned but not executed`) : ''}` +
+ `${unplanned.length > 0 ? pc.dim(` — ${unplanned.length} unplanned case(s)`) : ''}`,
+ );
+ }
+ if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);
+ if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);
+ console.log(`${pc.bold('verifyRunId')}: ${runId} ${pc.dim('(immutable snapshot)')}`);
+ console.log(
+ `${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subject.ref.subjectType}:${subject.ref.subjectId})`)}`,
+ );
+ if (options.open) {
+ console.log(`${pc.bold('open')}: /verify/${runId}`);
+ console.log(`${pc.bold('open acceptance')}: /acceptance/${acceptanceId}`);
+ }
+}
+
+// ── Option wiring (shared by both trees) ───────────────────
+//
+// Each `withXxxOptions` applies the flag set to a freshly-created command, so
+// the canonical and deprecated spellings always accept exactly the same flags.
+
+function withInstallOptions(cmd: Command): Command {
+ return cmd
+ .option('--dir <path>', 'Target working directory (default: current dir)')
+ .option('--skill <id>', 'Skill identifier to pull', 'acceptance')
+ .option('--force', 'Overwrite existing skill files')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withRunCreateOptions(cmd: Command): Command {
+ return cmd
+ .option('--source <source>', 'agent | agent-testing', 'agent-testing')
+ .option('--operation <id>', 'Link to an existing Agent Run')
+ .option('--title <title>', 'Session title')
+ .option('--goal <goal>', 'Goal/task being verified')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withRunDeleteOptions(cmd: Command): Command {
+ return cmd
+ .option('-y, --yes', 'Skip the confirmation prompt')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withResultIngestOptions(cmd: Command): Command {
+ return cmd
+ .requiredOption('--run <verifyRunId>', 'Target session id')
+ .requiredOption('--check <checkItemId>', 'Stable check item id within the session')
+ .requiredOption('--verdict <verdict>', 'passed|failed|uncertain')
+ .option('--title <title>', 'Check title')
+ .option('--index <n>', 'Display index')
+ .option('--confidence <n>', '0-1 confidence')
+ .option('--status <status>', 'pending|running|passed|failed|skipped (derived from verdict)')
+ .option('--evidence <text>', 'Key observation (stored as Toulmin evidence)')
+ .option('--suggestion <text>', 'Remediation hint')
+ .option('--soft', 'Non-blocking (required=false); defaults to blocking')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withResultListOptions(cmd: Command): Command {
+ return cmd
+ .option('--run <verifyRunId>', 'List by verification session')
+ .option('--operation <operationId>', 'List by Agent Run')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withSubmitOptions(cmd: Command): Command {
+ return cmd
+ .option('--run <verifyRunId>', 'Target verification session (or use --operation)')
+ .option('--operation <operationId>', 'Resolve the session from an Agent Run operation id')
+ .requiredOption('--item <checkItemId>', 'Plan item id (checkItemId)')
+ .option('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')
+ .option('--file <path>', 'Local file to upload as the evidence artifact')
+ .option('--content <text>', 'Inline text payload (instead of a file)')
+ .option('--verdict <verdict>', 'passed|failed|uncertain')
+ .option('--title <text>', 'Check item title snapshot')
+ .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')
+ .option('--desc <text>', 'Human-readable caption for the evidence')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withEvidenceUploadOptions(cmd: Command): Command {
+ return cmd
+ .requiredOption('--check <checkResultId>', 'Target check result id')
+ .requiredOption('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')
+ .option('--file <path>', 'Local file to upload as the artifact')
+ .option('--content <text>', 'Inline text payload (instead of a file)')
+ .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')
+ .option('--desc <text>', 'Human-readable caption')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withReportUpsertOptions(cmd: Command): Command {
+ return cmd
+ .requiredOption('--run <verifyRunId>', 'Target session id')
+ .option('--verdict <verdict>', 'passed|failed|uncertain')
+ .option('--summary <text>', 'Short summary')
+ .option('--content <markdown>', 'Full markdown body')
+ .option('--total <n>', 'Total checks')
+ .option('--passed <n>', 'Passed checks')
+ .option('--failed <n>', 'Failed checks')
+ .option('--uncertain <n>', 'Uncertain checks')
+ .option('--json [fields]', 'Output JSON');
+}
+
+function withIngestReportOptions(cmd: Command): Command {
+ return cmd
+ .option('--source <source>', 'agent | agent-testing', 'agent-testing')
+ .option('--operation <id>', 'Link the session to an existing Agent Run')
+ .option('--title <title>', 'Override the session title')
+ .option('--goal <goal>', 'The goal/task being verified')
+ .option(
+ '--subject <type:id>',
+ 'Override the required acceptance subject (defaults to the current LOBEHUB_TOPIC_ID)',
+ )
+ .option(
+ '--requirement <text>',
+ 'Acceptance requirement recorded when the aggregate is first created',
+ )
+ .option('--open', 'Print the in-app URL to open the report')
+ .option('--json [fields]', 'Output JSON');
+}
+
+// ── Canonical tree: `lh acceptance install` + `lh acceptance run …` ──
+
+/**
+ * The run-scoped acceptance commands. A run is one immutable round of a
+ * subject's acceptance; its results, evidence, and report are its sub-resources.
+ * Attached to the first-class `lh acceptance` command.
+ */
+export function attachAcceptanceRunCommands(acceptance: Command): void {
+ withInstallOptions(
+ acceptance
+ .command('install')
+ .description(
+ 'Install the acceptance skill skeleton into .agents/skills/acceptance (pulled from the server)',
+ ),
+ ).action(installAction);
+
+ const run = acceptance
+ .command('run')
+ .description('Acceptance rounds (immutable verification snapshots)');
+
+ withIngestReportOptions(
+ run
+ .command('ingest <reportDir>')
+ .description(
+ 'Ingest a local agent-testing report (result.json + report.md + assets) as a new round',
+ ),
+ ).action(ingestReportAction);
+
+ withRunCreateOptions(
+ run.command('create').description('Create a standalone round (verification session)'),
+ ).action(runCreateAction);
+
+ run
+ .command('list')
+ .description('List recent rounds')
+ .option('--json [fields]', 'Output JSON')
+ .action(runListAction);
+
+ run
+ .command('get <runId>')
+ .description('Show a round')
+ .option('--json [fields]', 'Output JSON')
+ .action(runGetAction);
+
+ withRunDeleteOptions(
+ run
+ .command('delete <runId>')
+ .description('Delete a round (cascades its results, evidence and report)'),
+ ).action(runDeleteAction);
+
+ const result = run.command('result').description('Check results within a round');
+ withResultIngestOptions(
+ result
+ .command('ingest')
+ .description('Upsert one check result by (run, checkItemId) from a supplied verdict'),
+ ).action(resultIngestAction);
+ withResultListOptions(
+ result
+ .command('list')
+ .description('List check results — by round (--run) or by Agent Run (--operation)'),
+ ).action(resultListAction);
+ withSubmitOptions(
+ result
+ .command('submit')
+ .description('Submit a check item — upsert its result and attach evidence in one call'),
+ ).action(submitAction);
+ result
+ .command('decision <resultId> <decision>')
+ .description(`Record human feedback on a result (${DECISIONS.join('|')})`)
+ .action(decisionAction);
+
+ const evidence = run.command('evidence').description('Evidence artifacts within a round');
+ withEvidenceUploadOptions(
+ evidence
+ .command('upload')
+ .description('Attach an evidence artifact (file or inline text) to a check result'),
+ ).action(evidenceUploadAction);
+ evidence
+ .command('list <checkResultId>')
+ .description('List evidence for a check result')
+ .option('--json [fields]', 'Output JSON')
+ .action(evidenceListAction);
+ evidence
+ .command('delete <evidenceId>')
+ .description('Delete an evidence artifact')
+ .option('--json [fields]', 'Output JSON')
+ .action(evidenceDeleteAction);
+
+ const report = run.command('report').description('The narrative report of a round');
+ withReportUpsertOptions(
+ report.command('upsert').description('Write (overwrite) the report for a round'),
+ ).action(reportUpsertAction);
+ report
+ .command('get <runId>')
+ .description('Show the report for a round')
+ .option('--json [fields]', 'Output JSON')
+ .action(reportGetAction);
+}
+
+// ── Deprecated aliases: keep the old `lh verify …` spellings working ──
+
+/** Warn once that a `lh verify` spelling has moved under `lh acceptance`. */
+function deprecate(cmd: Command, replacement: string): Command {
+ return cmd.hook('preAction', () => {
+ log.warn(
+ `\`lh verify ${cmd.name()}\` is deprecated — use \`${replacement}\` (removed in a future release)`,
+ );
+ });
+}
+
+/**
+ * The pre-move `lh verify …` command surface, kept as thin aliases that wire the
+ * exact same actions. Scheduled for removal once callers migrate to
+ * `lh acceptance`. Layout mirrors the original flat shape so existing scripts and
+ * tests keep working.
+ */
+export function attachDeprecatedVerifyRunAliases(verify: Command): void {
+ // Both legacy spellings — `verify init` (server pull) and `verify install`
+ // (the old bundled-skill installer) — converge on `acceptance install`.
+ deprecate(
+ withInstallOptions(
+ verify.command('init').description('Deprecated — use `lh acceptance install`'),
+ ),
+ 'lh acceptance install',
+ ).action(installAction);
+
+ deprecate(
+ withInstallOptions(
+ verify.command('install').description('Deprecated — use `lh acceptance install`'),
+ ),
+ 'lh acceptance install',
+ ).action(installAction);
+
+ deprecate(
+ withIngestReportOptions(
+ verify
+ .command('ingest-report <reportDir>')
+ .description('Deprecated — use `lh acceptance run ingest`'),
+ ),
+ 'lh acceptance run ingest',
+ ).action(ingestReportAction);
+
+ const run = verify.command('run').description('Deprecated — use `lh acceptance run`');
+ deprecate(
+ withRunCreateOptions(
+ run.command('create').description('Deprecated — use `lh acceptance run create`'),
+ ),
+ 'lh acceptance run create',
+ ).action(runCreateAction);
+ run
+ .command('list')
+ .description('Deprecated — use `lh acceptance run list`')
+ .option('--json [fields]', 'Output JSON')
+ .hook('preAction', () =>
+ log.warn('`lh verify run list` is deprecated — use `lh acceptance run list`'),
+ )
+ .action(runListAction);
+ run
+ .command('get <runId>')
+ .description('Deprecated — use `lh acceptance run get`')
+ .option('--json [fields]', 'Output JSON')
+ .hook('preAction', () =>
+ log.warn('`lh verify run get` is deprecated — use `lh acceptance run get`'),
+ )
+ .action(runGetAction);
+ deprecate(
+ withRunDeleteOptions(
+ run.command('delete <runId>').description('Deprecated — use `lh acceptance run delete`'),
+ ),
+ 'lh acceptance run delete',
+ ).action(runDeleteAction);
+
+ const result = verify
+ .command('result')
+ .description('Deprecated — use `lh acceptance run result`');
+ deprecate(
+ withResultIngestOptions(
+ result.command('ingest').description('Deprecated — use `lh acceptance run result ingest`'),
+ ),
+ 'lh acceptance run result ingest',
+ ).action(resultIngestAction);
+ deprecate(
+ withResultListOptions(
+ result.command('list').description('Deprecated — use `lh acceptance run result list`'),
+ ),
+ 'lh acceptance run result list',
+ ).action(resultListAction);
+
+ deprecate(
+ withSubmitOptions(
+ verify.command('submit').description('Deprecated — use `lh acceptance run result submit`'),
+ ),
+ 'lh acceptance run result submit',
+ ).action(submitAction);
+
+ verify
+ .command('decision <resultId> <decision>')
+ .description('Deprecated — use `lh acceptance run result decision`')
+ .hook('preAction', () =>
+ log.warn('`lh verify decision` is deprecated — use `lh acceptance run result decision`'),
+ )
+ .action(decisionAction);
+
+ const evidence = verify
+ .command('evidence')
+ .description('Deprecated — use `lh acceptance run evidence`');
+ deprecate(
+ withEvidenceUploadOptions(
+ evidence
+ .command('upload')
+ .description('Deprecated — use `lh acceptance run evidence upload`'),
+ ),
+ 'lh acceptance run evidence upload',
+ ).action(evidenceUploadAction);
+ evidence
+ .command('list <checkResultId>')
+ .description('Deprecated — use `lh acceptance run evidence list`')
+ .option('--json [fields]', 'Output JSON')
+ .hook('preAction', () =>
+ log.warn('`lh verify evidence list` is deprecated — use `lh acceptance run evidence list`'),
+ )
+ .action(evidenceListAction);
+ evidence
+ .command('delete <evidenceId>')
+ .description('Deprecated — use `lh acceptance run evidence delete`')
+ .option('--json [fields]', 'Output JSON')
+ .hook('preAction', () =>
+ log.warn(
+ '`lh verify evidence delete` is deprecated — use `lh acceptance run evidence delete`',
+ ),
+ )
+ .action(evidenceDeleteAction);
+
+ const report = verify
+ .command('report')
+ .description('Deprecated — use `lh acceptance run report`');
+ deprecate(
+ withReportUpsertOptions(
+ report.command('upsert').description('Deprecated — use `lh acceptance run report upsert`'),
+ ),
+ 'lh acceptance run report upsert',
+ ).action(reportUpsertAction);
+ report
+ .command('get <runId>')
+ .description('Deprecated — use `lh acceptance run report get`')
+ .option('--json [fields]', 'Output JSON')
+ .hook('preAction', () =>
+ log.warn('`lh verify report get` is deprecated — use `lh acceptance run report get`'),
+ )
+ .action(reportGetAction);
+}
diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.ts
index 0fcc90e374c..93857701955 100644
--- a/apps/cli/src/commands/verify.test.ts
+++ b/apps/cli/src/commands/verify.test.ts
@@ -18,6 +18,7 @@ import {
subjectFromResult,
surfacesFromResult,
} from './verify';
+import { registerAcceptanceCommands } from './verifyAcceptance';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
@@ -185,10 +186,10 @@ describe('verify init command', () => {
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
mockTrpcClient.verify.getSkillBundle.query.mockReset().mockResolvedValue({
- content: '# Verify SKILL',
+ content: '# Acceptance SKILL',
files: { 'references/plan-format.md': 'plan', 'surfaces/cli.md': 'cli' },
- identifier: 'verify',
- name: 'verify',
+ identifier: 'acceptance',
+ name: 'acceptance',
});
dir = mkdtempSync(path.join(tmpdir(), 'verify-init-'));
});
@@ -205,32 +206,32 @@ describe('verify init command', () => {
await program.parseAsync(['node', 'lh', 'verify', ...args]);
};
- it('writes SKILL.md and resource files into .claude/skills/verify', async () => {
+ it('defaults to the acceptance skill and writes it into .agents/skills/acceptance', async () => {
await run(['init', '--dir', dir]);
expect(mockTrpcClient.verify.getSkillBundle.query).toHaveBeenCalledWith({
- identifier: 'verify',
+ identifier: 'acceptance',
});
- const skillDir = path.join(dir, '.claude', 'skills', 'verify');
- expect(readFileSync(path.join(skillDir, 'SKILL.md'), 'utf8')).toBe('# Verify SKILL');
+ const skillDir = path.join(dir, '.agents', 'skills', 'acceptance');
+ expect(readFileSync(path.join(skillDir, 'SKILL.md'), 'utf8')).toBe('# Acceptance SKILL');
expect(readFileSync(path.join(skillDir, 'references/plan-format.md'), 'utf8')).toBe('plan');
expect(readFileSync(path.join(skillDir, 'surfaces/cli.md'), 'utf8')).toBe('cli');
});
it('skips existing files without --force and overwrites with it', async () => {
- const skillFile = path.join(dir, '.claude', 'skills', 'verify', 'SKILL.md');
+ const skillFile = path.join(dir, '.agents', 'skills', 'acceptance', 'SKILL.md');
await run(['init', '--dir', dir]);
// server now serves updated content
mockTrpcClient.verify.getSkillBundle.query.mockResolvedValue({
content: '# Updated SKILL',
files: {},
- identifier: 'verify',
- name: 'verify',
+ identifier: 'acceptance',
+ name: 'acceptance',
});
await run(['init', '--dir', dir]); // no --force → keep existing
- expect(readFileSync(skillFile, 'utf8')).toBe('# Verify SKILL');
+ expect(readFileSync(skillFile, 'utf8')).toBe('# Acceptance SKILL');
await run(['init', '--dir', dir, '--force']); // --force → overwrite
expect(readFileSync(skillFile, 'utf8')).toBe('# Updated SKILL');
@@ -239,7 +240,7 @@ describe('verify init command', () => {
it('reports the written/skipped counts as JSON', async () => {
await run(['init', '--dir', dir, '--json']);
const out = JSON.parse(consoleSpy.mock.calls.map((c) => String(c[0])).join(''));
- expect(out.skill).toBe('verify');
+ expect(out.skill).toBe('acceptance');
expect(out.written).toContain('SKILL.md');
expect(existsSync(path.join(out.dir, 'SKILL.md'))).toBe(true);
});
@@ -748,3 +749,53 @@ describe('subjectFromEnv — default topic acceptance', () => {
expect(subjectFromEnv()).toBeNull();
});
});
+
+describe('lh acceptance — canonical run tree', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ });
+ afterEach(() => consoleSpy.mockRestore());
+
+ const run = async (args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ // First-class `lh acceptance …` — the run subtree only hangs off this,
+ // never off the deprecated `lh verify acceptance` alias.
+ registerAcceptanceCommands(program);
+ await program.parseAsync(['node', 'lh', 'acceptance', ...args]);
+ };
+
+ it('routes `acceptance run delete` to the same deleteRun mutation', async () => {
+ mockTrpcClient.verify.deleteRun.mutate.mockReset().mockResolvedValue({ id: 'run_1' });
+ await run(['run', 'delete', 'run_1', '--yes']);
+ expect(mockTrpcClient.verify.deleteRun.mutate).toHaveBeenCalledWith({ verifyRunId: 'run_1' });
+ });
+
+ it('exposes `acceptance install` defaulting to the acceptance skill', async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'acceptance-install-'));
+ mockTrpcClient.verify.getSkillBundle.query.mockReset().mockResolvedValue({
+ content: '# Acceptance SKILL',
+ files: {},
+ identifier: 'acceptance',
+ name: 'acceptance',
+ });
+ await run(['install', '--dir', dir]);
+ expect(mockTrpcClient.verify.getSkillBundle.query).toHaveBeenCalledWith({
+ identifier: 'acceptance',
+ });
+ expect(existsSync(path.join(dir, '.agents', 'skills', 'acceptance', 'SKILL.md'))).toBe(true);
+ rmSync(dir, { force: true, recursive: true });
+ });
+
+ it('does NOT attach the run subtree to the deprecated `verify acceptance` alias', async () => {
+ const program = new Command();
+ program.exitOverride();
+ registerAcceptanceCommands(program, { deprecated: true });
+ const acceptance = program.commands.find((c) => c.name() === 'acceptance');
+ const hasRun = acceptance?.commands.some((c) => c.name() === 'run');
+ expect(hasRun).toBe(false);
+ });
+});
diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.ts
index 29f18ee8521..6a2d74e4d37 100644
--- a/apps/cli/src/commands/verify.ts
+++ b/apps/cli/src/commands/verify.ts
@@ -1,593 +1,39 @@
-import { execFileSync } from 'node:child_process';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
-import path from 'node:path';
-
-import type {
- AcceptanceSubjectType,
- VerifyRunOrigin,
- VerifyRunScenario,
- VerifySurface,
-} from '@lobechat/const/verify';
-import {
- acceptanceSubjectTypes,
- normalizeVerifySurface,
- verifyEvidenceTypes,
- verifyRunScenarios,
- verifySurfaces,
-} from '@lobechat/const/verify';
import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
-import { uploadLocalFile } from '../utils/uploadLocalFile';
+import { attachDeprecatedVerifyRunAliases } from './acceptanceRun';
import { registerAcceptanceCommands } from './verifyAcceptance';
-import { registerVerifyInstallCommand } from './verifyInstall';
-
-// ── Helpers ────────────────────────────────────────────────
-
-type VerifierType = 'agent' | 'llm' | 'program';
-type OnFail = 'auto_repair' | 'manual';
-type Decision = 'accepted' | 'overridden' | 'rejected';
-
-const VERIFIER_TYPES: VerifierType[] = ['program', 'agent', 'llm'];
-const ON_FAIL: OnFail[] = ['manual', 'auto_repair'];
-const DECISIONS: Decision[] = ['accepted', 'rejected', 'overridden'];
-/** The evidence media a plan item may require — the same closed set the executor gates on. */
-const EVIDENCE_TYPES = verifyEvidenceTypes;
-
-function parseConfig(raw?: string): Record<string, unknown> | undefined {
- if (!raw) return undefined;
- try {
- return JSON.parse(raw);
- } catch {
- log.error('--config must be valid JSON');
- process.exit(1);
- }
-}
-
-function assertEnum<T extends string>(value: T | undefined, allowed: T[], flag: string): void {
- if (value !== undefined && !allowed.includes(value)) {
- log.error(`${flag} must be one of: ${allowed.join(', ')}`);
- process.exit(1);
- }
-}
-
-type Verdict = 'failed' | 'passed' | 'uncertain';
-type EvidenceType = 'dom_snapshot' | 'gif' | 'screenshot' | 'text' | 'transcript' | 'video';
-
-const INLINE_TEXT_EVIDENCE_LIMIT = 5000;
-const INLINE_TEXT_EVIDENCE_TYPES = new Set<EvidenceType>(['dom_snapshot', 'text', 'transcript']);
-
-/** Map a free-form case/summary result token onto the verify verdict vocabulary. */
-function toVerdict(raw: unknown): Verdict {
- const s = String(raw ?? '').toLowerCase();
- if (['pass', 'passed', 'ok', 'success'].includes(s)) return 'passed';
- if (['fail', 'failed', 'error'].includes(s)) return 'failed';
- return 'uncertain'; // partial / blocked / skipped / pending / unknown
-}
-
-/**
- * The report's headline verdict when the author didn't set `summary.verdict`:
- * derived from the ingested cases, so a report can never ship verdict-less and
- * render as a permanent "?" in every list surface.
- */
-export function deriveReportVerdict(cases: unknown[]): Verdict | undefined {
- const verdicts = cases.map((c) => toVerdict((c as any)?.result ?? (c as any)?.verdict));
- if (verdicts.length === 0) return undefined;
- if (verdicts.includes('failed')) return 'failed';
- if (verdicts.includes('uncertain')) return 'uncertain';
- return 'passed';
-}
-
-/** Pick an evidence medium from a file extension. */
-function evidenceTypeForFile(file: string): EvidenceType {
- const ext = path.extname(file).toLowerCase().slice(1);
- if (ext === 'gif') return 'gif';
- if (['png', 'jpg', 'jpeg', 'webp', 'svg', 'bmp'].includes(ext)) return 'screenshot';
- if (['mp4', 'webm', 'mov', 'm4v'].includes(ext)) return 'video';
- if (['html', 'htm'].includes(ext)) return 'dom_snapshot';
- return 'text';
-}
-
-function inlineTextEvidenceForFile(file: string, type: EvidenceType | string): string | undefined {
- if (!INLINE_TEXT_EVIDENCE_TYPES.has(type as EvidenceType)) return undefined;
-
- try {
- const buffer = readFileSync(file);
- if (buffer.includes(0)) return undefined;
-
- const content = buffer.toString('utf8');
- return content.length > 0 && content.length < INLINE_TEXT_EVIDENCE_LIMIT ? content : undefined;
- } catch {
- return undefined;
- }
-}
-
-/** Normalize a case's `evidence` field (string | string[] | {path}[]) to path strings. */
-interface ReportEvidenceInput {
- comparison?: {
- id: string;
- label?: string;
- layout?: 'horizontal' | 'vertical';
- role: 'after' | 'before';
- };
- description?: string;
- path: string;
-}
-
-export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {
- if (!evidence) return [];
- const arr = Array.isArray(evidence) ? evidence : [evidence];
- return arr
- .map((e): ReportEvidenceInput | null => {
- if (typeof e === 'string') return { path: e };
- const value = objectValue(e);
- const evidencePath = value && firstString(value.path, value.file);
- if (!evidencePath) return null;
- const comparison = objectValue(value.comparison);
- const role = comparison?.role;
- const id = firstString(comparison?.id);
- // The report viewer pairs on `id` and drops any comparison lacking one, so
- // an id-less half could never render side by side. Warn rather than upload
- // a comparison that is silently downgraded to an ordinary image.
- if (comparison && !(id && (role === 'before' || role === 'after'))) {
- log.warn(
- `evidence ${evidencePath}: comparison needs both a string "id" and role "before"/"after" — ignoring it`,
- );
- }
- const layout = comparison?.layout === 'vertical' ? 'vertical' : undefined;
- return {
- comparison:
- id && (role === 'before' || role === 'after')
- ? { id, label: firstString(comparison?.label), layout, role }
- : undefined,
- description: firstString(value.description, value.desc),
- path: evidencePath,
- };
- })
- .filter((item): item is ReportEvidenceInput => item !== null);
-}
-
-function firstString(...values: unknown[]): string | undefined {
- return values.find((v): v is string => typeof v === 'string' && v.length > 0);
-}
-
-function firstStringOrNumber(...values: unknown[]): string | number | undefined {
- return values.find(
- (v): v is string | number => (typeof v === 'string' && v.length > 0) || typeof v === 'number',
- );
-}
-
-function objectValue(value: unknown): Record<string, unknown> | undefined {
- return value && typeof value === 'object' && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : undefined;
-}
-
-function safeWebUrl(value: string | undefined): string | undefined {
- if (!value) return undefined;
-
- try {
- const url = new URL(value);
- return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined;
- } catch {
- return undefined;
- }
-}
-
-/** Normalize common agent-testing PR shapes into the verify coding scope. */
-function pullRequestFromResult(result: Record<string, unknown>) {
- const pr = objectValue(result.pullRequest) ?? objectValue(result.pr);
- const url = safeWebUrl(
- firstString(
- pr?.url,
- pr?.htmlUrl,
- pr?.html_url,
- result.pullRequestUrl,
- result.prUrl,
- typeof result.pr === 'string' ? result.pr : undefined,
- ),
- );
- const number = firstStringOrNumber(pr?.number, result.pullRequestNumber, result.prNumber);
- const title = firstString(pr?.title, result.pullRequestTitle, result.prTitle);
- const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);
-
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
-}
-
-/**
- * The PR for a branch, asked of `gh`. A report almost always verifies a branch
- * that already has one, but the author has to remember to write it down — and
- * mostly doesn't, so the report loses its single most useful outbound link.
- * Best-effort by design: no `gh`, not a repo, not authenticated, or no PR for
- * the branch all mean "no PR", never a failed publish.
- */
-function pullRequestFromBranch(branch: string | undefined) {
- if (!branch) return undefined;
-
- try {
- const raw = execFileSync(
- 'gh',
- ['pr', 'view', branch, '--json', 'number,title,url'],
- // `gh` writes its "no pull requests found" diagnostics to stderr; keep them
- // off the CLI's own output.
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 },
- );
- const parsed = objectValue(JSON.parse(raw));
- const url = safeWebUrl(firstString(parsed?.url));
- const number = firstStringOrNumber(parsed?.number);
- const title = firstString(parsed?.title);
- const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);
-
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
- } catch {
- return undefined;
- }
-}
-
-/**
- * The surfaces the report says it exercised, as canonical values.
- *
- * Strict on purpose: an unrecognized surface is a hard error, not a silently
- * dropped value. Free-form surfaces are how the field rotted — prose, runtime
- * modes ("packaged build") and test kinds ("unit", "type-check") all ended up in
- * it, and none of them render. Failing here puts the fix in the author's hands
- * while they still have the context to make it.
- */
-export function surfacesFromResult(result: Record<string, unknown>): VerifySurface[] | undefined {
- if (!Array.isArray(result.surfaces)) return undefined;
-
- const raw = result.surfaces.filter((s: unknown): s is string => typeof s === 'string');
- const canonical: VerifySurface[] = [];
- const rejected: string[] = [];
-
- for (const value of raw) {
- const surface = normalizeVerifySurface(value);
- if (surface) {
- if (!canonical.includes(surface)) canonical.push(surface);
- } else {
- rejected.push(value);
- }
- }
-
- if (rejected.length > 0) {
- log.error(
- `result.json "surfaces" must name the product surface a check ran on, one of: ${verifySurfaces.join(', ')}`,
- );
- log.error(` rejected: ${rejected.map((v) => JSON.stringify(v)).join(', ')}`);
- log.error(
- ' Runtime detail ("packaged build", "CDP dev instance") belongs on a plan item\'s "method"; a test kind ("unit", "backend") is not a surface — a backend change verified through the CLI has surface "cli".',
- );
- process.exit(1);
- }
-
- return canonical.length > 0 ? canonical : undefined;
-}
-
-/**
- * What kind of delivery the report verified. Defaults to `coding` — the
- * agent-testing harness's home turf — and rejects an unknown value rather than
- * storing a scenario nothing renders (mirrors the strict surface policy: the
- * author still has the context to fix it).
- */
-export function scenarioFromResult(result: Record<string, unknown>): VerifyRunScenario {
- const raw = result.scenario;
- if (raw === undefined) return 'coding';
- if (typeof raw === 'string' && (verifyRunScenarios as readonly string[]).includes(raw)) {
- return raw as VerifyRunScenario;
- }
-
- log.error(
- `result.json "scenario" must be one of: ${verifyRunScenarios.join(', ')} — rejected: ${JSON.stringify(raw)}`,
- );
- process.exit(1);
-}
-
-/**
- * A non-coding scenario's scope, passed through from result.json `context` as
- * the scenario's own bag (the server stores it as-is; known shapes live in
- * `@lobechat/types`). Top-level `entry` / `createdAt` are lifted as defaults so
- * every scenario gets the shared provenance fields for free; explicit `context`
- * keys win.
- */
-export function genericContextFromResult(
- result: Record<string, unknown>,
-): Record<string, unknown> | undefined {
- const bag = objectValue(result.context) ?? {};
- const entries = Object.entries({
- entry: firstString(result.entry),
- testedAt: firstString(result.createdAt),
- ...bag,
- }).filter(([, v]) => v !== undefined);
-
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
-}
-
-/** Reject an out-of-vocabulary plan value rather than storing a word nothing reads. */
-function assertPlanEnum<T extends string>(
- value: string,
- allowed: readonly T[],
- field: string,
- itemId: string,
-): T {
- if ((allowed as readonly string[]).includes(value)) return value as T;
-
- log.error(`result.json plan item "${itemId}": "${field}" must be one of: ${allowed.join(', ')}`);
- log.error(` rejected: ${JSON.stringify(value)}`);
- process.exit(1);
-}
-
-/**
- * The checks the run set out to make, as frozen plan items.
- *
- * Two of the fields are a closed vocabulary, not free text, because the pipeline
- * actually acts on them:
- *
- * - `verifier` → {@link VerifyCheckItem.verifierType} (`program | agent | llm`):
- * how the item is judged. Defaults to `agent`, but a command-asserted check is
- * `program` and mislabelling it hides what actually produced the verdict.
- * - `requiredEvidence` → `verifierConfig.requiredEvidence`
- * ({@link RequiredEvidenceSpec}, medium from {@link verifyEvidenceTypes}):
- * the artifact the item MUST produce. The executor's coverage gate fails an
- * item whose required medium is missing, so this is enforcement, not a label —
- * an unknown medium would silently gate on nothing.
- *
- * `method` / `expected` stay prose: they are the author's intent in words, which
- * no enum can carry. Everything else the frozen {@link VerifyCheckItem} needs is
- * filled in here, so an author writes only `{ id, title }` plus what they mean.
- *
- * Returns `undefined` when the report declares no `plan` field. A `plan` that is
- * present but empty returns `[]`, recording an explicitly empty plan in this
- * immutable snapshot.
- */
-export function planFromResult(result: Record<string, unknown>) {
- if (!Array.isArray(result.plan)) return undefined;
-
- const items = result.plan.flatMap((entry: unknown, index: number) => {
- const item = objectValue(entry);
- const title = firstString(item?.title, item?.name);
- // An item with no title names no check — it can't be rendered or paired.
- if (!item || !title) return [];
-
- const id = String(item.id ?? `case-${index + 1}`);
- const method = firstString(item.method, item.how);
- const expected = firstString(item.expected, item.expectation);
-
- const verifierRaw = firstString(item.verifier, item.verifierType);
- const verifierType = verifierRaw
- ? assertPlanEnum(verifierRaw, VERIFIER_TYPES, 'verifier', id)
- : ('agent' as const);
-
- const requiredEvidence = Array.isArray(item.requiredEvidence)
- ? item.requiredEvidence.flatMap((spec: unknown) => {
- // Accept the bare medium (`"screenshot"`) or the full spec object.
- const record = objectValue(spec);
- const raw = typeof spec === 'string' ? spec : firstString(record?.type);
- if (!raw) return [];
-
- return [
- {
- hint: firstString(record?.hint),
- type: assertPlanEnum(raw, EVIDENCE_TYPES, 'requiredEvidence', id),
- },
- ];
- })
- : [];
-
- // Per-item surface: the acceptance union groups checks by it. Normalized to
- // the closed set (electron → desktop); an unknown value is dropped loudly
- // rather than stored as a mystery chip.
- const surfaceRaw = firstString(item.surface);
- const surface = surfaceRaw ? normalizeVerifySurface(surfaceRaw) : null;
- if (surfaceRaw && !surface) {
- log.warn(
- `plan item "${id}": surface "${surfaceRaw}" names no product surface (expected ${verifySurfaces.join('/')}) — dropping it`,
- );
- }
-
- // The acceptance union groups by category and folds superseded ids into
- // the new item's iteration timeline — both authored by the harness.
- const category = firstString(item.category, item.group);
- const supersedes = Array.isArray(item.supersedes)
- ? item.supersedes.filter((value: unknown): value is string => typeof value === 'string')
- : [];
-
- return [
- {
- ...(category === undefined ? {} : { category }),
- description: firstString(item.description),
- id,
- index,
- onFail: 'manual' as const,
- required: typeof item.required === 'boolean' ? item.required : true,
- ...(supersedes.length > 0 ? { supersedes } : {}),
- title,
- verifierConfig: {
- ...(method === undefined ? {} : { method }),
- ...(expected === undefined ? {} : { expected }),
- ...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),
- ...(surface ? { surface } : {}),
- },
- verifierType,
- },
- ];
- });
-
- // `[]` is meaningful — it clears a stale plan. Only an absent `plan` field
- // (handled above) means "don't touch what's stored".
- return items;
-}
-
-/**
- * The LobeHub conversation this harness is running inside, read off the env the
- * agent runtime echoes into the child process. Lets a report published from an
- * in-app agent link back to the session that produced it with no flags to
- * remember. Absent (a plain terminal) → no origin, which is not an error.
- *
- * Reads the env and ONLY the env. `--operation` is the opposite relation — the
- * Agent Run this session *verifies* — so letting it fall through to here would
- * attribute the report to the run under test instead of the run that wrote it,
- * corrupting the very provenance this records. The two ids are independent and
- * may legitimately differ in the same publish.
- */
-export function originFromEnv(): VerifyRunOrigin | undefined {
- const origin: VerifyRunOrigin = {
- agentId: firstString(process.env.LOBEHUB_AGENT_ID),
- operationId: firstString(process.env.LOBEHUB_OPERATION_ID),
- topicId: firstString(process.env.LOBEHUB_TOPIC_ID),
- };
-
- return Object.values(origin).some(Boolean) ? origin : undefined;
-}
-
-function metadataForReport(
- result: Record<string, unknown>,
- existingMetadata?: unknown,
- origin?: VerifyRunOrigin,
-): Record<string, unknown> | undefined {
- const hasInteractionCost = Object.prototype.hasOwnProperty.call(result, 'interactionCost');
- // Nothing to write is not the same as writing an empty metadata bag.
- if (!hasInteractionCost && !origin) return undefined;
-
- const metadata = { ...objectValue(existingMetadata) };
-
- if (hasInteractionCost) {
- const interactionCost = objectValue(result.interactionCost);
-
- if (interactionCost) {
- metadata.interactionCost = interactionCost;
- } else {
- delete metadata.interactionCost;
- }
- }
-
- if (origin) metadata.origin = origin;
-
- return metadata;
-}
-
-/** A parsed acceptance subject reference (`task:<id>` / `topic:<id>` / `document:<id>`). */
-export interface AcceptanceSubjectRef {
- subjectId: string;
- subjectType: AcceptanceSubjectType;
-}
-
-/**
- * Parse a `type:id` subject reference. Returns null on anything malformed —
- * callers decide whether that is an error (an explicit `--subject`) or a
- * silently absent field (result.json).
- */
-export function parseSubjectRef(raw: unknown): AcceptanceSubjectRef | null {
- if (typeof raw !== 'string') return null;
- const idx = raw.indexOf(':');
- if (idx <= 0) return null;
- const type = raw.slice(0, idx).trim().toLowerCase();
- const id = raw.slice(idx + 1).trim();
- if (!id || !(acceptanceSubjectTypes as readonly string[]).includes(type)) return null;
- return { subjectId: id, subjectType: type as AcceptanceSubjectType };
-}
-
-/**
- * The acceptance subject a report attributes itself to, from result.json's
- * `subject` field — either `"task:<id>"` or `{ type, id, requirement? }`. An
- * explicit `--subject` flag wins over this.
- */
-export function subjectFromResult(result: Record<string, unknown>): {
- ref: AcceptanceSubjectRef;
- requirement?: string;
-} | null {
- const raw = result.subject;
- if (typeof raw === 'string') {
- const ref = parseSubjectRef(raw);
- return ref ? { ref } : null;
- }
- const value = objectValue(raw);
- if (!value) return null;
- const ref = parseSubjectRef(`${firstString(value.type) ?? ''}:${firstString(value.id) ?? ''}`);
- return ref ? { ref, requirement: firstString(value.requirement) } : null;
-}
-
-/** Default acceptance subject for a report authored inside a LobeHub topic. */
-export function subjectFromEnv(): AcceptanceSubjectRef | null {
- const topicId = firstString(process.env.LOBEHUB_TOPIC_ID);
- return topicId ? { subjectId: topicId, subjectType: 'topic' } : null;
-}
+import {
+ assertEnum,
+ ON_FAIL,
+ type OnFail,
+ parseConfig,
+ printResults,
+ VERIFIER_TYPES,
+ type VerifierType,
+} from './verifyHelpers';
+
+// Re-export the report/ingest helpers so existing importers keep resolving them
+// from './verify' (tests, and callers predating the verifyHelpers split).
+export * from './verifyHelpers';
// ── Command Registration ───────────────────────────────────
export function registerVerifyCommand(program: Command) {
const verify = program
.command('verify')
- .description('Manage the Agent Run delivery checker (criteria, rubrics, plans, results)');
+ .description('Agent Run verification machinery — criteria, rubrics, and per-run check plans');
- // `verify acceptance …` — subject-level acceptance aggregates.
- // Legacy spelling — the canonical group is the first-class `lh acceptance`.
+ // `verify acceptance …` — legacy alias; the canonical group is the first-class
+ // `lh acceptance`.
registerAcceptanceCommands(verify, { deprecated: true });
- // `verify install` — install the bundled agent-testing skill from this CLI
- // package into the consumer repo. Distinct from `verify init` below, which
- // pulls a named skill bundle live from the server.
- registerVerifyInstallCommand(verify);
-
- // ════════════ init (materialize the portable verify skill) ════════════
- verify
- .command('init')
- .description('Write the portable verify skill into a working dir (.claude/skills/verify)')
- .option('--dir <path>', 'Target working directory (default: current dir)')
- .option('--skill <id>', 'Skill identifier to pull', 'verify')
- .option('--force', 'Overwrite existing skill files')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- dir?: string;
- force?: boolean;
- json?: boolean | string;
- skill: string;
- }) => {
- const client = await getTrpcClient();
- // Pulled live from the server's deployed builtin-skills — always the latest.
- const bundle = await client.verify.getSkillBundle.query({ identifier: options.skill });
-
- const baseDir = options.dir ? path.resolve(options.dir) : process.cwd();
- const skillDir = path.join(baseDir, '.claude', 'skills', bundle.identifier);
-
- // path → content for SKILL.md plus every resource file.
- const entries: [string, string][] = [
- ['SKILL.md', bundle.content],
- ...Object.entries(bundle.files),
- ];
-
- const written: string[] = [];
- const skipped: string[] = [];
- for (const [rel, content] of entries) {
- const dest = path.join(skillDir, rel);
- if (existsSync(dest) && !options.force) {
- skipped.push(rel);
- continue;
- }
- mkdirSync(path.dirname(dest), { recursive: true });
- writeFileSync(dest, content, 'utf8');
- written.push(rel);
- }
-
- const result = { dir: skillDir, skill: bundle.identifier, skipped, written };
- if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(
- `${pc.green('✓')} ${pc.bold(bundle.name)} skill → ${pc.dim(path.relative(process.cwd(), skillDir) || skillDir)}`,
- );
- console.log(
- ` ${written.length} written${skipped.length ? `, ${skipped.length} skipped` : ''}`,
- );
- if (skipped.length > 0)
- console.log(pc.dim(` (skipped existing — pass --force to overwrite)`));
- },
- );
-
+ // Deprecated `lh verify …` spellings for the run/result/evidence/report/install
+ // commands now living under `lh acceptance`. Kept for a few releases.
+ attachDeprecatedVerifyRunAliases(verify);
// ════════════ criteria ════════════
const criterion = verify.command('criterion').description('Reusable pass/fail standards');
@@ -954,746 +400,4 @@ export function registerVerifyCommand(program: Command) {
printResults(results);
},
);
-
- // ════════════ run (verification session entity) ════════════
- const run = verify.command('run').description('Verification sessions (verify_runs)');
-
- run
- .command('create')
- .description('Create a standalone verification session')
- .option('--source <source>', 'agent | agent-testing', 'agent-testing')
- .option('--operation <id>', 'Link to an existing Agent Run')
- .option('--title <title>', 'Session title')
- .option('--goal <goal>', 'Goal/task being verified')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- goal?: string;
- json?: boolean | string;
- operation?: string;
- source?: string;
- title?: string;
- }) => {
- const client = await getTrpcClient();
- const created = await client.verify.createRun.mutate({
- goal: options.goal,
- operationId: options.operation,
- source: options.source as any,
- title: options.title,
- });
- if (options.json !== undefined) {
- outputJson(created, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(`${pc.green('✓')} Created run ${pc.bold(created.id)}`);
- },
- );
-
- run
- .command('list')
- .description('List recent verification sessions')
- .option('--json [fields]', 'Output JSON')
- .action(async (options: { json?: boolean | string }) => {
- const client = await getTrpcClient();
- const runs = await client.verify.listRuns.query();
- if (options.json !== undefined) {
- outputJson(runs, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- if (runs.length === 0) return void console.log('No runs found.');
- printTable(
- runs.map((r: any) => [
- r.id,
- truncate(r.title || '', 40),
- r.source,
- r.status ?? '',
- r.operationId ? 'agent' : 'standalone',
- r.createdAt ? timeAgo(r.createdAt) : '',
- ]),
- ['ID', 'TITLE', 'SOURCE', 'STATUS', 'KIND', 'CREATED'],
- );
- });
-
- run
- .command('get <runId>')
- .description('Show a verification session')
- .option('--json [fields]', 'Output JSON')
- .action(async (runId: string, options: { json?: boolean | string }) => {
- const client = await getTrpcClient();
- const item = await client.verify.getRun.query({ verifyRunId: runId });
- if (options.json !== undefined) {
- outputJson(item, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- if (!item) return void console.log('Run not found.');
- console.log(JSON.stringify(item, null, 2));
- });
-
- run
- .command('delete <runId>')
- .description('Delete a verification session (cascades its results, evidence and report)')
- .option('-y, --yes', 'Skip the confirmation prompt')
- .option('--json [fields]', 'Output JSON')
- .action(async (runId: string, options: { json?: boolean | string; yes?: boolean }) => {
- const client = await getTrpcClient();
- if (!options.yes) {
- const ok = await confirm(
- `Delete run ${pc.bold(runId)} and all its results, evidence and report? This cannot be undone.`,
- );
- if (!ok) return void console.log('Aborted.');
- }
- const result = await client.verify.deleteRun.mutate({ verifyRunId: runId });
- if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(`${pc.green('✓')} Deleted run ${pc.bold(result.id)}`);
- });
-
- // ════════════ result (check result entity) ════════════
- const result = verify.command('result').description('Check results (verify_check_results)');
-
- result
- .command('ingest')
- .description('Upsert one check result by (run, checkItemId) from a supplied verdict')
- .requiredOption('--run <verifyRunId>', 'Target session id')
- .requiredOption('--check <checkItemId>', 'Stable check item id within the session')
- .requiredOption('--verdict <verdict>', 'passed|failed|uncertain')
- .option('--title <title>', 'Check title')
- .option('--index <n>', 'Display index')
- .option('--confidence <n>', '0-1 confidence')
- .option('--status <status>', 'pending|running|passed|failed|skipped (derived from verdict)')
- .option('--evidence <text>', 'Key observation (stored as Toulmin evidence)')
- .option('--suggestion <text>', 'Remediation hint')
- .option('--soft', 'Non-blocking (required=false); defaults to blocking')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- check: string;
- confidence?: string;
- evidence?: string;
- index?: string;
- json?: boolean | string;
- run: string;
- soft?: boolean;
- status?: string;
- suggestion?: string;
- title?: string;
- verdict: string;
- }) => {
- const client = await getTrpcClient();
- const created = await client.verify.ingestResult.mutate({
- checkItemId: options.check,
- checkItemIndex: options.index ? Number.parseInt(options.index, 10) : undefined,
- checkItemTitle: options.title,
- confidence: options.confidence ? Number.parseFloat(options.confidence) : undefined,
- required: options.soft ? false : undefined,
- status: options.status as any,
- suggestion: options.suggestion,
- toulmin: options.evidence ? { evidence: options.evidence } : undefined,
- verdict: options.verdict as any,
- verifyRunId: options.run,
- });
- if (options.json !== undefined) {
- outputJson(created, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(`${pc.green('✓')} Result ${pc.bold(created.id)} (${created.verdict})`);
- },
- );
-
- result
- .command('list')
- .description('List check results — by session (--run) or by Agent Run (--operation)')
- .option('--run <verifyRunId>', 'List by verification session')
- .option('--operation <operationId>', 'List by Agent Run')
- .option('--json [fields]', 'Output JSON')
- .action(async (options: { json?: boolean | string; operation?: string; run?: string }) => {
- if (!options.run && !options.operation) {
- log.error('Provide either --run or --operation');
- process.exit(1);
- }
- const client = await getTrpcClient();
- const results = options.run
- ? await client.verify.listResultsByRun.query({ verifyRunId: options.run })
- : await client.verify.listResults.query({ operationId: options.operation! });
- if (options.json !== undefined) {
- outputJson(results, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- if (results.length === 0) return void console.log('No results yet.');
- printResults(results);
- });
-
- // ════════════ submit (builder self-evidence: result + evidence in one call) ════════════
- verify
- .command('submit')
- .description('Submit a check item — upsert its result and attach evidence in one call')
- .option('--run <verifyRunId>', 'Target verification session (or use --operation)')
- .option('--operation <operationId>', 'Resolve the session from an Agent Run operation id')
- .requiredOption('--item <checkItemId>', 'Plan item id (checkItemId)')
- .option('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')
- .option('--file <path>', 'Local file to upload as the evidence artifact')
- .option('--content <text>', 'Inline text payload (instead of a file)')
- .option('--verdict <verdict>', 'passed|failed|uncertain')
- .option('--title <text>', 'Check item title snapshot')
- .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')
- .option('--desc <text>', 'Human-readable caption for the evidence')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- by?: string;
- content?: string;
- desc?: string;
- file?: string;
- item: string;
- json?: boolean | string;
- operation?: string;
- run?: string;
- title?: string;
- type?: string;
- verdict?: string;
- }) => {
- if (!options.run && !options.operation) {
- log.error('Provide --run <verifyRunId> or --operation <operationId>');
- process.exit(1);
- }
- const hasEvidence = Boolean(options.file) || Boolean(options.content);
- if (Boolean(options.file) && Boolean(options.content)) {
- log.error('Provide at most one of --file or --content');
- process.exit(1);
- }
- if (hasEvidence && !options.type) {
- log.error('--type is required when attaching evidence');
- process.exit(1);
- }
- if (!hasEvidence && !options.verdict) {
- log.error('Provide evidence (--file/--content) and/or a --verdict');
- process.exit(1);
- }
- const client = await getTrpcClient();
- let fileId: string | undefined;
- let inlineContent = options.content;
- if (options.file) {
- inlineContent = inlineTextEvidenceForFile(options.file, options.type!);
- if (inlineContent === undefined) {
- const uploaded = await uploadLocalFile(client, options.file);
- fileId = uploaded.id;
- }
- }
- const evidence = hasEvidence
- ? [
- {
- capturedBy: options.by as any,
- content: inlineContent,
- description: options.desc,
- fileId,
- type: options.type as any,
- },
- ]
- : undefined;
- const res = await client.verify.submitCheckEvidence.mutate({
- checkItemId: options.item,
- checkItemTitle: options.title,
- evidence,
- operationId: options.operation,
- verdict: options.verdict as any,
- verifyRunId: options.run,
- });
- if (options.json !== undefined) {
- outputJson(res, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(
- `${pc.green('✓')} Submitted ${pc.bold(res.checkResult.id)}` +
- `${res.checkResult.verdict ? ` (${res.checkResult.verdict})` : ''}` +
- `${res.evidence.length > 0 ? ` +${res.evidence.length} evidence` : ''}`,
- );
- },
- );
-
- // ════════════ evidence (artifact entity) ════════════
- const evidence = verify.command('evidence').description('Evidence artifacts (verify_evidence)');
-
- evidence
- .command('upload')
- .description('Attach an evidence artifact (file or inline text) to a check result')
- .requiredOption('--check <checkResultId>', 'Target check result id')
- .requiredOption('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')
- .option('--file <path>', 'Local file to upload as the artifact')
- .option('--content <text>', 'Inline text payload (instead of a file)')
- .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')
- .option('--desc <text>', 'Human-readable caption')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- by?: string;
- check: string;
- content?: string;
- desc?: string;
- file?: string;
- json?: boolean | string;
- type: string;
- }) => {
- if (Boolean(options.file) === Boolean(options.content)) {
- log.error('Provide exactly one of --file or --content');
- process.exit(1);
- }
- const client = await getTrpcClient();
- let fileId: string | undefined;
- let inlineContent = options.content;
- if (options.file) {
- inlineContent = inlineTextEvidenceForFile(options.file, options.type);
- if (inlineContent === undefined) {
- const uploaded = await uploadLocalFile(client, options.file);
- fileId = uploaded.id;
- }
- }
- const ev = await client.verify.uploadEvidence.mutate({
- capturedBy: options.by as any,
- checkResultId: options.check,
- content: inlineContent,
- description: options.desc,
- fileId,
- type: options.type as any,
- });
- if (options.json !== undefined) {
- outputJson(ev, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(
- `${pc.green('✓')} Evidence ${pc.bold(ev.id)}${fileId ? ` (file ${fileId})` : ''}`,
- );
- },
- );
-
- evidence
- .command('list <checkResultId>')
- .description('List evidence for a check result')
- .option('--json [fields]', 'Output JSON')
- .action(async (checkResultId: string, options: { json?: boolean | string }) => {
- const client = await getTrpcClient();
- const rows = await client.verify.listEvidence.query({ checkResultId });
- if (options.json !== undefined) {
- outputJson(rows, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- if (rows.length === 0) return void console.log('No evidence.');
- printTable(
- rows.map((e: any) => [
- e.id,
- e.type,
- e.capturedBy ?? '',
- e.fileId ? 'file' : 'inline',
- truncate(e.description || '', 40),
- ]),
- ['ID', 'TYPE', 'BY', 'PAYLOAD', 'DESC'],
- );
- });
-
- evidence
- .command('delete <evidenceId>')
- .description('Delete an evidence artifact')
- .option('--json [fields]', 'Output JSON')
- .action(async (evidenceId: string, options: { json?: boolean | string }) => {
- const client = await getTrpcClient();
- const result = await client.verify.deleteEvidence.mutate({ id: evidenceId });
- if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(`${pc.green('✓')} Deleted evidence ${pc.bold(result.id)}`);
- });
-
- // ════════════ report (narrative entity) ════════════
- const report = verify.command('report').description('Verification reports (verify_reports)');
-
- report
- .command('upsert')
- .description('Write (overwrite) the report for a session')
- .requiredOption('--run <verifyRunId>', 'Target session id')
- .option('--verdict <verdict>', 'passed|failed|uncertain')
- .option('--summary <text>', 'Short summary')
- .option('--content <markdown>', 'Full markdown body')
- .option('--total <n>', 'Total checks')
- .option('--passed <n>', 'Passed checks')
- .option('--failed <n>', 'Failed checks')
- .option('--uncertain <n>', 'Uncertain checks')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (options: {
- content?: string;
- failed?: string;
- json?: boolean | string;
- passed?: string;
- run: string;
- summary?: string;
- total?: string;
- uncertain?: string;
- verdict?: string;
- }) => {
- const num = (s?: string) => (s === undefined ? undefined : Number.parseInt(s, 10));
- const client = await getTrpcClient();
- const created = await client.verify.upsertReport.mutate({
- content: options.content,
- failedChecks: num(options.failed),
- passedChecks: num(options.passed),
- summary: options.summary,
- totalChecks: num(options.total),
- uncertainChecks: num(options.uncertain),
- verdict: options.verdict as any,
- verifyRunId: options.run,
- });
- if (options.json !== undefined) {
- outputJson(created, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- console.log(`${pc.green('✓')} Report ${pc.bold(created.id)} (${created.verdict ?? '—'})`);
- },
- );
-
- report
- .command('get <runId>')
- .description('Show the report for a session')
- .option('--json [fields]', 'Output JSON')
- .action(async (runId: string, options: { json?: boolean | string }) => {
- const client = await getTrpcClient();
- const item = await client.verify.getReport.query({ verifyRunId: runId });
- if (options.json !== undefined) {
- outputJson(item, typeof options.json === 'string' ? options.json : undefined);
- return;
- }
- if (!item) return void console.log('No report.');
- console.log(JSON.stringify(item, null, 2));
- });
-
- // ════════════ feedback ════════════
- verify
- .command('decision <resultId> <decision>')
- .description(`Record human feedback on a result (${DECISIONS.join('|')})`)
- .action(async (resultId: string, decision: Decision) => {
- assertEnum(decision, DECISIONS, 'decision');
- const client = await getTrpcClient();
- await client.verify.submitDecision.mutate({ decision, resultId });
- console.log(`${pc.green('✓')} Recorded ${pc.bold(decision)} on result ${pc.bold(resultId)}`);
- });
-
- // ════════════ ingest (aggregate convenience over the atomic commands) ════════════
- verify
- .command('ingest-report <reportDir>')
- .description(
- 'Ingest a local agent-testing report (result.json + report.md + assets) as a verify session',
- )
- .option('--source <source>', 'agent | agent-testing', 'agent-testing')
- .option('--operation <id>', 'Link the session to an existing Agent Run')
- .option('--title <title>', 'Override the session title')
- .option('--goal <goal>', 'The goal/task being verified')
- .option(
- '--subject <type:id>',
- 'Override the required acceptance subject (defaults to the current LOBEHUB_TOPIC_ID)',
- )
- .option(
- '--requirement <text>',
- 'Acceptance requirement recorded when the aggregate is first created',
- )
- .option('--open', 'Print the in-app URL to open the report')
- .option('--json [fields]', 'Output JSON')
- .action(
- async (
- reportDir: string,
- options: {
- goal?: string;
- json?: boolean | string;
- open?: boolean;
- operation?: string;
- requirement?: string;
- source?: string;
- subject?: string;
- title?: string;
- },
- ) => {
- const dir = path.resolve(reportDir);
- const resultPath = path.join(dir, 'result.json');
- if (!existsSync(resultPath)) {
- log.error(`result.json not found in ${dir}`);
- process.exit(1);
- }
-
- let result: any;
- try {
- result = JSON.parse(readFileSync(resultPath, 'utf8'));
- } catch {
- log.error('result.json is not valid JSON');
- process.exit(1);
- }
-
- const cases: any[] = Array.isArray(result.cases) ? result.cases : [];
- const summary = result.summary ?? {};
- const reportMdPath = path.join(dir, 'report.md');
- const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
-
- // What kind of delivery this report verified (default: coding).
- const scenario = scenarioFromResult(result);
-
- // The scenario's context for the report's scope header. Coding lifts the
- // well-known top-level fields (branch / commit / surfaces / PR); every
- // other scenario passes result.json `context` through as its own bag.
- // `pullRequest` is hoisted: the success output (text and --json) prints
- // the PR link after the ingest, whatever the scenario resolved to.
- let context: Record<string, unknown> | undefined;
- let pullRequest: ReturnType<typeof pullRequestFromResult>;
- if (scenario === 'coding') {
- const branch = typeof result.branch === 'string' ? result.branch : undefined;
- const surfaces = surfacesFromResult(result);
- // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the
- // report links to it without the author having to remember the field.
- pullRequest = pullRequestFromResult(result) ?? pullRequestFromBranch(branch);
- const contextEntries = Object.entries({
- branch,
- commit: typeof result.commit === 'string' ? result.commit : undefined,
- entry: typeof result.entry === 'string' ? result.entry : undefined,
- pullRequest,
- surfaces,
- testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,
- }).filter(([, v]) => v !== undefined);
- context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;
- } else {
- context = genericContextFromResult(result);
- }
-
- // What the run set out to check, written before it ran. Paired with the
- // results by `id`, so the report can show a planned item that never ran.
- const plan = planFromResult(result);
-
- // Every agent-testing report belongs to an acceptance. Explicit CLI input
- // wins, then result.json, then the authoring topic echoed by the runtime.
- let subject = subjectFromResult(result);
- if (options.subject) {
- const ref = parseSubjectRef(options.subject);
- if (!ref) {
- log.error(
- `--subject must be one of ${acceptanceSubjectTypes.map((t) => `${t}:<id>`).join(' | ')}`,
- );
- process.exit(1);
- }
- subject = { ref, requirement: subject?.requirement };
- } else if (result.subject && !subject) {
- log.error('result.json `subject` is malformed (expected "type:id" or {type,id})');
- process.exit(1);
- } else if (!subject) {
- const ref = subjectFromEnv();
- if (ref) subject = { ref };
- }
- if (!subject) {
- log.error(
- 'Acceptance subject is required: run inside a LobeHub topic or pass --subject task:<id> | topic:<id> | document:<id>',
- );
- process.exit(1);
- }
- const requirement = options.requirement ?? subject?.requirement;
-
- const client = await getTrpcClient();
- const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
- const title = options.title ?? result.title;
- // The title is the run's identity in every list surface — an untitled
- // run renders as a placeholder forever, so say so before it ships.
- if (!title) {
- log.warn(
- 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',
- );
- }
- // The in-app conversation that ran this harness, if any (env-supplied).
- // Strictly the authoring conversation. `--operation` names the Agent Run
- // under test and is passed to `createRun` below — a different relation.
- const origin = originFromEnv();
- const newRunMetadata = metadataForReport(result, undefined, origin);
-
- // Every ingest is a new immutable verification snapshot. A repair or
- // re-verification is represented by another run on the same acceptance.
- const run = await client.verify.createRun.mutate({
- context,
- goal,
- metadata: newRunMetadata,
- operationId: options.operation,
- plan,
- scenario,
- source: options.source as any,
- title,
- });
- const runId = run.id;
-
- // 1c. Chain the session onto its subject's acceptance as the next round
- // BEFORE the report lands, so the report-time status rollup already
- // sees the aggregate.
- const acceptance = await client.acceptance.ensure.mutate({
- requirement,
- subjectId: subject.ref.subjectId,
- subjectType: subject.ref.subjectType,
- });
- const acceptanceId = acceptance.id;
- await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: runId });
-
- // 2. Ingest each case as a check result + its evidence. `checkItemId` is
- // the stable key within this immutable run.
- const seenCheckItemIds = new Set<string>();
- let evidenceCount = 0;
- let inlined = 0;
- for (const [index, c] of cases.entries()) {
- const checkItemId = String(c.id ?? c.checkItemId ?? `case-${index + 1}`);
- seenCheckItemIds.add(checkItemId);
- const verdict = toVerdict(c.result ?? c.status ?? c.verdict);
- const observation = c.keyObservation ?? c.observation ?? c.note;
- const checkResult = await client.verify.ingestResult.mutate({
- checkItemId,
- checkItemIndex: index,
- checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
- required: c.required ?? true,
- // The case's key observation is recorded as Toulmin evidence; a real
- // remediation hint (if the report provides one) goes to `suggestion`.
- // Absent → explicit `null`, so this immutable snapshot records the
- // absence instead of relying on upsert defaults.
- suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,
- toulmin: typeof observation === 'string' ? { evidence: observation } : null,
- verdict,
- verifierType: 'agent',
- verifyRunId: runId,
- });
-
- for (const evidenceInput of reportEvidence(c.evidence)) {
- const rel = evidenceInput.path;
- const abs = path.isAbsolute(rel) ? rel : path.join(dir, rel);
- if (!existsSync(abs)) {
- log.warn(`evidence not found, skipping: ${rel}`);
- continue;
- }
- try {
- const type = evidenceTypeForFile(abs);
- const content = inlineTextEvidenceForFile(abs, type);
- const file = content === undefined ? await uploadLocalFile(client, abs) : undefined;
- await client.verify.uploadEvidence.mutate({
- capturedBy: 'cli',
- checkResultId: checkResult.id,
- // The filename, not the case title — the title already heads the
- // check card, so reusing it here just triples the same text.
- content,
- description: evidenceInput.description ?? path.basename(abs),
- fileId: file?.id,
- metadata: evidenceInput.comparison
- ? { comparison: evidenceInput.comparison }
- : undefined,
- type,
- });
- evidenceCount += 1;
- if (content !== undefined) inlined += 1;
- } catch (e) {
- // A stub/unreachable storage bucket (common in local dev) fails the
- // file PUT — don't abort the whole ingest over one artifact; the
- // session, results, and report are the deliverable.
- log.warn(`evidence upload failed, skipping ${path.basename(abs)}: ${String(e)}`);
- }
- }
- }
-
- // 3. Write the report. `summary` is the overall conclusion (rendered at
- // the top of the report page); `content` is the full markdown detail.
- const conclusion =
- typeof summary.conclusion === 'string'
- ? summary.conclusion
- : typeof summary.note === 'string'
- ? summary.note
- : undefined;
- // A 0-100 quality score lands on overallConfidence (0-1); the report page
- // surfaces it as the `score` stat.
- const score =
- typeof summary.score === 'number'
- ? Math.max(0, Math.min(1, summary.score / 100))
- : undefined;
- await client.verify.upsertReport.mutate({
- content,
- failedChecks: summary.failed,
- overallConfidence: score,
- passedChecks: summary.passed,
- summary: conclusion,
- totalChecks: summary.total ?? cases.length,
- uncertainChecks: (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,
- // An explicit summary.verdict wins; otherwise the headline is derived
- // from the ingested cases (deriveReportVerdict) so no report ships
- // verdict-less and lists as a permanent "?".
- verdict: summary.verdict ? toVerdict(summary.verdict) : deriveReportVerdict(cases),
- verifyRunId: runId,
- });
-
- // A case with no matching plan item means the run checked something it
- // never planned — worth saying out loud, but not a failure. Only
- // meaningful against a plan that actually names something: with no plan
- // (or a cleared one) every case is trivially "unplanned", which is noise.
- const unplanned = plan?.length
- ? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))
- : [];
-
- if (options.json !== undefined) {
- outputJson(
- {
- acceptanceId,
- cases: cases.length,
- evidence: evidenceCount,
- inlined,
- origin,
- planItems: plan?.length ?? 0,
- pullRequest,
- scenario,
- subject: subject.ref,
- unplanned,
- verifyRunId: runId,
- },
- typeof options.json === 'string' ? options.json : undefined,
- );
- return;
- }
-
- console.log(
- `${pc.green('✓')} Ingested ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` +
- `${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}`,
- );
- if (plan?.length) {
- const unexecuted = plan.filter((item) => !seenCheckItemIds.has(item.id));
- console.log(
- `${pc.bold('plan')}: ${plan.length} item(s)` +
- `${unexecuted.length > 0 ? pc.yellow(` — ${unexecuted.length} planned but not executed`) : ''}` +
- `${unplanned.length > 0 ? pc.dim(` — ${unplanned.length} unplanned case(s)`) : ''}`,
- );
- }
- if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);
- if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);
- console.log(`${pc.bold('verifyRunId')}: ${runId} ${pc.dim('(immutable snapshot)')}`);
- console.log(
- `${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subject.ref.subjectType}:${subject.ref.subjectId})`)}`,
- );
- if (options.open) {
- console.log(`${pc.bold('open')}: /verify/${runId}`);
- console.log(`${pc.bold('open acceptance')}: /acceptance/${acceptanceId}`);
- }
- },
- );
-}
-
-function printResults(results: any[]): void {
- printTable(
- results.map((r) => [
- truncate(r.checkItemTitle || r.checkItemId, 50),
- statusColor(r.status),
- r.verdict ?? '',
- r.confidence != null ? String(r.confidence) : '',
- r.required ? 'gate' : 'soft',
- truncate(r.suggestion || '', 40),
- ]),
- ['CHECK', 'STATUS', 'VERDICT', 'CONF', 'BLOCK', 'SUGGESTION'],
- );
-}
-
-function statusColor(status: string): string {
- if (status === 'passed') return pc.green(status);
- if (status === 'failed') return pc.red(status);
- if (status === 'running') return pc.yellow(status);
- return pc.dim(status);
}
diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.ts
index c1ba5ec7975..f45bec46c1b 100644
--- a/apps/cli/src/commands/verifyAcceptance.ts
+++ b/apps/cli/src/commands/verifyAcceptance.ts
@@ -4,7 +4,8 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
-import { parseSubjectRef } from './verify';
+import { attachAcceptanceRunCommands } from './acceptanceRun';
+import { parseSubjectRef } from './verifyHelpers';
/**
* Resolve an acceptance from either its uuid or a `type:id` subject reference —
@@ -307,4 +308,9 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
}
console.log(`${pc.red('✗')} Delivery rejected (${result.id}) — next round re-opens it`);
});
+
+ // The canonical `lh acceptance init` + `lh acceptance run …` tree hangs off the
+ // first-class command only; the legacy `lh verify acceptance` alias stays a thin
+ // decision surface (its run commands keep their old `lh verify …` spellings).
+ if (!options?.deprecated) attachAcceptanceRunCommands(acceptance);
}
diff --git a/apps/cli/src/commands/verifyHelpers.ts b/apps/cli/src/commands/verifyHelpers.ts
new file mode 100644
index 00000000000..817a919fd0b
--- /dev/null
+++ b/apps/cli/src/commands/verifyHelpers.ts
@@ -0,0 +1,541 @@
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import type {
+ AcceptanceSubjectType,
+ VerifyRunOrigin,
+ VerifyRunScenario,
+ VerifySurface,
+} from '@lobechat/const/verify';
+import {
+ acceptanceSubjectTypes,
+ normalizeVerifySurface,
+ verifyEvidenceTypes,
+ verifyRunScenarios,
+ verifySurfaces,
+} from '@lobechat/const/verify';
+import pc from 'picocolors';
+
+import { printTable, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+
+export type VerifierType = 'agent' | 'llm' | 'program';
+export type OnFail = 'auto_repair' | 'manual';
+export type Decision = 'accepted' | 'overridden' | 'rejected';
+
+export const VERIFIER_TYPES: VerifierType[] = ['program', 'agent', 'llm'];
+export const ON_FAIL: OnFail[] = ['manual', 'auto_repair'];
+export const DECISIONS: Decision[] = ['accepted', 'rejected', 'overridden'];
+/** The evidence media a plan item may require — the same closed set the executor gates on. */
+export const EVIDENCE_TYPES = verifyEvidenceTypes;
+
+export function parseConfig(raw?: string): Record<string, unknown> | undefined {
+ if (!raw) return undefined;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ log.error('--config must be valid JSON');
+ process.exit(1);
+ }
+}
+
+export function assertEnum<T extends string>(
+ value: T | undefined,
+ allowed: T[],
+ flag: string,
+): void {
+ if (value !== undefined && !allowed.includes(value)) {
+ log.error(`${flag} must be one of: ${allowed.join(', ')}`);
+ process.exit(1);
+ }
+}
+
+export type Verdict = 'failed' | 'passed' | 'uncertain';
+export type EvidenceType = 'dom_snapshot' | 'gif' | 'screenshot' | 'text' | 'transcript' | 'video';
+
+export const INLINE_TEXT_EVIDENCE_LIMIT = 5000;
+export const INLINE_TEXT_EVIDENCE_TYPES = new Set<EvidenceType>([
+ 'dom_snapshot',
+ 'text',
+ 'transcript',
+]);
+
+/** Map a free-form case/summary result token onto the verify verdict vocabulary. */
+export function toVerdict(raw: unknown): Verdict {
+ const s = String(raw ?? '').toLowerCase();
+ if (['pass', 'passed', 'ok', 'success'].includes(s)) return 'passed';
+ if (['fail', 'failed', 'error'].includes(s)) return 'failed';
+ return 'uncertain'; // partial / blocked / skipped / pending / unknown
+}
+
+/**
+ * The report's headline verdict when the author didn't set `summary.verdict`:
+ * derived from the ingested cases, so a report can never ship verdict-less and
+ * render as a permanent "?" in every list surface.
+ */
+export function deriveReportVerdict(cases: unknown[]): Verdict | undefined {
+ const verdicts = cases.map((c) => toVerdict((c as any)?.result ?? (c as any)?.verdict));
+ if (verdicts.length === 0) return undefined;
+ if (verdicts.includes('failed')) return 'failed';
+ if (verdicts.includes('uncertain')) return 'uncertain';
+ return 'passed';
+}
+
+/** Pick an evidence medium from a file extension. */
+export function evidenceTypeForFile(file: string): EvidenceType {
+ const ext = path.extname(file).toLowerCase().slice(1);
+ if (ext === 'gif') return 'gif';
+ if (['png', 'jpg', 'jpeg', 'webp', 'svg', 'bmp'].includes(ext)) return 'screenshot';
+ if (['mp4', 'webm', 'mov', 'm4v'].includes(ext)) return 'video';
+ if (['html', 'htm'].includes(ext)) return 'dom_snapshot';
+ return 'text';
+}
+
+export function inlineTextEvidenceForFile(
+ file: string,
+ type: EvidenceType | string,
+): string | undefined {
+ if (!INLINE_TEXT_EVIDENCE_TYPES.has(type as EvidenceType)) return undefined;
+
+ try {
+ const buffer = readFileSync(file);
+ if (buffer.includes(0)) return undefined;
+
+ const content = buffer.toString('utf8');
+ return content.length > 0 && content.length < INLINE_TEXT_EVIDENCE_LIMIT ? content : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Normalize a case's `evidence` field (string | string[] | {path}[]) to path strings. */
+export interface ReportEvidenceInput {
+ comparison?: {
+ id: string;
+ label?: string;
+ layout?: 'horizontal' | 'vertical';
+ role: 'after' | 'before';
+ };
+ description?: string;
+ path: string;
+}
+
+export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {
+ if (!evidence) return [];
+ const arr = Array.isArray(evidence) ? evidence : [evidence];
+ return arr
+ .map((e): ReportEvidenceInput | null => {
+ if (typeof e === 'string') return { path: e };
+ const value = objectValue(e);
+ const evidencePath = value && firstString(value.path, value.file);
+ if (!evidencePath) return null;
+ const comparison = objectValue(value.comparison);
+ const role = comparison?.role;
+ const id = firstString(comparison?.id);
+ // The report viewer pairs on `id` and drops any comparison lacking one, so
+ // an id-less half could never render side by side. Warn rather than upload
+ // a comparison that is silently downgraded to an ordinary image.
+ if (comparison && !(id && (role === 'before' || role === 'after'))) {
+ log.warn(
+ `evidence ${evidencePath}: comparison needs both a string "id" and role "before"/"after" — ignoring it`,
+ );
+ }
+ const layout = comparison?.layout === 'vertical' ? 'vertical' : undefined;
+ return {
+ comparison:
+ id && (role === 'before' || role === 'after')
+ ? { id, label: firstString(comparison?.label), layout, role }
+ : undefined,
+ description: firstString(value.description, value.desc),
+ path: evidencePath,
+ };
+ })
+ .filter((item): item is ReportEvidenceInput => item !== null);
+}
+
+export function firstString(...values: unknown[]): string | undefined {
+ return values.find((v): v is string => typeof v === 'string' && v.length > 0);
+}
+
+export function firstStringOrNumber(...values: unknown[]): string | number | undefined {
+ return values.find(
+ (v): v is string | number => (typeof v === 'string' && v.length > 0) || typeof v === 'number',
+ );
+}
+
+export function objectValue(value: unknown): Record<string, unknown> | undefined {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+}
+
+export function safeWebUrl(value: string | undefined): string | undefined {
+ if (!value) return undefined;
+
+ try {
+ const url = new URL(value);
+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Normalize common agent-testing PR shapes into the verify coding scope. */
+export function pullRequestFromResult(result: Record<string, unknown>) {
+ const pr = objectValue(result.pullRequest) ?? objectValue(result.pr);
+ const url = safeWebUrl(
+ firstString(
+ pr?.url,
+ pr?.htmlUrl,
+ pr?.html_url,
+ result.pullRequestUrl,
+ result.prUrl,
+ typeof result.pr === 'string' ? result.pr : undefined,
+ ),
+ );
+ const number = firstStringOrNumber(pr?.number, result.pullRequestNumber, result.prNumber);
+ const title = firstString(pr?.title, result.pullRequestTitle, result.prTitle);
+ const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+/**
+ * The PR for a branch, asked of `gh`. A report almost always verifies a branch
+ * that already has one, but the author has to remember to write it down — and
+ * mostly doesn't, so the report loses its single most useful outbound link.
+ * Best-effort by design: no `gh`, not a repo, not authenticated, or no PR for
+ * the branch all mean "no PR", never a failed publish.
+ */
+export function pullRequestFromBranch(branch: string | undefined) {
+ if (!branch) return undefined;
+
+ try {
+ const raw = execFileSync(
+ 'gh',
+ ['pr', 'view', branch, '--json', 'number,title,url'],
+ // `gh` writes its "no pull requests found" diagnostics to stderr; keep them
+ // off the CLI's own output.
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 },
+ );
+ const parsed = objectValue(JSON.parse(raw));
+ const url = safeWebUrl(firstString(parsed?.url));
+ const number = firstStringOrNumber(parsed?.number);
+ const title = firstString(parsed?.title);
+ const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * The surfaces the report says it exercised, as canonical values.
+ *
+ * Strict on purpose: an unrecognized surface is a hard error, not a silently
+ * dropped value. Free-form surfaces are how the field rotted — prose, runtime
+ * modes ("packaged build") and test kinds ("unit", "type-check") all ended up in
+ * it, and none of them render. Failing here puts the fix in the author's hands
+ * while they still have the context to make it.
+ */
+export function surfacesFromResult(result: Record<string, unknown>): VerifySurface[] | undefined {
+ if (!Array.isArray(result.surfaces)) return undefined;
+
+ const raw = result.surfaces.filter((s: unknown): s is string => typeof s === 'string');
+ const canonical: VerifySurface[] = [];
+ const rejected: string[] = [];
+
+ for (const value of raw) {
+ const surface = normalizeVerifySurface(value);
+ if (surface) {
+ if (!canonical.includes(surface)) canonical.push(surface);
+ } else {
+ rejected.push(value);
+ }
+ }
+
+ if (rejected.length > 0) {
+ log.error(
+ `result.json "surfaces" must name the product surface a check ran on, one of: ${verifySurfaces.join(', ')}`,
+ );
+ log.error(` rejected: ${rejected.map((v) => JSON.stringify(v)).join(', ')}`);
+ log.error(
+ ' Runtime detail ("packaged build", "CDP dev instance") belongs on a plan item\'s "method"; a test kind ("unit", "backend") is not a surface — a backend change verified through the CLI has surface "cli".',
+ );
+ process.exit(1);
+ }
+
+ return canonical.length > 0 ? canonical : undefined;
+}
+
+/**
+ * What kind of delivery the report verified. Defaults to `coding` — the
+ * agent-testing harness's home turf — and rejects an unknown value rather than
+ * storing a scenario nothing renders (mirrors the strict surface policy: the
+ * author still has the context to fix it).
+ */
+export function scenarioFromResult(result: Record<string, unknown>): VerifyRunScenario {
+ const raw = result.scenario;
+ if (raw === undefined) return 'coding';
+ if (typeof raw === 'string' && (verifyRunScenarios as readonly string[]).includes(raw)) {
+ return raw as VerifyRunScenario;
+ }
+
+ log.error(
+ `result.json "scenario" must be one of: ${verifyRunScenarios.join(', ')} — rejected: ${JSON.stringify(raw)}`,
+ );
+ process.exit(1);
+}
+
+/**
+ * A non-coding scenario's scope, passed through from result.json `context` as
+ * the scenario's own bag (the server stores it as-is; known shapes live in
+ * `@lobechat/types`). Top-level `entry` / `createdAt` are lifted as defaults so
+ * every scenario gets the shared provenance fields for free; explicit `context`
+ * keys win.
+ */
+export function genericContextFromResult(
+ result: Record<string, unknown>,
+): Record<string, unknown> | undefined {
+ const bag = objectValue(result.context) ?? {};
+ const entries = Object.entries({
+ entry: firstString(result.entry),
+ testedAt: firstString(result.createdAt),
+ ...bag,
+ }).filter(([, v]) => v !== undefined);
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+/** Reject an out-of-vocabulary plan value rather than storing a word nothing reads. */
+export function assertPlanEnum<T extends string>(
+ value: string,
+ allowed: readonly T[],
+ field: string,
+ itemId: string,
+): T {
+ if ((allowed as readonly string[]).includes(value)) return value as T;
+
+ log.error(`result.json plan item "${itemId}": "${field}" must be one of: ${allowed.join(', ')}`);
+ log.error(` rejected: ${JSON.stringify(value)}`);
+ process.exit(1);
+}
+
+/**
+ * The checks the run set out to make, as frozen plan items.
+ *
+ * Two of the fields are a closed vocabulary, not free text, because the pipeline
+ * actually acts on them:
+ *
+ * - `verifier` → {@link VerifyCheckItem.verifierType} (`program | agent | llm`):
+ * how the item is judged. Defaults to `agent`, but a command-asserted check is
+ * `program` and mislabelling it hides what actually produced the verdict.
+ * - `requiredEvidence` → `verifierConfig.requiredEvidence`
+ * ({@link RequiredEvidenceSpec}, medium from {@link verifyEvidenceTypes}):
+ * the artifact the item MUST produce. The executor's coverage gate fails an
+ * item whose required medium is missing, so this is enforcement, not a label —
+ * an unknown medium would silently gate on nothing.
+ *
+ * `method` / `expected` stay prose: they are the author's intent in words, which
+ * no enum can carry. Everything else the frozen {@link VerifyCheckItem} needs is
+ * filled in here, so an author writes only `{ id, title }` plus what they mean.
+ *
+ * Returns `undefined` when the report declares no `plan` field. A `plan` that is
+ * present but empty returns `[]`, recording an explicitly empty plan in this
+ * immutable snapshot.
+ */
+export function planFromResult(result: Record<string, unknown>) {
+ if (!Array.isArray(result.plan)) return undefined;
+
+ const items = result.plan.flatMap((entry: unknown, index: number) => {
+ const item = objectValue(entry);
+ const title = firstString(item?.title, item?.name);
+ // An item with no title names no check — it can't be rendered or paired.
+ if (!item || !title) return [];
+
+ const id = String(item.id ?? `case-${index + 1}`);
+ const method = firstString(item.method, item.how);
+ const expected = firstString(item.expected, item.expectation);
+
+ const verifierRaw = firstString(item.verifier, item.verifierType);
+ const verifierType = verifierRaw
+ ? assertPlanEnum(verifierRaw, VERIFIER_TYPES, 'verifier', id)
+ : ('agent' as const);
+
+ const requiredEvidence = Array.isArray(item.requiredEvidence)
+ ? item.requiredEvidence.flatMap((spec: unknown) => {
+ // Accept the bare medium (`"screenshot"`) or the full spec object.
+ const record = objectValue(spec);
+ const raw = typeof spec === 'string' ? spec : firstString(record?.type);
+ if (!raw) return [];
+
+ return [
+ {
+ hint: firstString(record?.hint),
+ type: assertPlanEnum(raw, EVIDENCE_TYPES, 'requiredEvidence', id),
+ },
+ ];
+ })
+ : [];
+
+ // Per-item surface: the acceptance union groups checks by it. Normalized to
+ // the closed set (electron → desktop); an unknown value is dropped loudly
+ // rather than stored as a mystery chip.
+ const surfaceRaw = firstString(item.surface);
+ const surface = surfaceRaw ? normalizeVerifySurface(surfaceRaw) : null;
+ if (surfaceRaw && !surface) {
+ log.warn(
+ `plan item "${id}": surface "${surfaceRaw}" names no product surface (expected ${verifySurfaces.join('/')}) — dropping it`,
+ );
+ }
+
+ // The acceptance union groups by category and folds superseded ids into
+ // the new item's iteration timeline — both authored by the harness.
+ const category = firstString(item.category, item.group);
+ const supersedes = Array.isArray(item.supersedes)
+ ? item.supersedes.filter((value: unknown): value is string => typeof value === 'string')
+ : [];
+
+ return [
+ {
+ ...(category === undefined ? {} : { category }),
+ description: firstString(item.description),
+ id,
+ index,
+ onFail: 'manual' as const,
+ required: typeof item.required === 'boolean' ? item.required : true,
+ ...(supersedes.length > 0 ? { supersedes } : {}),
+ title,
+ verifierConfig: {
+ ...(method === undefined ? {} : { method }),
+ ...(expected === undefined ? {} : { expected }),
+ ...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),
+ ...(surface ? { surface } : {}),
+ },
+ verifierType,
+ },
+ ];
+ });
+
+ // `[]` is meaningful — it clears a stale plan. Only an absent `plan` field
+ // (handled above) means "don't touch what's stored".
+ return items;
+}
+
+/**
+ * The LobeHub conversation this harness is running inside, read off the env the
+ * agent runtime echoes into the child process. Lets a report published from an
+ * in-app agent link back to the session that produced it with no flags to
+ * remember. Absent (a plain terminal) → no origin, which is not an error.
+ *
+ * Reads the env and ONLY the env. `--operation` is the opposite relation — the
+ * Agent Run this session *verifies* — so letting it fall through to here would
+ * attribute the report to the run under test instead of the run that wrote it,
+ * corrupting the very provenance this records. The two ids are independent and
+ * may legitimately differ in the same publish.
+ */
+export function originFromEnv(): VerifyRunOrigin | undefined {
+ const origin: VerifyRunOrigin = {
+ agentId: firstString(process.env.LOBEHUB_AGENT_ID),
+ operationId: firstString(process.env.LOBEHUB_OPERATION_ID),
+ topicId: firstString(process.env.LOBEHUB_TOPIC_ID),
+ };
+
+ return Object.values(origin).some(Boolean) ? origin : undefined;
+}
+
+export function metadataForReport(
+ result: Record<string, unknown>,
+ existingMetadata?: unknown,
+ origin?: VerifyRunOrigin,
+): Record<string, unknown> | undefined {
+ const hasInteractionCost = Object.prototype.hasOwnProperty.call(result, 'interactionCost');
+ // Nothing to write is not the same as writing an empty metadata bag.
+ if (!hasInteractionCost && !origin) return undefined;
+
+ const metadata = { ...objectValue(existingMetadata) };
+
+ if (hasInteractionCost) {
+ const interactionCost = objectValue(result.interactionCost);
+
+ if (interactionCost) {
+ metadata.interactionCost = interactionCost;
+ } else {
+ delete metadata.interactionCost;
+ }
+ }
+
+ if (origin) metadata.origin = origin;
+
+ return metadata;
+}
+
+/** A parsed acceptance subject reference (`task:<id>` / `topic:<id>` / `document:<id>`). */
+export interface AcceptanceSubjectRef {
+ subjectId: string;
+ subjectType: AcceptanceSubjectType;
+}
+
+/**
+ * Parse a `type:id` subject reference. Returns null on anything malformed —
+ * callers decide whether that is an error (an explicit `--subject`) or a
+ * silently absent field (result.json).
+ */
+export function parseSubjectRef(raw: unknown): AcceptanceSubjectRef | null {
+ if (typeof raw !== 'string') return null;
+ const idx = raw.indexOf(':');
+ if (idx <= 0) return null;
+ const type = raw.slice(0, idx).trim().toLowerCase();
+ const id = raw.slice(idx + 1).trim();
+ if (!id || !(acceptanceSubjectTypes as readonly string[]).includes(type)) return null;
+ return { subjectId: id, subjectType: type as AcceptanceSubjectType };
+}
+
+/**
+ * The acceptance subject a report attributes itself to, from result.json's
+ * `subject` field — either `"task:<id>"` or `{ type, id, requirement? }`. An
+ * explicit `--subject` flag wins over this.
+ */
+export function subjectFromResult(result: Record<string, unknown>): {
+ ref: AcceptanceSubjectRef;
+ requirement?: string;
+} | null {
+ const raw = result.subject;
+ if (typeof raw === 'string') {
+ const ref = parseSubjectRef(raw);
+ return ref ? { ref } : null;
+ }
+ const value = objectValue(raw);
+ if (!value) return null;
+ const ref = parseSubjectRef(`${firstString(value.type) ?? ''}:${firstString(value.id) ?? ''}`);
+ return ref ? { ref, requirement: firstString(value.requirement) } : null;
+}
+
+/** Default acceptance subject for a report authored inside a LobeHub topic. */
+export function subjectFromEnv(): AcceptanceSubjectRef | null {
+ const topicId = firstString(process.env.LOBEHUB_TOPIC_ID);
+ return topicId ? { subjectId: topicId, subjectType: 'topic' } : null;
+}
+
+export function printResults(results: any[]): void {
+ printTable(
+ results.map((r) => [
+ truncate(r.checkItemTitle || r.checkItemId, 50),
+ statusColor(r.status),
+ r.verdict ?? '',
+ r.confidence != null ? String(r.confidence) : '',
+ r.required ? 'gate' : 'soft',
+ truncate(r.suggestion || '', 40),
+ ]),
+ ['CHECK', 'STATUS', 'VERDICT', 'CONF', 'BLOCK', 'SUGGESTION'],
+ );
+}
+
+export function statusColor(status: string): string {
+ if (status === 'passed') return pc.green(status);
+ if (status === 'failed') return pc.red(status);
+ if (status === 'running') return pc.yellow(status);
+ return pc.dim(status);
+}
diff --git a/apps/cli/src/commands/verifyInstall.test.ts b/apps/cli/src/commands/verifyInstall.test.ts
deleted file mode 100644
index 1984b502e6c..00000000000
--- a/apps/cli/src/commands/verifyInstall.test.ts
+++ /dev/null
@@ -1,434 +0,0 @@
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- rmSync,
- statSync,
- writeFileSync,
-} from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-
-import { Command } from 'commander';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- HARNESS_SKILL_DIRS,
- isVerifyInstallSuccess,
- NoHarnessDirError,
- registerVerifyInstallCommand,
- runVerifyInstall,
-} from './verifyInstall';
-
-const { mockLocateBundledSkill } = vi.hoisted(() => ({
- mockLocateBundledSkill: vi.fn(),
-}));
-vi.mock('../utils/skillLocator', () => ({ locateBundledSkill: mockLocateBundledSkill }));
-vi.mock('../utils/logger', () => ({
- log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
- setVerbose: vi.fn(),
-}));
-
-let root: string;
-let bundleDir: string;
-
-function writeBundledSkill(dir: string) {
- mkdirSync(path.join(dir, 'scripts'), { recursive: true });
- writeFileSync(path.join(dir, 'SKILL.md'), '# agent-testing');
- writeFileSync(path.join(dir, 'scripts', 'run.sh'), '#!/bin/sh\necho hi\n');
- writeFileSync(path.join(dir, 'scripts', 'analyze.mjs'), 'console.log(1)');
- writeFileSync(path.join(dir, 'scripts', 'note.txt'), 'not executable');
-}
-
-beforeEach(() => {
- root = mkdtempSync(path.join(tmpdir(), 'verify-install-'));
- bundleDir = path.join(root, '__bundle__', 'agent-testing');
- writeBundledSkill(bundleDir);
- mockLocateBundledSkill.mockReset().mockReturnValue({
- cliRoot: path.join(root, '__bundle__'),
- skillDir: bundleDir,
- version: '1.0.0',
- });
-});
-
-afterEach(() => {
- rmSync(root, { recursive: true, force: true });
-});
-
-function makeCwd(): string {
- return mkdtempSync(path.join(root, 'consumer-'));
-}
-
-describe('runVerifyInstall — no harness dir found', () => {
- it('throws NoHarnessDirError listing recognized dirs, without --target', () => {
- const cwd = makeCwd();
- expect(() => runVerifyInstall({ cwd })).toThrow(NoHarnessDirError);
- try {
- runVerifyInstall({ cwd });
- } catch (e) {
- expect((e as Error).message).toContain('.claude/skills');
- expect((e as Error).message).toContain('.codex/skills');
- expect((e as Error).message).toContain('.agents/skills');
- expect((e as Error).message).toContain('--target');
- }
- });
-});
-
-describe('runVerifyInstall — fresh install', () => {
- it('installs into a single existing harness dir', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
-
- const result = runVerifyInstall({ cwd });
-
- expect(result.results).toHaveLength(1);
- expect(result.results[0].status).toBe('installed');
- const target = path.join(cwd, '.claude', 'skills', 'agent-testing');
- expect(result.results[0].target).toBe(target);
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');
-
- const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));
- expect(meta).toEqual({
- cliRoot: path.join(root, '__bundle__'),
- name: 'agent-testing',
- version: '1.0.0',
- });
- });
-
- it('cliRoot outside the consumer repo → marker keeps the absolute path', () => {
- // bundleDir/cliRoot live under `root`, sibling to (not inside) `cwd` —
- // simulates a global install / npx where @lobehub/cli sits outside the
- // consumer repo entirely.
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
-
- const result = runVerifyInstall({ cwd });
-
- const target = result.results[0].target;
- const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));
- expect(meta.cliRoot).toBe(path.join(root, '__bundle__'));
- expect(path.isAbsolute(meta.cliRoot)).toBe(true);
- });
-
- it('cliRoot inside the consumer repo → marker stores a POSIX-relative path from the marker dir', () => {
- // Simulates @lobehub/cli vendored inside the consumer repo itself (e.g.
- // this monorepo): cliRoot sits under cwd, so baking in an absolute path
- // would commit a machine-specific filesystem layout.
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- const inRepoCliRoot = path.join(cwd, 'apps', 'cli');
- mkdirSync(inRepoCliRoot, { recursive: true });
- mockLocateBundledSkill.mockReturnValue({
- cliRoot: inRepoCliRoot,
- skillDir: bundleDir,
- version: '1.0.0',
- });
-
- const result = runVerifyInstall({ cwd });
-
- const target = result.results[0].target;
- const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));
- expect(meta.cliRoot).toBe('../../../apps/cli');
- expect(path.isAbsolute(meta.cliRoot)).toBe(false);
- expect(path.resolve(target, meta.cliRoot)).toBe(inRepoCliRoot);
- });
-
- it('installs into every existing harness dir (multi-harness)', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- mkdirSync(path.join(cwd, '.codex', 'skills'), { recursive: true });
- // .agents/skills intentionally absent
-
- const result = runVerifyInstall({ cwd });
-
- expect(result.results.map((r) => r.status)).toEqual(['installed', 'installed']);
- expect(result.results.map((r) => r.target).sort()).toEqual(
- [
- path.join(cwd, '.claude', 'skills', 'agent-testing'),
- path.join(cwd, '.codex', 'skills', 'agent-testing'),
- ].sort(),
- );
- });
-
- it('re-applies chmod +x to .sh/.mjs/.cjs after copying, leaves other files untouched', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- const result = runVerifyInstall({ cwd });
- const target = result.results[0].target;
-
- const shMode = statSync(path.join(target, 'scripts', 'run.sh')).mode & 0o777;
- const mjsMode = statSync(path.join(target, 'scripts', 'analyze.mjs')).mode & 0o777;
- expect(shMode & 0o111).toBe(0o111);
- expect(mjsMode & 0o111).toBe(0o111);
- });
-
- it('respects --target, creating the dir if missing, and does not touch harness dirs', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true }); // present but must be ignored
-
- const result = runVerifyInstall({ cwd, target: 'custom/skills-dir' });
-
- expect(result.results).toHaveLength(1);
- const target = path.join(cwd, 'custom', 'skills-dir', 'agent-testing');
- expect(result.results[0].target).toBe(target);
- expect(existsSync(target)).toBe(true);
- expect(existsSync(path.join(cwd, '.claude', 'skills', 'agent-testing'))).toBe(false);
- });
-});
-
-describe('runVerifyInstall — edge cases', () => {
- it('version marker present, bundled version newer → overwrites skill body', () => {
- const cwd = makeCwd();
- const skillsDir = path.join(cwd, '.claude', 'skills');
- mkdirSync(skillsDir, { recursive: true });
- runVerifyInstall({ cwd }); // installs 1.0.0
-
- mockLocateBundledSkill.mockReturnValue({
- cliRoot: path.join(root, '__bundle__'),
- skillDir: bundleDir,
- version: '2.0.0',
- });
- writeFileSync(path.join(bundleDir, 'SKILL.md'), '# agent-testing v2');
-
- const result = runVerifyInstall({ cwd });
- expect(result.results[0].status).toBe('updated');
- const target = path.join(skillsDir, 'agent-testing');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing v2');
- const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));
- expect(meta.version).toBe('2.0.0');
- });
-
- it('marker present, same version → no-op with message', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- runVerifyInstall({ cwd });
-
- const result = runVerifyInstall({ cwd });
- expect(result.results[0].status).toBe('no-op');
- });
-
- it('marker present, bundled version older → no-op with message', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- mockLocateBundledSkill.mockReturnValue({
- cliRoot: path.join(root, '__bundle__'),
- skillDir: bundleDir,
- version: '5.0.0',
- });
- runVerifyInstall({ cwd }); // installs 5.0.0
-
- mockLocateBundledSkill.mockReturnValue({
- cliRoot: path.join(root, '__bundle__'),
- skillDir: bundleDir,
- version: '1.0.0',
- });
- const result = runVerifyInstall({ cwd });
- expect(result.results[0].status).toBe('no-op');
- });
-
- it('target agent-testing dir exists WITHOUT marker → refuses; --force replaces', () => {
- const cwd = makeCwd();
- const skillsDir = path.join(cwd, '.claude', 'skills');
- const target = path.join(skillsDir, 'agent-testing');
- mkdirSync(target, { recursive: true });
- writeFileSync(path.join(target, 'SKILL.md'), '# hand-written predecessor');
-
- const refused = runVerifyInstall({ cwd });
- expect(refused.results[0].status).toBe('refused');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# hand-written predecessor');
-
- const forced = runVerifyInstall({ cwd, force: true });
- expect(forced.results[0].status).toBe('updated');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');
- expect(forced.results[0].message).toBe('replaced unversioned install with 1.0.0');
- });
-
- it('marker present but with invalid/missing version → refuses; --force replaces', () => {
- const cwd = makeCwd();
- const skillsDir = path.join(cwd, '.claude', 'skills');
- const target = path.join(skillsDir, 'agent-testing');
- mkdirSync(target, { recursive: true });
- writeFileSync(path.join(target, 'SKILL.md'), '# hand-written predecessor');
- writeFileSync(path.join(target, '.skill-meta.json'), '{}');
-
- const refused = runVerifyInstall({ cwd });
- expect(refused.results[0].status).toBe('refused');
-
- const forced = runVerifyInstall({ cwd, force: true });
- expect(forced.results[0].status).toBe('updated');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');
- });
-
- it('marker from another tool → refuses instead of trusting its version; --force replaces', () => {
- const cwd = makeCwd();
- const target = path.join(cwd, '.claude', 'skills', 'agent-testing');
- mkdirSync(target, { recursive: true });
- writeFileSync(path.join(target, 'SKILL.md'), '# someone else’s skill');
- writeFileSync(
- path.join(target, '.skill-meta.json'),
- JSON.stringify({ name: 'other', version: '999.0.0' }),
- );
-
- const refused = runVerifyInstall({ cwd });
- expect(refused.results[0].status).toBe('refused');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# someone else’s skill');
-
- const forced = runVerifyInstall({ cwd, force: true });
- expect(forced.results[0].status).toBe('updated');
- expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');
- });
-
- it('consumer cwd not a git repo → installs anyway, reports isGitRepo: false', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- const result = runVerifyInstall({ cwd });
- expect(result.isGitRepo).toBe(false);
- expect(result.results[0].status).toBe('installed');
- });
-
- it('cwd is a git repo → reports isGitRepo: true', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- mkdirSync(path.join(cwd, '.git'), { recursive: true });
- const result = runVerifyInstall({ cwd });
- expect(result.isGitRepo).toBe(true);
- });
-
- it('no .gitignore at cwd → creates one containing .records/', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- const result = runVerifyInstall({ cwd });
- expect(result.gitignore.action).toBe('created');
- expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe('.records/\n');
- });
-
- it('.gitignore without .records/ entry → appends it, no dupes on re-run', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- writeFileSync(path.join(cwd, '.gitignore'), 'node_modules/\n');
-
- const result = runVerifyInstall({ cwd });
- expect(result.gitignore.action).toBe('appended');
- const content = readFileSync(path.join(cwd, '.gitignore'), 'utf8');
- expect(content).toBe('node_modules/\n.records/\n');
-
- const again = runVerifyInstall({ cwd });
- expect(again.gitignore.action).toBe('no-op');
- expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe(content);
- });
-
- it('.gitignore already covers .records/ → no-op', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- writeFileSync(path.join(cwd, '.gitignore'), 'dist/\n.records/\n');
-
- const result = runVerifyInstall({ cwd });
- expect(result.gitignore.action).toBe('no-op');
- expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe('dist/\n.records/\n');
- });
-
- it('never creates or touches .agents/verify/', () => {
- const cwd = makeCwd();
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- const verifyAdapterDir = path.join(cwd, '.agents', 'verify');
- mkdirSync(verifyAdapterDir, { recursive: true });
- writeFileSync(path.join(verifyAdapterDir, 'PROJECT.md'), 'existing adapter content');
-
- runVerifyInstall({ cwd });
-
- expect(readFileSync(path.join(verifyAdapterDir, 'PROJECT.md'), 'utf8')).toBe(
- 'existing adapter content',
- );
- expect(existsSync(path.join(cwd, '.agents', 'skills', 'agent-testing'))).toBe(false);
- });
-});
-
-describe('isVerifyInstallSuccess', () => {
- it('is true when at least one target installed/updated/no-op', () => {
- expect(isVerifyInstallSuccess([{ message: '', status: 'installed', target: 'a' }])).toBe(true);
- expect(isVerifyInstallSuccess([{ message: '', status: 'no-op', target: 'a' }])).toBe(true);
- expect(
- isVerifyInstallSuccess([
- { message: '', status: 'refused', target: 'a' },
- { message: '', status: 'installed', target: 'b' },
- ]),
- ).toBe(true);
- });
-
- it('is false when every target refused, or there are no targets', () => {
- expect(isVerifyInstallSuccess([{ message: '', status: 'refused', target: 'a' }])).toBe(false);
- expect(isVerifyInstallSuccess([])).toBe(false);
- });
-});
-
-describe('HARNESS_SKILL_DIRS', () => {
- it('lists the three recognized harness dirs', () => {
- expect(HARNESS_SKILL_DIRS).toEqual(['.claude/skills', '.codex/skills', '.agents/skills']);
- });
-});
-
-describe('lh verify install — command registration', () => {
- let consoleSpy: ReturnType<typeof vi.spyOn>;
- let exitSpy: ReturnType<typeof vi.spyOn>;
- let cwd: string;
- let cwdSpy: ReturnType<typeof vi.spyOn>;
-
- beforeEach(() => {
- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
- exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
- cwd = makeCwd();
- cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(cwd);
- });
-
- afterEach(() => {
- consoleSpy.mockRestore();
- exitSpy.mockRestore();
- cwdSpy.mockRestore();
- });
-
- const run = async (args: string[]) => {
- const program = new Command();
- program.exitOverride();
- const verify = program.command('verify');
- registerVerifyInstallCommand(verify);
- await program.parseAsync(['node', 'lh', 'verify', ...args]);
- };
-
- it('is registered as `verify install`, distinct from `verify init`', async () => {
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- await run(['install']);
-
- expect(existsSync(path.join(cwd, '.claude', 'skills', 'agent-testing', 'SKILL.md'))).toBe(true);
- expect(exitSpy).not.toHaveBeenCalledWith(1);
- });
-
- it('happy path installs and prints a per-target result line', async () => {
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- await run(['install']);
-
- const printed = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');
- expect(printed).toContain('installed');
- expect(printed).toContain('agent-testing');
- expect(printed).toContain('PROJECT.md');
- });
-
- it('--json outputs the structured result and exits 0 on success', async () => {
- mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });
- await run(['install', '--json']);
-
- const out = JSON.parse(consoleSpy.mock.calls.map((c) => String(c[0])).join(''));
- expect(out.results[0].status).toBe('installed');
- expect(exitSpy).toHaveBeenCalledWith(0);
- });
-
- it('--target installs into the given dir even without a recognized harness dir', async () => {
- await run(['install', '--target', 'custom-dir']);
- expect(existsSync(path.join(cwd, 'custom-dir', 'agent-testing', 'SKILL.md'))).toBe(true);
- });
-
- it('exits non-zero and logs an error when no harness dir and no --target', async () => {
- await run(['install']);
- expect(exitSpy).toHaveBeenCalledWith(1);
- });
-});
diff --git a/apps/cli/src/commands/verifyInstall.ts b/apps/cli/src/commands/verifyInstall.ts
deleted file mode 100644
index dc476507d05..00000000000
--- a/apps/cli/src/commands/verifyInstall.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-import {
- chmodSync,
- cpSync,
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- rmSync,
- writeFileSync,
-} from 'node:fs';
-import path from 'node:path';
-
-import type { Command } from 'commander';
-import pc from 'picocolors';
-import semver from 'semver';
-
-import { outputJson } from '../utils/format';
-import { log } from '../utils/logger';
-import { type BundledSkill, locateBundledSkill } from '../utils/skillLocator';
-
-export const SKILL_NAME = 'agent-testing';
-export const HARNESS_SKILL_DIRS = ['.claude/skills', '.codex/skills', '.agents/skills'];
-const GITIGNORE_ENTRY = '.records/';
-const EXECUTABLE_EXTENSIONS = new Set(['.sh', '.mjs', '.cjs']);
-
-export interface SkillMeta {
- cliRoot: string;
- name: string;
- version: string;
-}
-
-export type InstallStatus = 'installed' | 'no-op' | 'refused' | 'updated';
-
-export interface InstallResult {
- message: string;
- status: InstallStatus;
- target: string;
-}
-
-export interface VerifyInstallOptions {
- cwd: string;
- force?: boolean;
- target?: string;
-}
-
-export interface VerifyInstallResult {
- bundled: BundledSkill;
- gitignore: { action: 'appended' | 'created' | 'no-op'; path: string };
- isGitRepo: boolean;
- results: InstallResult[];
-}
-
-export class NoHarnessDirError extends Error {
- constructor(cwd: string) {
- super(
- `No harness skills directory found under ${cwd} ` +
- `(looked for ${HARNESS_SKILL_DIRS.join(', ')}). ` +
- 'Pass --target <dir> to install into a specific directory.',
- );
- this.name = 'NoHarnessDirError';
- }
-}
-
-function findHarnessDirs(cwd: string): string[] {
- return HARNESS_SKILL_DIRS.map((d) => path.join(cwd, d)).filter((d) => existsSync(d));
-}
-
-function readSkillMeta(skillDir: string): SkillMeta | undefined {
- const metaPath = path.join(skillDir, '.skill-meta.json');
- if (!existsSync(metaPath)) return undefined;
- try {
- const parsed = JSON.parse(readFileSync(metaPath, 'utf8'));
- if (parsed?.name !== SKILL_NAME) return undefined;
- if (!semver.valid(parsed.version)) return undefined;
- return parsed;
- } catch {
- return undefined;
- }
-}
-
-function chmodExecutablesRecursive(dir: string): void {
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) {
- chmodExecutablesRecursive(full);
- } else if (EXECUTABLE_EXTENSIONS.has(path.extname(entry.name))) {
- chmodSync(full, 0o755);
- }
- }
-}
-
-function writeSkillMeta(skillDir: string, meta: SkillMeta): void {
- writeFileSync(path.join(skillDir, '.skill-meta.json'), JSON.stringify(meta, null, 2) + '\n');
-}
-
-// The consumer repo may vendor @lobehub/cli inside itself (e.g. this very
-// monorepo), in which case cliRoot sits under cwd and an absolute path would
-// bake this machine's filesystem layout into a committed marker file. Resolve
-// relative to the marker's own directory instead, so the marker stays
-// portable across machines and CI. Global installs / npx still resolve
-// cliRoot outside the consumer repo, so those keep the absolute path — there
-// is no repo-relative path to express.
-function resolveCliRootForMeta(cliRoot: string, cwd: string, targetDir: string): string {
- const relFromCwd = path.relative(cwd, cliRoot);
- const isInsideRepo =
- relFromCwd !== '' && !relFromCwd.startsWith('..') && !path.isAbsolute(relFromCwd);
- if (!isInsideRepo) return cliRoot;
-
- const relFromTarget = path.relative(targetDir, cliRoot);
- return relFromTarget.split(path.sep).join('/');
-}
-
-function installOne(
- harnessDir: string,
- bundled: BundledSkill,
- force: boolean | undefined,
- cwd: string,
-): InstallResult {
- const target = path.join(harnessDir, SKILL_NAME);
- const exists = existsSync(target);
- const meta = exists ? readSkillMeta(target) : undefined;
-
- if (exists && !meta && !force) {
- return {
- message: `${path.join(target, '.skill-meta.json')} is missing or is not a ${SKILL_NAME} marker — this looks like a hand-written or pre-existing skill dir, refusing to overwrite. Pass --force to replace it.`,
- status: 'refused',
- target,
- };
- }
-
- if (meta && !force && semver.compare(bundled.version, meta.version) <= 0) {
- return {
- message: `already at version ${meta.version} (bundled: ${bundled.version})`,
- status: 'no-op',
- target,
- };
- }
-
- if (exists) rmSync(target, { recursive: true, force: true });
- cpSync(bundled.skillDir, target, { recursive: true });
- chmodExecutablesRecursive(target);
- writeSkillMeta(target, {
- cliRoot: resolveCliRootForMeta(bundled.cliRoot, cwd, target),
- name: SKILL_NAME,
- version: bundled.version,
- });
-
- return {
- message: exists
- ? meta
- ? `updated ${meta.version} → ${bundled.version}`
- : `replaced unversioned install with ${bundled.version}`
- : `installed ${bundled.version}`,
- status: exists ? 'updated' : 'installed',
- target,
- };
-}
-
-function ensureGitignore(cwd: string): { action: 'appended' | 'created' | 'no-op'; path: string } {
- const gitignorePath = path.join(cwd, '.gitignore');
- if (!existsSync(gitignorePath)) {
- writeFileSync(gitignorePath, `${GITIGNORE_ENTRY}\n`);
- return { action: 'created', path: gitignorePath };
- }
-
- const content = readFileSync(gitignorePath, 'utf8');
- const covered = content
- .split('\n')
- .map((line) => line.trim())
- .some((line) => line === GITIGNORE_ENTRY || line === GITIGNORE_ENTRY.replace(/\/$/, ''));
- if (covered) return { action: 'no-op', path: gitignorePath };
-
- const needsLeadingNewline = content.length > 0 && !content.endsWith('\n');
- writeFileSync(
- gitignorePath,
- content + (needsLeadingNewline ? '\n' : '') + `${GITIGNORE_ENTRY}\n`,
- );
- return { action: 'appended', path: gitignorePath };
-}
-
-export function runVerifyInstall(options: VerifyInstallOptions): VerifyInstallResult {
- const bundled = locateBundledSkill(SKILL_NAME);
- const cwd = options.cwd;
-
- let targets: string[];
- if (options.target) {
- const resolved = path.resolve(cwd, options.target);
- mkdirSync(resolved, { recursive: true });
- targets = [resolved];
- } else {
- targets = findHarnessDirs(cwd);
- if (targets.length === 0) throw new NoHarnessDirError(cwd);
- }
-
- const results = targets.map((dir) => installOne(dir, bundled, options.force, cwd));
- const isGitRepo = existsSync(path.join(cwd, '.git'));
- const gitignore = ensureGitignore(cwd);
-
- return { bundled, gitignore, isGitRepo, results };
-}
-
-export function isVerifyInstallSuccess(results: InstallResult[]): boolean {
- return results.some((r) => r.status !== 'refused');
-}
-
-// ── Command Registration ───────────────────────────────────
-
-const STATUS_GLYPH: Record<InstallStatus, string> = {
- 'installed': pc.green('✓ installed'),
- 'no-op': pc.dim('· no-op'),
- 'refused': pc.red('✗ refused'),
- 'updated': pc.yellow('↑ updated'),
-};
-
-export function registerVerifyInstallCommand(verify: Command) {
- verify
- .command('install')
- .description(
- "Install the bundled agent-testing skill into this repo's agent skill dirs (.claude/.codex/.agents)",
- )
- .option('--target <dir>', 'Install into a specific directory instead of auto-detecting')
- .option('--force', 'Replace an existing install even without a recognized version marker')
- .option('--json [fields]', 'Output JSON')
- .action(async (options: { force?: boolean; json?: boolean | string; target?: string }) => {
- let result: VerifyInstallResult;
- try {
- result = runVerifyInstall({
- cwd: process.cwd(),
- force: options.force,
- target: options.target,
- });
- } catch (e) {
- if (e instanceof NoHarnessDirError) {
- log.error(e.message);
- process.exit(1);
- return;
- }
- throw e;
- }
-
- const success = isVerifyInstallSuccess(result.results);
-
- if (options.json !== undefined) {
- outputJson(result, typeof options.json === 'string' ? options.json : undefined);
- process.exit(success ? 0 : 1);
- return;
- }
-
- for (const r of result.results) {
- console.log(
- `${STATUS_GLYPH[r.status]} ${pc.dim(path.relative(process.cwd(), r.target) || r.target)} ${pc.dim(`— ${r.message}`)}`,
- );
- }
-
- if (!result.isGitRepo) {
- console.log(
- pc.yellow(' (not a git repository — .records/ hygiene must be handled manually)'),
- );
- }
- if (result.gitignore.action !== 'no-op') {
- console.log(
- pc.dim(
- ` .gitignore ${result.gitignore.action === 'created' ? 'created with' : 'updated with'} ${GITIGNORE_ENTRY}`,
- ),
- );
- }
-
- console.log(
- pc.dim(
- ' First verification run bootstraps .agents/verify/PROJECT.md — see the skill docs.',
- ),
- );
-
- if (!success) process.exit(1);
- });
-}
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index da6ab1d8e44..190e4e2ef1b 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -1,4 +1,4 @@
-import { VerifySkill } from '@lobechat/builtin-skills';
+import { AcceptanceSkill } from '@lobechat/builtin-skills';
import {
normalizeVerifySurface,
verifyRunScenarios,
@@ -45,13 +45,17 @@ import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManag
/**
* Skills that `verify.getSkillBundle` will materialize to a builder's disk via
- * `lh verify init`. Keyed by identifier; add future pullable skills here. The
- * portable verify skill lives in @lobechat/builtin-skills but is intentionally
+ * `lh acceptance init`. Keyed by identifier; add future pullable skills here. The
+ * portable acceptance skill lives in @lobechat/builtin-skills but is intentionally
* NOT in its `builtinSkills` runtime array (kept out of the homogeneous agent
* runtime / tool picker), so it is referenced directly here.
+ *
+ * The legacy `verify` identifier is kept as an alias so cached callers passing
+ * `--skill verify` still resolve during the deprecation window.
*/
-const PULLABLE_SKILLS: Record<string, typeof VerifySkill> = {
- [VerifySkill.identifier]: VerifySkill,
+const PULLABLE_SKILLS: Record<string, typeof AcceptanceSkill> = {
+ [AcceptanceSkill.identifier]: AcceptanceSkill,
+ verify: AcceptanceSkill,
};
const verifierTypeSchema = z.enum(['program', 'agent', 'llm']);
diff --git a/packages/builtin-skills/src/verify/SKILL.md b/packages/builtin-skills/src/acceptance/SKILL.md
similarity index 90%
rename from packages/builtin-skills/src/verify/SKILL.md
rename to packages/builtin-skills/src/acceptance/SKILL.md
index bf256de4c69..a6c5743379d 100644
--- a/packages/builtin-skills/src/verify/SKILL.md
+++ b/packages/builtin-skills/src/acceptance/SKILL.md
@@ -1,11 +1,11 @@
---
-name: verify
+name: acceptance
description: >
Self-evidence for task delivery verification. When you run a task that has a
verify plan, this skill is the full operating manual: what to prove, which
surface to prove it on (CLI / web / desktop), how to drive that surface with
agent-browser, how to get past auth, and how to submit each artifact with
- `lh verify submit` so the delivery is judged on real proof — not your
+ `lh acceptance run result submit` so the delivery is judged on real proof — not your
word that it works. Triggers on 'verify the task', 'collect evidence', 'prove
it works', 'upload evidence', 'verify plan', 'requiredEvidence', or any run
that must self-certify its delivery.
@@ -31,7 +31,7 @@ no local report directory.
## Prerequisites
-- **`lh` is authed.** Confirm with `lh verify run list --json` (an empty `[]`
+- **`lh` is authed.** Confirm with `lh acceptance run list --json` (an empty `[]`
means authed; an auth error means stop and surface it).
- **You know your operation id.** It is provided as `$LOBE_OPERATION_ID` in the
environment (or named in your task prompt). Every command below keys off it.
@@ -50,7 +50,7 @@ lh verify plan state "$LOBE_OPERATION_ID" --json
Each `verifyPlan[]` item carries `id` (the **checkItemId**), `title`, `required`,
and `verifierConfig.requiredEvidence` (`[{ type, hint }]` — the artifacts you MUST
-capture). The `checkItemId` is the only handle you need: `lh verify submit` (Step 3)
+capture). The `checkItemId` is the only handle you need: `lh acceptance run result submit` (Step 3)
keys off it plus your operation id and creates the result row for you, so you do
**not** need a `checkResultId` up front. (Result rows generally don't exist yet at
this point — that's expected.) Exact shapes:
@@ -91,19 +91,19 @@ Rules of thumb:
Capture each required `type` (recipes per surface in
[references/evidence.md](references/evidence.md)), then submit one artifact per
-call with the criterion's `checkItemId`. `lh verify submit` resolves your session
+call with the criterion's `checkItemId`. `lh acceptance run result submit` resolves your session
from the operation id, lazily creates/updates the result row, and attaches the
evidence — one call, no `checkResultId` needed:
```bash
# CHECK_ITEM_ID is the plan item id for this criterion (from Step 1).
# file artifact (screenshot / dom / video)
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type screenshot --file ./proof/login.png --by agent-browser \
--desc "Logged-in home renders the workspace switcher"
# inline text artifact (stdout / computed value) — no file
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type text --content "$(your-cli command --json)" --by cli \
--desc "command reports success after the change"
```
@@ -122,8 +122,8 @@ is present. After submitting, the result rows exist, so map each `checkItemId` t
its `checkResultId` and list that row's evidence:
```bash
-lh verify result list --operation "$LOBE_OPERATION_ID" --json # checkItemId → checkResultId
-lh verify evidence list "$CHECK_RESULT_ID" --json
+lh acceptance run result list --operation "$LOBE_OPERATION_ID" --json # checkItemId → checkResultId
+lh acceptance run evidence list "$CHECK_RESULT_ID" --json
```
Coverage rule: for each required criterion, **every** `requiredEvidence[].type`
@@ -149,13 +149,13 @@ agent-browser --session app wait --text "Beta features"
agent-browser --session app screenshot ./proof/settings-beta.png
# 3. submit: creates the result row + attaches the screenshot in one call
-lh verify submit --operation "$OP" --item vci_settings --type screenshot \
+lh acceptance run result submit --operation "$OP" --item vci_settings --type screenshot \
--file ./proof/settings-beta.png --by agent-browser \
--desc "Settings page renders the new Beta features toggle"
# 4. self-check
-lh verify result list --operation "$OP" --json # → { checkItemId: vci_settings, id: vcr_77 }
-lh verify evidence list vcr_77 --json # → one screenshot present → 1/1 covered
+lh acceptance run result list --operation "$OP" --json # → { checkItemId: vci_settings, id: vcr_77 }
+lh acceptance run evidence list vcr_77 --json # → one screenshot present → 1/1 covered
```
## Portability rules
diff --git a/packages/builtin-skills/src/verify/index.ts b/packages/builtin-skills/src/acceptance/index.ts
similarity index 67%
rename from packages/builtin-skills/src/verify/index.ts
rename to packages/builtin-skills/src/acceptance/index.ts
index 5e242fad5a3..13befacbe38 100644
--- a/packages/builtin-skills/src/verify/index.ts
+++ b/packages/builtin-skills/src/acceptance/index.ts
@@ -13,31 +13,31 @@ import electron from './surfaces/electron.md';
import native from './surfaces/native.md';
import web from './surfaces/web.md';
-export const VerifyIdentifier = 'verify';
+export const AcceptanceIdentifier = 'acceptance';
/**
- * Portable builder-side verify skill. Unlike the repo-local `agent-testing`
+ * Portable builder-side acceptance skill. Unlike the repo-local `agent-testing`
* skill (macOS scripts + local report dirs + LobeHub-specific probes), this one
* depends only on the `lh` CLI and `agent-browser`, so any external builder
* (Claude Code / Codex) can run it from a task's working directory: discover the
- * plan → pick a surface → capture evidence per criterion → `lh verify
- * submit` → self-check coverage.
+ * plan → pick a surface → capture evidence per criterion → `lh acceptance run
+ * result submit` → self-check coverage.
*
* The references carry the full operating manual (agent-browser CLI, web vs
* Electron decision + setup, auth recipes, capture recipes), with all
* LobeHub-only coupling generalized away.
*
- * Resource keys keep the `.md` extension so a disk pull (`.claude/skills/verify/
- * references/*.md`) maps 1:1 to real files and the in-SKILL relative links
- * resolve.
+ * Resource keys keep the `.md` extension so a disk pull
+ * (`.agents/skills/acceptance/references/*.md`) maps 1:1 to real files and the
+ * in-SKILL relative links resolve.
*/
-export const VerifySkill: BuiltinSkill = {
+export const AcceptanceSkill: BuiltinSkill = {
avatar: '✅',
content,
description:
- 'Self-evidence for task delivery verification — discover the verify plan, pick the right surface (CLI / web / desktop), drive it with agent-browser, get past auth, capture portable evidence per criterion, and submit each with `lh verify submit` so the delivery is judged on real proof.',
- identifier: VerifyIdentifier,
- name: 'verify',
+ 'Self-evidence for task delivery acceptance — discover the verify plan, pick the right surface (CLI / web / desktop), drive it with agent-browser, get past auth, capture portable evidence per criterion, and submit each with `lh acceptance run result submit` so the delivery is judged on real proof.',
+ identifier: AcceptanceIdentifier,
+ name: 'acceptance',
resources: toResourceMeta({
'references/agent-browser.md': agentBrowser,
'references/auth.md': auth,
diff --git a/packages/builtin-skills/src/verify/references/agent-browser.md b/packages/builtin-skills/src/acceptance/references/agent-browser.md
similarity index 100%
rename from packages/builtin-skills/src/verify/references/agent-browser.md
rename to packages/builtin-skills/src/acceptance/references/agent-browser.md
diff --git a/packages/builtin-skills/src/verify/references/auth.md b/packages/builtin-skills/src/acceptance/references/auth.md
similarity index 100%
rename from packages/builtin-skills/src/verify/references/auth.md
rename to packages/builtin-skills/src/acceptance/references/auth.md
diff --git a/packages/builtin-skills/src/verify/references/computer-use.md b/packages/builtin-skills/src/acceptance/references/computer-use.md
similarity index 100%
rename from packages/builtin-skills/src/verify/references/computer-use.md
rename to packages/builtin-skills/src/acceptance/references/computer-use.md
diff --git a/packages/builtin-skills/src/verify/references/evidence.md b/packages/builtin-skills/src/acceptance/references/evidence.md
similarity index 97%
rename from packages/builtin-skills/src/verify/references/evidence.md
rename to packages/builtin-skills/src/acceptance/references/evidence.md
index b1f29f79755..f5ce6590505 100644
--- a/packages/builtin-skills/src/verify/references/evidence.md
+++ b/packages/builtin-skills/src/acceptance/references/evidence.md
@@ -43,7 +43,7 @@ Backend / CLI behavior is best proven by the command output itself — upload in
no file:
```bash
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
--content "$(your-cli command --json)" \
--by cli --desc "command reports success after the change"
```
diff --git a/packages/builtin-skills/src/verify/references/plan-format.md b/packages/builtin-skills/src/acceptance/references/plan-format.md
similarity index 88%
rename from packages/builtin-skills/src/verify/references/plan-format.md
rename to packages/builtin-skills/src/acceptance/references/plan-format.md
index 66fcb721bce..34fba656d0c 100644
--- a/packages/builtin-skills/src/verify/references/plan-format.md
+++ b/packages/builtin-skills/src/acceptance/references/plan-format.md
@@ -52,11 +52,11 @@ The plan (a) is all you need. For each `verifyPlan[]` item with non-empty
```bash
OP="$LOBE_OPERATION_ID"
-lh verify submit --operation "$OP" --item vci_a1b2c3 --type screenshot \
+lh acceptance run result submit --operation "$OP" --item vci_a1b2c3 --type screenshot \
--file ./proof/home.png --by agent-browser --desc "…"
```
-`lh verify submit` resolves the session from the operation id and **creates the
+`lh acceptance run result submit` resolves the session from the operation id and **creates the
check-result row for you** (idempotent on `checkItemId`), then attaches the
evidence — there is no `checkResultId` to look up first.
@@ -66,7 +66,7 @@ Once you've submitted, the result rows exist. To confirm coverage, read them bac
and list each row's evidence:
```jsonc
-// lh verify result list --operation "$OP" --json
+// lh acceptance run result list --operation "$OP" --json
[
{
"id": "vcr_x9y8z7", // checkResultId (created by submit)
@@ -77,5 +77,5 @@ and list each row's evidence:
```
```bash
-lh verify evidence list "$CHECK_RESULT_ID" --json # confirm each required type is present
+lh acceptance run evidence list "$CHECK_RESULT_ID" --json # confirm each required type is present
```
diff --git a/packages/builtin-skills/src/verify/references/recording.md b/packages/builtin-skills/src/acceptance/references/recording.md
similarity index 94%
rename from packages/builtin-skills/src/verify/references/recording.md
rename to packages/builtin-skills/src/acceptance/references/recording.md
index 359fa572564..8c27caeb2ac 100644
--- a/packages/builtin-skills/src/verify/references/recording.md
+++ b/packages/builtin-skills/src/acceptance/references/recording.md
@@ -80,11 +80,11 @@ ffmpeg -y -i ./proof/demo.mp4 \
## Upload
```bash
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type gif \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type gif \
--file ./proof/flow.gif --by agent-browser \
--desc "Response streams in token-by-token after send"
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type video \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type video \
--file ./proof/demo.mp4 --by cdp --desc "End-to-end import flow completes"
```
diff --git a/packages/builtin-skills/src/verify/surfaces/cli.md b/packages/builtin-skills/src/acceptance/surfaces/cli.md
similarity index 88%
rename from packages/builtin-skills/src/verify/surfaces/cli.md
rename to packages/builtin-skills/src/acceptance/surfaces/cli.md
index fb5f848d3e1..90a6aecb07f 100644
--- a/packages/builtin-skills/src/verify/surfaces/cli.md
+++ b/packages/builtin-skills/src/acceptance/surfaces/cli.md
@@ -19,18 +19,18 @@ only when the criterion is actually about rendered UI.
```bash
# CHECK_ITEM_ID is the criterion's plan item id (from `lh verify plan state`).
# short result → inline
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
--content "$(your-cli command --json)" \
--by cli --desc "command reports the new field after the change"
# larger output (test log, full dump) → file
your-cli command --json > ./proof/result.json
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
--file ./proof/result.json --by cli --desc "full result set"
# a test run is itself proof
your-test-runner path/to/spec > ./proof/test.log 2>&1
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
--file ./proof/test.log --by program --desc "regression spec passes"
```
diff --git a/packages/builtin-skills/src/verify/surfaces/electron.md b/packages/builtin-skills/src/acceptance/surfaces/electron.md
similarity index 100%
rename from packages/builtin-skills/src/verify/surfaces/electron.md
rename to packages/builtin-skills/src/acceptance/surfaces/electron.md
diff --git a/packages/builtin-skills/src/verify/surfaces/native.md b/packages/builtin-skills/src/acceptance/surfaces/native.md
similarity index 95%
rename from packages/builtin-skills/src/verify/surfaces/native.md
rename to packages/builtin-skills/src/acceptance/surfaces/native.md
index f8e0de5c705..89b57b892d7 100644
--- a/packages/builtin-skills/src/verify/surfaces/native.md
+++ b/packages/builtin-skills/src/acceptance/surfaces/native.md
@@ -33,7 +33,7 @@ Upload as evidence (provenance `cli`, since osascript/screencapture are
shell-driven):
```bash
-lh verify submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type screenshot \
+lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type screenshot \
--file ./proof/native-result.png --by cli \
--desc "Native app shows the expected state after the change"
```
diff --git a/packages/builtin-skills/src/verify/surfaces/web.md b/packages/builtin-skills/src/acceptance/surfaces/web.md
similarity index 100%
rename from packages/builtin-skills/src/verify/surfaces/web.md
rename to packages/builtin-skills/src/acceptance/surfaces/web.md
diff --git a/packages/builtin-skills/src/index.ts b/packages/builtin-skills/src/index.ts
index 3feb085ea18..7d11c1c64bf 100644
--- a/packages/builtin-skills/src/index.ts
+++ b/packages/builtin-skills/src/index.ts
@@ -7,6 +7,8 @@ import { TaskSkill } from './task';
export { AgentBrowserIdentifier } from './agent-browser';
export { ArtifactsIdentifier } from './artifacts';
+export { LobeHubIdentifier } from './lobehub';
+export { TaskIdentifier } from './task';
export {
buildReactArtifactProject,
REACT_ARTIFACT_APP_PATH,
@@ -24,18 +26,16 @@ export {
type ReactArtifactTemplateOptions,
type ReactArtifactTemplateOverrides,
} from '@lobechat/artifact-template';
-export { LobeHubIdentifier } from './lobehub';
-export { TaskIdentifier } from './task';
/**
* The portable verify skill is distributed to external builders (Claude Code /
- * Codex) by pulling it to disk (`lh verify init`), NOT by loading it into the
+ * Codex) by pulling it to disk (`lh acceptance install`), NOT by loading it into the
* homogeneous agent runtime. So it is exported as a named skill for the pull
* endpoint to import directly, but deliberately left OUT of `builtinSkills`
* below — keeping it out of every app-layer consumer of that array (server
* runtime, agentDocumentVfs, tool store / picker).
*/
-export { VerifyIdentifier, VerifySkill } from './verify';
+export { AcceptanceIdentifier, AcceptanceSkill } from './acceptance';
export const builtinSkills: BuiltinSkill[] = [
AgentBrowserSkill,
diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.ts
index 84a512effbd..153882a624e 100644
--- a/packages/prompts/src/prompts/task/index.test.ts
+++ b/packages/prompts/src/prompts/task/index.test.ts
@@ -398,7 +398,7 @@ describe('buildTaskRunPrompt', () => {
expect(result).toContain('login page renders (required)');
expect(result).toContain('· evidence: screenshot — full page');
expect(result).toContain('console is clean');
- expect(result).toContain('lh verify');
+ expect(result).toContain('lh acceptance run result submit');
});
it('should omit the verify section when verify is disabled', () => {
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index e8e33106bfe..0bab01c85f7 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -593,11 +593,9 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
}
}
}
+ taskLines.push(' Use the `acceptance` skill to capture each artifact, then submit it with');
taskLines.push(
- ' Use the `verify` skill to capture each artifact, then submit it with `lh verify',
- );
- taskLines.push(
- ' submit` (the skill resolves your verify run id and check item ids at runtime).',
+ ' `lh acceptance run result submit` (the skill resolves your run id and check item ids at runtime).',
);
}