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(acceptance): converge agent-testing into the acceptance skill (#18830)

Arvin Xuf23693b12124
diff --git a/.agents/acceptance/PROCESS.md b/.agents/acceptance/PROCESS.md
new file mode 100644
index 00000000000..e88ca64e677
--- /dev/null
+++ b/.agents/acceptance/PROCESS.md
@@ -0,0 +1,263 @@
+# PROCESS.md โ€” how a verification run works in LobeHub
+
+The `acceptance` skill owns the **contract**: what a check is, what counts as
+evidence, what a report and an immutable round look like. This file owns the
+**process**: how a run is planned, approved, executed, published, and torn down
+in this repository. [`PROJECT.md`](./PROJECT.md) owns the **commands**: ports,
+services, auth, surfaces, probes.
+
+Read all three. Where this file and the skill disagree about _how to run_, this
+file wins; about _what may be published_, the skill wins.
+
+```text
+PLAN (0โ€“2) โ†’ EXECUTE (3โ€“5) โ†’ FINISH (6)
+```
+
+Do not enter Execute until Plan has confirmed both the environment state and the
+plan. Loading skills and reading logs is silent preparation โ€” never narrate it.
+The first user-visible message of a session is about the user's test, not setup.
+
+## Phase 1 โ€” Plan
+
+### Step 0 โ€” Ground the target, then read the living logs
+
+**A test target must exist before anything else happens.** With no target in the
+invocation:
+
+1. Take it from the user's words in this conversation when they exist โ€” the task
+ lives in their words, not in git.
+2. Otherwise infer the likeliest candidate from the branch, recent commits, and
+ working-tree changes, and confirm it with one structured question, the guess
+ labeled as a guess. Never execute against an unconfirmed guess.
+3. Only when nothing is inferable, ask one direct open question.
+
+**Once the target is known**, read both layers of both living logs in full:
+
+- Generic (ships with the skill, read-only here):
+ `.agents/skills/acceptance/references/common-mistakes.md` and
+ `probe-mock-patterns.md`.
+- Project (writable, ours): [`common-mistakes.md`](./common-mistakes.md) and
+ [`probe-mock-patterns.md`](./probe-mock-patterns.md).
+
+Two that keep biting: never declare a case `passed` from grep or skeleton counts
+โ€” open the screenshot with Read and confirm it rendered; and when the goal is an
+error state, do not settle for happy-path because injection was hard.
+
+**The project layer is a curated log, not a transcript of review feedback.**
+Every piece of negative feedback triggers this admission check, and a candidate
+passing all five is recorded automatically โ€” no separate user request needed:
+
+1. **Durable** โ€” would it recur in a different feature or a later round?
+2. **Project-specific** โ€” does it depend on this product's semantics, environment,
+ or infrastructure? If not, genericize it and PR it to the skill source instead.
+3. **Invariant-level** โ€” does it state the behavior or evidence contract rather
+ than freezing one solution? Exact copy, pixel values, icon choices, and
+ annotation coordinates belong in a spec, the component, or a regression test.
+4. **Non-duplicative** โ€” search both layers first; amend an existing case when the
+ underlying failure is the same.
+5. **Actionable** โ€” can a future verifier choose a different action or reject
+ invalid evidence with it? Product taste and incident narrative cannot.
+
+A candidate that fails only for being too implementation-specific gets routed:
+product behavior to the spec, UI values to the component, regressions to a test,
+long incident context to `references/probe-field-notes.md`. Do not skip the
+recording merely because it requires abstracting the feedback first.
+
+### Step 1 โ€” Prepare the plan
+
+Skip to Step 2 if this is a re-run after a fix, the plan is already agreed, or
+the user gave exact commands.
+
+Draft the surface, cases, expected evidence, assumptions, and deliverable โ€” but
+do not ask for approval yet: Step 2 must establish real environment state first,
+so the user approves one complete, evidence-backed plan.
+
+Every case must be a delivery outcome a person can judge. Never plan the repo's
+own programmatic gates (tests, coverage, type-check, lint, build) โ€” ingest drops
+them and a gates-only round fails to publish.
+
+### Step 2 โ€” Environment and auth
+
+Concrete commands come from [`PROJECT.md`](./PROJECT.md); the rules below hold
+regardless.
+
+1. **Resolve the environment first** (ยง2). Read ports and base URLs from the
+ project's own env resolver โ€” never a hard-coded port table. If the resolved
+ values do not match a running dev server, fix the env before continuing.
+2. **Dependencies** (ยง2, ยง6). A root install does not cover `apps/desktop` or
+ `apps/cli`; install in each standalone app the run will touch. A stale
+ standalone install fails at launch with an unresolved workspace import.
+3. **Run long-lived scripts from the repo root.** Background commands inherit the
+ cwd, and every path here is repo-root-relative.
+4. **Start the environment** (ยง2), including every service the feature depends on
+ โ€” a queue, cache, or object store the code path dispatches to is a hard
+ prerequisite, not a nicety. Prefer the user's already-running config; never
+ clobber it.
+5. **Auth, scoped to the selected surface** (ยง3). Inject login state directly
+ (seeded session, cookie/state restore, CLI-minted token). **Never drive an
+ interactive login/OAuth flow** โ€” it hijacks the user's browser session. With no
+ injectable state, report โŒ Blocked and name the exact blocking step.
+6. **Screen-recording preflight, only for OS-capture surfaces.** macOS
+ `screencapture`/osascript returns a fully black frame when Screen Recording
+ permission is missing _or_ the display is asleep. Gate on
+ `.agents/acceptance/scripts/check-screen-recording.sh` (exit 0 = safe), and keep
+ the display awake for the session with `caffeinate -dimsu &`. CDP capture
+ (`agent-browser screenshot`, `cdp-screenshot.sh`, `record-app-screen.sh`) is
+ unaffected.
+
+### The approval gate
+
+At the end of Step 2, for the **first run against a subject Acceptance**, send one
+plan feedback and one structured confirmation question. Format, status markers,
+and confirmation behavior: [`references/plan-feedback.md`](./references/plan-feedback.md).
+
+That approval covers later iterations on the same Acceptance. On follow-up
+feedback: read the Acceptance, silently re-check environment and auth, repair,
+re-run the affected checks, and publish a new round โ€” no second approval. Ask
+again only on a **material boundary change**: a new surface, external system,
+account, secret, permission, or destructive action; a materially changed business
+goal; a user-owned blocker; or an environment change that invalidates the approved
+evidence strategy. Code revisions, restarts, recaptures, retries, and new rounds
+are not material changes.
+
+## Phase 2 โ€” Execute
+
+### Step 3 โ€” Pick the surface
+
+| Change scope | Surface | Why |
+| ---------------------------------------------- | ------------ | --------------------------------------------------- |
+| Backend (router / service / model / migration) | **CLI** | Fastest loop, text-assertable, no UI flakiness |
+| Pure frontend (components, store, styles, UX) | **Electron** | The primary product shape; live state introspection |
+| Full-stack (new API + the UI consuming it) | **Web** | Network and UI observable together |
+
+Launch commands per surface are in `PROJECT.md` ยง4; the operating manual for each
+is in the skill's `surfaces/`. Escalate, don't duplicate: verify a backend change
+with the CLI first, and add a UI pass only when the change reaches the UI.
+
+**Separate the driver from the evidence surface.** Producing the state under test
+and capturing the evidence are independent choices. Drive with the cheapest
+deterministic path the repo offers (a CLI command, an endpoint call, a seed
+script โ€” `PROJECT.md` ยง4/ยง5); use the evidence surface only for what it alone can
+prove. Typing a long prompt through browser automation when a CLI driver exists is
+slower, flakier, and no more authentic โ€” the server-side state is identical. The
+converse also holds: a CLI-driven state still needs UI evidence when the claim is
+about rendering.
+
+**Prove which runtime actually ran.** Several features have two execution paths and
+the UI picks one silently (client runtime vs server/queue runtime). A test that
+exercises the wrong path passes green without touching the code under test. Confirm
+with a server-side operation row, a queue step, or a server-only log line; if the UI
+will not take the intended path, call the server endpoint directly.
+
+### Step 4 โ€” Run
+
+Project scripts live in `.agents/acceptance/scripts/` and are described in
+`PROJECT.md` ยง5. The generic capture toolchain:
+
+| Script | Use |
+| --------------------------- | ------------------------------------------------------------------- |
+| `report-init.sh` | Scaffold a report directory grouped by acceptance subject |
+| `fixture.mjs` | Per-check fixtures: `init-check`, `list`, `compose` |
+| `record-gif.sh` | Frame sequence โ†’ GIF for time-based behavior |
+| `check-screen-recording.sh` | Preflight for OS capture (permission + display awake) |
+| `cdp-screenshot.sh` | Electron/Chrome screenshot over raw CDP (bypasses the daemon) |
+| `capture-app-window.sh` | Screenshot one app window (macOS OS capture) |
+| `record-app-screen.sh` | Record an app screen (CDP frames โ†’ video + gallery) |
+| `agent-browser-klm.mjs` | Wrap an `agent-browser` action and append its interaction-cost atom |
+
+macOS automation patterns: [`references/osascript.md`](./references/osascript.md).
+Screen recording: [`references/record-app-screen.md`](./references/record-app-screen.md).
+
+**Interaction cost (optional, UI runs).** Drive cost-bearing actions through the
+KLM wrapper so each one also records a user-equivalent atom:
+
+```bash
+TRACE="$DIR/interaction-trace.jsonl"
+
+.agents/acceptance/scripts/agent-browser-klm.mjs \
+ --klm-trace "$TRACE" --klm-phase login --klm-check case-1 \
+ --session "$SESSION" click @e3
+
+.agents/acceptance/scripts/agent-browser-klm.mjs mental \
+ --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \
+ --confidence 0.75 --reason "First view requires reading state and choosing the next action"
+```
+
+Leave the trace in the report directory โ€” `acceptance run ingest` prices it with
+the platform's timing model. There is no analyze step, and no cost is published
+when no trace exists. Contract:
+`.agents/skills/acceptance/references/interaction-cost.md`.
+
+### Step 5 โ€” Report and publish
+
+The report schema, the language rule, visual/dual-text/structured-visualization
+evidence rules, and the immutable-round rules are the skill's
+`references/report.md`. **Read it before writing the first line of
+`result.json`** โ€” a field in the wrong shape is dropped on ingest, so the round
+publishes green with its evidence silently degraded.
+
+What is specific to this repository:
+
+- **Reports live in `.records/reports/<subject-key>/<timestamp>-<slug>/`**
+ (gitignored), grouped by acceptance subject; the subject directory holds an
+ `acceptance.json` marker and one subdirectory per immutable round. Scaffold with
+ `report-init.sh --subject topic:tpc_xxx <slug> "<title>"`, which also pre-fills
+ `result.json.subject`.
+
+- **Reusable per-check inputs** live in `.records/fixtures/<subject-key>/<check-id>/`
+ (`check.json` + `seed/`). Execution outputs stay in the round's `assets/` and are
+ never copied back into a fixture.
+
+- **Publish against PRODUCTION defaults, not the local dev profile.** The product
+ under test runs locally, but publishing there yields a URL nobody can open and a
+ stub bucket that silently drops evidence uploads. Strip the local overrides:
+
+ ```bash
+ env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
+ lh acceptance run ingest "$DIR" --source agent-testing --subject "$SUBJECT" \
+ --requirement "$REQUIREMENT" --open --json
+ ```
+
+ Verify auth in the same clean env first; if it reports no authentication, have
+ the user run `lh login`. If a publish flag is rejected as an unknown option, the
+ `lh` on PATH is stale โ€” publish through `npx @lobehub/cli@latest` instead.
+
+- **Choose the subject by business continuity**, not by what is easiest to create:
+ an explicit instruction first; else the current conversation's `topic:<id>` (the
+ default for iterative fixes and review follow-ups); else an existing `task:<id>`
+ that already owns the deliverable; else `document:<id>` when the document is the
+ subject; and only then a new Task via `lh task create`. When the run was started
+ from a conversation, ingest attaches to it on its own โ€” pass `--subject` only to
+ override that, and never ask the user for an id the CLI already resolves. A
+ terminal Acceptance on the right Topic means a **new Acceptance on that same
+ Topic**, never a new Task invented to dodge it.
+
+- **Before a follow-up round**, read the current state rather than memory:
+ `lh acceptance view "$SUBJECT" --json`. Omit accepted checks, repair non-stale
+ rejects under their exact stable ids, and carry every `supersedes` chain forward.
+
+- **The final reply exposes only `https://app.lobehub.com/acceptance/<id>`** (add
+ `?r=<roundIndex>` for this round's snapshot). No images, local paths, or internal
+ run-page paths. Leave whitespace between the URL and any following text โ€” CJK
+ punctuation glued to it gets swallowed into the href.
+
+## Phase 3 โ€” Finish
+
+### Step 6 โ€” Teardown
+
+Default: stop what you started. A dev server left listening or an injection left
+in a source file corrupts the next run and the next agent's mental model.
+
+- **Stop only what THIS run started**, using `PROJECT.md` ยง2 stop commands. Never a
+ global process-name kill; never a listener you did not launch. A dev server the
+ user started stays up.
+- **Revert every code injection.** Restore the file and verify: `grep -rn AGENT-TEST`
+ returns nothing. 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.
+- **Keep the report and its evidence.** `.records/reports/**` is the deliverable and
+ is gitignored; the published round points at it.
+- **Check `git status` before calling the tree clean.** Some dev servers write
+ managed files on start.
+
+Skip teardown only when the user explicitly wants the environment left running.
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index d050bdb53d2..90b54ad14c3 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -1,12 +1,20 @@
-# PROJECT.md โ€” agent-testing adapter for LobeHub
+# PROJECT.md โ€” acceptance adapter for LobeHub
-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.
+This file is the **commands** layer of LobeHub's acceptance setup: every
+LobeHub-specific command, port, service, surface, and probe. The `acceptance`
+skill reads it โ€” it never guesses LobeHub's commands.
-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/`.
+Its two siblings:
+
+- [`PROCESS.md`](./PROCESS.md) โ€” the run process (approval gate, execution rules,
+ publishing, teardown).
+- `.agents/skills/acceptance/` โ€” the portable skill: what a check, evidence,
+ report, and round are. In this repository that path is a symlink onto the
+ skill's source, `packages/builtin-skills/src/acceptance/`.
+
+Every script referenced below lives under `.agents/acceptance/scripts/`, including
+the generic capture toolchain (`report-init.sh`, `cdp-screenshot.sh`,
+`record-gif.sh`, `check-screen-recording.sh`, โ€ฆ).
## 1. Project summary
@@ -336,7 +344,7 @@ in `.agents/acceptance/references/agent-gateway.md`.
- **OS-capture surfaces are macOS-only** (bot channels, `capture-app-window.sh`,
osascript screenshots): they come out black without Screen Recording (TCC)
permission or when the display is asleep/locked. CDP-based evidence
- (`agent-browser screenshot`, the installed skill's `cdp-screenshot.sh`) is
+ (`agent-browser screenshot`, `.agents/acceptance/scripts/cdp-screenshot.sh`) is
unaffected. Electron runs on Linux/cloud only under `xvfb-run`, and there OS
capture does not work โ€” prefer CDP evidence for cloud-portable runs.
diff --git a/.agents/acceptance/references/auth.md b/.agents/acceptance/references/auth.md
index 054a3f4efb6..caa0bd9b574 100644
--- a/.agents/acceptance/references/auth.md
+++ b/.agents/acceptance/references/auth.md
@@ -1,7 +1,7 @@
# Auth Setup for Local Agent Testing
**Auth is the gate for all automated testing.** Complete
-[Step 2.0](../../skills/agent-testing/SKILL.md#20-resolve-the-current-test-environment) first so
+[PROCESS.md Step 2](../PROCESS.md#step-2--environment-and-auth) first so
`SERVER_URL` and ports are resolved, then verify auth before writing any test
step.
diff --git a/.agents/acceptance/references/dev-server.md b/.agents/acceptance/references/dev-server.md
index b0686795edf..7c53d4c5181 100644
--- a/.agents/acceptance/references/dev-server.md
+++ b/.agents/acceptance/references/dev-server.md
@@ -6,7 +6,7 @@ surfaces (CLI, Electron, Web) hit.
## Resolve ports first
Run `test-env.sh` as described in
-[SKILL.md Step 2.0](../../skills/agent-testing/SKILL.md#20-resolve-the-current-test-environment)
+[PROCESS.md Step 2](../PROCESS.md#step-2--environment-and-auth)
before starting or probing any local test surface.
## Ports & modes
diff --git a/.agents/skills/agent-testing/references/osascript.md b/.agents/acceptance/references/osascript.md
similarity index 100%
rename from .agents/skills/agent-testing/references/osascript.md
rename to .agents/acceptance/references/osascript.md
diff --git a/.agents/skills/agent-testing/references/plan.md b/.agents/acceptance/references/plan-feedback.md
similarity index 65%
rename from .agents/skills/agent-testing/references/plan.md
rename to .agents/acceptance/references/plan-feedback.md
index 34eef9ef985..df056a47029 100644
--- a/.agents/skills/agent-testing/references/plan.md
+++ b/.agents/acceptance/references/plan-feedback.md
@@ -1,6 +1,6 @@
-# Phase 1 Plan Feedback
+# Phase 1 plan feedback
-Use this template at the end of Phase 1. Match the user's conversation language.
+Use this template at the end of Phase 1 (see [`../PROCESS.md`](../PROCESS.md)). Match the user's conversation language.
Keep it concrete and compact: report observed state, not generic readiness claims.
## Readiness verdicts
@@ -69,46 +69,19 @@ Do not include irrelevant environment rows. Add a row when the run has another h
prerequisite, such as a native app, gateway, fixture repository, or specific
external account.
-## Case selection gate (hard rule)
-
-Every planned case MUST be a delivery outcome a person can judge โ€” what the
-user sees, hears, reads, or receives. **Never plan a case whose subject is the
-repo's own programmatic gate**: unit / integration / regression tests, test
-suites, coverage, type-check, lint, format, or a clean build. Run those gates as
-part of your own diligence and report them as one line of narrative in
-`report.md` โ†’ Verification โ€” they are preconditions of shipping, not things the
-user accepts, and `lh acceptance run ingest` drops them from the round (a
-gates-only round fails to publish entirely). A plan feedback that lists such a
-case wastes the user's approval on a row that will never reach the page.
-
-The gate is about the check's _subject_, not its verifier: a CLI behavior case
-asserted by a command is a good case (`verifier: "program"`); "`bun run test`
-is green" is not.
-
-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 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']`.
-- Treat `supersedes` as persistent lineage. When a later round reuses a successor
- id, copy its complete historical `supersedes` list into the new plan again.
- Never assume an earlier round made the relationship permanent: the Acceptance
- union uses the latest plan snapshot for that id, so a later omission can split
- the successor and replaced check back into parallel rows.
-- Before publish, compare every reused plan id against `acceptance view`. If its
- latest or historical plan declared `supersedes`, fail the preflight until the
- new plan carries the same complete list (unless this round deliberately creates
- another semantic replacement and declares that new chain explicitly).
+## What a planned case may be
+
+The skill's HARD RULE decides this, and the gate must not propose a case that
+will never reach the page: every case is a delivery outcome a person judges, and
+the repo's own programmatic gates (tests, coverage, type-check, lint, build) are
+never cases โ€” ingest drops them and a gates-only round fails to publish. Run them
+as diligence and report them as one line of narrative.
+
+Seed a follow-up plan from `lh acceptance view <subject> --json`, not from
+memory: omit accepted checks, repair non-stale rejects under their exact stable
+ids, and carry every `supersedes` chain forward unchanged. For every user-visible
+UI case, plan the screenshot or recording that proves that exact claim โ€” program
+output may supplement visual evidence but never replaces it.
## Confirmation behavior
diff --git a/.agents/skills/agent-testing/references/record-app-screen.md b/.agents/acceptance/references/record-app-screen.md
similarity index 90%
rename from .agents/skills/agent-testing/references/record-app-screen.md
rename to .agents/acceptance/references/record-app-screen.md
index 194e292ce88..92db8871426 100644
--- a/.agents/skills/agent-testing/references/record-app-screen.md
+++ b/.agents/acceptance/references/record-app-screen.md
@@ -17,10 +17,10 @@ works under Xvfb and is unaffected by display sleep.
## 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?
+# The target app must be running with CDP exposed.
+.agents/acceptance/scripts/record-app-screen.sh start [output_name] # start recording
+.agents/acceptance/scripts/record-app-screen.sh stop # stop + assemble video
+.agents/acceptance/scripts/record-app-screen.sh status # is recording active?
```
### Arguments
@@ -78,7 +78,7 @@ The `.records/` directory is at the repo root and is gitignored.
# 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
+.agents/acceptance/scripts/record-app-screen.sh start my-test
# 3. Drive the automation
agent-browser --cdp 9222 click @e61
@@ -87,7 +87,7 @@ agent-browser --cdp 9222 press Enter
sleep 10
# 4. Stop and get results
-"$SKILL_DIR/scripts/record-app-screen.sh" stop
+.agents/acceptance/scripts/record-app-screen.sh stop
# โ†’ .records/my-test.mp4 + .records/my-test/*.png
```
diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs b/.agents/acceptance/scripts/agent-browser-klm.mjs
similarity index 100%
rename from .agents/skills/agent-testing/scripts/agent-browser-klm.mjs
rename to .agents/acceptance/scripts/agent-browser-klm.mjs
diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm.test.sh b/.agents/acceptance/scripts/agent-browser-klm.test.sh
similarity index 72%
rename from .agents/skills/agent-testing/scripts/agent-browser-klm.test.sh
rename to .agents/acceptance/scripts/agent-browser-klm.test.sh
index db38f5a79dc..59e042fb361 100755
--- a/.agents/skills/agent-testing/scripts/agent-browser-klm.test.sh
+++ b/.agents/acceptance/scripts/agent-browser-klm.test.sh
@@ -1,12 +1,16 @@
#!/usr/bin/env bash
-# Smoke tests for agent-browser KLM wrapper + analyzer. Uses a stub
-# agent-browser, so no real browser is required.
+# Smoke tests for the agent-browser KLM wrapper. Uses a stub agent-browser, so
+# no real browser is required.
+#
+# Scope: the wrapper's job is to forward the command and append correct operator
+# counts. Turning counts into seconds belongs to the platform
+# (`@lobechat/utils/verify/interactionCost`, exercised by its own unit test) and
+# is deliberately not re-asserted here.
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
@@ -37,11 +41,19 @@ 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'
+node - "$trace" << 'JS'
const fs = require('fs');
-const summary = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
+
+const events = fs
+ .readFileSync(process.argv[2], 'utf8')
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line));
+
+const totals = { H: 0, K: 0, M: 0, P: 0, R_ms: 0, T_chars: 0 };
+for (const event of events) {
+ for (const key of Object.keys(totals)) totals[key] += event.klm?.operators?.[key] ?? 0;
+}
function eq(actual, expected, label) {
if (actual !== expected) {
@@ -49,34 +61,14 @@ function eq(actual, expected, label) {
}
}
-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}`);
-}
+eq(events.length, 4, 'atom count');
+eq(totals.P, 2, 'P');
+eq(totals.K, 1, 'K');
+eq(totals.M, 2, 'M');
+eq(totals.T_chars, 5, 'T_chars');
+eq(totals.R_ms, 2000, 'R_ms');
+eq(events[0].phase.id, 'first', 'first phase');
+eq(events[0].schema, 'lobehub.agentBrowserKlmTrace@1', 'schema tag');
JS
grep -Fq -- "--session app click @e1" "$AGENT_BROWSER_STUB_LOG" || fail "wrapper did not forward click"
diff --git a/.agents/skills/agent-testing/scripts/capture-app-window.sh b/.agents/acceptance/scripts/capture-app-window.sh
similarity index 100%
rename from .agents/skills/agent-testing/scripts/capture-app-window.sh
rename to .agents/acceptance/scripts/capture-app-window.sh
diff --git a/.agents/skills/agent-testing/scripts/cdp-capture.cjs b/.agents/acceptance/scripts/cdp-capture.cjs
similarity index 65%
rename from .agents/skills/agent-testing/scripts/cdp-capture.cjs
rename to .agents/acceptance/scripts/cdp-capture.cjs
index 0bc6a5142e2..26144976d68 100755
--- a/.agents/skills/agent-testing/scripts/cdp-capture.cjs
+++ b/.agents/acceptance/scripts/cdp-capture.cjs
@@ -9,64 +9,29 @@
// 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. An installed
-// 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`.
+// Requires the `ws` package. The script lives in this repo's own
+// `.agents/acceptance/scripts/`, so Node's ancestor node_modules walk reaches the
+// workspace root โ€” no NODE_PATH wiring, and an unresolvable `ws` means the repo's
+// dependencies simply are not installed.
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' from " +
+ __filename +
+ '. Install the repository dependencies (pnpm install) and retry.',
+ }),
+ );
+ process.exit(7);
}
-
- 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();
diff --git a/.agents/skills/agent-testing/scripts/cdp-screenshot.sh b/.agents/acceptance/scripts/cdp-screenshot.sh
similarity index 100%
rename from .agents/skills/agent-testing/scripts/cdp-screenshot.sh
rename to .agents/acceptance/scripts/cdp-screenshot.sh
diff --git a/.agents/skills/agent-testing/scripts/check-screen-recording.sh b/.agents/acceptance/scripts/check-screen-recording.sh
similarity index 100%
rename from .agents/skills/agent-testing/scripts/check-screen-recording.sh
rename to .agents/acceptance/scripts/check-screen-recording.sh
diff --git a/.agents/skills/agent-testing/scripts/fixture.mjs b/.agents/acceptance/scripts/fixture.mjs
similarity index 100%
rename from .agents/skills/agent-testing/scripts/fixture.mjs
rename to .agents/acceptance/scripts/fixture.mjs
diff --git a/.agents/skills/agent-testing/scripts/record-app-screen.sh b/.agents/acceptance/scripts/record-app-screen.sh
similarity index 100%
rename from .agents/skills/agent-testing/scripts/record-app-screen.sh
rename to .agents/acceptance/scripts/record-app-screen.sh
diff --git a/.agents/skills/agent-testing/scripts/record-gif.sh b/.agents/acceptance/scripts/record-gif.sh
similarity index 100%
rename from .agents/skills/agent-testing/scripts/record-gif.sh
rename to .agents/acceptance/scripts/record-gif.sh
diff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/acceptance/scripts/report-init.sh
similarity index 99%
rename from .agents/skills/agent-testing/scripts/report-init.sh
rename to .agents/acceptance/scripts/report-init.sh
index 146ae932619..23aa838a249 100755
--- a/.agents/skills/agent-testing/scripts/report-init.sh
+++ b/.agents/acceptance/scripts/report-init.sh
@@ -125,7 +125,6 @@ cat > "$DIR/result.json" << EOF
"entry": "",
"plan": [],
"cases": [],
- "interactionCost": null,
"summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending", "conclusion": "", "score": null }
}
EOF
diff --git a/.agents/skills/acceptance b/.agents/skills/acceptance
new file mode 120000
index 00000000000..2ef3aff47d8
--- /dev/null
+++ b/.agents/skills/acceptance
@@ -0,0 +1 @@
+../../packages/builtin-skills/src/acceptance
\ No newline at end of file
diff --git a/.agents/skills/agent-testing-bot/SKILL.md b/.agents/skills/agent-testing-bot/SKILL.md
index 85d2919c2f7..0bac71cc05d 100644
--- a/.agents/skills/agent-testing-bot/SKILL.md
+++ b/.agents/skills/agent-testing-bot/SKILL.md
@@ -3,7 +3,7 @@ name: agent-testing-bot
description: >
Bot-channel end-to-end verification for LobeHub โ€” drives the real native chat
apps (Discord / Slack / Telegram / WeChat / Lark / QQ / iMessage) via osascript
- or the iMessage bridge, on macOS. Extends the generic agent-testing skill for
+ or the iMessage bridge, on macOS. Extends the generic acceptance skill for
bot surfaces. Triggers on 'test bot', 'bot test', 'test in discord',
'test in telegram', 'test in slack', 'test in wechat', 'test in weixin',
'test in lark', 'test in feishu', 'test in qq'.
@@ -11,8 +11,8 @@ description: >
# Agent Testing โ€” Bot Channels (LobeHub project skill)
-This skill **extends** the generic `agent-testing` skill (installed alongside at
-`../agent-testing/`) to the bot-channel surfaces. It does NOT replace the core
+This skill **extends** the generic `acceptance` skill (installed alongside at
+`../acceptance/`) to the bot-channel surfaces. It does NOT replace the core
process: the same three phases apply โ€”
```text
@@ -20,7 +20,7 @@ PLAN (Steps 0โ€“2) โ†’ EXECUTE (Steps 3โ€“6) โ†’ FINISH (Step 7)
```
โ€” and the same report + publish pipeline (`result.json` โ†’ `report-init.sh` โ†’
-`lh acceptance run ingest โ€ฆ --source agent-testing`). Read the generic skill's
+`lh acceptance run ingest โ€ฆ --source agent-testing`). Read the acceptance 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.
@@ -61,7 +61,7 @@ Every osascript platform script shares one interface:
The script activates the app, navigates to the channel/contact, sends the
message, waits, and screenshots the result window (via the generic skill's
-`../agent-testing/scripts/capture-app-window.sh`). iMessage is the exception: it
+`../../acceptance/scripts/capture-app-window.sh`). iMessage is the exception: it
uses a BlueBubbles bridge, not osascript โ€” see [imessage/index.md](./imessage/index.md).
## osascript prerequisites
@@ -69,7 +69,7 @@ uses a BlueBubbles bridge, not osascript โ€” see [imessage/index.md](./imessage/
The osascript platforms drive real macOS apps (activate, keystroke, click, read
accessibility, screenshot). Read the generic skill's general macOS-automation
reference before a first bot run:
-[../agent-testing/references/osascript.md](../agent-testing/references/osascript.md).
+[../../acceptance/references/osascript.md](../../acceptance/references/osascript.md).
The target native app must already be running and logged in.
## Screen-recording gate (macOS-only)
@@ -80,7 +80,7 @@ Screen Recording (TCC) permission is missing OR the display is asleep / locked /
on a screensaver. Gate BEFORE any bot capture:
```bash
-./.agents/skills/agent-testing/scripts/check-screen-recording.sh # exit 0 = OS capture will work
+./.agents/acceptance/scripts/check-screen-recording.sh # exit 0 = OS capture will work
```
Keep the display awake for the whole capture session (`caffeinate -dimsu &`, kill
diff --git a/.agents/skills/agent-testing-bot/discord/index.md b/.agents/skills/agent-testing-bot/discord/index.md
index 9ef5d5fc88e..39ba6629c2b 100644
--- a/.agents/skills/agent-testing-bot/discord/index.md
+++ b/.agents/skills/agent-testing-bot/discord/index.md
@@ -2,7 +2,7 @@
**App name:** `Discord` | **Process name:** `Discord`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/discord/test-discord-bot.sh b/.agents/skills/agent-testing-bot/discord/test-discord-bot.sh
index 00b2060e934..c7a1e753a6a 100755
--- a/.agents/skills/agent-testing-bot/discord/test-discord-bot.sh
+++ b/.agents/skills/agent-testing-bot/discord/test-discord-bot.sh
@@ -60,5 +60,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing-bot/lark/index.md b/.agents/skills/agent-testing-bot/lark/index.md
index a71309d9ab6..bc52d86860b 100644
--- a/.agents/skills/agent-testing-bot/lark/index.md
+++ b/.agents/skills/agent-testing-bot/lark/index.md
@@ -2,7 +2,7 @@
**App name:** `Lark` or `้ฃžไนฆ` | **Process name:** `Lark` or `้ฃžไนฆ`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/lark/test-lark-bot.sh b/.agents/skills/agent-testing-bot/lark/test-lark-bot.sh
index a41b2d2cf5b..57769c7a0a3 100755
--- a/.agents/skills/agent-testing-bot/lark/test-lark-bot.sh
+++ b/.agents/skills/agent-testing-bot/lark/test-lark-bot.sh
@@ -80,5 +80,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing-bot/qq/index.md b/.agents/skills/agent-testing-bot/qq/index.md
index 94eaea40e43..f8de3205614 100644
--- a/.agents/skills/agent-testing-bot/qq/index.md
+++ b/.agents/skills/agent-testing-bot/qq/index.md
@@ -2,7 +2,7 @@
**App name:** `QQ` | **Process name:** `QQ`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/qq/test-qq-bot.sh b/.agents/skills/agent-testing-bot/qq/test-qq-bot.sh
index 68b303c6907..c4c844213fa 100755
--- a/.agents/skills/agent-testing-bot/qq/test-qq-bot.sh
+++ b/.agents/skills/agent-testing-bot/qq/test-qq-bot.sh
@@ -72,5 +72,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing-bot/slack/index.md b/.agents/skills/agent-testing-bot/slack/index.md
index 4cd7498f9ab..340f2ca3a71 100644
--- a/.agents/skills/agent-testing-bot/slack/index.md
+++ b/.agents/skills/agent-testing-bot/slack/index.md
@@ -2,7 +2,7 @@
**App name:** `Slack` | **Process name:** `Slack`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/slack/test-slack-bot.sh b/.agents/skills/agent-testing-bot/slack/test-slack-bot.sh
index 651c2715f97..afc96f7363f 100755
--- a/.agents/skills/agent-testing-bot/slack/test-slack-bot.sh
+++ b/.agents/skills/agent-testing-bot/slack/test-slack-bot.sh
@@ -60,5 +60,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing-bot/telegram/index.md b/.agents/skills/agent-testing-bot/telegram/index.md
index 48e377344a1..b1c05660825 100644
--- a/.agents/skills/agent-testing-bot/telegram/index.md
+++ b/.agents/skills/agent-testing-bot/telegram/index.md
@@ -2,7 +2,7 @@
**App name:** `Telegram` | **Process name:** `Telegram`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh b/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh
index 5a2657d8898..d473c6aeff7 100755
--- a/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh
+++ b/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh
@@ -75,5 +75,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing-bot/wechat/index.md b/.agents/skills/agent-testing-bot/wechat/index.md
index fa9290cdf50..5da724afe4a 100644
--- a/.agents/skills/agent-testing-bot/wechat/index.md
+++ b/.agents/skills/agent-testing-bot/wechat/index.md
@@ -2,7 +2,7 @@
**App name:** `ๅพฎไฟก` or `WeChat` | **Process name:** `WeChat`
-See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.
+See [references/osascript.md](../../../acceptance/references/osascript.md) for shared patterns.
## Activate & Navigate
diff --git a/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh b/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh
index de47db74ecc..10af7e9465d 100755
--- a/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh
+++ b/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh
@@ -81,5 +81,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."
sleep "$WAIT"
echo "[$APP] Capturing screenshot..."
-"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
+"$SCRIPT_DIR/../../../acceptance/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"
echo "[$APP] Done! Screenshot saved to $SCREENSHOT"
diff --git a/.agents/skills/agent-testing/.skill-meta.json b/.agents/skills/agent-testing/.skill-meta.json
deleted file mode 100644
index 2d878452ee0..00000000000
--- a/.agents/skills/agent-testing/.skill-meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "cliRoot": "../../../apps/cli",
- "name": "agent-testing",
- "version": "0.0.44"
-}
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
deleted file mode 100644
index df0c8f01edb..00000000000
--- a/.agents/skills/agent-testing/SKILL.md
+++ /dev/null
@@ -1,771 +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 LobeHub Acceptance.
- 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/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
-[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/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 an automatically maintained, curated living log, not a
-transcript of review feedback.** Every piece of negative feedback must trigger the
-admission check below. After the check, automatically append a qualifying new case or
-merge the learning into an existing case; do not wait for a separate user request.
-
-1. **Durable:** would this mistake plausibly recur in a different feature or a later
- Acceptance run? A one-off visual direction is not durable.
-2. **Project-specific:** does it depend on this project's product semantics,
- environment, or infrastructure? If not, deduplicate it against the generic layer
- and propose the generalized rule upstream instead.
-3. **Invariant-level:** does the entry state the behavior or evidence contract rather
- than freezing one solution? Exact copy, pixel values, icon choices, component slot
- order, and annotation coordinates belong in a feature specification, design
- document, regression test, or historical field note.
-4. **Non-duplicative:** search both living-log layers and nearby entries first. Amend
- or merge an existing case when the new incident has the same underlying failure.
-5. **Actionable:** can a future verifier use the rule to choose a different action or
- reject invalid evidence? Pure product taste or an incident narrative is not a
- verification mistake.
-
-Candidates passing all five checks must be recorded automatically:
-
-- Add a project-specific mistake to `.agents/acceptance/common-mistakes.md` in English
- using the stable project id scheme and the shared structure (Wrong approach / Why
- it fails / Correct approach).
-- Add a project-specific probe or mock workaround to
- `.agents/acceptance/probe-mock-patterns.md` (Situation / Doesn't work / Works) only
- when it is reusable beyond the current fixture.
-
-When a candidate fails the admission check only because it is too implementation-
-specific, route it automatically: product behavior to the feature specification, UI
-values to design/component code, regressions to a test, and long incident context to
-field notes. Feedback that is both non-durable and not useful in any of those places
-needs no persistent record. Do not skip the automatic living-log update merely
-because recording requires merging or abstracting the feedback first.
-
-This gate prevents a recurring failure mode in living logs: literal
-โ€œnegative feedback โ†’ append verbatimโ€ turns local review decisions into global
-policy. Automatic recording remains required; the admission check controls the
-abstraction level and destination. This avoids an ever-growing mandatory checklist
-of duplicated generic rules, pixel-level prescriptions, and contradictory snapshots
-of old UI decisions. Periodic maintenance should merge overlapping cases, move
-implementation details downward, and retire rules whose product contract no longer
-exists.
-
-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/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
-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.
-
-**Case selection gate (hard rule):** every case must be a delivery outcome a
-person can judge. Never plan the repo's own programmatic gates โ€” unit /
-integration tests, coverage, type-check, lint, a clean build โ€” as cases; ingest
-drops them and a gates-only round fails to publish. Full rule:
-[references/plan.md](./references/plan.md#case-selection-gate-hard-rule).
-
-### 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, **inject the login state directly** (seeded
-session, cookie/state restore, CLI/API-minted tokens โ€” per `PROJECT.md` ยง3);
-**never drive an interactive login/OAuth flow** โ€” those open login pages in the
-user's browser and hijack their session. When no injectable state exists, report
-auth as โŒ Blocked and ask the user for one manual sign-in, naming 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 โ€” confirm the first run, continue follow-up rounds autonomously
-
-At the end of Step 2 for the **first run of a subject Acceptance**, 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.
-
-That first approval remains valid for later iterations attached to the same
-subject Acceptance. When the user gives feedback on an existing Acceptance or
-asks to iterate again:
-
-1. Read the current Acceptance and its non-stale feedback.
-2. Re-check the environment and auth silently, resolving safe agent-owned issues.
-3. Implement the repair, execute the affected checks, and publish a new immutable
- round to the same Acceptance without asking for another plan confirmation.
-4. Reuse stable check ids and omit user-accepted checks unless the change can
- regress them.
-
-Ask again only when the follow-up introduces a **material boundary change**:
-
-- a new surface, external system, account, secret, permission, or destructive action;
-- a materially expanded product scope or changed business goal;
-- a user-owned blocker or product choice that cannot be resolved safely;
-- an environment change that invalidates the previously approved evidence strategy.
-
-Routine code changes, fixture refreshes, server restarts, evidence recapture,
-retries, and new immutable Acceptance rounds are not material boundary changes.
-Do not pause after a follow-up fix: verification and publication are part of the
-same approved iteration.
-
-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 first-run 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.
-
-**Separate the driver from the evidence surface.** Picking a surface for
-evidence does NOT mean every action must go through it โ€” generating the state
-under test (running a flow, seeding data, triggering a job) and capturing the
-evidence (screenshot, DOM assertion, DB row) are independent choices. Pick the
-cheapest, most deterministic driver the project offers (a CLI run command, an
-API/endpoint call, a seed script โ€” see `PROJECT.md` ยง4/ยง5 for what exists), and
-use the evidence surface only for what it alone can prove. Typing long prompts
-or multi-step inputs through browser automation when a CLI/API driver exists is
-a smell: the browser run is slower, flakier, and no more authentic โ€” the
-server-side state it produces is identical. The reverse also holds: a CLI-driven
-state still needs UI evidence when the claim under test is about rendering.
-
-**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/acceptance/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`; `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)
-
-**Read [references/report.md](./references/report.md) in full before writing the
-first line of `result.json`** โ€” it is the schema, and this section is only a
-summary of it. Do not infer a field's shape from the snippets here; the nested
-ones are spelled out there and nowhere else. A field written in the wrong shape
-is dropped on ingest, so the run publishes green with its evidence silently
-degraded.
-
-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 acceptance 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`.
-- **Structured data uses native Acceptance visualizations by default (hard
- rule).** When a result contains metrics, time series, before/after model or
- benchmark comparisons, distributions, matrices, or tabular data, encode the
- review-sized values in `cases[].datasets` and declare the corresponding view
- in `cases[].visualizations`. Keep the raw CSV/JSON, benchmark output, trace,
- profile, or vectors in `evidence` so the chart remains auditable. Do NOT render
- those values into a PNG/GIF yourself when a supported native renderer can
- express them; static generated charts lose structured values, accessibility,
- theme adaptation, and consistent comparison semantics. Generate a static
- chart only when none of the supported renderers can faithfully represent the
- result, and explain that limitation in the case observation. Supported views:
- `metric-comparison`, `line-chart`, `bar-chart`, `scatter-plot`, `heatmap`, and
- `table`. See
- [references/report.md](./references/report.md#structured-visualizations).
-- **Non-visual behavioral claims use dual text evidence.** Attach two separate
- text artifacts to the same case: a reviewer-facing **reasoning** document and
- an audit-facing **execution** document. The reasoning artifact explains the
- claim, setup/threat model, method, pass criteria, interpretation, and limits.
- The execution artifact preserves the exact command/request plus relevant raw
- observations, then maps those observations back to the claim. Neither prose
- without observed values nor an unexplained log dump is sufficient. Keep both
- artifacts in the current round; never require a reviewer to join explanation
- from one immutable round with logs from another. See
- [references/report.md](./references/report.md#dual-text-evidence-for-non-visual-behavior).
-- **Final replies expose ONLY the published `/acceptance/<id>` page. Put no
- images, local paths, local file links, or internal run-page paths in the chat
- reply.**
- The acceptance page is the stable cross-round decision surface and renders
- each round's evidence inline. For a fixed this-round snapshot, append
- `?r=<roundIndex>` to the same acceptance URL (the ingest CLI prints it as
- `round snapshot`) โ€” that deep-links this round's full report. Do not mention
- any working-artifact location. Always leave whitespace between a URL and any
- following text โ€” CJK punctuation glued right after it (`โ€ฆ4c74๏ผˆๆœฌ่ฝฎ`)
- gets swallowed into the href by chat autolinkers and breaks the link.
-- **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.
- Keep the captured resolution by default. Before publishing, inspect the first,
- middle, and final frames at readable size and reject evidence with colored
- quantization noise, blurred text, or illegible one-pixel borders. Set
- `GIF_WIDTH` only when the resulting dimensions are genuinely too large.
-- **A deliverable the user hears needs `audio`.** TTS output, a voice reply, an
- alert tone: attach the clip the feature produced so the page renders a player.
- Prose about a sound, or a screenshot of a waveform, proves nothing โ€”
- [references/report.md](./references/report.md).
-- **Programmatic gates are NEVER acceptance checks (hard rule, enforced).**
- Unit / integration tests, coverage, type-check, lint, and a clean build are
- preconditions of shipping; they belong in one line of `report.md` โ†’
- Verification and MUST NOT appear in `plan[]` / `cases[]` under any phrasing.
- `acceptance run ingest` drops every matching item (matched on title, category,
- and method) and a gates-only round fails to publish โ€”
- [references/report.md](./references/report.md#hard-rule--what-is-not-an-acceptance-check).
-
-### Step 6 โ€” Publish to LobeHub Acceptance (mandatory)
-
-The report under `.records/reports/` is a private working artifact; the
-**deliverable is the report opened on the acceptance page**. 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 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
-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.
-
-#### Operation ID is optional for agent-testing (mandatory)
-
-An external project normally has no LobeHub Agent Operation, and that is valid.
-Do not ask the user for an Operation ID, invent one, or pass `--operation` merely
-because the report is being published to LobeHub.
-
-- Prefer `lh acceptance run ingest "$DIR" ...`. It creates a standalone
- verification run and does not require an Operation ID.
-- `--operation <id>` means โ€œthis verification session evaluates this existing
- LobeHub Agent Run.โ€ Use it only when the user explicitly targets a real
- operation that exists in the current LobeHub workspace.
-- `LOBEHUB_OPERATION_ID`, when present, identifies the in-app run that authored
- the report. The CLI records it as optional origin metadata; its absence in a
- plain terminal or external repository is not an error.
-- If atomic commands are genuinely needed, first run
- `lh acceptance run create --json`, retain its returned `verifyRunId`, and pass
- that value as `--run <verifyRunId>` to result/report/submit commands. Never
- substitute an Operation ID for a missing Verify Run ID.
-
-Interpret common errors before retrying:
-
-- `Provide --run or --operation` means an atomic command lacks its verification
- run handle; supply the returned `verifyRunId` through `--run`.
-- `Agent operation ... not found` means an invalid, stale, foreign, or fabricated
- `--operation` was supplied; remove it for standalone agent-testing.
-- `Agent verifier failed to start (no operation id returned)` is a server-side
- verifier-agent startup failure, not a requirement for the external harness to
- provide an Operation ID.
-
-`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
- `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`, `roundIndex`, and the acceptance
-paths. The final reply leads with
-`https://app.lobehub.com/acceptance/<acceptanceId>` as the latest cross-round
-state; for a fixed per-round snapshot use the same URL with `?r=<roundIndex>`
-(printed as `round snapshot`). Do not expose any other run path in the reply; the
-underlying immutable run is an internal record behind the acceptance page.
-
-#### 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.
-
-**Choose the subject by business continuity, not by which object is easiest to
-create:**
-
-1. Honor an explicit subject or an instruction to reuse a specific Acceptance.
-2. Otherwise, when the verification continues work discussed and implemented in
- the current LobeHub conversation, use its `topic:<id>`. This is the default for
- iterative fixes, review feedback, and follow-up UI polish in the same thread.
-3. Use an existing `task:<id>` when that Task already owns the deliverable, or
- when the work is intentionally independent, durable, spans multiple topics, or
- the user explicitly wants task-level tracking.
-4. Use `document:<id>` only when the document itself is the acceptance subject.
-5. Create a new Task only when no relevant current Topic, Task, or Document exists.
-
-**Acceptance lifecycle and subject selection are separate decisions.** If an
-Acceptance on the relevant Topic is terminal and new work needs a new Acceptance,
-keep the same Topic subject and create the new Acceptance there when the product
-lifecycle supports it. Never create a Task merely to avoid appending to a closed
-Acceptance.
-
-When the harness runs inside a relevant LobeHub topic, `acceptance run ingest`
-automatically uses `LOBEHUB_TOPIC_ID` as `topic:<id>` โ€” do not ask the user for it.
-Pass `--subject` explicitly when an existing Task or Document owns the work.
-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 acceptance run ingest "$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 acceptance view|accept|reject <id | type:id>`.
-
-When no relevant subject exists (no current Topic carrying the work and no
-existing Task or Document owns it), create a Task with the CLI instead of asking
-the user for an id:
-
-```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 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.
-- **`supersedes` is persistent plan lineage, not a one-round migration flag.**
- Every later round that reuses the successor id MUST repeat its complete
- `supersedes` list. The Acceptance union reads the latest plan snapshot for an
- id; omitting the list later can resurrect the replaced check as a parallel row.
- Before ingest, compare the new plan with `acceptance view`: if a reused id has
- ever declared `supersedes`, carry that declaration forward unchanged (including
- the full chain) unless the business meaning is explicitly being replaced again.
-- Treat `stale: true` feedback as history already consumed by a newer round.
-
-#### Every verification run is an immutable snapshot
-
-One call to `acceptance run ingest` creates one immutable internal run 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?, datasets?, visualizations? }`;
- structured views should retain raw benchmark/profile/vector files as evidence;
- `evidence` is a path (or array) relative to `$DIR`. Supported structured views are
- `metric-comparison`, `line-chart`, `bar-chart`, `scatter-plot`, `heatmap`, and `table`.
- `result`/`verdict` map onto
- `passed | failed | uncertain`.
-- 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`. Carry the `verifyRunId` returned by
- `create` into later commands as `--run`; external projects must not fall back to
- `--operation`.
-- File evidence uploads through the platform's storage. Against a stub or
- 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.
-
-## 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 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.
- 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/.agents/skills/agent-testing/references/agent-browser.md b/.agents/skills/agent-testing/references/agent-browser.md
deleted file mode 100644
index 4382c2c982e..00000000000
--- a/.agents/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/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
-`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/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.md
deleted file mode 100644
index f8abe740422..00000000000
--- a/.agents/skills/agent-testing/references/report.md
+++ /dev/null
@@ -1,685 +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
-acceptance page 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/`:
-
- - Structured data (metrics, time series, before/after model or benchmark
- comparisons, distributions, matrices, and tables): **use native Acceptance
- visualizations by default.** Put review-sized values in the case's
- `datasets[]`, declare their presentation in `visualizations[]`, and attach
- the raw CSV/JSON, benchmark output, trace, profile, or vectors as
- `evidence`. The structured view is the reviewer-facing decision aid; the raw
- artifact is the audit trail.
-
- Do **not** generate a PNG/GIF of data that `metric-comparison`, `line-chart`,
- `bar-chart`, `scatter-plot`, `heatmap`, or `table` can faithfully express.
- A static chart discards machine-readable values, accessibility, theme
- adaptation, and consistent comparison semantics. Generate a static chart
- only when no supported renderer can represent the result, and state that
- limitation in the case observation. Do not merely upload a CSV and expect
- the page to infer a chart: define both `datasets[]` and
- `visualizations[]` explicitly. See
- [Structured visualizations](#structured-visualizations) for the schema.
-
- - 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
- ```
-
- Keep source resolution unless file size requires an explicit `GIF_WIDTH`.
- The recorder uses per-frame palettes without dithering so neutral loading
- surfaces do not acquire colored noise. Verify the first, middle, and final
- frames visually at readable size before citing; reject blurred text, noisy
- grays, or lost one-pixel borders.
-
- - 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" }
- }
- ]
- ```
-
- `comparison` is a nested **object** on each half. Writing it flat โ€”
- `{ "path": "โ€ฆ", "comparison": "topic-row", "role": "before" }` โ€” is the
- usual slip, and it does not pair: `role` is read from inside `comparison`,
- never from the evidence item itself.
-
- The acceptance 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.
- `acceptance run ingest` warns on every malformed `comparison` it drops โ€”
- treat that warning as a failed publish and re-ingest a corrected round,
- exactly as with a skipped evidence upload.
-
- 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.
-
- - Audio (a deliverable the user **hears** โ€” TTS output, a voice reply, an
- alert tone): attach the clip itself as `audio` evidence. The acceptance page
- renders a player, so the reviewer can listen; prose about a sound, or a
- screenshot of a waveform, proves nothing. `mp3` / `wav` / `m4a` / `aac` /
- `flac` / `ogg` / `opus` are typed as `audio` from the extension.
-
- Verify the clip before citing it โ€” confirm it is non-silent and carries the
- expected content (duration plus a transcription or spectral check); an empty
- or truncated file is indistinguishable from a good one in a file listing.
- Pair it with a short text artifact when the claim is about _what was said_
- (input text, voice/model, measured duration): the player proves it plays,
- the text makes it auditable.
-
- A screen recording with system audio is the fallback for "the UI plays it at
- the right moment"; for "the output is correct", attach the file the feature
- produced.
-
- - CLI: use the dual-text evidence format below. Preserve the exact command +
- trimmed output (`<cli> <command> | tee "$DIR/assets/x-execution.txt"`) in
- the execution artifact, and attach a separate reasoning artifact.
-
- - Network: `agent-browser network requests` dumps or HAR files.
-
-### Dual text evidence for non-visual behavior
-
-For CLI, API, backend, policy, security, migration, and other non-visual
-behavioral checks, one text file rarely serves both audiences well. A reviewer
-needs to understand why the check is meaningful; an auditor needs the concrete
-observations. Attach **two separate text artifacts** to the same case, in this
-order:
-
-1. **Reasoning evidence** (`<check>-reasoning.md`) โ€” concise, reviewer-facing:
- - claim / behavior being verified;
- - setup or threat model;
- - action or attempted bypass;
- - explicit pass/fail criteria;
- - why the chosen observations support the verdict;
- - limitations and what remains unproven.
-2. **Execution evidence** (`<check>-execution.txt` or `.md`) โ€” audit-facing:
- - exact command, request, or probe;
- - relevant raw stdout/stderr, response body/status, exit code, filesystem or
- server-side observations;
- - a short annotation mapping each observed value to the pass/fail criteria.
-
-The split is semantic, not cosmetic. Do not duplicate the same prose into both
-files, and do not turn the execution artifact into a second high-level summary.
-Trim unrelated noise, but retain values that make the outcome independently
-auditable (for example exit codes, error text, file existence, response status,
-or server receive counts).
-
-```json
-{
- "evidence": ["assets/write-boundary-reasoning.md", "assets/write-boundary-execution.txt"],
- "id": "write-boundary",
- "name": "approved writes succeed and escape attempts are denied",
- "observation": "control exit=0; four escape attempts exit non-zero and created no files",
- "status": "pass"
-}
-```
-
-This is a hard default for non-visual behavioral claims, with two narrow
-exceptions:
-
-- a text artifact is only ancillary metadata for primary visual evidence (for
- example a screenshot plus a small DOM dump);
-- the evidence is intrinsically self-explanatory and contains no behavioral
- inference (for example a generated schema file whose exact contents are the
- claim).
-
-If a follow-up round corrects either half, publish both halves again in that
-round. Every immutable round must be a self-contained decision snapshot; never
-ask the reviewer to combine reasoning from an older round with execution logs
-from the current one.
-
-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.
-
- **HARD RULE: no programmatic gates in the plan.** Tests / type-check / lint /
- build are never plan items โ€” ingest drops them and a gates-only round fails
- to publish. See
- [what is NOT an acceptance check](#hard-rule--what-is-not-an-acceptance-check).
-
-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.
-
- **`scenario` is a closed enum, not a description** โ€” see the table below. The
- scaffold pre-fills `coding`; a one-line summary of what the run covers belongs in
- `context`, never in `scenario`.
-
-5. **Set the verdict** in both `report.md` and `result.json`. Describe key visual
- outcomes in prose; the published acceptance 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
- LobeHub Acceptance, 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 acceptance run ingest "$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
- `/acceptance/<acceptanceId>` plus its `?r=<roundIndex>` round-snapshot form.
- Include only the full production acceptance link in the final reply. Never
- expose local paths, local file links, or internal run-page paths. Leave
- whitespace after the URL, so
- an autolinker can't swallow adjacent CJK punctuation into the href. 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 (`acceptance run โ€ฆ` (plus `โ€ฆ 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"]
- },
- {
- "category": "Tab responsiveness",
- "id": "2",
- "name": "conversation tab switching avoids duplicate parsing",
- "surface": "desktop",
- "status": "pass",
- "observation": "The switch-time parsing hotspot disappeared and GC time fell.",
- "evidence": ["assets/benchmark.json", "assets/cpu-profile.json"],
- "datasets": [
- {
- "id": "switch-metrics",
- "fields": [
- { "key": "name", "type": "string" },
- { "key": "before", "type": "number", "unit": "ms" },
- { "key": "after", "type": "number", "unit": "ms" },
- { "key": "direction", "type": "category" },
- { "key": "target", "type": "number", "unit": "ms" }
- ],
- "rows": [
- {
- "name": "GC self-time",
- "before": 257,
- "after": 24.8,
- "direction": "lower",
- "target": 50
- }
- ]
- }
- ],
- "visualizations": [
- {
- "id": "switch-comparison",
- "type": "metric-comparison",
- "version": 1,
- "dataset": "switch-metrics",
- "title": "Performance comparison",
- "context": "Electron 40, warm cache, identical tool-heavy topic fixture",
- "encoding": {
- "label": "name",
- "before": "before",
- "after": "after",
- "direction": "direction",
- "target": "target"
- }
- }
- ]
- }
- ],
- "commit": "abc1234",
- "context": "Nested task tree API behind the new repository method",
- "createdAt": "2026-06-11T15:30:00+08:00",
- "entry": "<cli> task list --tree",
- "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"]
- },
- {
- "id": "2",
- "title": "conversation tab switching avoids duplicate parsing",
- "category": "Tab responsiveness",
- "surface": "desktop",
- "verifier": "program",
- "method": "Run the same warm-cache CDP switch profile before and after the change",
- "expected": "GC self-time is at or below 50 ms",
- "requiredEvidence": ["text"]
- }
- ],
- "pullRequest": {
- "number": 17152,
- "title": "feat(task): nested task tree",
- "url": "https://github.com/<org>/<repo>/pull/17152"
- },
- "scenario": "coding",
- "summary": {
- "total": 2,
- "passed": 2,
- "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` \| `audio` \| `text` \| `markdown` \| `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.
-
-### HARD RULE โ€” what is NOT an acceptance check
-
-A check is something a **person decides about the delivery**. The repo's own
-automated gates are not that, and on the page they are actively harmful: twenty
-green "unit tests pass" rows bury the two checks that actually needed someone to
-look.
-
-**These MUST NOT appear in `plan[]` / `cases[]`, under any phrasing:**
-
-| Not a check | Where it belongs |
-| ---------------------------------------------------------- | ---------------------------------------------------- |
-| Unit / integration / regression / snapshot tests, coverage | one line in `report.md` โ†’ **Verification** |
-| `type-check`, `tsc`, `eslint`, lint, format, a clean build | same โ€” a precondition of shipping, not a deliverable |
-| "the suite is green", "CI passes" | same |
-
-This is enforced, not advisory. `acceptance run ingest` **drops every matching
-item** โ€” matched on title, category, AND `method`, so "run `bun run test`"
-inside `method` under a product-sounding title still matches โ€” warns with the
-dropped ids, and recounts `summary` from the checks that remain. A round
-consisting **only** of such checks **fails to publish**. Apply the rule at plan
-time (Phase 1 case selection gate), before any case runs: a gate written as a
-check is a round spent proving something nobody accepts. Run the gates as your
-own diligence โ€” report them as one line of narrative.
-
-The line is the _subject_ of the check, not who judged it: a CLI behavior check
-asserted by a command is a good acceptance item (`verifier: "program"`);
-"`bun run test` is green" is not.
-
-**What IS a check:** what the user sees, hears, reads, or receives โ€” a rendered
-screen, a produced file, a response shape a client depends on, an audio clip that
-actually plays, a failure state that recovers.
-
-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.
-
-`scenario` is a **closed set** โ€” `coding` | `writing` | `research` | `generic` โ€”
-naming what KIND of delivery was verified, because the page renders a different
-scope header for each. It defaults to `coding` when omitted, and an out-of-set value
-**fails the ingest** rather than being stored:
-
-| value | the delivery under verification |
-| ---------- | ---------------------------------------------------------- |
-| `coding` | a software change (branch / commit / surfaces under test) |
-| `writing` | a written deliverable (manuscript / chapters / documents) |
-| `research` | a research deliverable (question / sources / claims) |
-| `generic` | anything else โ€” no modeled scope; `context` is an open bag |
-
-It is **not** a free-text summary of the run. Writing the sentence you would say
-out loud ("verify the memory tool rendersโ€ฆ") is the easy mistake โ€” the scaffold
-pre-fills `coding`, so overwriting it with prose turns a working file into a hard
-ingest failure at the very last step. That sentence belongs in `context`, which is
-the scenario's own scope bag and is rendered next to `scenario` in the page's scope
-header; for a non-`coding` scenario it also carries that scenario's modeled fields.
-
-### Structured visualizations
-
-A case may provide `datasets[]` plus `visualizations[]`. The ingest stores the
-versioned manifest on the check result and the Acceptance page renders each view.
-The first supported renderers are `metric-comparison`, `line-chart`, `bar-chart`,
-`scatter-plot`, `heatmap`, and `table` (all `version: 1`). Each view references one dataset by id
-and maps its fields through `encoding`.
-
-Use `line-chart.encoding.series[].style` (`muted` | `primary` | `accent`) to keep a
-baseline visually quiet and emphasize the compared run. Tables can mark best-in-column
-values with `encoding.highlights[]` (`{ field, mode: "min" | "max" }`); ties are all
-marked SOTA. `bar-chart` is the default for grouped model or benchmark score comparisons.
-
-Inline datasets use declared `fields[]` and object `rows[]`; undeclared cells,
-unsupported renderers, missing dataset references, and more than 10,000 total
-rows fail ingest. Use inline data only for a review-sized summary. Keep raw
-benchmark output, traces, vectors, or profiles in `evidence`; visualization is a
-decision aid, not a replacement for evidence.
-
-For comparable metrics, only publish before/after values produced by the same
-harness, fixture, environment, warm-up policy, statistic, and sample window. If
-those differ, use separate series or mark the case uncertain instead of presenting
-a misleading delta.
-
-Every visualization requires unique non-empty `id`, `type`, `dataset`, and
-`version: 1`; `dataset` must reference a declared dataset id. `title` and
-`context` are optional non-empty strings. Every encoding field name below must
-reference a field declared by that dataset.
-
-| Renderer | Required encoding | Optional encoding |
-| ------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
-| `metric-comparison` | `label`, `before`, `after` | `beforeSamples`, `afterSamples`, `direction`, `statistic`, `target`, `unit` |
-| `line-chart` | `x`, non-empty `series[]`; each series requires `field` | series `label`, series `style` (`muted` \| `primary` \| `accent`), `xLabel`, `yLabel` |
-| `bar-chart` | `category`, non-empty `series[]`; each series requires `field` | series `label`, `valueLabel` |
-| `scatter-plot` | `x`, `y` | `color`, `label`, `xLabel`, `yLabel` |
-| `heatmap` | `x`, `y`, `value` | none |
-| `table` | none; `encoding` itself may be omitted | non-empty `columns[]`; `highlights[]` entries require `field` and `mode` (`min` \| `max`) |
-
-Minimal valid encoding examples (replace every field-name string with a key
-declared in the referenced dataset):
-
-```json
-[
- {
- "id": "quality-delta",
- "type": "metric-comparison",
- "version": 1,
- "dataset": "metrics",
- "encoding": { "label": "metric", "before": "baseline", "after": "candidate" }
- },
- {
- "id": "loss-over-time",
- "type": "line-chart",
- "version": 1,
- "dataset": "training",
- "encoding": {
- "x": "step",
- "series": [
- { "field": "baselineLoss", "label": "Baseline", "style": "muted" },
- { "field": "candidateLoss", "label": "Candidate", "style": "primary" }
- ],
- "xLabel": "Step",
- "yLabel": "Loss"
- }
- },
- {
- "id": "scores-by-model",
- "type": "bar-chart",
- "version": 1,
- "dataset": "scores",
- "encoding": {
- "category": "model",
- "series": [{ "field": "score", "label": "Score" }],
- "valueLabel": "Accuracy"
- }
- },
- {
- "id": "latency-quality",
- "type": "scatter-plot",
- "version": 1,
- "dataset": "runs",
- "encoding": {
- "x": "latency",
- "y": "quality",
- "color": "model",
- "label": "run",
- "xLabel": "Latency (ms)",
- "yLabel": "Quality"
- }
- },
- {
- "id": "error-matrix",
- "type": "heatmap",
- "version": 1,
- "dataset": "errors",
- "encoding": { "x": "predicted", "y": "actual", "value": "count" }
- },
- {
- "id": "benchmark-table",
- "type": "table",
- "version": 1,
- "dataset": "benchmarks",
- "encoding": {
- "columns": ["model", "latency", "score"],
- "highlights": [
- { "field": "latency", "mode": "min" },
- { "field": "score", "mode": "max" }
- ]
- }
- }
-]
-```
-
-Dataset field `type` is one of `boolean`, `category`, `number`, `string`, or
-`temporal`; field keys and dataset/view ids must be unique. Rows may contain only
-declared keys with string, number, boolean, or null values. The combined inline
-row limit is 10,000.
-
-`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.
-
-An Operation ID is not part of report identity and is not required for external
-agent-testing. `acceptance run ingest` creates a standalone Verify Run. Use
-`--operation` only to link the report to a real, existing LobeHub Agent Run under
-test. For atomic publication, carry the `verifyRunId` returned by
-`acceptance run create` and pass it through `--run`; never ask an external-project
-user to supply an Operation ID or fabricate one.
-
-Choose by continuity: use the current Topic for work discussed and iterated in
-that conversation; use a Task only when it already owns the deliverable or the
-work intentionally needs independent, durable, cross-topic tracking; use a
-Document only when the document itself is under acceptance. Create a Task only
-when no relevant subject exists. A terminal Acceptance may require a new
-Acceptance, but it does not by itself justify changing the subject from Topic to
-Task.
-
-Inside a relevant LobeHub conversation, both subject fields may 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.
-
-`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, `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
-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 behavioral cases must attach both reasoning and execution text;
- transcripts, HAR files, and logs belong in the execution half.
-- **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/.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs b/.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs
deleted file mode 100755
index 1239ec826c1..00000000000
--- a/.agents/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/.agents/skills/agent-testing/surfaces/cli.md b/.agents/skills/agent-testing/surfaces/cli.md
deleted file mode 100644
index 1028b866ea9..00000000000
--- a/.agents/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/acceptance/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/.agents/skills/agent-testing/surfaces/electron.md b/.agents/skills/agent-testing/surfaces/electron.md
deleted file mode 100644
index 7db6dc21b94..00000000000
--- a/.agents/skills/agent-testing/surfaces/electron.md
+++ /dev/null
@@ -1,122 +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/acceptance/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, **inject the login state directly** (restore the persisted snapshot, or mint
-it via CLI/API seeding per `PROJECT.md` ยง3); **never trigger an interactive
-login/OAuth flow** โ€” it opens a login page in the user's own browser. When no
-injectable state exists, report auth as blocked and ask for one manual sign-in.
-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/.agents/skills/agent-testing/surfaces/web.md b/.agents/skills/agent-testing/surfaces/web.md
deleted file mode 100644
index 9d0088e80af..00000000000
--- a/.agents/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/acceptance/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 and validate 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/.agents/skills/debug-frontend-with-browser/SKILL.md b/.agents/skills/debug-frontend-with-browser/SKILL.md
index 1e9c96ae674..3fae1d98d31 100644
--- a/.agents/skills/debug-frontend-with-browser/SKILL.md
+++ b/.agents/skills/debug-frontend-with-browser/SKILL.md
@@ -1,21 +1,22 @@
---
name: debug-frontend-with-browser
-description: Frontend diagnosis extension for agent-testing. Use for intermittent rendering, ordering, stale-state, navigation, virtual-list, React/Zustand, optimistic-update, refresh-dependent, or browser-only failures where the first broken boundary may be DOM, component input, derived state, client cache, network data, or a pure transformation. Before any browser, Electron, or live-app interaction, this skill must load and follow agent-testing; it adds only boundary tracing, minimal fixture replay, and regression attribution.
+description: Frontend diagnosis extension for the acceptance skill. Use for intermittent rendering, ordering, stale-state, navigation, virtual-list, React/Zustand, optimistic-update, refresh-dependent, or browser-only failures where the first broken boundary may be DOM, component input, derived state, client cache, network data, or a pure transformation. Before any browser, Electron, or live-app interaction, this skill must load and follow the acceptance skill and the repository's `.agents/acceptance/` project layer; it adds only boundary tracing, minimal fixture replay, and regression attribution.
---
# Debug Frontend with Browser
Find the first boundary where correct data becomes incorrect. This skill extends
-`agent-testing`; it does not define a separate test workflow.
+`acceptance`; it does not define a separate test workflow.
## Mandatory foundation
Before any browser, Electron, network, cache, or application interaction:
-1. Read [`../agent-testing/SKILL.md`](../agent-testing/SKILL.md) in full.
+1. Read [`../acceptance/SKILL.md`](../acceptance/SKILL.md) and the project's
+ [`PROCESS.md`](../../acceptance/PROCESS.md) in full.
2. Follow its target grounding, living logs, project adapter, environment and auth
checks, approval gate, evidence rules, publication, and teardown.
-3. Enter this diagnostic workflow only after `agent-testing` has established the
+3. Enter this diagnostic workflow only after `acceptance` has established the
approved execution surface. If its environment or auth gate is blocked, stop
there instead of inventing another execution path.
4. Use the isolated environment and fixture strategy selected by the project
@@ -27,11 +28,11 @@ Before any browser, Electron, network, cache, or application interaction:
6. Never read secret files or print credentials, tokens, private content, or full
live objects. Return structural projections only.
-If `agent-testing` is unavailable, say so and stop before touching a live surface.
+If `acceptance` is unavailable, say so and stop before touching a live surface.
## Responsibility boundary
-| `agent-testing` owns | This skill adds |
+| `acceptance` owns | This skill adds |
| ------------------------------------------- | -------------------------------------- |
| Environment isolation and service lifecycle | Falsifiable symptom and event timeline |
| Authentication and fixture seeding | Boundary-by-boundary state comparison |
@@ -39,8 +40,8 @@ If `agent-testing` is unavailable, say so and stop before touching a live surfac
| Approval and mutation authority | Pure-function replay and commit A/B |
| Evidence, report, publication, teardown | Earliest-boundary fix guidance |
-Do not duplicate or weaken `agent-testing` rules here. When the two skills appear
-to conflict, `agent-testing` and the project adapter control execution.
+Do not duplicate or weaken `acceptance` rules here. When the two skills appear
+to conflict, `acceptance` and the project layer control execution.
## Diagnostic workflow
@@ -65,7 +66,7 @@ before reading implementation code.
- Use a GIF or video for flicker and other time-based behavior.
- Re-snapshot after navigation or a major render because element references expire.
-Use the surface and capture method chosen by `agent-testing`; do not relaunch or
+Use the surface and capture method chosen by `acceptance`; do not relaunch or
reattach to the user's resident application.
### 3. Find the first broken boundary
@@ -102,7 +103,7 @@ only fields required by the suspected boundary, such as:
- branch or group metadata;
- entity identifiers that affect selection or grouping.
-Store reusable inputs through the `agent-testing` fixture layout. Do not copy
+Store reusable inputs through the project's fixture layout. Do not copy
private production content into fixtures or tracked files.
### 5. Attribute with the same fixture
@@ -124,9 +125,9 @@ Do not infer causality from PR timing or filenames.
- Do not substitute timeouts, refreshes, DOM sorting, or downstream filters for a
source-state fix.
-### 7. Return to agent-testing for verification
+### 7. Return to the acceptance workflow for verification
-After diagnosis or a fix, resume the parent `agent-testing` workflow. It owns the
+After diagnosis or a fix, resume the parent `acceptance` workflow. It owns the
focused checks, isolated visual replay, evidence inspection, structured report,
publication, and cleanup. Do not publish a separate browser-debugging verdict.
diff --git a/.agents/skills/debug-frontend-with-browser/references/pitfalls.md b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
index 64f2f11c676..c0b56989e5c 100644
--- a/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
+++ b/.agents/skills/debug-frontend-with-browser/references/pitfalls.md
@@ -1,6 +1,6 @@
# Frontend Diagnosis Supplements
-Read this only after the mandatory `agent-testing` workflow has selected and
+Read this only after the mandatory `acceptance` workflow has selected and
approved an isolated execution surface.
## Contents
diff --git a/.agents/skills/heterogeneous-agent/references/debug-workflow.md b/.agents/skills/heterogeneous-agent/references/debug-workflow.md
index 6b7b047482f..e1dbe635848 100644
--- a/.agents/skills/heterogeneous-agent/references/debug-workflow.md
+++ b/.agents/skills/heterogeneous-agent/references/debug-workflow.md
@@ -290,7 +290,7 @@ When the bug comes from a real trace, distill it into the closest existing test
3. Add or update the narrowest failing test near the broken layer.
4. Fix the smallest layer that can explain the symptom.
5. Re-run focused tests.
-6. Only then do an Electron smoke test with the `agent-testing` skill if UI confirmation is still needed.
+6. Only then do an Electron smoke test with the `acceptance` skill if UI confirmation is still needed.
Do not start with a broad Electron repro if a raw trace or adapter test can prove the fault zone faster.
diff --git a/.agents/skills/skills-audit/SKILL.md b/.agents/skills/skills-audit/SKILL.md
index bc1d337179d..13773c2078e 100644
--- a/.agents/skills/skills-audit/SKILL.md
+++ b/.agents/skills/skills-audit/SKILL.md
@@ -48,7 +48,7 @@ Common false positives (do NOT merge):
- `db-migrations` vs `drizzle` โ€” distinct workflows (migration files vs schema authoring).
- `agent-runtime-hooks` vs `agent-tracing` vs `agent-signal` โ€” different surfaces of the agent system.
-- `testing` vs `agent-testing` โ€” different test types.
+- `testing` vs `acceptance` โ€” different test types.
### 4 โ€” Description format consistency
diff --git a/.agents/skills/ux-audit/SKILL.md b/.agents/skills/ux-audit/SKILL.md
index b9025fca09d..5aab0539614 100644
--- a/.agents/skills/ux-audit/SKILL.md
+++ b/.agents/skills/ux-audit/SKILL.md
@@ -26,11 +26,11 @@ page as the product grows; that's the "continuous" part.
An audit is not one activity. A finding is only trustworthy from a layer that can actually
_see_ it. Each layer has its own procedure file; run the ones the surface needs.
-| Layer | File | What it does | Catches | Cost |
-| -------------- | --------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| **L1 Static** | [layer-1-static.md](references/layer-1-static.md) | Read the code | Missing states/branches (empty/error/retry), no draft persist, absent patterns, structural issues | cheap, offline, **every audit** |
-| **L2 Visual** | [layer-2-visual.md](references/layer-2-visual.md) | Screenshots of the rendered surface | Real visual hierarchy & dominant control, spacing/contrast/alignment, truncation/overflow, how empty/loading/error actually look, responsive breakpoints, dark/light | medium; needs a render |
-| **L3 Dynamic** | [layer-3-dynamic.md](references/layer-3-dynamic.md) | Drive the real user journey via **agent-testing** + instrument | In-progress/locked states, forced error/empty states, does step N lead to N+1, focus/keyboard, **quantified CLS / LCP / INP / long-tasks** | high; needs a running env + auth |
+| Layer | File | What it does | Catches | Cost |
+| -------------- | --------------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| **L1 Static** | [layer-1-static.md](references/layer-1-static.md) | Read the code | Missing states/branches (empty/error/retry), no draft persist, absent patterns, structural issues | cheap, offline, **every audit** |
+| **L2 Visual** | [layer-2-visual.md](references/layer-2-visual.md) | Screenshots of the rendered surface | Real visual hierarchy & dominant control, spacing/contrast/alignment, truncation/overflow, how empty/loading/error actually look, responsive breakpoints, dark/light | medium; needs a render |
+| **L3 Dynamic** | [layer-3-dynamic.md](references/layer-3-dynamic.md) | Drive the real user journey via **acceptance** + instrument | In-progress/locked states, forced error/empty states, does step N lead to N+1, focus/keyboard, **quantified CLS / LCP / INP / long-tasks** | high; needs a running env + auth |
### Coverage matrix โ€” which layer can conclude what
@@ -260,7 +260,7 @@ An audit is not finished when the findings are written โ€” it is finished when t
- **[ux](../ux/SKILL.md)** โ€” the execution checklists this audit measures against, and where
generalizable findings get landed.
-- **agent-testing** โ€” the automation framework L3 drives (agent-browser CDP: snapshot / eval
+- **acceptance** โ€” the automation framework L3 drives (agent-browser CDP: snapshot / eval
/ screenshot / GIF). L3 assumes its Step 0 env + auth are green.
- **deep-review** โ€” code-level review; this skill is its design-level sibling (deep-review's `ux` dimension checks flows inside a code review; this skill audits a whole surface).
- **skills-audit** โ€” the same "periodic, evidence-based audit" shape, applied to the skill
diff --git a/.agents/skills/ux-audit/references/layer-2-visual.md b/.agents/skills/ux-audit/references/layer-2-visual.md
index 3476bc162fc..df893737b44 100644
--- a/.agents/skills/ux-audit/references/layer-2-visual.md
+++ b/.agents/skills/ux-audit/references/layer-2-visual.md
@@ -15,12 +15,12 @@ Part of the **ux-audit** skill โ€” see [`../SKILL.md`](../SKILL.md).
- **User-supplied** โ€” the fastest anchor; a screenshot pasted into the chat is enough for a
first pass. Ask for the specific state/viewport you're missing.
-- **Captured via agent-testing** โ€” `agent-browser --cdp 9222 screenshot` renders from the
- renderer (works headless under `xvfb-run`). See the **agent-testing** skill for launch +
+- **Captured via the acceptance skill** โ€” `agent-browser --cdp 9222 screenshot` renders from the
+ renderer (works headless under `xvfb-run`). See the **acceptance** skill for launch +
auth (its Step 0). Capture the states you need; forcing hard-to-reach states (error,
empty) is an L3 job (see [layer-3-dynamic.md](layer-3-dynamic.md)).
- **Verify before citing.** Open every screenshot with the **Read tool** and confirm it
- shows what you claim _before_ writing a finding โ€” same rule agent-testing uses for
+ shows what you claim _before_ writing a finding โ€” same rule the acceptance skill uses for
evidence. A cited screenshot you didn't look at is a vibe, not evidence.
**Capture the set, not one frame:** the default state, plus (where reachable) empty /
diff --git a/.agents/skills/ux-audit/references/layer-3-dynamic.md b/.agents/skills/ux-audit/references/layer-3-dynamic.md
index 061eb6e82e3..ea9144bce40 100644
--- a/.agents/skills/ux-audit/references/layer-3-dynamic.md
+++ b/.agents/skills/ux-audit/references/layer-3-dynamic.md
@@ -5,7 +5,7 @@ It's the only layer that reaches states that exist only at runtime (in-progress,
error / empty), that verifies a **journey** stitches step-to-step, and that produces
**numbers** โ€” CLS, LCP, INP, long-tasks โ€” which no screenshot or code read can give.
-This layer runs on the **agent-testing** framework. Read that skill first; L3 assumes its
+This layer runs on the **acceptance** framework. Read that skill first; L3 assumes its
**Step 0 (env + auth)** is already green. Everything below is CDP-based, so it also works
headless in cloud under `xvfb-run`.
@@ -15,13 +15,13 @@ Part of the **ux-audit** skill โ€” see [`../SKILL.md`](../SKILL.md).
Connect to the running app (Electron or web) and use:
-| Command | Use in an audit |
-| ------------------------------------------------ | ------------------------------------------------------------------------------ |
-| `agent-browser --cdp 9222 snapshot -i` | accessibility/DOM tree + interactive elements (find controls, assert presence) |
-| `agent-browser --cdp 9222 screenshot` | render evidence at each step (feeds L2 checks) |
-| `agent-browser --cdp 9222 eval "<js>"` | **instrument** โ€” inject web-vitals, read state, force conditions |
-| `type` / `click` (see agent-testing `surfaces/`) | drive the journey |
-| `scripts/record-gif.sh` | time-based evidence (streaming, a layout jump) |
+| Command | Use in an audit |
+| --------------------------------------------- | ------------------------------------------------------------------------------ |
+| `agent-browser --cdp 9222 snapshot -i` | accessibility/DOM tree + interactive elements (find controls, assert presence) |
+| `agent-browser --cdp 9222 screenshot` | render evidence at each step (feeds L2 checks) |
+| `agent-browser --cdp 9222 eval "<js>"` | **instrument** โ€” inject web-vitals, read state, force conditions |
+| `type` / `click` (see acceptance `surfaces/`) | drive the journey |
+| `scripts/record-gif.sh` | time-based evidence (streaming, a layout jump) |
> **Constraint:** resizing the Electron window triggers a full SPA reload โ€” do **responsive
> / multi-viewport** sweeps against **web Chrome over CDP**, not by resizing Electron.
@@ -83,7 +83,7 @@ that shifted.
## Honest limits
-- Needs a running env + green auth (agent-testing Step 0); slower and more **flaky** than
+- Needs a running env + green auth (`.agents/acceptance/PROCESS.md` Step 2); slower and more **flaky** than
L1/L2 โ€” re-run a failed step before trusting it.
- Not every state is easy to force (some error paths need route-level mocking / fixtures).
- Screenshots captured here still need an L2 vision pass (Read the image before citing).
diff --git a/.agents/skills/ux/references/feedback.md b/.agents/skills/ux/references/feedback.md
index eb5d47b4530..8c713ed3c45 100644
--- a/.agents/skills/ux/references/feedback.md
+++ b/.agents/skills/ux/references/feedback.md
@@ -74,7 +74,7 @@ one sidebar โ€” a header read as 44 was really 36, a search box read as 32 was 3
title read as 28 was 26.9 โ€” and each error propagated into every anchor below it. Open the
real surface, read `getBoundingClientRect()` on each anchor, and build the skeleton from
those values. (To hold a route's pending state on screen long enough to measure, see the
-agent-testing skill's probe pattern for parking a lazy chunk.)
+acceptance skill's probe pattern for parking a lazy chunk.)
**Branch the skeleton wherever the real chrome branches.** Platform and feature conditions
that remove an element change the container's height: on macOS desktop
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 1685feeb7e1..5b3b14a6fe8 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -10,8 +10,8 @@ import { getTrpcClient } from '../api/client';
import { resolveServerUrl } from '../settings';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
-import type { IgnoreResult, LinkResult } from '../utils/skillWiring';
-import { ensureSkillIgnored, linkHarnessSkills } from '../utils/skillWiring';
+import type { LinkResult } from '../utils/skillWiring';
+import { linkHarnessSkills } from '../utils/skillWiring';
import { uploadLocalFile } from '../utils/uploadLocalFile';
import {
type Decision,
@@ -20,6 +20,7 @@ import {
evidenceTypeForFile,
genericContextFromResult,
inlineTextEvidenceForFile,
+ interactionCostFromReportDir,
metadataForReport,
originFromEnv,
parseSubjectRef,
@@ -49,7 +50,6 @@ import {
interface InstallOptions {
dir?: string;
force?: boolean;
- gitignore?: boolean;
json?: boolean | string;
skill: string;
}
@@ -70,7 +70,9 @@ async function installAction(options: InstallOptions): Promise<void> {
// 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.
+ // is a materialized artifact, re-installed to update, never hand-edited. It is
+ // meant to be COMMITTED: the consuming repo reviews skill changes like any
+ // other file, so install never writes an ignore entry for it.
const baseDir = options.dir ? path.resolve(options.dir) : process.cwd();
const skillDir = path.join(baseDir, '.agents', 'skills', bundle.identifier);
@@ -109,35 +111,34 @@ async function installAction(options: InstallOptions): Promise<void> {
}
const link = linkHarnessSkills(baseDir, bundle.identifier);
- const ignored =
- options.gitignore === false
- ? []
- : ensureSkillIgnored(baseDir, bundle.identifier, link.kind === 'linked');
const result = {
dir: skillDir,
- ignored,
link,
removed,
skill: bundle.identifier,
skipped,
+ // Recorded so a caller can tell which version now sits on disk; the
+ // installed SKILL.md carries the same value in its frontmatter.
+ version: bundle.version,
written,
};
if (options.json !== undefined) {
outputJson(result, typeof options.json === 'string' ? options.json : undefined);
return;
}
+ const versionLabel = bundle.version ? pc.dim(` v${bundle.version}`) : '';
console.log(
- `${pc.green('โœ“')} ${pc.bold(bundle.name)} skill โ†’ ${pc.dim(path.relative(process.cwd(), skillDir) || skillDir)}`,
+ `${pc.green('โœ“')} ${pc.bold(bundle.name)}${versionLabel} skill โ†’ ${pc.dim(path.relative(process.cwd(), skillDir) || skillDir)}`,
);
console.log(
` ${written.length} written${skipped.length ? `, ${skipped.length} skipped` : ''}${removed.length ? `, ${removed.length} stale removed` : ''}`,
);
if (skipped.length > 0) console.log(pc.dim(` (skipped existing โ€” pass --force to overwrite)`));
- printWiring(link, ignored);
+ printWiring(link);
}
-function printWiring(link: LinkResult, ignored: IgnoreResult[]): void {
+function printWiring(link: LinkResult): void {
const arrow = pc.dim(' โ†ณ');
switch (link.kind) {
case 'linked':
@@ -157,13 +158,6 @@ function printWiring(link: LinkResult, ignored: IgnoreResult[]): void {
break;
}
}
-
- for (const entry of ignored) {
- if (entry.kind !== 'added') continue;
- console.log(
- `${arrow} ignored ${entry.entry} in ${pc.dim(path.relative(process.cwd(), entry.file))}`,
- );
- }
}
// โ”€โ”€ run โ”€โ”€
@@ -688,6 +682,10 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
// Strictly the authoring conversation. `--operation` names the Agent Run
// under test and is passed to `createRun` below โ€” a different relation.
const origin = originFromEnv();
+ // A UI run that traced its actions prices them here, with the platform's own
+ // counting logic; a run without a trace just has no interaction cost.
+ const tracedCost = interactionCostFromReportDir(dir, result);
+ if (tracedCost) result.interactionCost = tracedCost;
const newRunMetadata = metadataForReport(result, undefined, origin);
if (acceptance.status === 'accepted' || acceptance.status === 'closed') {
@@ -898,7 +896,6 @@ function withInstallOptions(cmd: Command): Command {
.option('--dir <path>', 'Target working directory (default: current dir)')
.option('--skill <id>', 'Skill identifier to pull', 'acceptance')
.option('--force', 'Overwrite existing skill files')
- .option('--no-gitignore', 'Do not record the installed skill in .gitignore')
.option('--json [fields]', 'Output JSON');
}
diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.ts
index a993815a637..f52a3158b0b 100644
--- a/apps/cli/src/commands/verify.test.ts
+++ b/apps/cli/src/commands/verify.test.ts
@@ -852,6 +852,102 @@ describe('verify ingest-report โ€” every run is an immutable acceptance round',
);
});
+ it('prices a recorded interaction trace with the platform counting logic', async () => {
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ const atom = (operators: Record<string, number>) =>
+ JSON.stringify({
+ klm: { category: 'action', operators },
+ phase: { id: 'login', label: 'Login' },
+ schema: 'lobehub.agentBrowserKlmTrace@1',
+ });
+ writeFileSync(
+ path.join(dir, 'interaction-trace.jsonl'),
+ `${atom({ K: 1, P: 1 })}\n${atom({ R_ms: 2000 })}\n`,
+ );
+
+ await run(['ingest-report', dir, '--json']);
+
+ expect(verify.createRun.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ interactionCost: expect.objectContaining({
+ activeSeconds: 1.3,
+ model: 'goms-klm@lobe-v1',
+ sourceTrace: 'interaction-trace.jsonl',
+ totalSeconds: 3.3,
+ }),
+ }),
+ }),
+ );
+ });
+
+ it('publishes without interaction cost when no trace was recorded', async () => {
+ // A CLI-only round, or a machine with no agent-browser, records no trace.
+ // Interaction cost is an optional overlay: absent must stay silent, never a
+ // warning and never a 0s measurement rendered as a real one.
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ const warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
+
+ await run(['ingest-report', dir, '--json']);
+
+ const metadata = verify.createRun.mutate.mock.calls[0][0].metadata;
+ expect(metadata?.interactionCost).toBeUndefined();
+ expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining('interaction'));
+ warnSpy.mockRestore();
+ });
+
+ it('still prices the trace when result.json scaffolds interactionCost as null', async () => {
+ // Regression (found by running the flow): `report-init.sh` writes
+ // `"interactionCost": null` to document the field. Treating key presence as
+ // an explicit summary made the project's own scaffolder silently suppress
+ // pricing on every traced round it created.
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ writeFileSync(
+ path.join(dir, 'result.json'),
+ JSON.stringify({ cases: [], interactionCost: null }),
+ );
+ writeFileSync(
+ path.join(dir, 'interaction-trace.jsonl'),
+ `${JSON.stringify({
+ klm: { category: 'action', operators: { P: 1 } },
+ schema: 'lobehub.agentBrowserKlmTrace@1',
+ })}\n`,
+ );
+
+ await run(['ingest-report', dir, '--json']);
+
+ expect(verify.createRun.mutate.mock.calls[0][0].metadata.interactionCost).toMatchObject({
+ totalSeconds: 1.1,
+ });
+ });
+
+ it('keeps an explicit result.json interactionCost over the trace', async () => {
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ writeFileSync(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [],
+ interactionCost: {
+ activeSeconds: 9,
+ model: 'hand-written',
+ operators: {},
+ totalSeconds: 9,
+ waitSeconds: 0,
+ },
+ }),
+ );
+ writeFileSync(
+ path.join(dir, 'interaction-trace.jsonl'),
+ `${JSON.stringify({ klm: { operators: { P: 1 } } })}\n`,
+ );
+
+ await run(['ingest-report', dir, '--json']);
+
+ expect(verify.createRun.mutate.mock.calls[0][0].metadata.interactionCost.model).toBe(
+ 'hand-written',
+ );
+ });
+
it('finishes the human (non-json) output path for a non-coding report', async () => {
// Regression: `pullRequest` was block-scoped inside the coding branch while
// the text success output still read it, so every non-json ingest crashed
@@ -1222,6 +1318,29 @@ describe('lh acceptance โ€” canonical run tree', () => {
rmSync(dir, { force: true, recursive: true });
});
+ it('reports the installed version and leaves it in the SKILL.md on disk', async () => {
+ // The version is what a later install compares against, so it has to survive
+ // in two places: the JSON result, and the frontmatter of the materialized
+ // file (the copy a builder actually reads).
+ const dir = mkdtempSync(path.join(tmpdir(), 'acceptance-version-'));
+ mockTrpcClient.verify.getSkillBundle.query.mockReset().mockResolvedValue({
+ content: '---\nname: acceptance\nversion: 1.0.0\n---\n\n# Acceptance SKILL',
+ files: {},
+ identifier: 'acceptance',
+ name: 'acceptance',
+ version: '1.0.0',
+ });
+
+ await run(['install', '--dir', dir, '--json']);
+
+ const printed = JSON.parse(consoleSpy.mock.calls.at(-1)![0] as string);
+ expect(printed.version).toBe('1.0.0');
+ expect(
+ readFileSync(path.join(dir, '.agents', 'skills', 'acceptance', 'SKILL.md'), 'utf8'),
+ ).toContain('version: 1.0.0');
+ rmSync(dir, { force: true, recursive: true });
+ });
+
it('removes stale materialized resources on `acceptance update`', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'acceptance-update-'));
mockTrpcClient.verify.getSkillBundle.query.mockReset().mockResolvedValueOnce({
diff --git a/apps/cli/src/commands/verifyHelpers.ts b/apps/cli/src/commands/verifyHelpers.ts
index 12a5f09482d..8b24464e313 100644
--- a/apps/cli/src/commands/verifyHelpers.ts
+++ b/apps/cli/src/commands/verifyHelpers.ts
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import type {
@@ -10,6 +10,7 @@ import type {
} from '@lobechat/const/verify';
import {
acceptanceSubjectTypes,
+ GOMS_KLM_TRACE_FILE,
isProgrammaticTestCheck,
normalizeVerifySurface,
PROGRAMMATIC_TEST_CHECK_HINT,
@@ -19,12 +20,14 @@ import {
} from '@lobechat/const/verify';
import type {
VerifyCheckResultMetadata,
+ VerifyInteractionCost,
VerifyVisualizationDataset,
VerifyVisualizationField,
VerifyVisualizationManifest,
VerifyVisualizationValue,
VerifyVisualizationView,
} from '@lobechat/types';
+import { parseKlmTrace, summarizeKlmTrace } from '@lobechat/utils/verify/interactionCost';
import pc from 'picocolors';
import { printTable, truncate } from '../utils/format';
@@ -797,6 +800,50 @@ export function originFromEnv(): VerifyRunOrigin | undefined {
return Object.values(origin).some(Boolean) ? origin : undefined;
}
+/**
+ * Derive the round's GOMS-KLM interaction cost from a trace dropped in the
+ * report directory, so the number the page shows is always the platform's own
+ * counting of the recorded actions.
+ *
+ * Interaction cost is an optional overlay. A round with no UI driver โ€” a CLI
+ * verification, or a machine without agent-browser โ€” simply has no trace, and
+ * that is silently skipped, never a warning and never a failure. A driver that
+ * computed its own summary still wins.
+ *
+ * "Its own summary" means an actual object. A scaffolded `result.json` carries
+ * `"interactionCost": null` to document the field, and a null is the absence of
+ * a measurement, not an assertion that this round cost nothing โ€” treating mere
+ * key presence as an override let the report scaffolder silently suppress
+ * pricing on every traced run it created.
+ */
+export function interactionCostFromReportDir(
+ dir: string,
+ result: Record<string, unknown>,
+): VerifyInteractionCost | undefined {
+ if (objectValue(result.interactionCost)) return undefined;
+
+ const tracePath = path.join(dir, GOMS_KLM_TRACE_FILE);
+ if (!existsSync(tracePath)) return undefined;
+
+ let raw: string;
+ try {
+ raw = readFileSync(tracePath, 'utf8');
+ } catch {
+ log.warn(`${GOMS_KLM_TRACE_FILE} could not be read โ€” publishing without interaction cost`);
+ return undefined;
+ }
+
+ const cost = summarizeKlmTrace(parseKlmTrace(raw), { sourceTrace: GOMS_KLM_TRACE_FILE });
+ if (!cost) {
+ log.warn(
+ `${GOMS_KLM_TRACE_FILE} recorded no priceable action (driver missing, or every action blocked) โ€” skipping interaction cost`,
+ );
+ return undefined;
+ }
+
+ return cost;
+}
+
export function metadataForReport(
result: Record<string, unknown>,
existingMetadata?: unknown,
diff --git a/apps/cli/src/utils/skillLocator.test.ts b/apps/cli/src/utils/skillLocator.test.ts
deleted file mode 100644
index 35ded6fc89f..00000000000
--- a/apps/cli/src/utils/skillLocator.test.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { findCliRoot, locateBundledSkill } from './skillLocator';
-
-let root: string;
-
-beforeEach(() => {
- root = mkdtempSync(path.join(tmpdir(), 'skill-locator-'));
-});
-
-afterEach(() => {
- rmSync(root, { recursive: true, force: true });
-});
-
-function writeCliPackage(cliRoot: string, version = '1.2.3') {
- mkdirSync(cliRoot, { recursive: true });
- writeFileSync(
- path.join(cliRoot, 'package.json'),
- JSON.stringify({ name: '@lobehub/cli', version }),
- );
-}
-
-describe('findCliRoot', () => {
- it('finds the package root from a built dist/ layout', () => {
- const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');
- writeCliPackage(cliRoot);
- const distDir = path.join(cliRoot, 'dist');
- mkdirSync(distDir, { recursive: true });
-
- expect(findCliRoot(distDir)).toBe(cliRoot);
- });
-
- it('finds the package root from the monorepo dev entry (src/) layout', () => {
- const cliRoot = path.join(root, 'apps', 'cli');
- writeCliPackage(cliRoot);
- const srcDir = path.join(cliRoot, 'src');
- mkdirSync(srcDir, { recursive: true });
-
- expect(findCliRoot(srcDir)).toBe(cliRoot);
- });
-
- it('ignores intermediate package.json files that are not @lobehub/cli', () => {
- const cliRoot = path.join(root, 'apps', 'cli');
- writeCliPackage(cliRoot);
- const utilsDir = path.join(cliRoot, 'src', 'utils');
- mkdirSync(utilsDir, { recursive: true });
- writeFileSync(
- path.join(cliRoot, 'src', 'package.json'),
- JSON.stringify({ name: 'not-the-cli' }),
- );
-
- expect(findCliRoot(utilsDir)).toBe(cliRoot);
- });
-
- it('returns undefined when no matching package.json exists up to the filesystem root', () => {
- const dir = path.join(root, 'some', 'unrelated', 'dir');
- mkdirSync(dir, { recursive: true });
-
- expect(findCliRoot(dir)).toBeUndefined();
- });
-});
-
-describe('locateBundledSkill', () => {
- it('resolves cliRoot, skillDir, and version from a simulated package layout', () => {
- const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');
- writeCliPackage(cliRoot, '9.9.9');
- const skillDir = path.join(cliRoot, 'skills', 'agent-testing');
- mkdirSync(skillDir, { recursive: true });
- writeFileSync(path.join(skillDir, 'SKILL.md'), '# agent-testing');
- const distDir = path.join(cliRoot, 'dist');
- mkdirSync(distDir, { recursive: true });
-
- const result = locateBundledSkill('agent-testing', distDir);
-
- expect(result.cliRoot).toBe(cliRoot);
- expect(result.skillDir).toBe(skillDir);
- expect(result.version).toBe('9.9.9');
- });
-
- it('throws when the package root cannot be found', () => {
- const dir = path.join(root, 'nowhere');
- mkdirSync(dir, { recursive: true });
-
- expect(() => locateBundledSkill('agent-testing', dir)).toThrow(/package root/);
- });
-
- it('throws when the package root exists but the skill directory is missing', () => {
- const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');
- writeCliPackage(cliRoot);
- const distDir = path.join(cliRoot, 'dist');
- mkdirSync(distDir, { recursive: true });
-
- expect(() => locateBundledSkill('agent-testing', distDir)).toThrow(/not found/);
- });
-
- it('resolves against the real apps/cli agent-testing skill by default', () => {
- const result = locateBundledSkill();
- expect(result.skillDir.endsWith(path.join('skills', 'agent-testing'))).toBe(true);
- });
-});
diff --git a/apps/cli/src/utils/skillLocator.ts b/apps/cli/src/utils/skillLocator.ts
deleted file mode 100644
index c4b6fb5b2b9..00000000000
--- a/apps/cli/src/utils/skillLocator.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { existsSync, readFileSync } from 'node:fs';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { cliPackageName } from '../pkg';
-
-export interface BundledSkill {
- cliRoot: string;
- skillDir: string;
- version: string;
-}
-
-// Anchored to a package.json name match rather than a fixed relative depth
-// because the caller's own file lives at a different depth in the built
-// dist/index.js layout (global install / npx) vs. the monorepo dev entry
-// (bun src/index.ts).
-export function findCliRoot(startDir: string): string | undefined {
- let dir = startDir;
- while (true) {
- const pkgPath = path.join(dir, 'package.json');
- if (existsSync(pkgPath)) {
- try {
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
- if (pkg && pkg.name === cliPackageName) return dir;
- } catch {
- // Not a readable/valid package.json โ€” keep walking up.
- }
- }
- const parent = path.dirname(dir);
- if (parent === dir) return undefined;
- dir = parent;
- }
-}
-
-// startDir is anchored to this module's own location by the caller
-// (import.meta.url), never process.cwd() โ€” resolution must not depend on
-// where the CLI happens to be invoked from.
-export function locateBundledSkill(
- skillName = 'agent-testing',
- startDir: string = path.dirname(fileURLToPath(import.meta.url)),
-): BundledSkill {
- const cliRoot = findCliRoot(startDir);
- if (!cliRoot) {
- throw new Error(
- `Could not locate the ${cliPackageName} package root walking up from ${startDir}. ` +
- 'The CLI install may be corrupted.',
- );
- }
-
- const skillDir = path.join(cliRoot, 'skills', skillName);
- if (!existsSync(skillDir)) {
- throw new Error(
- `Bundled skill "${skillName}" not found at ${skillDir}. ` +
- `The ${cliPackageName} install may be missing its skills/ directory.`,
- );
- }
-
- const pkg = JSON.parse(readFileSync(path.join(cliRoot, 'package.json'), 'utf8'));
-
- return { cliRoot, skillDir, version: pkg.version };
-}
diff --git a/apps/cli/src/utils/skillWiring.test.ts b/apps/cli/src/utils/skillWiring.test.ts
index 092d8f9aa38..6df45da3df6 100644
--- a/apps/cli/src/utils/skillWiring.test.ts
+++ b/apps/cli/src/utils/skillWiring.test.ts
@@ -4,7 +4,6 @@ import {
lstatSync,
mkdirSync,
mkdtempSync,
- readFileSync,
readlinkSync,
rmSync,
symlinkSync,
@@ -15,7 +14,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { detectClaudeHarness, ensureSkillIgnored, linkHarnessSkills } from './skillWiring';
+import { detectClaudeHarness, linkHarnessSkills } from './skillWiring';
let root: string;
@@ -102,97 +101,26 @@ describe('linkHarnessSkills', () => {
});
});
-describe('ensureSkillIgnored', () => {
- it('skips entirely outside a git repository', () => {
- expect(ensureSkillIgnored(root, 'acceptance', false)).toEqual([
- { kind: 'skipped', reason: 'not a git repository' },
- ]);
- expect(existsSync(path.join(root, '.gitignore'))).toBe(false);
- });
-
- it('records the skill in a nested .agents/skills/.gitignore that also ignores itself', () => {
- gitInit(root);
-
- const results = ensureSkillIgnored(root, 'acceptance', false);
-
- expect(results[0]).toMatchObject({ entry: '/acceptance/', kind: 'added' });
- const nested = path.join(root, '.agents', 'skills', '.gitignore');
- expect(readFileSync(nested, 'utf8')).toBe('/.gitignore\n/acceptance/\n');
- expect(existsSync(path.join(root, '.gitignore'))).toBe(false);
- });
-
- it('leaves git status clean after wiring a fresh project', () => {
+describe('install wiring never writes .gitignore', () => {
+ // The materialized acceptance skill is checked into the consuming repo, so
+ // wiring must leave every ignore file untouched โ€” an ignored skill dir would
+ // silently keep it out of review.
+ it('leaves the repo without any generated ignore entry', () => {
gitInit(root);
writeFileSync(path.join(root, 'CLAUDE.md'), '# project');
mkdirSync(path.join(root, '.agents', 'skills', 'acceptance'), { recursive: true });
writeFileSync(path.join(root, '.agents', 'skills', 'acceptance', 'SKILL.md'), '# skill');
- const link = linkHarnessSkills(root, 'acceptance');
- ensureSkillIgnored(root, 'acceptance', link.kind === 'linked');
- execFileSync('git', ['add', '.gitignore', 'CLAUDE.md'], { cwd: root, stdio: 'ignore' });
+ linkHarnessSkills(root, 'acceptance');
+
+ expect(existsSync(path.join(root, '.gitignore'))).toBe(false);
+ expect(existsSync(path.join(root, '.agents', 'skills', '.gitignore'))).toBe(false);
const status = execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], {
cwd: root,
encoding: 'utf8',
});
- expect(status).not.toContain('.agents/skills/.gitignore');
- expect(status).not.toContain('.agents/skills/acceptance');
- expect(status).not.toContain('.claude/skills');
- });
-
- it('does not seed the self-ignore into a pre-existing nested file', () => {
- gitInit(root);
- mkdirSync(path.join(root, '.agents', 'skills'), { recursive: true });
- writeFileSync(path.join(root, '.agents', 'skills', '.gitignore'), '/legacy/\n');
-
- ensureSkillIgnored(root, 'acceptance', false);
-
- expect(readFileSync(path.join(root, '.agents', 'skills', '.gitignore'), 'utf8')).toBe(
- '/legacy/\n/acceptance/\n',
- );
- });
-
- it('does not duplicate an entry on re-run', () => {
- gitInit(root);
- ensureSkillIgnored(root, 'acceptance', false);
-
- const results = ensureSkillIgnored(root, 'acceptance', false);
-
- expect(results[0]).toMatchObject({ entry: '/acceptance/', kind: 'present' });
- expect(readFileSync(path.join(root, '.agents', 'skills', '.gitignore'), 'utf8')).toBe(
- '/.gitignore\n/acceptance/\n',
- );
- });
-
- it('adds the root .gitignore line when we created the link and git does not ignore it', () => {
- gitInit(root);
- writeFileSync(path.join(root, '.gitignore'), 'node_modules\n');
-
- ensureSkillIgnored(root, 'acceptance', true);
-
- expect(readFileSync(path.join(root, '.gitignore'), 'utf8')).toBe(
- 'node_modules\n/.claude/skills\n',
- );
- });
-
- it('leaves the root .gitignore alone when .claude is already ignored', () => {
- gitInit(root);
- writeFileSync(path.join(root, '.gitignore'), '.claude/\n');
-
- ensureSkillIgnored(root, 'acceptance', true);
-
- expect(readFileSync(path.join(root, '.gitignore'), 'utf8')).toBe('.claude/\n');
- });
-
- it('appends a missing trailing newline before the new entry', () => {
- gitInit(root);
- writeFileSync(path.join(root, '.gitignore'), 'node_modules');
-
- ensureSkillIgnored(root, 'acceptance', true);
-
- expect(readFileSync(path.join(root, '.gitignore'), 'utf8')).toBe(
- 'node_modules\n/.claude/skills\n',
- );
+ expect(status).toContain('.agents/skills/acceptance/SKILL.md');
});
});
diff --git a/apps/cli/src/utils/skillWiring.ts b/apps/cli/src/utils/skillWiring.ts
index 882bceeeb03..ad8094c4908 100644
--- a/apps/cli/src/utils/skillWiring.ts
+++ b/apps/cli/src/utils/skillWiring.ts
@@ -1,13 +1,4 @@
-import { execFileSync } from 'node:child_process';
-import {
- existsSync,
- lstatSync,
- mkdirSync,
- readFileSync,
- readlinkSync,
- symlinkSync,
- writeFileSync,
-} from 'node:fs';
+import { existsSync, lstatSync, mkdirSync, readlinkSync, symlinkSync } from 'node:fs';
import path from 'node:path';
export const AGENTS_SKILLS_DIR = path.join('.agents', 'skills');
@@ -19,11 +10,6 @@ export type LinkResult =
| { kind: 'none' }
| { kind: 'skipped'; link: string; reason: string };
-export type IgnoreResult =
- | { kind: 'added'; entry: string; file: string }
- | { kind: 'present'; entry: string; file: string }
- | { kind: 'skipped'; reason: string };
-
export function detectClaudeHarness(baseDir: string): boolean {
return existsSync(path.join(baseDir, 'CLAUDE.md')) || existsSync(path.join(baseDir, '.claude'));
}
@@ -83,66 +69,3 @@ export function linkHarnessSkills(baseDir: string, skillId: string): LinkResult
}
return { kind: 'linked', link: rel, target };
}
-
-function findGitRoot(startDir: string): string | undefined {
- let dir = startDir;
- while (true) {
- if (existsSync(path.join(dir, '.git'))) return dir;
- const parent = path.dirname(dir);
- if (parent === dir) return undefined;
- dir = parent;
- }
-}
-
-function isIgnoredByGit(baseDir: string, relPath: string): boolean {
- try {
- execFileSync('git', ['check-ignore', '-q', '--', relPath], { cwd: baseDir, stdio: 'ignore' });
- return true;
- } catch {
- return false;
- }
-}
-
-function appendIgnoreEntry(file: string, entry: string): IgnoreResult {
- const existing = existsSync(file) ? readFileSync(file, 'utf8') : '';
- if (existing.split('\n').some((line) => line.trim() === entry)) {
- return { entry, file, kind: 'present' };
- }
- const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
- writeFileSync(file, `${existing}${prefix}${entry}\n`, 'utf8');
- return { entry, file, kind: 'added' };
-}
-
-/**
- * Nested `.agents/skills/.gitignore` owns the list of materialized skills, so the
- * project's root file stays untouched โ€” it only gains a line when we created the
- * `.claude/skills` symlink and git isn't ignoring it already.
- */
-export function ensureSkillIgnored(
- baseDir: string,
- skillId: string,
- createdRootLink: boolean,
-): IgnoreResult[] {
- if (!findGitRoot(baseDir)) return [{ kind: 'skipped', reason: 'not a git repository' }];
-
- const results: IgnoreResult[] = [];
- const skillsDir = path.join(baseDir, AGENTS_SKILLS_DIR);
- mkdirSync(skillsDir, { recursive: true });
-
- // A file we generate must not itself become untracked noise. Git still reads an
- // ignore file that ignores itself, so seeding this line keeps `git status`
- // clean. Only when we create it โ€” an existing file is the project's own.
- const nested = path.join(skillsDir, '.gitignore');
- if (!existsSync(nested)) appendIgnoreEntry(nested, '/.gitignore');
-
- results.push(appendIgnoreEntry(nested, `/${skillId}/`));
-
- if (createdRootLink) {
- const rel = '.claude/skills';
- if (!isIgnoredByGit(baseDir, rel)) {
- results.push(appendIgnoreEntry(path.join(baseDir, '.gitignore'), `/${rel}`));
- }
- }
-
- return results;
-}
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index a0ab5d72fb6..bfc3e17e5e2 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -642,6 +642,9 @@ export const verifyRouter = router({
),
identifier: skill.identifier,
name: skill.name,
+ // The skill's own declared version, so an installer can compare a copy
+ // already on disk against the latest bundle.
+ version: skill.version,
};
}),
diff --git a/packages/builtin-skills/src/acceptance/SKILL.md b/packages/builtin-skills/src/acceptance/SKILL.md
index 5cd8d9ec122..253848ab79f 100644
--- a/packages/builtin-skills/src/acceptance/SKILL.md
+++ b/packages/builtin-skills/src/acceptance/SKILL.md
@@ -1,15 +1,17 @@
---
name: acceptance
+version: 0.1.0
description: >
- Self-evidence for delivery verification in any repository, with or without
- LOBE_OPERATION_ID or a preconfigured verify plan. Discover an existing plan
- when present; otherwise author checks and publish a standalone acceptance.
- Pick the proving surface (CLI / web / desktop / iOS Simulator), capture real
- evidence, and submit it with the lh CLI. Triggers on 'verify the task',
- 'collect evidence',
- 'prove it works', 'upload evidence', 'verify plan', 'requiredEvidence', or any
- run that must self-certify its delivery. Missing LobeHub environment IDs never
- make this skill inapplicable.
+ End-to-end verification and self-evidence for a delivery in any repository,
+ with or without a preconfigured verify plan. Discover an existing plan when
+ one was handed to this run; otherwise author checks and publish a standalone
+ acceptance. Pick the proving surface (CLI / web / desktop / iOS Simulator),
+ drive the real product, capture visually confirmed evidence, and publish a
+ round with the lh CLI. Triggers on 'verify the task', 'collect evidence',
+ 'prove it works', 'upload evidence', 'verify plan', 'requiredEvidence',
+ 'local test', 'manual test', 'test report', 'test with cli', 'test in
+ electron', 'test desktop', or any local end-to-end verification task. Needs no
+ ambient ids, and never depends on running inside a LobeHub conversation.
---
# Verify (Builder Self-Evidence)
@@ -21,23 +23,54 @@ criterion that declares `requiredEvidence` **cannot pass on your text alone**:
if the artifact is missing, the structural gate marks it `uncertain` and the
delivery is held.
+## Read the project layer first (when the repository has one)
+
+Before touching an environment, check for `.agents/acceptance/`. A repository
+that verifies itself keeps its own layer there, and it outranks any guess you
+would otherwise make:
+
+| File | What it owns |
+| ------------------------ | ------------------------------------------------------------ |
+| `PROJECT.md` | Start/stop commands, ports, services, auth, surfaces, probes |
+| `PROCESS.md` | The run process: approval gate, execution rules, teardown |
+| `common-mistakes.md` | Project living log โ€” what earlier rounds got wrong here |
+| `probe-mock-patterns.md` | Project living log โ€” how to force state on this product |
+
+**The division of labor:** the project layer owns _how this repository is run_;
+this skill owns _what a valid acceptance round is_ (plan, evidence, report,
+immutable round, the hard rule below). Where they disagree on running, the
+project layer wins. Where they disagree on what may be published, this skill
+wins. Never invent a start command, a port, or an auth flow that `PROJECT.md`
+already answers, and never work around a divergence silently โ€” fix the adapter
+in place during the run.
+
+No `.agents/acceptance/` means the repository has no project layer yet. Continue
+with the portable path below; if the run needs an adapter, bootstrap one first โ€”
+[project-adapter.md](references/project-adapter.md).
+
+Read both living-log layers before executing a round that drives a product
+surface: this skill's generic
+[common-mistakes.md](references/common-mistakes.md) and
+[probe-mock-patterns.md](references/probe-mock-patterns.md), plus the project's
+own copies. Record new project-specific learnings in the project layer only.
+
## Applicability invariant
-This skill applies whenever the delivery needs real verification. Environment
-IDs select a path; they are not prerequisites:
+This skill applies whenever the delivery needs real verification. **It requires
+no ids at all** โ€” nothing about it is conditional on where it runs:
-- `$LOBE_OPERATION_ID` means a verify plan already exists. Discover and satisfy
- it.
-- No `$LOBE_OPERATION_ID` means you author the checks and publish a structured
- report round.
-- `$LOBEHUB_TOPIC_ID` or `--subject` groups rounds under an existing LobeHub
- object.
-- No topic or subject means `lh acceptance run ingest` creates a standalone
- acceptance automatically.
+- **Were you handed an operation id** (a verify plan already exists for this
+ run)? Discover that plan and satisfy it.
+- **Otherwise** โ€” the normal case โ€” author the checks yourself and publish a
+ structured report round.
+- **Attaching to something specific?** Pass `--subject` (`task:<id>`,
+ `topic:<id>`, or `document:<id>`) when the caller named one. Otherwise omit it:
+ `lh acceptance run ingest` attaches the round itself when it can, and creates a
+ standalone acceptance when it cannot.
-Never report that this skill is inapplicable merely because
-`$LOBE_OPERATION_ID`, `$LOBEHUB_TOPIC_ID`, or a Task ID is absent. Continue with
-the standalone path.
+Never report this skill inapplicable, and never go hunting through the
+environment for an id to make it applicable. Missing ids are the default state,
+not a degraded one.
So while you do the work, capture the proof and submit it. The loop:
@@ -52,21 +85,24 @@ or fixed report directory are required.
## Two entry points โ€” an operation id is NOT required
-Every evidence command targets a **verification session** (a round). How you
-name that session is a choice, not a prerequisite:
+Every evidence command targets a **verification session** (a round). How you name
+that session is a choice, not a prerequisite:
+
+| You have | Target the round with | Path |
+| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
+| An operation id you were given | `--operation "$OPERATION_ID"` | This document: discover the plan, satisfy its criteria |
+| No plan โ€” you author the checks | Publish a whole directory with `lh acceptance run ingest`; it creates the round and, when needed, a standalone acceptance | [references/report.md](references/report.md) |
-| You have | Target the round with | Path |
-| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
-| A verify plan (`$LOBE_OPERATION_ID` set) | `--operation "$LOBE_OPERATION_ID"` | This document: discover the plan, satisfy its criteria |
-| No plan โ€” you author the checks | Publish a whole directory with `lh acceptance run ingest`; it creates the round and, when needed, a standalone acceptance | [references/report.md](references/report.md) |
+**The authored path is the default.** You have an operation id only when the
+invocation names one โ€” a task, a caller, or the user hands it to you. Do not read
+the environment looking for one, and do not treat its absence as a problem to
+solve: a round created without an operation is simply recorded as `standalone`.
`--operation` and `--run` are interchangeable on `result submit` and
-`result list`; a round created without an operation is simply recorded as
-`standalone`. (`evidence list` takes neither โ€” it keys off a positional
-`<checkResultId>` you read from `result list`.) **A missing operation id never
-means "skip the acceptance"** โ€” it only means you author the plan instead of
-discovering it. On a later repair round, pass the previously printed
-`--acceptance <acceptanceId>` so the new snapshot joins the same history.
+`result list`. (`evidence list` takes neither โ€” it keys off a positional
+`<checkResultId>` you read from `result list`.) On a later repair round, pass the
+previously printed `--acceptance <acceptanceId>` so the new snapshot joins the
+same history.
On the first ingest, always supply `--requirement "<one-sentence business goal>"`.
The requirement describes what the whole acceptance judges, not the narrower
@@ -129,9 +165,8 @@ stay internal.
- **`lh` is authed.** Confirm with `lh acceptance run list --json` (an empty `[]`
means authed; an auth error means stop and surface it).
-- **A round path.** Use `$LOBE_OPERATION_ID` when supplied. Otherwise author a
- structured report; ingest creates both its round and, outside LobeHub, its
- standalone acceptance.
+- **A round path.** Use the operation id when this run was given one. Otherwise
+ author a structured report; ingest creates both its round and its acceptance.
- **Install only the UI driver required by the selected surface.** Web/Electron
use `agent-browser`; native iOS uses Xcode/`simctl` plus a Simulator HID/AX CLI
such as AXe, or the repository's existing UI-test driver. Probe installed tools
@@ -146,10 +181,10 @@ stay internal.
> recipes below to capture its evidence. Publish that authored plan and its
> cases together with `lh acceptance run ingest`.
-One read tells you what to prove:
+One read tells you what to prove (`$OPERATION_ID` is the id this run was given):
```bash
-lh verify plan state "$LOBE_OPERATION_ID" --json
+lh verify plan state "$OPERATION_ID" --json
```
Each `verifyPlan[]` item carries `id` (the **checkItemId**), `title`, `required`,
@@ -203,6 +238,12 @@ Rules of thumb:
Simulator HID/Accessibility CLI for taps, long press, swipe, pan, and UI-tree
inspection; use `simctl` for lifecycle/framebuffer capture. If the available
CLI cannot express the planned touch sequence, mark the case `blocked`.
+- **A UI round may also price its interaction cost.** While driving the product,
+ record each action's raw KLM operator counts into `interaction-trace.jsonl` in
+ the report directory; ingest prices them with the platform's pinned timing
+ model. It is an optional overlay โ€” a CLI round, or a machine with no UI driver
+ installed, records no trace and publishes normally. Never hand-write the
+ numbers. See [interaction-cost.md](references/interaction-cost.md).
- **Auth is a gate, scoped to the surface.** If the state under test is behind a
login, authenticate that surface first or every capture lands on the sign-in
page. Follow the selected surface's Auth section; load
@@ -220,12 +261,12 @@ lazily creates/updates the result row, and attaches the evidence โ€” one call, n
```bash
# CHECK_ITEM_ID is the plan item id for this criterion (from Step 1).
# file artifact already captured by the selected surface
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type "$EVIDENCE_TYPE" --file "$ARTIFACT_PATH" --by "$PROVENANCE" \
--desc "Observed state after the planned action"
# inline text artifact (stdout / computed value) โ€” no file
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type text --content "$(your-cli command --json)" --by cli \
--desc "command reports success after the change"
```
@@ -246,7 +287,7 @@ is present. After submitting, the result rows exist, so map each `checkItemId` t
its `checkResultId` and list that row's evidence:
```bash
-lh acceptance run result list --operation "$LOBE_OPERATION_ID" --json # checkItemId โ†’ checkResultId
+lh acceptance run result list --operation "$OPERATION_ID" --json # checkItemId โ†’ checkResultId
lh acceptance run evidence list "$CHECK_RESULT_ID" --json
```
@@ -289,8 +330,12 @@ Load detailed references only after selecting the applicable path:
| Need | Reference |
| ------------------------------------------------------ | ------------------------------------------------------------------- |
+| The project layer, and bootstrapping an adapter | [project-adapter.md](references/project-adapter.md) |
+| Verification mistakes to self-check against | [common-mistakes.md](references/common-mistakes.md) |
+| Forcing state, error injection, runtime probes | [probe-mock-patterns.md](references/probe-mock-patterns.md) |
| Existing verify-plan schema and join keys | [plan-format.md](references/plan-format.md) |
| Shared media, provenance, submission, and safety rules | [evidence.md](references/evidence.md) |
+| Interaction cost for a UI round (optional overlay) | [interaction-cost.md](references/interaction-cost.md) |
| Authored structured rounds and `result.json` | [report.md](references/report.md) |
| Web/Electron Chromium CLI commands | [agent-browser.md](references/agent-browser.md) |
| Authenticated Web session | [auth-web.md](references/auth-web.md) |
diff --git a/packages/builtin-skills/src/acceptance/index.test.ts b/packages/builtin-skills/src/acceptance/index.test.ts
index d6918d422be..6cc57550919 100644
--- a/packages/builtin-skills/src/acceptance/index.test.ts
+++ b/packages/builtin-skills/src/acceptance/index.test.ts
@@ -4,6 +4,8 @@ import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
+import { AcceptanceSkill } from './index';
+
const skillDir = path.dirname(fileURLToPath(import.meta.url));
const readMarkdownBundle = (directory: string): string =>
readdirSync(directory, { withFileTypes: true })
@@ -14,6 +16,13 @@ const readMarkdownBundle = (directory: string): string =>
})
.join('\n');
+const listMarkdown = (directory: string): string[] =>
+ readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const filePath = path.join(directory, entry.name);
+ if (entry.isDirectory()) return listMarkdown(filePath);
+ return entry.name.endsWith('.md') ? [path.relative(skillDir, filePath)] : [];
+ });
+
const skillContent = readFileSync(path.join(skillDir, 'SKILL.md'), 'utf8');
const skillBundle = readMarkdownBundle(skillDir);
@@ -28,6 +37,40 @@ describe('AcceptanceSkill', () => {
);
});
+ it('ships every reference on disk โ€” an unregistered file never reaches a builder', () => {
+ // The bundle is built from `resources`, not from the directory: a reference
+ // added to the folder but not registered here is invisible to every puller
+ // while still looking present in the repo.
+ const onDisk = listMarkdown(skillDir)
+ .filter((file) => file !== 'SKILL.md')
+ .sort();
+
+ expect(Object.keys(AcceptanceSkill.resources ?? {}).sort()).toEqual(onDisk);
+ });
+
+ it('carries a version parsed from its own SKILL.md frontmatter', () => {
+ // The version must reach the bundle, not just sit in the markdown: an
+ // installer compares `bundle.version` against the copy already on disk, and
+ // a version only a human can read makes that impossible.
+ expect(skillContent).toMatch(/^version: \d+\.\d+\.\d+$/m);
+ expect(AcceptanceSkill.version).toMatch(/^\d+\.\d+\.\d+$/);
+ });
+
+ it('names no host environment variable โ€” the skill needs no ambient ids', () => {
+ // The skill is portable and runs anywhere. Instructing a builder to read
+ // `$LOBEHUB_TOPIC_ID` / `$LOBE_OPERATION_ID` both couples it to one host and
+ // invites it to hunt for an id that is absent by design; the CLI resolves
+ // subject and origin from its own env without the agent's help.
+ expect(skillBundle).not.toMatch(/LOBEHUB_[A-Z_]+/);
+ expect(skillBundle).not.toMatch(/LOBE_OPERATION_ID/);
+ });
+
+ it('routes to the project layer before touching an environment', () => {
+ expect(skillContent).toContain('.agents/acceptance/');
+ expect(skillContent).toContain('PROCESS.md');
+ expect(skillContent).toContain('project-adapter.md');
+ });
+
it('keeps the latest evidence and multi-round acceptance contracts', () => {
expect(skillBundle).toContain('Dual text evidence for non-visual behavior');
expect(skillContent).toContain('lh acceptance view <acceptanceId | type:id> --json');
diff --git a/packages/builtin-skills/src/acceptance/index.ts b/packages/builtin-skills/src/acceptance/index.ts
index 79bc8b99fca..b5b3d8747ad 100644
--- a/packages/builtin-skills/src/acceptance/index.ts
+++ b/packages/builtin-skills/src/acceptance/index.ts
@@ -1,11 +1,15 @@
import type { BuiltinSkill } from '@lobechat/types';
-import { toResourceMeta } from '../lobehub/helpers';
+import { readSkillVersion, toResourceMeta } from '../lobehub/helpers';
import agentBrowser from './references/agent-browser.md';
import authWeb from './references/auth-web.md';
+import commonMistakes from './references/common-mistakes.md';
import computerUse from './references/computer-use.md';
import evidence from './references/evidence.md';
+import interactionCost from './references/interaction-cost.md';
import planFormat from './references/plan-format.md';
+import probeMockPatterns from './references/probe-mock-patterns.md';
+import projectAdapter from './references/project-adapter.md';
import recordingCdp from './references/recording-cdp.md';
import recordingIosSimulator from './references/recording-ios-simulator.md';
import recordingNativeMacos from './references/recording-native-macos.md';
@@ -20,15 +24,20 @@ import web from './surfaces/web.md';
export const AcceptanceIdentifier = 'acceptance';
/**
- * Portable builder-side acceptance skill. Unlike the repo-local `agent-testing`
- * skill (macOS scripts + project-specific working artifacts and probes), this one
- * keeps its acceptance contract independent of repository-local scripts, so any
- * external builder (Claude Code / Codex) can run it from a task's working
- * directory, with or without a LobeHub operation/topic: discover or author the
- * plan โ†’ pick a surface โ†’ capture evidence per criterion โ†’ publish a round โ†’
- * self-check coverage. Surface-specific tools remain explicit: agent-browser for
- * Web/Electron, shell-level native automation for macOS, and an installed
- * Simulator HID/Accessibility CLI plus Xcode/simctl for iOS.
+ * The single builder-side acceptance skill: discover or author the plan โ†’ pick a
+ * surface โ†’ capture evidence per criterion โ†’ publish a round โ†’ self-check
+ * coverage. It runs from any task's working directory, with or without a LobeHub
+ * operation/topic, and depends on no repository-local script. Surface-specific
+ * tools stay explicit: agent-browser for Web/Electron, shell-level native
+ * automation for macOS, and an installed Simulator HID/Accessibility CLI plus
+ * Xcode/simctl for iOS.
+ *
+ * Everything a specific repository needs on top โ€” its start/stop commands, its
+ * approval gate and teardown, its own living logs and probe scripts โ€” lives in
+ * that repository's `.agents/acceptance/` project layer, which SKILL.md reads
+ * first. This split replaced the former repo-local `agent-testing` skill: the
+ * contract is here, the repository's process is there, and neither restates the
+ * other.
*
* The references carry the shared contracts and surface-scoped operating
* manuals. Authentication and recording resources are split by runtime so a
@@ -37,20 +46,30 @@ export const AcceptanceIdentifier = 'acceptance';
* 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.
+ *
+ * `version` is read from SKILL.md's own frontmatter rather than declared here,
+ * so there is one place to bump and an installed copy on disk always states the
+ * version it carries. Bump it whenever a change alters what a builder must DO โ€”
+ * a new required step, a changed contract or vocabulary, a moved reference โ€”
+ * not for a typo or a reworded sentence.
*/
export const AcceptanceSkill: BuiltinSkill = {
avatar: 'โœ…',
content,
description:
- 'Self-evidence for delivery acceptance in any repository, with or without a LobeHub operation or verify plan โ€” discover or author checks, verify CLI, web, desktop, or iOS Simulator behavior on the correct surface, capture real evidence, and publish a standalone or subject-linked acceptance round.',
+ 'End-to-end verification and self-evidence for a delivery in any repository, with or without a LobeHub operation or verify plan โ€” discover or author checks, drive CLI, web, desktop, or iOS Simulator on the correct surface, capture visually confirmed evidence, and publish a standalone or subject-linked acceptance round. Reads the repositoryโ€™s own `.agents/acceptance/` project layer when one exists.',
identifier: AcceptanceIdentifier,
name: 'acceptance',
resources: toResourceMeta({
'references/agent-browser.md': agentBrowser,
+ 'references/common-mistakes.md': commonMistakes,
'references/auth-web.md': authWeb,
'references/computer-use.md': computerUse,
'references/evidence.md': evidence,
+ 'references/interaction-cost.md': interactionCost,
'references/plan-format.md': planFormat,
+ 'references/probe-mock-patterns.md': probeMockPatterns,
+ 'references/project-adapter.md': projectAdapter,
'references/recording-cdp.md': recordingCdp,
'references/recording-ios-simulator.md': recordingIosSimulator,
'references/recording-native-macos.md': recordingNativeMacos,
@@ -62,4 +81,5 @@ export const AcceptanceSkill: BuiltinSkill = {
'surfaces/web.md': web,
}),
source: 'builtin',
+ version: readSkillVersion(content),
};
diff --git a/packages/builtin-skills/src/acceptance/references/agent-browser.md b/packages/builtin-skills/src/acceptance/references/agent-browser.md
index 96c5282b0a7..721ce8e6eb2 100644
--- a/packages/builtin-skills/src/acceptance/references/agent-browser.md
+++ b/packages/builtin-skills/src/acceptance/references/agent-browser.md
@@ -88,6 +88,15 @@ agent-browser wait --text "Welcome" # Wait for text to appear
agent-browser wait --fn "!document.body.innerText.includes('Loading...')" # Wait for condition
agent-browser wait "#spinner" --state hidden # Wait for element to disappear
+# Downloads
+agent-browser download @e1 ./file.pdf # Click an element to trigger a download
+agent-browser wait --download ./output.zip # Wait for a download to finish
+
+# Diff (compare page states)
+agent-browser diff snapshot # Current vs the last snapshot
+agent-browser diff screenshot --baseline before.png # Visual pixel diff
+agent-browser diff url <url1> <url2> # Compare two pages
+
# Network (key for full-stack evidence)
agent-browser network requests # Inspect tracked requests
agent-browser network requests --type xhr,fetch # Filter by resource type
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/packages/builtin-skills/src/acceptance/references/common-mistakes.md
similarity index 96%
rename from .agents/skills/agent-testing/references/common-mistakes.md
rename to packages/builtin-skills/src/acceptance/references/common-mistakes.md
index 29101944045..d9bcb67da52 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/packages/builtin-skills/src/acceptance/references/common-mistakes.md
@@ -1,16 +1,16 @@
# 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/acceptance/common-mistakes.md` (the writable project layer).
+> **This is the GENERIC layer of the living log.** It ships with the skill, so a
+> consumer repo's copy is materialized and read-only โ€” change it by PR to the
+> skill source. Every entry here must be **product-independent**: no project's
+> packages, routes, schemas, env vars, service names, or business logic. Those go
+> to `.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
-> 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.
+> **Read this file in full before executing a round that drives a product
+> surface**, and self-check against each case before calling a check passed. 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.
---
@@ -34,6 +34,14 @@ 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.
+**The mirror case โ€” asserting a feature is ABSENT by grep.** Searching the page
+text for a feature's name to prove it is _not_ rendered is worse than the positive
+case, because your own report prose is on that page: an acceptance whose goal
+sentence names the feature will match its own words and report the feature as
+present. When the claim is about presence or absence of a UI section, assert it
+against structured state (the API/metadata that drives it, or a located DOM node),
+not against a substring of the rendered text.
+
---
## M2 โ€” Goal is verifying error states, but stopping at happy-path because injection is hard
diff --git a/packages/builtin-skills/src/acceptance/references/evidence.md b/packages/builtin-skills/src/acceptance/references/evidence.md
index 72538ec9923..bdf6695324d 100644
--- a/packages/builtin-skills/src/acceptance/references/evidence.md
+++ b/packages/builtin-skills/src/acceptance/references/evidence.md
@@ -29,7 +29,7 @@ page gives the reviewer a player.
```bash
# The generated file is the evidence โ€” attach the artifact the feature produced,
# not a re-encode and not a screenshot of the player.
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type audio --file ./out/tts-zh-female.mp3 --by program \
--desc "TTS output for ใ€ŒไปŠๅคฉๅคฉๆฐ”ไธ้”™ใ€, zh-CN female voice, 2.4s"
```
@@ -69,12 +69,12 @@ join an explanation from an older round with fresh execution output.
```bash
# File artifact captured by the selected surface.
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type "$EVIDENCE_TYPE" --file "$ARTIFACT_PATH" --by "$PROVENANCE" \
--desc "Observed state after the planned action"
# Short text assertion.
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" \
+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \
--type text --content "$ASSERTION_OUTPUT" --by cli \
--desc "Machine-readable assertion output"
```
diff --git a/packages/builtin-skills/src/acceptance/references/interaction-cost.md b/packages/builtin-skills/src/acceptance/references/interaction-cost.md
new file mode 100644
index 00000000000..dfa3918a801
--- /dev/null
+++ b/packages/builtin-skills/src/acceptance/references/interaction-cost.md
@@ -0,0 +1,75 @@
+# Interaction cost (GOMS-KLM)
+
+An optional overlay for **UI rounds**: while you drive the product, record what a
+person would have had to do to reach the same state. The round then carries a
+_user-equivalent_ interaction cost, so a flow can be judged on what it costs to
+walk, not just on whether it passed.
+
+**Where it surfaces:** in that round's report, as its own collapsible section โ€”
+which on the acceptance page opens from the round history, available to the
+acceptance owner. It is not part of the shared aggregate a non-owner viewer
+sees, so never promise a reviewer they will see it there.
+
+**Skip it whenever it does not apply.** A CLI or backend round has no interaction
+to price. A machine without a UI driver installed (no `agent-browser`) records no
+trace. In both cases you publish exactly as usual โ€” no trace file, no cost
+section, no warning. Never hand-write the numbers to fill the gap.
+
+## The seam: you count actions, the platform prices them
+
+You never compute seconds. The driver appends one JSON atom per action to
+`interaction-trace.jsonl` in the report directory, carrying raw **operator
+counts**; `lh acceptance run ingest` finds that file and prices it with the
+platform's pinned timing model (`goms-klm@lobe-v1`).
+
+That split is the point: every round is priced by one model, and any published
+number can be recomputed from its trace. A summary you calculated yourself is not
+comparable with anyone else's.
+
+```jsonl
+{"schema":"lobehub.agentBrowserKlmTrace@1","type":"action","phase":{"id":"login","label":"Sign in"},"klm":{"category":"action","operators":{"P":1,"K":1}},"durationMs":840}
+{"schema":"lobehub.agentBrowserKlmTrace@1","type":"mental_estimate","phase":{"id":"first-view"},"klm":{"category":"mental","operators":{"M":2}},"mentalEstimate":{"score":3,"confidence":0.75,"reason":"Reading the state and deciding the next action"}}
+```
+
+| Field | Meaning |
+| -------------------- | -------------------------------------------------------------------------- |
+| `schema` | Must be `lobehub.agentBrowserKlmTrace@1`; a foreign tag is not summed |
+| `phase.id` / `label` | Groups atoms into a step of the journey; `phase.checkItemId` links a check |
+| `klm.operators` | Raw counts โ€” see the operator table below |
+| `klm.category` | `action` \| `mental` \| `blocked` โ€” `blocked` charges nothing |
+| `durationMs` | Agent wall-clock, reported separately from the user-equivalent price |
+
+## Operators
+
+| Operator | Counts | Typical source |
+| --------- | ----------------------------------------- | ------------------------------------ |
+| `P` | Pointing at a target | `click`, drag |
+| `K` | One keystroke / button press | `click` (the press), `press` |
+| `T_chars` | Characters typed | `fill`, `type` |
+| `H` | Homing between keyboard and pointer | Switching input device |
+| `M` | Mental preparation โ€” **estimated by you** | Deciding, locating, reading state |
+| `R_ms` | Measured system wait, in ms โ€” not modeled | Navigation / load the user waits out |
+
+Two rules keep the number honest:
+
+- **An action that did not happen costs nothing.** A failed, timed-out, or
+ blocked command is recorded with `"category":"blocked"` and zero operators.
+ Never charge a retry loop as if a person performed it.
+- **`M` is an estimate, and it is yours.** Record it explicitly at the moments a
+ person would actually have to think โ€” first view of a screen, choosing between
+ options, re-orienting after a state change โ€” with a short reason. Do not
+ sprinkle it on every action to inflate the total.
+
+## Publishing
+
+Leave `interaction-trace.jsonl` in the report directory and publish normally:
+
+```bash
+lh acceptance run ingest "$REPORT_DIR" --source agent-testing --json
+```
+
+Ingest computes `interactionCost` and stores it on the round. If a trace exists
+but records nothing priceable โ€” every action blocked, for instance โ€” the round
+publishes without a cost section rather than claiming a 0s journey. An explicit
+`result.json.interactionCost` is left untouched, so a driver that already
+computed a summary is never overwritten.
diff --git a/packages/builtin-skills/src/acceptance/references/plan-format.md b/packages/builtin-skills/src/acceptance/references/plan-format.md
index 34fba656d0c..130555ace97 100644
--- a/packages/builtin-skills/src/acceptance/references/plan-format.md
+++ b/packages/builtin-skills/src/acceptance/references/plan-format.md
@@ -6,7 +6,7 @@ documents its shape and how to turn it into a per-criterion worklist. You submit
each criterion's evidence by its `checkItemId` โ€” no separate upload handle to
resolve.
-## (a) `lh verify plan state $LOBE_OPERATION_ID --json`
+## (a) `lh verify plan state $OPERATION_ID --json`
Returns the run's verify state plus the **frozen plan** (immutable once
confirmed):
@@ -51,7 +51,7 @@ The plan (a) is all you need. For each `verifyPlan[]` item with non-empty
| `vci_a1b2c3` | Login flow reaches the workspace | `screenshot` |
```bash
-OP="$LOBE_OPERATION_ID"
+OP="$OPERATION_ID"
lh acceptance run result submit --operation "$OP" --item vci_a1b2c3 --type screenshot \
--file ./proof/home.png --by agent-browser --desc "โ€ฆ"
```
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/packages/builtin-skills/src/acceptance/references/probe-mock-patterns.md
similarity index 98%
rename from .agents/skills/agent-testing/references/probe-mock-patterns.md
rename to packages/builtin-skills/src/acceptance/references/probe-mock-patterns.md
index ccd04568959..3e7cf9a1684 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/packages/builtin-skills/src/acceptance/references/probe-mock-patterns.md
@@ -1,10 +1,11 @@
# 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/acceptance/probe-mock-patterns.md` (the writable project layer).
+> **This is the GENERIC layer of the living log.** It ships with the skill, so a
+> consumer repo's copy is materialized and read-only โ€” change it by PR to the
+> skill source. 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/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.
diff --git a/.agents/skills/agent-testing/references/project-adapter.md b/packages/builtin-skills/src/acceptance/references/project-adapter.md
similarity index 79%
rename from .agents/skills/agent-testing/references/project-adapter.md
rename to packages/builtin-skills/src/acceptance/references/project-adapter.md
index b08723088f0..7b1ebf922bc 100644
--- a/.agents/skills/agent-testing/references/project-adapter.md
+++ b/packages/builtin-skills/src/acceptance/references/project-adapter.md
@@ -1,4 +1,4 @@
-# Project Adapter (`.agents/acceptance/PROJECT.md`)
+# Project layer (`.agents/acceptance/`)
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
@@ -6,14 +6,25 @@ surfaces it has, and how to jump straight into app state โ€” lives in a per-proj
adapter at `.agents/acceptance/PROJECT.md`. The skill reads it; it never guesses the
project's commands.
+A repository that verifies itself often has more than commands to share: an
+approval gate before touching the environment, a teardown discipline, a publish
+target, a report directory convention. Those live beside the adapter in
+`.agents/acceptance/PROCESS.md`. **When that file exists it owns the run process,
+and this skill supplies the acceptance contract** โ€” plan, evidence, report,
+round. Read both before executing; where they disagree about _how to run_, the
+project layer wins, and where they disagree about _what a valid round is_, this
+skill wins.
+
## Where the adapter lives
```text
-<repo>/.agents/acceptance/ # committed โ€” the adapter and project logs are team assets
-โ”œโ”€โ”€ PROJECT.md # the adapter (this contract)
+<repo>/.agents/acceptance/ # committed โ€” the adapter and project logs are team assets
+โ”œโ”€โ”€ PROJECT.md # the adapter: commands, ports, services, auth, surfaces
+โ”œโ”€โ”€ PROCESS.md # optional: the project's run process (gate, teardown, publish)
โ”œโ”€โ”€ common-mistakes.md # PROJECT-layer living log (writable)
โ”œโ”€โ”€ probe-mock-patterns.md # PROJECT-layer living log (writable)
-โ””โ”€โ”€ scripts/ # optional: project env / probe scripts
+โ”œโ”€โ”€ references/ # optional: project-owned how-tos
+โ””โ”€โ”€ scripts/ # optional: project env / probe / capture scripts
```
`.agents/acceptance/` is **committed** (the adapter and the project living logs are
@@ -55,7 +66,7 @@ anywhere in the repo.
## Copy-pasteable template
```markdown
-# PROJECT.md โ€” agent-testing adapter for <project name>
+# PROJECT.md โ€” acceptance adapter for <project name>
## 1. Project summary
@@ -120,7 +131,7 @@ which directory/package is the server, the web app, the desktop shell, the CLI.>
- <e.g. "OS-capture surfaces are macOS-only">
```
-## First-run bootstrap (SKILL.md Step 0.5)
+## First-run bootstrap
When `.agents/acceptance/PROJECT.md` is absent, build it before doing anything else:
@@ -139,9 +150,9 @@ When `.agents/acceptance/PROJECT.md` is absent, build it before doing anything e
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
-bootstraps `PROJECT.md`.
+`lh acceptance 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
@@ -153,10 +164,15 @@ 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
+are the **generic layer** โ€” product-independent, and read-only in a consumer repo:
+the installed copy is materialized from the skill source, so an edit there is lost
+on the next update. Change it by PR to the skill source. The project's own
`.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
every project-specific noun) and PR it to the generic layer upstream.
+
+**Confidentiality runs one way.** Anything naming a project's packages, routes,
+schemas, env vars, service names, or business logic stays in the project layer;
+only a rule that reads correctly with every project noun removed may be promoted.
diff --git a/packages/builtin-skills/src/acceptance/references/report.md b/packages/builtin-skills/src/acceptance/references/report.md
index 7045a816219..34e335ec9f7 100644
--- a/packages/builtin-skills/src/acceptance/references/report.md
+++ b/packages/builtin-skills/src/acceptance/references/report.md
@@ -1,9 +1,9 @@
# Structured Report Rounds (`lh acceptance run ingest`)
Per-criterion `result submit` (SKILL.md Step 3) assumes a verify plan already
-exists. When it doesn't โ€” a standalone delivery, a task run without
-`$LOBE_OPERATION_ID`, or any run where **you** author the checks โ€” publish a
-**structured report round** instead: a self-contained directory that
+exists. When it doesn't โ€” a standalone delivery, or any run where **you** author
+the checks, which is the usual case โ€” publish a **structured report round**
+instead: a self-contained directory that
`lh acceptance run ingest` uploads as one immutable verification round. The
acceptance page renders itself from `result.json`: provenance, the overall
conclusion, and the check list from `plan[]` paired with `cases[]`, each with
@@ -38,7 +38,7 @@ lh acceptance run ingest "$REPORT_DIR" \
# Re-verification โ€” append a new immutable round to the same acceptance
lh acceptance run ingest "$REPORT_DIR" --acceptance "$ACCEPTANCE_ID" --json
-# Existing LobeHub subject โ€” group by a Task, Topic, or Document
+# Attach to a subject you were told to use โ€” a Task, Topic, or Document
lh acceptance run ingest "$REPORT_DIR" --subject topic:tpc_xxx --json
# B. atomic fallback โ€” create the round first, then submit into it with --run
@@ -122,9 +122,10 @@ supersedes? }`.
Describe the durable goal of the whole acceptance, not this round's narrower
implementation scope.
- Inside a LobeHub topic, the command groups the round under the current topic.
- Outside one, it creates a standalone acceptance automatically; no Task ID is
- required. To publish a repair into that same history, add
+ Grouping needs nothing from you: the command attaches the round to the
+ conversation it was invoked from when it can, and otherwise creates a
+ standalone acceptance. Pass `--subject` only when you were told which Task,
+ Topic, or Document owns the work. To publish a repair into that same history, add
`--acceptance <acceptanceId>` using the ID printed by the first ingest. The
command uploads cases + evidence + report body and prints
`/acceptance/<acceptanceId>` plus its `?r=<roundIndex>` snapshot form. Include
diff --git a/packages/builtin-skills/src/acceptance/surfaces/cli.md b/packages/builtin-skills/src/acceptance/surfaces/cli.md
index 6e0e57abe0f..68bdf4feeb3 100644
--- a/packages/builtin-skills/src/acceptance/surfaces/cli.md
+++ b/packages/builtin-skills/src/acceptance/surfaces/cli.md
@@ -19,18 +19,18 @@ about rendered UI.
```bash
# CHECK_ITEM_ID is the criterion's plan item id (from `lh verify plan state`).
# short result โ†’ inline
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$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 acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$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 acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \
+lh acceptance run result submit --operation "$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/acceptance/surfaces/native.md b/packages/builtin-skills/src/acceptance/surfaces/native.md
index 92994a72049..f481542e264 100644
--- a/packages/builtin-skills/src/acceptance/surfaces/native.md
+++ b/packages/builtin-skills/src/acceptance/surfaces/native.md
@@ -34,7 +34,7 @@ Upload as evidence (provenance `cli`, since osascript/screencapture are
shell-driven):
```bash
-lh acceptance run result submit --operation "$LOBE_OPERATION_ID" --item "$CHECK_ITEM_ID" --type screenshot \
+lh acceptance run result submit --operation "$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/lobehub/helpers.test.ts b/packages/builtin-skills/src/lobehub/helpers.test.ts
new file mode 100644
index 00000000000..97d5ca19dd3
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/helpers.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { readSkillVersion } from './helpers';
+
+const skill = (frontmatter: string) => `---\n${frontmatter}\n---\n\n# Body\n`;
+
+describe('readSkillVersion', () => {
+ it('reads the version declared in the frontmatter', () => {
+ expect(readSkillVersion(skill('name: acceptance\nversion: 1.2.3'))).toBe('1.2.3');
+ });
+
+ it('strips quotes so a YAML-quoted version is comparable', () => {
+ expect(readSkillVersion(skill("name: acceptance\nversion: '2.0.0'"))).toBe('2.0.0');
+ });
+
+ it('returns undefined for a skill that declares no version', () => {
+ // Every other builtin skill is unversioned today; that must stay legal.
+ expect(readSkillVersion(skill('name: artifacts\ndescription: x'))).toBeUndefined();
+ });
+
+ it('ignores a version line nested inside a block scalar', () => {
+ // `description: >` continuation lines are indented, and their prose can
+ // easily contain "version:". Only a column-zero key is the real field.
+ const content = skill(
+ 'name: acceptance\ndescription: >\n Bump the version: 9.9.9 when asked.',
+ );
+
+ expect(readSkillVersion(content)).toBeUndefined();
+ });
+
+ it('returns undefined when there is no frontmatter at all', () => {
+ expect(readSkillVersion('# Just a document\n\nversion: 1.0.0\n')).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-skills/src/lobehub/helpers.ts b/packages/builtin-skills/src/lobehub/helpers.ts
index ad6865ee722..d67bd898b21 100644
--- a/packages/builtin-skills/src/lobehub/helpers.ts
+++ b/packages/builtin-skills/src/lobehub/helpers.ts
@@ -17,3 +17,34 @@ export const toResourceMeta = (
]),
);
};
+
+/** Matches only the leading YAML frontmatter block of a `SKILL.md`. */
+const FRONTMATTER_BLOCK = /^---\r?\n([\S\s]*?)\r?\n---/;
+
+/**
+ * Read a skill's declared `version` out of its `SKILL.md` frontmatter.
+ *
+ * The frontmatter is the single source of truth: the same file is what gets
+ * materialized onto a builder's disk, so an installed copy always carries the
+ * version it was installed at โ€” which is what makes an install-time
+ * "your copy is N, latest is M" comparison possible without a side-car marker
+ * file that can drift from the content it describes.
+ *
+ * Deliberately a small regex rather than a YAML parser: this package is imported
+ * by the server, the CLI, and the desktop workspace stub, and one scalar field
+ * does not justify a parser dependency in all three. The key must sit at column
+ * zero, so an indented `version:` inside a block scalar (`description: >`) is
+ * correctly ignored.
+ */
+export const readSkillVersion = (content: string): string | undefined => {
+ const block = FRONTMATTER_BLOCK.exec(content)?.[1];
+ if (!block) return undefined;
+
+ const line = block.split(/\r?\n/).find((entry) => entry.startsWith('version:'));
+ const value = line
+ ?.slice('version:'.length)
+ .trim()
+ .replaceAll(/^['"]|['"]$/g, '');
+
+ return value || undefined;
+};
diff --git a/packages/builtin-skills/vitest.config.mts b/packages/builtin-skills/vitest.config.mts
index 52f86e133c7..e15af983972 100644
--- a/packages/builtin-skills/vitest.config.mts
+++ b/packages/builtin-skills/vitest.config.mts
@@ -1,6 +1,20 @@
-import { defineConfig } from 'vitest/config';
+import { defineConfig, type Plugin } from 'vitest/config';
+
+/**
+ * Skill content is authored as real `.md` files and imported as strings. The app
+ * bundlers already do this; vitest needs its own loader before a test can import
+ * a skill module (rather than only reading its files off disk).
+ */
+const rawMarkdown = (): Plugin => ({
+ name: 'builtin-skills-raw-markdown',
+ transform(code, id) {
+ if (!id.endsWith('.md')) return null;
+ return { code: `export default ${JSON.stringify(code)};`, map: null };
+ },
+});
export default defineConfig({
+ plugins: [rawMarkdown()],
test: {
coverage: {
provider: 'v8',
diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.ts
index fc1becb6e67..bc5b1f27dbc 100644
--- a/packages/const/src/verify.ts
+++ b/packages/const/src/verify.ts
@@ -365,3 +365,37 @@ export interface VerifyRunOrigin {
/** The topic to reopen to continue from this report. */
topicId?: string;
}
+
+/**
+ * GOMS-KLM interaction cost โ€” the standard model for pricing a verification
+ * round's *user-equivalent* interaction cost.
+ *
+ * The seam is deliberate: a UI driver (the acceptance skill's agent-browser
+ * wrapper) only emits raw **operator counts** per action into a JSONL trace; the
+ * platform turns counts into seconds with the timing model below. Keeping the
+ * timing here rather than in the driver means every report is priced by one
+ * model, and any published `interactionCost` can be recomputed from its trace.
+ */
+export const GOMS_KLM_MODEL = 'goms-klm@lobe-v1';
+
+/** Schema tag every trace atom carries; a foreign tag is not summed. */
+export const GOMS_KLM_TRACE_SCHEMA = 'lobehub.agentBrowserKlmTrace@1';
+
+/**
+ * Conventional trace filename inside a report directory. `acceptance run ingest`
+ * picks it up automatically โ€” absent means the round simply has no interaction
+ * cost (a CLI-only run, or a machine without agent-browser), never an error.
+ */
+export const GOMS_KLM_TRACE_FILE = 'interaction-trace.jsonl';
+
+/**
+ * Seconds per KLM operator (Card, Moran & Newell), tuned for pointer-driven web
+ * UI. `T_char` prices one typed character; `R_ms` is measured wait, not modeled.
+ */
+export const GOMS_KLM_TIMING_SECONDS = {
+ H: 0.4,
+ K: 0.2,
+ M: 1.35,
+ P: 1.1,
+ T_char: 0.2,
+} as const;
diff --git a/packages/types/src/skill/index.ts b/packages/types/src/skill/index.ts
index 3f90a5e2e6e..5100fae0a4c 100644
--- a/packages/types/src/skill/index.ts
+++ b/packages/types/src/skill/index.ts
@@ -61,6 +61,13 @@ export interface BuiltinSkill {
* the raw `agent-skills:lobe-annotation-cleanup`.
*/
title?: string;
+ /**
+ * Declared in the skill's own `SKILL.md` frontmatter and parsed from it, so a
+ * copy materialized onto a builder's disk carries the version it was installed
+ * at. Lets an installer compare an existing copy against the latest bundle
+ * instead of blindly overwriting or blindly skipping.
+ */
+ version?: string;
}
// ===== Skill Source =====
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 3f5b191c8ed..1d091e91000 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -507,6 +507,8 @@ export interface VerifyInteractionCostOperators {
export interface VerifyInteractionCostPhase {
actionCount?: number;
activeSeconds?: number;
+ /** Wall-clock the agent actually spent here โ€” not the user-equivalent price. */
+ actualAgentSeconds?: number;
checkItemId?: string;
id: string;
label?: string;
diff --git a/packages/utils/src/verify/interactionCost.test.ts b/packages/utils/src/verify/interactionCost.test.ts
new file mode 100644
index 00000000000..5a722fdf1e7
--- /dev/null
+++ b/packages/utils/src/verify/interactionCost.test.ts
@@ -0,0 +1,114 @@
+import { GOMS_KLM_MODEL, GOMS_KLM_TRACE_SCHEMA } from '@lobechat/const/verify';
+import { describe, expect, it } from 'vitest';
+
+import { parseKlmTrace, summarizeKlmTrace } from './interactionCost';
+
+const atom = (overrides: Record<string, unknown> = {}) => ({
+ klm: { category: 'action', operators: { K: 0, M: 0, P: 1, R_ms: 0, T_chars: 0 } },
+ phase: { id: 'login', label: 'Login' },
+ schema: GOMS_KLM_TRACE_SCHEMA,
+ ...overrides,
+});
+
+describe('parseKlmTrace', () => {
+ it('reads one atom per line and ignores blanks', () => {
+ const raw = `${JSON.stringify(atom())}\n\n${JSON.stringify(atom())}\n`;
+
+ expect(parseKlmTrace(raw)).toHaveLength(2);
+ });
+
+ it('drops a truncated line instead of failing the whole trace', () => {
+ const raw = `${JSON.stringify(atom())}\n{"klm":{"operators":{"P":1`;
+
+ expect(parseKlmTrace(raw)).toHaveLength(1);
+ });
+});
+
+describe('summarizeKlmTrace', () => {
+ it('prices operators with the pinned timing model', () => {
+ const cost = summarizeKlmTrace([
+ atom({ klm: { category: 'action', operators: { K: 1, P: 1 } } }),
+ atom({ klm: { category: 'action', operators: { M: 1, R_ms: 2000 } } }),
+ ]);
+
+ // P 1.1 + K 0.2 + M 1.35 = 2.65 active, plus 2s measured wait.
+ expect(cost?.activeSeconds).toBe(2.65);
+ expect(cost?.waitSeconds).toBe(2);
+ expect(cost?.totalSeconds).toBe(4.65);
+ expect(cost?.model).toBe(GOMS_KLM_MODEL);
+ expect(cost?.operators).toEqual({ H: 0, K: 1, M: 1, P: 1, R_ms: 2000, T_chars: 0 });
+ });
+
+ it('reproduces the wrapper smoke run: click + fill + wait + mental estimate', () => {
+ // The exact scenario `.agents/acceptance/scripts/agent-browser-klm.test.sh`
+ // records โ€” that script now only asserts the operator counts, so the pricing
+ // half of the old analyzer lives here.
+ const cost = summarizeKlmTrace([
+ atom({ klm: { category: 'action', operators: { K: 1, P: 1 } }, phase: { id: 'first' } }),
+ atom({ klm: { category: 'action', operators: { P: 1, T_chars: 5 } }, phase: { id: 'form' } }),
+ atom({ klm: { category: 'wait', operators: { R_ms: 2000 } }, phase: { id: 'wait' } }),
+ atom({
+ klm: { category: 'mental', operators: { M: 2 } },
+ phase: { id: 'first' },
+ type: 'mental_estimate',
+ }),
+ ]);
+
+ expect(cost?.activeSeconds).toBe(6.1);
+ expect(cost?.waitSeconds).toBe(2);
+ expect(cost?.totalSeconds).toBe(8.1);
+ expect(cost?.phases?.[0].id).toBe('first');
+ });
+
+ it('groups by phase and sorts the most expensive first', () => {
+ const cost = summarizeKlmTrace([
+ atom({ klm: { operators: { P: 1 } }, phase: { id: 'login', label: 'Login' } }),
+ atom({ klm: { operators: { P: 3 } }, phase: { id: 'compose', label: 'Compose' } }),
+ ]);
+
+ expect(cost?.phases?.map((phase) => phase.id)).toEqual(['compose', 'login']);
+ expect(cost?.phases?.[0].seconds).toBe(3.3);
+ });
+
+ it('files unphased atoms under one unscoped bucket', () => {
+ const cost = summarizeKlmTrace([atom({ phase: undefined })]);
+
+ expect(cost?.phases?.[0]).toMatchObject({ id: 'unscoped', label: undefined });
+ });
+
+ it('separates agent wall-clock from the user-equivalent price', () => {
+ const cost = summarizeKlmTrace([atom({ durationMs: 8000, klm: { operators: { P: 1 } } })]);
+
+ expect(cost?.actualAgentSeconds).toBe(8);
+ expect(cost?.totalSeconds).toBe(1.1);
+ });
+
+ it('collects mental estimates with their phase', () => {
+ const cost = summarizeKlmTrace([
+ atom({
+ klm: { category: 'mental', operators: { M: 2 } },
+ mentalEstimate: { reason: 'first view', score: 3 },
+ type: 'mental_estimate',
+ }),
+ ]);
+
+ expect(cost?.mentalEstimates).toEqual([{ phaseId: 'login', reason: 'first view', score: 3 }]);
+ expect(cost?.categoryCounts).toEqual({ mental: 1 });
+ });
+
+ it('returns null for an empty trace rather than a 0s measurement', () => {
+ expect(summarizeKlmTrace([])).toBeNull();
+ });
+
+ it('returns null when every action was blocked', () => {
+ // No agent-browser on the machine: each command fails, the wrapper charges
+ // zero operators. Publishing that as a 0s cost would read as a free run.
+ const blocked = atom({ klm: { category: 'blocked', operators: {} } });
+
+ expect(summarizeKlmTrace([blocked, blocked])).toBeNull();
+ });
+
+ it('ignores atoms tagged with a foreign schema', () => {
+ expect(summarizeKlmTrace([atom({ schema: 'someone.else@2' })])).toBeNull();
+ });
+});
diff --git a/packages/utils/src/verify/interactionCost.ts b/packages/utils/src/verify/interactionCost.ts
new file mode 100644
index 00000000000..d2affa353ba
--- /dev/null
+++ b/packages/utils/src/verify/interactionCost.ts
@@ -0,0 +1,206 @@
+import {
+ GOMS_KLM_MODEL,
+ GOMS_KLM_TIMING_SECONDS,
+ GOMS_KLM_TRACE_SCHEMA,
+} from '@lobechat/const/verify';
+import type {
+ VerifyInteractionCost,
+ VerifyInteractionCostOperators,
+ VerifyInteractionCostPhase,
+} from '@lobechat/types';
+
+/**
+ * The standard GOMS-KLM counting logic for acceptance rounds.
+ *
+ * A UI driver records one atom per action into a JSONL trace, carrying only raw
+ * operator counts. This module is the single place those counts become seconds,
+ * so a published `interactionCost` is always reproducible from its trace instead
+ * of being whatever number a driver happened to compute.
+ *
+ * Interaction cost is an optional overlay: no driver, no trace, no cost. Callers
+ * treat an absent or unreadable trace as "this round has no interaction cost",
+ * never as a failure.
+ */
+
+/** One recorded interaction atom. Unknown fields are ignored, not rejected. */
+export interface KlmTraceEvent {
+ durationMs?: number;
+ klm?: {
+ category?: string;
+ operators?: VerifyInteractionCostOperators;
+ };
+ mentalEstimate?: Record<string, unknown>;
+ phase?: {
+ checkItemId?: string;
+ id?: string;
+ label?: string;
+ };
+ schema?: string;
+ type?: string;
+}
+
+const UNSCOPED_PHASE = 'unscoped';
+
+const emptyOperators = (): Required<VerifyInteractionCostOperators> => ({
+ H: 0,
+ K: 0,
+ M: 0,
+ P: 0,
+ R_ms: 0,
+ T_chars: 0,
+});
+
+const round = (value: number): number => Math.round(value * 100) / 100;
+
+const num = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) ? value : 0;
+
+const addOperators = (
+ target: Required<VerifyInteractionCostOperators>,
+ source: VerifyInteractionCostOperators = {},
+): void => {
+ target.H += num(source.H);
+ target.K += num(source.K);
+ target.M += num(source.M);
+ target.P += num(source.P);
+ target.R_ms += num(source.R_ms);
+ target.T_chars += num(source.T_chars);
+};
+
+/** Price only the operators a person performs; measured wait is charged separately. */
+const activeSeconds = (operators: Required<VerifyInteractionCostOperators>): number =>
+ round(
+ operators.H * GOMS_KLM_TIMING_SECONDS.H +
+ operators.K * GOMS_KLM_TIMING_SECONDS.K +
+ operators.M * GOMS_KLM_TIMING_SECONDS.M +
+ operators.P * GOMS_KLM_TIMING_SECONDS.P +
+ operators.T_chars * GOMS_KLM_TIMING_SECONDS.T_char,
+ );
+
+const totalSeconds = (operators: Required<VerifyInteractionCostOperators>): number =>
+ round(activeSeconds(operators) + operators.R_ms / 1000);
+
+/**
+ * Parse a trace file's contents. A malformed line is dropped rather than
+ * failing the whole trace โ€” a truncated last line (the run was killed mid-write)
+ * must not cost the round every atom before it.
+ */
+export const parseKlmTrace = (raw: string): KlmTraceEvent[] =>
+ raw
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .flatMap((line) => {
+ try {
+ const parsed = JSON.parse(line);
+ return parsed && typeof parsed === 'object' ? [parsed as KlmTraceEvent] : [];
+ } catch {
+ return [];
+ }
+ });
+
+interface SummarizeOptions {
+ /** Model id label; defaults to the pinned standard model. */
+ model?: string;
+ /** Trace filename recorded on the summary so a reader can re-derive it. */
+ sourceTrace?: string;
+}
+
+/**
+ * Sum a trace into the `interactionCost` shape the acceptance page renders.
+ *
+ * Returns `null` when nothing priceable was recorded โ€” an empty trace, or one
+ * where every attempt was blocked (the classic case: agent-browser is not
+ * installed, so each action failed and was charged zero). Publishing that as a
+ * 0s cost would render a failed run as a free one; no measurement is the honest
+ * outcome.
+ */
+export const summarizeKlmTrace = (
+ events: KlmTraceEvent[],
+ { model = GOMS_KLM_MODEL, sourceTrace }: SummarizeOptions = {},
+): VerifyInteractionCost | null => {
+ const usable = events.filter(
+ (event) => event.schema === undefined || event.schema === GOMS_KLM_TRACE_SCHEMA,
+ );
+ if (usable.length === 0) return null;
+
+ const operators = emptyOperators();
+ const categoryCounts: Record<string, number> = {};
+ const mentalEstimates: Record<string, unknown>[] = [];
+ const phases = new Map<
+ string,
+ {
+ actionCount: number;
+ actualAgentMs: number;
+ checkItemId?: string;
+ id: string;
+ label?: string;
+ operators: Required<VerifyInteractionCostOperators>;
+ }
+ >();
+ let actualAgentMs = 0;
+
+ for (const event of usable) {
+ const eventOperators = event.klm?.operators ?? {};
+ addOperators(operators, eventOperators);
+
+ const category = event.klm?.category ?? 'unknown';
+ categoryCounts[category] = (categoryCounts[category] ?? 0) + 1;
+ actualAgentMs += num(event.durationMs);
+
+ if (event.type === 'mental_estimate' && event.mentalEstimate) {
+ mentalEstimates.push({ ...event.mentalEstimate, phaseId: event.phase?.id });
+ }
+
+ const key = event.phase?.id || event.phase?.checkItemId || UNSCOPED_PHASE;
+ const phase = phases.get(key) ?? {
+ actionCount: 0,
+ actualAgentMs: 0,
+ checkItemId: event.phase?.checkItemId,
+ id: key,
+ label: event.phase?.label || (key === UNSCOPED_PHASE ? undefined : key),
+ operators: emptyOperators(),
+ };
+
+ addOperators(phase.operators, eventOperators);
+ phase.actionCount += 1;
+ phase.actualAgentMs += num(event.durationMs);
+ phases.set(key, phase);
+ }
+
+ const phaseItems: VerifyInteractionCostPhase[] = [...phases.values()]
+ .map((phase) => ({
+ actionCount: phase.actionCount,
+ activeSeconds: activeSeconds(phase.operators),
+ actualAgentSeconds: round(phase.actualAgentMs / 1000),
+ checkItemId: phase.checkItemId,
+ id: phase.id,
+ label: phase.label,
+ operators: phase.operators,
+ seconds: totalSeconds(phase.operators),
+ waitSeconds: round(phase.operators.R_ms / 1000),
+ }))
+ .sort((a, b) => (b.seconds ?? 0) - (a.seconds ?? 0));
+
+ const total = totalSeconds(operators);
+ // Every action blocked (no driver installed, or the whole UI run died) sums to
+ // zero. That is an absence of measurement, not a measurement of zero.
+ if (total === 0) return null;
+
+ return {
+ actionCount: usable.length,
+ activeSeconds: activeSeconds(operators),
+ actualAgentSeconds: round(actualAgentMs / 1000),
+ categoryCounts,
+ generatedAt: new Date().toISOString(),
+ mentalEstimates,
+ model,
+ operators,
+ phases: phaseItems,
+ scope: 'user-equivalent',
+ sourceTrace,
+ timingSeconds: GOMS_KLM_TIMING_SECONDS,
+ totalSeconds: total,
+ waitSeconds: round(operators.R_ms / 1000),
+ };
+};
diff --git a/src/features/Acceptance/Report/InteractionCost.tsx b/src/features/Acceptance/Report/InteractionCost.tsx
new file mode 100644
index 00000000000..f1f70959612
--- /dev/null
+++ b/src/features/Acceptance/Report/InteractionCost.tsx
@@ -0,0 +1,368 @@
+'use client';
+
+import type { VerifyInteractionCost } from '@lobechat/types';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ formatSeconds,
+ OPERATOR_KEYS,
+ operatorValue,
+ phaseOperatorSegments,
+ phaseSeconds,
+} from './interactionCostModel';
+
+export { formatSeconds, readInteractionCost } from './interactionCostModel';
+
+/**
+ * The round's user-equivalent interaction cost, and the reader that lifts it off
+ * a run's metadata bag.
+ *
+ * Extracted from ReportViewer so the acceptance aggregate can render it too:
+ * the report only opens from owner-scoped round history, so a panel living
+ * solely there is invisible to exactly the audience the number is for โ€” the
+ * reviewer deciding whether a flow is worth accepting.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ interactionCost: css`
+ --klm-blue-1: color-mix(in srgb, ${cssVar.colorInfo} 70%, ${cssVar.colorBgContainer});
+ --klm-blue-2: ${cssVar.colorInfo};
+ --klm-blue-3: color-mix(in srgb, ${cssVar.colorInfo} 84%, ${cssVar.colorText});
+ --klm-blue-4: color-mix(in srgb, ${cssVar.colorInfo} 68%, ${cssVar.colorText});
+ --klm-blue-5: color-mix(in srgb, ${cssVar.colorInfo} 54%, ${cssVar.colorText});
+ --klm-blue-6: color-mix(in srgb, ${cssVar.colorInfo} 42%, ${cssVar.colorText});
+
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: 100%;
+ `,
+ interactionCostHeader: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ align-items: center;
+ justify-content: flex-end;
+ `,
+ interactionCostModel: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ interactionMetric: css`
+ min-width: 0;
+ padding-block: 9px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusSM};
+ `,
+ interactionMetricLabel: css`
+ display: block;
+ margin-block-end: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ interactionMetricValue: css`
+ font-size: 18px;
+ font-weight: 650;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.2;
+ color: ${cssVar.colorText};
+ `,
+ interactionMetrics: css`
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+
+ @media (width <= 520px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+ operatorChip: css`
+ --operator-color: ${cssVar.colorTextSecondary};
+
+ display: inline-flex;
+ gap: 5px;
+ align-items: baseline;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: color-mix(in srgb, var(--operator-color) 72%, ${cssVar.colorTextSecondary});
+
+ &::before {
+ content: '';
+
+ flex: 0 0 auto;
+
+ width: 6px;
+ height: 6px;
+ margin-block-start: 0.5em;
+ border-radius: 50%;
+
+ background: var(--operator-color);
+ }
+
+ b {
+ font-weight: 650;
+ color: var(--operator-color);
+ }
+
+ &[data-operator='K'] {
+ --operator-color: var(--klm-blue-1);
+ }
+
+ &[data-operator='P'] {
+ --operator-color: var(--klm-blue-2);
+ }
+
+ &[data-operator='M'] {
+ --operator-color: var(--klm-blue-3);
+ }
+
+ &[data-operator='H'] {
+ --operator-color: var(--klm-blue-4);
+ }
+
+ &[data-operator='T_chars'] {
+ --operator-color: var(--klm-blue-5);
+ }
+
+ &[data-operator='R_ms'] {
+ --operator-color: var(--klm-blue-6);
+ }
+ `,
+ operatorList: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 14px;
+ `,
+ /* Secondary to the phase name: it may be a long check title, so it is the part
+ that gives way and truncates rather than squeezing the name out of the row. */
+ phaseCheck: css`
+ overflow: hidden;
+ flex: 1 1 auto;
+
+ min-width: 0;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextQuaternary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ phaseList: css`
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ `,
+ phaseName: css`
+ overflow: hidden;
+ display: flex;
+ gap: 6px;
+ align-items: baseline;
+
+ min-width: 0;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+ `,
+ /* The phase is what tells two rows apart, so it never shrinks โ€” a long check
+ title must not collapse it to nothing and leave the rows looking identical. */
+ phaseSlug: css`
+ overflow: hidden;
+ flex: 0 0 auto;
+ max-width: 60%;
+ text-overflow: ellipsis;
+ `,
+ phaseRow: css`
+ display: grid;
+ grid-template-columns: minmax(120px, 1fr) minmax(140px, 1.6fr) auto;
+ gap: 10px;
+ align-items: center;
+
+ @media (width <= 640px) {
+ grid-template-columns: 1fr;
+ gap: 5px;
+ }
+ `,
+ phaseSegment: css`
+ --operator-color: ${cssVar.colorTextSecondary};
+
+ flex: 0 0 auto;
+ min-width: 2px;
+ height: 100%;
+ background: var(--operator-color);
+
+ &[data-operator='K'] {
+ --operator-color: var(--klm-blue-1);
+ }
+
+ &[data-operator='P'] {
+ --operator-color: var(--klm-blue-2);
+ }
+
+ &[data-operator='M'] {
+ --operator-color: var(--klm-blue-3);
+ }
+
+ &[data-operator='H'] {
+ --operator-color: var(--klm-blue-4);
+ }
+
+ &[data-operator='T_chars'] {
+ --operator-color: var(--klm-blue-5);
+ }
+
+ &[data-operator='R_ms'] {
+ --operator-color: var(--klm-blue-6);
+ }
+ `,
+ phaseTrack: css`
+ overflow: hidden;
+ display: flex;
+
+ height: 8px;
+ border-radius: 999px;
+
+ background: transparent;
+ box-shadow: inset 0 0 0 1px ${cssVar.colorBorderSecondary};
+ `,
+ phaseValue: css`
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+export interface InteractionCostPanelProps {
+ /**
+ * `checkItemId` โ†’ the check's display label. A phase the driver attributed to
+ * a check then names it, so a reviewer reads the cost against the thing being
+ * judged rather than against an internal phase slug.
+ */
+ checkLabels?: Record<string, string>;
+ cost: VerifyInteractionCost;
+ /** Which round this measurement came from, when the host shows several. */
+ roundLabel?: string;
+}
+
+const InteractionCostPanel = memo<InteractionCostPanelProps>(
+ ({ checkLabels, cost, roundLabel }) => {
+ const { t } = useTranslation('verify');
+ const phases = cost.phases ?? [];
+ const maxPhaseSeconds = Math.max(...phases.map(phaseSeconds), 0);
+ const metrics = [
+ {
+ label: t('report.interaction.total'),
+ value: formatSeconds(cost.totalSeconds),
+ },
+ {
+ label: t('report.interaction.active'),
+ value: formatSeconds(cost.activeSeconds),
+ },
+ {
+ label: t('report.interaction.wait'),
+ value: formatSeconds(cost.waitSeconds),
+ },
+ ];
+
+ return (
+ <section className={styles.interactionCost}>
+ <div className={styles.interactionCostHeader}>
+ {roundLabel && <span className={styles.interactionCostModel}>{roundLabel}</span>}
+ <span className={styles.interactionCostModel}>{cost.model}</span>
+ </div>
+
+ <div className={styles.interactionMetrics}>
+ {metrics.map((metric) => (
+ <div className={styles.interactionMetric} key={metric.label}>
+ <span className={styles.interactionMetricLabel}>{metric.label}</span>
+ <span className={styles.interactionMetricValue}>{metric.value}</span>
+ </div>
+ ))}
+ </div>
+
+ <div className={styles.operatorList}>
+ {OPERATOR_KEYS.map((key) => {
+ const value = cost.operators[key];
+ if (value === undefined) return null;
+
+ return (
+ <span className={styles.operatorChip} data-operator={key} key={key}>
+ <span>{t(`report.interaction.operator.${key}`)}</span>
+ <b>{operatorValue(key, value)}</b>
+ </span>
+ );
+ })}
+ </div>
+
+ {phases.length > 0 && (
+ <div className={styles.phaseList}>
+ {phases.map((phase) => {
+ const seconds = phaseSeconds(phase);
+ const activeSeconds = phase.activeSeconds ?? 0;
+ const waitSeconds = phase.waitSeconds ?? 0;
+ const activeWidth = maxPhaseSeconds > 0 ? (activeSeconds / maxPhaseSeconds) * 100 : 0;
+ const waitWidth = maxPhaseSeconds > 0 ? (waitSeconds / maxPhaseSeconds) * 100 : 0;
+ const segments = phaseOperatorSegments(phase, cost.timingSeconds);
+ const name = phase.label ?? phase.id;
+ const checkLabel = phase.checkItemId
+ ? (checkLabels?.[phase.checkItemId] ?? phase.checkItemId)
+ : undefined;
+
+ return (
+ <div className={styles.phaseRow} key={phase.id}>
+ <span
+ className={styles.phaseName}
+ title={checkLabel ? `${name} ยท ${checkLabel}` : name}
+ >
+ <span className={styles.phaseSlug}>{name}</span>
+ {checkLabel && <span className={styles.phaseCheck}>{checkLabel}</span>}
+ </span>
+ <span className={styles.phaseTrack}>
+ {segments.length > 0 ? (
+ segments.map((segment) => (
+ <span
+ className={styles.phaseSegment}
+ data-operator={segment.key}
+ key={segment.key}
+ style={{
+ width: `${
+ maxPhaseSeconds > 0 ? (segment.seconds / maxPhaseSeconds) * 100 : 0
+ }%`,
+ }}
+ title={`${t(`report.interaction.operator.${segment.key}`)} ${formatSeconds(
+ segment.seconds,
+ )}`}
+ />
+ ))
+ ) : (
+ <>
+ <span
+ className={styles.phaseSegment}
+ style={{ width: `${activeWidth}%` }}
+ />
+ <span
+ className={styles.phaseSegment}
+ data-operator={'R_ms'}
+ style={{ width: `${waitWidth}%` }}
+ />
+ </>
+ )}
+ </span>
+ <span className={styles.phaseValue}>{formatSeconds(seconds)}</span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ );
+ },
+);
+
+InteractionCostPanel.displayName = 'InteractionCostPanel';
+
+export default InteractionCostPanel;
diff --git a/src/features/Acceptance/Report/ReportViewer.tsx b/src/features/Acceptance/Report/ReportViewer.tsx
index a925d001e06..26766efdd75 100644
--- a/src/features/Acceptance/Report/ReportViewer.tsx
+++ b/src/features/Acceptance/Report/ReportViewer.tsx
@@ -5,14 +5,10 @@ import type {
VerifyCheckItem,
VerifyCodingScope,
VerifyEvidenceType,
- VerifyInteractionCost,
- VerifyInteractionCostOperators,
- VerifyInteractionCostPhase,
VerifyRunOrigin,
VerifySurface,
VerifyVerdict,
} from '@lobechat/types';
-import { toRecord } from '@lobechat/utils/object';
import { Block, Center, Empty, Flexbox, Icon, Image, Markdown } from '@lobehub/ui';
import { Button, Drawer, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
@@ -65,6 +61,7 @@ import {
meaningfulEvidenceCaption,
readEvidenceComparison,
} from './EvidenceComparisonCard';
+import InteractionCostPanel, { readInteractionCost } from './InteractionCost';
import {
CollapsibleMarkdownEvidence,
DocumentViewer,
@@ -156,189 +153,6 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorInfoBg};
`,
- interactionCost: css`
- --klm-blue-1: color-mix(in srgb, ${cssVar.colorInfo} 70%, ${cssVar.colorBgContainer});
- --klm-blue-2: ${cssVar.colorInfo};
- --klm-blue-3: color-mix(in srgb, ${cssVar.colorInfo} 84%, ${cssVar.colorText});
- --klm-blue-4: color-mix(in srgb, ${cssVar.colorInfo} 68%, ${cssVar.colorText});
- --klm-blue-5: color-mix(in srgb, ${cssVar.colorInfo} 54%, ${cssVar.colorText});
- --klm-blue-6: color-mix(in srgb, ${cssVar.colorInfo} 42%, ${cssVar.colorText});
-
- display: flex;
- flex-direction: column;
- gap: 12px;
- width: 100%;
- `,
- interactionCostHeader: css`
- display: flex;
- flex-wrap: wrap;
- gap: 8px 12px;
- align-items: center;
- justify-content: flex-end;
- `,
- interactionCostModel: css`
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- interactionMetrics: css`
- display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
- gap: 8px;
-
- @media (width <= 520px) {
- grid-template-columns: 1fr;
- }
- `,
- interactionMetric: css`
- min-width: 0;
- padding-block: 9px;
- padding-inline: 10px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusSM};
- `,
- interactionMetricLabel: css`
- display: block;
- margin-block-end: 4px;
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- interactionMetricValue: css`
- font-size: 18px;
- font-weight: 650;
- font-variant-numeric: tabular-nums;
- line-height: 1.2;
- color: ${cssVar.colorText};
- `,
- operatorList: css`
- display: flex;
- flex-wrap: wrap;
- gap: 8px 14px;
- `,
- operatorChip: css`
- --operator-color: ${cssVar.colorTextSecondary};
-
- display: inline-flex;
- gap: 5px;
- align-items: baseline;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: color-mix(in srgb, var(--operator-color) 72%, ${cssVar.colorTextSecondary});
-
- &::before {
- content: '';
-
- flex: 0 0 auto;
-
- width: 6px;
- height: 6px;
- margin-block-start: 0.5em;
- border-radius: 50%;
-
- background: var(--operator-color);
- }
-
- b {
- font-weight: 650;
- color: var(--operator-color);
- }
-
- &[data-operator='K'] {
- --operator-color: var(--klm-blue-1);
- }
-
- &[data-operator='P'] {
- --operator-color: var(--klm-blue-2);
- }
-
- &[data-operator='M'] {
- --operator-color: var(--klm-blue-3);
- }
-
- &[data-operator='H'] {
- --operator-color: var(--klm-blue-4);
- }
-
- &[data-operator='T_chars'] {
- --operator-color: var(--klm-blue-5);
- }
-
- &[data-operator='R_ms'] {
- --operator-color: var(--klm-blue-6);
- }
- `,
- phaseList: css`
- display: flex;
- flex-direction: column;
- gap: 8px;
- `,
- phaseRow: css`
- display: grid;
- grid-template-columns: minmax(120px, 1fr) minmax(140px, 1.6fr) auto;
- gap: 10px;
- align-items: center;
-
- @media (width <= 640px) {
- grid-template-columns: 1fr;
- gap: 5px;
- }
- `,
- phaseName: css`
- overflow: hidden;
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- phaseTrack: css`
- overflow: hidden;
- display: flex;
-
- height: 8px;
- border-radius: 999px;
-
- background: transparent;
- box-shadow: inset 0 0 0 1px ${cssVar.colorBorderSecondary};
- `,
- phaseSegment: css`
- --operator-color: ${cssVar.colorTextSecondary};
-
- flex: 0 0 auto;
- min-width: 2px;
- height: 100%;
- background: var(--operator-color);
-
- &[data-operator='K'] {
- --operator-color: var(--klm-blue-1);
- }
-
- &[data-operator='P'] {
- --operator-color: var(--klm-blue-2);
- }
-
- &[data-operator='M'] {
- --operator-color: var(--klm-blue-3);
- }
-
- &[data-operator='H'] {
- --operator-color: var(--klm-blue-4);
- }
-
- &[data-operator='T_chars'] {
- --operator-color: var(--klm-blue-5);
- }
-
- &[data-operator='R_ms'] {
- --operator-color: var(--klm-blue-6);
- }
- `,
- phaseValue: css`
- font-size: 12px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextTertiary};
- `,
/* Provenance: where the code came from. Reference material the reader scans,
so it stays visually subordinate to the verdict + summary above it. */
codingScope: css`
@@ -969,137 +783,6 @@ const liveStatusLabelKey = {
verifying: 'report.status.verifying',
} as const;
-const OPERATOR_KEYS = ['K', 'P', 'M', 'H', 'T_chars', 'R_ms'] as const;
-type OperatorKey = (typeof OPERATOR_KEYS)[number];
-
-const OPERATOR_DEFAULT_SECONDS: Record<OperatorKey, number> = {
- H: 0.4,
- K: 0.2,
- M: 1.35,
- P: 1.1,
- R_ms: 0.001,
- T_chars: 0.2,
-};
-
-const finiteNumber = (value: unknown): number | undefined =>
- typeof value === 'number' && Number.isFinite(value) ? value : undefined;
-
-const finiteString = (value: unknown): string | undefined =>
- typeof value === 'string' && value.length > 0 ? value : undefined;
-
-const readOperators = (value: unknown): VerifyInteractionCostOperators => {
- const record = toRecord(value);
- if (!record) return {};
-
- return {
- H: finiteNumber(record.H),
- K: finiteNumber(record.K),
- M: finiteNumber(record.M),
- P: finiteNumber(record.P),
- R_ms: finiteNumber(record.R_ms),
- T_chars: finiteNumber(record.T_chars),
- };
-};
-
-const readTimingSeconds = (value: unknown): Record<string, number> | undefined => {
- const record = toRecord(value);
- if (!record) return undefined;
-
- const entries = Object.entries(record).flatMap(([key, field]) => {
- const seconds = finiteNumber(field);
- return seconds === undefined ? [] : [[key, seconds] as const];
- });
-
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
-};
-
-const readPhase = (value: unknown, index: number): VerifyInteractionCostPhase | null => {
- const record = toRecord(value);
- if (!record) return null;
-
- const seconds = finiteNumber(record.seconds);
- const activeSeconds = finiteNumber(record.activeSeconds);
- const waitSeconds = finiteNumber(record.waitSeconds);
- const hasTiming =
- seconds !== undefined || activeSeconds !== undefined || waitSeconds !== undefined;
- if (!hasTiming) return null;
-
- return {
- actionCount: finiteNumber(record.actionCount),
- activeSeconds,
- checkItemId: finiteString(record.checkItemId),
- id: finiteString(record.id) ?? `phase-${index + 1}`,
- label: finiteString(record.label),
- operators: readOperators(record.operators),
- seconds,
- waitSeconds,
- };
-};
-
-const readInteractionCost = (metadata: unknown): VerifyInteractionCost | null => {
- const cost = toRecord(toRecord(metadata)?.interactionCost);
- if (!cost) return null;
-
- const totalSeconds = finiteNumber(cost.totalSeconds);
- if (totalSeconds === undefined) return null;
-
- return {
- actionCount: finiteNumber(cost.actionCount),
- activeSeconds: finiteNumber(cost.activeSeconds) ?? 0,
- model: finiteString(cost.model) ?? 'goms-klm',
- operators: readOperators(cost.operators),
- phases: Array.isArray(cost.phases)
- ? cost.phases
- .map((phase, index) => readPhase(phase, index))
- .filter((phase): phase is VerifyInteractionCostPhase => Boolean(phase))
- : [],
- scope: finiteString(cost.scope),
- sourceTrace: finiteString(cost.sourceTrace),
- timingSeconds: readTimingSeconds(cost.timingSeconds),
- totalSeconds,
- waitSeconds: finiteNumber(cost.waitSeconds) ?? 0,
- };
-};
-
-const formatSeconds = (seconds: number): string =>
- `${seconds >= 10 ? seconds.toFixed(1) : seconds.toFixed(2)}s`;
-
-const phaseSeconds = (phase: VerifyInteractionCostPhase): number =>
- phase.seconds ?? (phase.activeSeconds ?? 0) + (phase.waitSeconds ?? 0);
-
-const operatorSeconds = (
- key: OperatorKey,
- value: number,
- timingSeconds?: Record<string, number>,
-): number => {
- if (key === 'R_ms') return value / 1000;
- if (key === 'T_chars') {
- return (
- value * (timingSeconds?.T_chars ?? timingSeconds?.T_char ?? OPERATOR_DEFAULT_SECONDS[key])
- );
- }
-
- return value * (timingSeconds?.[key] ?? OPERATOR_DEFAULT_SECONDS[key]);
-};
-
-const operatorValue = (key: OperatorKey, value: number): string => {
- if (key === 'R_ms') return formatSeconds(value / 1000);
- if (key === 'T_chars') return `${Math.round(value)} chars`;
- return Number.isInteger(value) ? String(value) : value.toFixed(2);
-};
-
-const phaseOperatorSegments = (
- phase: VerifyInteractionCostPhase,
- timingSeconds?: Record<string, number>,
-): { key: OperatorKey; seconds: number; value: number }[] =>
- OPERATOR_KEYS.flatMap((key) => {
- const value = phase.operators?.[key];
- if (value === undefined || value <= 0) return [];
-
- const seconds = operatorSeconds(key, value, timingSeconds);
- return seconds > 0 ? [{ key, seconds, value }] : [];
- });
-
const evidenceDisplayName = (
evidence: VerifyEvidenceWithUrl,
t: TFunction<'verify'>,
@@ -1118,109 +801,6 @@ const evidenceComparison = (evidence: VerifyEvidenceWithUrl): EvidenceComparison
return readEvidenceComparison(evidence.metadata);
};
-const InteractionCostPanel = memo<{ cost: VerifyInteractionCost }>(({ cost }) => {
- const { t } = useTranslation('verify');
- const phases = cost.phases ?? [];
- const maxPhaseSeconds = Math.max(...phases.map(phaseSeconds), 0);
- const metrics = [
- {
- label: t('report.interaction.total'),
- value: formatSeconds(cost.totalSeconds),
- },
- {
- label: t('report.interaction.active'),
- value: formatSeconds(cost.activeSeconds),
- },
- {
- label: t('report.interaction.wait'),
- value: formatSeconds(cost.waitSeconds),
- },
- ];
-
- return (
- <section className={styles.interactionCost}>
- <div className={styles.interactionCostHeader}>
- <span className={styles.interactionCostModel}>{cost.model}</span>
- </div>
-
- <div className={styles.interactionMetrics}>
- {metrics.map((metric) => (
- <div className={styles.interactionMetric} key={metric.label}>
- <span className={styles.interactionMetricLabel}>{metric.label}</span>
- <span className={styles.interactionMetricValue}>{metric.value}</span>
- </div>
- ))}
- </div>
-
- <div className={styles.operatorList}>
- {OPERATOR_KEYS.map((key) => {
- const value = cost.operators[key];
- if (value === undefined) return null;
-
- return (
- <span className={styles.operatorChip} data-operator={key} key={key}>
- <span>{t(`report.interaction.operator.${key}`)}</span>
- <b>{operatorValue(key, value)}</b>
- </span>
- );
- })}
- </div>
-
- {phases.length > 0 && (
- <div className={styles.phaseList}>
- {phases.map((phase) => {
- const seconds = phaseSeconds(phase);
- const activeSeconds = phase.activeSeconds ?? 0;
- const waitSeconds = phase.waitSeconds ?? 0;
- const activeWidth = maxPhaseSeconds > 0 ? (activeSeconds / maxPhaseSeconds) * 100 : 0;
- const waitWidth = maxPhaseSeconds > 0 ? (waitSeconds / maxPhaseSeconds) * 100 : 0;
- const segments = phaseOperatorSegments(phase, cost.timingSeconds);
-
- return (
- <div className={styles.phaseRow} key={phase.id}>
- <span className={styles.phaseName} title={phase.label ?? phase.id}>
- {phase.label ?? phase.id}
- </span>
- <span className={styles.phaseTrack}>
- {segments.length > 0 ? (
- segments.map((segment) => (
- <span
- className={styles.phaseSegment}
- data-operator={segment.key}
- key={segment.key}
- style={{
- width: `${
- maxPhaseSeconds > 0 ? (segment.seconds / maxPhaseSeconds) * 100 : 0
- }%`,
- }}
- title={`${t(`report.interaction.operator.${segment.key}`)} ${formatSeconds(
- segment.seconds,
- )}`}
- />
- ))
- ) : (
- <>
- <span className={styles.phaseSegment} style={{ width: `${activeWidth}%` }} />
- <span
- className={styles.phaseSegment}
- data-operator={'R_ms'}
- style={{ width: `${waitWidth}%` }}
- />
- </>
- )}
- </span>
- <span className={styles.phaseValue}>{formatSeconds(seconds)}</span>
- </div>
- );
- })}
- </div>
- )}
- </section>
- );
-});
-
-InteractionCostPanel.displayName = 'InteractionCostPanel';
-
/** One evidence artifact rendered by its type: zoomable image/gif, video, doc, text. */
const EvidenceItem = memo<{
evidence: VerifyEvidenceWithUrl;
diff --git a/src/features/Acceptance/Report/interactionCostModel.ts b/src/features/Acceptance/Report/interactionCostModel.ts
new file mode 100644
index 00000000000..af49f61f25d
--- /dev/null
+++ b/src/features/Acceptance/Report/interactionCostModel.ts
@@ -0,0 +1,147 @@
+import type {
+ VerifyInteractionCost,
+ VerifyInteractionCostOperators,
+ VerifyInteractionCostPhase,
+} from '@lobechat/types';
+import { toRecord } from '@lobechat/utils/object';
+
+/**
+ * Reading and pricing helpers for a round's user-equivalent interaction cost.
+ *
+ * Split from the panel so the values can be unit-tested and reused without
+ * mounting React โ€” the acceptance page selects which round to show from these,
+ * and the panel is left as presentation.
+ */
+
+export const OPERATOR_KEYS = ['K', 'P', 'M', 'H', 'T_chars', 'R_ms'] as const;
+export type OperatorKey = (typeof OPERATOR_KEYS)[number];
+
+/** Fallback pricing for a cost recorded before `timingSeconds` travelled with it. */
+const OPERATOR_DEFAULT_SECONDS: Record<OperatorKey, number> = {
+ H: 0.4,
+ K: 0.2,
+ M: 1.35,
+ P: 1.1,
+ R_ms: 0.001,
+ T_chars: 0.2,
+};
+
+const finiteNumber = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+const finiteString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+const readOperators = (value: unknown): VerifyInteractionCostOperators => {
+ const record = toRecord(value);
+ if (!record) return {};
+
+ return {
+ H: finiteNumber(record.H),
+ K: finiteNumber(record.K),
+ M: finiteNumber(record.M),
+ P: finiteNumber(record.P),
+ R_ms: finiteNumber(record.R_ms),
+ T_chars: finiteNumber(record.T_chars),
+ };
+};
+
+const readTimingSeconds = (value: unknown): Record<string, number> | undefined => {
+ const record = toRecord(value);
+ if (!record) return undefined;
+
+ const entries = Object.entries(record).flatMap(([key, field]) => {
+ const seconds = finiteNumber(field);
+ return seconds === undefined ? [] : [[key, seconds] as const];
+ });
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+};
+
+const readPhase = (value: unknown, index: number): VerifyInteractionCostPhase | null => {
+ const record = toRecord(value);
+ if (!record) return null;
+
+ const seconds = finiteNumber(record.seconds);
+ const activeSeconds = finiteNumber(record.activeSeconds);
+ const waitSeconds = finiteNumber(record.waitSeconds);
+ const hasTiming =
+ seconds !== undefined || activeSeconds !== undefined || waitSeconds !== undefined;
+ if (!hasTiming) return null;
+
+ return {
+ actionCount: finiteNumber(record.actionCount),
+ activeSeconds,
+ checkItemId: finiteString(record.checkItemId),
+ id: finiteString(record.id) ?? `phase-${index + 1}`,
+ label: finiteString(record.label),
+ operators: readOperators(record.operators),
+ seconds,
+ waitSeconds,
+ };
+};
+
+/** Lift the interaction cost off a run's metadata bag; `null` when unpriced. */
+export const readInteractionCost = (metadata: unknown): VerifyInteractionCost | null => {
+ const cost = toRecord(toRecord(metadata)?.interactionCost);
+ if (!cost) return null;
+
+ const totalSeconds = finiteNumber(cost.totalSeconds);
+ if (totalSeconds === undefined) return null;
+
+ return {
+ actionCount: finiteNumber(cost.actionCount),
+ activeSeconds: finiteNumber(cost.activeSeconds) ?? 0,
+ model: finiteString(cost.model) ?? 'goms-klm',
+ operators: readOperators(cost.operators),
+ phases: Array.isArray(cost.phases)
+ ? cost.phases
+ .map((phase, index) => readPhase(phase, index))
+ .filter((phase): phase is VerifyInteractionCostPhase => Boolean(phase))
+ : [],
+ scope: finiteString(cost.scope),
+ sourceTrace: finiteString(cost.sourceTrace),
+ timingSeconds: readTimingSeconds(cost.timingSeconds),
+ totalSeconds,
+ waitSeconds: finiteNumber(cost.waitSeconds) ?? 0,
+ };
+};
+
+export const formatSeconds = (seconds: number): string =>
+ `${seconds >= 10 ? seconds.toFixed(1) : seconds.toFixed(2)}s`;
+
+export const phaseSeconds = (phase: VerifyInteractionCostPhase): number =>
+ phase.seconds ?? (phase.activeSeconds ?? 0) + (phase.waitSeconds ?? 0);
+
+const operatorSeconds = (
+ key: OperatorKey,
+ value: number,
+ timingSeconds?: Record<string, number>,
+): number => {
+ if (key === 'R_ms') return value / 1000;
+ if (key === 'T_chars') {
+ return (
+ value * (timingSeconds?.T_chars ?? timingSeconds?.T_char ?? OPERATOR_DEFAULT_SECONDS[key])
+ );
+ }
+
+ return value * (timingSeconds?.[key] ?? OPERATOR_DEFAULT_SECONDS[key]);
+};
+
+export const operatorValue = (key: OperatorKey, value: number): string => {
+ if (key === 'R_ms') return formatSeconds(value / 1000);
+ if (key === 'T_chars') return `${Math.round(value)} chars`;
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
+};
+
+export const phaseOperatorSegments = (
+ phase: VerifyInteractionCostPhase,
+ timingSeconds?: Record<string, number>,
+): { key: OperatorKey; seconds: number; value: number }[] =>
+ OPERATOR_KEYS.flatMap((key) => {
+ const value = phase.operators?.[key];
+ if (value === undefined || value <= 0) return [];
+
+ const seconds = operatorSeconds(key, value, timingSeconds);
+ return seconds > 0 ? [{ key, seconds, value }] : [];
+ });
diff --git a/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx b/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
index 2695dedd680..86510943dbb 100644
--- a/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceCheckInventory.tsx
@@ -14,6 +14,7 @@ import { mutate as globalMutate } from '@/libs/swr';
import { isAcceptanceListKey } from '@/libs/swr/keys';
import { verifyService } from '@/services/verify';
+import AcceptanceInteractionCost from './AcceptanceInteractionCost';
import { useAcceptanceScope } from './AcceptanceScope';
import CheckList, {
type CheckFilter,
@@ -302,6 +303,9 @@ const AcceptanceCheckInventory = ({
})
}
/>
+ {/* After the list, never inside it: the checks are the decision surface,
+ and a row sitting among them reads as one more thing to review. */}
+ <AcceptanceInteractionCost data={data} />
</>
);
};
diff --git a/src/features/Acceptance/Viewer/AcceptanceInteractionCost.tsx b/src/features/Acceptance/Viewer/AcceptanceInteractionCost.tsx
new file mode 100644
index 00000000000..1a227d3ae83
--- /dev/null
+++ b/src/features/Acceptance/Viewer/AcceptanceInteractionCost.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { Icon } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronRight } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+import InteractionCostPanel from '../Report/InteractionCost';
+import { formatSeconds } from '../Report/interactionCostModel';
+import { buildCheckLabels, selectPricedRound } from './interactionCost';
+
+/**
+ * The latest priced round's interaction cost, on the acceptance page itself.
+ *
+ * The panel used to live only in the round report, which opens from owner-scoped
+ * round history โ€” so the one audience the number exists for, a reviewer weighing
+ * whether a flow is worth accepting, could never see it. The cost already ships
+ * in the shared bundle (only `origin` is stripped for visitors), so surfacing it
+ * here needs no extra read and no extra permission.
+ *
+ * Deliberately a plain disclosure, not a card: the checks are what a reviewer
+ * acts on, and a bordered block here would compete with them for the same
+ * attention. Collapsed it is one muted line carrying the only number worth
+ * seeing at a glance; the breakdown is one click away.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ padding-block-end: 4px;
+ padding-inline-start: 24px;
+ `,
+ chevron: css`
+ transition: transform 0.15s ease;
+
+ &[data-open='true'] {
+ transform: rotate(90deg);
+ }
+ `,
+ total: css`
+ margin-inline-start: 6px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface AcceptanceInteractionCostProps {
+ data: AcceptanceBundle;
+}
+
+const AcceptanceInteractionCost = memo<AcceptanceInteractionCostProps>(({ data }) => {
+ const { t } = useTranslation('verify');
+ const [open, setOpen] = useState(false);
+
+ const priced = useMemo(() => selectPricedRound(data.rounds), [data.rounds]);
+ const checkLabels = useMemo(() => buildCheckLabels(data.checks), [data.checks]);
+
+ if (!priced) return null;
+
+ return (
+ <>
+ <Button
+ icon={<Icon className={styles.chevron} data-open={open} icon={ChevronRight} />}
+ size={'small'}
+ style={{ alignSelf: 'flex-start' }}
+ type={'text'}
+ onClick={() => setOpen((prev) => !prev)}
+ >
+ {t('report.interaction.title')}
+ <span className={styles.total}>{formatSeconds(priced.cost.totalSeconds)}</span>
+ </Button>
+ {open && (
+ <div className={styles.body}>
+ <InteractionCostPanel
+ checkLabels={checkLabels}
+ cost={priced.cost}
+ roundLabel={t('acceptance.round', { round: priced.roundIndex })}
+ />
+ </div>
+ )}
+ </>
+ );
+});
+
+AcceptanceInteractionCost.displayName = 'AcceptanceInteractionCost';
+
+export default AcceptanceInteractionCost;
diff --git a/src/features/Acceptance/Viewer/interactionCost.test.ts b/src/features/Acceptance/Viewer/interactionCost.test.ts
new file mode 100644
index 00000000000..0e69d7833cc
--- /dev/null
+++ b/src/features/Acceptance/Viewer/interactionCost.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCheckLabels, selectPricedRound } from './interactionCost';
+
+const cost = {
+ activeSeconds: 4,
+ model: 'goms-klm@lobe-v1',
+ operators: { K: 1, M: 2, P: 1, R_ms: 7894 },
+ phases: [
+ {
+ activeSeconds: 2.7,
+ checkItemId: 'cost-priced',
+ id: 'open-acceptance',
+ seconds: 10.59,
+ waitSeconds: 7.89,
+ },
+ ],
+ totalSeconds: 11.89,
+ waitSeconds: 7.89,
+};
+
+const round = (roundIndex: number, metadata: unknown) => ({ run: { metadata, roundIndex } });
+
+describe('selectPricedRound', () => {
+ it('reads the cost a round recorded', () => {
+ const priced = selectPricedRound([round(1, { interactionCost: cost })]);
+
+ expect(priced?.roundIndex).toBe(1);
+ expect(priced?.cost.totalSeconds).toBe(11.89);
+ expect(priced?.cost.phases?.[0].checkItemId).toBe('cost-priced');
+ });
+
+ it('keeps the last priced round when a later round has no trace', () => {
+ // A follow-up CLI round measures nothing. Falling through to it would read
+ // as "the flow became free" instead of "this round measured nothing".
+ const priced = selectPricedRound([
+ round(1, { interactionCost: cost }),
+ round(2, { origin: { topicId: 't' } }),
+ ]);
+
+ expect(priced?.roundIndex).toBe(1);
+ });
+
+ it('prefers the newest measurement when several rounds are priced', () => {
+ const priced = selectPricedRound([
+ round(1, { interactionCost: cost }),
+ round(2, { interactionCost: { ...cost, totalSeconds: 3.5 } }),
+ ]);
+
+ expect(priced).toMatchObject({ roundIndex: 2 });
+ expect(priced?.cost.totalSeconds).toBe(3.5);
+ });
+
+ it('returns null when no round was priced', () => {
+ // A CLI-only acceptance must render no measurement block at all.
+ expect(selectPricedRound([round(1, { origin: {} })])).toBeNull();
+ expect(selectPricedRound([])).toBeNull();
+ });
+
+ it('ignores a metadata bag whose cost has no total', () => {
+ expect(selectPricedRound([round(1, { interactionCost: { model: 'x' } })])).toBeNull();
+ });
+});
+
+describe('buildCheckLabels', () => {
+ it('maps a check id onto the title a reviewer reads', () => {
+ expect(buildCheckLabels([{ id: 'cost-priced', title: 'ๅนณๅฐไปŽ trace ่ฎก็ฎ—ไบคไบ’ๆˆๆœฌ' }])).toEqual({
+ 'cost-priced': 'ๅนณๅฐไปŽ trace ่ฎก็ฎ—ไบคไบ’ๆˆๆœฌ',
+ });
+ });
+});
diff --git a/src/features/Acceptance/Viewer/interactionCost.ts b/src/features/Acceptance/Viewer/interactionCost.ts
new file mode 100644
index 00000000000..7a1cbf50c5b
--- /dev/null
+++ b/src/features/Acceptance/Viewer/interactionCost.ts
@@ -0,0 +1,42 @@
+import type { VerifyInteractionCost } from '@lobechat/types';
+
+import { readInteractionCost } from '../Report/interactionCostModel';
+
+/** A round's cost plus the round it was measured in. */
+export interface PricedRound {
+ cost: VerifyInteractionCost;
+ roundIndex: number;
+}
+
+interface RoundLike {
+ run: { metadata?: unknown; roundIndex?: number | null };
+}
+
+interface CheckLike {
+ id: string;
+ title: string;
+}
+
+/**
+ * The newest round that actually recorded an interaction cost.
+ *
+ * Not simply the last round: a follow-up CLI round carries no trace, and
+ * blanking the measurement a UI round already made would read as "this flow
+ * became free" rather than "this round measured nothing".
+ */
+export const selectPricedRound = (rounds: readonly RoundLike[]): PricedRound | null => {
+ for (let index = rounds.length - 1; index >= 0; index -= 1) {
+ const round = rounds[index];
+ const cost = readInteractionCost(round.run.metadata);
+ if (cost) return { cost, roundIndex: round.run.roundIndex ?? 0 };
+ }
+
+ return null;
+};
+
+/**
+ * `checkItemId` โ†’ check title, so a phase the driver attributed to a check reads
+ * as the thing being judged instead of an internal slug.
+ */
+export const buildCheckLabels = (checks: readonly CheckLike[]): Record<string, string> =>
+ Object.fromEntries(checks.map((check) => [check.id, check.title]));