🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(acceptance): publish Task acceptance through the acceptance skill, chapters included (#20866)
Arvin Xu818721186e2c
diff --git a/.agents/skills/acceptance/SKILL.md b/.agents/skills/acceptance/SKILL.mdindex 5f25f6be24b..cc7703b41a0 100644--- a/.agents/skills/acceptance/SKILL.md+++ b/.agents/skills/acceptance/SKILL.md@@ -2,7 +2,7 @@name: acceptancelicense: Apache-2.0metadata:- version: "0.7.5"+ version: "0.8.1"description: >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@@ -132,10 +132,15 @@ have an operation id only when the invocation names one. Never hunt theenvironment for one, and never report this skill inapplicable — a round withoutan operation is simply recorded as `standalone`.-| You have | Path |-| ------------------------------- | -------------------------------------------------------------------------------------------------------------------- |-| No plan — you author the checks | Write `result.json` + `assets/`, publish with `lh acceptance run ingest` — [report.md](references/report.md) |-| An operation id you were given | `lh verify plan state`, then `result submit --operation` per criterion — [plan-format.md](references/plan-format.md) |+| You have | Path |+| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |+| No plan — you author the checks | Write `result.json` + `assets/`, publish with `lh acceptance run ingest` — [report.md](references/report.md) |+| An operation id you were given | Read the frozen plan, write the same round directory keyed by its check item ids, publish with `ingest --operation` — [plan-format.md](references/plan-format.md) |++The paths differ only in where the checks come from and which round the ingest+lands in. Capture is identical: the surface guides, recordings with+[chapters](references/video-chapters.md), before/after pairs, screenshots you+looked at, `proposal.md`. A handed-down plan never licenses a lighter capture.Pass `--subject` (`task:<id>` / `topic:<id>` / `document:<id>`) only when thecaller named one; otherwise ingest attaches the round itself when it can and@@ -143,10 +148,18 @@ creates a standalone acceptance when it cannot. On the first ingest, always supp`--requirement "<one-sentence business goal>"` — the durable goal of the wholeacceptance, not this round's scope; it is immutable once recorded.-Prerequisites: `lh` is authed (`lh acceptance run list --json` returns `[]` or-data; an auth error means stop and surface it), and only the UI driver the-selected surface needs is installed — probe before adding dependencies, and never-substitute a private agent plugin.+Prerequisites: run `lh acceptance preflight --json` before writing any plan or+report text — an auth error means stop and surface it — and install only the UI+driver the selected surface needs; probe before adding dependencies, and never+substitute a private agent plugin. Its `language.locale` is the **report+language**: write every human-readable field (title, plan, case names,+observations, evidence descriptions, conclusion, `report.md`, `proposal.md`) in+it, even when the prompt that invoked you is in another language — a delegating+agent's prompt does not show which language the user reads. The publish commands+reject text in the wrong script, so run `lh acceptance run ingest <dir> --dry-run`+as soon as the plan is in `result.json`, before executing it. When+`language.status` is `unset`, use the language the user converses in. On a CLI+without `preflight`, check auth with `lh acceptance run list --json`.## Optional user-journey flows@@ -361,7 +374,7 @@ safety — are in [evidence.md](references/evidence.md).## Keep checklist explanations brief-Write each check's `observation` and inline explanation in the user's language,+Write each check's `observation` and inline explanation in the report language,usually 1–3 short sentences: what was done, what happened, and any limitationneeded to judge that outcome. Do not paste the execution report into the check.Omit repeated titles, verdict labels, SHA/port/ID headers, environment boilerplate,@@ -458,12 +471,12 @@ claim. Obtain the links from the path you actually executed:- **Authored round:** copy `acceptanceUrl` returned by`lh acceptance run ingest --json` verbatim.-- **Operation-plan round:** follow the read-only- [plan handoff lookup](references/plan-format.md#resolve-the-plan-rounds-handoff-links).- It resolves the supplied operation ID to its existing run, acceptance, and- round using the CLI's actual server configuration. Copy its- `acceptanceUrl` output. Do not run authored ingest, create another- acceptance, or resubmit evidence merely to obtain a link.+- **Operation-plan round:** copy `acceptanceUrl` returned by+ `lh acceptance run ingest --operation <id> --json`. When the plan needed no+ ingest, or the CLI predates plan-round ingest, follow the read-only+ [plan handoff lookup](references/plan-format.md#resolve-the-plan-rounds-handoff-links)+ instead. Do not ingest without `--operation`, create another acceptance, or+ resubmit evidence merely to obtain a link.Never guess a host, acceptance ID, or round index. The documented plan lookup isthe only reconstruction needed for CLIs whose submission output contains only an@@ -489,8 +502,9 @@ Coverage: 2/2 criteria, all required evidence uploadedsimctl io` over host-window capture. Rounds land under `.acceptances/`;allocate them with `new_round` ([report.md](references/report.md#no-operation-id-needed)),which seeds the `.acceptances/.gitignore` that keeps them out of git.-- **Upload as you go.** Evidence keyed to its check mid-run survives a crash near- the end.+- **Save as you go.** Write each artifact into the round's `assets/` and its case+ into `result.json` the moment it is captured, so a crash near the end loses+ nothing; then publish the round once.- **Don't invent evidence.** Capture only the types a check declares.- **Chapter every recording.** Log a mark for each step and each claim youverify on a frame, and disclose every anomaly you noticed as a `flag`; the@@ -509,7 +523,7 @@ For both acceptance-checker handoffs and review output, read| Mistakes checklist (read every round) | [common-mistakes.md](references/common-mistakes.md) || Forcing state, error injection, runtime probes | [probe-mock-patterns.md](references/probe-mock-patterns.md) || Authored rounds, `result.json`, ingest | [report.md](references/report.md) |-| Plan-driven rounds: schema, submit, coverage | [plan-format.md](references/plan-format.md) |+| Plan-driven rounds: plan, ingest, coverage | [plan-format.md](references/plan-format.md) || Evidence media, provenance, submission, safety | [evidence.md](references/evidence.md) || Interaction cost overlay | [interaction-cost.md](references/interaction-cost.md) || Web/Electron Chromium CLI commands | [agent-browser.md](references/agent-browser.md) |diff --git a/.agents/skills/acceptance/references/evidence.md b/.agents/skills/acceptance/references/evidence.mdindex 56f889dc04f..db64e068e93 100644--- a/.agents/skills/acceptance/references/evidence.md+++ b/.agents/skills/acceptance/references/evidence.md@@ -31,11 +31,17 @@ a file exists. Upload the clip itself with `--type audio` and the acceptancepage gives the reviewer a player.```bash-# The generated file is the evidence — attach the artifact the feature produced,+# The generated file is the evidence — keep the artifact the feature produced,# not a re-encode and not a screenshot of the player.-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"+cp ./out/tts-zh-female.mp3 "$REPORT_DIR/assets/"+```++```jsonc+// its case in result.json+"evidence": [+ { "path": "assets/tts-zh-female.mp3",+ "description": "TTS output for 「今天天气不错」, zh-CN female voice, 2.4s" }+]```- `mp3` / `wav` / `m4a` / `aac` / `flac` / `ogg` / `opus` are recognized by@@ -65,12 +71,14 @@ join an explanation from an older round with fresh execution output.## File versus inline content-- Use `--file` for binary artifacts and larger text/DOM/transcript files.-- Use `--content` for short text assertions. Pass exactly one of `--file` and- `--content`.-- **Description is mandatory for every file artifact.** Always supply a non-empty- `--desc` when using `--file`, and a `description` when attaching a `fileId` or- adding a file to an ingest manifest. Small text files converted to inline+- Save binary artifacts and larger text/DOM/transcript files into the round's+ `assets/` and list them in the case's `evidence`; ingest inlines small text+ files itself.+- When supplementing a single artifact with `result submit`, use `--file` for a+ file and `--content` for a short text assertion — exactly one of them.+- **Description is mandatory for every file artifact.** Always supply a+ `description` on each `evidence` entry in `result.json`, and a non-empty+ `--desc` when supplementing with `--file` or attaching a `fileId`. Small text files converted to inlinecontent still require it; do not rely on the filename fallback.- Write a concise, factual sentence identifying the file's contents and theirrelevance to the criterion, including the action, observed state, or target@@ -83,15 +91,11 @@ join an explanation from an older round with fresh execution output.separately instead of repeating the criterion title for every file.```bash-# File artifact captured by the selected surface.+# Supplementing one artifact after the round was published.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 "$OPERATION_ID" --item "$CHECK_ITEM_ID" \- --type text --content "$ASSERTION_OUTPUT" --by cli \- --desc "Machine-readable assertion output"+# A video carries its chapters: add --chapters "$CHAPTERS_JSON".```## Provenance (`--by`)diff --git a/.agents/skills/acceptance/references/plan-format.md b/.agents/skills/acceptance/references/plan-format.mdindex 23dc058d158..4efc028843e 100644--- a/.agents/skills/acceptance/references/plan-format.md+++ b/.agents/skills/acceptance/references/plan-format.md@@ -1,14 +1,14 @@-# Plan-driven rounds — discover, submit, self-check+# Plan-driven rounds — read the plan, capture, ingest into its roundUse this path only when the invocation handed you an operation id: a verify plan-already exists and you satisfy it criterion by criterion. Authoring your own-checks (the default) is [report.md](./report.md). Never mix both for one round.+already exists and its round is waiting. Everything except where the checks come+from and where the round lands is the authored path in [report.md](./report.md):+the same `new_round` directory, `result.json`, `proposal.md`, assets, and capture+discipline — surface guides, recordings with [chapters](./video-chapters.md),+before/after pairs, screenshots you looked at. Never mix this path with an+authored ingest for one round.-`--operation` and `--run` are interchangeable on `result submit` and-`result list`; `evidence list` keys off a positional `<checkResultId>` from-`result list`.--## (a) `lh verify plan state $OPERATION_ID --json`+## Read the frozen plan — `lh verify plan state $OPERATION_ID --json`Returns the run's verify state plus the **frozen plan** (immutable onceconfirmed):@@ -43,6 +43,28 @@ confirmed):- `hint` is guidance for what the artifact should show — it is not validated, butfollow it so the reviewer can recognize the proof.+## Write the round against the frozen plan++Allocate the round under the subject the invocation named (`task-T-12`, or the+operation when there is none) and copy each frozen item into `plan[]` unchanged,+so the local report reads the same as the page:++```bash+REPORT_DIR=$(new_round "task-$TASK_IDENTIFIER" plan-round)+```++| Field in `result.json` | From the frozen plan |+| ---------------------- | ----------------------------------------------------------------------------- |+| `plan[].id` | `verifyPlan[].id` — verbatim |+| `plan[].title` | `verifyPlan[].title` |+| `requiredEvidence` | `verifyPlan[].verifierConfig.requiredEvidence[].type` |+| `cases[].id` | the `verifyPlan[].id` the case proves — ingest rejects any id outside the plan |++Then pick the surface for each item and capture into `$REPORT_DIR/assets/`+exactly as an authored round does. Every recording gets its chapters while you+drive it; each case's `observation` says what you saw. Leave `status` honest —+it is your record, not the verdict.+Only items with a non-empty `requiredEvidence` need an artifact; the rest arejudged on the deliverable text — don't fabricate evidence for them. The `hint`usually implies the surface (SKILL.md, Pick the surface).@@ -51,59 +73,76 @@ Apply [acceptance-checker.md](acceptance-checker.md) before execution and at finof the first round; follow-up rounds have no acceptance-checker. Preserve frozen check IDs;report coverage gaps instead of silently changing the supplied plan. Theacceptance-checker's review does not replace the configured verifier or authorize-overriding its verdict. Keep existing submission and round semantics.+overriding its verdict.++## Publish into the operation's round++```bash+lh acceptance run ingest "$REPORT_DIR" --operation "$OPERATION_ID" --json+```++With `--operation`, ingest finds the round the operation already owns and writes+into it — it never creates another round or acceptance. It attaches every case's+evidence (chapters, comparisons and captions included) to that round's rows and+posts `proposal.md`. It publishes no verdicts and no `report.md`: the round's+verifier judges every item and writes the report when it settles, so put your+narrative in the final response.++Read the JSON: `mode` is `plan-round`; `missingEvidence`, `failedEvidence` and+`unexecuted` must be empty. A case id outside the plan fails before anything is+written and lists the valid ids.-## Your worklist → submit by checkItemId+An older CLI without plan-round ingest fails on `--operation` with a duplicate+run error — check first: `lh acceptance run ingest --help` describes+`--operation` as publishing into the run's existing round. Without it, submit+each artifact with `result submit` (below), chapters included.-For each `verifyPlan[]` item with non-empty `requiredEvidence`, capture each-`type` with the selected surface guide and submit **one artifact per call** by-`checkItemId` (the same `--item` reuses the row):+## Supplement one artifact-| checkItemId | title | requiredEvidence |-| ------------ | -------------------------------- | ---------------- |-| `vci_a1b2c3` | Login flow reaches the workspace | `screenshot` |+A single missing or failed artifact — a retry, or a verifier asking for one more+capture — goes in with `result submit`, not a second ingest (re-ingesting+duplicates every artifact):```bash-OP="$OPERATION_ID"-lh acceptance run result submit --operation "$OP" --item vci_a1b2c3 --type screenshot \- --file ./proof/home.png --by agent-browser --desc "…"+lh acceptance run result submit --operation "$OPERATION_ID" --item vci_a1b2c3 --type video \+ --file "$REPORT_DIR/assets/reload.mp4" --chapters "$REPORT_DIR/assets/reload.chapters.json" \+ --by cdp --desc "…"```-`lh acceptance run result submit` resolves the session from the operation id and **creates the-check-result row for you** (idempotent on `checkItemId`), then attaches the-evidence — there is no `checkResultId` to look up first. `--by` records-provenance (`agent-browser` | `cdp` | `cli` | `program`); `--file` for binaries,-`--content` for text, exactly one. Leave the verdict to the review step — add-`--verdict` only when the task explicitly asks you to self-assert. Keep the-printed run URL internal.+It resolves the round from the operation id, creates the check-result row on+first use (idempotent on `checkItemId`), and rejects a malformed chapter or+chapters on a non-video before uploading. Add the artifact to the case's+`evidence` in `result.json` too, so the local round stays the full record.+Leave `--verdict` off unless the task explicitly asks you to self-assert.## Self-check coverage (do not skip)-Once you've submitted, the result rows exist. Map each `checkItemId` to its-`checkResultId` and list that row's evidence:+Ingest's `missingEvidence` is the first check. To read the round back, map each+`checkItemId` to its `checkResultId` and list that row's evidence:```jsonc// lh acceptance run result list --operation "$OP" --json[{- "id": "vcr_x9y8z7", // checkResultId (created by submit)+ "id": "vcr_x9y8z7", // checkResultId"checkItemId": "vci_a1b2c3", // joins back to verifyPlan[].id- "status": "running",+ "status": "pending",},]``````bash-lh acceptance run evidence list "$CHECK_RESULT_ID" --json # confirm each required type is present+lh acceptance run evidence list "$CHECK_RESULT_ID" --json # each required type present; videos carry metadata.chapters```Coverage rule: for each required criterion, **every** `requiredEvidence[].type`-appears at least once in its evidence list. A missing type → capture and submit-again; then hand off per SKILL.md (acceptance URL + `coverage: n/n`).+appears at least once in its evidence list, and every video has chapters. A gap →+capture and supplement it; then hand off per SKILL.md (acceptance URL ++`coverage: n/n`).## Resolve the plan round's handoff links-`result submit --json` returns an internal `url`, not `acceptanceUrl`. Some plans need no evidence submissions at all. In both cases, resolve+`ingest --operation --json` returns `acceptanceUrl`; copy it. Some plans need no evidence at all, and an older CLI's `result submit --json` returns only an internal `url`. In those cases, resolvethe supplied operation ID with `lh verify plan state <operationId> --json`, thenread its `verifyRunId` using `lh acceptance run get <runId> --json`. The run's`acceptanceId` and `roundIndex` identify the existing handoff; do not substitute adiff --git a/.agents/skills/acceptance/references/report.md b/.agents/skills/acceptance/references/report.mdindex 2099e0e8e06..6558f71142f 100644--- a/.agents/skills/acceptance/references/report.md+++ b/.agents/skills/acceptance/references/report.md@@ -1,10 +1,10 @@# 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, 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+Every round is a **structured report round**: a self-contained directory that+`lh acceptance run ingest` uploads as one immutable verification round. You+author the checks here, which is the usual case; when a verify plan was handed to+you, the same directory is keyed by its check item ids and ingested into the+plan's round ([plan-format.md](./plan-format.md)). Theacceptance page renders itself from `result.json`: provenance, the overallconclusion, and the check list from `plan[]` paired with `cases[]`, each withits evidence inline — **images render as figures, before/after pairs render@@ -19,8 +19,8 @@ never gets that rendering; the structured round does.- [result.json schema](#resultjson-schema)- [Rules](#rules)-Rule of thumb: **plan exists → per-criterion submit; you author the checks →-structured round ingest.** Never mix both for the same delivery round.+Rule of thumb: **you author the checks → `ingest`; a plan was handed to you →+`ingest --operation`.** Never mix both for the same delivery round.## No operation id needed@@ -155,8 +155,8 @@ supersedes? }`.one-paragraph verdict into `summary.conclusion`.5. **Write `proposal.md` — the round's own note to the reviewer.** What thisround delivers and where you want their eyes, the way a person writes a pull- request description: a few sentences, in the language the user is conversing- in. `ingest` posts it into the acceptance's discussion as a message on this+ request description: a few sentences, in the+ [report language](../SKILL.md#two-paths--no-id-is-required). `ingest` posts it into the acceptance's discussion as a message on thisround, so it is the first thing a reviewer reads and they can answer it inplace. It is NOT the verification write-up — do not restate the checks or theverdict, those are `result.json` and `report.md`. Every round gets one: the@@ -165,7 +165,7 @@ supersedes? }`.checks.6. **`report.md` is the narrative tail only** — this-round notes, follow-ups,score. Do NOT repeat the scope block or a case table; those double up on the- page. Write it in the language the user is conversing in.+ page. Write it in the report language.7. **Review, then publish:** hand the completed plan, report, original evidence,and an explicit file list with relevant diff text or prepared diff artifactpaths (including in-round repairs, base and tested revision, and affected case IDs)diff --git a/.agents/skills/acceptance/references/video-chapters.md b/.agents/skills/acceptance/references/video-chapters.mdindex fe4e8c5ab3c..ee1f2056ca8 100644--- a/.agents/skills/acceptance/references/video-chapters.md+++ b/.agents/skills/acceptance/references/video-chapters.md@@ -57,6 +57,11 @@ The recording's start time depends on the recorder:- **`simctl` / `ffmpeg` recorders**: log `mark step "Recording started"` themoment the recorder reports it started, and use that mark's `wall` as thestart.+- **Playwright `recordVideo`**: the video starts when the browser context is+ created, not at your first `goto` or `reload`. Log the start right after+ `browser.newContext(...)` returns, and log marks from the script itself+ (`Date.now() / 1000` per mark) — times measured from a reload or from+ `performance.now()` are offset by every second spent before them.Convert marks into chapters:@@ -90,20 +95,26 @@ Authored rounds put `chapters` on the video's evidence entry in `result.json`:]```-A single upload carries them in metadata:+Plan rounds use the same `result.json` entry and publish it with+`ingest --operation`. A single supplementary upload takes the chapters file+directly, and rejects a malformed marker before uploading:```bash-lh acceptance run evidence upload --check "$CHECK_RESULT_ID" --type video \- --file ./proof/scroll-top.mp4 --desc "Five scrolls at the top of a short topic" \- --metadata "{\"chapters\": $(cat ./proof/flow.chapters.json)}"+lh acceptance run result submit --operation "$OPERATION_ID" --item "$CHECK_ITEM_ID" \+ --type video --file ./proof/scroll-top.mp4 --chapters ./proof/flow.chapters.json \+ --desc "Five scrolls at the top of a short topic"+# with a check result id instead: lh acceptance run evidence upload --check … --chapters …```Ingest warns and drops every malformed marker — a negative or missing `t`, anunknown `kind`, a `step` without a `label`, a `check`/`flag` without a `note` —and ignores chapters on anything that is not a video. Treat the warning as a-claim the reviewer will not see: fix it and re-ingest before handing off.-Chapters need `lh` 0.0.60 or later (`lh --version`); an older CLI uploads the-video without them, so read the evidence back and confirm they arrived.+claim the reviewer will not see: fix it and re-ingest before handing off — in a+plan round, supplement that video with `result submit --chapters` instead, since+a second ingest duplicates every artifact. Chapters need `lh` 0.0.60 or later+(`lh --version`); an older CLI uploads the video without them, so read the+evidence back and confirm they arrived. `--chapters` on a single upload is newer+still: `lh acceptance run result submit --help` lists it when available.## When the reviewer answers on the timelinediff --git a/.agents/skills/acceptance/surfaces/cli.md b/.agents/skills/acceptance/surfaces/cli.mdindex 68bdf4feeb3..0c54b448973 100644--- a/.agents/skills/acceptance/surfaces/cli.md+++ b/.agents/skills/acceptance/surfaces/cli.md@@ -13,28 +13,24 @@ about rendered UI.1. Run the command, test, or query that exercises the change. Prefer a machineoutput mode (`--json`, a structured dump) so the proof is assertable, not prose.-2. Capture the output and upload it as `text` evidence — inline with `--content`- for short output, or `--file` for a larger dump.+2. Save the output into the round's `assets/` and list it in the case's+ `evidence` — ingest inlines small text files and uploads larger dumps.```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 "$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 "$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 "$OPERATION_ID" --item "$CHECK_ITEM_ID" --type text \- --file ./proof/test.log --by program --desc "regression spec passes"+your-cli command --json > "$REPORT_DIR/assets/new-field.json"+your-test-runner path/to/spec > "$REPORT_DIR/assets/regression.log" 2>&1```-Provenance: `cli` for command stdout, `program` for a script/test you ran. See+```jsonc+// the case in result.json (its id is the plan item id when a plan was handed to you)+"evidence": [+ { "path": "assets/new-field.json", "description": "command reports the new field after the change" },+ { "path": "assets/regression.log", "description": "regression spec passes" }+]+```++When supplementing with `result submit`, `--by` is `cli` for command stdout and+`program` for a script/test you ran. See[../references/evidence.md](../references/evidence.md) for the evidence contract.## Authdiff --git a/.agents/skills/acceptance/surfaces/native.md b/.agents/skills/acceptance/surfaces/native.mdindex f481542e264..a083f290f01 100644--- a/.agents/skills/acceptance/surfaces/native.md+++ b/.agents/skills/acceptance/surfaces/native.md@@ -27,16 +27,17 @@ osascript -e "tell application \"$APP\" to activate"sleep 1# ... navigate + act via osascript (see computer-use.md) ...sleep 2 # let the result settle-screencapture -l "$(osascript -e "tell application \"System Events\" to tell process \"$APP\" to get id of window 1")" ./proof/native-result.png+screencapture -l "$(osascript -e "tell application \"System Events\" to tell process \"$APP\" to get id of window 1")" "$REPORT_DIR/assets/native-result.png"```-Upload as evidence (provenance `cli`, since osascript/screencapture are-shell-driven):+Save it into the round's `assets/` and cite it from the case once you have+looked at it:-```bash-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"+```jsonc+"evidence": [+ { "path": "assets/native-result.png",+ "description": "Native app shows the expected state after the change" }+]```## Mid-flow use from another surfacediff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.mdindex 7bdf2f284be..c6d7b17cef6 100644--- a/.agents/skills/cli/SKILL.md+++ b/.agents/skills/cli/SKILL.md@@ -23,6 +23,7 @@ apps/cli/src/├── index.ts # Entry point — parses argv, invokes program.ts├── program.ts # Builds the Commander program, registers every command├── api/+│ ├── acceptance/ # `lh acceptance`: review loop, rounds (run/), plans, criteria, rubrics; `lh verify` aliases│ ├── client.ts # tRPC client (type-safe backend API)│ └── http.ts # Raw HTTP utilities├── auth/@@ -69,8 +70,6 @@ apps/cli/src/│ ├── trace/ # Inspect and replay recorded agent execution traces│ ├── update.ts # Self-update to the latest published version│ ├── user.ts # User account & settings-│ ├── verify.ts # Agent Run verification machinery (criteria, rubrics, check plans)-│ ├── verifyAcceptance.ts # `lh acceptance`: cross-round delivery review loop│ └── workspace.ts # Workspace list/scope/members/usage/audit├── daemon/│ └── manager.ts # Background daemon process management@@ -106,8 +105,8 @@ apps/cli/src/| `lh task` | - | Manage agent tasks (assignees, checkpoints, deps, review) || `lh thread` | - | Manage message threads || `lh trace` | - | Inspect and replay recorded agent execution traces |-| `lh verify` | - | Agent Run verification machinery — criteria, rubrics, per-run check plans |-| `lh acceptance` | - | Delivery acceptances — the cross-round review loop (checks, feedback, decision) |+| `lh acceptance` | - | Delivery acceptances: review loop, rounds, per-run check plans, criteria, rubrics |+| `lh verify` | - | Deprecated alias of `lh acceptance` commands || `lh eval` | - | Manage evaluation workflows and benchmarks || `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) || `lh doc` | - | Document CRUD, batch-create, parse, topic linking |diff --git a/apps/cli/src/commands/acceptanceCommentFeedback.ts b/apps/cli/src/commands/acceptance/commentFeedback.tssimilarity index 97%rename from apps/cli/src/commands/acceptanceCommentFeedback.tsrename to apps/cli/src/commands/acceptance/commentFeedback.tsindex e658299aaf3..4ed77ab4597 100644--- a/apps/cli/src/commands/acceptanceCommentFeedback.ts+++ b/apps/cli/src/commands/acceptance/commentFeedback.ts@@ -1,6 +1,6 @@import type { AcceptanceCommentItem } from '@lobechat/types';-import { formatAnnotationRegion } from './verifyHelpers';+import { formatAnnotationRegion } from './utils';interface FeedbackCheck {id: string;diff --git a/apps/cli/src/commands/acceptance/criterion.ts b/apps/cli/src/commands/acceptance/criterion.tsnew file mode 100644index 00000000000..236b5dea3fb--- /dev/null+++ b/apps/cli/src/commands/acceptance/criterion.ts@@ -0,0 +1,91 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { confirm, outputJson, printTable, timeAgo, truncate } from '../../utils/format';+import {+ assertEnum,+ ON_FAIL,+ type OnFail,+ parseConfig,+ VERIFIER_TYPES,+ type VerifierType,+} from './utils';++/** `criterion` — reusable pass/fail standards that rubrics and plans draw on. */+export function attachCriterionCommands(parent: Command): Command {+ const criterion = parent.command('criterion').description('Reusable pass/fail standards');++ criterion+ .command('list')+ .description('List criteria')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const items = await client.verify.listCriteria.query();++ if (options.json !== undefined) {+ outputJson(items, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (items.length === 0) return void console.log('No criteria found.');+ printTable(+ items.map((c) => [+ c.id,+ truncate(c.title, 60),+ c.verifierType,+ c.required ? 'gate' : 'soft',+ c.onFail,+ c.updatedAt ? timeAgo(c.updatedAt) : '',+ ]),+ ['ID', 'TITLE', 'TYPE', 'BLOCK', 'ON-FAIL', 'UPDATED'],+ );+ });++ criterion+ .command('create')+ .description('Create a criterion')+ .requiredOption('-t, --title <title>', 'Criterion title')+ .requiredOption('--type <type>', `Verifier type (${VERIFIER_TYPES.join('|')})`)+ .option('--on-fail <strategy>', `Action on failure (${ON_FAIL.join('|')})`)+ .option('--soft', 'Non-blocking (required=false); defaults to blocking')+ .option('--config <json>', 'Verifier config as JSON')+ .option('--doc <id>', 'Linked guidance document id')+ .action(+ async (options: {+ config?: string;+ doc?: string;+ onFail?: OnFail;+ soft?: boolean;+ title: string;+ type: VerifierType;+ }) => {+ assertEnum(options.type, VERIFIER_TYPES, '--type');+ assertEnum(options.onFail, ON_FAIL, '--on-fail');+ const client = await getTrpcClient();+ const result = await client.verify.createCriterion.mutate({+ documentId: options.doc,+ onFail: options.onFail,+ required: options.soft ? false : undefined,+ title: options.title,+ verifierConfig: parseConfig(options.config),+ verifierType: options.type,+ });+ console.log(`${pc.green('✓')} Created criterion ${pc.bold((result as any).id)}`);+ },+ );++ criterion+ .command('delete <id>')+ .description('Delete a criterion')+ .option('--yes', 'Skip confirmation')+ .action(async (id: string, options: { yes?: boolean }) => {+ if (!options.yes && !(await confirm(`Delete criterion ${id}?`)))+ return void console.log('Cancelled.');+ const client = await getTrpcClient();+ await client.verify.deleteCriterion.mutate({ id });+ console.log(`${pc.green('✓')} Deleted criterion ${pc.bold(id)}`);+ });++ return criterion;+}diff --git a/apps/cli/src/commands/acceptance/deprecatedVerify.test.ts b/apps/cli/src/commands/acceptance/deprecatedVerify.test.tsnew file mode 100644index 00000000000..fb44a954d15--- /dev/null+++ b/apps/cli/src/commands/acceptance/deprecatedVerify.test.ts@@ -0,0 +1,88 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerAcceptanceCommands } from '.';+import { registerVerifyCommand } from './deprecatedVerify';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ verify: {+ getVerifyState: { query: vi.fn() },+ listCriteria: { query: vi.fn() },+ listRubrics: { query: vi.fn() },+ },+ },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn(async () => mockTrpcClient) }));+vi.mock('../../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++const parse = async (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerVerifyCommand(program);+ registerAcceptanceCommands(program);+ await program.parseAsync(['node', 'lh', ...args]);+};++describe('`lh verify` moved under `lh acceptance`', () => {+ beforeEach(() => {+ vi.spyOn(log, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});+ mockTrpcClient.verify.getVerifyState.query.mockResolvedValue(null);+ mockTrpcClient.verify.listCriteria.query.mockResolvedValue([]);+ mockTrpcClient.verify.listRubrics.query.mockResolvedValue([]);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it.each([+ [['acceptance', 'plan', 'state', 'op_1']],+ [['acceptance', 'criterion', 'list']],+ [['acceptance', 'rubric', 'list']],+ ])('runs %j without a deprecation warning', async (args) => {+ await parse(...args);++ expect(log.warn).not.toHaveBeenCalled();+ });++ it.each([+ [['verify', 'plan', 'state', 'op_1'], 'lh acceptance plan state'],+ [['verify', 'criterion', 'list'], 'lh acceptance criterion list'],+ [['verify', 'rubric', 'list'], 'lh acceptance rubric list'],+ ])('keeps %j working and names %s as its replacement', async (args, replacement) => {+ await parse(...args);++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining(`use \`${replacement}\``));+ });++ it('routes both spellings of plan state to the same query', async () => {+ await parse('verify', 'plan', 'state', 'op_1');+ await parse('acceptance', 'plan', 'state', 'op_2');++ expect(mockTrpcClient.verify.getVerifyState.query.mock.calls).toEqual([+ [{ operationId: 'op_1' }],+ [{ operationId: 'op_2' }],+ ]);+ });++ it('points `lh verify execute` at `lh acceptance plan execute`', async () => {+ const program = new Command();+ registerVerifyCommand(program);+ registerAcceptanceCommands(program);+ const plan = program.commands+ .find((c) => c.name() === 'acceptance')+ ?.commands.find((c) => c.name() === 'plan');++ expect(plan?.commands.map((c) => c.name())).toContain('execute');+ expect(program.commands.find((c) => c.name() === 'verify')?.description()).toContain(+ 'lh acceptance',+ );+ });+});diff --git a/apps/cli/src/commands/acceptance/deprecatedVerify.ts b/apps/cli/src/commands/acceptance/deprecatedVerify.tsnew file mode 100644index 00000000000..5a9ff33c297--- /dev/null+++ b/apps/cli/src/commands/acceptance/deprecatedVerify.ts@@ -0,0 +1,42 @@+import type { Command } from 'commander';++import { log } from '../../utils/logger';+import { attachCriterionCommands } from './criterion';+import { registerAcceptanceCommands } from './index';+import { attachPlanCommands, attachPlanExecuteCommand } from './plan';+import { attachRubricCommands } from './rubric';+import { attachDeprecatedVerifyRunAliases } from './run';++/** Warn before any command of a group that moved under `lh acceptance` runs. */+const deprecateGroup = (group: Command, replacement: string): Command =>+ group.hook('preAction', (_group, action) => {+ // The subcommand path below the group, e.g. `state` for `verify plan state`.+ const rest: string[] = [];+ for (let cmd: Command | null = action; cmd && cmd !== group; cmd = cmd.parent)+ rest.unshift(cmd.name());+ const suffix = rest.length > 0 ? ` ${rest.join(' ')}` : '';+ log.warn(+ `\`lh verify ${group.name()}${suffix}\` is deprecated — use \`${replacement}${suffix}\` (removed in a future release)`,+ );+ });++/**+ * The pre-move `lh verify …` command surface. Every command now lives under+ * `lh acceptance`; these aliases wire the same implementations and warn, and+ * are scheduled for removal once callers migrate.+ */+export function registerVerifyCommand(program: Command) {+ const verify = program.command('verify').description('Deprecated — use `lh acceptance`');++ // `verify acceptance …` — legacy alias of the first-class `lh acceptance`.+ registerAcceptanceCommands(verify, { deprecated: true });+ attachDeprecatedVerifyRunAliases(verify);++ deprecateGroup(attachCriterionCommands(verify), 'lh acceptance criterion');+ deprecateGroup(attachRubricCommands(verify), 'lh acceptance rubric');+ deprecateGroup(attachPlanCommands(verify), 'lh acceptance plan');+ deprecateGroup(+ attachPlanExecuteCommand(verify.command('execute <operationId>')),+ 'lh acceptance plan execute',+ );+}diff --git a/apps/cli/src/commands/acceptanceFlowFeedback.test.ts b/apps/cli/src/commands/acceptance/flow.feedback.test.tssimilarity index 96%rename from apps/cli/src/commands/acceptanceFlowFeedback.test.tsrename to apps/cli/src/commands/acceptance/flow.feedback.test.tsindex eae9ce9bbc9..4a228561700 100644--- a/apps/cli/src/commands/acceptanceFlowFeedback.test.ts+++ b/apps/cli/src/commands/acceptance/flow.feedback.test.ts@@ -1,17 +1,17 @@import { Command } from 'commander';import { expect, it, vi } from 'vitest';-import type * as Format from '../utils/format';-import { registerAcceptanceCommands } from './verifyAcceptance';+import type * as Format from '../../utils/format';+import { registerAcceptanceCommands } from '.';const { getBundle, outputJson } = vi.hoisted(() => ({ getBundle: vi.fn(), outputJson: vi.fn() }));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: async () => ({acceptance: { getBundle: { query: getBundle } },acceptanceComment: { list: { query: async () => ({ items: [] }) } },}),}));-vi.mock('../utils/format', async (original) => ({+vi.mock('../../utils/format', async (original) => ({...(await original<typeof Format>()),outputJson,}));diff --git a/apps/cli/src/commands/acceptanceFlow.test.ts b/apps/cli/src/commands/acceptance/flow.test.tssimilarity index 94%rename from apps/cli/src/commands/acceptanceFlow.test.tsrename to apps/cli/src/commands/acceptance/flow.test.tsindex 8e5a86b6e23..5dd0d62d53a 100644--- a/apps/cli/src/commands/acceptanceFlow.test.ts+++ b/apps/cli/src/commands/acceptance/flow.test.ts@@ -1,7 +1,7 @@import { Command } from 'commander';import { expect, it, vi } from 'vitest';-import { attachAcceptanceFlowCommands } from './acceptanceFlow';+import { attachAcceptanceFlowCommands } from './flow';const { startFlow, deleteFlow, confirm, outputJson } = vi.hoisted(() => ({startFlow: vi.fn().mockResolvedValue({ id: 'flow-run' }),@@ -10,12 +10,12 @@ const { startFlow, deleteFlow, confirm, outputJson } = vi.hoisted(() => ({outputJson: vi.fn(),}));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: async () => ({acceptance: { startFlow: { mutate: startFlow }, deleteFlow: { mutate: deleteFlow } },}),}));-vi.mock('../utils/format', () => ({ confirm, outputJson }));+vi.mock('../../utils/format', () => ({ confirm, outputJson }));it('starts the requested flow version without triggering the root CLI version option', async () => {const program = new Command().version('0.0.52').exitOverride();diff --git a/apps/cli/src/commands/acceptanceFlow.ts b/apps/cli/src/commands/acceptance/flow.tssimilarity index 95%rename from apps/cli/src/commands/acceptanceFlow.tsrename to apps/cli/src/commands/acceptance/flow.tsindex 7f552eef777..c6573da22f4 100644--- a/apps/cli/src/commands/acceptanceFlow.ts+++ b/apps/cli/src/commands/acceptance/flow.ts@@ -3,9 +3,9 @@ import { readFile } from 'node:fs/promises';import type { Command } from 'commander';import pc from 'picocolors';-import { getTrpcClient } from '../api/client';-import { confirm, outputJson } from '../utils/format';-import { assertReportLanguage, flowLanguageFields } from './acceptanceLanguage';+import { getTrpcClient } from '../../api/client';+import { confirm, outputJson } from '../../utils/format';+import { assertReportLanguage, flowLanguageFields } from './language';/** Agent entry point: author a graph before exercising the product, then append real visits. */export function attachAcceptanceFlowCommands(acceptance: Command) {diff --git a/apps/cli/src/commands/verifyAcceptance.create.test.ts b/apps/cli/src/commands/acceptance/index.create.test.tssimilarity index 96%rename from apps/cli/src/commands/verifyAcceptance.create.test.tsrename to apps/cli/src/commands/acceptance/index.create.test.tsindex 308343dd36d..1b8a2b86bc9 100644--- a/apps/cli/src/commands/verifyAcceptance.create.test.ts+++ b/apps/cli/src/commands/acceptance/index.create.test.ts@@ -5,11 +5,11 @@ import path from 'node:path';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { getTrpcClient } from '../api/client';-import { registerAcceptanceCommands } from './verifyAcceptance';+import { getTrpcClient } from '../../api/client';+import { registerAcceptanceCommands } from '.';-vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));-vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://self-hosted.example/base/' }));+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://self-hosted.example/base/' }));const acceptanceId = 'd8391b91-60bb-49be-a5b7-f14f0c52876a';const acceptanceUrl = `https://self-hosted.example/acceptance/${acceptanceId}`;diff --git a/apps/cli/src/commands/acceptanceFeedback.test.ts b/apps/cli/src/commands/acceptance/index.feedback.test.tssimilarity index 98%rename from apps/cli/src/commands/acceptanceFeedback.test.tsrename to apps/cli/src/commands/acceptance/index.feedback.test.tsindex e87243c6adf..3fd8de66077 100644--- a/apps/cli/src/commands/acceptanceFeedback.test.ts+++ b/apps/cli/src/commands/acceptance/index.feedback.test.ts@@ -2,8 +2,8 @@ import type { AcceptanceCommentItem } from '@lobechat/types';import { Command } from 'commander';import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import type * as Format from '../utils/format';-import { registerAcceptanceCommands } from './verifyAcceptance';+import type * as Format from '../../utils/format';+import { registerAcceptanceCommands } from '.';const { getBundle, listComments, outputJson, setPreviewUrl } = vi.hoisted(() => ({getBundle: vi.fn(),@@ -11,13 +11,13 @@ const { getBundle, listComments, outputJson, setPreviewUrl } = vi.hoisted(() =>outputJson: vi.fn(),setPreviewUrl: vi.fn(),}));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: async () => ({acceptance: { getBundle: { query: getBundle }, setPreviewUrl: { mutate: setPreviewUrl } },acceptanceComment: { list: { query: listComments } },}),}));-vi.mock('../utils/format', async (original) => ({+vi.mock('../../utils/format', async (original) => ({...(await original<typeof Format>()),outputJson,}));diff --git a/apps/cli/src/commands/verifyAcceptance.linkPr.test.ts b/apps/cli/src/commands/acceptance/index.linkPr.test.tssimilarity index 92%rename from apps/cli/src/commands/verifyAcceptance.linkPr.test.tsrename to apps/cli/src/commands/acceptance/index.linkPr.test.tsindex 35ef7b76e40..854a0932025 100644--- a/apps/cli/src/commands/verifyAcceptance.linkPr.test.ts+++ b/apps/cli/src/commands/acceptance/index.linkPr.test.ts@@ -1,10 +1,10 @@import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { getTrpcClient } from '../api/client';-import { registerAcceptanceCommands } from './verifyAcceptance';+import { getTrpcClient } from '../../api/client';+import { registerAcceptanceCommands } from '.';-vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));const acceptanceId = '598ebab1-74a3-4a7f-9bcb-9bfa71c654cb';const prUrl = 'https://github.com/lobehub/lobehub/pull/20171';diff --git a/apps/cli/src/commands/verifyAcceptance.regroup.test.ts b/apps/cli/src/commands/acceptance/index.regroup.test.tssimilarity index 90%rename from apps/cli/src/commands/verifyAcceptance.regroup.test.tsrename to apps/cli/src/commands/acceptance/index.regroup.test.tsindex 4c974b9334f..abdd6ad290a 100644--- a/apps/cli/src/commands/verifyAcceptance.regroup.test.ts+++ b/apps/cli/src/commands/acceptance/index.regroup.test.ts@@ -5,16 +5,16 @@ import path from 'node:path';import { Command } from 'commander';import { afterEach, expect, it, vi } from 'vitest';-import { registerAcceptanceCommands } from './verifyAcceptance';+import { registerAcceptanceCommands } from '.';const { regroup, outputJson } = vi.hoisted(() => ({regroup: vi.fn().mockResolvedValue({ version: 2 }),outputJson: vi.fn(),}));-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({getTrpcClient: async () => ({ acceptance: { regroupChecks: { mutate: regroup } } }),}));-vi.mock('../utils/format', () => ({ outputJson }));+vi.mock('../../utils/format', () => ({ outputJson }));afterEach(() => vi.clearAllMocks());it('submits only the requested grouping and version, without starting a verification round', async () => {diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/acceptance/index.tssimilarity index 96%rename from apps/cli/src/commands/verifyAcceptance.tsrename to apps/cli/src/commands/acceptance/index.tsindex 39ba20d866a..ceff266b37e 100644--- a/apps/cli/src/commands/verifyAcceptance.ts+++ b/apps/cli/src/commands/acceptance/index.ts@@ -7,22 +7,25 @@ import type { Command } from 'commander';import { InvalidArgumentError } from 'commander';import pc from 'picocolors';-import { getTrpcClient } from '../api/client';-import { resolveServerUrl } from '../settings';-import { outputJson, printTable, timeAgo, truncate } from '../utils/format';-import { log } from '../utils/logger';-import { collectCommentFeedback } from './acceptanceCommentFeedback';-import { attachAcceptanceFlowCommands } from './acceptanceFlow';+import { getTrpcClient } from '../../api/client';+import { resolveServerUrl } from '../../settings';+import { outputJson, printTable, timeAgo, truncate } from '../../utils/format';+import { log } from '../../utils/logger';+import { collectCommentFeedback } from './commentFeedback';+import { attachCriterionCommands } from './criterion';+import { attachAcceptanceFlowCommands } from './flow';import {assertReportLanguage,languageSummary,resolveReportLanguage,responseLanguageSettingsUrl,unsetLanguageWarning,-} from './acceptanceLanguage';-import { attachAcceptanceRunCommands } from './acceptanceRun';-import type { ReviewAnnotationRegion } from './verifyHelpers';-import { formatAnnotationRegion, formatDisputedChapter, parseSubjectRef } from './verifyHelpers';+} from './language';+import { attachPlanCommands } from './plan';+import { attachRubricCommands } from './rubric';+import { attachAcceptanceRunCommands } from './run';+import type { ReviewAnnotationRegion } from './utils';+import { formatAnnotationRegion, formatDisputedChapter, parseSubjectRef } from './utils';/*** Resolve an acceptance from either its uuid or a `type:id` subject reference —@@ -658,8 +661,12 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat}});- // The canonical `lh acceptance init` + `lh acceptance run …` tree hangs off the- // first-class command only; the legacy `lh verify acceptance` alias stays a thin- // decision surface (its run commands keep their old `lh verify …` spellings).- if (!options?.deprecated) attachAcceptanceRunCommands(acceptance);+ // The canonical `lh acceptance install` + `run` / `plan` / `criterion` / `rubric`+ // trees hang off the first-class command only; the legacy `lh verify acceptance`+ // alias stays a thin decision surface (the rest keep their `lh verify …` aliases).+ if (options?.deprecated) return;+ attachAcceptanceRunCommands(acceptance);+ attachPlanCommands(acceptance);+ attachCriterionCommands(acceptance);+ attachRubricCommands(acceptance);}diff --git a/apps/cli/src/commands/acceptanceInstall.test.ts b/apps/cli/src/commands/acceptance/install.test.tssimilarity index 97%rename from apps/cli/src/commands/acceptanceInstall.test.tsrename to apps/cli/src/commands/acceptance/install.test.tsindex 673f97bb4b8..1e67151a6a8 100644--- a/apps/cli/src/commands/acceptanceInstall.test.ts+++ b/apps/cli/src/commands/acceptance/install.test.ts@@ -5,11 +5,11 @@ import path from 'node:path';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createPublicLambdaClient, getTrpcClient } from '../api/client';-import { registerVerifyCommand } from './verify';-import { registerAcceptanceCommands } from './verifyAcceptance';+import { createPublicLambdaClient, getTrpcClient } from '../../api/client';+import { registerAcceptanceCommands } from '.';+import { registerVerifyCommand } from './deprecatedVerify';-vi.mock('../api/client', () => ({+vi.mock('../../api/client', () => ({createPublicLambdaClient: vi.fn(),getTrpcClient: vi.fn(),}));diff --git a/apps/cli/src/commands/acceptance/install.ts b/apps/cli/src/commands/acceptance/install.tsnew file mode 100644index 00000000000..864174d16b7--- /dev/null+++ b/apps/cli/src/commands/acceptance/install.ts@@ -0,0 +1,168 @@+import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import path from 'node:path';++import type { Command } from 'commander';+import pc from 'picocolors';++import type { TrpcClient } from '../../api/client';+import { ensureAcceptanceDirIgnored } from '../../utils/acceptanceDir';+import { outputJson } from '../../utils/format';+import type { LinkResult } from '../../utils/skillWiring';+import { linkHarnessSkills } from '../../utils/skillWiring';++// ── install ──++export interface InstallOptions {+ dir?: string;+ force?: boolean;+ json?: boolean | string;+ skill: string;+ skillVersion?: string;+}++const listMaterializedFiles = (directory: string): string[] => {+ if (!existsSync(directory)) return [];++ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const entryPath = path.join(directory, entry.name);+ return entry.isDirectory() ? listMaterializedFiles(entryPath) : [entryPath];+ });+};++export async function installAction(options: InstallOptions, client: TrpcClient): Promise<void> {+ const version = options.skillVersion?.replace(/^v/, '');+ const bundle = await client.verify.getSkillBundle.query({+ identifier: options.skill,+ ...(version === undefined ? {} : { version }),+ });+ // Older servers ignore the requested version. A matching version label alone+ // does not prove that the content was resolved from the requested tag.+ if (+ version !== undefined &&+ (bundle.version !== version || bundle.source?.ref !== `v${version}`)+ ) {+ throw new Error(+ `Requested acceptance skill ${version} from tag v${version}, but the server returned version ${bundle.version ?? 'unknown'} from ${bundle.source?.ref ?? 'an unknown source'}. Update your server to support skill tag selection.`,+ );+ }++ // 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. 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);++ // path → content for SKILL.md plus every resource file.+ const entries: [string, string][] = [+ ['SKILL.md', bundle.content],+ ...Object.entries(bundle.files),+ ];++ const written: string[] = [];+ const skipped: string[] = [];+ for (const [rel, content] of entries) {+ const dest = path.join(skillDir, rel);+ if (existsSync(dest) && !options.force) {+ skipped.push(rel);+ continue;+ }+ mkdirSync(path.dirname(dest), { recursive: true });+ writeFileSync(dest, content, 'utf8');+ written.push(rel);+ }++ // `acceptance update` is an explicit force-refresh of a materialized skill,+ // not a merge into a hand-maintained directory. Remove files that belonged to+ // an older bundle so renamed/split references cannot remain discoverable.+ const removed: string[] = [];+ if (options.force) {+ const currentEntries = new Set(entries.map(([rel]) => path.normalize(rel)));+ for (const file of listMaterializedFiles(skillDir)) {+ const relativePath = path.relative(skillDir, file);+ if (currentEntries.has(path.normalize(relativePath))) continue;++ rmSync(file, { force: true });+ removed.push(relativePath.split(path.sep).join('/'));+ }+ }++ const links = linkHarnessSkills(baseDir, bundle.identifier);+ // `link` predates `links` and stays as a compatibility alias for the Claude+ // result — `install --json link` and `.link.kind` readers keep working.+ const link: LinkResult = links.find((l) => 'link' in l && l.link.startsWith('.claude')) ?? {+ kind: 'none',+ };+ // The skill is committed; its OUTPUT is not. Seed the artifact directory's own+ // self-ignoring file now, so the first run's screenshots never land as+ // untracked noise in a repo that has never heard of us.+ const ignored = ensureAcceptanceDirIgnored(baseDir);++ const result = {+ dir: skillDir,+ ignored,+ link,+ links,+ removed,+ skill: bundle.identifier,+ skipped,+ source: bundle.source,+ // 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)}${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(links);+}++function printWiring(links: LinkResult[]): void {+ const arrow = pc.dim(' ↳');+ for (const link of links) {+ switch (link.kind) {+ case 'linked':+ case 'linked-single': {+ console.log(`${arrow} linked ${link.link} → ${pc.dim(link.target)}`);+ break;+ }+ case 'already': {+ console.log(`${arrow} ${pc.dim(`${link.link} already linked`)}`);+ break;+ }+ case 'skipped': {+ console.log(`${arrow} ${pc.yellow(`skipped ${link.link}: ${link.reason}`)}`);+ break;+ }+ default: {+ console.log(+ `${arrow} ${pc.dim('no harness dirs detected — agents that read .agents/skills pick it up automatically')}`,+ );+ break;+ }+ }+ }+}++export function withInstallOptions(cmd: Command): Command {+ return cmd+ .option('--dir <path>', 'Target working directory (default: current dir)')+ .option('--skill <id>', 'Skill identifier to pull', 'acceptance')+ .option(+ '--skill-version <version>',+ 'Install a specific skill tag (default: latest default-branch source)',+ )+ .option('--force', 'Overwrite existing skill files')+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptanceLanguage.test.ts b/apps/cli/src/commands/acceptance/language.test.tssimilarity index 98%rename from apps/cli/src/commands/acceptanceLanguage.test.tsrename to apps/cli/src/commands/acceptance/language.test.tsindex 45e23f221fa..79442aed434 100644--- a/apps/cli/src/commands/acceptanceLanguage.test.ts+++ b/apps/cli/src/commands/acceptance/language.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { log } from '../utils/logger';+import { log } from '../../utils/logger';import {assertReportLanguage,findLanguageViolations,@@ -8,9 +8,9 @@ import {ingestLanguageFields,ReportLanguageError,reportLanguageFor,-} from './acceptanceLanguage';+} from './language';-vi.mock('../settings', () => ({+vi.mock('../../settings', () => ({resolveServerUrl: () => 'https://user:[email protected]',}));diff --git a/apps/cli/src/commands/acceptanceLanguage.ts b/apps/cli/src/commands/acceptance/language.tssimilarity index 99%rename from apps/cli/src/commands/acceptanceLanguage.tsrename to apps/cli/src/commands/acceptance/language.tsindex 61930bf19e9..b4f389477d3 100644--- a/apps/cli/src/commands/acceptanceLanguage.ts+++ b/apps/cli/src/commands/acceptance/language.ts@@ -1,5 +1,5 @@-import { resolveServerUrl } from '../settings';-import { log } from '../utils/logger';+import { resolveServerUrl } from '../../settings';+import { log } from '../../utils/logger';/*** Acceptance pages are read by the account owner, so every human-readablediff --git a/apps/cli/src/commands/acceptance/plan.ts b/apps/cli/src/commands/acceptance/plan.tsnew file mode 100644index 00000000000..5d296ca3cf9--- /dev/null+++ b/apps/cli/src/commands/acceptance/plan.ts@@ -0,0 +1,154 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { outputJson, printTable, timeAgo, truncate } from '../../utils/format';+import { printResults } from './utils';++/** `plan` — the per-run check plan lifecycle of an Agent Run's acceptance round. */+export function attachPlanCommands(parent: Command): Command {+ const plan = parent.command('plan').description('Per-run check plan lifecycle');++ plan+ .command('generate <operationId>')+ .description('Generate a draft check plan for a run')+ .requiredOption('--goal <goal>', "The run's task/instruction the plan must satisfy")+ .option('--rubric <id>', 'Mounted rubric id')+ .option('--criteria <ids>', 'Ad-hoc criterion ids (comma-separated)')+ .option('--ai', 'Let the LLM propose additional criteria')+ .option('--max-ai <n>', 'Max AI-proposed criteria')+ .option('--context <text>', 'Extra context for the AI prompt')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ operationId: string,+ options: {+ ai?: boolean;+ context?: string;+ criteria?: string;+ goal: string;+ json?: boolean | string;+ maxAi?: string;+ rubric?: string;+ },+ ) => {+ const client = await getTrpcClient();+ const items = await client.verify.generateDraftPlan.mutate({+ context: options.context,+ enableAiGeneration: options.ai,+ goal: options.goal,+ maxAiCriteria: options.maxAi ? Number.parseInt(options.maxAi, 10) : undefined,+ operationId,+ verifyCriteriaIds: options.criteria+ ?.split(',')+ .map((s) => s.trim())+ .filter(Boolean),+ verifyRubricId: options.rubric ?? null,+ });+ if (options.json !== undefined) {+ outputJson(items, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Draft plan: ${pc.bold(String(items.length))} item(s)`);+ printTable(+ items.map((i: any) => [+ String(i.index),+ truncate(i.title, 60),+ i.verifierType,+ i.required ? 'gate' : 'soft',+ ]),+ ['#', 'TITLE', 'TYPE', 'BLOCK'],+ );+ },+ );++ plan+ .command('state <operationId>')+ .description('Show the verify state (status + frozen plan) of a run')+ .option('--json [fields]', 'Output JSON')+ .action(async (operationId: string, options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const state = await client.verify.getVerifyState.query({ operationId });+ if (options.json !== undefined) {+ outputJson(state, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (!state) return void console.log('No verify state for this run.');+ console.log(`${pc.bold('status')}: ${state.verifyStatus ?? pc.dim('(none)')}`);+ console.log(+ `${pc.bold('confirmed')}: ${state.verifyPlanConfirmedAt ? timeAgo(state.verifyPlanConfirmedAt) : pc.dim('no')}`,+ );+ const items = (state.verifyPlan ?? []) as any[];+ console.log(`${pc.bold('plan')}: ${items.length} item(s)`);+ if (items.length > 0)+ printTable(+ items.map((i) => [+ String(i.index),+ truncate(i.title, 60),+ i.verifierType,+ i.required ? 'gate' : 'soft',+ ]),+ ['#', 'TITLE', 'TYPE', 'BLOCK'],+ );+ });++ plan+ .command('confirm <operationId>')+ .description('Freeze (confirm) the draft plan')+ .action(async (operationId: string) => {+ const client = await getTrpcClient();+ await client.verify.confirmPlan.mutate({ operationId });+ console.log(`${pc.green('✓')} Confirmed plan for run ${pc.bold(operationId)}`);+ });++ plan+ .command('skip <operationId>')+ .description('Skip verification for a run')+ .action(async (operationId: string) => {+ const client = await getTrpcClient();+ await client.verify.skipPlan.mutate({ operationId });+ console.log(`${pc.green('✓')} Skipped verification for run ${pc.bold(operationId)}`);+ });++ attachPlanExecuteCommand(plan.command('execute <operationId>'));+ return plan;+}++/** Execute the confirmed plan against a deliverable (LLM judge). */+export function attachPlanExecuteCommand(command: Command): Command {+ return command+ .description('Execute the confirmed plan against a deliverable (LLM judge)')+ .requiredOption('--goal <goal>', "The run's task")+ .requiredOption('--deliverable <text>', 'The output to judge')+ .requiredOption('--model <model>', 'Judge model')+ .requiredOption('--provider <provider>', 'Judge provider')+ .option('--no-batch', 'Judge each item separately instead of one batched call')+ .option('--json [fields]', 'Output JSON')+ .action(+ async (+ operationId: string,+ options: {+ batch?: boolean;+ deliverable: string;+ goal: string;+ json?: boolean | string;+ model: string;+ provider: string;+ },+ ) => {+ const client = await getTrpcClient();+ const results = await client.verify.executeVerify.mutate({+ batchLlm: options.batch,+ deliverable: options.deliverable,+ goal: options.goal,+ modelConfig: { model: options.model, provider: options.provider },+ operationId,+ });+ if (options.json !== undefined) {+ outputJson(results, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ printResults(results);+ },+ );+}diff --git a/apps/cli/src/commands/acceptance/rubric.test.ts b/apps/cli/src/commands/acceptance/rubric.test.tsnew file mode 100644index 00000000000..d9ed5a8df18--- /dev/null+++ b/apps/cli/src/commands/acceptance/rubric.test.ts@@ -0,0 +1,96 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerVerifyCommand } from './deprecatedVerify';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),+ },+ },+ verify: {+ createRubric: { mutate: vi.fn() },+ deleteRun: { mutate: vi.fn() },+ getRubric: { query: vi.fn() },+ updateRubric: { mutate: vi.fn() },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++describe('verify rubric config commands', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ mockTrpcClient.verify.createRubric.mutate.mockReset().mockResolvedValue({ id: 'rub-1' });+ mockTrpcClient.verify.updateRubric.mutate.mockReset().mockResolvedValue(undefined);+ mockTrpcClient.verify.getRubric.query.mockReset();+ });++ afterEach(() => consoleSpy.mockRestore());++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerVerifyCommand(program);+ await program.parseAsync(['node', 'lh', 'verify', ...args]);+ };++ it('passes maxRepairRounds config when creating a rubric', async () => {+ await run(['rubric', 'create', '-t', 'Standard', '--max-repair-rounds', '3']);++ expect(mockTrpcClient.verify.createRubric.mutate).toHaveBeenCalledWith({+ config: { maxRepairRounds: 3 },+ description: undefined,+ title: 'Standard',+ });+ });++ it('omits config when no max-repair-rounds flag is given', async () => {+ await run(['rubric', 'create', '-t', 'Standard']);++ expect(mockTrpcClient.verify.createRubric.mutate).toHaveBeenCalledWith({+ config: undefined,+ description: undefined,+ title: 'Standard',+ });+ });++ it('updates only the config when max-repair-rounds is passed', async () => {+ await run(['rubric', 'update', 'rub-1', '--max-repair-rounds', '0']);++ expect(mockTrpcClient.verify.updateRubric.mutate).toHaveBeenCalledWith({+ id: 'rub-1',+ value: { config: { maxRepairRounds: 0 } },+ });+ });++ it('views a rubric and prints its repair-round config', async () => {+ mockTrpcClient.verify.getRubric.query.mockResolvedValue({+ config: { maxRepairRounds: 4 },+ description: 'desc',+ id: 'rub-1',+ title: 'Standard',+ });++ await run(['rubric', 'view', 'rub-1']);++ expect(mockTrpcClient.verify.getRubric.query).toHaveBeenCalledWith({ id: 'rub-1' });+ const printed = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(printed).toContain('Standard');+ expect(printed).toContain('4');+ });+});diff --git a/apps/cli/src/commands/acceptance/rubric.ts b/apps/cli/src/commands/acceptance/rubric.tsnew file mode 100644index 00000000000..ab77ed33f84--- /dev/null+++ b/apps/cli/src/commands/acceptance/rubric.ts@@ -0,0 +1,149 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { confirm, outputJson, printTable, timeAgo, truncate } from '../../utils/format';+import { log } from '../../utils/logger';++/** `rubric` — named groups of criteria a Task mounts as its acceptance contract. */+export function attachRubricCommands(parent: Command): Command {+ const rubric = parent.command('rubric').description('Named groups of criteria');++ rubric+ .command('list')+ .description('List rubrics')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const items = await client.verify.listRubrics.query();+ if (options.json !== undefined) {+ outputJson(items, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (items.length === 0) return void console.log('No rubrics found.');+ printTable(+ items.map((r) => [+ r.id,+ truncate(r.title, 60),+ truncate(r.description || '', 60),+ r.updatedAt ? timeAgo(r.updatedAt) : '',+ ]),+ ['ID', 'TITLE', 'DESCRIPTION', 'UPDATED'],+ );+ });++ rubric+ .command('create')+ .description('Create a rubric')+ .requiredOption('-t, --title <title>', 'Rubric title')+ .option('-d, --description <text>', 'Rubric description')+ .option('--max-repair-rounds <n>', 'Cap on automatic repair rounds (0-5)')+ .action(async (options: { description?: string; maxRepairRounds?: string; title: string }) => {+ const client = await getTrpcClient();+ const result = await client.verify.createRubric.mutate({+ config:+ options.maxRepairRounds !== undefined+ ? { maxRepairRounds: Number(options.maxRepairRounds) }+ : undefined,+ description: options.description,+ title: options.title,+ });+ console.log(`${pc.green('✓')} Created rubric ${pc.bold((result as any).id)}`);+ });++ rubric+ .command('view <id>')+ .description('Show a rubric and its run-policy config')+ .option('--json [fields]', 'Output JSON')+ .action(async (id: string, options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const item = await client.verify.getRubric.query({ id });+ if (!item) return void log.error('Rubric not found.');+ if (options.json !== undefined) {+ outputJson(item, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.bold('ID')} ${item.id}`);+ console.log(`${pc.bold('Title')} ${item.title}`);+ if (item.description) console.log(`${pc.bold('Description')} ${item.description}`);+ const maxRepairRounds = (item.config as { maxRepairRounds?: number } | null)?.maxRepairRounds;+ console.log(`${pc.bold('Repair rounds')} ${maxRepairRounds ?? pc.dim('default')}`);+ });++ rubric+ .command('update <id>')+ .description('Update a rubric (title / description / run-policy config)')+ .option('-t, --title <title>', 'New title')+ .option('-d, --description <text>', 'New description')+ .option('--max-repair-rounds <n>', 'Cap on automatic repair rounds (0-5)')+ .action(+ async (+ id: string,+ options: { description?: string; maxRepairRounds?: string; title?: string },+ ) => {+ const client = await getTrpcClient();+ const value: {+ config?: { maxRepairRounds?: number };+ description?: string;+ title?: string;+ } = {};+ if (options.title !== undefined) value.title = options.title;+ if (options.description !== undefined) value.description = options.description;+ if (options.maxRepairRounds !== undefined)+ value.config = { maxRepairRounds: Number(options.maxRepairRounds) };+ await client.verify.updateRubric.mutate({ id, value });+ console.log(`${pc.green('✓')} Updated rubric ${pc.bold(id)}`);+ },+ );++ rubric+ .command('delete <id>')+ .description('Delete a rubric')+ .option('--yes', 'Skip confirmation')+ .action(async (id: string, options: { yes?: boolean }) => {+ if (!options.yes && !(await confirm(`Delete rubric ${id}?`)))+ return void console.log('Cancelled.');+ const client = await getTrpcClient();+ await client.verify.deleteRubric.mutate({ id });+ console.log(`${pc.green('✓')} Deleted rubric ${pc.bold(id)}`);+ });++ rubric+ .command('criteria <rubricId>')+ .description('List criteria in a rubric')+ .option('--json [fields]', 'Output JSON')+ .action(async (rubricId: string, options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const items = await client.verify.getRubricCriteria.query({ rubricId });+ if (options.json !== undefined) {+ outputJson(items, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (items.length === 0) return void console.log('No criteria in this rubric.');+ printTable(+ items.map((c: any) => [+ c.id,+ truncate(c.title, 60),+ c.verifierType,+ c.required ? 'gate' : 'soft',+ ]),+ ['ID', 'TITLE', 'TYPE', 'BLOCK'],+ );+ });++ rubric+ .command('set-criteria <rubricId> <criterionIds...>')+ .description('Set the criteria a rubric aggregates (order preserved)')+ .action(async (rubricId: string, criterionIds: string[]) => {+ const client = await getTrpcClient();+ await client.verify.setRubricCriteria.mutate({+ criteria: criterionIds.map((criterionId, i) => ({ criterionId, sortOrder: i })),+ rubricId,+ });+ console.log(+ `${pc.green('✓')} Rubric ${pc.bold(rubricId)} now has ${criterionIds.length} criterion(s)`,+ );+ });++ return rubric;+}diff --git a/apps/cli/src/commands/acceptance/run/deprecatedAliases.test.ts b/apps/cli/src/commands/acceptance/run/deprecatedAliases.test.tsnew file mode 100644index 00000000000..e70e8151391--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/deprecatedAliases.test.ts@@ -0,0 +1,100 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerVerifyCommand } from '../deprecatedVerify';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),+ },+ },+ verify: {+ createRubric: { mutate: vi.fn() },+ deleteRun: { mutate: vi.fn() },+ getRubric: { query: vi.fn() },+ updateRubric: { mutate: vi.fn() },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../../../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++describe('verify run delete command', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ mockTrpcClient.verify.deleteRun.mutate.mockReset().mockResolvedValue({+ id: 'run-1',+ success: true,+ });+ });++ afterEach(() => consoleSpy.mockRestore());++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerVerifyCommand(program);+ await program.parseAsync(['node', 'lh', 'verify', ...args]);+ };++ it('deletes the run without prompting when --yes is passed', async () => {+ await run(['run', 'delete', 'run-1', '--yes']);++ expect(mockTrpcClient.verify.deleteRun.mutate).toHaveBeenCalledWith({ verifyRunId: 'run-1' });+ });+});++describe('verify evidence upload command', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ mockGetTrpcClient.mockReset();+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`process.exit ${code}`);+ }) as any);+ });++ afterEach(() => {+ exitSpy.mockRestore();+ });++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerVerifyCommand(program);+ await program.parseAsync(['node', 'lh', 'verify', ...args]);+ };++ it('rejects evidence with both file and inline content', async () => {+ await expect(+ run([+ 'evidence',+ 'upload',+ '--check',+ 'result-1',+ '--type',+ 'text',+ '--file',+ 'artifact.txt',+ '--content',+ 'inline payload',+ ]),+ ).rejects.toThrow('process.exit 1');++ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockGetTrpcClient).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/acceptance/run/deprecatedAliases.ts b/apps/cli/src/commands/acceptance/run/deprecatedAliases.tsnew file mode 100644index 00000000000..acea691f457--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/deprecatedAliases.ts@@ -0,0 +1,183 @@+import type { Command } from 'commander';++import { getTrpcClient } from '../../../api/client';+import { log } from '../../../utils/logger';+import { installAction, type InstallOptions, withInstallOptions } from '../install';+import {+ evidenceDeleteAction,+ evidenceListAction,+ evidenceUploadAction,+ withEvidenceUploadOptions,+} from './evidence';+import { ingestReportAction, withIngestReportOptions } from './ingest';+import { reportGetAction, reportUpsertAction, withReportUpsertOptions } from './report';+import {+ decisionAction,+ resultIngestAction,+ resultListAction,+ submitAction,+ withResultIngestOptions,+ withResultListOptions,+ withSubmitOptions,+} from './result';+import {+ runCreateAction,+ runDeleteAction,+ runGetAction,+ runListAction,+ withRunCreateOptions,+ withRunDeleteOptions,+} from './session';++// ── Deprecated aliases: keep the old `lh verify …` spellings working ──++/** Warn once that a `lh verify` spelling has moved under `lh acceptance`. */+function deprecate(cmd: Command, replacement: string): Command {+ return cmd.hook('preAction', () => {+ log.warn(+ `\`lh verify ${cmd.name()}\` is deprecated — use \`${replacement}\` (removed in a future release)`,+ );+ });+}++/**+ * The pre-move `lh verify …` command surface, kept as thin aliases that wire the+ * exact same actions. Scheduled for removal once callers migrate to+ * `lh acceptance`. Layout mirrors the original flat shape so existing scripts and+ * tests keep working.+ */+export function attachDeprecatedVerifyRunAliases(verify: Command): void {+ // Both legacy spellings — `verify init` (server pull) and `verify install`+ // (the old bundled-skill installer) — converge on `acceptance install`.+ deprecate(+ withInstallOptions(+ verify.command('init').description('Deprecated — use `lh acceptance install`'),+ ),+ 'lh acceptance install',+ ).action(async (options: InstallOptions) => installAction(options, await getTrpcClient()));++ deprecate(+ withInstallOptions(+ verify.command('install').description('Deprecated — use `lh acceptance install`'),+ ),+ 'lh acceptance install',+ ).action(async (options: InstallOptions) => installAction(options, await getTrpcClient()));++ deprecate(+ withIngestReportOptions(+ verify+ .command('ingest-report <reportDir>')+ .description('Deprecated — use `lh acceptance run ingest`'),+ ),+ 'lh acceptance run ingest',+ ).action(ingestReportAction);++ const run = verify.command('run').description('Deprecated — use `lh acceptance run`');+ deprecate(+ withRunCreateOptions(+ run.command('create').description('Deprecated — use `lh acceptance run create`'),+ ),+ 'lh acceptance run create',+ ).action(runCreateAction);+ run+ .command('list')+ .description('Deprecated — use `lh acceptance run list`')+ .option('--json [fields]', 'Output JSON')+ .hook('preAction', () =>+ log.warn('`lh verify run list` is deprecated — use `lh acceptance run list`'),+ )+ .action(runListAction);+ run+ .command('get <runId>')+ .description('Deprecated — use `lh acceptance run get`')+ .option('--json [fields]', 'Output JSON')+ .hook('preAction', () =>+ log.warn('`lh verify run get` is deprecated — use `lh acceptance run get`'),+ )+ .action(runGetAction);+ deprecate(+ withRunDeleteOptions(+ run.command('delete <runId>').description('Deprecated — use `lh acceptance run delete`'),+ ),+ 'lh acceptance run delete',+ ).action(runDeleteAction);++ const result = verify+ .command('result')+ .description('Deprecated — use `lh acceptance run result`');+ deprecate(+ withResultIngestOptions(+ result.command('ingest').description('Deprecated — use `lh acceptance run result ingest`'),+ ),+ 'lh acceptance run result ingest',+ ).action(resultIngestAction);+ deprecate(+ withResultListOptions(+ result.command('list').description('Deprecated — use `lh acceptance run result list`'),+ ),+ 'lh acceptance run result list',+ ).action(resultListAction);++ deprecate(+ withSubmitOptions(+ verify.command('submit').description('Deprecated — use `lh acceptance run result submit`'),+ ),+ 'lh acceptance run result submit',+ ).action(submitAction);++ verify+ .command('decision <resultId> <decision>')+ .description('Deprecated — use `lh acceptance run result decision`')+ .hook('preAction', () =>+ log.warn('`lh verify decision` is deprecated — use `lh acceptance run result decision`'),+ )+ .action(decisionAction);++ const evidence = verify+ .command('evidence')+ .description('Deprecated — use `lh acceptance run evidence`');+ deprecate(+ withEvidenceUploadOptions(+ evidence+ .command('upload')+ .description('Deprecated — use `lh acceptance run evidence upload`'),+ ),+ 'lh acceptance run evidence upload',+ ).action(evidenceUploadAction);+ evidence+ .command('list <checkResultId>')+ .description('Deprecated — use `lh acceptance run evidence list`')+ .option('--json [fields]', 'Output JSON')+ .hook('preAction', () =>+ log.warn('`lh verify evidence list` is deprecated — use `lh acceptance run evidence list`'),+ )+ .action(evidenceListAction);+ evidence+ .command('delete <evidenceId>')+ .description('Deprecated — use `lh acceptance run evidence delete`')+ .option('--json [fields]', 'Output JSON')+ .hook('preAction', () =>+ log.warn(+ '`lh verify evidence delete` is deprecated — use `lh acceptance run evidence delete`',+ ),+ )+ .action(evidenceDeleteAction);++ const report = verify+ .command('report')+ .description('Deprecated — use `lh acceptance run report`');+ deprecate(+ withReportUpsertOptions(+ report.command('upsert').description('Deprecated — use `lh acceptance run report upsert`'),+ ),+ 'lh acceptance run report upsert',+ ).action(reportUpsertAction);+ report+ .command('get <runId>')+ .description('Deprecated — use `lh acceptance run report get`')+ .option('--json [fields]', 'Output JSON')+ .hook('preAction', () =>+ log.warn('`lh verify report get` is deprecated — use `lh acceptance run report get`'),+ )+ .action(reportGetAction);+}diff --git a/apps/cli/src/commands/acceptance/run/evidence.ts b/apps/cli/src/commands/acceptance/run/evidence.tsnew file mode 100644index 00000000000..1d5e3437516--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/evidence.ts@@ -0,0 +1,118 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { outputJson, printTable, truncate } from '../../../utils/format';+import { log } from '../../../utils/logger';+import { assertReportLanguage, evidenceCaptionFields } from '../language';+import {+ evidenceDescriptionForFile,+ evidenceMetadataFromOptions,+ inlineTextEvidenceForFile,+} from '../utils';+import { uploadAcceptanceFile } from './evidenceUpload';++// ── evidence ──++export interface EvidenceUploadOptions {+ by?: string;+ chapters?: string;+ check: string;+ content?: string;+ desc?: string;+ file?: string;+ fileId?: string;+ json?: boolean | string;+ metadata?: string;+ type: string;+}++export async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<void> {+ if ([options.file, options.content, options.fileId].filter(Boolean).length !== 1) {+ log.error('Provide exactly one of --file, --file-id or --content');+ process.exit(1);+ }+ const metadata = evidenceMetadataFromOptions(options);+ const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--desc', text: options.desc },+ ...evidenceCaptionFields(options.chapters ? '--chapters' : '--metadata', metadata),+ ]);+ let fileId = options.fileId;+ let inlineContent = options.content;+ if (options.file) {+ inlineContent = inlineTextEvidenceForFile(options.file, options.type);+ if (inlineContent === undefined) {+ const uploaded = await uploadAcceptanceFile(client, options.file, options.json);+ if (!uploaded) return;+ fileId = uploaded.id;+ }+ }+ const ev = await client.verify.uploadEvidence.mutate({+ capturedBy: options.by as any,+ checkResultId: options.check,+ content: inlineContent,+ description: evidenceDescriptionForFile(options.desc, options.file),+ fileId,+ metadata,+ type: options.type as any,+ });+ if (options.json !== undefined) {+ outputJson(ev, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Evidence ${pc.bold(ev.id)}${fileId ? ` (file ${fileId})` : ''}`);+}++export async function evidenceListAction(+ checkResultId: string,+ options: { json?: boolean | string },+): Promise<void> {+ const client = await getTrpcClient();+ const rows = await client.verify.listEvidence.query({ checkResultId });+ if (options.json !== undefined) {+ outputJson(rows, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (rows.length === 0) return void console.log('No evidence.');+ printTable(+ rows.map((e: any) => [+ e.id,+ e.type,+ e.capturedBy ?? '',+ e.fileId ? 'file' : 'inline',+ truncate(e.description || '', 40),+ ]),+ ['ID', 'TYPE', 'BY', 'PAYLOAD', 'DESC'],+ );+}++export async function evidenceDeleteAction(+ evidenceId: string,+ options: { json?: boolean | string },+): Promise<void> {+ const client = await getTrpcClient();+ const result = await client.verify.deleteEvidence.mutate({ id: evidenceId });+ if (options.json !== undefined) {+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Deleted evidence ${pc.bold(result.id)}`);+}++export function withEvidenceUploadOptions(cmd: Command): Command {+ return cmd+ .requiredOption('--check <checkResultId>', 'Target check result id')+ .requiredOption(+ '--type <type>',+ 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript',+ )+ .option('--file <path>', 'Local file to upload as the artifact')+ .option('--file-id <id>', 'Attach an already-uploaded file without uploading it again')+ .option('--content <text>', 'Inline text payload (instead of a file)')+ .option('--metadata <json>', 'Evidence metadata, preserved when retrying an attachment')+ .option('--chapters <file>', 'Video chapters JSON (steps, checks, flags on the timeline)')+ .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')+ .option('--desc <text>', 'Human-readable caption')+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptanceEvidence.ts b/apps/cli/src/commands/acceptance/run/evidenceUpload.tssimilarity index 94%rename from apps/cli/src/commands/acceptanceEvidence.tsrename to apps/cli/src/commands/acceptance/run/evidenceUpload.tsindex 9d69b5561f2..8b43cccf16e 100644--- a/apps/cli/src/commands/acceptanceEvidence.ts+++ b/apps/cli/src/commands/acceptance/run/evidenceUpload.ts@@ -1,19 +1,19 @@import { access } from 'node:fs/promises';import path from 'node:path';-import type { TrpcClient } from '../api/client';-import { resolveWorkspaceId } from '../api/workspace';-import { resolveServerUrl } from '../settings';-import { outputJson } from '../utils/format';-import { log } from '../utils/logger';-import { uploadLocalFile } from '../utils/uploadLocalFile';-import type { EvidenceType } from './verifyHelpers';+import type { TrpcClient } from '../../../api/client';+import { resolveWorkspaceId } from '../../../api/workspace';+import { resolveServerUrl } from '../../../settings';+import { outputJson } from '../../../utils/format';+import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import type { EvidenceType } from '../utils';import {evidenceDescriptionForFile,evidenceTypeForFile,inlineTextEvidenceForFile,reportEvidence,-} from './verifyHelpers';+} from '../utils';export async function storageQuotaRecovery(client: TrpcClient) {const serverUrl = new URL(resolveServerUrl());diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptance/run/index.test.tssimilarity index 68%rename from apps/cli/src/commands/acceptanceRun.test.tsrename to apps/cli/src/commands/acceptance/run/index.test.tsindex a2d75fd8e9f..920c268bea2 100644--- a/apps/cli/src/commands/acceptanceRun.test.ts+++ b/apps/cli/src/commands/acceptance/run/index.test.ts@@ -1,115 +1,39 @@import { execFile } from 'node:child_process';-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';-import { tmpdir } from 'node:os';+import { readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import { Command } from 'commander';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { getTrpcClient } from '../api/client';-import { resolveWorkspaceId } from '../api/workspace';-import { resolveServerUrl } from '../settings';-import { log } from '../utils/logger';-import { uploadLocalFile } from '../utils/uploadLocalFile';-import { attachAcceptanceRunCommands } from './acceptanceRun';-import type * as VerifyHelpers from './verifyHelpers';-import { pullRequestFromBranch } from './verifyHelpers';--vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));-vi.mock('../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));-vi.mock('../settings', () => ({ resolveServerUrl: vi.fn() }));-vi.mock('../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));-vi.mock('./verifyHelpers', async (importOriginal) => ({+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveWorkspaceId } from '../../../api/workspace';+import { resolveServerUrl } from '../../../settings';+import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import type * as VerifyHelpers from '../utils';+import { pullRequestFromBranch } from '../utils';+import { attachAcceptanceRunCommands } from '.';+import { usePublicationHarness } from './testUtils';++vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));+vi.mock('../../../settings', () => ({ resolveServerUrl: vi.fn() }));+vi.mock('../../../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));+vi.mock('../utils', async (importOriginal) => ({...(await importOriginal<typeof VerifyHelpers>()),pullRequestFromBranch: vi.fn(),}));describe('acceptance publication with missing evidence', () => {- const client = {- acceptance: {- attachRun: { mutate: vi.fn() },- ensure: { mutate: vi.fn() },- getBundle: { query: vi.fn() },- linkPullRequest: { mutate: vi.fn() },- },- verify: {- createRun: { mutate: vi.fn() },- ingestResult: { mutate: vi.fn() },- uploadEvidence: { mutate: vi.fn() },- upsertReport: { mutate: vi.fn() },- },- user: { getUserState: { query: vi.fn() } },- workspace: { getById: { query: vi.fn() } },- };- let dir: string;- let printed: string[];- let originalExitCode: typeof process.exitCode;-- beforeEach(async () => {- vi.resetAllMocks();- originalExitCode = process.exitCode;- process.exitCode = undefined;- printed = [];- vi.spyOn(console, 'log').mockImplementation((line) => printed.push(String(line)));- vi.spyOn(log, 'warn').mockImplementation(() => {});- vi.mocked(resolveServerUrl).mockReturnValue('https://app.lobehub.com');- vi.mocked(getTrpcClient).mockResolvedValue(- client as unknown as Awaited<ReturnType<typeof getTrpcClient>>,- );- vi.mocked(uploadLocalFile).mockResolvedValue({ id: 'file-1', url: 'https://files.test/1' });- client.acceptance.ensure.mutate.mockResolvedValue({ id: 'acceptance-1' });- client.acceptance.getBundle.query.mockResolvedValue({});- client.acceptance.attachRun.mutate.mockResolvedValue({ id: 'run-1', roundIndex: 2 });- client.verify.createRun.mutate.mockResolvedValue({ id: 'run-1' });- client.verify.ingestResult.mutate.mockImplementation(async (input) => ({- id: `result-${input.checkItemId}`,- }));- client.verify.uploadEvidence.mutate.mockResolvedValue({ id: 'evidence-1' });- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'en-US' } },- });- dir = await mkdtemp(path.join(tmpdir(), 'lh-evidence-'));- await writeFile(path.join(dir, "screen's shot.png"), 'image fixture');- await writeFile(path.join(dir, 'scroll.mp4'), 'video fixture');- await writeFile(path.join(dir, 'output.txt'), 'Observed the expected response.');- });-- afterEach(async () => {- process.exitCode = originalExitCode;- vi.restoreAllMocks();- await rm(dir, { force: true, recursive: true });- });-- const run = async (...args: string[]) => {- const program = new Command();- program.exitOverride();- attachAcceptanceRunCommands(program.command('acceptance'));- await program.parseAsync(['node', 'lh', 'acceptance', 'run', ...args]);- };-- const report = async (requiredEvidence: string[], evidence: string[], verdict = 'passed') => {- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [{ evidence, id: 'screen', name: '用户能看到处理结果', status: verdict }],- plan: [{ id: 'screen', requiredEvidence, title: '用户能看到处理结果' }],- summary: { passed: 1, total: 1, verdict },- title: '处理结果展示',- }),- );- };-- const result = () => JSON.parse(printed.at(-1)!);- const finalCheck = () => client.verify.ingestResult.mutate.mock.calls.at(-1)![0];- const finalReport = () => client.verify.upsertReport.mutate.mock.calls.at(-1)![0];+ const h = usePublicationHarness();+ const { client, finalCheck, finalReport, report, result, run } = h;it('publishes partial JSON and downgrades a pass when quota blocks required screenshots', async () => {vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));await report(['screenshot', 'text'], ["screen's shot.png", 'output.txt']);- const original = await readFile(path.join(dir, 'result.json'), 'utf8');+ const original = await readFile(path.join(h.dir, 'result.json'), 'utf8');- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(process.exitCode).toBe(1);expect(result()).toMatchObject({@@ -139,7 +63,7 @@ describe('acceptance publication with missing evidence', () => {uncertainChecks: 1,verdict: 'uncertain',});- expect(await readFile(path.join(dir, 'result.json'), 'utf8')).toBe(original);+ expect(await readFile(path.join(h.dir, 'result.json'), 'utf8')).toBe(original);});it('links the reported pull request to the acceptance, and survives a failed link', async () => {@@ -149,7 +73,7 @@ describe('acceptance publication with missing evidence', () => {url: 'https://github.com/lobehub/lobehub/pull/20171',};await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ evidence: ['output.txt'], id: 'screen', name: '用户能看到处理结果', status: 'passed' },@@ -162,7 +86,7 @@ describe('acceptance publication with missing evidence', () => {);client.acceptance.linkPullRequest.mutate.mockRejectedValue(new Error('CONFLICT'));- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(client.acceptance.linkPullRequest.mutate).toHaveBeenCalledExactlyOnceWith({id: 'acceptance-1',@@ -177,7 +101,7 @@ describe('acceptance publication with missing evidence', () => {const inferred = { number: 7, url: 'https://github.com/lobehub/lobehub/pull/7' };vi.mocked(pullRequestFromBranch).mockReturnValue(inferred);await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({branch: 'canary',cases: [@@ -189,7 +113,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(pullRequestFromBranch).toHaveBeenCalledWith('canary');expect(result()).toMatchObject({ pullRequest: inferred });@@ -200,7 +124,7 @@ describe('acceptance publication with missing evidence', () => {vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));await report(['text'], ['output.txt', "screen's shot.png"]);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(process.exitCode).toBe(1);expect(result()).toMatchObject({ missingEvidence: [], publicationStatus: 'partial' });@@ -209,11 +133,11 @@ describe('acceptance publication with missing evidence', () => {});it('counts only attached evidence, but accepts another successful file of the same required type', async () => {- await writeFile(path.join(dir, 'second.png'), 'another image');+ await writeFile(path.join(h.dir, 'second.png'), 'another image');vi.mocked(uploadLocalFile).mockRejectedValueOnce(new Error('storage_block:upgrade_required'));await report(['screenshot'], ["screen's shot.png", 'second.png']);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({evidence: 1,@@ -228,7 +152,7 @@ describe('acceptance publication with missing evidence', () => {async (verdict) => {await report(['screenshot'], ['missing.png'], verdict);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result().failedEvidence[0].reason).toBe('file_missing');expect(finalCheck().verdict).toBe(verdict);@@ -240,7 +164,7 @@ describe('acceptance publication with missing evidence', () => {it('reports missing required evidence even when no upload was attempted', async () => {await report(['screenshot'], []);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({failedEvidence: [],@@ -255,13 +179,13 @@ describe('acceptance publication with missing evidence', () => {vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));await report(['screenshot'], ["screen's shot.png"]);- await run('ingest', dir);+ await run('ingest', h.dir);- expect(printed.join('\n')).toContain('Partially published');- expect(printed.join('\n')).toContain('https://app.lobehub.com/acceptance/acceptance-1?r=2');- expect(printed.join('\n')).toContain('evidence upload');- expect(printed.join('\n')).toContain('POSIX shell');- expect(printed.join('\n')).toContain('retryArgs');+ expect(h.printed.join('\n')).toContain('Partially published');+ expect(h.printed.join('\n')).toContain('https://app.lobehub.com/acceptance/acceptance-1?r=2');+ expect(h.printed.join('\n')).toContain('evidence upload');+ expect(h.printed.join('\n')).toContain('POSIX shell');+ expect(h.printed.join('\n')).toContain('retryArgs');expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('https://lobehub.com/acceptance'),);@@ -281,7 +205,7 @@ describe('acceptance publication with missing evidence', () => {vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));await report(['screenshot'], ["screen's shot.png"]);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result().recovery).toMatchObject({cleanupUrl: 'https://lobe.example.test:8443/acceptance',@@ -301,7 +225,7 @@ describe('acceptance publication with missing evidence', () => {if (error) vi.mocked(uploadLocalFile).mockRejectedValue(new Error(error));await report(['screenshot'], ["screen's shot.png"]);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).not.toHaveProperty('recovery');expect(result().publicationStatus).toBe(error ? 'partial' : 'complete');@@ -315,13 +239,13 @@ describe('acceptance publication with missing evidence', () => {await report(['screenshot'], ["screen's shot.png"]);const args =command === 'ingest'- ? ['ingest', dir]+ ? ['ingest', h.dir]: [...(command === 'evidence'? ['evidence', 'upload', '--check', 'result-screen']: ['result', 'submit', '--run', 'run-1', '--item', 'screen']),'--file',- path.join(dir, "screen's shot.png"),+ path.join(h.dir, "screen's shot.png"),'--type','screenshot','--desc',@@ -427,7 +351,7 @@ describe('acceptance publication with missing evidence', () => {await run(...command,'--file',- path.join(dir, "screen's shot.png"),+ path.join(h.dir, "screen's shot.png"),'--type','screenshot','--desc',@@ -448,7 +372,7 @@ describe('acceptance publication with missing evidence', () => {expect(JSON.stringify(vi.mocked(log.warn).mock.calls)).not.toMatch(/quota-user|quota%40password|quota@password/,);- expect(printed.join('\n')).not.toMatch(/quota-user|quota%40password|quota@password/);+ expect(h.printed.join('\n')).not.toMatch(/quota-user|quota%40password|quota@password/);if (json) {expect(result()).toMatchObject({error: 'storage_block:upgrade_required',@@ -470,7 +394,7 @@ describe('acceptance publication with missing evidence', () => {run(...command,'--file',- path.join(dir, "screen's shot.png"),+ path.join(h.dir, "screen's shot.png"),'--type','screenshot','--desc',@@ -479,7 +403,7 @@ describe('acceptance publication with missing evidence', () => {),).rejects.toBe(error);- expect(printed).toEqual([]);+ expect(h.printed).toEqual([]);expect(log.warn).not.toHaveBeenCalled();});});@@ -488,7 +412,7 @@ describe('acceptance publication with missing evidence', () => {'accounts for an unexecuted check alongside a %s case',async (verdict) => {await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ id: 'response', name: '收到回复', status: verdict, evidence: ['output.txt'] }],plan: [@@ -503,7 +427,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({cases: 1,@@ -526,7 +450,7 @@ describe('acceptance publication with missing evidence', () => {it('keeps an entirely unexecuted required-evidence plan uncertain', async () => {await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [],plan: [{ id: 'screen', title: '画面展示', requiredEvidence: ['screenshot'] }],@@ -534,7 +458,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({ publicationStatus: 'partial', unexecuted: ['screen'] });expect(finalReport()).toMatchObject({@@ -554,7 +478,7 @@ describe('acceptance publication with missing evidence', () => {unresolvedSupersedes: ['typo-id'],});await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ evidence: ['output.txt'], id: 'response', name: '收到回复', status: 'passed' }],plan: [{ id: 'response', supersedes: ['typo-id'], title: '收到回复' }],@@ -562,7 +486,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({ unresolvedSupersedes: ['typo-id'] });expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('typo-id'));@@ -570,7 +494,7 @@ describe('acceptance publication with missing evidence', () => {it('reports no unresolved supersedes when an older server omits the field', async () => {await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ evidence: ['output.txt'], id: 'response', name: '收到回复', status: 'passed' }],plan: [{ id: 'response', title: '收到回复' }],@@ -578,7 +502,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({ unresolvedSupersedes: [] });});@@ -600,7 +524,7 @@ describe('acceptance publication with missing evidence', () => {roundIndex: 1,});await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ evidence: ['output.txt'], id: 'draft-response', name: '草稿回复', status: 'passed' },@@ -611,7 +535,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({cases: 2,@@ -647,7 +571,7 @@ describe('acceptance publication with missing evidence', () => {});await report(['text'], hasScreenshot ? ["screen's shot.png"] : ['output.txt']);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({missingEvidence: hasScreenshot ? [] : [{ checkItemId: 'screen', types: ['screenshot'] }],@@ -672,7 +596,7 @@ describe('acceptance publication with missing evidence', () => {it('exposes shell-independent upload arguments without escaping path or description', async () => {const description = `User's "input" $HOME %TEMP% & | \`literal\``;await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{@@ -686,7 +610,7 @@ describe('acceptance publication with missing evidence', () => {}),);vi.mocked(uploadLocalFile).mockRejectedValueOnce(new Error('storage_block:upgrade_required'));- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');const failure = result().failedEvidence[0];expect(failure.retryCommandShell).toBe('posix');expect(failure.retryArgs).toEqual([@@ -699,7 +623,7 @@ describe('acceptance publication with missing evidence', () => {'--type','screenshot','--file',- path.join(dir, "screen's shot.png"),+ path.join(h.dir, "screen's shot.png"),'--desc',description,]);@@ -710,13 +634,13 @@ describe('acceptance publication with missing evidence', () => {expect(client.verify.uploadEvidence.mutate).toHaveBeenCalledWith(expect.objectContaining({ description, fileId: 'file-1' }),);- expect(uploadLocalFile).toHaveBeenLastCalledWith(client, path.join(dir, "screen's shot.png"));+ expect(uploadLocalFile).toHaveBeenLastCalledWith(client, path.join(h.dir, "screen's shot.png"));});it('finishes a complete publication with no failure exit code', async () => {await report(['screenshot', 'text'], ["screen's shot.png", 'output.txt']);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(result()).toMatchObject({evidence: 2,@@ -735,7 +659,7 @@ describe('acceptance publication with missing evidence', () => {{ kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },];await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{@@ -750,7 +674,7 @@ describe('acceptance publication with missing evidence', () => {],}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(client.verify.uploadEvidence.mutate).toHaveBeenCalledWith(expect.objectContaining({ metadata: { chapters }, type: 'video' }),@@ -761,7 +685,7 @@ describe('acceptance publication with missing evidence', () => {const description = "Before: user's input $(printf should-not-expand)";const comparison = { id: 'input', role: 'before' };await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{@@ -777,7 +701,7 @@ describe('acceptance publication with missing evidence', () => {}),);client.verify.uploadEvidence.mutate.mockRejectedValueOnce(new Error('attachment unavailable'));- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');const failure = result().failedEvidence[0];expect(failure).toMatchObject({ fileId: 'file-1', reason: 'upload_failed' });expect(failure.retryArgs).toEqual([@@ -826,7 +750,7 @@ describe('acceptance publication with missing evidence', () => {it('recounts mixed checks without converting an observed failure into uncertainty', async () => {vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));await writeFile(- path.join(dir, 'result.json'),+ path.join(h.dir, 'result.json'),JSON.stringify({cases: [{ evidence: ["screen's shot.png"], id: 'screen', name: '画面展示', status: 'passed' },@@ -838,7 +762,7 @@ describe('acceptance publication with missing evidence', () => {}),);- await run('ingest', dir, '--json');+ await run('ingest', h.dir, '--json');expect(finalReport()).toMatchObject({failedChecks: 1,@@ -848,153 +772,4 @@ describe('acceptance publication with missing evidence', () => {verdict: 'failed',});});-- describe('report language', () => {- const englishReport = async () => {- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [{ id: 'screen', name: '用户能看到处理结果', observation: 'The page shows it.' }],- plan: [{ expected: '页面显示结果', id: 'screen', title: '用户能看到处理结果' }],- summary: { conclusion: '通过', verdict: 'passed' },- title: '处理结果展示',- }),- );- await writeFile(path.join(dir, 'report.md'), 'All checks passed.');- };-- it('rejects a report in the wrong language before any remote write', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });- await englishReport();-- const error = await run('ingest', dir).catch((e: unknown) => e);-- expect(String(error)).toContain('responseLanguage) is "zh-CN"');- expect(String(error)).toContain('cases[screen].observation');- expect(String(error)).toContain('report.md');- expect(String(error)).not.toContain('plan[screen].title');- expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(client.verify.createRun.mutate).not.toHaveBeenCalled();- });-- it('validates a plan-only report with --dry-run without publishing', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- plan: [{ id: 'screen', method: 'Open the page', title: '用户能看到处理结果' }],- title: '处理结果展示',- }),- );-- await expect(run('ingest', dir, '--dry-run')).rejects.toThrow('plan[screen].method');-- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- plan: [{ id: 'screen', method: '打开页面', title: '用户能看到处理结果' }],- title: '处理结果展示',- }),- );- await run('ingest', dir, '--dry-run', '--json');-- expect(result()).toMatchObject({- dryRun: true,- language: { enforced: true, locale: 'zh-CN', status: 'enforced' },- planItems: 1,- });- expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(client.verify.createRun.mutate).not.toHaveBeenCalled();- });-- it('rejects an English category, which renders as the checklist group heading', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- plan: [{ category: 'Task hierarchy', id: 'screen', title: '用户能看到处理结果' }],- title: '处理结果展示',- }),- );-- await expect(run('ingest', dir, '--dry-run')).rejects.toThrow('plan[screen].category');- });-- it('rejects an English required-evidence hint, shown as the evidence tooltip', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });- await writeFile(- path.join(dir, 'result.json'),- JSON.stringify({- plan: [- {- id: 'screen',- requiredEvidence: [{ hint: 'Capture checkout result', type: 'screenshot' }],- title: '用户能看到处理结果',- },- ],- title: '处理结果展示',- }),- );-- await expect(run('ingest', dir, '--dry-run')).rejects.toThrow(- 'plan[screen].requiredEvidence[0].hint',- );- });-- it('rejects English captions in `evidence upload --metadata` before uploading', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });-- await expect(- run(- 'evidence',- 'upload',- '--check',- 'result-screen',- '--content',- '日志',- '--type',- 'text',- '--desc',- '执行记录',- '--metadata',- JSON.stringify({- chapters: [{ kind: 'step', label: 'Open checkout', t: 0 }],- comparison: { id: 'pair', label: '重试前', role: 'before' },- }),- ),- ).rejects.toThrow('--metadata.chapters[0].label');- expect(client.verify.uploadEvidence.mutate).not.toHaveBeenCalled();- });-- it('rejects `run create` with a title in the wrong language', async () => {- client.user.getUserState.query.mockResolvedValue({- settings: { general: { responseLanguage: 'zh-CN' } },- });-- await expect(- run('create', '--title', 'Checkout recovery', '--goal', '验证重试'),- ).rejects.toThrow('--title');- expect(client.verify.createRun.mutate).not.toHaveBeenCalled();- });-- it('warns and still publishes when the account has no response language', async () => {- client.user.getUserState.query.mockResolvedValue({ settings: { general: {} } });- await englishReport();-- await run('ingest', dir, '--json');-- expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('no response language set'));- expect(client.verify.createRun.mutate).toHaveBeenCalledOnce();- });- });});diff --git a/apps/cli/src/commands/acceptance/run/index.tree.test.ts b/apps/cli/src/commands/acceptance/run/index.tree.test.tsnew file mode 100644index 00000000000..9d9ca592d55--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/index.tree.test.ts@@ -0,0 +1,144 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerAcceptanceCommands } from '..';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),+ },+ },+ verify: {+ createRubric: { mutate: vi.fn() },+ deleteRun: { mutate: vi.fn() },+ getRubric: { query: vi.fn() },+ updateRubric: { mutate: vi.fn() },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../../../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++describe('lh acceptance — canonical run tree', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ (mockTrpcClient.verify as Record<string, any>).submitCheckEvidence = {+ mutate: vi.fn().mockResolvedValue({+ checkResult: { id: 'result_1', verifyRunId: 'run_1' },+ evidence: [{ id: 'evidence_1' }],+ }),+ };+ });+ afterEach(() => consoleSpy.mockRestore());++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ // First-class `lh acceptance …` — the run subtree only hangs off this,+ // never off the deprecated `lh verify acceptance` alias.+ registerAcceptanceCommands(program);+ await program.parseAsync(['node', 'lh', 'acceptance', ...args]);+ };++ it('routes `acceptance run delete` to the same deleteRun mutation', async () => {+ mockTrpcClient.verify.deleteRun.mutate.mockReset().mockResolvedValue({ id: 'run_1' });+ await run(['run', 'delete', 'run_1', '--yes']);+ expect(mockTrpcClient.verify.deleteRun.mutate).toHaveBeenCalledWith({ verifyRunId: 'run_1' });+ });++ it('prints the acceptance link, never a /verify link, after submitting evidence', async () => {+ mockTrpcClient.verify.getRun = {+ query: vi.fn().mockResolvedValue({ acceptanceId: 'acc_1', id: 'run_1', roundIndex: 2 }),+ };+ await run([+ 'run',+ 'result',+ 'submit',+ '--operation',+ 'op_1',+ '--item',+ 'check_1',+ '--type',+ 'text',+ '--content',+ 'passed',+ ]);++ const lines = consoleSpy.mock.calls.map((call) => String(call[0]));+ expect(lines).toContain('acceptance: https://app.lobehub.com/acceptance/acc_1');+ expect(lines.some((line) => line.includes('/verify/'))).toBe(false);+ });++ it('reports no link for a round outside any acceptance', async () => {+ mockTrpcClient.verify.getRun = {+ query: vi.fn().mockResolvedValue({ acceptanceId: null, id: 'run_1', roundIndex: null }),+ };+ await run([+ 'run',+ 'result',+ 'submit',+ '--operation',+ 'op_1',+ '--item',+ 'check_1',+ '--type',+ 'text',+ '--content',+ 'passed',+ '--json',+ ]);++ const output = JSON.parse(consoleSpy.mock.calls.map((call) => String(call[0])).join(''));+ expect(output).toMatchObject({ acceptanceUrl: null, roundIndex: null });+ expect(output).not.toHaveProperty('url');+ });++ it('includes the acceptance URL in JSON output', async () => {+ mockTrpcClient.verify.getRun = {+ query: vi.fn().mockResolvedValue({ acceptanceId: 'acc_1', id: 'run_1', roundIndex: 2 }),+ };+ await run([+ 'run',+ 'result',+ 'submit',+ '--operation',+ 'op_1',+ '--item',+ 'check_1',+ '--type',+ 'text',+ '--content',+ 'passed',+ '--json',+ ]);++ const output = JSON.parse(consoleSpy.mock.calls.map((call) => String(call[0])).join(''));+ expect(output).toMatchObject({+ acceptanceUrl: 'https://app.lobehub.com/acceptance/acc_1',+ roundIndex: 2,+ });+ expect(output).not.toHaveProperty('url');+ });++ it('does NOT attach the run subtree to the deprecated `verify acceptance` alias', async () => {+ const program = new Command();+ program.exitOverride();+ registerAcceptanceCommands(program, { deprecated: true });+ const acceptance = program.commands.find((c) => c.name() === 'acceptance');+ const hasRun = acceptance?.commands.some((c) => c.name() === 'run');+ expect(hasRun).toBe(false);+ });+});diff --git a/apps/cli/src/commands/acceptance/run/index.ts b/apps/cli/src/commands/acceptance/run/index.tsnew file mode 100644index 00000000000..559d9a86f12--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/index.ts@@ -0,0 +1,143 @@+import type { Command } from 'commander';++import { createPublicLambdaClient } from '../../../api/client';+import { installAction, type InstallOptions, withInstallOptions } from '../install';+import { DECISIONS } from '../utils';+import {+ evidenceDeleteAction,+ evidenceListAction,+ evidenceUploadAction,+ withEvidenceUploadOptions,+} from './evidence';+import { ingestReportAction, withIngestReportOptions } from './ingest';+import { reportGetAction, reportUpsertAction, withReportUpsertOptions } from './report';+import {+ decisionAction,+ resultIngestAction,+ resultListAction,+ submitAction,+ withResultIngestOptions,+ withResultListOptions,+ withSubmitOptions,+} from './result';+import {+ runCreateAction,+ runDeleteAction,+ runGetAction,+ runListAction,+ withRunCreateOptions,+ withRunDeleteOptions,+} from './session';++// ── Actions ────────────────────────────────────────────────+//+// One implementation per command, shared by the canonical `lh acceptance run …`+// tree and the deprecated `lh verify …` aliases. Both wire the same function, so+// the two spellings never drift while the aliases live out their deprecation.++// ── Canonical tree: `lh acceptance install` + `lh acceptance run …` ──++/**+ * The run-scoped acceptance commands. A run is one immutable round of a+ * subject's acceptance; its results, evidence, and report are its sub-resources.+ * Attached to the first-class `lh acceptance` command.+ */+export function attachAcceptanceRunCommands(acceptance: Command): void {+ withInstallOptions(+ acceptance+ .command('install')+ .description('Install the latest acceptance skill source into .agents/skills/acceptance'),+ ).action((options: InstallOptions) => installAction(options, createPublicLambdaClient()));++ withInstallOptions(+ acceptance+ .command('update')+ .description('Download the latest skill source, replacing its files and re-wiring harnesses'),+ ).action((options: InstallOptions) =>+ installAction({ ...options, force: true }, createPublicLambdaClient()),+ );++ const run = acceptance+ .command('run')+ .description('Acceptance rounds (immutable verification snapshots)');++ withIngestReportOptions(+ run+ .command('ingest <reportDir>')+ .description(+ 'Ingest a local agent-testing report (result.json + report.md + proposal.md + assets) as a new round',+ ),+ ).action(ingestReportAction);++ withRunCreateOptions(+ run.command('create').description('Create a standalone round (verification session)'),+ ).action(runCreateAction);++ run+ .command('list')+ .description('List recent rounds')+ .option('--json [fields]', 'Output JSON')+ .action(runListAction);++ run+ .command('get <runId>')+ .description('Show a round')+ .option('--json [fields]', 'Output JSON')+ .action(runGetAction);++ withRunDeleteOptions(+ run+ .command('delete <runId>')+ .description('Delete a round (cascades its results, evidence and report)'),+ ).action(runDeleteAction);++ const result = run.command('result').description('Check results within a round');+ withResultIngestOptions(+ result+ .command('ingest')+ .description('Upsert one check result by (run, checkItemId) from a supplied verdict'),+ ).action(resultIngestAction);+ withResultListOptions(+ result+ .command('list')+ .description('List check results — by round (--run) or by Agent Run (--operation)'),+ ).action(resultListAction);+ withSubmitOptions(+ result+ .command('submit')+ .description('Submit a check item — upsert its result and attach evidence in one call'),+ ).action(submitAction);+ result+ .command('decision <resultId> <decision>')+ .description(`Record human feedback on a result (${DECISIONS.join('|')})`)+ .action(decisionAction);++ const evidence = run.command('evidence').description('Evidence artifacts within a round');+ withEvidenceUploadOptions(+ evidence+ .command('upload')+ .description('Attach an evidence artifact (file or inline text) to a check result'),+ ).action(evidenceUploadAction);+ evidence+ .command('list <checkResultId>')+ .description('List evidence for a check result')+ .option('--json [fields]', 'Output JSON')+ .action(evidenceListAction);+ evidence+ .command('delete <evidenceId>')+ .description('Delete an evidence artifact')+ .option('--json [fields]', 'Output JSON')+ .action(evidenceDeleteAction);++ const report = run.command('report').description('The narrative report of a round');+ withReportUpsertOptions(+ report.command('upsert').description('Write (overwrite) the report for a round'),+ ).action(reportUpsertAction);+ report+ .command('get <runId>')+ .description('Show the report for a round')+ .option('--json [fields]', 'Output JSON')+ .action(reportGetAction);+}++export { attachDeprecatedVerifyRunAliases } from './deprecatedAliases';diff --git a/apps/cli/src/commands/acceptance/run/ingest.language.test.ts b/apps/cli/src/commands/acceptance/run/ingest.language.test.tsnew file mode 100644index 00000000000..94b8c25919c--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/ingest.language.test.ts@@ -0,0 +1,206 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';++import { describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import type * as VerifyHelpers from '../utils';+import { usePublicationHarness } from './testUtils';++vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));+vi.mock('../../../settings', () => ({ resolveServerUrl: vi.fn() }));+vi.mock('../../../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));+vi.mock('../utils', async (importOriginal) => ({+ ...(await importOriginal<typeof VerifyHelpers>()),+ pullRequestFromBranch: vi.fn(),+}));++describe('lh acceptance run', () => {+ const h = usePublicationHarness();+ const { client, result, run } = h;++ describe('report language', () => {+ const englishReport = async () => {+ await writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ cases: [{ id: 'screen', name: '用户能看到处理结果', observation: 'The page shows it.' }],+ plan: [{ expected: '页面显示结果', id: 'screen', title: '用户能看到处理结果' }],+ summary: { conclusion: '通过', verdict: 'passed' },+ title: '处理结果展示',+ }),+ );+ await writeFile(path.join(h.dir, 'report.md'), 'All checks passed.');+ };++ it('rejects a report in the wrong language before any remote write', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await englishReport();++ const error = await run('ingest', h.dir).catch((e: unknown) => e);++ expect(String(error)).toContain('responseLanguage) is "zh-CN"');+ expect(String(error)).toContain('cases[screen].observation');+ expect(String(error)).toContain('report.md');+ expect(String(error)).not.toContain('plan[screen].title');+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('validates a plan-only report with --dry-run without publishing', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ plan: [{ id: 'screen', method: 'Open the page', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', h.dir, '--dry-run')).rejects.toThrow('plan[screen].method');++ await writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ plan: [{ id: 'screen', method: '打开页面', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );+ await run('ingest', h.dir, '--dry-run', '--json');++ expect(result()).toMatchObject({+ dryRun: true,+ language: { enforced: true, locale: 'zh-CN', status: 'enforced' },+ planItems: 1,+ });+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('rejects an English category, which renders as the checklist group heading', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ plan: [{ category: 'Task hierarchy', id: 'screen', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', h.dir, '--dry-run')).rejects.toThrow('plan[screen].category');+ });++ it('rejects an English required-evidence hint, shown as the evidence tooltip', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ plan: [+ {+ id: 'screen',+ requiredEvidence: [{ hint: 'Capture checkout result', type: 'screenshot' }],+ title: '用户能看到处理结果',+ },+ ],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', h.dir, '--dry-run')).rejects.toThrow(+ 'plan[screen].requiredEvidence[0].hint',+ );+ });++ it('rejects English captions in `evidence upload --metadata` before uploading', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });++ await expect(+ run(+ 'evidence',+ 'upload',+ '--check',+ 'result-screen',+ '--content',+ '日志',+ '--type',+ 'text',+ '--desc',+ '执行记录',+ '--metadata',+ JSON.stringify({+ chapters: [{ kind: 'step', label: 'Open checkout', t: 0 }],+ comparison: { id: 'pair', label: '重试前', role: 'before' },+ }),+ ),+ ).rejects.toThrow('--metadata.chapters[0].label');+ expect(client.verify.uploadEvidence.mutate).not.toHaveBeenCalled();+ });++ it('rejects English chapter captions in `result submit --chapters` before uploading', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(h.dir, 'chapters.json'),+ JSON.stringify([+ { kind: 'step', label: '刷新页面', t: 0 },+ { kind: 'check', note: 'Device chip shows on the first frame', t: 1.5 },+ ]),+ );++ await expect(+ run(+ 'result',+ 'submit',+ '--operation',+ 'op-1',+ '--item',+ 'reload',+ '--file',+ path.join(h.dir, 'scroll.mp4'),+ '--type',+ 'video',+ '--desc',+ '刷新后的录屏',+ '--chapters',+ path.join(h.dir, 'chapters.json'),+ ),+ ).rejects.toThrow('--chapters.chapters[1].note');+ expect(uploadLocalFile).not.toHaveBeenCalled();+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ });++ it('rejects `run create` with a title in the wrong language', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });++ await expect(+ run('create', '--title', 'Checkout recovery', '--goal', '验证重试'),+ ).rejects.toThrow('--title');+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('warns and still publishes when the account has no response language', async () => {+ client.user.getUserState.query.mockResolvedValue({ settings: { general: {} } });+ await englishReport();++ await run('ingest', h.dir, '--json');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('no response language set'));+ expect(client.verify.createRun.mutate).toHaveBeenCalledOnce();+ });+ });+});diff --git a/apps/cli/src/commands/acceptance/run/ingest.test.ts b/apps/cli/src/commands/acceptance/run/ingest.test.tsnew file mode 100644index 00000000000..cff4d77e563--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/ingest.test.ts@@ -0,0 +1,586 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import { registerVerifyCommand } from '../deprecatedVerify';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),+ },+ },+ verify: {+ createRubric: { mutate: vi.fn() },+ deleteRun: { mutate: vi.fn() },+ getRubric: { query: vi.fn() },+ updateRubric: { mutate: vi.fn() },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../../../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));++describe('verify ingest-report — every run is an immutable acceptance round', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let dir: string;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ const verify = mockTrpcClient.verify as Record<string, any>;+ verify.createRun = { mutate: vi.fn().mockResolvedValue({ id: 'run-new' }) };+ verify.updateRun = { mutate: vi.fn() };+ verify.upsertReport = { mutate: vi.fn().mockResolvedValue({}) };+ mockTrpcClient.acceptance = {+ attachRun: { mutate: vi.fn() },+ ensure: { mutate: vi.fn().mockResolvedValue({ id: 'acceptance-1' }) },+ getBundle: { query: vi.fn().mockResolvedValue({}) },+ };+ mockTrpcClient.workspace = {+ getById: { query: vi.fn().mockResolvedValue({ id: 'workspace-1' }) },+ };++ dir = mkdtempSync(path.join(tmpdir(), 'lh-ingest-'));+ writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ cases: [] }));+ process.env.LOBEHUB_TOPIC_ID = 'topic-1';+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ vi.unstubAllEnvs();+ delete process.env.LOBEHUB_TOPIC_ID;+ rmSync(dir, { force: true, recursive: true });+ });++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerVerifyCommand(program);+ await program.parseAsync(['node', 'lh', 'verify', ...args]);+ };++ it('keeps position-based fallback ids stable when screening drops an earlier case', async () => {+ // Regression (codex review): the survivors used to be re-enumerated after+ // the programmatic-test screen, so dropping an id-less first case shifted+ // every later fallback id (`case-2` ingested as `case-1`) — orphaning the+ // results from their plan items in the immutable round.+ const verify = mockTrpcClient.verify as Record<string, any>;+ verify.ingestResult = { mutate: vi.fn().mockResolvedValue({ id: 'result-1' }) };+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [+ { name: '单元测试全部通过', status: 'pass' },+ { name: '回复在气泡中渲染', status: 'pass' },+ { name: '失败态可重试', status: 'pass' },+ ],+ plan: [+ { id: 'case-2', title: '回复在气泡中渲染' },+ { id: 'case-3', title: '失败态可重试' },+ ],+ title: 'fallback id screening',+ }),+ );++ await run(['ingest-report', dir, '--json']);++ const ingested = verify.ingestResult.mutate.mock.calls.map(+ ([input]: [{ checkItemId: string }]) => input.checkItemId,+ );+ expect(ingested).toEqual(['case-2', 'case-3']);+ });++ it('creates a fresh run and binds it to the current topic acceptance', async () => {+ const verify = mockTrpcClient.verify as Record<string, any>;++ await run(['ingest-report', dir, '--json']);++ expect(verify.updateRun.mutate).not.toHaveBeenCalled();+ expect(verify.createRun.mutate).toHaveBeenCalled();+ // The ambient topic may be folded onto its Task by the server.+ expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({+ foldTaskRunTopic: true,+ requirement: undefined,+ subjectId: 'topic-1',+ subjectType: 'topic',+ });+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({+ acceptanceId: 'acceptance-1',+ verifyRunId: 'run-new',+ });+ });++ it('keeps an explicit topic subject exact instead of folding it onto a Task', async () => {+ await run(['ingest-report', dir, '--subject', 'topic:topic-explicit', '--json']);++ expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({+ requirement: undefined,+ subjectId: 'topic-explicit',+ subjectType: 'topic',+ });+ });++ it('creates a standalone acceptance when an external project has no operation or subject', async () => {+ delete process.env.LOBEHUB_TOPIC_ID;+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({ cases: [], title: 'External delivery verification' }),+ );++ await run(['ingest-report', dir, '--json']);++ expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({+ requirement: undefined,+ subjectId: expect.stringMatching(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ ),+ subjectType: 'standalone',+ title: 'External delivery verification',+ });+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({+ acceptanceId: 'acceptance-1',+ verifyRunId: 'run-new',+ });+ });++ it('reuses the asset when the acceptance row is keyed by criterion rather than plan item', async () => {+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ acceptance: {+ id: 'acceptance-existing',+ status: 'delivered',+ subjectId: 'subject',+ subjectType: 'standalone',+ },+ checks: [+ { id: 'criterion-1', planItem: { id: 'stable-check', sourceCriterionId: 'criterion-1' } },+ ],+ });+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ id: 'stable-check', name: '输入区域可用', status: 'pass' }],+ plan: [+ {+ id: 'stable-check',+ title: '输入区域可用',+ verifier: 'agent',+ method: '打开输入区域',+ expected: '可以输入',+ },+ ],+ }),+ );+ await run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']);+ expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ plan: [expect.objectContaining({ id: 'stable-check', sourceCriterionId: 'criterion-1' })],+ }),+ );+ });++ it('reuses criteria when the round reaches its acceptance through the subject', async () => {+ // Regression: only `--acceptance` read the existing checks, so re-ingesting+ // a topic's report minted fresh criteria and duplicated every check row.+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ checks: [{ id: 'criterion-1', planItem: { id: '1', sourceCriterionId: 'criterion-1' } }],+ });+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ id: '1', name: '标题可编辑', status: 'pass' }],+ plan: [{ id: '1', title: '标题可编辑' }],+ }),+ );++ await run(['ingest-report', dir, '--json']);++ expect(mockTrpcClient.acceptance.getBundle.query).toHaveBeenCalledWith({ id: 'acceptance-1' });+ expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ plan: [expect.objectContaining({ id: '1', sourceCriterionId: 'criterion-1' })],+ }),+ );+ });++ describe('identical re-ingest', () => {+ const publishedRound = (content: string) => ({+ report: { content, summary: '全部通过' },+ run: { id: 'run-r1', plan: [{ id: '1', title: '标题可编辑' }], roundIndex: 1 },+ });++ beforeEach(() => {+ (mockTrpcClient.verify as Record<string, any>).ingestResult = {+ mutate: vi.fn().mockResolvedValue({ id: 'result-1' }),+ };+ writeFileSync(path.join(dir, 'report.md'), '## 备注\n\n首次发布');+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ id: '1', name: '标题可编辑', status: 'pass' }],+ plan: [{ id: '1', title: '标题可编辑' }],+ summary: { conclusion: '全部通过', failed: 0, passed: 1, total: 1 },+ }),+ );+ });++ it('refuses to stack a round identical to the latest one', async () => {+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ rounds: [publishedRound('## 备注\n\n首次发布')],+ });+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`process.exit ${code}`);+ }) as never);++ try {+ await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow('process.exit 1');+ expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();+ } finally {+ exitSpy.mockRestore();+ }+ });++ it('publishes the next round once the report actually changed', async () => {+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ rounds: [publishedRound('## 备注\n\n上一轮的报告')],+ });++ await run(['ingest-report', dir, '--json']);++ expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalled();+ });+ });++ it.each([null, 'workspace-1'])(+ 'appends a re-verification round when both scopes are %s',+ async (workspaceId) => {+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', workspaceId ?? '');+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ acceptance: {+ id: 'acceptance-existing',+ status: 'delivered',+ subjectId: 'standalone-subject',+ subjectType: 'standalone',+ workspaceId,+ },+ });++ await run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']);++ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({+ acceptanceId: 'acceptance-existing',+ verifyRunId: 'run-new',+ });+ expect(mockTrpcClient.verify.upsertReport.mutate).toHaveBeenCalled();+ expect(process.env.LOBEHUB_WORKSPACE_ID).toBe(workspaceId ?? '');+ if (!workspaceId) expect(mockTrpcClient.workspace.getById.query).not.toHaveBeenCalled();+ },+ );++ it.each([+ { effectiveWorkspace: null, name: 'revoked workspace membership' },+ { effectiveWorkspace: { id: 'workspace-other' }, name: 'a different server workspace' },+ { effectiveWorkspace: new Error('Workspace lookup unavailable'), name: 'a failed lookup' },+ ])('rejects $name before creating a run', async ({ effectiveWorkspace }) => {+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', 'workspace-1');+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ acceptance: {+ id: 'acceptance-existing',+ status: 'delivered',+ subjectId: 'standalone-subject',+ subjectType: 'standalone',+ workspaceId: 'workspace-1',+ },+ });+ const query = mockTrpcClient.workspace.getById.query;+ if (effectiveWorkspace instanceof Error) query.mockRejectedValue(effectiveWorkspace);+ else query.mockResolvedValue(effectiveWorkspace);++ await expect(+ run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']),+ ).rejects.toThrow(+ effectiveWorkspace instanceof Error ? effectiveWorkspace.message : 'No run was created.',+ );++ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.verify.upsertReport.mutate).not.toHaveBeenCalled();+ expect(process.env.LOBEHUB_WORKSPACE_ID).toBe('workspace-1');+ });++ it.each([+ { current: '', hint: 'LOBEHUB_WORKSPACE_ID=workspace-target', target: 'workspace-target' },+ {+ current: 'workspace-current',+ hint: 'LOBEHUB_WORKSPACE_ID=workspace-target',+ target: 'workspace-target',+ },+ { current: 'workspace-current', hint: 'lh workspace use --personal', target: null },+ ])(+ 'rejects scope $current → $target before any remote writes',+ async ({ current, target, hint }) => {+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', current);+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({+ acceptance: {+ id: 'acceptance-existing',+ status: 'delivered',+ subjectId: 'standalone-subject',+ subjectType: 'standalone',+ workspaceId: target,+ },+ });++ await expect(+ run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']),+ ).rejects.toThrow(hint);++ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.verify.upsertReport.mutate).not.toHaveBeenCalled();+ expect(process.env.LOBEHUB_WORKSPACE_ID).toBe(current);+ },+ );++ it('passes a non-coding scenario and its context bag through to the run', async () => {+ const verify = mockTrpcClient.verify as Record<string, any>;+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [],+ context: { question: 'How mature is X?', sourceCount: 8 },+ scenario: 'research',+ }),+ );++ await run(['ingest-report', dir, '--json']);++ expect(verify.createRun.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({ question: 'How mature is X?', sourceCount: 8 }),+ scenario: 'research',+ }),+ );+ });++ 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+ // with a ReferenceError AFTER creating the run.+ const verify = mockTrpcClient.verify as Record<string, any>;+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [],+ context: { question: 'How mature is X?' },+ scenario: 'research',+ }),+ );++ await run(['ingest-report', dir]);++ expect(verify.createRun.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ scenario: 'research' }),+ );+ // The success tail printed — the command reached past the run creation.+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('verifyRunId'));+ });++ it('rejects an unknown scenario instead of silently tagging the run coding', async () => {+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`process.exit ${code}`);+ }) as never);+ writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ cases: [], scenario: 'poetry' }));++ try {+ await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow('process.exit 1');+ expect(+ (mockTrpcClient.verify as Record<string, any>).createRun.mutate,+ ).not.toHaveBeenCalled();+ } finally {+ exitSpy.mockRestore();+ }+ });++ it('validates every visualization before creating or attaching an immutable round', async () => {+ const verify = mockTrpcClient.verify as Record<string, any>;+ writeFileSync(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [+ {+ datasets: [+ {+ fields: [{ key: 'score', type: 'number' }],+ id: 'scores',+ rows: [{ score: 1 }],+ },+ ],+ id: 'broken-chart',+ visualizations: [+ {+ dataset: 'scores',+ encoding: {},+ id: 'chart',+ type: 'bar-chart',+ version: 1,+ },+ ],+ },+ ],+ }),+ );++ await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow(+ 'case broken-chart: visualizations[0].encoding.category',+ );+ expect(verify.createRun.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();+ });++ it('creates another run when the same report directory is ingested again', async () => {+ const verify = mockTrpcClient.verify as Record<string, any>;+ verify.createRun.mutate+ .mockResolvedValueOnce({ id: 'run-first' })+ .mockResolvedValueOnce({ id: 'run-second' });++ await run(['ingest-report', dir, '--json']);+ await run(['ingest-report', dir, '--json']);++ expect(verify.createRun.mutate).toHaveBeenCalledTimes(2);+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenNthCalledWith(1, {+ acceptanceId: 'acceptance-1',+ verifyRunId: 'run-first',+ });+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenNthCalledWith(2, {+ acceptanceId: 'acceptance-1',+ verifyRunId: 'run-second',+ });+ });++ it('with --open prints only acceptance links, the round snapshot via ?r=', async () => {+ // The acceptance page is the sole user-facing link; the round's fixed+ // snapshot is the same URL with `?r=<roundIndex>` — never a /verify link.+ mockTrpcClient.acceptance.attachRun.mutate = vi.fn().mockResolvedValue({ roundIndex: 3 });++ await run(['ingest-report', dir, '--open']);++ const lines = consoleSpy.mock.calls.map((call) => String(call[0]));+ expect(lines.some((line) => line.includes('/acceptance/acceptance-1'))).toBe(true);+ expect(lines.some((line) => line.includes('/acceptance/acceptance-1?r=3'))).toBe(true);+ expect(lines.some((line) => line.includes('/verify/'))).toBe(false);+ });+});diff --git a/apps/cli/src/commands/acceptance/run/ingest.ts b/apps/cli/src/commands/acceptance/run/ingest.tsnew file mode 100644index 00000000000..6f7dd67b688--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/ingest.ts@@ -0,0 +1,708 @@+import { randomUUID } from 'node:crypto';+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';++import { acceptanceSubjectTypes } from '@lobechat/const/verify';+import type { VerifyAgentPlanConfig, VerifyCheckItem } from '@lobechat/types';+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { resolveWorkspaceId } from '../../../api/workspace';+import { resolveServerUrl } from '../../../settings';+import { ensureAcceptanceDirIgnoredFor } from '../../../utils/acceptanceDir';+import { outputJson } from '../../../utils/format';+import { log } from '../../../utils/logger';+import { assertReportLanguage, ingestLanguageFields, languageSummary } from '../language';+import {+ deriveReportVerdict,+ type EvidenceType,+ findIdenticalLatestRound,+ genericContextFromResult,+ interactionCostFromReportDir,+ metadataForReport,+ originFromEnv,+ parseSubjectRef,+ planFromResult,+ pullRequestFromBranch,+ pullRequestFromResult,+ reuseSourceCriteria,+ scenarioFromResult,+ screenProgrammaticTestChecks,+ subjectFromEnv,+ subjectFromResult,+ surfacesFromResult,+ toVerdict,+ type Verdict,+ visualizationMetadata,+} from '../utils';+import type { FailedReportEvidence } from './evidenceUpload';+import { storageQuotaRecovery, uploadReportEvidence } from './evidenceUpload';+import { ingestIntoPlanRound } from './planRound';++// ── ingest-report (aggregate convenience over the atomic commands) ──++export interface IngestReportOptions {+ acceptance?: string;+ /** Run every local check, including the report language, then stop before publishing. */+ dryRun?: boolean;+ goal?: string;+ json?: boolean | string;+ open?: boolean;+ operation?: string;+ requirement?: string;+ source?: string;+ subject?: string;+ title?: string;+}++export async function ingestReportAction(+ reportDir: string,+ options: IngestReportOptions,+): Promise<void> {+ const dir = path.resolve(reportDir);+ // The guarantee has to hold however the round got here — a project that never+ // ran `acceptance install`, or an agent that wrote the round by hand, still+ // must not leave evidence binaries untracked in someone's repo.+ ensureAcceptanceDirIgnoredFor(dir);+ const resultPath = path.join(dir, 'result.json');+ if (!existsSync(resultPath)) {+ log.error(`result.json not found in ${dir}`);+ process.exit(1);+ }++ let result: any;+ try {+ result = JSON.parse(readFileSync(resultPath, 'utf8'));+ } catch {+ log.error('result.json is not valid JSON');+ process.exit(1);+ }++ // Unit tests, type-checks and lint gates are preconditions of shipping, not+ // things a person accepts — a page full of them buries the checks that+ // actually needed a human eye. Screen them out of both the plan and the cases+ // before anything is published.+ const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result);+ const allCases: any[] = Array.isArray(result.cases) ? result.cases : [];+ // Freeze each case's id BEFORE filtering: the fallback id is position-based+ // (`case-N`), so dropping an earlier case would re-enumerate the survivors in+ // the ingest loop — pairing them with the wrong plan items and publishing+ // orphaned results into the immutable round.+ const casesWithIds = allCases.map((c, index) => ({+ case: c,+ checkItemId: String(c?.id ?? c?.checkItemId ?? `case-${index + 1}`),+ }));+ const cases = casesWithIds.filter(({ checkItemId }) => !droppedIds.has(checkItemId));+ // Every check was a gate: there is nothing here for a person to accept, and+ // publishing an empty round would just create a verdict-less page. Fail before+ // the first remote mutation, while the author can still fix the report.+ if (cases.length === 0 && allCases.length > 0) {+ log.error(+ 'every check in this round is a programmatic gate (tests / type-check / lint) — nothing here needs a human decision.',+ );+ log.error(+ ' Verify what the delivery does, shows, or produces, and keep the gates as one line of report.md.',+ );+ process.exit(1);+ }+ // Validate every schemaless visualization before the first remote mutation.+ // An ingest that cannot render must not create or attach a partial immutable round.+ const caseMetadata = cases.map(({ case: item, checkItemId }) => {+ try {+ return visualizationMetadata(item);+ } catch (error) {+ throw new Error(+ `case ${checkItemId}: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }+ });+ const summary = result.summary ?? {};+ const reportMdPath = path.join(dir, 'report.md');+ const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;++ // What this round is, said to the person who has to accept it, in their+ // language — the delivery's own note, not the verification write-up. It+ // posts into the discussion as a message from whoever ran the ingest, so a+ // reviewer reads it where the conversation already is rather than behind a+ // report link.+ const proposalMdPath = path.join(dir, 'proposal.md');+ const proposal = (+ existsSync(proposalMdPath)+ ? readFileSync(proposalMdPath, 'utf8')+ : typeof result.proposal === 'string'+ ? result.proposal+ : ''+ ).trim();++ // What kind of delivery this report verified (default: coding).+ const scenario = scenarioFromResult(result);++ // The scenario's context for the report's scope header. Coding lifts the+ // well-known top-level fields (branch / commit / surfaces / PR); every+ // other scenario passes result.json `context` through as its own bag.+ // `pullRequest` is hoisted: the success output (text and --json) prints+ // the PR link after the ingest, whatever the scenario resolved to.+ let context: Record<string, unknown> | undefined;+ let pullRequest: ReturnType<typeof pullRequestFromResult>;+ // Only a PR the report names is a delivery claim; the branch lookup below is+ // best-effort provenance and may find a long-lived branch's unrelated PR.+ let authoredPullRequest: ReturnType<typeof pullRequestFromResult>;+ if (scenario === 'coding') {+ const branch = typeof result.branch === 'string' ? result.branch : undefined;+ const surfaces = surfacesFromResult(result);+ // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the+ // report links to it without the author having to remember the field.+ authoredPullRequest = pullRequestFromResult(result);+ pullRequest = authoredPullRequest ?? pullRequestFromBranch(branch);+ const contextEntries = Object.entries({+ branch,+ commit: typeof result.commit === 'string' ? result.commit : undefined,+ entry: typeof result.entry === 'string' ? result.entry : undefined,+ pullRequest,+ surfaces,+ testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,+ }).filter(([, v]) => v !== undefined);+ context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;+ } else {+ context = genericContextFromResult(result);+ }++ // What the run set out to check, written before it ran. Paired with the+ // results by `id`, so the report can show a planned item that never ran.+ let plan: VerifyCheckItem[] | undefined = planFromResult(result, droppedIds);++ const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);+ const title = options.title ?? result.title;+ // The title is the run's identity in every list surface — an untitled+ // run renders as a placeholder forever, so say so before it ships.+ if (!title) {+ log.warn(+ 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',+ );+ }++ const requestedAcceptanceId = options.acceptance?.trim();+ if (requestedAcceptanceId && (options.subject || result.subject)) {+ log.error(+ 'Choose one acceptance target: pass --acceptance <id>, or use --subject/result.json `subject`.',+ );+ process.exit(1);+ }++ // Explicit subject input wins, then result.json, then the authoring topic.+ // An external repository has none of those, so create a first-class+ // standalone subject instead of making the caller manufacture a Task ID.+ let subject = subjectFromResult(result);+ let foldTaskRunTopic = false;+ if (!requestedAcceptanceId && options.subject) {+ const ref = parseSubjectRef(options.subject);+ if (!ref) {+ log.error(+ `--subject must be one of ${acceptanceSubjectTypes.map((t) => `${t}:<id>`).join(' | ')}`,+ );+ process.exit(1);+ }+ subject = { ref, requirement: subject?.requirement };+ } else if (!requestedAcceptanceId && result.subject && !subject) {+ log.error('result.json `subject` is malformed (expected "type:id" or {type,id})');+ process.exit(1);+ } else if (!requestedAcceptanceId && !subject) {+ const ref = subjectFromEnv();+ if (ref) subject = { ref };+ // Only the ambient topic may be folded onto its Task; an explicit subject stays exact.+ foldTaskRunTopic = Boolean(ref);+ }+ if (!requestedAcceptanceId && !subject) {+ subject = {+ ref: { subjectId: randomUUID(), subjectType: 'standalone' },+ };+ }+ const requirement = options.requirement ?? subject?.requirement;++ // The overall conclusion, rendered at the top of the report page. Read up+ // front so the duplicate check below compares what would land.+ const conclusion =+ typeof summary.conclusion === 'string'+ ? summary.conclusion+ : typeof summary.note === 'string'+ ? summary.note+ : undefined;++ const client = await getTrpcClient();+ // Before the first remote mutation: a round in the wrong language cannot be+ // fixed in place, only replaced by another immutable round.+ const language = await assertReportLanguage(+ client,+ ingestLanguageFields({+ cases,+ conclusion,+ goal,+ plan,+ proposal,+ report: content,+ requirement,+ title,+ }),+ );+ if (options.dryRun) {+ const checked =+ language.status === 'enforced'+ ? `report language ${language.locale} ✓`+ : language.status === 'unchecked'+ ? `report language ${language.locale} (not script-checked)`+ : 'report language not set';+ if (options.json !== undefined) {+ outputJson(+ {+ cases: cases.length,+ dryRun: true,+ language: languageSummary(language),+ planItems: plan?.length ?? 0,+ },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }+ console.log(+ `${pc.green('✓ Dry run passed')} — ${cases.length} case(s), ${plan?.length ?? 0} plan item(s), ${checked}. Nothing was published.`,+ );+ return;+ }+ // An Agent Run that already owns a round (a Task's plan round) publishes into+ // it: the operation id is unique per run, and a second round would be judged+ // apart from the verifier's. Only a confirmed plan marks such a round — an+ // earlier authored ingest under this operation left a run with no confirmed+ // plan, and folding a retry into it would drop the authored verdicts and report.+ const operationState = options.operation+ ? await client.verify.getVerifyState.query({ operationId: options.operation })+ : null;+ if (operationState?.verifyPlanConfirmedAt) {+ if (options.acceptance || options.subject) {+ log.error(+ `Operation ${options.operation} already has a verification round; drop --acceptance/--subject.`,+ );+ process.exit(1);+ }+ return ingestIntoPlanRound(client, {+ authoredPlan: plan,+ caseMetadata,+ cases,+ dir,+ droppedLabels,+ json: options.json,+ operationId: options.operation!,+ proposal,+ pullRequest: authoredPullRequest,+ reportContent: content,+ state: operationState,+ });+ }+ let acceptance;+ let bundle;+ if (requestedAcceptanceId) {+ bundle = await client.acceptance.getBundle.query({ id: requestedAcceptanceId });+ acceptance = bundle.acceptance;+ // ID-based reads can cross scopes, but creating a run uses the CLI's scope.+ // Reject before any writes instead of leaving an unattachable run behind.+ const currentWorkspaceId = resolveWorkspaceId();+ const targetWorkspaceId = acceptance.workspaceId ?? undefined;+ if (currentWorkspaceId !== targetWorkspaceId) {+ const current = currentWorkspaceId ? `workspace "${currentWorkspaceId}"` : 'personal space';+ const target = targetWorkspaceId ? `workspace "${targetWorkspaceId}"` : 'personal space';+ const hint = targetWorkspaceId+ ? `Set LOBEHUB_WORKSPACE_ID=${targetWorkspaceId} for this command and retry.`+ : "Unset LOBEHUB_WORKSPACE_ID and run 'lh workspace use --personal', then retry.";+ throw new Error(+ `Acceptance "${acceptance.id}" belongs to ${target}, but the CLI is using ${current}. ${hint} No run was created.`,+ );+ }+ if (targetWorkspaceId) {+ // Revoked membership can make the server fall back to personal scope+ // even when the locally selected workspace still matches the target.+ const workspace = await client.workspace.getById.query();+ if (workspace?.id !== targetWorkspaceId) {+ throw new Error(+ `The server did not resolve workspace "${targetWorkspaceId}" for this account. Check your access with 'lh workspace list' before retrying. No run was created.`,+ );+ }+ }+ subject = {+ ref: {+ subjectId: acceptance.subjectId,+ subjectType: acceptance.subjectType,+ },+ };+ } else {+ acceptance = await client.acceptance.ensure.mutate({+ requirement,+ subjectId: subject!.ref.subjectId,+ subjectType: subject!.ref.subjectType,+ ...(foldTaskRunTopic ? { foldTaskRunTopic } : {}),+ ...(subject!.ref.subjectType === 'standalone' && (title || goal)+ ? { title: title || goal }+ : {}),+ });+ // The server may fold the subject (a Task's run topic lands on the Task).+ subject = {+ ...subject!,+ ref: { subjectId: acceptance.subjectId, subjectType: acceptance.subjectType },+ };+ // A subject's acceptance may already hold rounds; this one has to line up+ // with them exactly as an explicit `--acceptance` round does.+ bundle = await client.acceptance.getBundle.query({ id: acceptance.id });+ }+ plan = reuseSourceCriteria(plan, bundle?.checks);++ const identicalRound = findIdenticalLatestRound(bundle?.rounds, {+ plan,+ report: { content, summary: conclusion },+ });+ if (identicalRound) {+ log.error(+ `This report is identical to round ${identicalRound.roundIndex ?? '?'} (${identicalRound.id}) — nothing new to publish.`,+ );+ log.error(+ ` To replace that round, delete it first: lh acceptance run delete ${identicalRound.id}`,+ );+ process.exit(1);+ }+ // The in-app conversation that ran this harness, if any (env-supplied).+ // Strictly the authoring conversation. `--operation` names the Agent Run+ // under test and is passed to `createRun` below — a different relation.+ const origin = originFromEnv();+ // 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') {+ log.error(+ `Acceptance is already ${acceptance.status}. Reopen it before publishing another round.`,+ );+ process.exit(1);+ }++ // Every ingest is an immutable verification snapshot. A repair or+ // re-verification is another round on the same acceptance, unless the+ // acceptance still holds a draft round: the server folds this run into it.+ if (operationState) {+ log.error(+ `Operation ${options.operation} already has an authored round (${operationState.verifyRunId}); a round is immutable.`,+ );+ log.error(+ ' Retry only failed evidence with its retryArgs, or publish a new round without --operation.',+ );+ process.exit(1);+ }+ const run = await client.verify.createRun.mutate({+ context,+ goal,+ metadata: newRunMetadata,+ operationId: options.operation,+ plan,+ scenario,+ source: options.source as any,+ title,+ });+ // 1c. Chain the session onto its subject's acceptance as the next round+ // BEFORE the report lands, so the report-time status rollup already+ // sees the aggregate. Results and the report go to the round the server+ // returns, which is the draft round when this run was folded into one.+ const acceptanceId = acceptance.id;+ const attached = await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: run.id });+ // Folding preserves the draft's checks and their evidence requirements.+ plan = attached?.plan ?? plan;+ const runId = attached?.id ?? run.id;+ if (runId !== run.id)+ console.log(pc.dim(`Folded into the acceptance's draft round ${attached.roundIndex ?? ''}`));+ // The chained round's index — `?r=<roundIndex>` on the acceptance URL+ // deep-links this round's report as the fixed snapshot view.+ const roundIndex = attached?.roundIndex ?? null;+ // A `supersedes` entry that names no check of this acceptance folds nothing:+ // the old row would stay on the page as if never replaced. An older server+ // does not report these, so treat the field as optional.+ const unresolvedSupersedes: string[] = attached?.unresolvedSupersedes ?? [];+ if (unresolvedSupersedes.length > 0) {+ log.warn(+ `supersedes names no check of this acceptance, so nothing was replaced: ${unresolvedSupersedes.join(', ')}. Name it by a plan item id from an earlier round or a check id from \`lh acceptance view --json\`.`,+ );+ }+ const acceptanceUrl = new URL(+ `/acceptance/${encodeURIComponent(acceptanceId)}`,+ resolveServerUrl(),+ ).toString();+ const roundUrl =+ roundIndex === null ? null : `${acceptanceUrl}?r=${encodeURIComponent(String(roundIndex))}`;++ // 2. Ingest each case as a check result + its evidence. `checkItemId` is+ // the stable key within this immutable run.+ const seenCheckItemIds = new Set<string>();+ let evidenceCount = 0;+ let inlined = 0;+ const failedEvidence: (FailedReportEvidence & { checkItemId: string })[] = [];+ const missingEvidence: { checkItemId: string; types: EvidenceType[] }[] = [];+ const publishedVerdicts: Verdict[] = [];+ for (const [index, { case: c, checkItemId }] of cases.entries()) {+ seenCheckItemIds.add(checkItemId);+ const verdict = toVerdict(c.result ?? c.status ?? c.verdict);+ const observation = c.keyObservation ?? c.observation ?? c.note;+ const checkInput = {+ checkItemId,+ checkItemIndex: index,+ checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,+ metadata: caseMetadata[index],+ required: c.required ?? true,+ // The case's key observation is recorded as Toulmin evidence; a real+ // remediation hint (if the report provides one) goes to `suggestion`.+ // Absent → explicit `null`, so this immutable snapshot records the+ // absence instead of relying on upsert defaults.+ suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,+ toulmin: typeof observation === 'string' ? { evidence: observation } : null,+ verdict,+ verifierType: 'agent' as const,+ verifyRunId: runId,+ };+ const checkResult = await client.verify.ingestResult.mutate(checkInput);+ const uploaded = await uploadReportEvidence(client, {+ checkResultId: checkResult.id,+ dir,+ evidence: c.evidence,+ });+ evidenceCount += uploaded.count;+ inlined += uploaded.inlined;+ failedEvidence.push(...uploaded.failedEvidence.map((failure) => ({ ...failure, checkItemId })));+ const config = plan?.find((item) => item.id === checkItemId)?.verifierConfig as+ VerifyAgentPlanConfig | undefined;+ const required = config?.requiredEvidence;+ const gaps = [...new Set(required?.map((spec) => spec.type) ?? [])].filter(+ (type) => !uploaded.types.has(type),+ );+ const publishedVerdict = gaps.length > 0 && verdict === 'passed' ? 'uncertain' : verdict;+ publishedVerdicts.push(publishedVerdict);+ if (gaps.length > 0) {+ missingEvidence.push({ checkItemId, types: gaps });+ const limitation = `Required evidence not published: ${gaps.join(', ')}.`;+ log.warn(`${checkItemId}: ${limitation}`);+ await client.verify.ingestResult.mutate({+ ...checkInput,+ toulmin: { ...checkInput.toulmin, limitation },+ verdict: publishedVerdict,+ });+ }+ }++ const unexecuted = plan?.filter((item) => !seenCheckItemIds.has(item.id)) ?? [];+ for (const item of unexecuted) {+ const config = item.verifierConfig as VerifyAgentPlanConfig;+ const types = [...new Set(config.requiredEvidence?.map((spec) => spec.type) ?? [])];+ if (types.length === 0) continue;+ missingEvidence.push({ checkItemId: item.id, types });+ // Count the gap without inventing an execution result for an unexecuted check.+ publishedVerdicts.push('uncertain');+ log.warn(`${item.id}: not executed; required evidence not published: ${types.join(', ')}.`);+ }++ // 3. Write the report. `summary` is the overall conclusion (read above);+ // `content` is the full markdown detail.+ // A 0-100 quality score lands on overallConfidence (0-1); the report page+ // surfaces it as the `score` stat.+ const score =+ typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;+ // The authored counts describe the report the author wrote. Once a+ // programmatic-test check is screened out they no longer match what was+ // published, so recount the landed cases and unexecuted evidence gaps — a+ // stats block that disagrees with the visible check list is worse than no stats.+ const recount = cases.length !== allCases.length || missingEvidence.length > 0;+ const counted = (verdict: Verdict) => publishedVerdicts.filter((v) => v === verdict).length;+ const derivedVerdict = deriveReportVerdict(publishedVerdicts.map((verdict) => ({ verdict })));+ const reportVerdict =+ summary.verdict && cases.length === allCases.length+ ? toVerdict(summary.verdict)+ : derivedVerdict;+ await client.verify.upsertReport.mutate({+ content,+ failedChecks: recount ? counted('failed') : summary.failed,+ overallConfidence: score,+ passedChecks: recount ? counted('passed') : summary.passed,+ summary: conclusion,+ totalChecks: recount ? publishedVerdicts.length : (summary.total ?? cases.length),+ uncertainChecks: recount+ ? counted('uncertain') || undefined+ : (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,+ // Missing evidence cannot be overridden by an authored "passed" summary.+ // Keep a real failure rather than hiding it behind an evidence warning.+ verdict:+ missingEvidence.length > 0+ ? reportVerdict === 'failed' || derivedVerdict === 'failed'+ ? 'failed'+ : 'uncertain'+ : reportVerdict,+ verifyRunId: runId,+ });++ // 4. Post the round's note. It renders as part of the round rather than as+ // another message, so the discussion reads "<agent> shipped round N"+ // followed by what it says. Last, and never fatal: the round itself is+ // the deliverable, and a failed comment must not strand a published round+ // behind an aborted ingest.+ let proposalPosted = false;+ if (proposal) {+ try {+ await client.acceptanceComment.create.mutate({+ acceptanceId,+ // Signed by the agent that produced the round, not by whoever's+ // credentials carried the ingest. Absent outside an agent run, and+ // then it falls back to the account.+ authorAgentId: process.env.LOBEHUB_AGENT_ID || undefined,+ // Derived from the round, so re-ingesting the same round edits nothing+ // and duplicates nothing.+ clientId: `proposal:${runId}`,+ content: proposal,+ contextRunId: runId,+ kind: 'proposal',+ });+ proposalPosted = true;+ } catch (e) {+ log.warn(`proposal not posted to the discussion: ${String(e)}`);+ }+ }++ // 5. Link the PR to the acceptance itself. The round's context is a+ // snapshot of this ingest; the acceptance is what the PR delivers, and+ // the page reads its PRs from there. Only the report's own PR is linked:+ // a branch-inferred one stays round provenance. Never fatal: an older+ // server lacks the procedure, and the round itself is the deliverable.+ if (authoredPullRequest?.url) {+ try {+ await client.acceptance.linkPullRequest.mutate({+ id: acceptanceId,+ title:+ typeof authoredPullRequest.title === 'string' ? authoredPullRequest.title : undefined,+ url: String(authoredPullRequest.url),+ });+ } catch (e) {+ log.warn(`pull request not linked to the acceptance: ${String(e)}`);+ }+ }++ // A case with no matching plan item means the run checked something it+ // never planned — worth saying out loud, but not a failure. Only+ // meaningful against a plan that actually names something: with no plan+ // (or a cleared one) every case is trivially "unplanned", which is noise.+ const unplanned = plan?.length+ ? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))+ : [];++ const recovery = failedEvidence.some((failure) => failure.reason === 'storage_quota')+ ? await storageQuotaRecovery(client)+ : undefined;+ const partial = failedEvidence.length > 0 || missingEvidence.length > 0;+ if (partial) {+ process.exitCode = 1;+ log.warn(+ 'Report saved, but evidence publication is incomplete. Keep the local artifacts; retry only the missing evidence, not the whole ingest. Supplementing evidence does not change recorded verdicts.',+ );+ if (missingEvidence.some(({ checkItemId }) => !seenCheckItemIds.has(checkItemId))) {+ log.warn(+ 'Unexecuted checks have no result to attach evidence to. Execute them and publish a new round on the same acceptance; do not re-ingest this unchanged report.',+ );+ }+ if (recovery) log.warn(recovery.message);+ }++ if (options.json !== undefined) {+ outputJson(+ {+ acceptanceId,+ acceptanceUrl,+ cases: cases.length,+ droppedProgrammaticChecks: droppedLabels,+ evidence: evidenceCount,+ failedEvidence,+ inlined,+ missingEvidence,+ origin,+ planItems: plan?.length ?? 0,+ proposalPosted,+ publicationStatus: partial ? 'partial' : 'complete',+ pullRequest,+ recovery,+ roundIndex,+ roundUrl,+ scenario,+ subject: subject!.ref,+ unexecuted: unexecuted.map((item) => item.id),+ unplanned,+ unresolvedSupersedes,+ verifyRunId: runId,+ },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }++ console.log(+ `${partial ? pc.yellow('⚠ Partially published') : pc.green('✓ Ingested')} ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` ++ `${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}` ++ `${droppedLabels.length > 0 ? pc.yellow(` — ${droppedLabels.length} programmatic-test check(s) dropped`) : ''}`,+ );+ for (const failure of failedEvidence) {+ console.log(`${pc.yellow('retry (POSIX shell)')}: ${failure.retryCommand}`);+ console.log(+ `${pc.dim('retryArgs (lh, shell disabled)')}: ${JSON.stringify(failure.retryArgs)}`,+ );+ }+ if (plan?.length) {+ console.log(+ `${pc.bold('plan')}: ${plan.length} item(s)` ++ `${unexecuted.length > 0 ? pc.yellow(` — ${unexecuted.length} planned but not executed`) : ''}` ++ `${unplanned.length > 0 ? pc.dim(` — ${unplanned.length} unplanned case(s)`) : ''}`,+ );+ }+ if (proposalPosted) console.log(`${pc.bold('proposal')}: posted to the discussion`);+ if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);+ if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);+ console.log(`${pc.bold('verifyRunId')}: ${runId} ${pc.dim('(immutable snapshot)')}`);+ const subjectLabel =+ subject!.ref.subjectType === 'standalone'+ ? 'standalone'+ : `${subject!.ref.subjectType}:${subject!.ref.subjectId}`;+ console.log(`${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subjectLabel})`)}`);+ if (options.open || partial) {+ // The acceptance page is the only report page — an old /verify link only+ // redirects here. `?r=<roundIndex>` is this round's fixed snapshot.+ console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);+ if (roundUrl) {+ console.log(`${pc.bold('round snapshot')}: ${roundUrl}`);+ }+ }+}++export function withIngestReportOptions(cmd: Command): Command {+ return cmd+ .option('--source <source>', 'agent | agent-testing', 'agent-testing')+ .option(+ '--operation <id>',+ "Agent Run under test; a run that already owns a round (a Task's plan round) is published into",+ )+ .option('--acceptance <id>', 'Append this round to an existing acceptance')+ .option('--title <title>', 'Override the session title')+ .option('--goal <goal>', 'The goal/task being verified')+ .option(+ '--subject <type:id>',+ 'Attach to a task/topic/document (defaults to the current topic; otherwise standalone)',+ )+ .option(+ '--requirement <text>',+ 'Acceptance requirement recorded when the aggregate is first created',+ )+ .option('--open', 'Print the in-app URL to open the report')+ .option(+ '--dry-run',+ 'Validate the report (including its language) without publishing; works on a plan-only result.json',+ )+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptance/run/planRound.test.ts b/apps/cli/src/commands/acceptance/run/planRound.test.tsnew file mode 100644index 00000000000..b6b35ce9542--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/planRound.test.ts@@ -0,0 +1,251 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import type * as VerifyHelpers from '../utils';+import { usePublicationHarness } from './testUtils';++vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));+vi.mock('../../../settings', () => ({ resolveServerUrl: vi.fn() }));+vi.mock('../../../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));+vi.mock('../utils', async (importOriginal) => ({+ ...(await importOriginal<typeof VerifyHelpers>()),+ pullRequestFromBranch: vi.fn(),+}));++describe('lh acceptance run', () => {+ const h = usePublicationHarness();+ const { client, report, result, run } = h;++ describe('ingest into an operation that already owns a plan round', () => {+ const chapters = [+ { kind: 'step', label: 'Reload with listDevices held', t: 1.2 },+ { kind: 'check', note: 'First frame already shows the cached device', t: 2.4 },+ ];+ const frozenPlan = [+ {+ id: 'vci_reload',+ index: 0,+ required: true,+ title: '刷新后首屏直接显示设备',+ verifierConfig: { requiredEvidence: [{ type: 'video' }] },+ verifierType: 'llm',+ },+ {+ id: 'vci_code',+ index: 1,+ required: true,+ title: '持久化改用 replica',+ verifierConfig: {},+ verifierType: 'llm',+ },+ ];+ const writeRound = (cases: unknown[]) =>+ writeFile(+ path.join(h.dir, 'result.json'),+ JSON.stringify({+ cases,+ plan: [{ id: 'authored', title: 'ignored when the plan is frozen' }],+ summary: { verdict: 'passed' },+ title: '设备列表首屏',+ }),+ );++ beforeEach(async () => {+ client.verify.getVerifyState.query.mockResolvedValue({+ verifyPlan: frozenPlan,+ verifyPlanConfirmedAt: '2026-10-12T17:35:52.000Z',+ verifyRunId: 'plan-run',+ });+ client.verify.getRun.query.mockResolvedValue({+ acceptanceId: 'acceptance-task',+ id: 'plan-run',+ roundIndex: 1,+ });+ client.verify.submitCheckEvidence.mutate.mockImplementation(async (input) => ({+ checkResult: { id: `result-${input.checkItemId}`, verifyRunId: 'plan-run' },+ evidence: [],+ }));+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`exit ${code}`);+ }) as never);+ vi.spyOn(log, 'error').mockImplementation(() => {});+ await writeFile(path.join(h.dir, 'report.md'), '# builder narrative');+ await writeFile(path.join(h.dir, 'proposal.md'), '刷新后设备芯片首帧即显示。');+ });++ it('publishes cases and chaptered videos into the plan round without creating a round or judging it', async () => {+ await writeRound([+ {+ evidence: [{ chapters, description: 'warm reload', path: 'scroll.mp4' }],+ id: 'vci_reload',+ observation: 'device chip renders on the first frame',+ status: 'passed',+ },+ { evidence: ['output.txt'], id: 'vci_code', status: 'passed' },+ ]);++ await run('ingest', h.dir, '--operation', 'op-task', '--json');++ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ expect(client.acceptance.attachRun.mutate).not.toHaveBeenCalled();+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(client.verify.ingestResult.mutate).not.toHaveBeenCalled();+ // The round's verifier writes the report and the verdicts.+ expect(client.verify.upsertReport.mutate).not.toHaveBeenCalled();+ expect(client.verify.submitCheckEvidence.mutate).toHaveBeenCalledWith({+ checkItemId: 'vci_reload',+ operationId: 'op-task',+ toulmin: { evidence: 'device chip renders on the first frame' },+ });+ expect(client.verify.uploadEvidence.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ checkResultId: 'result-vci_reload',+ metadata: { chapters },+ type: 'video',+ }),+ );+ expect(client.acceptanceComment.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ acceptanceId: 'acceptance-task', contextRunId: 'plan-run' }),+ );+ expect(result()).toMatchObject({+ acceptanceUrl: 'https://app.lobehub.com/acceptance/acceptance-task',+ missingEvidence: [],+ mode: 'plan-round',+ publicationStatus: 'complete',+ roundIndex: 1,+ verifyRunId: 'plan-run',+ });+ expect(process.exitCode).toBeUndefined();+ });++ it('rejects a case id outside the frozen plan before writing anything', async () => {+ await writeRound([{ evidence: ['scroll.mp4'], id: 'reload', status: 'passed' }]);++ await expect(run('ingest', h.dir, '--operation', 'op-task')).rejects.toThrow('exit 1');+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('vci_reload'));+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ expect(uploadLocalFile).not.toHaveBeenCalled();+ });++ it('reports a planned video that never got a case as missing', async () => {+ await writeRound([{ evidence: ['output.txt'], id: 'vci_code', status: 'passed' }]);++ await run('ingest', h.dir, '--operation', 'op-task', '--json');++ expect(process.exitCode).toBe(1);+ expect(result()).toMatchObject({+ missingEvidence: [{ checkItemId: 'vci_reload', types: ['video'] }],+ publicationStatus: 'partial',+ unexecuted: ['vci_reload'],+ });+ });++ it('applies the verifier gate: deliverable scopes and same-medium substitutes are covered', async () => {+ client.verify.getVerifyState.query.mockResolvedValue({+ verifyPlan: [+ {+ ...frozenPlan[0],+ verifierConfig: {+ requiredEvidence: [{ type: 'gif' }, { scope: 'deliverable', type: 'markdown' }],+ },+ },+ {+ ...frozenPlan[1],+ verifierConfig: { requiredEvidence: [{ scope: 'task_artifacts', type: 'text' }] },+ },+ ],+ verifyPlanConfirmedAt: '2026-10-12T17:35:52.000Z',+ verifyRunId: 'plan-run',+ });+ // A recording uploaded as video satisfies a gif requirement; the deliverable+ // markdown and the unexecuted item's task artifact are the verifier's to resolve.+ await writeRound([{ evidence: ['scroll.mp4'], id: 'vci_reload', status: 'passed' }]);++ await run('ingest', h.dir, '--operation', 'op-task', '--json');++ expect(result()).toMatchObject({ missingEvidence: [], publicationStatus: 'complete' });+ expect(process.exitCode).toBeUndefined();+ });++ it('posts the proposal on the repair round the evidence was redirected to', async () => {+ // A check whose failure spawned a repair is answered on the live repair+ // round; the proposal and the output must name that round, not the old one.+ client.verify.submitCheckEvidence.mutate.mockImplementation(async (input) => ({+ checkResult: { id: `result-${input.checkItemId}`, verifyRunId: 'repair-run' },+ evidence: [],+ }));+ client.verify.getRun.query.mockImplementation(async ({ verifyRunId }) =>+ verifyRunId === 'repair-run'+ ? { acceptanceId: 'acceptance-task', id: 'repair-run', roundIndex: 2 }+ : { acceptanceId: 'acceptance-task', id: 'plan-run', roundIndex: 1 },+ );+ await writeRound([+ { evidence: ['scroll.mp4'], id: 'vci_reload', status: 'passed' },+ { evidence: ['output.txt'], id: 'vci_code', status: 'passed' },+ ]);++ await run('ingest', h.dir, '--operation', 'op-task', '--json');++ expect(client.acceptanceComment.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ clientId: 'proposal:repair-run', contextRunId: 'repair-run' }),+ );+ expect(result()).toMatchObject({ roundIndex: 2, verifyRunId: 'repair-run' });+ });++ it('reports an unattached plan round as blocked, not complete', async () => {+ client.verify.getRun.query.mockResolvedValue({+ acceptanceId: null,+ id: 'plan-run',+ roundIndex: null,+ });+ await writeRound([+ { evidence: ['scroll.mp4'], id: 'vci_reload', status: 'passed' },+ { evidence: ['output.txt'], id: 'vci_code', status: 'passed' },+ ]);++ await run('ingest', h.dir, '--operation', 'op-task', '--json');++ expect(result()).toMatchObject({+ acceptanceUrl: null,+ missingEvidence: [],+ publicationStatus: 'blocked',+ });+ expect(process.exitCode).toBe(1);+ });++ it('refuses to fold a retry into an earlier authored round under the same operation', async () => {+ // An authored ingest with --operation leaves a run whose plan was never+ // confirmed; it is not a plan round, and its verdicts and report are final.+ client.verify.getVerifyState.query.mockResolvedValue({+ verifyPlan: [{ id: 'screen', title: '用户能看到处理结果' }],+ verifyPlanConfirmedAt: null,+ verifyRunId: 'authored-run',+ });+ await report([], ['output.txt']);++ await expect(run('ingest', h.dir, '--operation', 'op-authored')).rejects.toThrow('exit 1');++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('authored-run'));+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ expect(client.verify.uploadEvidence.mutate).not.toHaveBeenCalled();+ });++ it('keeps creating a round for an operation with no verification run', async () => {+ client.verify.getVerifyState.query.mockResolvedValue(null);+ await report([], ['output.txt']);++ await run('ingest', h.dir, '--operation', 'op-free', '--json');++ expect(client.verify.createRun.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op-free' }),+ );+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/cli/src/commands/acceptance/run/planRound.ts b/apps/cli/src/commands/acceptance/run/planRound.tsnew file mode 100644index 00000000000..9bb2115abe4--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/planRound.ts@@ -0,0 +1,253 @@+import { runEvidenceGaps } from '@lobechat/const/verify';+import type { VerifyCheckItem } from '@lobechat/types';+import pc from 'picocolors';++import type { TrpcClient } from '../../../api/client';+import { resolveServerUrl } from '../../../settings';+import { outputJson } from '../../../utils/format';+import { log } from '../../../utils/logger';+import type { EvidenceType } from '../utils';+import type { FailedReportEvidence } from './evidenceUpload';+import { storageQuotaRecovery, uploadReportEvidence } from './evidenceUpload';++interface PlanRoundCase {+ case: any;+ checkItemId: string;+}++export interface PlanRoundIngestParams {+ /** result.json `plan[]`, used only when the frozen plan is empty. */+ authoredPlan?: VerifyCheckItem[];+ /** Per-case visualization metadata — check-result metadata a plan round cannot take. */+ caseMetadata: unknown[];+ /** `cases[]` after programmatic-test screening, ids frozen. */+ cases: PlanRoundCase[];+ dir: string;+ droppedLabels: string[];+ json?: boolean | string;+ operationId: string;+ proposal: string;+ pullRequest?: { title?: unknown; url?: unknown };+ /** report.md, which a plan round does not publish: its verifier writes the report. */+ reportContent?: string;+ state: {+ verifyPlan: VerifyCheckItem[] | null;+ verifyRunId: string;+ };+}++/**+ * Publish an authored round directory INTO the verification round an Agent Run+ * already owns (a Task's plan round), instead of creating another round.+ *+ * The run is keyed by its operation id — a second run on the same operation is+ * a unique violation, and a separate round would shadow the verifier's verdicts+ * and settle the acceptance behind the repair loop. So this path:+ * - writes each case through `submitCheckEvidence`, which enforces the frozen+ * plan and redirects to the live repair round, and attaches evidence (video+ * chapters included) exactly as a standalone ingest does;+ * - publishes no verdicts and no report: the round's verifier judges every item+ * and writes the report when it settles.+ */+export async function ingestIntoPlanRound(+ client: TrpcClient,+ params: PlanRoundIngestParams,+): Promise<void> {+ const frozenPlan = params.state.verifyPlan ?? [];+ const plan = frozenPlan.length > 0 ? frozenPlan : (params.authoredPlan ?? []);++ // Fail before the first write: an unknown id cannot land in a frozen plan,+ // and a half-published round is worse than none.+ if (frozenPlan.length > 0) {+ const unknown = params.cases.filter(+ ({ checkItemId }) => !frozenPlan.some((item) => item.id === checkItemId),+ );+ if (unknown.length > 0) {+ log.error(+ `case id(s) not in this run's frozen plan: ${unknown.map(({ checkItemId }) => checkItemId).join(', ')}`,+ );+ log.error(+ ` Use the plan's check item ids as cases[].id: ${frozenPlan.map((item) => `${item.id} (${item.title})`).join('; ')}`,+ );+ process.exit(1);+ }+ }+ if (params.caseMetadata.some(Boolean))+ log.warn(+ 'case visualizations are not published into a plan round — attach the data as evidence instead',+ );+ if (params.reportContent?.trim())+ log.warn(+ "report.md is not published into a plan round: its verifier writes the round's report. Keep the narrative in your final response.",+ );++ let evidenceCount = 0;+ let inlined = 0;+ const seen = new Set<string>();+ const failedEvidence: (FailedReportEvidence & { checkItemId: string })[] = [];+ const missingEvidence: { checkItemId: string; types: EvidenceType[] }[] = [];+ // `submitCheckEvidence` lands a check whose failure already spawned a repair+ // on that live repair round, not on the operation's own (settled) round.+ const landedRunIds = new Set<string>();+ for (const { case: c, checkItemId } of params.cases) {+ seen.add(checkItemId);+ const observation = c.keyObservation ?? c.observation ?? c.note;+ const { checkResult } = await client.verify.submitCheckEvidence.mutate({+ checkItemId,+ operationId: params.operationId,+ toulmin: typeof observation === 'string' ? { evidence: observation } : undefined,+ });+ if (checkResult.verifyRunId) landedRunIds.add(checkResult.verifyRunId);+ const uploaded = await uploadReportEvidence(client, {+ checkResultId: checkResult.id,+ dir: params.dir,+ evidence: c.evidence,+ });+ evidenceCount += uploaded.count;+ inlined += uploaded.inlined;+ failedEvidence.push(...uploaded.failedEvidence.map((failure) => ({ ...failure, checkItemId })));+ const gaps = coverageGaps(+ plan.find((item) => item.id === checkItemId),+ [...uploaded.types],+ );+ if (gaps.length > 0) {+ missingEvidence.push({ checkItemId, types: gaps });+ log.warn(`${checkItemId}: required evidence not published: ${gaps.join(', ')}.`);+ }+ }+ const unexecuted = plan.filter((item) => !seen.has(item.id));+ for (const item of unexecuted) {+ const types = coverageGaps(item, []);+ if (types.length === 0) continue;+ missingEvidence.push({ checkItemId: item.id, types });+ log.warn(`${item.id}: no case; required evidence not published: ${types.join(', ')}.`);+ }++ const run = await resolveLandedRun(client, params.state.verifyRunId, landedRunIds);++ let proposalPosted = false;+ if (params.proposal && run?.acceptanceId) {+ try {+ await client.acceptanceComment.create.mutate({+ acceptanceId: run.acceptanceId,+ authorAgentId: process.env.LOBEHUB_AGENT_ID || undefined,+ clientId: `proposal:${run.id}`,+ content: params.proposal,+ contextRunId: run.id,+ kind: 'proposal',+ });+ proposalPosted = true;+ } catch (e) {+ log.warn(`proposal not posted to the discussion: ${String(e)}`);+ }+ }+ if (params.pullRequest?.url && run?.acceptanceId) {+ try {+ await client.acceptance.linkPullRequest.mutate({+ id: run.acceptanceId,+ title: typeof params.pullRequest.title === 'string' ? params.pullRequest.title : undefined,+ url: String(params.pullRequest.url),+ });+ } catch (e) {+ log.warn(`pull request not linked to the acceptance: ${String(e)}`);+ }+ }++ const acceptanceUrl = run?.acceptanceId+ ? new URL(`/acceptance/${encodeURIComponent(run.acceptanceId)}`, resolveServerUrl()).toString()+ : null;+ // The evidence landed, but with no acceptance there is nothing to hand off:+ // a caller reading only the status must not take this for a publication.+ const blocked = !acceptanceUrl;+ if (blocked) {+ process.exitCode = 1;+ log.warn(+ 'this run is not attached to an acceptance yet — report the handoff as blocked; do not ingest a duplicate round',+ );+ }+ const recovery = failedEvidence.some((failure) => failure.reason === 'storage_quota')+ ? await storageQuotaRecovery(client)+ : undefined;+ const partial = failedEvidence.length > 0 || missingEvidence.length > 0;+ if (partial) {+ process.exitCode = 1;+ log.warn(+ 'Evidence publication is incomplete. Keep the local artifacts and retry only the missing evidence.',+ );+ if (recovery) log.warn(recovery.message);+ }++ if (params.json !== undefined) {+ outputJson(+ {+ acceptanceId: run?.acceptanceId ?? null,+ acceptanceUrl,+ cases: params.cases.length,+ droppedProgrammaticChecks: params.droppedLabels,+ evidence: evidenceCount,+ failedEvidence,+ inlined,+ missingEvidence,+ mode: 'plan-round',+ operationId: params.operationId,+ planItems: plan.length,+ proposalPosted,+ publicationStatus: blocked ? 'blocked' : partial ? 'partial' : 'complete',+ recovery,+ roundIndex: run?.roundIndex ?? null,+ unexecuted: unexecuted.map((item) => item.id),+ verifyRunId: run?.id ?? params.state.verifyRunId,+ },+ typeof params.json === 'string' ? params.json : undefined,+ );+ return;+ }++ console.log(+ `${blocked ? pc.yellow('⚠ Published without an acceptance') : partial ? pc.yellow('⚠ Partially published') : pc.green('✓ Published')} ${pc.bold(String(params.cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s) into the plan round of ${pc.bold(params.operationId)}`,+ );+ for (const failure of failedEvidence) {+ console.log(`${pc.yellow('retry (POSIX shell)')}: ${failure.retryCommand}`);+ }+ if (unexecuted.length > 0)+ console.log(pc.yellow(`plan: ${unexecuted.length} item(s) without a case`));+ if (proposalPosted) console.log(`${pc.bold('proposal')}: posted to the discussion`);+ console.log(+ `${pc.bold('verifyRunId')}: ${run?.id ?? params.state.verifyRunId} ${pc.dim('(judged by its verifier)')}`,+ );+ if (acceptanceUrl) console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);+}++/**+ * The verifier's own gate: only `run_evidence` must exist as rows (deliverable+ * and task artifacts are resolved by the verifier), and a same-medium artifact+ * (`video` for `gif`, `markdown` for `text`) covers the requirement.+ */+const coverageGaps = (item: VerifyCheckItem | undefined, published: EvidenceType[]) =>+ runEvidenceGaps(+ item?.verifierConfig as Record<string, unknown> | undefined,+ published.map((type) => ({ type })),+ ) as EvidenceType[];++/**+ * The round this publication actually landed on, so the proposal, the links and+ * the JSON output name the round the reviewer will see. Evidence redirected to a+ * repair round makes that round the live one; when cases split across rounds,+ * the newest round is the one still being judged.+ */+const resolveLandedRun = async (+ client: TrpcClient,+ operationRunId: string,+ landedRunIds: Set<string>,+) => {+ const ids = landedRunIds.size > 0 ? [...landedRunIds] : [operationRunId];+ const runs = await Promise.all(+ ids.map((verifyRunId) => client.verify.getRun.query({ verifyRunId })),+ );+ return runs+ .filter((run): run is NonNullable<typeof run> => Boolean(run))+ .reduce<(typeof runs)[number] | undefined>(+ (latest, run) => (!latest || (run.roundIndex ?? 0) > (latest.roundIndex ?? 0) ? run : latest),+ undefined,+ );+};diff --git a/apps/cli/src/commands/acceptance/run/report.ts b/apps/cli/src/commands/acceptance/run/report.tsnew file mode 100644index 00000000000..b348a0d91d2--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/report.ts@@ -0,0 +1,71 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { outputJson } from '../../../utils/format';+import { assertReportLanguage } from '../language';++// ── report ──++export interface ReportUpsertOptions {+ content?: string;+ failed?: string;+ json?: boolean | string;+ passed?: string;+ run: string;+ summary?: string;+ total?: string;+ uncertain?: string;+ verdict?: string;+}++export async function reportUpsertAction(options: ReportUpsertOptions): Promise<void> {+ const num = (s?: string) => (s === undefined ? undefined : Number.parseInt(s, 10));+ const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--summary', text: options.summary },+ { path: '--content', text: options.content },+ ]);+ const created = await client.verify.upsertReport.mutate({+ content: options.content,+ failedChecks: num(options.failed),+ passedChecks: num(options.passed),+ summary: options.summary,+ totalChecks: num(options.total),+ uncertainChecks: num(options.uncertain),+ verdict: options.verdict as any,+ verifyRunId: options.run,+ });+ if (options.json !== undefined) {+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Report ${pc.bold(created.id)} (${created.verdict ?? '—'})`);+}++export async function reportGetAction(+ runId: string,+ options: { json?: boolean | string },+): Promise<void> {+ const client = await getTrpcClient();+ const item = await client.verify.getReport.query({ verifyRunId: runId });+ if (options.json !== undefined) {+ outputJson(item, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (!item) return void console.log('No report.');+ console.log(JSON.stringify(item, null, 2));+}++export function withReportUpsertOptions(cmd: Command): Command {+ return cmd+ .requiredOption('--run <verifyRunId>', 'Target session id')+ .option('--verdict <verdict>', 'passed|failed|uncertain')+ .option('--summary <text>', 'Short summary')+ .option('--content <markdown>', 'Full markdown body')+ .option('--total <n>', 'Total checks')+ .option('--passed <n>', 'Passed checks')+ .option('--failed <n>', 'Failed checks')+ .option('--uncertain <n>', 'Uncertain checks')+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptance/run/result.chapters.test.ts b/apps/cli/src/commands/acceptance/run/result.chapters.test.tsnew file mode 100644index 00000000000..89405f098c6--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/result.chapters.test.ts@@ -0,0 +1,105 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import type * as VerifyHelpers from '../utils';+import { usePublicationHarness } from './testUtils';++vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));+vi.mock('../../../settings', () => ({ resolveServerUrl: vi.fn() }));+vi.mock('../../../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));+vi.mock('../utils', async (importOriginal) => ({+ ...(await importOriginal<typeof VerifyHelpers>()),+ pullRequestFromBranch: vi.fn(),+}));++describe('lh acceptance run', () => {+ const h = usePublicationHarness();+ const { client, run } = h;++ describe('result submit chapters', () => {+ const chapters = [+ { kind: 'step', label: 'Reload with listDevices held', t: 1.2 },+ { kind: 'check', note: 'First frame already shows the cached device', t: 2.4 },+ ];+ const submit = (...extra: string[]) =>+ run(+ 'result',+ 'submit',+ '--operation',+ 'op-1',+ '--item',+ 'reload',+ '--file',+ path.join(h.dir, 'scroll.mp4'),+ '--type',+ 'video',+ ...extra,+ );++ beforeEach(() => {+ client.verify.submitCheckEvidence.mutate.mockResolvedValue({+ checkResult: { id: 'result-reload', verifyRunId: 'run-1' },+ evidence: [{ id: 'evidence-1' }],+ });+ client.verify.getRun.query.mockResolvedValue({ acceptanceId: 'acceptance-1', id: 'run-1' });+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`exit ${code}`);+ }) as never);+ vi.spyOn(log, 'error').mockImplementation(() => {});+ });++ it('attaches a plan-round video with its chapters', async () => {+ await writeFile(path.join(h.dir, 'chapters.json'), JSON.stringify(chapters));++ await submit('--chapters', path.join(h.dir, 'chapters.json'));++ expect(client.verify.submitCheckEvidence.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ checkItemId: 'reload',+ evidence: [expect.objectContaining({ metadata: { chapters }, type: 'video' })],+ operationId: 'op-1',+ }),+ );+ });++ it('rejects a malformed marker before uploading anything', async () => {+ await writeFile(+ path.join(h.dir, 'chapters.json'),+ JSON.stringify([...chapters, { kind: 'check', t: 3 }]),+ );++ await expect(submit('--chapters', path.join(h.dir, 'chapters.json'))).rejects.toThrow(+ '1 of 3 chapters are malformed',+ );+ expect(uploadLocalFile).not.toHaveBeenCalled();+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ });++ it('rejects chapters on evidence that has no timeline', async () => {+ await writeFile(path.join(h.dir, 'chapters.json'), JSON.stringify(chapters));++ await expect(+ run(+ 'result',+ 'submit',+ '--operation',+ 'op-1',+ '--item',+ 'reload',+ '--file',+ path.join(h.dir, "screen's shot.png"),+ '--type',+ 'screenshot',+ '--chapters',+ path.join(h.dir, 'chapters.json'),+ ),+ ).rejects.toThrow('--chapters only applies to --type video evidence');+ expect(client.verify.submitCheckEvidence.mutate).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/cli/src/commands/acceptance/run/result.ts b/apps/cli/src/commands/acceptance/run/result.tsnew file mode 100644index 00000000000..c51e335ca4b--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/result.ts@@ -0,0 +1,239 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { resolveServerUrl } from '../../../settings';+import { outputJson } from '../../../utils/format';+import { log } from '../../../utils/logger';+import { assertReportLanguage, evidenceCaptionFields } from '../language';+import {+ type Decision,+ DECISIONS,+ evidenceDescriptionForFile,+ evidenceMetadataFromOptions,+ inlineTextEvidenceForFile,+ printResults,+} from '../utils';+import { uploadAcceptanceFile } from './evidenceUpload';++// ── result ──++export interface ResultIngestOptions {+ check: string;+ confidence?: string;+ evidence?: string;+ index?: string;+ json?: boolean | string;+ run: string;+ soft?: boolean;+ status?: string;+ suggestion?: string;+ title?: string;+ verdict: string;+}++export async function resultIngestAction(options: ResultIngestOptions): Promise<void> {+ const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--evidence', text: options.evidence },+ { path: '--suggestion', text: options.suggestion },+ ]);+ const created = await client.verify.ingestResult.mutate({+ checkItemId: options.check,+ checkItemIndex: options.index ? Number.parseInt(options.index, 10) : undefined,+ checkItemTitle: options.title,+ confidence: options.confidence ? Number.parseFloat(options.confidence) : undefined,+ required: options.soft ? false : undefined,+ status: options.status as any,+ suggestion: options.suggestion,+ toulmin: options.evidence ? { evidence: options.evidence } : undefined,+ verdict: options.verdict as any,+ verifyRunId: options.run,+ });+ if (options.json !== undefined) {+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Result ${pc.bold(created.id)} (${created.verdict})`);+}++export async function resultListAction(options: {+ json?: boolean | string;+ operation?: string;+ run?: string;+}): Promise<void> {+ if (!options.run && !options.operation) {+ log.error('Provide either --run or --operation');+ process.exit(1);+ }+ const client = await getTrpcClient();+ const results = options.run+ ? await client.verify.listResultsByRun.query({ verifyRunId: options.run })+ : await client.verify.listResults.query({ operationId: options.operation! });+ if (options.json !== undefined) {+ outputJson(results, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (results.length === 0) return void console.log('No results yet.');+ printResults(results);+}++export interface SubmitOptions {+ by?: string;+ chapters?: string;+ content?: string;+ desc?: string;+ file?: string;+ item: string;+ json?: boolean | string;+ metadata?: string;+ operation?: string;+ run?: string;+ title?: string;+ type?: string;+ verdict?: string;+}++export async function submitAction(options: SubmitOptions): Promise<void> {+ if (!options.run && !options.operation) {+ log.error('Provide --run <verifyRunId> or --operation <operationId>');+ process.exit(1);+ }+ const hasEvidence = Boolean(options.file) || Boolean(options.content);+ if (Boolean(options.file) && Boolean(options.content)) {+ log.error('Provide at most one of --file or --content');+ process.exit(1);+ }+ if (hasEvidence && !options.type) {+ log.error('--type is required when attaching evidence');+ process.exit(1);+ }+ if (!hasEvidence && !options.verdict) {+ log.error('Provide evidence (--file/--content) and/or a --verdict');+ process.exit(1);+ }+ if (!hasEvidence && (options.chapters || options.metadata)) {+ log.error('--chapters/--metadata describe evidence: pass --file or --content too');+ process.exit(1);+ }+ // Parse before uploading: a bad chapters file must not leave an orphan upload.+ const metadata = evidenceMetadataFromOptions(options);+ const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--desc', text: options.desc },+ // Chapter labels/notes and comparison labels render on the page as prose too.+ ...evidenceCaptionFields(options.chapters ? '--chapters' : '--metadata', metadata),+ ]);+ let fileId: string | undefined;+ let inlineContent = options.content;+ if (options.file) {+ inlineContent = inlineTextEvidenceForFile(options.file, options.type!);+ if (inlineContent === undefined) {+ const uploaded = await uploadAcceptanceFile(client, options.file, options.json);+ if (!uploaded) return;+ fileId = uploaded.id;+ }+ }+ const evidence = hasEvidence+ ? [+ {+ capturedBy: options.by as any,+ content: inlineContent,+ description: evidenceDescriptionForFile(options.desc, options.file),+ fileId,+ metadata,+ type: options.type as any,+ },+ ]+ : undefined;+ const res = await client.verify.submitCheckEvidence.mutate({+ checkItemId: options.item,+ checkItemTitle: options.title,+ evidence,+ operationId: options.operation,+ verdict: options.verdict as any,+ verifyRunId: options.run,+ });+ const verifyRunId = res.checkResult.verifyRunId ?? options.run;+ if (!verifyRunId) {+ log.error('Submitted result did not resolve to a verification run');+ process.exit(1);+ }+ // The acceptance page is the only report surface; a round not attached to one+ // has no link to hand off (the plan handoff lookup reports it as blocked).+ const round = await client.verify.getRun.query({ verifyRunId }).catch(() => null);+ const acceptanceUrl = round?.acceptanceId+ ? new URL(+ `/acceptance/${encodeURIComponent(round.acceptanceId)}`,+ resolveServerUrl(),+ ).toString()+ : null;+ if (options.json !== undefined) {+ outputJson(+ { ...res, acceptanceUrl, roundIndex: round?.roundIndex ?? null },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }+ console.log(+ `${pc.green('✓')} Submitted ${pc.bold(res.checkResult.id)}` ++ `${res.checkResult.verdict ? ` (${res.checkResult.verdict})` : ''}` ++ `${res.evidence.length > 0 ? ` +${res.evidence.length} evidence` : ''}`,+ );+ console.log(+ acceptanceUrl+ ? `${pc.bold('acceptance')}: ${acceptanceUrl}`+ : pc.dim('round not attached to an acceptance yet — no link to hand off'),+ );+}++export async function decisionAction(resultId: string, decision: Decision): Promise<void> {+ if (decision !== undefined && !DECISIONS.includes(decision)) {+ log.error(`decision must be one of: ${DECISIONS.join(', ')}`);+ process.exit(1);+ }+ const client = await getTrpcClient();+ await client.verify.submitDecision.mutate({ decision, resultId });+ console.log(`${pc.green('✓')} Recorded ${pc.bold(decision)} on result ${pc.bold(resultId)}`);+}++export function withResultIngestOptions(cmd: Command): Command {+ return cmd+ .requiredOption('--run <verifyRunId>', 'Target session id')+ .requiredOption('--check <checkItemId>', 'Stable check item id within the session')+ .requiredOption('--verdict <verdict>', 'passed|failed|uncertain')+ .option('--title <title>', 'Check title')+ .option('--index <n>', 'Display index')+ .option('--confidence <n>', '0-1 confidence')+ .option('--status <status>', 'pending|running|passed|failed|skipped (derived from verdict)')+ .option('--evidence <text>', 'Key observation (stored as Toulmin evidence)')+ .option('--suggestion <text>', 'Remediation hint')+ .option('--soft', 'Non-blocking (required=false); defaults to blocking')+ .option('--json [fields]', 'Output JSON');+}++export function withResultListOptions(cmd: Command): Command {+ return cmd+ .option('--run <verifyRunId>', 'List by verification session')+ .option('--operation <operationId>', 'List by Agent Run')+ .option('--json [fields]', 'Output JSON');+}++export function withSubmitOptions(cmd: Command): Command {+ return cmd+ .option('--run <verifyRunId>', 'Target verification session (or use --operation)')+ .option('--operation <operationId>', 'Resolve the session from an Agent Run operation id')+ .requiredOption('--item <checkItemId>', 'Plan item id (checkItemId)')+ .option('--type <type>', 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript')+ .option('--file <path>', 'Local file to upload as the evidence artifact')+ .option('--content <text>', 'Inline text payload (instead of a file)')+ .option('--verdict <verdict>', 'passed|failed|uncertain')+ .option('--title <text>', 'Check item title snapshot')+ .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')+ .option('--desc <text>', 'Human-readable caption for the evidence')+ .option('--chapters <file>', 'Video chapters JSON (steps, checks, flags on the timeline)')+ .option('--metadata <json>', 'Evidence metadata JSON object')+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptance/run/session.ts b/apps/cli/src/commands/acceptance/run/session.tsnew file mode 100644index 00000000000..33dfeacec65--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/session.ts@@ -0,0 +1,104 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { confirm, outputJson, printTable, timeAgo, truncate } from '../../../utils/format';+import { assertReportLanguage } from '../language';++// ── run ──++export interface RunCreateOptions {+ goal?: string;+ json?: boolean | string;+ operation?: string;+ source?: string;+ title?: string;+}++export async function runCreateAction(options: RunCreateOptions): Promise<void> {+ const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--goal', text: options.goal },+ ]);+ const created = await client.verify.createRun.mutate({+ goal: options.goal,+ operationId: options.operation,+ source: options.source as any,+ title: options.title,+ });+ if (options.json !== undefined) {+ outputJson(created, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Created run ${pc.bold(created.id)}`);+}++export async function runListAction(options: { json?: boolean | string }): Promise<void> {+ const client = await getTrpcClient();+ const runs = await client.verify.listRuns.query();+ if (options.json !== undefined) {+ outputJson(runs, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (runs.length === 0) return void console.log('No runs found.');+ printTable(+ runs.map((r: any) => [+ r.id,+ truncate(r.title || '', 40),+ r.source,+ r.status ?? '',+ r.operationId ? 'agent' : 'standalone',+ r.createdAt ? timeAgo(r.createdAt) : '',+ ]),+ ['ID', 'TITLE', 'SOURCE', 'STATUS', 'KIND', 'CREATED'],+ );+}++export async function runGetAction(+ runId: string,+ options: { json?: boolean | string },+): Promise<void> {+ const client = await getTrpcClient();+ const item = await client.verify.getRun.query({ verifyRunId: runId });+ if (options.json !== undefined) {+ outputJson(item, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ if (!item) return void console.log('Run not found.');+ console.log(JSON.stringify(item, null, 2));+}++export async function runDeleteAction(+ runId: string,+ options: { json?: boolean | string; yes?: boolean },+): Promise<void> {+ const client = await getTrpcClient();+ if (!options.yes) {+ const ok = await confirm(+ `Delete run ${pc.bold(runId)} and all its results, evidence and report? This cannot be undone.`,+ );+ if (!ok) return void console.log('Aborted.');+ }+ const result = await client.verify.deleteRun.mutate({ verifyRunId: runId });+ if (options.json !== undefined) {+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} Deleted run ${pc.bold(result.id)}`);+}++export function withRunCreateOptions(cmd: Command): Command {+ return cmd+ .option('--source <source>', 'agent | agent-testing', 'agent-testing')+ .option('--operation <id>', 'Link to an existing Agent Run')+ .option('--title <title>', 'Session title')+ .option('--goal <goal>', 'Goal/task being verified')+ .option('--json [fields]', 'Output JSON');+}++export function withRunDeleteOptions(cmd: Command): Command {+ return cmd+ .option('-y, --yes', 'Skip the confirmation prompt')+ .option('--json [fields]', 'Output JSON');+}diff --git a/apps/cli/src/commands/acceptance/run/testUtils.ts b/apps/cli/src/commands/acceptance/run/testUtils.tsnew file mode 100644index 00000000000..83e757bec4c--- /dev/null+++ b/apps/cli/src/commands/acceptance/run/testUtils.ts@@ -0,0 +1,117 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, vi } from 'vitest';++import { getTrpcClient } from '../../../api/client';+import { resolveServerUrl } from '../../../settings';+import { log } from '../../../utils/logger';+import { uploadLocalFile } from '../../../utils/uploadLocalFile';+import { attachAcceptanceRunCommands } from '.';++/**+ * The shared harness of the `lh acceptance run` publication tests: a mocked+ * tRPC client, a temp report directory with fixture artifacts, captured stdout,+ * and the command runner. Call it inside a `describe`; each test file keeps its+ * own `vi.mock` calls (`../../../api/client`, `../../../settings`,+ * `../../../utils/uploadLocalFile`), since Vitest hoists them per file.+ */+export const usePublicationHarness = () => {+ const client = {+ acceptanceComment: { create: { mutate: vi.fn() } },+ acceptance: {+ attachRun: { mutate: vi.fn() },+ ensure: { mutate: vi.fn() },+ getBundle: { query: vi.fn() },+ linkPullRequest: { mutate: vi.fn() },+ },+ verify: {+ createRun: { mutate: vi.fn() },+ getRun: { query: vi.fn() },+ getVerifyState: { query: vi.fn() },+ ingestResult: { mutate: vi.fn() },+ submitCheckEvidence: { mutate: vi.fn() },+ uploadEvidence: { mutate: vi.fn() },+ upsertReport: { mutate: vi.fn() },+ },+ user: { getUserState: { query: vi.fn() } },+ workspace: { getById: { query: vi.fn() } },+ };+ const state = { dir: '', printed: [] as string[] };+ let originalExitCode: typeof process.exitCode;++ beforeEach(async () => {+ vi.resetAllMocks();+ originalExitCode = process.exitCode;+ process.exitCode = undefined;+ state.printed = [];+ vi.spyOn(console, 'log').mockImplementation((line) => state.printed.push(String(line)));+ vi.spyOn(log, 'warn').mockImplementation(() => {});+ vi.mocked(resolveServerUrl).mockReturnValue('https://app.lobehub.com');+ vi.mocked(getTrpcClient).mockResolvedValue(+ client as unknown as Awaited<ReturnType<typeof getTrpcClient>>,+ );+ vi.mocked(uploadLocalFile).mockResolvedValue({ id: 'file-1', url: 'https://files.test/1' });+ client.acceptance.ensure.mutate.mockResolvedValue({ id: 'acceptance-1' });+ client.acceptance.getBundle.query.mockResolvedValue({});+ client.acceptance.attachRun.mutate.mockResolvedValue({ id: 'run-1', roundIndex: 2 });+ client.verify.createRun.mutate.mockResolvedValue({ id: 'run-1' });+ client.verify.ingestResult.mutate.mockImplementation(async (input) => ({+ id: `result-${input.checkItemId}`,+ }));+ client.verify.uploadEvidence.mutate.mockResolvedValue({ id: 'evidence-1' });+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'en-US' } },+ });+ state.dir = await mkdtemp(path.join(tmpdir(), 'lh-evidence-'));+ await writeFile(path.join(state.dir, "screen's shot.png"), 'image fixture');+ await writeFile(path.join(state.dir, 'scroll.mp4'), 'video fixture');+ await writeFile(path.join(state.dir, 'output.txt'), 'Observed the expected response.');+ });++ afterEach(async () => {+ process.exitCode = originalExitCode;+ vi.restoreAllMocks();+ await rm(state.dir, { force: true, recursive: true });+ });++ const run = async (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ attachAcceptanceRunCommands(program.command('acceptance'));+ await program.parseAsync(['node', 'lh', 'acceptance', 'run', ...args]);+ };++ const report = async (requiredEvidence: string[], evidence: string[], verdict = 'passed') => {+ await writeFile(+ path.join(state.dir, 'result.json'),+ JSON.stringify({+ cases: [{ evidence, id: 'screen', name: '用户能看到处理结果', status: verdict }],+ plan: [{ id: 'screen', requiredEvidence, title: '用户能看到处理结果' }],+ summary: { passed: 1, total: 1, verdict },+ title: '处理结果展示',+ }),+ );+ };++ const result = () => JSON.parse(state.printed.at(-1)!);+ const finalCheck = () => client.verify.ingestResult.mutate.mock.calls.at(-1)![0];+ const finalReport = () => client.verify.upsertReport.mutate.mock.calls.at(-1)![0];++ return {+ client,+ finalCheck,+ finalReport,+ get dir() {+ return state.dir;+ },+ get printed() {+ return state.printed;+ },+ report,+ result,+ run,+ };+};diff --git a/apps/cli/src/commands/acceptance/utils/annotation.test.ts b/apps/cli/src/commands/acceptance/utils/annotation.test.tsnew file mode 100644index 00000000000..64e4ea2ac26--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/annotation.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';++import { formatAnnotationRegion, formatDisputedChapter } from '.';++describe('formatAnnotationRegion', () => {+ const rect = { height: 0.03, width: 0.12, x: 0.31, y: 0.24 };++ it('names the evidence the region was drawn on and where on it', () => {+ expect(+ formatAnnotationRegion(+ { comment: 'too light', evidenceId: 'ev-1', rect },+ new Map([['ev-1', 'c11-profile-editing.png']]),+ ),+ ).toBe('c11-profile-editing.png @ 31%,24% · 12%×3%');+ });++ // Without the filename a reader still cannot tell WHICH screenshot was circled,+ // so the raw id is better than dropping the reference entirely.+ it('falls back to the raw evidence id when the label is unknown', () => {+ expect(formatAnnotationRegion({ evidenceId: 'ev-9', rect })).toBe('ev-9 @ 31%,24% · 12%×3%');+ });++ it('renders the position alone when the annotation names no evidence', () => {+ expect(formatAnnotationRegion({ rect })).toBe('31%,24% · 12%×3%');+ });++ it('renders the evidence alone when the rect is absent', () => {+ expect(formatAnnotationRegion({ evidenceId: 'ev-1' }, new Map([['ev-1', 'shot.png']]))).toBe(+ 'shot.png',+ );+ });++ // Reviews made before regions existed carry only a comment — printing an empty+ // "└" line under every one of them would be pure noise.+ it('returns undefined when there is no location at all', () => {+ expect(formatAnnotationRegion({ comment: 'just a note' })).toBeUndefined();+ expect(formatAnnotationRegion({ rect: { x: 0.1 } })).toBeUndefined();+ });+ it('leads with the frame on a video, then the region circled on it', () => {+ expect(+ formatAnnotationRegion(+ { evidenceId: 'ev-1', rect, time: { start: 7.2 } },+ new Map([['ev-1', 'scroll.mp4']]),+ ),+ ).toBe('scroll.mp4 @ frame at 0:07.20 · 31%,24% · 12%×3%');+ });++ it('prints a span, and no region at all when the note covers the whole frame', () => {+ expect(+ formatAnnotationRegion({+ evidenceId: 'ev-1',+ rect: { height: 1, width: 1, x: 0, y: 0 },+ time: { end: 67.65, start: 66.75 },+ }),+ ).toBe('ev-1 @ 1:06.75–1:07.65');+ });+});++describe('formatDisputedChapter', () => {+ it('quotes the agent claim the reviewer objected to', () => {+ expect(+ formatDisputedChapter({ kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 }),+ ).toBe('your check at 0:07.90: "no skeleton after scroll #3"');+ });++ it('says nothing when there is no claim to quote', () => {+ expect(formatDisputedChapter(undefined)).toBeUndefined();+ expect(formatDisputedChapter({ kind: 'check', t: 1 })).toBeUndefined();+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/annotation.ts b/apps/cli/src/commands/acceptance/utils/annotation.tsnew file mode 100644index 00000000000..dc7b0f674fe--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/annotation.ts@@ -0,0 +1,83 @@+import { formatVideoTimestamp, isFullFrameRect } from '@lobechat/const/verify';++/** A region a reviewer circled on one evidence image, or on one video frame or span. */+export interface ReviewAnnotationRegion {+ comment?: string;+ /** The agent chapter the reviewer disagrees with. */+ disputes?: { kind?: string; note?: string; t?: number };+ evidenceId?: string;+ rect?: { height?: number; width?: number; x?: number; y?: number };+ time?: { end?: number; start?: number };+}++/** `m:ss.cc` — shared with the acceptance page so both read the same moment. */+export const formatVideoTime = formatVideoTimestamp;++const isSeconds = (value?: number): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0;++const asPercent = (value?: number) =>+ typeof value === 'number' && Number.isFinite(value) ? `${Math.round(value * 100)}%` : undefined;++/**+ * Where a review annotation points, rendered for a terminal.+ *+ * The comment alone is not enough to act on: a screenshot usually has several+ * plausible targets, and without the image and the rect the reader has to guess+ * which one was circled. `rect` is normalized to the image box (0–1), so it is+ * printed as percentages. On a video the frame or span comes first, since the+ * reader has to seek there before any region means anything.+ *+ * Returns `undefined` when the annotation carries no location at all — an older+ * review, or one made before regions existed.+ */+export function formatAnnotationRegion(+ annotation: ReviewAnnotationRegion,+ evidenceLabels?: Map<string, string>,+): string | undefined {+ const label = annotation.evidenceId+ ? (evidenceLabels?.get(annotation.evidenceId) ?? annotation.evidenceId)+ : undefined;++ const { rect, time } = annotation;+ let moment: string | undefined;+ if (isSeconds(time?.start))+ moment = isSeconds(time.end)+ ? `${formatVideoTime(time.start)}–${formatVideoTime(time.end)}`+ : `frame at ${formatVideoTime(time.start)}`;+ // A video note that marks a moment without circling an area spans the whole+ // frame; printing "0%,0% · 100%×100%" would read as a real region.+ const wholeFrame =+ moment !== undefined &&+ rect !== undefined &&+ isFullFrameRect({+ height: rect.height ?? 0,+ width: rect.width ?? 0,+ x: rect.x ?? -1,+ y: rect.y ?? -1,+ });++ const x = asPercent(rect?.x);+ const y = asPercent(rect?.y);+ const width = asPercent(rect?.width);+ const height = asPercent(rect?.height);+ const at = x && y ? `${x},${y}` : undefined;+ const size = width && height ? `${width}×${height}` : undefined;+ const position = [moment, wholeFrame ? undefined : at, wholeFrame ? undefined : size]+ .filter(Boolean)+ .join(' · ');++ if (!label && !position) return undefined;+ if (!position) return label;+ return label ? `${label} @ ${position}` : position;+}++/**+ * The agent's own claim a reviewer objected to, quoted back so the repair run+ * sees exactly which of its statements was judged wrong.+ */+export function formatDisputedChapter(disputes?: ReviewAnnotationRegion['disputes']) {+ if (!disputes?.note) return undefined;+ const at = isSeconds(disputes.t) ? ` at ${formatVideoTime(disputes.t)}` : '';+ return `your ${disputes.kind ?? 'claim'}${at}: "${disputes.note}"`;+}diff --git a/apps/cli/src/commands/acceptance/utils/evidence.test.ts b/apps/cli/src/commands/acceptance/utils/evidence.test.tsnew file mode 100644index 00000000000..2256de04d70--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/evidence.test.ts@@ -0,0 +1,218 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import {+ evidenceDescriptionForFile,+ evidenceTypeForFile,+ inlineTextEvidenceForFile,+ reportEvidence,+} from '.';++describe('reportEvidence — comparison normalization', () => {+ it('accepts plain string paths', () => {+ expect(reportEvidence('assets/a.png')).toEqual([{ path: 'assets/a.png' }]);+ expect(reportEvidence(['a.png', 'b.png']).map((e) => e.path)).toEqual(['a.png', 'b.png']);+ });++ it('keeps a comparison that carries both an id and a before/after role', () => {+ const [before, after] = reportEvidence([+ { comparison: { id: 'row', role: 'before' }, path: 'before.png' },+ { comparison: { id: 'row', label: '改后', role: 'after' }, path: 'after.png' },+ ]);++ expect(before.comparison).toEqual({+ id: 'row',+ label: undefined,+ layout: undefined,+ role: 'before',+ });+ expect(after.comparison).toEqual({+ id: 'row',+ label: '改后',+ layout: undefined,+ role: 'after',+ });+ });++ it('passes a vertical layout through and ignores any other value', () => {+ const forLayout = (layout: unknown) =>+ reportEvidence([{ comparison: { id: 'row', layout, role: 'before' }, path: 'a.png' }])[0]+ .comparison?.layout;++ expect(forLayout('vertical')).toBe('vertical');+ // Side by side is the default, so anything unrecognized simply falls back to it.+ expect(forLayout('horizontal')).toBeUndefined();+ expect(forLayout('diagonal')).toBeUndefined();+ expect(forLayout(undefined)).toBeUndefined();+ });++ // The report viewer pairs on `id`, so an id-less comparison could never render+ // side by side — dropping it here keeps the upload honest instead of shipping+ // metadata the UI silently ignores.+ it('drops a comparison missing an id, keeping the image as ordinary evidence', () => {+ const [item] = reportEvidence([{ comparison: { role: 'before' }, path: 'before.png' }]);++ expect(item).toEqual({ comparison: undefined, description: undefined, path: 'before.png' });+ });++ it('drops a comparison whose role is absent or unrecognized', () => {+ expect(+ reportEvidence([{ comparison: { id: 'x', role: 'middle' }, path: 'a.png' }])[0].comparison,+ ).toBeUndefined();+ expect(+ reportEvidence([{ comparison: { id: 'x' }, path: 'a.png' }])[0].comparison,+ ).toBeUndefined();+ });++ // The flat shape (`comparison: "row", role: "before"`) is the easiest one to+ // write from memory, and it used to be the ONLY malformed shape that produced+ // no warning: the guard parsed the field into an object first, so a string+ // read as "no comparison at all" and the ingest exited clean while the page+ // rendered two unpaired images.+ it('warns and drops a comparison that is not an object', () => {+ vi.mocked(log.warn).mockClear();++ const [item] = reportEvidence([+ { comparison: 'row', path: 'before.png', role: 'before' } as unknown,+ ]);++ expect(item).toEqual({ comparison: undefined, description: undefined, path: 'before.png' });+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('before.png'));+ });++ it('warns for every malformed comparison shape, and stays quiet for a valid or absent one', () => {+ const warnsFor = (comparison: unknown) => {+ vi.mocked(log.warn).mockClear();+ reportEvidence([{ comparison, path: 'a.png' } as unknown]);+ return vi.mocked(log.warn).mock.calls.length > 0;+ };++ expect(warnsFor('row')).toBe(true);+ expect(warnsFor(['row'])).toBe(true);+ expect(warnsFor({ id: 'row' })).toBe(true);+ expect(warnsFor({ id: 'row', role: 'middle' })).toBe(true);++ // Falsy but present: someone wrote the field, so it is malformed rather+ // than absent. A truthiness guard would drop these without a word.+ expect(warnsFor('')).toBe(true);+ expect(warnsFor(0)).toBe(true);+ expect(warnsFor(false)).toBe(true);+ expect(warnsFor(Number.NaN)).toBe(true);++ // Absent is null/undefined only — an evidence item without a pair.+ expect(warnsFor({ id: 'row', role: 'before' })).toBe(false);+ expect(warnsFor(undefined)).toBe(false);+ expect(warnsFor(null)).toBe(false);+ });++ it('supports the `file` / `desc` aliases and skips entries with no path', () => {+ expect(+ reportEvidence([{ desc: 'a shot', file: 'a.png' }, { comparison: { id: 'x' } }]),+ ).toEqual([{ comparison: undefined, description: 'a shot', path: 'a.png' }]);+ });+});++describe('reportEvidence — video chapters', () => {+ beforeEach(() => {+ vi.mocked(log.warn).mockClear();+ });++ it('carries well-formed chapters on a video, sorted by time', () => {+ const [item] = reportEvidence([+ {+ chapters: [+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ { kind: 'step', label: 'Scroll #1', t: 2 },+ ],+ path: 'proof/scroll.mp4',+ },+ ]);++ expect(item.chapters).toEqual([+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ ]);+ expect(log.warn).not.toHaveBeenCalled();+ });++ // A dropped marker is a claim the agent believes the reviewer will see.+ it('names how many markers it dropped and why', () => {+ const [item] = reportEvidence([+ {+ chapters: [+ { kind: 'step', label: 'Open', t: 0 },+ { kind: 'check', t: 3 },+ ],+ path: 'clip.webm',+ },+ ]);++ expect(item.chapters).toEqual([{ kind: 'step', label: 'Open', t: 0 }]);+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('dropped 1 of 2 chapters'));+ });++ it('ignores chapters on a still image, and a chapters field that is not a list', () => {+ expect(+ reportEvidence([{ chapters: [{ kind: 'step', label: 'x', t: 0 }], path: 'a.png' }])[0]+ .chapters,+ ).toBeUndefined();+ expect(reportEvidence([{ chapters: 'intro', path: 'a.mp4' }])[0].chapters).toBeUndefined();+ expect(log.warn).toHaveBeenCalledTimes(2);+ });+});++describe('evidenceTypeForFile — markdown evidence', () => {+ it('maps .md / .markdown to the markdown medium, keeping .txt as text', () => {+ expect(evidenceTypeForFile('assets/root-cause.md')).toBe('markdown');+ expect(evidenceTypeForFile('assets/root-cause.markdown')).toBe('markdown');+ expect(evidenceTypeForFile('assets/root-cause.txt')).toBe('text');+ });++ it('types an audio clip as audio, not the binary-blob-as-text fallback', () => {+ // Before `audio` existed these fell through to `text`, so a TTS deliverable+ // published as an unreadable, unplayable artifact.+ expect(evidenceTypeForFile('assets/tts-zh.mp3')).toBe('audio');+ expect(evidenceTypeForFile('assets/reply.WAV')).toBe('audio');+ expect(evidenceTypeForFile('assets/voice.m4a')).toBe('audio');+ expect(evidenceTypeForFile('assets/tone.opus')).toBe('audio');+ // .webm stays video — the container is overwhelmingly used for screen clips.+ expect(evidenceTypeForFile('assets/flow.webm')).toBe('video');+ });++ it('inlines a small markdown file as content instead of uploading it', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'lh-evidence-'));+ const file = path.join(dir, 'root-cause.md');+ writeFileSync(file, '### 根因证据\n\n- `heteroSessionId` 未透传');++ try {+ expect(inlineTextEvidenceForFile(file, evidenceTypeForFile(file))).toBe(+ '### 根因证据\n\n- `heteroSessionId` 未透传',+ );+ } finally {+ rmSync(dir, { force: true, recursive: true });+ }+ });+});++describe('file evidence descriptions', () => {+ it('preserves an explicit description', () => {+ expect(evidenceDescriptionForFile('Goal final state', '/tmp/state.json')).toBe(+ 'Goal final state',+ );+ });++ it('retains the basename when a file is inlined without a description', () => {+ expect(evidenceDescriptionForFile(undefined, '/tmp/goal-final-state.json')).toBe(+ 'goal-final-state.json',+ );+ expect(evidenceDescriptionForFile(' ', '/tmp/events.json')).toBe('events.json');+ });++ it('does not invent a description for inline content', () => {+ expect(evidenceDescriptionForFile(undefined)).toBeUndefined();+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/evidence.ts b/apps/cli/src/commands/acceptance/utils/evidence.tsnew file mode 100644index 00000000000..b8c70e9162c--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/evidence.ts@@ -0,0 +1,184 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import type { VerifyEvidenceChapter } from '@lobechat/const/verify';+import { MAX_VERIFY_EVIDENCE_CHAPTERS, readEvidenceChapters } from '@lobechat/const/verify';++import { log } from '../../../utils/logger';+import { firstString, objectValue } from './values';++export type EvidenceType =+ 'audio' | 'dom_snapshot' | 'gif' | 'markdown' | 'screenshot' | 'text' | 'transcript' | 'video';++export const INLINE_TEXT_EVIDENCE_LIMIT = 5000;+export const INLINE_TEXT_EVIDENCE_TYPES = new Set<EvidenceType>([+ 'dom_snapshot',+ 'markdown',+ 'text',+ 'transcript',+]);++/** Pick an evidence medium from a file extension. */+export function evidenceTypeForFile(file: string): EvidenceType {+ const ext = path.extname(file).toLowerCase().slice(1);+ if (ext === 'gif') return 'gif';+ if (['png', 'jpg', 'jpeg', 'webp', 'svg', 'bmp'].includes(ext)) return 'screenshot';+ if (['mp4', 'webm', 'mov', 'm4v'].includes(ext)) return 'video';+ // Audio before the text fallback: an unrecognized binary used to land on+ // `text`, publishing a TTS clip as an unreadable, unplayable blob.+ if (+ ['mp3', 'wav', 'm4a', 'aac', 'flac', 'ogg', 'oga', 'opus', 'aiff', 'aif', 'wma'].includes(ext)+ )+ return 'audio';+ if (['html', 'htm'].includes(ext)) return 'dom_snapshot';+ if (['md', 'markdown'].includes(ext)) return 'markdown';+ return 'text';+}++export function inlineTextEvidenceForFile(+ file: string,+ type: EvidenceType | string,+): string | undefined {+ if (!INLINE_TEXT_EVIDENCE_TYPES.has(type as EvidenceType)) return undefined;++ try {+ const buffer = readFileSync(file);+ if (buffer.includes(0)) return undefined;++ const content = buffer.toString('utf8');+ return content.length > 0 && content.length < INLINE_TEXT_EVIDENCE_LIMIT ? content : undefined;+ } catch {+ return undefined;+ }+}++/** Normalize a case's `evidence` field (string | string[] | {path}[]) to path strings. */+export interface ReportEvidenceInput {+ /** Video only: agent markers on the timeline — steps it took, claims it checked, flags it raised. */+ chapters?: VerifyEvidenceChapter[];+ comparison?: {+ id: string;+ label?: string;+ layout?: 'horizontal' | 'vertical';+ role: 'after' | 'before';+ };+ description?: string;+ path: string;+}++export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {+ if (!evidence) return [];+ const arr = Array.isArray(evidence) ? evidence : [evidence];+ return arr+ .map((e): ReportEvidenceInput | null => {+ if (typeof e === 'string') return { path: e };+ const value = objectValue(e);+ const evidencePath = value && firstString(value.path, value.file);+ if (!evidencePath) return null;+ const comparison = objectValue(value.comparison);+ const role = comparison?.role;+ const id = firstString(comparison?.id);+ // The report viewer pairs on `id` and drops any comparison lacking one, so+ // an id-less half could never render side by side. Warn rather than upload+ // a comparison that is silently downgraded to an ordinary image.+ //+ // Test the raw field, not the parsed object: a comparison written flat+ // (`comparison: "row", role: "before"`) is not an object at all, so keying+ // the warning off `objectValue()` skipped the one shape that most needs+ // it — the author saw a clean ingest and unpaired images on the page.+ // Absent means null/undefined only; `""` / `0` / `false` are malformed+ // values that were written on purpose, so they warn like any other.+ const hasComparison = value.comparison !== undefined && value.comparison !== null;+ if (hasComparison && !(comparison && id && (role === 'before' || role === 'after'))) {+ log.warn(+ `evidence ${evidencePath}: comparison must be an object with a string "id" and role "before"/"after" — ignoring it`,+ );+ }+ const layout = comparison?.layout === 'vertical' ? 'vertical' : undefined;+ return {+ chapters: reportEvidenceChapters(evidencePath, value.chapters),+ comparison:+ id && (role === 'before' || role === 'after')+ ? { id, label: firstString(comparison?.label), layout, role }+ : undefined,+ description: firstString(value.description, value.desc),+ path: evidencePath,+ };+ })+ .filter((item): item is ReportEvidenceInput => item !== null);+}++/**+ * A video's chapters, with every dropped marker named: a marker the reviewer+ * never sees is a claim the agent believes it made, so the author must know.+ */+function reportEvidenceChapters(+ evidencePath: string,+ raw: unknown,+): VerifyEvidenceChapter[] | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (evidenceTypeForFile(evidencePath) !== 'video') {+ log.warn(`evidence ${evidencePath}: chapters only apply to video evidence — ignoring them`);+ return undefined;+ }+ if (!Array.isArray(raw)) {+ log.warn(`evidence ${evidencePath}: chapters must be an array — ignoring them`);+ return undefined;+ }+ const chapters = readEvidenceChapters(raw) ?? [];+ const dropped = raw.length - chapters.length;+ if (dropped > 0) {+ log.warn(+ `evidence ${evidencePath}: dropped ${dropped} of ${raw.length} chapters — each needs a non-negative "t" (seconds), a "kind" of step/check/flag, a "label" for a step and a "note" for a check or flag`,+ );+ }+ return chapters.length > 0 ? chapters : undefined;+}++/**+ * The metadata bag for one command-line evidence upload: `--metadata` JSON with+ * `--chapters <file>` merged in. Unlike a report ingest, a single upload names+ * its chapters explicitly, so a malformed or misplaced marker is an error to+ * fix before the upload rather than a warning after it.+ */+export function evidenceMetadataFromOptions(options: {+ chapters?: string;+ metadata?: string;+ type?: string;+}): Record<string, unknown> | undefined {+ let metadata: Record<string, unknown> | undefined;+ if (options.metadata) {+ const parsed: unknown = JSON.parse(options.metadata);+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))+ throw new Error('--metadata must be a JSON object');+ metadata = parsed as Record<string, unknown>;+ }+ if (!options.chapters) return metadata;++ if (options.type !== 'video') throw new Error('--chapters only applies to --type video evidence');+ const raw: unknown = JSON.parse(readFileSync(options.chapters, 'utf8'));+ // Accept the bare array video-chapters.md writes, or a `{ chapters }` bag.+ const list =+ raw && typeof raw === 'object' && !Array.isArray(raw)+ ? (raw as { chapters?: unknown }).chapters+ : raw;+ if (!Array.isArray(list)) throw new Error(`${options.chapters}: chapters must be a JSON array`);+ if (list.length > MAX_VERIFY_EVIDENCE_CHAPTERS)+ throw new Error(+ `${options.chapters}: ${list.length} chapters exceed the limit of ${MAX_VERIFY_EVIDENCE_CHAPTERS} per video`,+ );+ const chapters = readEvidenceChapters(list) ?? [];+ if (chapters.length !== list.length)+ throw new Error(+ `${options.chapters}: ${list.length - chapters.length} of ${list.length} chapters are malformed — each needs a non-negative "t" (seconds), a "kind" of step/check/flag, a "label" for a step and a "note" for a check or flag`,+ );+ return { ...metadata, chapters };+}++/** Keep file identity when small text artifacts are stored inline. */+export function evidenceDescriptionForFile(+ description?: string,+ file?: string,+): string | undefined {+ return description?.trim() || (file ? path.basename(file) : undefined);+}diff --git a/apps/cli/src/commands/acceptance/utils/index.ts b/apps/cli/src/commands/acceptance/utils/index.tsnew file mode 100644index 00000000000..024f1dba17d--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/index.ts@@ -0,0 +1,9 @@+export * from './annotation';+export * from './evidence';+export * from './options';+export * from './plan';+export * from './reportContext';+export * from './subject';+export * from './values';+export * from './verdict';+export * from './visualization';diff --git a/apps/cli/src/commands/acceptance/utils/options.ts b/apps/cli/src/commands/acceptance/utils/options.tsnew file mode 100644index 00000000000..44713bf52a5--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/options.ts@@ -0,0 +1,34 @@+import { verifyEvidenceTypes } from '@lobechat/const/verify';++import { log } from '../../../utils/logger';++export type VerifierType = 'agent' | 'llm' | 'program';+export type OnFail = 'auto_repair' | 'manual';+export type Decision = 'accepted' | 'overridden' | 'rejected';++export const VERIFIER_TYPES: VerifierType[] = ['program', 'agent', 'llm'];+export const ON_FAIL: OnFail[] = ['manual', 'auto_repair'];+export const DECISIONS: Decision[] = ['accepted', 'rejected', 'overridden'];+/** The evidence media a plan item may require — the same closed set the executor gates on. */+export const EVIDENCE_TYPES = verifyEvidenceTypes;++export function parseConfig(raw?: string): Record<string, unknown> | undefined {+ if (!raw) return undefined;+ try {+ return JSON.parse(raw);+ } catch {+ log.error('--config must be valid JSON');+ process.exit(1);+ }+}++export function assertEnum<T extends string>(+ value: T | undefined,+ allowed: T[],+ flag: string,+): void {+ if (value !== undefined && !allowed.includes(value)) {+ log.error(`${flag} must be one of: ${allowed.join(', ')}`);+ process.exit(1);+ }+}diff --git a/apps/cli/src/commands/acceptance/utils/plan.test.ts b/apps/cli/src/commands/acceptance/utils/plan.test.tsnew file mode 100644index 00000000000..9730045b5d5--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/plan.test.ts@@ -0,0 +1,175 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../../utils/logger';+import { planFromResult, screenProgrammaticTestChecks } from '.';++describe('screenProgrammaticTestChecks', () => {+ let warnSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => undefined);+ });++ afterEach(() => {+ warnSpy.mockRestore();+ });++ it('drops the repo test suites and static gates, keeping real acceptance checks', () => {+ const result = {+ cases: [+ { id: 'c1', name: '语音回复能在气泡里播放', status: 'pass' },+ { id: 'c2', name: '单元测试全部通过', status: 'pass' },+ ],+ plan: [+ { id: 'c1', title: '语音回复能在气泡里播放' },+ { id: 'c2', title: '单元测试全部通过' },+ { id: 'c3', method: 'bun run check --type', title: '类型检查无报错' },+ ],+ };++ const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result);++ expect([...droppedIds]).toEqual(['c2', 'c3']);+ expect(droppedLabels).toEqual(['c2 — 单元测试全部通过', 'c3 — 类型检查无报错']);+ expect(warnSpy).toHaveBeenCalled();+ });++ it('screens plan and cases together so a dropped item never orphans its pair', () => {+ // The plan item names the gate; the case is titled loosely. Screening only+ // one side would leave the other behind as an "unplanned" row.+ const { droppedIds } = screenProgrammaticTestChecks({+ cases: [{ id: 'c1', name: 'all green' }],+ plan: [{ id: 'c1', title: 'vitest suite passes' }],+ });++ expect([...droppedIds]).toEqual(['c1']);+ });++ it('says nothing when the round has no programmatic-test checks', () => {+ const { droppedIds, droppedLabels } = screenProgrammaticTestChecks({+ plan: [{ id: '1', title: 'the reply streams token by token' }],+ });++ expect(droppedIds.size).toBe(0);+ expect(droppedLabels).toEqual([]);+ expect(warnSpy).not.toHaveBeenCalled();+ });++ it('omits the screened ids from the frozen plan', () => {+ const result = {+ plan: [+ { id: 'c1', title: 'the reply streams token by token' },+ { id: 'c2', title: 'unit tests pass' },+ ],+ };+ const { droppedIds } = screenProgrammaticTestChecks(result);++ expect(planFromResult(result, droppedIds)!.map((item) => item.id)).toEqual(['c1']);+ });+});++describe('planFromResult — plan item normalization', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit');+ }) as never);+ });++ afterEach(() => {+ exitSpy.mockRestore();+ });++ it('fills every frozen-item field the author does not write', () => {+ expect(planFromResult({ plan: [{ id: '1', title: 'logs are persisted' }] })).toEqual([+ {+ description: undefined,+ id: '1',+ index: 0,+ onFail: 'manual',+ required: true,+ title: 'logs are persisted',+ verifierConfig: {},+ verifierType: 'agent',+ },+ ]);+ });++ it('honors the declared verifier instead of assuming every check is agent-judged', () => {+ const [item] = planFromResult({+ plan: [{ id: '1', title: 'cli returns a tree', verifier: 'program' }],+ })!;++ expect(item.verifierType).toBe('program');+ });++ it('carries requiredEvidence, which the executor coverage gate actually enforces', () => {+ const [item] = planFromResult({+ plan: [+ {+ id: '1',+ requiredEvidence: ['screenshot', { hint: 'the raw command output', type: 'text' }],+ title: 'ui renders',+ },+ ],+ })!;++ expect(item.verifierConfig).toEqual({+ requiredEvidence: [+ { hint: undefined, type: 'screenshot' },+ { hint: 'the raw command output', type: 'text' },+ ],+ });+ });++ it('rejects an out-of-vocabulary verifier or evidence medium', () => {+ // An unrecognized medium would gate on nothing — silently weaker than no gate.+ expect(() => planFromResult({ plan: [{ id: '1', title: 't', verifier: 'eyeball' }] })).toThrow(+ 'process.exit',+ );+ expect(() =>+ planFromResult({ plan: [{ id: '1', requiredEvidence: ['vibes'], title: 't' }] }),+ ).toThrow('process.exit');+ });++ it('carries how the check would be made and what it expected', () => {+ const [item] = planFromResult({+ plan: [{ expected: 'the file exists', id: '1', method: 'tail the log', title: 'logs' }],+ })!;++ expect(item.verifierConfig).toEqual({ expected: 'the file exists', method: 'tail the log' });+ });++ it('normalizes a per-item surface and drops one that names no surface', () => {+ const items = planFromResult({+ plan: [+ { id: '1', surface: 'electron', title: 'tray dedupe' },+ { id: '2', surface: 'unit', title: 'model test' },+ { id: '3', title: 'no surface' },+ ],+ })!;++ expect(items[0].verifierConfig).toEqual({ surface: 'desktop' });+ expect(items[1].verifierConfig).toEqual({});+ expect(items[2].verifierConfig).toEqual({});+ });++ it('keys items by the same id the cases use, so results pair back to them', () => {+ const items = planFromResult({ plan: [{ id: 'case-a', title: 'a' }, { title: 'b' }] })!;++ expect(items.map((i) => i.id)).toEqual(['case-a', 'case-2']);+ });++ it('drops an item that names no check', () => {+ expect(planFromResult({ plan: [{ id: '1' }] })).toEqual([]);+ });++ it('distinguishes "no plan field" from an explicitly empty plan', () => {+ // Absent → undefined: this snapshot did not declare a plan.+ expect(planFromResult({})).toBeUndefined();++ // Present but empty → `[]`: this snapshot explicitly planned no checks.+ expect(planFromResult({ plan: [] })).toEqual([]);+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/plan.ts b/apps/cli/src/commands/acceptance/utils/plan.tsnew file mode 100644index 00000000000..33f2b7ed6bc--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/plan.ts@@ -0,0 +1,282 @@+import {+ isProgrammaticTestCheck,+ normalizeVerifySurface,+ PROGRAMMATIC_TEST_CHECK_HINT,+ verifyEvidenceTypes,+ verifySurfaces,+} from '@lobechat/const/verify';+import { verifyCheckDefinitionSchema } from '@lobechat/types';++import { log } from '../../../utils/logger';+import { EVIDENCE_TYPES, VERIFIER_TYPES } from './options';+import { firstString, objectValue } from './values';++/** The id a plan entry / case will be ingested under, mirroring the readers below. */+const planItemId = (item: Record<string, unknown>, index: number) =>+ String(item.id ?? `case-${index + 1}`);+const caseItemId = (item: Record<string, unknown>, index: number) =>+ String(item.id ?? item.checkItemId ?? `case-${index + 1}`);++/** The outcome of {@link screenProgrammaticTestChecks}. */+export interface ProgrammaticTestScreen {+ /** Check ids to omit from both the frozen plan and the ingested cases. */+ droppedIds: Set<string>;+ /** What was dropped, `id — title`, for one warning the author can act on. */+ droppedLabels: string[];+}++/**+ * Which checks in this report are the repo's own programmatic test / static-+ * analysis gates rather than delivery outcomes a person accepts.+ *+ * Screened once, over the plan AND the cases, so a dropped plan item can never+ * leave its case behind as an orphan "unplanned" row (or the reverse). Both+ * sides are matched on their own text, then unioned by id.+ *+ * Dropping one item rather than failing the ingest is deliberate: the round's+ * real checks are still worth publishing, and a hard error would cost the author+ * the whole publish over an item they only meant as a footnote. (The caller does+ * refuse to publish when the screen empties the round — then there is nothing+ * left for a person to accept.)+ */+export function screenProgrammaticTestChecks(+ result: Record<string, unknown>,+): ProgrammaticTestScreen {+ const droppedIds = new Set<string>();+ const droppedLabels: string[] = [];++ const screen = (entry: unknown, id: string) => {+ const item = objectValue(entry);+ if (!item) return;+ const title = firstString(item.title, item.name, item.case);+ if (+ !isProgrammaticTestCheck(+ title,+ firstString(item.category, item.group),+ firstString(item.method, item.how),+ )+ ) {+ return;+ }+ if (!droppedIds.has(id)) {+ droppedIds.add(id);+ droppedLabels.push(title ? `${id} — ${title}` : id);+ }+ };++ if (Array.isArray(result.plan)) {+ result.plan.forEach((entry, index) =>+ screen(entry, planItemId(objectValue(entry) ?? {}, index)),+ );+ }+ if (Array.isArray(result.cases)) {+ result.cases.forEach((entry, index) =>+ screen(entry, caseItemId(objectValue(entry) ?? {}, index)),+ );+ }++ if (droppedLabels.length > 0) {+ log.warn(+ `dropping ${droppedLabels.length} programmatic-test check(s) from this acceptance round:`,+ );+ for (const label of droppedLabels) log.warn(` - ${label}`);+ log.warn(` ${PROGRAMMATIC_TEST_CHECK_HINT}`);+ }++ return { droppedIds, droppedLabels };+}++/** Reject an out-of-vocabulary plan value rather than storing a word nothing reads. */+export function assertPlanEnum<T extends string>(+ value: string,+ allowed: readonly T[],+ field: string,+ itemId: string,+): T {+ if ((allowed as readonly string[]).includes(value)) return value as T;++ log.error(`result.json plan item "${itemId}": "${field}" must be one of: ${allowed.join(', ')}`);+ log.error(` rejected: ${JSON.stringify(value)}`);+ process.exit(1);+}++/**+ * The checks the run set out to make, as frozen plan items.+ *+ * Two of the fields are a closed vocabulary, not free text, because the pipeline+ * actually acts on them:+ *+ * - `verifier` → {@link VerifyCheckItem.verifierType} (`program | agent | llm`):+ * how the item is judged. Defaults to `agent`, but a command-asserted check is+ * `program` and mislabelling it hides what actually produced the verdict.+ * - `requiredEvidence` → `verifierConfig.requiredEvidence`+ * ({@link RequiredEvidenceSpec}, medium from {@link verifyEvidenceTypes}):+ * the artifact the item MUST produce. The executor's coverage gate fails an+ * item whose required medium is missing, so this is enforcement, not a label —+ * an unknown medium would silently gate on nothing.+ *+ * `method` / `expected` stay prose: they are the author's intent in words, which+ * no enum can carry. Everything else the frozen {@link VerifyCheckItem} needs is+ * filled in here, so an author writes only `{ id, title }` plus what they mean.+ *+ * Returns `undefined` when the report declares no `plan` field. A `plan` that is+ * present but empty returns `[]`, recording an explicitly empty plan in this+ * immutable snapshot.+ *+ * `droppedIds` (from {@link screenProgrammaticTestChecks}) omits the repo's own+ * test/lint gates, which are shipping preconditions rather than acceptance items.+ */+export function planFromResult(result: Record<string, unknown>, droppedIds?: Set<string>) {+ if (!Array.isArray(result.plan)) return undefined;++ const items = result.plan.flatMap((entry: unknown, index: number) => {+ const item = objectValue(entry);+ const title = firstString(item?.title, item?.name);+ // An item with no title names no check — it can't be rendered or paired.+ if (!item || !title) return [];++ const id = planItemId(item, index);+ if (droppedIds?.has(id)) return [];+ const method = firstString(item.method, item.how);+ const expected = firstString(item.expected, item.expectation);++ const verifierRaw = firstString(item.verifier, item.verifierType);+ const verifierType = verifierRaw+ ? assertPlanEnum(verifierRaw, VERIFIER_TYPES, 'verifier', id)+ : ('agent' as const);++ const requiredEvidence = Array.isArray(item.requiredEvidence)+ ? item.requiredEvidence.flatMap((spec: unknown) => {+ // Accept the bare medium (`"screenshot"`) or the full spec object.+ const record = objectValue(spec);+ const raw = typeof spec === 'string' ? spec : firstString(record?.type);+ if (!raw) return [];++ return [+ {+ hint: firstString(record?.hint),+ type: assertPlanEnum(raw, EVIDENCE_TYPES, 'requiredEvidence', id),+ },+ ];+ })+ : [];++ // Per-item surface: the acceptance union groups checks by it. Normalized to+ // the closed set (electron → desktop); an unknown value is dropped loudly+ // rather than stored as a mystery chip.+ const surfaceRaw = firstString(item.surface);+ const surface = surfaceRaw ? normalizeVerifySurface(surfaceRaw) : null;+ if (surfaceRaw && !surface) {+ log.warn(+ `plan item "${id}": surface "${surfaceRaw}" names no product surface (expected ${verifySurfaces.join('/')}) — dropping it`,+ );+ }++ // The acceptance union groups by category and folds superseded ids into+ // the new item's iteration timeline — both authored by the harness.+ const category = firstString(item.category, item.group);+ const supersedes = Array.isArray(item.supersedes)+ ? item.supersedes.filter((value: unknown): value is string => typeof value === 'string')+ : [];++ return [+ {+ ...(category === undefined ? {} : { category }),+ description: firstString(item.description),+ sourceCriterionId: firstString(item.sourceCriterionId),+ definition:+ item.definition === undefined+ ? undefined+ : verifyCheckDefinitionSchema.parse(item.definition),+ id,+ index,+ onFail: 'manual' as const,+ required: typeof item.required === 'boolean' ? item.required : true,+ ...(supersedes.length > 0 ? { supersedes } : {}),+ title,+ verifierConfig: {+ ...(method === undefined ? {} : { method }),+ ...(expected === undefined ? {} : { expected }),+ ...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),+ ...(surface ? { surface } : {}),+ },+ verifierType,+ },+ ];+ });++ // `[]` is meaningful — it clears a stale plan. Only an absent `plan` field+ // (handled above) means "don't touch what's stored".+ return items;+}++interface ExistingAcceptanceCheck {+ id: string;+ planItem?: { id?: string; sourceCriterionId?: string | null } | null;+}++/**+ * Line a new round's plan up with the checks its acceptance already holds.+ * The server mints a fresh criterion for every item that arrives without one,+ * and the union keys rows by criterion — so a re-verification that skips this+ * lands every check as a brand-new row instead of the next entry in its history.+ */+export function reuseSourceCriteria<T extends { id: string; sourceCriterionId?: string | null }>(+ plan: T[] | undefined,+ checks: ExistingAcceptanceCheck[] | null | undefined,+): T[] | undefined {+ if (!plan || !checks?.length) return plan;++ return plan.map((item) => ({+ ...item,+ sourceCriterionId:+ item.sourceCriterionId ??+ checks.find((check) => check.id === item.id || check.planItem?.id === item.id)?.planItem+ ?.sourceCriterionId ??+ undefined,+ }));+}++interface ExistingAcceptanceRound {+ report?: { content?: string | null; summary?: string | null } | null;+ run: {+ id: string;+ plan?: { id: string; title: string }[] | null;+ roundIndex?: number | null;+ };+}++/**+ * The acceptance's latest round when it already publishes exactly this report.+ * Re-running the same ingest (a retry loop, a re-sent command) would otherwise+ * stack identical rounds on the page. Compares what the author wrote — body,+ * conclusion and plan — not the published counts, which the ingest derives+ * later from evidence uploads. Only a report with a body counts: without one,+ * two genuinely different runs of the same plan are indistinguishable here.+ */+export function findIdenticalLatestRound(+ rounds: ExistingAcceptanceRound[] | null | undefined,+ incoming: {+ plan?: { id: string; title: string }[];+ report: { content?: string; summary?: string };+ },+): ExistingAcceptanceRound['run'] | undefined {+ if (!incoming.report.content || !rounds?.length) return undefined;++ const latest = rounds.reduce((a, b) =>+ (b.run.roundIndex ?? 0) > (a.run.roundIndex ?? 0) ? b : a,+ );+ const published = latest.report;+ if (!published) return undefined;++ const same = (a: unknown, b: unknown) => (a ?? null) === (b ?? null);+ const planKey = (items: { id: string; title: string }[] | null | undefined) =>+ JSON.stringify((items ?? []).map(({ id, title }) => [id, title]));++ const identical =+ same(published.content, incoming.report.content) &&+ same(published.summary, incoming.report.summary) &&+ planKey(latest.run.plan) === planKey(incoming.plan);++ return identical ? latest.run : undefined;+}diff --git a/apps/cli/src/commands/acceptance/utils/reportContext.test.ts b/apps/cli/src/commands/acceptance/utils/reportContext.test.tsnew file mode 100644index 00000000000..d141757df11--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/reportContext.test.ts@@ -0,0 +1,128 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { genericContextFromResult, originFromEnv, scenarioFromResult, surfacesFromResult } from '.';++describe('surfacesFromResult — surface normalization', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit');+ }) as never);+ });++ afterEach(() => {+ exitSpy.mockRestore();+ });++ it('canonicalizes known aliases and dedupes', () => {+ expect(surfacesFromResult({ surfaces: ['electron', 'cli', 'desktop'] })).toEqual([+ 'desktop',+ 'cli',+ ]);+ });++ it('rejects a value that names no surface instead of silently dropping it', () => {+ // Free-form surfaces are how the field rotted: prose, runtime modes and test+ // kinds all ended up in it. Failing here puts the fix in the author's hands+ // while they still have the context to make it.+ expect(() =>+ surfacesFromResult({ surfaces: ['Electron 打包版(app.isPackaged=true)'] }),+ ).toThrow('process.exit');+ expect(() => surfacesFromResult({ surfaces: ['unit'] })).toThrow('process.exit');+ });++ it('returns undefined when the report names no surfaces at all', () => {+ expect(surfacesFromResult({})).toBeUndefined();+ expect(surfacesFromResult({ surfaces: [] })).toBeUndefined();+ });+});++describe('scenarioFromResult / genericContextFromResult — non-coding scenarios', () => {+ it('defaults to coding and passes any known scenario through', () => {+ expect(scenarioFromResult({})).toBe('coding');+ expect(scenarioFromResult({ scenario: 'research' })).toBe('research');+ expect(scenarioFromResult({ scenario: 'writing' })).toBe('writing');+ expect(scenarioFromResult({ scenario: 'generic' })).toBe('generic');+ });++ it('hard-errors on a scenario nothing renders', () => {+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`process.exit ${code}`);+ }) as never);++ try {+ expect(() => scenarioFromResult({ scenario: 'poetry' })).toThrow('process.exit 1');+ } finally {+ exitSpy.mockRestore();+ }+ });++ it('lifts shared provenance defaults but lets explicit context keys win', () => {+ expect(+ genericContextFromResult({+ context: { testedAt: '2026-07-16T10:00:00Z', wordCount: 82_000, work: '长夜' },+ createdAt: '2026-07-15T00:00:00Z',+ entry: 'lh doc export',+ }),+ ).toEqual({+ entry: 'lh doc export',+ testedAt: '2026-07-16T10:00:00Z',+ wordCount: 82_000,+ work: '长夜',+ });++ expect(genericContextFromResult({})).toBeUndefined();+ });+});++describe('originFromEnv — in-app provenance', () => {+ const saved = { ...process.env };++ afterEach(() => {+ process.env = { ...saved };+ });++ it('reads the conversation the agent runtime echoed into the child env', () => {+ process.env.LOBEHUB_AGENT_ID = 'agt_1';+ process.env.LOBEHUB_TOPIC_ID = 'tpc_1';+ process.env.LOBEHUB_OPERATION_ID = 'op_1';++ expect(originFromEnv()).toEqual({+ agentId: 'agt_1',+ operationId: 'op_1',+ topicId: 'tpc_1',+ });+ });++ it('retains conversation provenance for persistent Pi without an authoring operation', () => {+ process.env.LOBEHUB_AGENT_ID = 'agt_pi';+ process.env.LOBEHUB_TOPIC_ID = 'tpc_pi';+ delete process.env.LOBEHUB_OPERATION_ID;++ expect(originFromEnv()).toEqual({+ agentId: 'agt_pi',+ operationId: undefined,+ topicId: 'tpc_pi',+ });+ });++ it('never takes its operationId from --operation, which names the run under TEST', () => {+ // `--operation` links the session to the Agent Run being verified; origin is+ // the run that AUTHORED the report. Conflating them attributes the report to+ // its own subject — exactly the provenance this is meant to preserve.+ process.env.LOBEHUB_OPERATION_ID = 'op_authoring_run';++ expect(originFromEnv()?.operationId).toBe('op_authoring_run');+ // The flag is passed to `createRun` separately; it must not reach here at all.+ expect(originFromEnv).toHaveLength(0);+ });++ it('is undefined outside a LobeHub-spawned agent — a plain terminal is not an error', () => {+ delete process.env.LOBEHUB_AGENT_ID;+ delete process.env.LOBEHUB_TOPIC_ID;+ delete process.env.LOBEHUB_OPERATION_ID;++ expect(originFromEnv()).toBeUndefined();+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/reportContext.ts b/apps/cli/src/commands/acceptance/utils/reportContext.tsnew file mode 100644index 00000000000..5881910daf6--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/reportContext.ts@@ -0,0 +1,236 @@+import { execFileSync } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';++import type { VerifyRunOrigin, VerifyRunScenario, VerifySurface } from '@lobechat/const/verify';+import {+ GOMS_KLM_TRACE_FILE,+ normalizeVerifySurface,+ verifyRunScenarios,+ verifySurfaces,+} from '@lobechat/const/verify';+import type { VerifyInteractionCost } from '@lobechat/types';+import { parseKlmTrace, summarizeKlmTrace } from '@lobechat/utils/verify/interactionCost';++import { log } from '../../../utils/logger';+import { firstString, firstStringOrNumber, objectValue, safeWebUrl } from './values';++/** Normalize common agent-testing PR shapes into the verify coding scope. */+export function pullRequestFromResult(result: Record<string, unknown>) {+ const pr = objectValue(result.pullRequest) ?? objectValue(result.pr);+ const url = safeWebUrl(+ firstString(+ pr?.url,+ pr?.htmlUrl,+ pr?.html_url,+ result.pullRequestUrl,+ result.prUrl,+ typeof result.pr === 'string' ? result.pr : undefined,+ ),+ );+ const number = firstStringOrNumber(pr?.number, result.pullRequestNumber, result.prNumber);+ const title = firstString(pr?.title, result.pullRequestTitle, result.prTitle);+ const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);++ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+}++/**+ * The PR for a branch, asked of `gh`. A report almost always verifies a branch+ * that already has one, but the author has to remember to write it down — and+ * mostly doesn't, so the report loses its single most useful outbound link.+ * Best-effort by design: no `gh`, not a repo, not authenticated, or no PR for+ * the branch all mean "no PR", never a failed publish.+ */+export function pullRequestFromBranch(branch: string | undefined) {+ if (!branch) return undefined;++ try {+ const raw = execFileSync(+ 'gh',+ ['pr', 'view', branch, '--json', 'number,title,url'],+ // `gh` writes its "no pull requests found" diagnostics to stderr; keep them+ // off the CLI's own output.+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 },+ );+ const parsed = objectValue(JSON.parse(raw));+ const url = safeWebUrl(firstString(parsed?.url));+ const number = firstStringOrNumber(parsed?.number);+ const title = firstString(parsed?.title);+ const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);++ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+ } catch {+ return undefined;+ }+}++/**+ * The surfaces the report says it exercised, as canonical values.+ *+ * Strict on purpose: an unrecognized surface is a hard error, not a silently+ * dropped value. Free-form surfaces are how the field rotted — prose, runtime+ * modes ("packaged build") and test kinds ("unit", "type-check") all ended up in+ * it, and none of them render. Failing here puts the fix in the author's hands+ * while they still have the context to make it.+ */+export function surfacesFromResult(result: Record<string, unknown>): VerifySurface[] | undefined {+ if (!Array.isArray(result.surfaces)) return undefined;++ const raw = result.surfaces.filter((s: unknown): s is string => typeof s === 'string');+ const canonical: VerifySurface[] = [];+ const rejected: string[] = [];++ for (const value of raw) {+ const surface = normalizeVerifySurface(value);+ if (surface) {+ if (!canonical.includes(surface)) canonical.push(surface);+ } else {+ rejected.push(value);+ }+ }++ if (rejected.length > 0) {+ log.error(+ `result.json "surfaces" must name the product surface a check ran on, one of: ${verifySurfaces.join(', ')}`,+ );+ log.error(` rejected: ${rejected.map((v) => JSON.stringify(v)).join(', ')}`);+ log.error(+ ' Runtime detail ("packaged build", "CDP dev instance") belongs on a plan item\'s "method"; a test kind ("unit", "backend") is not a surface — a backend change verified through the CLI has surface "cli".',+ );+ process.exit(1);+ }++ return canonical.length > 0 ? canonical : undefined;+}++/**+ * What kind of delivery the report verified. Defaults to `coding` — the+ * agent-testing harness's home turf — and rejects an unknown value rather than+ * storing a scenario nothing renders (mirrors the strict surface policy: the+ * author still has the context to fix it).+ */+export function scenarioFromResult(result: Record<string, unknown>): VerifyRunScenario {+ const raw = result.scenario;+ if (raw === undefined) return 'coding';+ if (typeof raw === 'string' && (verifyRunScenarios as readonly string[]).includes(raw)) {+ return raw as VerifyRunScenario;+ }++ log.error(+ `result.json "scenario" must be one of: ${verifyRunScenarios.join(', ')} — rejected: ${JSON.stringify(raw)}`,+ );+ process.exit(1);+}++/**+ * A non-coding scenario's scope, passed through from result.json `context` as+ * the scenario's own bag (the server stores it as-is; known shapes live in+ * `@lobechat/types`). Top-level `entry` / `createdAt` are lifted as defaults so+ * every scenario gets the shared provenance fields for free; explicit `context`+ * keys win.+ */+export function genericContextFromResult(+ result: Record<string, unknown>,+): Record<string, unknown> | undefined {+ const bag = objectValue(result.context) ?? {};+ const entries = Object.entries({+ entry: firstString(result.entry),+ testedAt: firstString(result.createdAt),+ ...bag,+ }).filter(([, v]) => v !== undefined);++ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+}++/**+ * The LobeHub conversation this harness is running inside, read off the env the+ * agent runtime echoes into the child process. Lets a report published from an+ * in-app agent link back to the session that produced it with no flags to+ * remember. Absent (a plain terminal) → no origin, which is not an error.+ *+ * Reads the env and ONLY the env. `--operation` is the opposite relation — the+ * Agent Run this session *verifies* — so letting it fall through to here would+ * attribute the report to the run under test instead of the run that wrote it,+ * corrupting the very provenance this records. The two ids are independent and+ * may legitimately differ in the same publish.+ */+export function originFromEnv(): VerifyRunOrigin | undefined {+ const origin: VerifyRunOrigin = {+ agentId: firstString(process.env.LOBEHUB_AGENT_ID),+ operationId: firstString(process.env.LOBEHUB_OPERATION_ID),+ topicId: firstString(process.env.LOBEHUB_TOPIC_ID),+ };++ return Object.values(origin).some(Boolean) ? origin : undefined;+}++/**+ * 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,+ origin?: VerifyRunOrigin,+): Record<string, unknown> | undefined {+ const hasInteractionCost = Object.prototype.hasOwnProperty.call(result, 'interactionCost');+ // Nothing to write is not the same as writing an empty metadata bag.+ if (!hasInteractionCost && !origin) return undefined;++ const metadata = { ...objectValue(existingMetadata) };++ if (hasInteractionCost) {+ const interactionCost = objectValue(result.interactionCost);++ if (interactionCost) {+ metadata.interactionCost = interactionCost;+ } else {+ delete metadata.interactionCost;+ }+ }++ if (origin) metadata.origin = origin;++ return metadata;+}diff --git a/apps/cli/src/commands/acceptance/utils/subject.test.ts b/apps/cli/src/commands/acceptance/utils/subject.test.tsnew file mode 100644index 00000000000..41ee8126008--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/subject.test.ts@@ -0,0 +1,74 @@+import { afterEach, describe, expect, it } from 'vitest';++import { parseSubjectRef, subjectFromEnv, subjectFromResult } from '.';++describe('parseSubjectRef / subjectFromResult — acceptance subject', () => {+ it('parses the closed set of type:id references', () => {+ expect(parseSubjectRef('task:task_123')).toEqual({+ subjectId: 'task_123',+ subjectType: 'task',+ });+ expect(parseSubjectRef('topic:tpc_abc')).toEqual({+ subjectId: 'tpc_abc',+ subjectType: 'topic',+ });+ expect(parseSubjectRef('document:doc_1')).toEqual({+ subjectId: 'doc_1',+ subjectType: 'document',+ });+ });++ it('rejects unknown types and malformed references', () => {+ expect(parseSubjectRef('release:rel_1')).toBeNull();+ expect(parseSubjectRef('task:')).toBeNull();+ expect(parseSubjectRef('task_123')).toBeNull();+ expect(parseSubjectRef(undefined)).toBeNull();+ });++ it('keeps an id containing colons intact (splits on the FIRST colon only)', () => {+ expect(parseSubjectRef('topic:tpc:odd:id')).toEqual({+ subjectId: 'tpc:odd:id',+ subjectType: 'topic',+ });+ });++ it('reads result.json subject in both string and object shapes', () => {+ expect(subjectFromResult({ subject: 'task:task_9' })).toEqual({+ ref: { subjectId: 'task_9', subjectType: 'task' },+ });+ expect(+ subjectFromResult({+ subject: { id: 'tpc_1', requirement: 'no regressions', type: 'topic' },+ }),+ ).toEqual({+ ref: { subjectId: 'tpc_1', subjectType: 'topic' },+ requirement: 'no regressions',+ });+ });++ it('returns null on a malformed subject field instead of guessing', () => {+ expect(subjectFromResult({})).toBeNull();+ expect(subjectFromResult({ subject: 'nonsense' })).toBeNull();+ expect(subjectFromResult({ subject: { id: 'x' } })).toBeNull();+ });+});++describe('subjectFromEnv — default topic acceptance', () => {+ const saved = { ...process.env };++ afterEach(() => {+ process.env = { ...saved };+ });++ it('binds an in-app run to its authoring topic', () => {+ process.env.LOBEHUB_TOPIC_ID = 'tpc_1';++ expect(subjectFromEnv()).toEqual({ subjectId: 'tpc_1', subjectType: 'topic' });+ });++ it('requires an explicit subject outside a topic', () => {+ delete process.env.LOBEHUB_TOPIC_ID;++ expect(subjectFromEnv()).toBeNull();+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/subject.ts b/apps/cli/src/commands/acceptance/utils/subject.tsnew file mode 100644index 00000000000..003549e1c41--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/subject.ts@@ -0,0 +1,51 @@+import type { AcceptanceSubjectType } from '@lobechat/const/verify';+import { acceptanceSubjectTypes } from '@lobechat/const/verify';++import { firstString, objectValue } from './values';++/** A parsed acceptance subject reference (`task:<id>` / `topic:<id>` / `document:<id>`). */+export interface AcceptanceSubjectRef {+ subjectId: string;+ subjectType: AcceptanceSubjectType;+}++/**+ * Parse a `type:id` subject reference. Returns null on anything malformed —+ * callers decide whether that is an error (an explicit `--subject`) or a+ * silently absent field (result.json).+ */+export function parseSubjectRef(raw: unknown): AcceptanceSubjectRef | null {+ if (typeof raw !== 'string') return null;+ const idx = raw.indexOf(':');+ if (idx <= 0) return null;+ const type = raw.slice(0, idx).trim().toLowerCase();+ const id = raw.slice(idx + 1).trim();+ if (!id || !(acceptanceSubjectTypes as readonly string[]).includes(type)) return null;+ return { subjectId: id, subjectType: type as AcceptanceSubjectType };+}++/**+ * The acceptance subject a report attributes itself to, from result.json's+ * `subject` field — either `"task:<id>"` or `{ type, id, requirement? }`. An+ * explicit `--subject` flag wins over this.+ */+export function subjectFromResult(result: Record<string, unknown>): {+ ref: AcceptanceSubjectRef;+ requirement?: string;+} | null {+ const raw = result.subject;+ if (typeof raw === 'string') {+ const ref = parseSubjectRef(raw);+ return ref ? { ref } : null;+ }+ const value = objectValue(raw);+ if (!value) return null;+ const ref = parseSubjectRef(`${firstString(value.type) ?? ''}:${firstString(value.id) ?? ''}`);+ return ref ? { ref, requirement: firstString(value.requirement) } : null;+}++/** Default acceptance subject for a report authored inside a LobeHub topic. */+export function subjectFromEnv(): AcceptanceSubjectRef | null {+ const topicId = firstString(process.env.LOBEHUB_TOPIC_ID);+ return topicId ? { subjectId: topicId, subjectType: 'topic' } : null;+}diff --git a/apps/cli/src/commands/acceptance/utils/values.ts b/apps/cli/src/commands/acceptance/utils/values.tsnew file mode 100644index 00000000000..41d2ff29b6c--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/values.ts@@ -0,0 +1,28 @@+/** Readers for loosely shaped report JSON written by agents. */++export function firstString(...values: unknown[]): string | undefined {+ return values.find((v): v is string => typeof v === 'string' && v.length > 0);+}++export function firstStringOrNumber(...values: unknown[]): string | number | undefined {+ return values.find(+ (v): v is string | number => (typeof v === 'string' && v.length > 0) || typeof v === 'number',+ );+}++export function objectValue(value: unknown): Record<string, unknown> | undefined {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;+}++export function safeWebUrl(value: string | undefined): string | undefined {+ if (!value) return undefined;++ try {+ const url = new URL(value);+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined;+ } catch {+ return undefined;+ }+}diff --git a/apps/cli/src/commands/acceptance/utils/verdict.test.ts b/apps/cli/src/commands/acceptance/utils/verdict.test.tsnew file mode 100644index 00000000000..9849d72a517--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/verdict.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { deriveReportVerdict } from '.';++describe('deriveReportVerdict — headline fallback when summary.verdict is absent', () => {+ it('derives passed when every case passed', () => {+ expect(deriveReportVerdict([{ result: 'passed' }, { result: 'ok' }])).toBe('passed');+ });++ it('any failed case fails the report', () => {+ expect(deriveReportVerdict([{ result: 'passed' }, { result: 'failed' }])).toBe('failed');+ });++ it('a non-passed, non-failed case makes the report uncertain', () => {+ expect(deriveReportVerdict([{ result: 'passed' }, { result: 'blocked' }])).toBe('uncertain');+ });++ it('no cases → no derived verdict', () => {+ expect(deriveReportVerdict([])).toBeUndefined();+ });++ it('reads the documented `status` field, same as the per-case ingest', () => {+ // Regression: `status` was skipped here while the per-case ingest reads+ // `result ?? status ?? verdict`, so an all-pass report written with the+ // documented field derived `uncertain` whenever this fallback ran (e.g.+ // after the programmatic-test screen recounts the summary).+ expect(deriveReportVerdict([{ status: 'pass' }, { status: 'pass' }])).toBe('passed');+ expect(deriveReportVerdict([{ status: 'pass' }, { status: 'fail' }])).toBe('failed');+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/verdict.ts b/apps/cli/src/commands/acceptance/utils/verdict.tsnew file mode 100644index 00000000000..9a63fc073a9--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/verdict.ts@@ -0,0 +1,51 @@+import pc from 'picocolors';++import { printTable, truncate } from '../../../utils/format';++export type Verdict = 'failed' | 'passed' | 'uncertain';+/** Map a free-form case/summary result token onto the verify verdict vocabulary. */+export function toVerdict(raw: unknown): Verdict {+ const s = String(raw ?? '').toLowerCase();+ if (['pass', 'passed', 'ok', 'success'].includes(s)) return 'passed';+ if (['fail', 'failed', 'error'].includes(s)) return 'failed';+ return 'uncertain'; // partial / blocked / skipped / pending / unknown+}++/**+ * The report's headline verdict when the author didn't set `summary.verdict`:+ * derived from the ingested cases, so a report can never ship verdict-less and+ * render as a permanent "?" in every list surface.+ */+export function deriveReportVerdict(cases: unknown[]): Verdict | undefined {+ // Same field fallback as the per-case ingest (`result ?? status ?? verdict`) —+ // the documented case field is `status`, so dropping it here derived+ // `uncertain` for an all-pass report whenever this fallback actually ran.+ const verdicts = cases.map((c) =>+ toVerdict((c as any)?.result ?? (c as any)?.status ?? (c as any)?.verdict),+ );+ if (verdicts.length === 0) return undefined;+ if (verdicts.includes('failed')) return 'failed';+ if (verdicts.includes('uncertain')) return 'uncertain';+ return 'passed';+}++export function printResults(results: any[]): void {+ printTable(+ results.map((r) => [+ truncate(r.checkItemTitle || r.checkItemId, 50),+ statusColor(r.status),+ r.verdict ?? '',+ r.confidence != null ? String(r.confidence) : '',+ r.required ? 'gate' : 'soft',+ truncate(r.suggestion || '', 40),+ ]),+ ['CHECK', 'STATUS', 'VERDICT', 'CONF', 'BLOCK', 'SUGGESTION'],+ );+}++export function statusColor(status: string): string {+ if (status === 'passed') return pc.green(status);+ if (status === 'failed') return pc.red(status);+ if (status === 'running') return pc.yellow(status);+ return pc.dim(status);+}diff --git a/apps/cli/src/commands/acceptance/utils/visualization.test.ts b/apps/cli/src/commands/acceptance/utils/visualization.test.tsnew file mode 100644index 00000000000..281ca84281a--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/visualization.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';++import { visualizationMetadata } from '.';++describe('visualizationMetadata', () => {+ const input = {+ datasets: [+ {+ fields: [+ { key: 'name', type: 'string' },+ { key: 'before', type: 'number', unit: 'ms' },+ { key: 'after', type: 'number', unit: 'ms' },+ ],+ id: 'metrics',+ rows: [{ after: 24.8, before: 257, name: 'GC self-time' }],+ },+ ],+ visualizations: [+ {+ dataset: 'metrics',+ encoding: { after: 'after', before: 'before', label: 'name' },+ id: 'performance',+ type: 'metric-comparison',+ version: 1,+ },+ ],+ };++ it('normalizes datasets and views into versioned check-result metadata', () => {+ expect(visualizationMetadata(input)).toEqual({+ visualization: {+ datasets: input.datasets,+ schemaVersion: 1,+ views: input.visualizations,+ },+ });+ });++ it('rejects a view that references a missing dataset', () => {+ expect(() =>+ visualizationMetadata({+ ...input,+ visualizations: [{ ...input.visualizations[0], dataset: 'missing' }],+ }),+ ).toThrow('dataset');+ });++ it('rejects cells outside the declared field schema', () => {+ expect(() =>+ visualizationMetadata({+ ...input,+ datasets: [{ ...input.datasets[0], rows: [{ unexpected: 1 }] }],+ }),+ ).toThrow('does not match');+ });++ it('accepts grouped bar charts and SOTA table highlights', () => {+ expect(+ visualizationMetadata({+ ...input,+ visualizations: [+ {+ dataset: 'metrics',+ encoding: { category: 'name', series: [{ field: 'before' }] },+ id: 'scores',+ type: 'bar-chart',+ version: 1,+ },+ {+ dataset: 'metrics',+ encoding: { highlights: [{ field: 'after', mode: 'min' }] },+ id: 'score-table',+ type: 'table',+ version: 1,+ },+ ],+ })?.visualization?.views.map((view) => view.type),+ ).toEqual(['bar-chart', 'table']);+ });++ it.each([+ ['bar-chart', {}],+ ['heatmap', { x: 'name', y: 'before' }],+ ['line-chart', { series: [], x: 'name' }],+ ['metric-comparison', { after: 'after', before: 'before' }],+ ['scatter-plot', { x: 'before', y: 'missing' }],+ ['table', { columns: ['missing'] }],+ ])('rejects malformed %s encodings', (type, encoding) => {+ expect(() =>+ visualizationMetadata({+ ...input,+ visualizations: [{ dataset: 'metrics', encoding, id: 'invalid-view', type, version: 1 }],+ }),+ ).toThrow();+ });++ it('rejects duplicate dataset field keys', () => {+ expect(() =>+ visualizationMetadata({+ ...input,+ datasets: [+ {+ ...input.datasets[0],+ fields: [+ { key: 'name', type: 'string' },+ { key: 'name', type: 'number' },+ ],+ },+ ],+ }),+ ).toThrow('field keys must be unique');+ });+});diff --git a/apps/cli/src/commands/acceptance/utils/visualization.ts b/apps/cli/src/commands/acceptance/utils/visualization.tsnew file mode 100644index 00000000000..ac2e70305fd--- /dev/null+++ b/apps/cli/src/commands/acceptance/utils/visualization.ts@@ -0,0 +1,250 @@+import type {+ VerifyCheckResultMetadata,+ VerifyVisualizationDataset,+ VerifyVisualizationField,+ VerifyVisualizationManifest,+ VerifyVisualizationValue,+ VerifyVisualizationView,+} from '@lobechat/types';++import { firstString, objectValue } from './values';++const VISUALIZATION_FIELD_TYPES = new Set(['boolean', 'category', 'number', 'string', 'temporal']);+const VISUALIZATION_TYPES = new Set([+ 'bar-chart',+ 'heatmap',+ 'line-chart',+ 'metric-comparison',+ 'scatter-plot',+ 'table',+]);+const MAX_INLINE_VISUALIZATION_ROWS = 10_000;++const visualizationValue = (value: unknown): value is VerifyVisualizationValue =>+ value === null || ['boolean', 'number', 'string'].includes(typeof value);++const visualizationField = (+ encoding: Record<string, unknown>,+ key: string,+ fieldKeys: Set<string>,+ path: string,+) => {+ const field = firstString(encoding[key]);+ if (!field || !fieldKeys.has(field)) {+ throw new Error(`${path}.${key} must reference a declared dataset field`);+ }+ return field;+};++const optionalVisualizationField = (+ encoding: Record<string, unknown>,+ key: string,+ fieldKeys: Set<string>,+ path: string,+) => {+ if (encoding[key] === undefined) return;+ visualizationField(encoding, key, fieldKeys, path);+};++const optionalVisualizationString = (value: Record<string, unknown>, key: string, path: string) => {+ if (value[key] !== undefined && !firstString(value[key])) {+ throw new Error(`${path}.${key} must be a non-empty string`);+ }+};++const visualizationSeries = (+ encoding: Record<string, unknown>,+ fieldKeys: Set<string>,+ path: string,+ options?: { styles?: boolean },+) => {+ if (!Array.isArray(encoding.series) || encoding.series.length === 0) {+ throw new Error(`${path}.series must be a non-empty array`);+ }+ encoding.series.forEach((rawSeries, seriesIndex) => {+ const series = objectValue(rawSeries);+ const seriesPath = `${path}.series[${seriesIndex}]`;+ if (!series) throw new Error(`${seriesPath} must be an object`);+ visualizationField(series, 'field', fieldKeys, seriesPath);+ if (series.label !== undefined && !firstString(series.label)) {+ throw new Error(`${seriesPath}.label must be a non-empty string`);+ }+ if (+ options?.styles &&+ series.style !== undefined &&+ !['accent', 'muted', 'primary'].includes(String(series.style))+ ) {+ throw new Error(`${seriesPath}.style is invalid`);+ }+ });+};++const validateVisualizationEncoding = (+ view: Record<string, unknown>,+ fieldKeys: Set<string>,+ index: number,+) => {+ const path = `visualizations[${index}].encoding`;+ if (view.type === 'table' && view.encoding === undefined) return;+ const encoding = objectValue(view.encoding);+ if (!encoding) throw new Error(`${path} is required for ${String(view.type)}`);++ switch (view.type) {+ case 'bar-chart': {+ visualizationField(encoding, 'category', fieldKeys, path);+ visualizationSeries(encoding, fieldKeys, path);+ optionalVisualizationString(encoding, 'valueLabel', path);+ break;+ }+ case 'heatmap': {+ visualizationField(encoding, 'x', fieldKeys, path);+ visualizationField(encoding, 'y', fieldKeys, path);+ visualizationField(encoding, 'value', fieldKeys, path);+ break;+ }+ case 'line-chart': {+ visualizationField(encoding, 'x', fieldKeys, path);+ visualizationSeries(encoding, fieldKeys, path, { styles: true });+ optionalVisualizationString(encoding, 'xLabel', path);+ optionalVisualizationString(encoding, 'yLabel', path);+ break;+ }+ case 'metric-comparison': {+ visualizationField(encoding, 'label', fieldKeys, path);+ visualizationField(encoding, 'before', fieldKeys, path);+ visualizationField(encoding, 'after', fieldKeys, path);+ for (const key of [+ 'afterSamples',+ 'beforeSamples',+ 'direction',+ 'statistic',+ 'target',+ 'unit',+ ]) {+ optionalVisualizationField(encoding, key, fieldKeys, path);+ }+ break;+ }+ case 'scatter-plot': {+ visualizationField(encoding, 'x', fieldKeys, path);+ visualizationField(encoding, 'y', fieldKeys, path);+ optionalVisualizationField(encoding, 'color', fieldKeys, path);+ optionalVisualizationField(encoding, 'label', fieldKeys, path);+ optionalVisualizationString(encoding, 'xLabel', path);+ optionalVisualizationString(encoding, 'yLabel', path);+ break;+ }+ case 'table': {+ if (encoding.columns !== undefined) {+ if (!Array.isArray(encoding.columns) || encoding.columns.length === 0) {+ throw new Error(`${path}.columns must be a non-empty array`);+ }+ encoding.columns.forEach((field, fieldIndex) =>+ visualizationField({ field }, 'field', fieldKeys, `${path}.columns[${fieldIndex}]`),+ );+ }+ if (encoding.highlights !== undefined) {+ if (!Array.isArray(encoding.highlights)) {+ throw new Error(`${path}.highlights must be an array`);+ }+ encoding.highlights.forEach((rawHighlight, highlightIndex) => {+ const highlight = objectValue(rawHighlight);+ const highlightPath = `${path}.highlights[${highlightIndex}]`;+ if (!highlight) throw new Error(`${highlightPath} must be an object`);+ visualizationField(highlight, 'field', fieldKeys, highlightPath);+ if (highlight.mode !== 'max' && highlight.mode !== 'min') {+ throw new Error(`${highlightPath}.mode must be max or min`);+ }+ });+ }+ break;+ }+ }+};++/** Parse the case's datasets + views into versioned check-result metadata. */+export function visualizationMetadata(value: unknown): VerifyCheckResultMetadata | undefined {+ const input = objectValue(value);+ if (!input || (input.datasets === undefined && input.visualizations === undefined))+ return undefined;+ if (!Array.isArray(input.datasets) || !Array.isArray(input.visualizations)) {+ throw new Error('datasets and visualizations must both be arrays');+ }++ let rowCount = 0;+ const datasets = input.datasets.map((rawDataset, datasetIndex) => {+ const dataset = objectValue(rawDataset);+ const id = firstString(dataset?.id);+ if (!id || !Array.isArray(dataset?.fields) || !Array.isArray(dataset.rows)) {+ throw new Error(`datasets[${datasetIndex}] needs id, fields, and rows`);+ }++ const fields = dataset.fields.map((rawField, fieldIndex) => {+ const field = objectValue(rawField);+ const key = firstString(field?.key);+ const type = field?.type;+ if (!key || typeof type !== 'string' || !VISUALIZATION_FIELD_TYPES.has(type)) {+ throw new Error(`datasets[${datasetIndex}].fields[${fieldIndex}] is invalid`);+ }+ return {+ key,+ label: firstString(field.label),+ type,+ unit: firstString(field.unit),+ } as VerifyVisualizationField;+ });+ const fieldKeys = new Set(fields.map((field) => field.key));+ if (fieldKeys.size !== fields.length) {+ throw new Error(`datasets[${datasetIndex}] field keys must be unique`);+ }++ const rows = dataset.rows.map((rawRow, rowIndex) => {+ const row = objectValue(rawRow);+ if (+ !row ||+ Object.entries(row).some(([key, cell]) => !fieldKeys.has(key) || !visualizationValue(cell))+ ) {+ throw new Error(`datasets[${datasetIndex}].rows[${rowIndex}] does not match its fields`);+ }+ return row as Record<string, VerifyVisualizationValue>;+ });+ rowCount += rows.length;+ return { fields, id, rows } satisfies VerifyVisualizationDataset;+ });++ if (rowCount > MAX_INLINE_VISUALIZATION_ROWS) {+ throw new Error(`visualization metadata exceeds ${MAX_INLINE_VISUALIZATION_ROWS} inline rows`);+ }+ const datasetIds = new Set(datasets.map((dataset) => dataset.id));+ if (datasetIds.size !== datasets.length) throw new Error('dataset ids must be unique');+ const fieldKeysByDataset = new Map(+ datasets.map((dataset) => [dataset.id, new Set(dataset.fields.map((field) => field.key))]),+ );++ const views = input.visualizations.map((rawView, index) => {+ const view = objectValue(rawView);+ const id = firstString(view?.id);+ const type = view?.type;+ const dataset = firstString(view?.dataset);+ if (+ !id ||+ typeof type !== 'string' ||+ !VISUALIZATION_TYPES.has(type) ||+ !dataset ||+ !datasetIds.has(dataset) ||+ view.version !== 1+ ) {+ throw new Error(`visualizations[${index}] has an invalid id, type, version, or dataset`);+ }+ optionalVisualizationString(view, 'context', `visualizations[${index}]`);+ optionalVisualizationString(view, 'title', `visualizations[${index}]`);+ validateVisualizationEncoding(view, fieldKeysByDataset.get(dataset)!, index);+ return view as unknown as VerifyVisualizationView;+ });+ if (new Set(views.map((view) => view.id)).size !== views.length) {+ throw new Error('visualization ids must be unique');+ }++ const visualization: VerifyVisualizationManifest = { datasets, schemaVersion: 1, views };+ return { visualization };+}diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.tsdeleted file mode 100644index 4df49542c3d..00000000000--- a/apps/cli/src/commands/acceptanceRun.ts+++ /dev/null@@ -1,1560 +0,0 @@-import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import path from 'node:path';--import { acceptanceSubjectTypes } from '@lobechat/const/verify';-import type { VerifyAgentPlanConfig, VerifyCheckItem } from '@lobechat/types';-import type { Command } from 'commander';-import pc from 'picocolors';--import type { TrpcClient } from '../api/client';-import { createPublicLambdaClient, getTrpcClient } from '../api/client';-import { resolveWorkspaceId } from '../api/workspace';-import { resolveServerUrl } from '../settings';-import { ensureAcceptanceDirIgnored, ensureAcceptanceDirIgnoredFor } from '../utils/acceptanceDir';-import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';-import { log } from '../utils/logger';-import type { LinkResult } from '../utils/skillWiring';-import { linkHarnessSkills } from '../utils/skillWiring';-import type { FailedReportEvidence } from './acceptanceEvidence';-import {- storageQuotaRecovery,- uploadAcceptanceFile,- uploadReportEvidence,-} from './acceptanceEvidence';-import {- assertReportLanguage,- evidenceCaptionFields,- ingestLanguageFields,- languageSummary,-} from './acceptanceLanguage';-import {- type Decision,- DECISIONS,- deriveReportVerdict,- evidenceDescriptionForFile,- type EvidenceType,- findIdenticalLatestRound,- genericContextFromResult,- inlineTextEvidenceForFile,- interactionCostFromReportDir,- metadataForReport,- originFromEnv,- parseSubjectRef,- planFromResult,- printResults,- pullRequestFromBranch,- pullRequestFromResult,- reuseSourceCriteria,- scenarioFromResult,- screenProgrammaticTestChecks,- subjectFromEnv,- subjectFromResult,- surfacesFromResult,- toVerdict,- type Verdict,- visualizationMetadata,-} from './verifyHelpers';--// ── Actions ────────────────────────────────────────────────-//-// One implementation per command, shared by the canonical `lh acceptance run …`-// tree and the deprecated `lh verify …` aliases. Both wire the same function, so-// the two spellings never drift while the aliases live out their deprecation.--// ── install ──--interface InstallOptions {- dir?: string;- force?: boolean;- json?: boolean | string;- skill: string;- skillVersion?: string;-}--const listMaterializedFiles = (directory: string): string[] => {- if (!existsSync(directory)) return [];-- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {- const entryPath = path.join(directory, entry.name);- return entry.isDirectory() ? listMaterializedFiles(entryPath) : [entryPath];- });-};--async function installAction(options: InstallOptions, client: TrpcClient): Promise<void> {- const version = options.skillVersion?.replace(/^v/, '');- const bundle = await client.verify.getSkillBundle.query({- identifier: options.skill,- ...(version === undefined ? {} : { version }),- });- // Older servers ignore the requested version. A matching version label alone- // does not prove that the content was resolved from the requested tag.- if (- version !== undefined &&- (bundle.version !== version || bundle.source?.ref !== `v${version}`)- ) {- throw new Error(- `Requested acceptance skill ${version} from tag v${version}, but the server returned version ${bundle.version ?? 'unknown'} from ${bundle.source?.ref ?? 'an unknown source'}. Update your server to support skill tag selection.`,- );- }-- // 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. 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);-- // path → content for SKILL.md plus every resource file.- const entries: [string, string][] = [- ['SKILL.md', bundle.content],- ...Object.entries(bundle.files),- ];-- const written: string[] = [];- const skipped: string[] = [];- for (const [rel, content] of entries) {- const dest = path.join(skillDir, rel);- if (existsSync(dest) && !options.force) {- skipped.push(rel);- continue;- }- mkdirSync(path.dirname(dest), { recursive: true });- writeFileSync(dest, content, 'utf8');- written.push(rel);- }-- // `acceptance update` is an explicit force-refresh of a materialized skill,- // not a merge into a hand-maintained directory. Remove files that belonged to- // an older bundle so renamed/split references cannot remain discoverable.- const removed: string[] = [];- if (options.force) {- const currentEntries = new Set(entries.map(([rel]) => path.normalize(rel)));- for (const file of listMaterializedFiles(skillDir)) {- const relativePath = path.relative(skillDir, file);- if (currentEntries.has(path.normalize(relativePath))) continue;-- rmSync(file, { force: true });- removed.push(relativePath.split(path.sep).join('/'));- }- }-- const links = linkHarnessSkills(baseDir, bundle.identifier);- // `link` predates `links` and stays as a compatibility alias for the Claude- // result — `install --json link` and `.link.kind` readers keep working.- const link: LinkResult = links.find((l) => 'link' in l && l.link.startsWith('.claude')) ?? {- kind: 'none',- };- // The skill is committed; its OUTPUT is not. Seed the artifact directory's own- // self-ignoring file now, so the first run's screenshots never land as- // untracked noise in a repo that has never heard of us.- const ignored = ensureAcceptanceDirIgnored(baseDir);-- const result = {- dir: skillDir,- ignored,- link,- links,- removed,- skill: bundle.identifier,- skipped,- source: bundle.source,- // 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)}${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(links);-}--function printWiring(links: LinkResult[]): void {- const arrow = pc.dim(' ↳');- for (const link of links) {- switch (link.kind) {- case 'linked':- case 'linked-single': {- console.log(`${arrow} linked ${link.link} → ${pc.dim(link.target)}`);- break;- }- case 'already': {- console.log(`${arrow} ${pc.dim(`${link.link} already linked`)}`);- break;- }- case 'skipped': {- console.log(`${arrow} ${pc.yellow(`skipped ${link.link}: ${link.reason}`)}`);- break;- }- default: {- console.log(- `${arrow} ${pc.dim('no harness dirs detected — agents that read .agents/skills pick it up automatically')}`,- );- break;- }- }- }-}--// ── run ──--interface RunCreateOptions {- goal?: string;- json?: boolean | string;- operation?: string;- source?: string;- title?: string;-}--async function runCreateAction(options: RunCreateOptions): Promise<void> {- const client = await getTrpcClient();- await assertReportLanguage(client, [- { path: '--title', text: options.title },- { path: '--goal', text: options.goal },- ]);- const created = await client.verify.createRun.mutate({- goal: options.goal,- operationId: options.operation,- source: options.source as any,- title: options.title,- });- if (options.json !== undefined) {- outputJson(created, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Created run ${pc.bold(created.id)}`);-}--async function runListAction(options: { json?: boolean | string }): Promise<void> {- const client = await getTrpcClient();- const runs = await client.verify.listRuns.query();- if (options.json !== undefined) {- outputJson(runs, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (runs.length === 0) return void console.log('No runs found.');- printTable(- runs.map((r: any) => [- r.id,- truncate(r.title || '', 40),- r.source,- r.status ?? '',- r.operationId ? 'agent' : 'standalone',- r.createdAt ? timeAgo(r.createdAt) : '',- ]),- ['ID', 'TITLE', 'SOURCE', 'STATUS', 'KIND', 'CREATED'],- );-}--async function runGetAction(runId: string, options: { json?: boolean | string }): Promise<void> {- const client = await getTrpcClient();- const item = await client.verify.getRun.query({ verifyRunId: runId });- if (options.json !== undefined) {- outputJson(item, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (!item) return void console.log('Run not found.');- console.log(JSON.stringify(item, null, 2));-}--async function runDeleteAction(- runId: string,- options: { json?: boolean | string; yes?: boolean },-): Promise<void> {- const client = await getTrpcClient();- if (!options.yes) {- const ok = await confirm(- `Delete run ${pc.bold(runId)} and all its results, evidence and report? This cannot be undone.`,- );- if (!ok) return void console.log('Aborted.');- }- const result = await client.verify.deleteRun.mutate({ verifyRunId: runId });- if (options.json !== undefined) {- outputJson(result, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Deleted run ${pc.bold(result.id)}`);-}--// ── result ──--interface ResultIngestOptions {- check: string;- confidence?: string;- evidence?: string;- index?: string;- json?: boolean | string;- run: string;- soft?: boolean;- status?: string;- suggestion?: string;- title?: string;- verdict: string;-}--async function resultIngestAction(options: ResultIngestOptions): Promise<void> {- const client = await getTrpcClient();- await assertReportLanguage(client, [- { path: '--title', text: options.title },- { path: '--evidence', text: options.evidence },- { path: '--suggestion', text: options.suggestion },- ]);- const created = await client.verify.ingestResult.mutate({- checkItemId: options.check,- checkItemIndex: options.index ? Number.parseInt(options.index, 10) : undefined,- checkItemTitle: options.title,- confidence: options.confidence ? Number.parseFloat(options.confidence) : undefined,- required: options.soft ? false : undefined,- status: options.status as any,- suggestion: options.suggestion,- toulmin: options.evidence ? { evidence: options.evidence } : undefined,- verdict: options.verdict as any,- verifyRunId: options.run,- });- if (options.json !== undefined) {- outputJson(created, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Result ${pc.bold(created.id)} (${created.verdict})`);-}--async function resultListAction(options: {- json?: boolean | string;- operation?: string;- run?: string;-}): Promise<void> {- if (!options.run && !options.operation) {- log.error('Provide either --run or --operation');- process.exit(1);- }- const client = await getTrpcClient();- const results = options.run- ? await client.verify.listResultsByRun.query({ verifyRunId: options.run })- : await client.verify.listResults.query({ operationId: options.operation! });- if (options.json !== undefined) {- outputJson(results, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (results.length === 0) return void console.log('No results yet.');- printResults(results);-}--interface SubmitOptions {- by?: string;- content?: string;- desc?: string;- file?: string;- item: string;- json?: boolean | string;- operation?: string;- run?: string;- title?: string;- type?: string;- verdict?: string;-}--async function submitAction(options: SubmitOptions): Promise<void> {- if (!options.run && !options.operation) {- log.error('Provide --run <verifyRunId> or --operation <operationId>');- process.exit(1);- }- const hasEvidence = Boolean(options.file) || Boolean(options.content);- if (Boolean(options.file) && Boolean(options.content)) {- log.error('Provide at most one of --file or --content');- process.exit(1);- }- if (hasEvidence && !options.type) {- log.error('--type is required when attaching evidence');- process.exit(1);- }- if (!hasEvidence && !options.verdict) {- log.error('Provide evidence (--file/--content) and/or a --verdict');- process.exit(1);- }- const client = await getTrpcClient();- await assertReportLanguage(client, [- { path: '--title', text: options.title },- { path: '--desc', text: options.desc },- ]);- let fileId: string | undefined;- let inlineContent = options.content;- if (options.file) {- inlineContent = inlineTextEvidenceForFile(options.file, options.type!);- if (inlineContent === undefined) {- const uploaded = await uploadAcceptanceFile(client, options.file, options.json);- if (!uploaded) return;- fileId = uploaded.id;- }- }- const evidence = hasEvidence- ? [- {- capturedBy: options.by as any,- content: inlineContent,- description: evidenceDescriptionForFile(options.desc, options.file),- fileId,- type: options.type as any,- },- ]- : undefined;- const res = await client.verify.submitCheckEvidence.mutate({- checkItemId: options.item,- checkItemTitle: options.title,- evidence,- operationId: options.operation,- verdict: options.verdict as any,- verifyRunId: options.run,- });- const verifyRunId = res.checkResult.verifyRunId ?? options.run;- if (!verifyRunId) {- log.error('Submitted result did not resolve to a verification run');- process.exit(1);- }- const url = new URL(`/verify/${verifyRunId}`, resolveServerUrl()).toString();- if (options.json !== undefined) {- outputJson({ ...res, url }, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(- `${pc.green('✓')} Submitted ${pc.bold(res.checkResult.id)}` +- `${res.checkResult.verdict ? ` (${res.checkResult.verdict})` : ''}` +- `${res.evidence.length > 0 ? ` +${res.evidence.length} evidence` : ''}`,- );- console.log(`${pc.bold('report')}: ${url}`);-}--async function decisionAction(resultId: string, decision: Decision): Promise<void> {- if (decision !== undefined && !DECISIONS.includes(decision)) {- log.error(`decision must be one of: ${DECISIONS.join(', ')}`);- process.exit(1);- }- const client = await getTrpcClient();- await client.verify.submitDecision.mutate({ decision, resultId });- console.log(`${pc.green('✓')} Recorded ${pc.bold(decision)} on result ${pc.bold(resultId)}`);-}--// ── evidence ──--interface EvidenceUploadOptions {- by?: string;- check: string;- content?: string;- desc?: string;- file?: string;- fileId?: string;- json?: boolean | string;- metadata?: string;- type: string;-}--async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<void> {- if ([options.file, options.content, options.fileId].filter(Boolean).length !== 1) {- log.error('Provide exactly one of --file, --file-id or --content');- process.exit(1);- }- const metadata: unknown = options.metadata ? JSON.parse(options.metadata) : undefined;- const client = await getTrpcClient();- await assertReportLanguage(client, [- { path: '--desc', text: options.desc },- ...evidenceCaptionFields('--metadata', metadata),- ]);- let fileId = options.fileId;- let inlineContent = options.content;- if (options.file) {- inlineContent = inlineTextEvidenceForFile(options.file, options.type);- if (inlineContent === undefined) {- const uploaded = await uploadAcceptanceFile(client, options.file, options.json);- if (!uploaded) return;- fileId = uploaded.id;- }- }- const ev = await client.verify.uploadEvidence.mutate({- capturedBy: options.by as any,- checkResultId: options.check,- content: inlineContent,- description: evidenceDescriptionForFile(options.desc, options.file),- fileId,- metadata,- type: options.type as any,- });- if (options.json !== undefined) {- outputJson(ev, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Evidence ${pc.bold(ev.id)}${fileId ? ` (file ${fileId})` : ''}`);-}--async function evidenceListAction(- checkResultId: string,- options: { json?: boolean | string },-): Promise<void> {- const client = await getTrpcClient();- const rows = await client.verify.listEvidence.query({ checkResultId });- if (options.json !== undefined) {- outputJson(rows, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (rows.length === 0) return void console.log('No evidence.');- printTable(- rows.map((e: any) => [- e.id,- e.type,- e.capturedBy ?? '',- e.fileId ? 'file' : 'inline',- truncate(e.description || '', 40),- ]),- ['ID', 'TYPE', 'BY', 'PAYLOAD', 'DESC'],- );-}--async function evidenceDeleteAction(- evidenceId: string,- options: { json?: boolean | string },-): Promise<void> {- const client = await getTrpcClient();- const result = await client.verify.deleteEvidence.mutate({ id: evidenceId });- if (options.json !== undefined) {- outputJson(result, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Deleted evidence ${pc.bold(result.id)}`);-}--// ── report ──--interface ReportUpsertOptions {- content?: string;- failed?: string;- json?: boolean | string;- passed?: string;- run: string;- summary?: string;- total?: string;- uncertain?: string;- verdict?: string;-}--async function reportUpsertAction(options: ReportUpsertOptions): Promise<void> {- const num = (s?: string) => (s === undefined ? undefined : Number.parseInt(s, 10));- const client = await getTrpcClient();- await assertReportLanguage(client, [- { path: '--summary', text: options.summary },- { path: '--content', text: options.content },- ]);- const created = await client.verify.upsertReport.mutate({- content: options.content,- failedChecks: num(options.failed),- passedChecks: num(options.passed),- summary: options.summary,- totalChecks: num(options.total),- uncertainChecks: num(options.uncertain),- verdict: options.verdict as any,- verifyRunId: options.run,- });- if (options.json !== undefined) {- outputJson(created, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Report ${pc.bold(created.id)} (${created.verdict ?? '—'})`);-}--async function reportGetAction(runId: string, options: { json?: boolean | string }): Promise<void> {- const client = await getTrpcClient();- const item = await client.verify.getReport.query({ verifyRunId: runId });- if (options.json !== undefined) {- outputJson(item, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (!item) return void console.log('No report.');- console.log(JSON.stringify(item, null, 2));-}--// ── ingest-report (aggregate convenience over the atomic commands) ──--interface IngestReportOptions {- acceptance?: string;- /** Run every local check, including the report language, then stop before publishing. */- dryRun?: boolean;- goal?: string;- json?: boolean | string;- open?: boolean;- operation?: string;- requirement?: string;- source?: string;- subject?: string;- title?: string;-}--async function ingestReportAction(reportDir: string, options: IngestReportOptions): Promise<void> {- const dir = path.resolve(reportDir);- // The guarantee has to hold however the round got here — a project that never- // ran `acceptance install`, or an agent that wrote the round by hand, still- // must not leave evidence binaries untracked in someone's repo.- ensureAcceptanceDirIgnoredFor(dir);- const resultPath = path.join(dir, 'result.json');- if (!existsSync(resultPath)) {- log.error(`result.json not found in ${dir}`);- process.exit(1);- }-- let result: any;- try {- result = JSON.parse(readFileSync(resultPath, 'utf8'));- } catch {- log.error('result.json is not valid JSON');- process.exit(1);- }-- // Unit tests, type-checks and lint gates are preconditions of shipping, not- // things a person accepts — a page full of them buries the checks that- // actually needed a human eye. Screen them out of both the plan and the cases- // before anything is published.- const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result);- const allCases: any[] = Array.isArray(result.cases) ? result.cases : [];- // Freeze each case's id BEFORE filtering: the fallback id is position-based- // (`case-N`), so dropping an earlier case would re-enumerate the survivors in- // the ingest loop — pairing them with the wrong plan items and publishing- // orphaned results into the immutable round.- const casesWithIds = allCases.map((c, index) => ({- case: c,- checkItemId: String(c?.id ?? c?.checkItemId ?? `case-${index + 1}`),- }));- const cases = casesWithIds.filter(({ checkItemId }) => !droppedIds.has(checkItemId));- // Every check was a gate: there is nothing here for a person to accept, and- // publishing an empty round would just create a verdict-less page. Fail before- // the first remote mutation, while the author can still fix the report.- if (cases.length === 0 && allCases.length > 0) {- log.error(- 'every check in this round is a programmatic gate (tests / type-check / lint) — nothing here needs a human decision.',- );- log.error(- ' Verify what the delivery does, shows, or produces, and keep the gates as one line of report.md.',- );- process.exit(1);- }- // Validate every schemaless visualization before the first remote mutation.- // An ingest that cannot render must not create or attach a partial immutable round.- const caseMetadata = cases.map(({ case: item, checkItemId }) => {- try {- return visualizationMetadata(item);- } catch (error) {- throw new Error(- `case ${checkItemId}: ${error instanceof Error ? error.message : String(error)}`,- { cause: error },- );- }- });- const summary = result.summary ?? {};- const reportMdPath = path.join(dir, 'report.md');- const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;-- // What this round is, said to the person who has to accept it, in their- // language — the delivery's own note, not the verification write-up. It- // posts into the discussion as a message from whoever ran the ingest, so a- // reviewer reads it where the conversation already is rather than behind a- // report link.- const proposalMdPath = path.join(dir, 'proposal.md');- const proposal = (- existsSync(proposalMdPath)- ? readFileSync(proposalMdPath, 'utf8')- : typeof result.proposal === 'string'- ? result.proposal- : ''- ).trim();-- // What kind of delivery this report verified (default: coding).- const scenario = scenarioFromResult(result);-- // The scenario's context for the report's scope header. Coding lifts the- // well-known top-level fields (branch / commit / surfaces / PR); every- // other scenario passes result.json `context` through as its own bag.- // `pullRequest` is hoisted: the success output (text and --json) prints- // the PR link after the ingest, whatever the scenario resolved to.- let context: Record<string, unknown> | undefined;- let pullRequest: ReturnType<typeof pullRequestFromResult>;- // Only a PR the report names is a delivery claim; the branch lookup below is- // best-effort provenance and may find a long-lived branch's unrelated PR.- let authoredPullRequest: ReturnType<typeof pullRequestFromResult>;- if (scenario === 'coding') {- const branch = typeof result.branch === 'string' ? result.branch : undefined;- const surfaces = surfacesFromResult(result);- // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the- // report links to it without the author having to remember the field.- authoredPullRequest = pullRequestFromResult(result);- pullRequest = authoredPullRequest ?? pullRequestFromBranch(branch);- const contextEntries = Object.entries({- branch,- commit: typeof result.commit === 'string' ? result.commit : undefined,- entry: typeof result.entry === 'string' ? result.entry : undefined,- pullRequest,- surfaces,- testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,- }).filter(([, v]) => v !== undefined);- context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;- } else {- context = genericContextFromResult(result);- }-- // What the run set out to check, written before it ran. Paired with the- // results by `id`, so the report can show a planned item that never ran.- let plan: VerifyCheckItem[] | undefined = planFromResult(result, droppedIds);-- const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);- const title = options.title ?? result.title;- // The title is the run's identity in every list surface — an untitled- // run renders as a placeholder forever, so say so before it ships.- if (!title) {- log.warn(- 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',- );- }-- const requestedAcceptanceId = options.acceptance?.trim();- if (requestedAcceptanceId && (options.subject || result.subject)) {- log.error(- 'Choose one acceptance target: pass --acceptance <id>, or use --subject/result.json `subject`.',- );- process.exit(1);- }-- // Explicit subject input wins, then result.json, then the authoring topic.- // An external repository has none of those, so create a first-class- // standalone subject instead of making the caller manufacture a Task ID.- let subject = subjectFromResult(result);- let foldTaskRunTopic = false;- if (!requestedAcceptanceId && options.subject) {- const ref = parseSubjectRef(options.subject);- if (!ref) {- log.error(- `--subject must be one of ${acceptanceSubjectTypes.map((t) => `${t}:<id>`).join(' | ')}`,- );- process.exit(1);- }- subject = { ref, requirement: subject?.requirement };- } else if (!requestedAcceptanceId && result.subject && !subject) {- log.error('result.json `subject` is malformed (expected "type:id" or {type,id})');- process.exit(1);- } else if (!requestedAcceptanceId && !subject) {- const ref = subjectFromEnv();- if (ref) subject = { ref };- // Only the ambient topic may be folded onto its Task; an explicit subject stays exact.- foldTaskRunTopic = Boolean(ref);- }- if (!requestedAcceptanceId && !subject) {- subject = {- ref: { subjectId: randomUUID(), subjectType: 'standalone' },- };- }- const requirement = options.requirement ?? subject?.requirement;-- // The overall conclusion, rendered at the top of the report page. Read up- // front so the duplicate check below compares what would land.- const conclusion =- typeof summary.conclusion === 'string'- ? summary.conclusion- : typeof summary.note === 'string'- ? summary.note- : undefined;-- const client = await getTrpcClient();- // Before the first remote mutation: a round in the wrong language cannot be- // fixed in place, only replaced by another immutable round.- const language = await assertReportLanguage(- client,- ingestLanguageFields({- cases,- conclusion,- goal,- plan,- proposal,- report: content,- requirement,- title,- }),- );- if (options.dryRun) {- const checked =- language.status === 'enforced'- ? `report language ${language.locale} ✓`- : language.status === 'unchecked'- ? `report language ${language.locale} (not script-checked)`- : 'report language not set';- if (options.json !== undefined) {- outputJson(- {- cases: cases.length,- dryRun: true,- language: languageSummary(language),- planItems: plan?.length ?? 0,- },- typeof options.json === 'string' ? options.json : undefined,- );- return;- }- console.log(- `${pc.green('✓ Dry run passed')} — ${cases.length} case(s), ${plan?.length ?? 0} plan item(s), ${checked}. Nothing was published.`,- );- return;- }- let acceptance;- let bundle;- if (requestedAcceptanceId) {- bundle = await client.acceptance.getBundle.query({ id: requestedAcceptanceId });- acceptance = bundle.acceptance;- // ID-based reads can cross scopes, but creating a run uses the CLI's scope.- // Reject before any writes instead of leaving an unattachable run behind.- const currentWorkspaceId = resolveWorkspaceId();- const targetWorkspaceId = acceptance.workspaceId ?? undefined;- if (currentWorkspaceId !== targetWorkspaceId) {- const current = currentWorkspaceId ? `workspace "${currentWorkspaceId}"` : 'personal space';- const target = targetWorkspaceId ? `workspace "${targetWorkspaceId}"` : 'personal space';- const hint = targetWorkspaceId- ? `Set LOBEHUB_WORKSPACE_ID=${targetWorkspaceId} for this command and retry.`- : "Unset LOBEHUB_WORKSPACE_ID and run 'lh workspace use --personal', then retry.";- throw new Error(- `Acceptance "${acceptance.id}" belongs to ${target}, but the CLI is using ${current}. ${hint} No run was created.`,- );- }- if (targetWorkspaceId) {- // Revoked membership can make the server fall back to personal scope- // even when the locally selected workspace still matches the target.- const workspace = await client.workspace.getById.query();- if (workspace?.id !== targetWorkspaceId) {- throw new Error(- `The server did not resolve workspace "${targetWorkspaceId}" for this account. Check your access with 'lh workspace list' before retrying. No run was created.`,- );- }- }- subject = {- ref: {- subjectId: acceptance.subjectId,- subjectType: acceptance.subjectType,- },- };- } else {- acceptance = await client.acceptance.ensure.mutate({- requirement,- subjectId: subject!.ref.subjectId,- subjectType: subject!.ref.subjectType,- ...(foldTaskRunTopic ? { foldTaskRunTopic } : {}),- ...(subject!.ref.subjectType === 'standalone' && (title || goal)- ? { title: title || goal }- : {}),- });- // The server may fold the subject (a Task's run topic lands on the Task).- subject = {- ...subject!,- ref: { subjectId: acceptance.subjectId, subjectType: acceptance.subjectType },- };- // A subject's acceptance may already hold rounds; this one has to line up- // with them exactly as an explicit `--acceptance` round does.- bundle = await client.acceptance.getBundle.query({ id: acceptance.id });- }- plan = reuseSourceCriteria(plan, bundle?.checks);-- const identicalRound = findIdenticalLatestRound(bundle?.rounds, {- plan,- report: { content, summary: conclusion },- });- if (identicalRound) {- log.error(- `This report is identical to round ${identicalRound.roundIndex ?? '?'} (${identicalRound.id}) — nothing new to publish.`,- );- log.error(- ` To replace that round, delete it first: lh acceptance run delete ${identicalRound.id}`,- );- process.exit(1);- }- // The in-app conversation that ran this harness, if any (env-supplied).- // Strictly the authoring conversation. `--operation` names the Agent Run- // under test and is passed to `createRun` below — a different relation.- const origin = originFromEnv();- // 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') {- log.error(- `Acceptance is already ${acceptance.status}. Reopen it before publishing another round.`,- );- process.exit(1);- }-- // Every ingest is an immutable verification snapshot. A repair or- // re-verification is another round on the same acceptance, unless the- // acceptance still holds a draft round: the server folds this run into it.- const run = await client.verify.createRun.mutate({- context,- goal,- metadata: newRunMetadata,- operationId: options.operation,- plan,- scenario,- source: options.source as any,- title,- });- // 1c. Chain the session onto its subject's acceptance as the next round- // BEFORE the report lands, so the report-time status rollup already- // sees the aggregate. Results and the report go to the round the server- // returns, which is the draft round when this run was folded into one.- const acceptanceId = acceptance.id;- const attached = await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: run.id });- // Folding preserves the draft's checks and their evidence requirements.- plan = attached?.plan ?? plan;- const runId = attached?.id ?? run.id;- if (runId !== run.id)- console.log(pc.dim(`Folded into the acceptance's draft round ${attached.roundIndex ?? ''}`));- // The chained round's index — `?r=<roundIndex>` on the acceptance URL- // deep-links this round's report as the fixed snapshot view.- const roundIndex = attached?.roundIndex ?? null;- // A `supersedes` entry that names no check of this acceptance folds nothing:- // the old row would stay on the page as if never replaced. An older server- // does not report these, so treat the field as optional.- const unresolvedSupersedes: string[] = attached?.unresolvedSupersedes ?? [];- if (unresolvedSupersedes.length > 0) {- log.warn(- `supersedes names no check of this acceptance, so nothing was replaced: ${unresolvedSupersedes.join(', ')}. Name it by a plan item id from an earlier round or a check id from \`lh acceptance view --json\`.`,- );- }- const acceptanceUrl = new URL(- `/acceptance/${encodeURIComponent(acceptanceId)}`,- resolveServerUrl(),- ).toString();- const roundUrl =- roundIndex === null ? null : `${acceptanceUrl}?r=${encodeURIComponent(String(roundIndex))}`;-- // 2. Ingest each case as a check result + its evidence. `checkItemId` is- // the stable key within this immutable run.- const seenCheckItemIds = new Set<string>();- let evidenceCount = 0;- let inlined = 0;- const failedEvidence: (FailedReportEvidence & { checkItemId: string })[] = [];- const missingEvidence: { checkItemId: string; types: EvidenceType[] }[] = [];- const publishedVerdicts: Verdict[] = [];- for (const [index, { case: c, checkItemId }] of cases.entries()) {- seenCheckItemIds.add(checkItemId);- const verdict = toVerdict(c.result ?? c.status ?? c.verdict);- const observation = c.keyObservation ?? c.observation ?? c.note;- const checkInput = {- checkItemId,- checkItemIndex: index,- checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,- metadata: caseMetadata[index],- required: c.required ?? true,- // The case's key observation is recorded as Toulmin evidence; a real- // remediation hint (if the report provides one) goes to `suggestion`.- // Absent → explicit `null`, so this immutable snapshot records the- // absence instead of relying on upsert defaults.- suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,- toulmin: typeof observation === 'string' ? { evidence: observation } : null,- verdict,- verifierType: 'agent' as const,- verifyRunId: runId,- };- const checkResult = await client.verify.ingestResult.mutate(checkInput);- const uploaded = await uploadReportEvidence(client, {- checkResultId: checkResult.id,- dir,- evidence: c.evidence,- });- evidenceCount += uploaded.count;- inlined += uploaded.inlined;- failedEvidence.push(...uploaded.failedEvidence.map((failure) => ({ ...failure, checkItemId })));- const config = plan?.find((item) => item.id === checkItemId)?.verifierConfig as- VerifyAgentPlanConfig | undefined;- const required = config?.requiredEvidence;- const gaps = [...new Set(required?.map((spec) => spec.type) ?? [])].filter(- (type) => !uploaded.types.has(type),- );- const publishedVerdict = gaps.length > 0 && verdict === 'passed' ? 'uncertain' : verdict;- publishedVerdicts.push(publishedVerdict);- if (gaps.length > 0) {- missingEvidence.push({ checkItemId, types: gaps });- const limitation = `Required evidence not published: ${gaps.join(', ')}.`;- log.warn(`${checkItemId}: ${limitation}`);- await client.verify.ingestResult.mutate({- ...checkInput,- toulmin: { ...checkInput.toulmin, limitation },- verdict: publishedVerdict,- });- }- }-- const unexecuted = plan?.filter((item) => !seenCheckItemIds.has(item.id)) ?? [];- for (const item of unexecuted) {- const config = item.verifierConfig as VerifyAgentPlanConfig;- const types = [...new Set(config.requiredEvidence?.map((spec) => spec.type) ?? [])];- if (types.length === 0) continue;- missingEvidence.push({ checkItemId: item.id, types });- // Count the gap without inventing an execution result for an unexecuted check.- publishedVerdicts.push('uncertain');- log.warn(`${item.id}: not executed; required evidence not published: ${types.join(', ')}.`);- }-- // 3. Write the report. `summary` is the overall conclusion (read above);- // `content` is the full markdown detail.- // A 0-100 quality score lands on overallConfidence (0-1); the report page- // surfaces it as the `score` stat.- const score =- typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;- // The authored counts describe the report the author wrote. Once a- // programmatic-test check is screened out they no longer match what was- // published, so recount the landed cases and unexecuted evidence gaps — a- // stats block that disagrees with the visible check list is worse than no stats.- const recount = cases.length !== allCases.length || missingEvidence.length > 0;- const counted = (verdict: Verdict) => publishedVerdicts.filter((v) => v === verdict).length;- const derivedVerdict = deriveReportVerdict(publishedVerdicts.map((verdict) => ({ verdict })));- const reportVerdict =- summary.verdict && cases.length === allCases.length- ? toVerdict(summary.verdict)- : derivedVerdict;- await client.verify.upsertReport.mutate({- content,- failedChecks: recount ? counted('failed') : summary.failed,- overallConfidence: score,- passedChecks: recount ? counted('passed') : summary.passed,- summary: conclusion,- totalChecks: recount ? publishedVerdicts.length : (summary.total ?? cases.length),- uncertainChecks: recount- ? counted('uncertain') || undefined- : (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,- // Missing evidence cannot be overridden by an authored "passed" summary.- // Keep a real failure rather than hiding it behind an evidence warning.- verdict:- missingEvidence.length > 0- ? reportVerdict === 'failed' || derivedVerdict === 'failed'- ? 'failed'- : 'uncertain'- : reportVerdict,- verifyRunId: runId,- });-- // 4. Post the round's note. It renders as part of the round rather than as- // another message, so the discussion reads "<agent> shipped round N"- // followed by what it says. Last, and never fatal: the round itself is- // the deliverable, and a failed comment must not strand a published round- // behind an aborted ingest.- let proposalPosted = false;- if (proposal) {- try {- await client.acceptanceComment.create.mutate({- acceptanceId,- // Signed by the agent that produced the round, not by whoever's- // credentials carried the ingest. Absent outside an agent run, and- // then it falls back to the account.- authorAgentId: process.env.LOBEHUB_AGENT_ID || undefined,- // Derived from the round, so re-ingesting the same round edits nothing- // and duplicates nothing.- clientId: `proposal:${runId}`,- content: proposal,- contextRunId: runId,- kind: 'proposal',- });- proposalPosted = true;- } catch (e) {- log.warn(`proposal not posted to the discussion: ${String(e)}`);- }- }-- // 5. Link the PR to the acceptance itself. The round's context is a- // snapshot of this ingest; the acceptance is what the PR delivers, and- // the page reads its PRs from there. Only the report's own PR is linked:- // a branch-inferred one stays round provenance. Never fatal: an older- // server lacks the procedure, and the round itself is the deliverable.- if (authoredPullRequest?.url) {- try {- await client.acceptance.linkPullRequest.mutate({- id: acceptanceId,- title:- typeof authoredPullRequest.title === 'string' ? authoredPullRequest.title : undefined,- url: String(authoredPullRequest.url),- });- } catch (e) {- log.warn(`pull request not linked to the acceptance: ${String(e)}`);- }- }-- // A case with no matching plan item means the run checked something it- // never planned — worth saying out loud, but not a failure. Only- // meaningful against a plan that actually names something: with no plan- // (or a cleared one) every case is trivially "unplanned", which is noise.- const unplanned = plan?.length- ? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))- : [];-- const recovery = failedEvidence.some((failure) => failure.reason === 'storage_quota')- ? await storageQuotaRecovery(client)- : undefined;- const partial = failedEvidence.length > 0 || missingEvidence.length > 0;- if (partial) {- process.exitCode = 1;- log.warn(- 'Report saved, but evidence publication is incomplete. Keep the local artifacts; retry only the missing evidence, not the whole ingest. Supplementing evidence does not change recorded verdicts.',- );- if (missingEvidence.some(({ checkItemId }) => !seenCheckItemIds.has(checkItemId))) {- log.warn(- 'Unexecuted checks have no result to attach evidence to. Execute them and publish a new round on the same acceptance; do not re-ingest this unchanged report.',- );- }- if (recovery) log.warn(recovery.message);- }-- if (options.json !== undefined) {- outputJson(- {- acceptanceId,- acceptanceUrl,- cases: cases.length,- droppedProgrammaticChecks: droppedLabels,- evidence: evidenceCount,- failedEvidence,- inlined,- missingEvidence,- origin,- planItems: plan?.length ?? 0,- proposalPosted,- publicationStatus: partial ? 'partial' : 'complete',- pullRequest,- recovery,- roundIndex,- roundUrl,- scenario,- subject: subject!.ref,- unexecuted: unexecuted.map((item) => item.id),- unplanned,- unresolvedSupersedes,- verifyRunId: runId,- },- typeof options.json === 'string' ? options.json : undefined,- );- return;- }-- console.log(- `${partial ? pc.yellow('⚠ Partially published') : pc.green('✓ Ingested')} ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` +- `${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}` +- `${droppedLabels.length > 0 ? pc.yellow(` — ${droppedLabels.length} programmatic-test check(s) dropped`) : ''}`,- );- for (const failure of failedEvidence) {- console.log(`${pc.yellow('retry (POSIX shell)')}: ${failure.retryCommand}`);- console.log(- `${pc.dim('retryArgs (lh, shell disabled)')}: ${JSON.stringify(failure.retryArgs)}`,- );- }- if (plan?.length) {- console.log(- `${pc.bold('plan')}: ${plan.length} item(s)` +- `${unexecuted.length > 0 ? pc.yellow(` — ${unexecuted.length} planned but not executed`) : ''}` +- `${unplanned.length > 0 ? pc.dim(` — ${unplanned.length} unplanned case(s)`) : ''}`,- );- }- if (proposalPosted) console.log(`${pc.bold('proposal')}: posted to the discussion`);- if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);- if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);- console.log(`${pc.bold('verifyRunId')}: ${runId} ${pc.dim('(immutable snapshot)')}`);- const subjectLabel =- subject!.ref.subjectType === 'standalone'- ? 'standalone'- : `${subject!.ref.subjectType}:${subject!.ref.subjectId}`;- console.log(`${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subjectLabel})`)}`);- if (options.open || partial) {- // The acceptance page is the only link surfaced to users — the raw /verify- // page stays internal. `?r=<roundIndex>` is this round's fixed snapshot.- console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);- if (roundUrl) {- console.log(`${pc.bold('round snapshot')}: ${roundUrl}`);- }- }-}--// ── Option wiring (shared by both trees) ───────────────────-//-// Each `withXxxOptions` applies the flag set to a freshly-created command, so-// the canonical and deprecated spellings always accept exactly the same flags.--function withInstallOptions(cmd: Command): Command {- return cmd- .option('--dir <path>', 'Target working directory (default: current dir)')- .option('--skill <id>', 'Skill identifier to pull', 'acceptance')- .option(- '--skill-version <version>',- 'Install a specific skill tag (default: latest default-branch source)',- )- .option('--force', 'Overwrite existing skill files')- .option('--json [fields]', 'Output JSON');-}--function withRunCreateOptions(cmd: Command): Command {- return cmd- .option('--source <source>', 'agent | agent-testing', 'agent-testing')- .option('--operation <id>', 'Link to an existing Agent Run')- .option('--title <title>', 'Session title')- .option('--goal <goal>', 'Goal/task being verified')- .option('--json [fields]', 'Output JSON');-}--function withRunDeleteOptions(cmd: Command): Command {- return cmd- .option('-y, --yes', 'Skip the confirmation prompt')- .option('--json [fields]', 'Output JSON');-}--function withResultIngestOptions(cmd: Command): Command {- return cmd- .requiredOption('--run <verifyRunId>', 'Target session id')- .requiredOption('--check <checkItemId>', 'Stable check item id within the session')- .requiredOption('--verdict <verdict>', 'passed|failed|uncertain')- .option('--title <title>', 'Check title')- .option('--index <n>', 'Display index')- .option('--confidence <n>', '0-1 confidence')- .option('--status <status>', 'pending|running|passed|failed|skipped (derived from verdict)')- .option('--evidence <text>', 'Key observation (stored as Toulmin evidence)')- .option('--suggestion <text>', 'Remediation hint')- .option('--soft', 'Non-blocking (required=false); defaults to blocking')- .option('--json [fields]', 'Output JSON');-}--function withResultListOptions(cmd: Command): Command {- return cmd- .option('--run <verifyRunId>', 'List by verification session')- .option('--operation <operationId>', 'List by Agent Run')- .option('--json [fields]', 'Output JSON');-}--function withSubmitOptions(cmd: Command): Command {- return cmd- .option('--run <verifyRunId>', 'Target verification session (or use --operation)')- .option('--operation <operationId>', 'Resolve the session from an Agent Run operation id')- .requiredOption('--item <checkItemId>', 'Plan item id (checkItemId)')- .option('--type <type>', 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript')- .option('--file <path>', 'Local file to upload as the evidence artifact')- .option('--content <text>', 'Inline text payload (instead of a file)')- .option('--verdict <verdict>', 'passed|failed|uncertain')- .option('--title <text>', 'Check item title snapshot')- .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')- .option('--desc <text>', 'Human-readable caption for the evidence')- .option('--json [fields]', 'Output JSON');-}--function withEvidenceUploadOptions(cmd: Command): Command {- return cmd- .requiredOption('--check <checkResultId>', 'Target check result id')- .requiredOption(- '--type <type>',- 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript',- )- .option('--file <path>', 'Local file to upload as the artifact')- .option('--file-id <id>', 'Attach an already-uploaded file without uploading it again')- .option('--content <text>', 'Inline text payload (instead of a file)')- .option('--metadata <json>', 'Evidence metadata, preserved when retrying an attachment')- .option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')- .option('--desc <text>', 'Human-readable caption')- .option('--json [fields]', 'Output JSON');-}--function withReportUpsertOptions(cmd: Command): Command {- return cmd- .requiredOption('--run <verifyRunId>', 'Target session id')- .option('--verdict <verdict>', 'passed|failed|uncertain')- .option('--summary <text>', 'Short summary')- .option('--content <markdown>', 'Full markdown body')- .option('--total <n>', 'Total checks')- .option('--passed <n>', 'Passed checks')- .option('--failed <n>', 'Failed checks')- .option('--uncertain <n>', 'Uncertain checks')- .option('--json [fields]', 'Output JSON');-}--function withIngestReportOptions(cmd: Command): Command {- return cmd- .option('--source <source>', 'agent | agent-testing', 'agent-testing')- .option('--operation <id>', 'Link the session to an existing Agent Run')- .option('--acceptance <id>', 'Append this round to an existing acceptance')- .option('--title <title>', 'Override the session title')- .option('--goal <goal>', 'The goal/task being verified')- .option(- '--subject <type:id>',- 'Attach to a task/topic/document (defaults to the current topic; otherwise standalone)',- )- .option(- '--requirement <text>',- 'Acceptance requirement recorded when the aggregate is first created',- )- .option('--open', 'Print the in-app URL to open the report')- .option(- '--dry-run',- 'Validate the report (including its language) without publishing; works on a plan-only result.json',- )- .option('--json [fields]', 'Output JSON');-}--// ── Canonical tree: `lh acceptance install` + `lh acceptance run …` ──--/**- * The run-scoped acceptance commands. A run is one immutable round of a- * subject's acceptance; its results, evidence, and report are its sub-resources.- * Attached to the first-class `lh acceptance` command.- */-export function attachAcceptanceRunCommands(acceptance: Command): void {- withInstallOptions(- acceptance- .command('install')- .description('Install the latest acceptance skill source into .agents/skills/acceptance'),- ).action((options: InstallOptions) => installAction(options, createPublicLambdaClient()));-- withInstallOptions(- acceptance- .command('update')- .description('Download the latest skill source, replacing its files and re-wiring harnesses'),- ).action((options: InstallOptions) =>- installAction({ ...options, force: true }, createPublicLambdaClient()),- );-- const run = acceptance- .command('run')- .description('Acceptance rounds (immutable verification snapshots)');-- withIngestReportOptions(- run- .command('ingest <reportDir>')- .description(- 'Ingest a local agent-testing report (result.json + report.md + proposal.md + assets) as a new round',- ),- ).action(ingestReportAction);-- withRunCreateOptions(- run.command('create').description('Create a standalone round (verification session)'),- ).action(runCreateAction);-- run- .command('list')- .description('List recent rounds')- .option('--json [fields]', 'Output JSON')- .action(runListAction);-- run- .command('get <runId>')- .description('Show a round')- .option('--json [fields]', 'Output JSON')- .action(runGetAction);-- withRunDeleteOptions(- run- .command('delete <runId>')- .description('Delete a round (cascades its results, evidence and report)'),- ).action(runDeleteAction);-- const result = run.command('result').description('Check results within a round');- withResultIngestOptions(- result- .command('ingest')- .description('Upsert one check result by (run, checkItemId) from a supplied verdict'),- ).action(resultIngestAction);- withResultListOptions(- result- .command('list')- .description('List check results — by round (--run) or by Agent Run (--operation)'),- ).action(resultListAction);- withSubmitOptions(- result- .command('submit')- .description('Submit a check item — upsert its result and attach evidence in one call'),- ).action(submitAction);- result- .command('decision <resultId> <decision>')- .description(`Record human feedback on a result (${DECISIONS.join('|')})`)- .action(decisionAction);-- const evidence = run.command('evidence').description('Evidence artifacts within a round');- withEvidenceUploadOptions(- evidence- .command('upload')- .description('Attach an evidence artifact (file or inline text) to a check result'),- ).action(evidenceUploadAction);- evidence- .command('list <checkResultId>')- .description('List evidence for a check result')- .option('--json [fields]', 'Output JSON')- .action(evidenceListAction);- evidence- .command('delete <evidenceId>')- .description('Delete an evidence artifact')- .option('--json [fields]', 'Output JSON')- .action(evidenceDeleteAction);-- const report = run.command('report').description('The narrative report of a round');- withReportUpsertOptions(- report.command('upsert').description('Write (overwrite) the report for a round'),- ).action(reportUpsertAction);- report- .command('get <runId>')- .description('Show the report for a round')- .option('--json [fields]', 'Output JSON')- .action(reportGetAction);-}--// ── Deprecated aliases: keep the old `lh verify …` spellings working ──--/** Warn once that a `lh verify` spelling has moved under `lh acceptance`. */-function deprecate(cmd: Command, replacement: string): Command {- return cmd.hook('preAction', () => {- log.warn(- `\`lh verify ${cmd.name()}\` is deprecated — use \`${replacement}\` (removed in a future release)`,- );- });-}--/**- * The pre-move `lh verify …` command surface, kept as thin aliases that wire the- * exact same actions. Scheduled for removal once callers migrate to- * `lh acceptance`. Layout mirrors the original flat shape so existing scripts and- * tests keep working.- */-export function attachDeprecatedVerifyRunAliases(verify: Command): void {- // Both legacy spellings — `verify init` (server pull) and `verify install`- // (the old bundled-skill installer) — converge on `acceptance install`.- deprecate(- withInstallOptions(- verify.command('init').description('Deprecated — use `lh acceptance install`'),- ),- 'lh acceptance install',- ).action(async (options: InstallOptions) => installAction(options, await getTrpcClient()));-- deprecate(- withInstallOptions(- verify.command('install').description('Deprecated — use `lh acceptance install`'),- ),- 'lh acceptance install',- ).action(async (options: InstallOptions) => installAction(options, await getTrpcClient()));-- deprecate(- withIngestReportOptions(- verify- .command('ingest-report <reportDir>')- .description('Deprecated — use `lh acceptance run ingest`'),- ),- 'lh acceptance run ingest',- ).action(ingestReportAction);-- const run = verify.command('run').description('Deprecated — use `lh acceptance run`');- deprecate(- withRunCreateOptions(- run.command('create').description('Deprecated — use `lh acceptance run create`'),- ),- 'lh acceptance run create',- ).action(runCreateAction);- run- .command('list')- .description('Deprecated — use `lh acceptance run list`')- .option('--json [fields]', 'Output JSON')- .hook('preAction', () =>- log.warn('`lh verify run list` is deprecated — use `lh acceptance run list`'),- )- .action(runListAction);- run- .command('get <runId>')- .description('Deprecated — use `lh acceptance run get`')- .option('--json [fields]', 'Output JSON')- .hook('preAction', () =>- log.warn('`lh verify run get` is deprecated — use `lh acceptance run get`'),- )- .action(runGetAction);- deprecate(- withRunDeleteOptions(- run.command('delete <runId>').description('Deprecated — use `lh acceptance run delete`'),- ),- 'lh acceptance run delete',- ).action(runDeleteAction);-- const result = verify- .command('result')- .description('Deprecated — use `lh acceptance run result`');- deprecate(- withResultIngestOptions(- result.command('ingest').description('Deprecated — use `lh acceptance run result ingest`'),- ),- 'lh acceptance run result ingest',- ).action(resultIngestAction);- deprecate(- withResultListOptions(- result.command('list').description('Deprecated — use `lh acceptance run result list`'),- ),- 'lh acceptance run result list',- ).action(resultListAction);-- deprecate(- withSubmitOptions(- verify.command('submit').description('Deprecated — use `lh acceptance run result submit`'),- ),- 'lh acceptance run result submit',- ).action(submitAction);-- verify- .command('decision <resultId> <decision>')- .description('Deprecated — use `lh acceptance run result decision`')- .hook('preAction', () =>- log.warn('`lh verify decision` is deprecated — use `lh acceptance run result decision`'),- )- .action(decisionAction);-- const evidence = verify- .command('evidence')- .description('Deprecated — use `lh acceptance run evidence`');- deprecate(- withEvidenceUploadOptions(- evidence- .command('upload')- .description('Deprecated — use `lh acceptance run evidence upload`'),- ),- 'lh acceptance run evidence upload',- ).action(evidenceUploadAction);- evidence- .command('list <checkResultId>')- .description('Deprecated — use `lh acceptance run evidence list`')- .option('--json [fields]', 'Output JSON')- .hook('preAction', () =>- log.warn('`lh verify evidence list` is deprecated — use `lh acceptance run evidence list`'),- )- .action(evidenceListAction);- evidence- .command('delete <evidenceId>')- .description('Deprecated — use `lh acceptance run evidence delete`')- .option('--json [fields]', 'Output JSON')- .hook('preAction', () =>- log.warn(- '`lh verify evidence delete` is deprecated — use `lh acceptance run evidence delete`',- ),- )- .action(evidenceDeleteAction);-- const report = verify- .command('report')- .description('Deprecated — use `lh acceptance run report`');- deprecate(- withReportUpsertOptions(- report.command('upsert').description('Deprecated — use `lh acceptance run report upsert`'),- ),- 'lh acceptance run report upsert',- ).action(reportUpsertAction);- report- .command('get <runId>')- .description('Deprecated — use `lh acceptance run report get`')- .option('--json [fields]', 'Output JSON')- .hook('preAction', () =>- log.warn('`lh verify report get` is deprecated — use `lh acceptance run report get`'),- )- .action(reportGetAction);-}diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.tsdeleted file mode 100644index 9353e4bcddc..00000000000--- a/apps/cli/src/commands/verify.test.ts+++ /dev/null@@ -1,1596 +0,0 @@-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import path from 'node:path';--import { Command } from 'commander';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { log } from '../utils/logger';-import {- deriveReportVerdict,- evidenceTypeForFile,- formatAnnotationRegion,- formatDisputedChapter,- genericContextFromResult,- inlineTextEvidenceForFile,- originFromEnv,- parseSubjectRef,- planFromResult,- registerVerifyCommand,- reportEvidence,- scenarioFromResult,- screenProgrammaticTestChecks,- subjectFromEnv,- subjectFromResult,- surfacesFromResult,- visualizationMetadata,-} from './verify';-import { registerAcceptanceCommands } from './verifyAcceptance';-import { evidenceDescriptionForFile } from './verifyHelpers';--const { mockTrpcClient } = vi.hoisted(() => ({- mockTrpcClient: {- user: {- getUserState: {- query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),- },- },- verify: {- createRubric: { mutate: vi.fn() },- deleteRun: { mutate: vi.fn() },- getRubric: { query: vi.fn() },- updateRubric: { mutate: vi.fn() },- },- },-}));--const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({- getTrpcClient: vi.fn(),-}));--vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));-vi.mock('../settings', () => ({- loadActiveWorkspace: () => undefined,- resolveServerUrl: () => 'https://app.lobehub.com',-}));-describe('verify rubric config commands', () => {- let consoleSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- mockTrpcClient.verify.createRubric.mutate.mockReset().mockResolvedValue({ id: 'rub-1' });- mockTrpcClient.verify.updateRubric.mutate.mockReset().mockResolvedValue(undefined);- mockTrpcClient.verify.getRubric.query.mockReset();- });-- afterEach(() => consoleSpy.mockRestore());-- const run = async (args: string[]) => {- const program = new Command();- program.exitOverride();- registerVerifyCommand(program);- await program.parseAsync(['node', 'lh', 'verify', ...args]);- };-- it('passes maxRepairRounds config when creating a rubric', async () => {- await run(['rubric', 'create', '-t', 'Standard', '--max-repair-rounds', '3']);-- expect(mockTrpcClient.verify.createRubric.mutate).toHaveBeenCalledWith({- config: { maxRepairRounds: 3 },- description: undefined,- title: 'Standard',- });- });-- it('omits config when no max-repair-rounds flag is given', async () => {- await run(['rubric', 'create', '-t', 'Standard']);-- expect(mockTrpcClient.verify.createRubric.mutate).toHaveBeenCalledWith({- config: undefined,- description: undefined,- title: 'Standard',- });- });-- it('updates only the config when max-repair-rounds is passed', async () => {- await run(['rubric', 'update', 'rub-1', '--max-repair-rounds', '0']);-- expect(mockTrpcClient.verify.updateRubric.mutate).toHaveBeenCalledWith({- id: 'rub-1',- value: { config: { maxRepairRounds: 0 } },- });- });-- it('views a rubric and prints its repair-round config', async () => {- mockTrpcClient.verify.getRubric.query.mockResolvedValue({- config: { maxRepairRounds: 4 },- description: 'desc',- id: 'rub-1',- title: 'Standard',- });-- await run(['rubric', 'view', 'rub-1']);-- expect(mockTrpcClient.verify.getRubric.query).toHaveBeenCalledWith({ id: 'rub-1' });- const printed = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');- expect(printed).toContain('Standard');- expect(printed).toContain('4');- });-});--describe('verify run delete command', () => {- let consoleSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- mockTrpcClient.verify.deleteRun.mutate.mockReset().mockResolvedValue({- id: 'run-1',- success: true,- });- });-- afterEach(() => consoleSpy.mockRestore());-- const run = async (args: string[]) => {- const program = new Command();- program.exitOverride();- registerVerifyCommand(program);- await program.parseAsync(['node', 'lh', 'verify', ...args]);- };-- it('deletes the run without prompting when --yes is passed', async () => {- await run(['run', 'delete', 'run-1', '--yes']);-- expect(mockTrpcClient.verify.deleteRun.mutate).toHaveBeenCalledWith({ verifyRunId: 'run-1' });- });-});--describe('verify evidence upload command', () => {- let exitSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- mockGetTrpcClient.mockReset();- exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {- throw new Error(`process.exit ${code}`);- }) as any);- });-- afterEach(() => {- exitSpy.mockRestore();- });-- const run = async (args: string[]) => {- const program = new Command();- program.exitOverride();- registerVerifyCommand(program);- await program.parseAsync(['node', 'lh', 'verify', ...args]);- };-- it('rejects evidence with both file and inline content', async () => {- await expect(- run([- 'evidence',- 'upload',- '--check',- 'result-1',- '--type',- 'text',- '--file',- 'artifact.txt',- '--content',- 'inline payload',- ]),- ).rejects.toThrow('process.exit 1');-- expect(exitSpy).toHaveBeenCalledWith(1);- expect(mockGetTrpcClient).not.toHaveBeenCalled();- });-});--describe('reportEvidence — comparison normalization', () => {- it('accepts plain string paths', () => {- expect(reportEvidence('assets/a.png')).toEqual([{ path: 'assets/a.png' }]);- expect(reportEvidence(['a.png', 'b.png']).map((e) => e.path)).toEqual(['a.png', 'b.png']);- });-- it('keeps a comparison that carries both an id and a before/after role', () => {- const [before, after] = reportEvidence([- { comparison: { id: 'row', role: 'before' }, path: 'before.png' },- { comparison: { id: 'row', label: '改后', role: 'after' }, path: 'after.png' },- ]);-- expect(before.comparison).toEqual({- id: 'row',- label: undefined,- layout: undefined,- role: 'before',- });- expect(after.comparison).toEqual({- id: 'row',- label: '改后',- layout: undefined,- role: 'after',- });- });-- it('passes a vertical layout through and ignores any other value', () => {- const forLayout = (layout: unknown) =>- reportEvidence([{ comparison: { id: 'row', layout, role: 'before' }, path: 'a.png' }])[0]- .comparison?.layout;-- expect(forLayout('vertical')).toBe('vertical');- // Side by side is the default, so anything unrecognized simply falls back to it.- expect(forLayout('horizontal')).toBeUndefined();- expect(forLayout('diagonal')).toBeUndefined();- expect(forLayout(undefined)).toBeUndefined();- });-- // The report viewer pairs on `id`, so an id-less comparison could never render- // side by side — dropping it here keeps the upload honest instead of shipping- // metadata the UI silently ignores.- it('drops a comparison missing an id, keeping the image as ordinary evidence', () => {- const [item] = reportEvidence([{ comparison: { role: 'before' }, path: 'before.png' }]);-- expect(item).toEqual({ comparison: undefined, description: undefined, path: 'before.png' });- });-- it('drops a comparison whose role is absent or unrecognized', () => {- expect(- reportEvidence([{ comparison: { id: 'x', role: 'middle' }, path: 'a.png' }])[0].comparison,- ).toBeUndefined();- expect(- reportEvidence([{ comparison: { id: 'x' }, path: 'a.png' }])[0].comparison,- ).toBeUndefined();- });-- // The flat shape (`comparison: "row", role: "before"`) is the easiest one to- // write from memory, and it used to be the ONLY malformed shape that produced- // no warning: the guard parsed the field into an object first, so a string- // read as "no comparison at all" and the ingest exited clean while the page- // rendered two unpaired images.- it('warns and drops a comparison that is not an object', () => {- vi.mocked(log.warn).mockClear();-- const [item] = reportEvidence([- { comparison: 'row', path: 'before.png', role: 'before' } as unknown,- ]);-- expect(item).toEqual({ comparison: undefined, description: undefined, path: 'before.png' });- expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('before.png'));- });-- it('warns for every malformed comparison shape, and stays quiet for a valid or absent one', () => {- const warnsFor = (comparison: unknown) => {- vi.mocked(log.warn).mockClear();- reportEvidence([{ comparison, path: 'a.png' } as unknown]);- return vi.mocked(log.warn).mock.calls.length > 0;- };-- expect(warnsFor('row')).toBe(true);- expect(warnsFor(['row'])).toBe(true);- expect(warnsFor({ id: 'row' })).toBe(true);- expect(warnsFor({ id: 'row', role: 'middle' })).toBe(true);-- // Falsy but present: someone wrote the field, so it is malformed rather- // than absent. A truthiness guard would drop these without a word.- expect(warnsFor('')).toBe(true);- expect(warnsFor(0)).toBe(true);- expect(warnsFor(false)).toBe(true);- expect(warnsFor(Number.NaN)).toBe(true);-- // Absent is null/undefined only — an evidence item without a pair.- expect(warnsFor({ id: 'row', role: 'before' })).toBe(false);- expect(warnsFor(undefined)).toBe(false);- expect(warnsFor(null)).toBe(false);- });-- it('supports the `file` / `desc` aliases and skips entries with no path', () => {- expect(- reportEvidence([{ desc: 'a shot', file: 'a.png' }, { comparison: { id: 'x' } }]),- ).toEqual([{ comparison: undefined, description: 'a shot', path: 'a.png' }]);- });-});--describe('reportEvidence — video chapters', () => {- beforeEach(() => {- vi.mocked(log.warn).mockClear();- });-- it('carries well-formed chapters on a video, sorted by time', () => {- const [item] = reportEvidence([- {- chapters: [- { kind: 'check', note: 'no skeleton', t: 7.9 },- { kind: 'step', label: 'Scroll #1', t: 2 },- ],- path: 'proof/scroll.mp4',- },- ]);-- expect(item.chapters).toEqual([- { kind: 'step', label: 'Scroll #1', t: 2 },- { kind: 'check', note: 'no skeleton', t: 7.9 },- ]);- expect(log.warn).not.toHaveBeenCalled();- });-- // A dropped marker is a claim the agent believes the reviewer will see.- it('names how many markers it dropped and why', () => {- const [item] = reportEvidence([- {- chapters: [- { kind: 'step', label: 'Open', t: 0 },- { kind: 'check', t: 3 },- ],- path: 'clip.webm',- },- ]);-- expect(item.chapters).toEqual([{ kind: 'step', label: 'Open', t: 0 }]);- expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('dropped 1 of 2 chapters'));- });-- it('ignores chapters on a still image, and a chapters field that is not a list', () => {- expect(- reportEvidence([{ chapters: [{ kind: 'step', label: 'x', t: 0 }], path: 'a.png' }])[0]- .chapters,- ).toBeUndefined();- expect(reportEvidence([{ chapters: 'intro', path: 'a.mp4' }])[0].chapters).toBeUndefined();- expect(log.warn).toHaveBeenCalledTimes(2);- });-});--describe('visualizationMetadata', () => {- const input = {- datasets: [- {- fields: [- { key: 'name', type: 'string' },- { key: 'before', type: 'number', unit: 'ms' },- { key: 'after', type: 'number', unit: 'ms' },- ],- id: 'metrics',- rows: [{ after: 24.8, before: 257, name: 'GC self-time' }],- },- ],- visualizations: [- {- dataset: 'metrics',- encoding: { after: 'after', before: 'before', label: 'name' },- id: 'performance',- type: 'metric-comparison',- version: 1,- },- ],- };-- it('normalizes datasets and views into versioned check-result metadata', () => {- expect(visualizationMetadata(input)).toEqual({- visualization: {- datasets: input.datasets,- schemaVersion: 1,- views: input.visualizations,- },- });- });-- it('rejects a view that references a missing dataset', () => {- expect(() =>- visualizationMetadata({- ...input,- visualizations: [{ ...input.visualizations[0], dataset: 'missing' }],- }),- ).toThrow('dataset');- });-- it('rejects cells outside the declared field schema', () => {- expect(() =>- visualizationMetadata({- ...input,- datasets: [{ ...input.datasets[0], rows: [{ unexpected: 1 }] }],- }),- ).toThrow('does not match');- });-- it('accepts grouped bar charts and SOTA table highlights', () => {- expect(- visualizationMetadata({- ...input,- visualizations: [- {- dataset: 'metrics',- encoding: { category: 'name', series: [{ field: 'before' }] },- id: 'scores',- type: 'bar-chart',- version: 1,- },- {- dataset: 'metrics',- encoding: { highlights: [{ field: 'after', mode: 'min' }] },- id: 'score-table',- type: 'table',- version: 1,- },- ],- })?.visualization?.views.map((view) => view.type),- ).toEqual(['bar-chart', 'table']);- });-- it.each([- ['bar-chart', {}],- ['heatmap', { x: 'name', y: 'before' }],- ['line-chart', { series: [], x: 'name' }],- ['metric-comparison', { after: 'after', before: 'before' }],- ['scatter-plot', { x: 'before', y: 'missing' }],- ['table', { columns: ['missing'] }],- ])('rejects malformed %s encodings', (type, encoding) => {- expect(() =>- visualizationMetadata({- ...input,- visualizations: [{ dataset: 'metrics', encoding, id: 'invalid-view', type, version: 1 }],- }),- ).toThrow();- });-- it('rejects duplicate dataset field keys', () => {- expect(() =>- visualizationMetadata({- ...input,- datasets: [- {- ...input.datasets[0],- fields: [- { key: 'name', type: 'string' },- { key: 'name', type: 'number' },- ],- },- ],- }),- ).toThrow('field keys must be unique');- });-});--describe('evidenceTypeForFile — markdown evidence', () => {- it('maps .md / .markdown to the markdown medium, keeping .txt as text', () => {- expect(evidenceTypeForFile('assets/root-cause.md')).toBe('markdown');- expect(evidenceTypeForFile('assets/root-cause.markdown')).toBe('markdown');- expect(evidenceTypeForFile('assets/root-cause.txt')).toBe('text');- });-- it('types an audio clip as audio, not the binary-blob-as-text fallback', () => {- // Before `audio` existed these fell through to `text`, so a TTS deliverable- // published as an unreadable, unplayable artifact.- expect(evidenceTypeForFile('assets/tts-zh.mp3')).toBe('audio');- expect(evidenceTypeForFile('assets/reply.WAV')).toBe('audio');- expect(evidenceTypeForFile('assets/voice.m4a')).toBe('audio');- expect(evidenceTypeForFile('assets/tone.opus')).toBe('audio');- // .webm stays video — the container is overwhelmingly used for screen clips.- expect(evidenceTypeForFile('assets/flow.webm')).toBe('video');- });-- it('inlines a small markdown file as content instead of uploading it', () => {- const dir = mkdtempSync(path.join(tmpdir(), 'lh-evidence-'));- const file = path.join(dir, 'root-cause.md');- writeFileSync(file, '### 根因证据\n\n- `heteroSessionId` 未透传');-- try {- expect(inlineTextEvidenceForFile(file, evidenceTypeForFile(file))).toBe(- '### 根因证据\n\n- `heteroSessionId` 未透传',- );- } finally {- rmSync(dir, { force: true, recursive: true });- }- });-});--describe('surfacesFromResult — surface normalization', () => {- let exitSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {- throw new Error('process.exit');- }) as never);- });-- afterEach(() => {- exitSpy.mockRestore();- });-- it('canonicalizes known aliases and dedupes', () => {- expect(surfacesFromResult({ surfaces: ['electron', 'cli', 'desktop'] })).toEqual([- 'desktop',- 'cli',- ]);- });-- it('rejects a value that names no surface instead of silently dropping it', () => {- // Free-form surfaces are how the field rotted: prose, runtime modes and test- // kinds all ended up in it. Failing here puts the fix in the author's hands- // while they still have the context to make it.- expect(() =>- surfacesFromResult({ surfaces: ['Electron 打包版(app.isPackaged=true)'] }),- ).toThrow('process.exit');- expect(() => surfacesFromResult({ surfaces: ['unit'] })).toThrow('process.exit');- });-- it('returns undefined when the report names no surfaces at all', () => {- expect(surfacesFromResult({})).toBeUndefined();- expect(surfacesFromResult({ surfaces: [] })).toBeUndefined();- });-});--describe('screenProgrammaticTestChecks', () => {- let warnSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => undefined);- });-- afterEach(() => {- warnSpy.mockRestore();- });-- it('drops the repo test suites and static gates, keeping real acceptance checks', () => {- const result = {- cases: [- { id: 'c1', name: '语音回复能在气泡里播放', status: 'pass' },- { id: 'c2', name: '单元测试全部通过', status: 'pass' },- ],- plan: [- { id: 'c1', title: '语音回复能在气泡里播放' },- { id: 'c2', title: '单元测试全部通过' },- { id: 'c3', method: 'bun run check --type', title: '类型检查无报错' },- ],- };-- const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result);-- expect([...droppedIds]).toEqual(['c2', 'c3']);- expect(droppedLabels).toEqual(['c2 — 单元测试全部通过', 'c3 — 类型检查无报错']);- expect(warnSpy).toHaveBeenCalled();- });-- it('screens plan and cases together so a dropped item never orphans its pair', () => {- // The plan item names the gate; the case is titled loosely. Screening only- // one side would leave the other behind as an "unplanned" row.- const { droppedIds } = screenProgrammaticTestChecks({- cases: [{ id: 'c1', name: 'all green' }],- plan: [{ id: 'c1', title: 'vitest suite passes' }],- });-- expect([...droppedIds]).toEqual(['c1']);- });-- it('says nothing when the round has no programmatic-test checks', () => {- const { droppedIds, droppedLabels } = screenProgrammaticTestChecks({- plan: [{ id: '1', title: 'the reply streams token by token' }],- });-- expect(droppedIds.size).toBe(0);- expect(droppedLabels).toEqual([]);- expect(warnSpy).not.toHaveBeenCalled();- });-- it('omits the screened ids from the frozen plan', () => {- const result = {- plan: [- { id: 'c1', title: 'the reply streams token by token' },- { id: 'c2', title: 'unit tests pass' },- ],- };- const { droppedIds } = screenProgrammaticTestChecks(result);-- expect(planFromResult(result, droppedIds)!.map((item) => item.id)).toEqual(['c1']);- });-});--describe('planFromResult — plan item normalization', () => {- let exitSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {- throw new Error('process.exit');- }) as never);- });-- afterEach(() => {- exitSpy.mockRestore();- });-- it('fills every frozen-item field the author does not write', () => {- expect(planFromResult({ plan: [{ id: '1', title: 'logs are persisted' }] })).toEqual([- {- description: undefined,- id: '1',- index: 0,- onFail: 'manual',- required: true,- title: 'logs are persisted',- verifierConfig: {},- verifierType: 'agent',- },- ]);- });-- it('honors the declared verifier instead of assuming every check is agent-judged', () => {- const [item] = planFromResult({- plan: [{ id: '1', title: 'cli returns a tree', verifier: 'program' }],- })!;-- expect(item.verifierType).toBe('program');- });-- it('carries requiredEvidence, which the executor coverage gate actually enforces', () => {- const [item] = planFromResult({- plan: [- {- id: '1',- requiredEvidence: ['screenshot', { hint: 'the raw command output', type: 'text' }],- title: 'ui renders',- },- ],- })!;-- expect(item.verifierConfig).toEqual({- requiredEvidence: [- { hint: undefined, type: 'screenshot' },- { hint: 'the raw command output', type: 'text' },- ],- });- });-- it('rejects an out-of-vocabulary verifier or evidence medium', () => {- // An unrecognized medium would gate on nothing — silently weaker than no gate.- expect(() => planFromResult({ plan: [{ id: '1', title: 't', verifier: 'eyeball' }] })).toThrow(- 'process.exit',- );- expect(() =>- planFromResult({ plan: [{ id: '1', requiredEvidence: ['vibes'], title: 't' }] }),- ).toThrow('process.exit');- });-- it('carries how the check would be made and what it expected', () => {- const [item] = planFromResult({- plan: [{ expected: 'the file exists', id: '1', method: 'tail the log', title: 'logs' }],- })!;-- expect(item.verifierConfig).toEqual({ expected: 'the file exists', method: 'tail the log' });- });-- it('normalizes a per-item surface and drops one that names no surface', () => {- const items = planFromResult({- plan: [- { id: '1', surface: 'electron', title: 'tray dedupe' },- { id: '2', surface: 'unit', title: 'model test' },- { id: '3', title: 'no surface' },- ],- })!;-- expect(items[0].verifierConfig).toEqual({ surface: 'desktop' });- expect(items[1].verifierConfig).toEqual({});- expect(items[2].verifierConfig).toEqual({});- });-- it('keys items by the same id the cases use, so results pair back to them', () => {- const items = planFromResult({ plan: [{ id: 'case-a', title: 'a' }, { title: 'b' }] })!;-- expect(items.map((i) => i.id)).toEqual(['case-a', 'case-2']);- });-- it('drops an item that names no check', () => {- expect(planFromResult({ plan: [{ id: '1' }] })).toEqual([]);- });-- it('distinguishes "no plan field" from an explicitly empty plan', () => {- // Absent → undefined: this snapshot did not declare a plan.- expect(planFromResult({})).toBeUndefined();-- // Present but empty → `[]`: this snapshot explicitly planned no checks.- expect(planFromResult({ plan: [] })).toEqual([]);- });-});--describe('verify ingest-report — every run is an immutable acceptance round', () => {- let consoleSpy: ReturnType<typeof vi.spyOn>;- let dir: string;-- beforeEach(() => {- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- vi.stubEnv('LOBEHUB_WORKSPACE_ID', '');- mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- const verify = mockTrpcClient.verify as Record<string, any>;- verify.createRun = { mutate: vi.fn().mockResolvedValue({ id: 'run-new' }) };- verify.updateRun = { mutate: vi.fn() };- verify.upsertReport = { mutate: vi.fn().mockResolvedValue({}) };- mockTrpcClient.acceptance = {- attachRun: { mutate: vi.fn() },- ensure: { mutate: vi.fn().mockResolvedValue({ id: 'acceptance-1' }) },- getBundle: { query: vi.fn().mockResolvedValue({}) },- };- mockTrpcClient.workspace = {- getById: { query: vi.fn().mockResolvedValue({ id: 'workspace-1' }) },- };-- dir = mkdtempSync(path.join(tmpdir(), 'lh-ingest-'));- writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ cases: [] }));- process.env.LOBEHUB_TOPIC_ID = 'topic-1';- });-- afterEach(() => {- consoleSpy.mockRestore();- vi.unstubAllEnvs();- delete process.env.LOBEHUB_TOPIC_ID;- rmSync(dir, { force: true, recursive: true });- });-- const run = async (args: string[]) => {- const program = new Command();- program.exitOverride();- registerVerifyCommand(program);- await program.parseAsync(['node', 'lh', 'verify', ...args]);- };-- it('keeps position-based fallback ids stable when screening drops an earlier case', async () => {- // Regression (codex review): the survivors used to be re-enumerated after- // the programmatic-test screen, so dropping an id-less first case shifted- // every later fallback id (`case-2` ingested as `case-1`) — orphaning the- // results from their plan items in the immutable round.- const verify = mockTrpcClient.verify as Record<string, any>;- verify.ingestResult = { mutate: vi.fn().mockResolvedValue({ id: 'result-1' }) };- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [- { name: '单元测试全部通过', status: 'pass' },- { name: '回复在气泡中渲染', status: 'pass' },- { name: '失败态可重试', status: 'pass' },- ],- plan: [- { id: 'case-2', title: '回复在气泡中渲染' },- { id: 'case-3', title: '失败态可重试' },- ],- title: 'fallback id screening',- }),- );-- await run(['ingest-report', dir, '--json']);-- const ingested = verify.ingestResult.mutate.mock.calls.map(- ([input]: [{ checkItemId: string }]) => input.checkItemId,- );- expect(ingested).toEqual(['case-2', 'case-3']);- });-- it('creates a fresh run and binds it to the current topic acceptance', async () => {- const verify = mockTrpcClient.verify as Record<string, any>;-- await run(['ingest-report', dir, '--json']);-- expect(verify.updateRun.mutate).not.toHaveBeenCalled();- expect(verify.createRun.mutate).toHaveBeenCalled();- // The ambient topic may be folded onto its Task by the server.- expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({- foldTaskRunTopic: true,- requirement: undefined,- subjectId: 'topic-1',- subjectType: 'topic',- });- expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({- acceptanceId: 'acceptance-1',- verifyRunId: 'run-new',- });- });-- it('keeps an explicit topic subject exact instead of folding it onto a Task', async () => {- await run(['ingest-report', dir, '--subject', 'topic:topic-explicit', '--json']);-- expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({- requirement: undefined,- subjectId: 'topic-explicit',- subjectType: 'topic',- });- });-- it('creates a standalone acceptance when an external project has no operation or subject', async () => {- delete process.env.LOBEHUB_TOPIC_ID;- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({ cases: [], title: 'External delivery verification' }),- );-- await run(['ingest-report', dir, '--json']);-- expect(mockTrpcClient.acceptance.ensure.mutate).toHaveBeenCalledWith({- requirement: undefined,- subjectId: expect.stringMatching(- /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,- ),- subjectType: 'standalone',- title: 'External delivery verification',- });- expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({- acceptanceId: 'acceptance-1',- verifyRunId: 'run-new',- });- });-- it('reuses the asset when the acceptance row is keyed by criterion rather than plan item', async () => {- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- acceptance: {- id: 'acceptance-existing',- status: 'delivered',- subjectId: 'subject',- subjectType: 'standalone',- },- checks: [- { id: 'criterion-1', planItem: { id: 'stable-check', sourceCriterionId: 'criterion-1' } },- ],- });- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [{ id: 'stable-check', name: '输入区域可用', status: 'pass' }],- plan: [- {- id: 'stable-check',- title: '输入区域可用',- verifier: 'agent',- method: '打开输入区域',- expected: '可以输入',- },- ],- }),- );- await run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']);- expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalledWith(- expect.objectContaining({- plan: [expect.objectContaining({ id: 'stable-check', sourceCriterionId: 'criterion-1' })],- }),- );- });-- it('reuses criteria when the round reaches its acceptance through the subject', async () => {- // Regression: only `--acceptance` read the existing checks, so re-ingesting- // a topic's report minted fresh criteria and duplicated every check row.- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- checks: [{ id: 'criterion-1', planItem: { id: '1', sourceCriterionId: 'criterion-1' } }],- });- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [{ id: '1', name: '标题可编辑', status: 'pass' }],- plan: [{ id: '1', title: '标题可编辑' }],- }),- );-- await run(['ingest-report', dir, '--json']);-- expect(mockTrpcClient.acceptance.getBundle.query).toHaveBeenCalledWith({ id: 'acceptance-1' });- expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalledWith(- expect.objectContaining({- plan: [expect.objectContaining({ id: '1', sourceCriterionId: 'criterion-1' })],- }),- );- });-- describe('identical re-ingest', () => {- const publishedRound = (content: string) => ({- report: { content, summary: '全部通过' },- run: { id: 'run-r1', plan: [{ id: '1', title: '标题可编辑' }], roundIndex: 1 },- });-- beforeEach(() => {- (mockTrpcClient.verify as Record<string, any>).ingestResult = {- mutate: vi.fn().mockResolvedValue({ id: 'result-1' }),- };- writeFileSync(path.join(dir, 'report.md'), '## 备注\n\n首次发布');- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [{ id: '1', name: '标题可编辑', status: 'pass' }],- plan: [{ id: '1', title: '标题可编辑' }],- summary: { conclusion: '全部通过', failed: 0, passed: 1, total: 1 },- }),- );- });-- it('refuses to stack a round identical to the latest one', async () => {- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- rounds: [publishedRound('## 备注\n\n首次发布')],- });- const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {- throw new Error(`process.exit ${code}`);- }) as never);-- try {- await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow('process.exit 1');- expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();- } finally {- exitSpy.mockRestore();- }- });-- it('publishes the next round once the report actually changed', async () => {- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- rounds: [publishedRound('## 备注\n\n上一轮的报告')],- });-- await run(['ingest-report', dir, '--json']);-- expect(mockTrpcClient.verify.createRun.mutate).toHaveBeenCalled();- });- });-- it.each([null, 'workspace-1'])(- 'appends a re-verification round when both scopes are %s',- async (workspaceId) => {- vi.stubEnv('LOBEHUB_WORKSPACE_ID', workspaceId ?? '');- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- acceptance: {- id: 'acceptance-existing',- status: 'delivered',- subjectId: 'standalone-subject',- subjectType: 'standalone',- workspaceId,- },- });-- await run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']);-- expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({- acceptanceId: 'acceptance-existing',- verifyRunId: 'run-new',- });- expect(mockTrpcClient.verify.upsertReport.mutate).toHaveBeenCalled();- expect(process.env.LOBEHUB_WORKSPACE_ID).toBe(workspaceId ?? '');- if (!workspaceId) expect(mockTrpcClient.workspace.getById.query).not.toHaveBeenCalled();- },- );-- it.each([- { effectiveWorkspace: null, name: 'revoked workspace membership' },- { effectiveWorkspace: { id: 'workspace-other' }, name: 'a different server workspace' },- { effectiveWorkspace: new Error('Workspace lookup unavailable'), name: 'a failed lookup' },- ])('rejects $name before creating a run', async ({ effectiveWorkspace }) => {- vi.stubEnv('LOBEHUB_WORKSPACE_ID', 'workspace-1');- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- acceptance: {- id: 'acceptance-existing',- status: 'delivered',- subjectId: 'standalone-subject',- subjectType: 'standalone',- workspaceId: 'workspace-1',- },- });- const query = mockTrpcClient.workspace.getById.query;- if (effectiveWorkspace instanceof Error) query.mockRejectedValue(effectiveWorkspace);- else query.mockResolvedValue(effectiveWorkspace);-- await expect(- run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']),- ).rejects.toThrow(- effectiveWorkspace instanceof Error ? effectiveWorkspace.message : 'No run was created.',- );-- expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.verify.upsertReport.mutate).not.toHaveBeenCalled();- expect(process.env.LOBEHUB_WORKSPACE_ID).toBe('workspace-1');- });-- it.each([- { current: '', hint: 'LOBEHUB_WORKSPACE_ID=workspace-target', target: 'workspace-target' },- {- current: 'workspace-current',- hint: 'LOBEHUB_WORKSPACE_ID=workspace-target',- target: 'workspace-target',- },- { current: 'workspace-current', hint: 'lh workspace use --personal', target: null },- ])(- 'rejects scope $current → $target before any remote writes',- async ({ current, target, hint }) => {- vi.stubEnv('LOBEHUB_WORKSPACE_ID', current);- mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({- acceptance: {- id: 'acceptance-existing',- status: 'delivered',- subjectId: 'standalone-subject',- subjectType: 'standalone',- workspaceId: target,- },- });-- await expect(- run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']),- ).rejects.toThrow(hint);-- expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.verify.upsertReport.mutate).not.toHaveBeenCalled();- expect(process.env.LOBEHUB_WORKSPACE_ID).toBe(current);- },- );-- it('passes a non-coding scenario and its context bag through to the run', async () => {- const verify = mockTrpcClient.verify as Record<string, any>;- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [],- context: { question: 'How mature is X?', sourceCount: 8 },- scenario: 'research',- }),- );-- await run(['ingest-report', dir, '--json']);-- expect(verify.createRun.mutate).toHaveBeenCalledWith(- expect.objectContaining({- context: expect.objectContaining({ question: 'How mature is X?', sourceCount: 8 }),- scenario: 'research',- }),- );- });-- 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- // with a ReferenceError AFTER creating the run.- const verify = mockTrpcClient.verify as Record<string, any>;- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [],- context: { question: 'How mature is X?' },- scenario: 'research',- }),- );-- await run(['ingest-report', dir]);-- expect(verify.createRun.mutate).toHaveBeenCalledWith(- expect.objectContaining({ scenario: 'research' }),- );- // The success tail printed — the command reached past the run creation.- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('verifyRunId'));- });-- it('rejects an unknown scenario instead of silently tagging the run coding', async () => {- const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {- throw new Error(`process.exit ${code}`);- }) as never);- writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ cases: [], scenario: 'poetry' }));-- try {- await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow('process.exit 1');- expect(- (mockTrpcClient.verify as Record<string, any>).createRun.mutate,- ).not.toHaveBeenCalled();- } finally {- exitSpy.mockRestore();- }- });-- it('validates every visualization before creating or attaching an immutable round', async () => {- const verify = mockTrpcClient.verify as Record<string, any>;- writeFileSync(- path.join(dir, 'result.json'),- JSON.stringify({- cases: [- {- datasets: [- {- fields: [{ key: 'score', type: 'number' }],- id: 'scores',- rows: [{ score: 1 }],- },- ],- id: 'broken-chart',- visualizations: [- {- dataset: 'scores',- encoding: {},- id: 'chart',- type: 'bar-chart',- version: 1,- },- ],- },- ],- }),- );-- await expect(run(['ingest-report', dir, '--json'])).rejects.toThrow(- 'case broken-chart: visualizations[0].encoding.category',- );- expect(verify.createRun.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();- expect(mockTrpcClient.acceptance.attachRun.mutate).not.toHaveBeenCalled();- });-- it('creates another run when the same report directory is ingested again', async () => {- const verify = mockTrpcClient.verify as Record<string, any>;- verify.createRun.mutate- .mockResolvedValueOnce({ id: 'run-first' })- .mockResolvedValueOnce({ id: 'run-second' });-- await run(['ingest-report', dir, '--json']);- await run(['ingest-report', dir, '--json']);-- expect(verify.createRun.mutate).toHaveBeenCalledTimes(2);- expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenNthCalledWith(1, {- acceptanceId: 'acceptance-1',- verifyRunId: 'run-first',- });- expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenNthCalledWith(2, {- acceptanceId: 'acceptance-1',- verifyRunId: 'run-second',- });- });-- it('with --open prints only acceptance links, the round snapshot via ?r=', async () => {- // The acceptance page is the sole user-facing link; the round's fixed- // snapshot is the same URL with `?r=<roundIndex>` — never a /verify link.- mockTrpcClient.acceptance.attachRun.mutate = vi.fn().mockResolvedValue({ roundIndex: 3 });-- await run(['ingest-report', dir, '--open']);-- const lines = consoleSpy.mock.calls.map((call) => String(call[0]));- expect(lines.some((line) => line.includes('/acceptance/acceptance-1'))).toBe(true);- expect(lines.some((line) => line.includes('/acceptance/acceptance-1?r=3'))).toBe(true);- expect(lines.some((line) => line.includes('/verify/'))).toBe(false);- });-});--describe('scenarioFromResult / genericContextFromResult — non-coding scenarios', () => {- it('defaults to coding and passes any known scenario through', () => {- expect(scenarioFromResult({})).toBe('coding');- expect(scenarioFromResult({ scenario: 'research' })).toBe('research');- expect(scenarioFromResult({ scenario: 'writing' })).toBe('writing');- expect(scenarioFromResult({ scenario: 'generic' })).toBe('generic');- });-- it('hard-errors on a scenario nothing renders', () => {- const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {- throw new Error(`process.exit ${code}`);- }) as never);-- try {- expect(() => scenarioFromResult({ scenario: 'poetry' })).toThrow('process.exit 1');- } finally {- exitSpy.mockRestore();- }- });-- it('lifts shared provenance defaults but lets explicit context keys win', () => {- expect(- genericContextFromResult({- context: { testedAt: '2026-07-16T10:00:00Z', wordCount: 82_000, work: '长夜' },- createdAt: '2026-07-15T00:00:00Z',- entry: 'lh doc export',- }),- ).toEqual({- entry: 'lh doc export',- testedAt: '2026-07-16T10:00:00Z',- wordCount: 82_000,- work: '长夜',- });-- expect(genericContextFromResult({})).toBeUndefined();- });-});--describe('parseSubjectRef / subjectFromResult — acceptance subject', () => {- it('parses the closed set of type:id references', () => {- expect(parseSubjectRef('task:task_123')).toEqual({- subjectId: 'task_123',- subjectType: 'task',- });- expect(parseSubjectRef('topic:tpc_abc')).toEqual({- subjectId: 'tpc_abc',- subjectType: 'topic',- });- expect(parseSubjectRef('document:doc_1')).toEqual({- subjectId: 'doc_1',- subjectType: 'document',- });- });-- it('rejects unknown types and malformed references', () => {- expect(parseSubjectRef('release:rel_1')).toBeNull();- expect(parseSubjectRef('task:')).toBeNull();- expect(parseSubjectRef('task_123')).toBeNull();- expect(parseSubjectRef(undefined)).toBeNull();- });-- it('keeps an id containing colons intact (splits on the FIRST colon only)', () => {- expect(parseSubjectRef('topic:tpc:odd:id')).toEqual({- subjectId: 'tpc:odd:id',- subjectType: 'topic',- });- });-- it('reads result.json subject in both string and object shapes', () => {- expect(subjectFromResult({ subject: 'task:task_9' })).toEqual({- ref: { subjectId: 'task_9', subjectType: 'task' },- });- expect(- subjectFromResult({- subject: { id: 'tpc_1', requirement: 'no regressions', type: 'topic' },- }),- ).toEqual({- ref: { subjectId: 'tpc_1', subjectType: 'topic' },- requirement: 'no regressions',- });- });-- it('returns null on a malformed subject field instead of guessing', () => {- expect(subjectFromResult({})).toBeNull();- expect(subjectFromResult({ subject: 'nonsense' })).toBeNull();- expect(subjectFromResult({ subject: { id: 'x' } })).toBeNull();- });-});--describe('originFromEnv — in-app provenance', () => {- const saved = { ...process.env };-- afterEach(() => {- process.env = { ...saved };- });-- it('reads the conversation the agent runtime echoed into the child env', () => {- process.env.LOBEHUB_AGENT_ID = 'agt_1';- process.env.LOBEHUB_TOPIC_ID = 'tpc_1';- process.env.LOBEHUB_OPERATION_ID = 'op_1';-- expect(originFromEnv()).toEqual({- agentId: 'agt_1',- operationId: 'op_1',- topicId: 'tpc_1',- });- });-- it('retains conversation provenance for persistent Pi without an authoring operation', () => {- process.env.LOBEHUB_AGENT_ID = 'agt_pi';- process.env.LOBEHUB_TOPIC_ID = 'tpc_pi';- delete process.env.LOBEHUB_OPERATION_ID;-- expect(originFromEnv()).toEqual({- agentId: 'agt_pi',- operationId: undefined,- topicId: 'tpc_pi',- });- });-- it('never takes its operationId from --operation, which names the run under TEST', () => {- // `--operation` links the session to the Agent Run being verified; origin is- // the run that AUTHORED the report. Conflating them attributes the report to- // its own subject — exactly the provenance this is meant to preserve.- process.env.LOBEHUB_OPERATION_ID = 'op_authoring_run';-- expect(originFromEnv()?.operationId).toBe('op_authoring_run');- // The flag is passed to `createRun` separately; it must not reach here at all.- expect(originFromEnv).toHaveLength(0);- });-- it('is undefined outside a LobeHub-spawned agent — a plain terminal is not an error', () => {- delete process.env.LOBEHUB_AGENT_ID;- delete process.env.LOBEHUB_TOPIC_ID;- delete process.env.LOBEHUB_OPERATION_ID;-- expect(originFromEnv()).toBeUndefined();- });-});--describe('deriveReportVerdict — headline fallback when summary.verdict is absent', () => {- it('derives passed when every case passed', () => {- expect(deriveReportVerdict([{ result: 'passed' }, { result: 'ok' }])).toBe('passed');- });-- it('any failed case fails the report', () => {- expect(deriveReportVerdict([{ result: 'passed' }, { result: 'failed' }])).toBe('failed');- });-- it('a non-passed, non-failed case makes the report uncertain', () => {- expect(deriveReportVerdict([{ result: 'passed' }, { result: 'blocked' }])).toBe('uncertain');- });-- it('no cases → no derived verdict', () => {- expect(deriveReportVerdict([])).toBeUndefined();- });-- it('reads the documented `status` field, same as the per-case ingest', () => {- // Regression: `status` was skipped here while the per-case ingest reads- // `result ?? status ?? verdict`, so an all-pass report written with the- // documented field derived `uncertain` whenever this fallback ran (e.g.- // after the programmatic-test screen recounts the summary).- expect(deriveReportVerdict([{ status: 'pass' }, { status: 'pass' }])).toBe('passed');- expect(deriveReportVerdict([{ status: 'pass' }, { status: 'fail' }])).toBe('failed');- });-});--describe('subjectFromEnv — default topic acceptance', () => {- const saved = { ...process.env };-- afterEach(() => {- process.env = { ...saved };- });-- it('binds an in-app run to its authoring topic', () => {- process.env.LOBEHUB_TOPIC_ID = 'tpc_1';-- expect(subjectFromEnv()).toEqual({ subjectId: 'tpc_1', subjectType: 'topic' });- });-- it('requires an explicit subject outside a topic', () => {- delete process.env.LOBEHUB_TOPIC_ID;-- expect(subjectFromEnv()).toBeNull();- });-});--describe('lh acceptance — canonical run tree', () => {- let consoleSpy: ReturnType<typeof vi.spyOn>;-- beforeEach(() => {- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- (mockTrpcClient.verify as Record<string, any>).submitCheckEvidence = {- mutate: vi.fn().mockResolvedValue({- checkResult: { id: 'result_1', verifyRunId: 'run_1' },- evidence: [{ id: 'evidence_1' }],- }),- };- });- afterEach(() => consoleSpy.mockRestore());-- const run = async (args: string[]) => {- const program = new Command();- program.exitOverride();- // First-class `lh acceptance …` — the run subtree only hangs off this,- // never off the deprecated `lh verify acceptance` alias.- registerAcceptanceCommands(program);- await program.parseAsync(['node', 'lh', 'acceptance', ...args]);- };-- it('routes `acceptance run delete` to the same deleteRun mutation', async () => {- mockTrpcClient.verify.deleteRun.mutate.mockReset().mockResolvedValue({ id: 'run_1' });- await run(['run', 'delete', 'run_1', '--yes']);- expect(mockTrpcClient.verify.deleteRun.mutate).toHaveBeenCalledWith({ verifyRunId: 'run_1' });- });-- it('prints the full verification report URL after submitting evidence', async () => {- await run([- 'run',- 'result',- 'submit',- '--operation',- 'op_1',- '--item',- 'check_1',- '--type',- 'text',- '--content',- 'passed',- ]);-- const lines = consoleSpy.mock.calls.map((call) => String(call[0]));- expect(lines).toContain('report: https://app.lobehub.com/verify/run_1');- });-- it('includes the verification report URL in JSON output', async () => {- await run([- 'run',- 'result',- 'submit',- '--operation',- 'op_1',- '--item',- 'check_1',- '--type',- 'text',- '--content',- 'passed',- '--json',- ]);-- const output = JSON.parse(consoleSpy.mock.calls.map((call) => String(call[0])).join(''));- expect(output.url).toBe('https://app.lobehub.com/verify/run_1');- });-- it('does NOT attach the run subtree to the deprecated `verify acceptance` alias', async () => {- const program = new Command();- program.exitOverride();- registerAcceptanceCommands(program, { deprecated: true });- const acceptance = program.commands.find((c) => c.name() === 'acceptance');- const hasRun = acceptance?.commands.some((c) => c.name() === 'run');- expect(hasRun).toBe(false);- });-});--describe('formatAnnotationRegion', () => {- const rect = { height: 0.03, width: 0.12, x: 0.31, y: 0.24 };-- it('names the evidence the region was drawn on and where on it', () => {- expect(- formatAnnotationRegion(- { comment: 'too light', evidenceId: 'ev-1', rect },- new Map([['ev-1', 'c11-profile-editing.png']]),- ),- ).toBe('c11-profile-editing.png @ 31%,24% · 12%×3%');- });-- // Without the filename a reader still cannot tell WHICH screenshot was circled,- // so the raw id is better than dropping the reference entirely.- it('falls back to the raw evidence id when the label is unknown', () => {- expect(formatAnnotationRegion({ evidenceId: 'ev-9', rect })).toBe('ev-9 @ 31%,24% · 12%×3%');- });-- it('renders the position alone when the annotation names no evidence', () => {- expect(formatAnnotationRegion({ rect })).toBe('31%,24% · 12%×3%');- });-- it('renders the evidence alone when the rect is absent', () => {- expect(formatAnnotationRegion({ evidenceId: 'ev-1' }, new Map([['ev-1', 'shot.png']]))).toBe(- 'shot.png',- );- });-- // Reviews made before regions existed carry only a comment — printing an empty- // "└" line under every one of them would be pure noise.- it('returns undefined when there is no location at all', () => {- expect(formatAnnotationRegion({ comment: 'just a note' })).toBeUndefined();- expect(formatAnnotationRegion({ rect: { x: 0.1 } })).toBeUndefined();- });- it('leads with the frame on a video, then the region circled on it', () => {- expect(- formatAnnotationRegion(- { evidenceId: 'ev-1', rect, time: { start: 7.2 } },- new Map([['ev-1', 'scroll.mp4']]),- ),- ).toBe('scroll.mp4 @ frame at 0:07.20 · 31%,24% · 12%×3%');- });-- it('prints a span, and no region at all when the note covers the whole frame', () => {- expect(- formatAnnotationRegion({- evidenceId: 'ev-1',- rect: { height: 1, width: 1, x: 0, y: 0 },- time: { end: 67.65, start: 66.75 },- }),- ).toBe('ev-1 @ 1:06.75–1:07.65');- });-});--describe('formatDisputedChapter', () => {- it('quotes the agent claim the reviewer objected to', () => {- expect(- formatDisputedChapter({ kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 }),- ).toBe('your check at 0:07.90: "no skeleton after scroll #3"');- });-- it('says nothing when there is no claim to quote', () => {- expect(formatDisputedChapter(undefined)).toBeUndefined();- expect(formatDisputedChapter({ kind: 'check', t: 1 })).toBeUndefined();- });-});--describe('file evidence descriptions', () => {- it('preserves an explicit description', () => {- expect(evidenceDescriptionForFile('Goal final state', '/tmp/state.json')).toBe(- 'Goal final state',- );- });-- it('retains the basename when a file is inlined without a description', () => {- expect(evidenceDescriptionForFile(undefined, '/tmp/goal-final-state.json')).toBe(- 'goal-final-state.json',- );- expect(evidenceDescriptionForFile(' ', '/tmp/events.json')).toBe('events.json');- });-- it('does not invent a description for inline content', () => {- expect(evidenceDescriptionForFile(undefined)).toBeUndefined();- });-});diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.tsdeleted file mode 100644index 965f9413c54..00000000000--- a/apps/cli/src/commands/verify.ts+++ /dev/null@@ -1,391 +0,0 @@-import type { Command } from 'commander';-import pc from 'picocolors';--import { getTrpcClient } from '../api/client';-import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';-import { log } from '../utils/logger';-import { attachDeprecatedVerifyRunAliases } from './acceptanceRun';-import { registerAcceptanceCommands } from './verifyAcceptance';-import {- assertEnum,- ON_FAIL,- type OnFail,- parseConfig,- printResults,- VERIFIER_TYPES,- type VerifierType,-} from './verifyHelpers';--// Re-export the report/ingest helpers so existing importers keep resolving them-// from './verify' (tests, and callers predating the verifyHelpers split).-export * from './verifyHelpers';--// ── Command Registration ───────────────────────────────────--export function registerVerifyCommand(program: Command) {- const verify = program- .command('verify')- .description('Agent Run verification machinery — criteria, rubrics, and per-run check plans');-- // `verify acceptance …` — legacy alias; the canonical group is the first-class- // `lh acceptance`.- registerAcceptanceCommands(verify, { deprecated: true });-- // Deprecated `lh verify …` spellings for the run/result/evidence/report/install- // commands now living under `lh acceptance`. Kept for a few releases.- attachDeprecatedVerifyRunAliases(verify);- // ════════════ criteria ════════════- const criterion = verify.command('criterion').description('Reusable pass/fail standards');-- criterion- .command('list')- .description('List criteria')- .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(async (options: { json?: boolean | string }) => {- const client = await getTrpcClient();- const items = await client.verify.listCriteria.query();-- if (options.json !== undefined) {- outputJson(items, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (items.length === 0) return void console.log('No criteria found.');- printTable(- items.map((c) => [- c.id,- truncate(c.title, 60),- c.verifierType,- c.required ? 'gate' : 'soft',- c.onFail,- c.updatedAt ? timeAgo(c.updatedAt) : '',- ]),- ['ID', 'TITLE', 'TYPE', 'BLOCK', 'ON-FAIL', 'UPDATED'],- );- });-- criterion- .command('create')- .description('Create a criterion')- .requiredOption('-t, --title <title>', 'Criterion title')- .requiredOption('--type <type>', `Verifier type (${VERIFIER_TYPES.join('|')})`)- .option('--on-fail <strategy>', `Action on failure (${ON_FAIL.join('|')})`)- .option('--soft', 'Non-blocking (required=false); defaults to blocking')- .option('--config <json>', 'Verifier config as JSON')- .option('--doc <id>', 'Linked guidance document id')- .action(- async (options: {- config?: string;- doc?: string;- onFail?: OnFail;- soft?: boolean;- title: string;- type: VerifierType;- }) => {- assertEnum(options.type, VERIFIER_TYPES, '--type');- assertEnum(options.onFail, ON_FAIL, '--on-fail');- const client = await getTrpcClient();- const result = await client.verify.createCriterion.mutate({- documentId: options.doc,- onFail: options.onFail,- required: options.soft ? false : undefined,- title: options.title,- verifierConfig: parseConfig(options.config),- verifierType: options.type,- });- console.log(`${pc.green('✓')} Created criterion ${pc.bold((result as any).id)}`);- },- );-- criterion- .command('delete <id>')- .description('Delete a criterion')- .option('--yes', 'Skip confirmation')- .action(async (id: string, options: { yes?: boolean }) => {- if (!options.yes && !(await confirm(`Delete criterion ${id}?`)))- return void console.log('Cancelled.');- const client = await getTrpcClient();- await client.verify.deleteCriterion.mutate({ id });- console.log(`${pc.green('✓')} Deleted criterion ${pc.bold(id)}`);- });-- // ════════════ rubrics ════════════- const rubric = verify.command('rubric').description('Named groups of criteria');-- rubric- .command('list')- .description('List rubrics')- .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(async (options: { json?: boolean | string }) => {- const client = await getTrpcClient();- const items = await client.verify.listRubrics.query();- if (options.json !== undefined) {- outputJson(items, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (items.length === 0) return void console.log('No rubrics found.');- printTable(- items.map((r) => [- r.id,- truncate(r.title, 60),- truncate(r.description || '', 60),- r.updatedAt ? timeAgo(r.updatedAt) : '',- ]),- ['ID', 'TITLE', 'DESCRIPTION', 'UPDATED'],- );- });-- rubric- .command('create')- .description('Create a rubric')- .requiredOption('-t, --title <title>', 'Rubric title')- .option('-d, --description <text>', 'Rubric description')- .option('--max-repair-rounds <n>', 'Cap on automatic repair rounds (0-5)')- .action(async (options: { description?: string; maxRepairRounds?: string; title: string }) => {- const client = await getTrpcClient();- const result = await client.verify.createRubric.mutate({- config:- options.maxRepairRounds !== undefined- ? { maxRepairRounds: Number(options.maxRepairRounds) }- : undefined,- description: options.description,- title: options.title,- });- console.log(`${pc.green('✓')} Created rubric ${pc.bold((result as any).id)}`);- });-- rubric- .command('view <id>')- .description('Show a rubric and its run-policy config')- .option('--json [fields]', 'Output JSON')- .action(async (id: string, options: { json?: boolean | string }) => {- const client = await getTrpcClient();- const item = await client.verify.getRubric.query({ id });- if (!item) return void log.error('Rubric not found.');- if (options.json !== undefined) {- outputJson(item, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.bold('ID')} ${item.id}`);- console.log(`${pc.bold('Title')} ${item.title}`);- if (item.description) console.log(`${pc.bold('Description')} ${item.description}`);- const maxRepairRounds = (item.config as { maxRepairRounds?: number } | null)?.maxRepairRounds;- console.log(`${pc.bold('Repair rounds')} ${maxRepairRounds ?? pc.dim('default')}`);- });-- rubric- .command('update <id>')- .description('Update a rubric (title / description / run-policy config)')- .option('-t, --title <title>', 'New title')- .option('-d, --description <text>', 'New description')- .option('--max-repair-rounds <n>', 'Cap on automatic repair rounds (0-5)')- .action(- async (- id: string,- options: { description?: string; maxRepairRounds?: string; title?: string },- ) => {- const client = await getTrpcClient();- const value: {- config?: { maxRepairRounds?: number };- description?: string;- title?: string;- } = {};- if (options.title !== undefined) value.title = options.title;- if (options.description !== undefined) value.description = options.description;- if (options.maxRepairRounds !== undefined)- value.config = { maxRepairRounds: Number(options.maxRepairRounds) };- await client.verify.updateRubric.mutate({ id, value });- console.log(`${pc.green('✓')} Updated rubric ${pc.bold(id)}`);- },- );-- rubric- .command('delete <id>')- .description('Delete a rubric')- .option('--yes', 'Skip confirmation')- .action(async (id: string, options: { yes?: boolean }) => {- if (!options.yes && !(await confirm(`Delete rubric ${id}?`)))- return void console.log('Cancelled.');- const client = await getTrpcClient();- await client.verify.deleteRubric.mutate({ id });- console.log(`${pc.green('✓')} Deleted rubric ${pc.bold(id)}`);- });-- rubric- .command('criteria <rubricId>')- .description('List criteria in a rubric')- .option('--json [fields]', 'Output JSON')- .action(async (rubricId: string, options: { json?: boolean | string }) => {- const client = await getTrpcClient();- const items = await client.verify.getRubricCriteria.query({ rubricId });- if (options.json !== undefined) {- outputJson(items, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (items.length === 0) return void console.log('No criteria in this rubric.');- printTable(- items.map((c: any) => [- c.id,- truncate(c.title, 60),- c.verifierType,- c.required ? 'gate' : 'soft',- ]),- ['ID', 'TITLE', 'TYPE', 'BLOCK'],- );- });-- rubric- .command('set-criteria <rubricId> <criterionIds...>')- .description('Set the criteria a rubric aggregates (order preserved)')- .action(async (rubricId: string, criterionIds: string[]) => {- const client = await getTrpcClient();- await client.verify.setRubricCriteria.mutate({- criteria: criterionIds.map((criterionId, i) => ({ criterionId, sortOrder: i })),- rubricId,- });- console.log(- `${pc.green('✓')} Rubric ${pc.bold(rubricId)} now has ${criterionIds.length} criterion(s)`,- );- });-- // ════════════ per-run plan ════════════- const plan = verify.command('plan').description('Per-run check plan lifecycle');-- plan- .command('generate <operationId>')- .description('Generate a draft check plan for a run')- .requiredOption('--goal <goal>', "The run's task/instruction the plan must satisfy")- .option('--rubric <id>', 'Mounted rubric id')- .option('--criteria <ids>', 'Ad-hoc criterion ids (comma-separated)')- .option('--ai', 'Let the LLM propose additional criteria')- .option('--max-ai <n>', 'Max AI-proposed criteria')- .option('--context <text>', 'Extra context for the AI prompt')- .option('--json [fields]', 'Output JSON')- .action(- async (- operationId: string,- options: {- ai?: boolean;- context?: string;- criteria?: string;- goal: string;- json?: boolean | string;- maxAi?: string;- rubric?: string;- },- ) => {- const client = await getTrpcClient();- const items = await client.verify.generateDraftPlan.mutate({- context: options.context,- enableAiGeneration: options.ai,- goal: options.goal,- maxAiCriteria: options.maxAi ? Number.parseInt(options.maxAi, 10) : undefined,- operationId,- verifyCriteriaIds: options.criteria- ?.split(',')- .map((s) => s.trim())- .filter(Boolean),- verifyRubricId: options.rubric ?? null,- });- if (options.json !== undefined) {- outputJson(items, typeof options.json === 'string' ? options.json : undefined);- return;- }- console.log(`${pc.green('✓')} Draft plan: ${pc.bold(String(items.length))} item(s)`);- printTable(- items.map((i: any) => [- String(i.index),- truncate(i.title, 60),- i.verifierType,- i.required ? 'gate' : 'soft',- ]),- ['#', 'TITLE', 'TYPE', 'BLOCK'],- );- },- );-- plan- .command('state <operationId>')- .description('Show the verify state (status + frozen plan) of a run')- .option('--json [fields]', 'Output JSON')- .action(async (operationId: string, options: { json?: boolean | string }) => {- const client = await getTrpcClient();- const state = await client.verify.getVerifyState.query({ operationId });- if (options.json !== undefined) {- outputJson(state, typeof options.json === 'string' ? options.json : undefined);- return;- }- if (!state) return void console.log('No verify state for this run.');- console.log(`${pc.bold('status')}: ${state.verifyStatus ?? pc.dim('(none)')}`);- console.log(- `${pc.bold('confirmed')}: ${state.verifyPlanConfirmedAt ? timeAgo(state.verifyPlanConfirmedAt) : pc.dim('no')}`,- );- const items = (state.verifyPlan ?? []) as any[];- console.log(`${pc.bold('plan')}: ${items.length} item(s)`);- if (items.length > 0)- printTable(- items.map((i) => [- String(i.index),- truncate(i.title, 60),- i.verifierType,- i.required ? 'gate' : 'soft',- ]),- ['#', 'TITLE', 'TYPE', 'BLOCK'],- );- });-- plan- .command('confirm <operationId>')- .description('Freeze (confirm) the draft plan')- .action(async (operationId: string) => {- const client = await getTrpcClient();- await client.verify.confirmPlan.mutate({ operationId });- console.log(`${pc.green('✓')} Confirmed plan for run ${pc.bold(operationId)}`);- });-- plan- .command('skip <operationId>')- .description('Skip verification for a run')- .action(async (operationId: string) => {- const client = await getTrpcClient();- await client.verify.skipPlan.mutate({ operationId });- console.log(`${pc.green('✓')} Skipped verification for run ${pc.bold(operationId)}`);- });-- // ════════════ execute (agent path) ════════════- verify- .command('execute <operationId>')- .description('Execute the confirmed plan against a deliverable (LLM judge)')- .requiredOption('--goal <goal>', "The run's task")- .requiredOption('--deliverable <text>', 'The output to judge')- .requiredOption('--model <model>', 'Judge model')- .requiredOption('--provider <provider>', 'Judge provider')- .option('--no-batch', 'Judge each item separately instead of one batched call')- .option('--json [fields]', 'Output JSON')- .action(- async (- operationId: string,- options: {- batch?: boolean;- deliverable: string;- goal: string;- json?: boolean | string;- model: string;- provider: string;- },- ) => {- const client = await getTrpcClient();- const results = await client.verify.executeVerify.mutate({- batchLlm: options.batch,- deliverable: options.deliverable,- goal: options.goal,- modelConfig: { model: options.model, provider: options.provider },- operationId,- });- if (options.json !== undefined) {- outputJson(results, typeof options.json === 'string' ? options.json : undefined);- return;- }- printResults(results);- },- );-}diff --git a/apps/cli/src/commands/verifyHelpers.ts b/apps/cli/src/commands/verifyHelpers.tsdeleted file mode 100644index 4ded3475791..00000000000--- a/apps/cli/src/commands/verifyHelpers.ts+++ /dev/null@@ -1,1140 +0,0 @@-import { execFileSync } from 'node:child_process';-import { existsSync, readFileSync } from 'node:fs';-import path from 'node:path';--import type {- AcceptanceSubjectType,- VerifyEvidenceChapter,- VerifyRunOrigin,- VerifyRunScenario,- VerifySurface,-} from '@lobechat/const/verify';-import {- acceptanceSubjectTypes,- formatVideoTimestamp,- GOMS_KLM_TRACE_FILE,- isFullFrameRect,- isProgrammaticTestCheck,- normalizeVerifySurface,- PROGRAMMATIC_TEST_CHECK_HINT,- readEvidenceChapters,- verifyEvidenceTypes,- verifyRunScenarios,- verifySurfaces,-} from '@lobechat/const/verify';-import type {- VerifyCheckResultMetadata,- VerifyInteractionCost,- VerifyVisualizationDataset,- VerifyVisualizationField,- VerifyVisualizationManifest,- VerifyVisualizationValue,- VerifyVisualizationView,-} from '@lobechat/types';-import { verifyCheckDefinitionSchema } from '@lobechat/types';-import { parseKlmTrace, summarizeKlmTrace } from '@lobechat/utils/verify/interactionCost';-import pc from 'picocolors';--import { printTable, truncate } from '../utils/format';-import { log } from '../utils/logger';--export type VerifierType = 'agent' | 'llm' | 'program';-export type OnFail = 'auto_repair' | 'manual';-export type Decision = 'accepted' | 'overridden' | 'rejected';--export const VERIFIER_TYPES: VerifierType[] = ['program', 'agent', 'llm'];-export const ON_FAIL: OnFail[] = ['manual', 'auto_repair'];-export const DECISIONS: Decision[] = ['accepted', 'rejected', 'overridden'];-/** The evidence media a plan item may require — the same closed set the executor gates on. */-export const EVIDENCE_TYPES = verifyEvidenceTypes;--export function parseConfig(raw?: string): Record<string, unknown> | undefined {- if (!raw) return undefined;- try {- return JSON.parse(raw);- } catch {- log.error('--config must be valid JSON');- process.exit(1);- }-}--export function assertEnum<T extends string>(- value: T | undefined,- allowed: T[],- flag: string,-): void {- if (value !== undefined && !allowed.includes(value)) {- log.error(`${flag} must be one of: ${allowed.join(', ')}`);- process.exit(1);- }-}--export type Verdict = 'failed' | 'passed' | 'uncertain';-export type EvidenceType =- 'audio' | 'dom_snapshot' | 'gif' | 'markdown' | 'screenshot' | 'text' | 'transcript' | 'video';--export const INLINE_TEXT_EVIDENCE_LIMIT = 5000;-export const INLINE_TEXT_EVIDENCE_TYPES = new Set<EvidenceType>([- 'dom_snapshot',- 'markdown',- 'text',- 'transcript',-]);--/** Map a free-form case/summary result token onto the verify verdict vocabulary. */-export function toVerdict(raw: unknown): Verdict {- const s = String(raw ?? '').toLowerCase();- if (['pass', 'passed', 'ok', 'success'].includes(s)) return 'passed';- if (['fail', 'failed', 'error'].includes(s)) return 'failed';- return 'uncertain'; // partial / blocked / skipped / pending / unknown-}--/**- * The report's headline verdict when the author didn't set `summary.verdict`:- * derived from the ingested cases, so a report can never ship verdict-less and- * render as a permanent "?" in every list surface.- */-export function deriveReportVerdict(cases: unknown[]): Verdict | undefined {- // Same field fallback as the per-case ingest (`result ?? status ?? verdict`) —- // the documented case field is `status`, so dropping it here derived- // `uncertain` for an all-pass report whenever this fallback actually ran.- const verdicts = cases.map((c) =>- toVerdict((c as any)?.result ?? (c as any)?.status ?? (c as any)?.verdict),- );- if (verdicts.length === 0) return undefined;- if (verdicts.includes('failed')) return 'failed';- if (verdicts.includes('uncertain')) return 'uncertain';- return 'passed';-}--/** Pick an evidence medium from a file extension. */-export function evidenceTypeForFile(file: string): EvidenceType {- const ext = path.extname(file).toLowerCase().slice(1);- if (ext === 'gif') return 'gif';- if (['png', 'jpg', 'jpeg', 'webp', 'svg', 'bmp'].includes(ext)) return 'screenshot';- if (['mp4', 'webm', 'mov', 'm4v'].includes(ext)) return 'video';- // Audio before the text fallback: an unrecognized binary used to land on- // `text`, publishing a TTS clip as an unreadable, unplayable blob.- if (- ['mp3', 'wav', 'm4a', 'aac', 'flac', 'ogg', 'oga', 'opus', 'aiff', 'aif', 'wma'].includes(ext)- )- return 'audio';- if (['html', 'htm'].includes(ext)) return 'dom_snapshot';- if (['md', 'markdown'].includes(ext)) return 'markdown';- return 'text';-}--export function inlineTextEvidenceForFile(- file: string,- type: EvidenceType | string,-): string | undefined {- if (!INLINE_TEXT_EVIDENCE_TYPES.has(type as EvidenceType)) return undefined;-- try {- const buffer = readFileSync(file);- if (buffer.includes(0)) return undefined;-- const content = buffer.toString('utf8');- return content.length > 0 && content.length < INLINE_TEXT_EVIDENCE_LIMIT ? content : undefined;- } catch {- return undefined;- }-}--/** Normalize a case's `evidence` field (string | string[] | {path}[]) to path strings. */-export interface ReportEvidenceInput {- /** Video only: agent markers on the timeline — steps it took, claims it checked, flags it raised. */- chapters?: VerifyEvidenceChapter[];- comparison?: {- id: string;- label?: string;- layout?: 'horizontal' | 'vertical';- role: 'after' | 'before';- };- description?: string;- path: string;-}--const VISUALIZATION_FIELD_TYPES = new Set(['boolean', 'category', 'number', 'string', 'temporal']);-const VISUALIZATION_TYPES = new Set([- 'bar-chart',- 'heatmap',- 'line-chart',- 'metric-comparison',- 'scatter-plot',- 'table',-]);-const MAX_INLINE_VISUALIZATION_ROWS = 10_000;--const visualizationValue = (value: unknown): value is VerifyVisualizationValue =>- value === null || ['boolean', 'number', 'string'].includes(typeof value);--const visualizationField = (- encoding: Record<string, unknown>,- key: string,- fieldKeys: Set<string>,- path: string,-) => {- const field = firstString(encoding[key]);- if (!field || !fieldKeys.has(field)) {- throw new Error(`${path}.${key} must reference a declared dataset field`);- }- return field;-};--const optionalVisualizationField = (- encoding: Record<string, unknown>,- key: string,- fieldKeys: Set<string>,- path: string,-) => {- if (encoding[key] === undefined) return;- visualizationField(encoding, key, fieldKeys, path);-};--const optionalVisualizationString = (value: Record<string, unknown>, key: string, path: string) => {- if (value[key] !== undefined && !firstString(value[key])) {- throw new Error(`${path}.${key} must be a non-empty string`);- }-};--const visualizationSeries = (- encoding: Record<string, unknown>,- fieldKeys: Set<string>,- path: string,- options?: { styles?: boolean },-) => {- if (!Array.isArray(encoding.series) || encoding.series.length === 0) {- throw new Error(`${path}.series must be a non-empty array`);- }- encoding.series.forEach((rawSeries, seriesIndex) => {- const series = objectValue(rawSeries);- const seriesPath = `${path}.series[${seriesIndex}]`;- if (!series) throw new Error(`${seriesPath} must be an object`);- visualizationField(series, 'field', fieldKeys, seriesPath);- if (series.label !== undefined && !firstString(series.label)) {- throw new Error(`${seriesPath}.label must be a non-empty string`);- }- if (- options?.styles &&- series.style !== undefined &&- !['accent', 'muted', 'primary'].includes(String(series.style))- ) {- throw new Error(`${seriesPath}.style is invalid`);- }- });-};--const validateVisualizationEncoding = (- view: Record<string, unknown>,- fieldKeys: Set<string>,- index: number,-) => {- const path = `visualizations[${index}].encoding`;- if (view.type === 'table' && view.encoding === undefined) return;- const encoding = objectValue(view.encoding);- if (!encoding) throw new Error(`${path} is required for ${String(view.type)}`);-- switch (view.type) {- case 'bar-chart': {- visualizationField(encoding, 'category', fieldKeys, path);- visualizationSeries(encoding, fieldKeys, path);- optionalVisualizationString(encoding, 'valueLabel', path);- break;- }- case 'heatmap': {- visualizationField(encoding, 'x', fieldKeys, path);- visualizationField(encoding, 'y', fieldKeys, path);- visualizationField(encoding, 'value', fieldKeys, path);- break;- }- case 'line-chart': {- visualizationField(encoding, 'x', fieldKeys, path);- visualizationSeries(encoding, fieldKeys, path, { styles: true });- optionalVisualizationString(encoding, 'xLabel', path);- optionalVisualizationString(encoding, 'yLabel', path);- break;- }- case 'metric-comparison': {- visualizationField(encoding, 'label', fieldKeys, path);- visualizationField(encoding, 'before', fieldKeys, path);- visualizationField(encoding, 'after', fieldKeys, path);- for (const key of [- 'afterSamples',- 'beforeSamples',- 'direction',- 'statistic',- 'target',- 'unit',- ]) {- optionalVisualizationField(encoding, key, fieldKeys, path);- }- break;- }- case 'scatter-plot': {- visualizationField(encoding, 'x', fieldKeys, path);- visualizationField(encoding, 'y', fieldKeys, path);- optionalVisualizationField(encoding, 'color', fieldKeys, path);- optionalVisualizationField(encoding, 'label', fieldKeys, path);- optionalVisualizationString(encoding, 'xLabel', path);- optionalVisualizationString(encoding, 'yLabel', path);- break;- }- case 'table': {- if (encoding.columns !== undefined) {- if (!Array.isArray(encoding.columns) || encoding.columns.length === 0) {- throw new Error(`${path}.columns must be a non-empty array`);- }- encoding.columns.forEach((field, fieldIndex) =>- visualizationField({ field }, 'field', fieldKeys, `${path}.columns[${fieldIndex}]`),- );- }- if (encoding.highlights !== undefined) {- if (!Array.isArray(encoding.highlights)) {- throw new Error(`${path}.highlights must be an array`);- }- encoding.highlights.forEach((rawHighlight, highlightIndex) => {- const highlight = objectValue(rawHighlight);- const highlightPath = `${path}.highlights[${highlightIndex}]`;- if (!highlight) throw new Error(`${highlightPath} must be an object`);- visualizationField(highlight, 'field', fieldKeys, highlightPath);- if (highlight.mode !== 'max' && highlight.mode !== 'min') {- throw new Error(`${highlightPath}.mode must be max or min`);- }- });- }- break;- }- }-};--/** Parse the case's datasets + views into versioned check-result metadata. */-export function visualizationMetadata(value: unknown): VerifyCheckResultMetadata | undefined {- const input = objectValue(value);- if (!input || (input.datasets === undefined && input.visualizations === undefined))- return undefined;- if (!Array.isArray(input.datasets) || !Array.isArray(input.visualizations)) {- throw new Error('datasets and visualizations must both be arrays');- }-- let rowCount = 0;- const datasets = input.datasets.map((rawDataset, datasetIndex) => {- const dataset = objectValue(rawDataset);- const id = firstString(dataset?.id);- if (!id || !Array.isArray(dataset?.fields) || !Array.isArray(dataset.rows)) {- throw new Error(`datasets[${datasetIndex}] needs id, fields, and rows`);- }-- const fields = dataset.fields.map((rawField, fieldIndex) => {- const field = objectValue(rawField);- const key = firstString(field?.key);- const type = field?.type;- if (!key || typeof type !== 'string' || !VISUALIZATION_FIELD_TYPES.has(type)) {- throw new Error(`datasets[${datasetIndex}].fields[${fieldIndex}] is invalid`);- }- return {- key,- label: firstString(field.label),- type,- unit: firstString(field.unit),- } as VerifyVisualizationField;- });- const fieldKeys = new Set(fields.map((field) => field.key));- if (fieldKeys.size !== fields.length) {- throw new Error(`datasets[${datasetIndex}] field keys must be unique`);- }-- const rows = dataset.rows.map((rawRow, rowIndex) => {- const row = objectValue(rawRow);- if (- !row ||- Object.entries(row).some(([key, cell]) => !fieldKeys.has(key) || !visualizationValue(cell))- ) {- throw new Error(`datasets[${datasetIndex}].rows[${rowIndex}] does not match its fields`);- }- return row as Record<string, VerifyVisualizationValue>;- });- rowCount += rows.length;- return { fields, id, rows } satisfies VerifyVisualizationDataset;- });-- if (rowCount > MAX_INLINE_VISUALIZATION_ROWS) {- throw new Error(`visualization metadata exceeds ${MAX_INLINE_VISUALIZATION_ROWS} inline rows`);- }- const datasetIds = new Set(datasets.map((dataset) => dataset.id));- if (datasetIds.size !== datasets.length) throw new Error('dataset ids must be unique');- const fieldKeysByDataset = new Map(- datasets.map((dataset) => [dataset.id, new Set(dataset.fields.map((field) => field.key))]),- );-- const views = input.visualizations.map((rawView, index) => {- const view = objectValue(rawView);- const id = firstString(view?.id);- const type = view?.type;- const dataset = firstString(view?.dataset);- if (- !id ||- typeof type !== 'string' ||- !VISUALIZATION_TYPES.has(type) ||- !dataset ||- !datasetIds.has(dataset) ||- view.version !== 1- ) {- throw new Error(`visualizations[${index}] has an invalid id, type, version, or dataset`);- }- optionalVisualizationString(view, 'context', `visualizations[${index}]`);- optionalVisualizationString(view, 'title', `visualizations[${index}]`);- validateVisualizationEncoding(view, fieldKeysByDataset.get(dataset)!, index);- return view as unknown as VerifyVisualizationView;- });- if (new Set(views.map((view) => view.id)).size !== views.length) {- throw new Error('visualization ids must be unique');- }-- const visualization: VerifyVisualizationManifest = { datasets, schemaVersion: 1, views };- return { visualization };-}--export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {- if (!evidence) return [];- const arr = Array.isArray(evidence) ? evidence : [evidence];- return arr- .map((e): ReportEvidenceInput | null => {- if (typeof e === 'string') return { path: e };- const value = objectValue(e);- const evidencePath = value && firstString(value.path, value.file);- if (!evidencePath) return null;- const comparison = objectValue(value.comparison);- const role = comparison?.role;- const id = firstString(comparison?.id);- // The report viewer pairs on `id` and drops any comparison lacking one, so- // an id-less half could never render side by side. Warn rather than upload- // a comparison that is silently downgraded to an ordinary image.- //- // Test the raw field, not the parsed object: a comparison written flat- // (`comparison: "row", role: "before"`) is not an object at all, so keying- // the warning off `objectValue()` skipped the one shape that most needs- // it — the author saw a clean ingest and unpaired images on the page.- // Absent means null/undefined only; `""` / `0` / `false` are malformed- // values that were written on purpose, so they warn like any other.- const hasComparison = value.comparison !== undefined && value.comparison !== null;- if (hasComparison && !(comparison && id && (role === 'before' || role === 'after'))) {- log.warn(- `evidence ${evidencePath}: comparison must be an object with a string "id" and role "before"/"after" — ignoring it`,- );- }- const layout = comparison?.layout === 'vertical' ? 'vertical' : undefined;- return {- chapters: reportEvidenceChapters(evidencePath, value.chapters),- comparison:- id && (role === 'before' || role === 'after')- ? { id, label: firstString(comparison?.label), layout, role }- : undefined,- description: firstString(value.description, value.desc),- path: evidencePath,- };- })- .filter((item): item is ReportEvidenceInput => item !== null);-}--/**- * A video's chapters, with every dropped marker named: a marker the reviewer- * never sees is a claim the agent believes it made, so the author must know.- */-function reportEvidenceChapters(- evidencePath: string,- raw: unknown,-): VerifyEvidenceChapter[] | undefined {- if (raw === undefined || raw === null) return undefined;- if (evidenceTypeForFile(evidencePath) !== 'video') {- log.warn(`evidence ${evidencePath}: chapters only apply to video evidence — ignoring them`);- return undefined;- }- if (!Array.isArray(raw)) {- log.warn(`evidence ${evidencePath}: chapters must be an array — ignoring them`);- return undefined;- }- const chapters = readEvidenceChapters(raw) ?? [];- const dropped = raw.length - chapters.length;- if (dropped > 0) {- log.warn(- `evidence ${evidencePath}: dropped ${dropped} of ${raw.length} chapters — each needs a non-negative "t" (seconds), a "kind" of step/check/flag, a "label" for a step and a "note" for a check or flag`,- );- }- return chapters.length > 0 ? chapters : undefined;-}--export function firstString(...values: unknown[]): string | undefined {- return values.find((v): v is string => typeof v === 'string' && v.length > 0);-}--export function firstStringOrNumber(...values: unknown[]): string | number | undefined {- return values.find(- (v): v is string | number => (typeof v === 'string' && v.length > 0) || typeof v === 'number',- );-}--export function objectValue(value: unknown): Record<string, unknown> | undefined {- return value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : undefined;-}--export function safeWebUrl(value: string | undefined): string | undefined {- if (!value) return undefined;-- try {- const url = new URL(value);- return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined;- } catch {- return undefined;- }-}--/** Normalize common agent-testing PR shapes into the verify coding scope. */-export function pullRequestFromResult(result: Record<string, unknown>) {- const pr = objectValue(result.pullRequest) ?? objectValue(result.pr);- const url = safeWebUrl(- firstString(- pr?.url,- pr?.htmlUrl,- pr?.html_url,- result.pullRequestUrl,- result.prUrl,- typeof result.pr === 'string' ? result.pr : undefined,- ),- );- const number = firstStringOrNumber(pr?.number, result.pullRequestNumber, result.prNumber);- const title = firstString(pr?.title, result.pullRequestTitle, result.prTitle);- const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);-- return entries.length > 0 ? Object.fromEntries(entries) : undefined;-}--/**- * The PR for a branch, asked of `gh`. A report almost always verifies a branch- * that already has one, but the author has to remember to write it down — and- * mostly doesn't, so the report loses its single most useful outbound link.- * Best-effort by design: no `gh`, not a repo, not authenticated, or no PR for- * the branch all mean "no PR", never a failed publish.- */-export function pullRequestFromBranch(branch: string | undefined) {- if (!branch) return undefined;-- try {- const raw = execFileSync(- 'gh',- ['pr', 'view', branch, '--json', 'number,title,url'],- // `gh` writes its "no pull requests found" diagnostics to stderr; keep them- // off the CLI's own output.- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 },- );- const parsed = objectValue(JSON.parse(raw));- const url = safeWebUrl(firstString(parsed?.url));- const number = firstStringOrNumber(parsed?.number);- const title = firstString(parsed?.title);- const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);-- return entries.length > 0 ? Object.fromEntries(entries) : undefined;- } catch {- return undefined;- }-}--/**- * The surfaces the report says it exercised, as canonical values.- *- * Strict on purpose: an unrecognized surface is a hard error, not a silently- * dropped value. Free-form surfaces are how the field rotted — prose, runtime- * modes ("packaged build") and test kinds ("unit", "type-check") all ended up in- * it, and none of them render. Failing here puts the fix in the author's hands- * while they still have the context to make it.- */-export function surfacesFromResult(result: Record<string, unknown>): VerifySurface[] | undefined {- if (!Array.isArray(result.surfaces)) return undefined;-- const raw = result.surfaces.filter((s: unknown): s is string => typeof s === 'string');- const canonical: VerifySurface[] = [];- const rejected: string[] = [];-- for (const value of raw) {- const surface = normalizeVerifySurface(value);- if (surface) {- if (!canonical.includes(surface)) canonical.push(surface);- } else {- rejected.push(value);- }- }-- if (rejected.length > 0) {- log.error(- `result.json "surfaces" must name the product surface a check ran on, one of: ${verifySurfaces.join(', ')}`,- );- log.error(` rejected: ${rejected.map((v) => JSON.stringify(v)).join(', ')}`);- log.error(- ' Runtime detail ("packaged build", "CDP dev instance") belongs on a plan item\'s "method"; a test kind ("unit", "backend") is not a surface — a backend change verified through the CLI has surface "cli".',- );- process.exit(1);- }-- return canonical.length > 0 ? canonical : undefined;-}--/**- * What kind of delivery the report verified. Defaults to `coding` — the- * agent-testing harness's home turf — and rejects an unknown value rather than- * storing a scenario nothing renders (mirrors the strict surface policy: the- * author still has the context to fix it).- */-export function scenarioFromResult(result: Record<string, unknown>): VerifyRunScenario {- const raw = result.scenario;- if (raw === undefined) return 'coding';- if (typeof raw === 'string' && (verifyRunScenarios as readonly string[]).includes(raw)) {- return raw as VerifyRunScenario;- }-- log.error(- `result.json "scenario" must be one of: ${verifyRunScenarios.join(', ')} — rejected: ${JSON.stringify(raw)}`,- );- process.exit(1);-}--/**- * A non-coding scenario's scope, passed through from result.json `context` as- * the scenario's own bag (the server stores it as-is; known shapes live in- * `@lobechat/types`). Top-level `entry` / `createdAt` are lifted as defaults so- * every scenario gets the shared provenance fields for free; explicit `context`- * keys win.- */-export function genericContextFromResult(- result: Record<string, unknown>,-): Record<string, unknown> | undefined {- const bag = objectValue(result.context) ?? {};- const entries = Object.entries({- entry: firstString(result.entry),- testedAt: firstString(result.createdAt),- ...bag,- }).filter(([, v]) => v !== undefined);-- return entries.length > 0 ? Object.fromEntries(entries) : undefined;-}--/** The id a plan entry / case will be ingested under, mirroring the readers below. */-const planItemId = (item: Record<string, unknown>, index: number) =>- String(item.id ?? `case-${index + 1}`);-const caseItemId = (item: Record<string, unknown>, index: number) =>- String(item.id ?? item.checkItemId ?? `case-${index + 1}`);--/** The outcome of {@link screenProgrammaticTestChecks}. */-export interface ProgrammaticTestScreen {- /** Check ids to omit from both the frozen plan and the ingested cases. */- droppedIds: Set<string>;- /** What was dropped, `id — title`, for one warning the author can act on. */- droppedLabels: string[];-}--/**- * Which checks in this report are the repo's own programmatic test / static-- * analysis gates rather than delivery outcomes a person accepts.- *- * Screened once, over the plan AND the cases, so a dropped plan item can never- * leave its case behind as an orphan "unplanned" row (or the reverse). Both- * sides are matched on their own text, then unioned by id.- *- * Dropping one item rather than failing the ingest is deliberate: the round's- * real checks are still worth publishing, and a hard error would cost the author- * the whole publish over an item they only meant as a footnote. (The caller does- * refuse to publish when the screen empties the round — then there is nothing- * left for a person to accept.)- */-export function screenProgrammaticTestChecks(- result: Record<string, unknown>,-): ProgrammaticTestScreen {- const droppedIds = new Set<string>();- const droppedLabels: string[] = [];-- const screen = (entry: unknown, id: string) => {- const item = objectValue(entry);- if (!item) return;- const title = firstString(item.title, item.name, item.case);- if (- !isProgrammaticTestCheck(- title,- firstString(item.category, item.group),- firstString(item.method, item.how),- )- ) {- return;- }- if (!droppedIds.has(id)) {- droppedIds.add(id);- droppedLabels.push(title ? `${id} — ${title}` : id);- }- };-- if (Array.isArray(result.plan)) {- result.plan.forEach((entry, index) =>- screen(entry, planItemId(objectValue(entry) ?? {}, index)),- );- }- if (Array.isArray(result.cases)) {- result.cases.forEach((entry, index) =>- screen(entry, caseItemId(objectValue(entry) ?? {}, index)),- );- }-- if (droppedLabels.length > 0) {- log.warn(- `dropping ${droppedLabels.length} programmatic-test check(s) from this acceptance round:`,- );- for (const label of droppedLabels) log.warn(` - ${label}`);- log.warn(` ${PROGRAMMATIC_TEST_CHECK_HINT}`);- }-- return { droppedIds, droppedLabels };-}--/** Reject an out-of-vocabulary plan value rather than storing a word nothing reads. */-export function assertPlanEnum<T extends string>(- value: string,- allowed: readonly T[],- field: string,- itemId: string,-): T {- if ((allowed as readonly string[]).includes(value)) return value as T;-- log.error(`result.json plan item "${itemId}": "${field}" must be one of: ${allowed.join(', ')}`);- log.error(` rejected: ${JSON.stringify(value)}`);- process.exit(1);-}--/**- * The checks the run set out to make, as frozen plan items.- *- * Two of the fields are a closed vocabulary, not free text, because the pipeline- * actually acts on them:- *- * - `verifier` → {@link VerifyCheckItem.verifierType} (`program | agent | llm`):- * how the item is judged. Defaults to `agent`, but a command-asserted check is- * `program` and mislabelling it hides what actually produced the verdict.- * - `requiredEvidence` → `verifierConfig.requiredEvidence`- * ({@link RequiredEvidenceSpec}, medium from {@link verifyEvidenceTypes}):- * the artifact the item MUST produce. The executor's coverage gate fails an- * item whose required medium is missing, so this is enforcement, not a label —- * an unknown medium would silently gate on nothing.- *- * `method` / `expected` stay prose: they are the author's intent in words, which- * no enum can carry. Everything else the frozen {@link VerifyCheckItem} needs is- * filled in here, so an author writes only `{ id, title }` plus what they mean.- *- * Returns `undefined` when the report declares no `plan` field. A `plan` that is- * present but empty returns `[]`, recording an explicitly empty plan in this- * immutable snapshot.- *- * `droppedIds` (from {@link screenProgrammaticTestChecks}) omits the repo's own- * test/lint gates, which are shipping preconditions rather than acceptance items.- */-export function planFromResult(result: Record<string, unknown>, droppedIds?: Set<string>) {- if (!Array.isArray(result.plan)) return undefined;-- const items = result.plan.flatMap((entry: unknown, index: number) => {- const item = objectValue(entry);- const title = firstString(item?.title, item?.name);- // An item with no title names no check — it can't be rendered or paired.- if (!item || !title) return [];-- const id = planItemId(item, index);- if (droppedIds?.has(id)) return [];- const method = firstString(item.method, item.how);- const expected = firstString(item.expected, item.expectation);-- const verifierRaw = firstString(item.verifier, item.verifierType);- const verifierType = verifierRaw- ? assertPlanEnum(verifierRaw, VERIFIER_TYPES, 'verifier', id)- : ('agent' as const);-- const requiredEvidence = Array.isArray(item.requiredEvidence)- ? item.requiredEvidence.flatMap((spec: unknown) => {- // Accept the bare medium (`"screenshot"`) or the full spec object.- const record = objectValue(spec);- const raw = typeof spec === 'string' ? spec : firstString(record?.type);- if (!raw) return [];-- return [- {- hint: firstString(record?.hint),- type: assertPlanEnum(raw, EVIDENCE_TYPES, 'requiredEvidence', id),- },- ];- })- : [];-- // Per-item surface: the acceptance union groups checks by it. Normalized to- // the closed set (electron → desktop); an unknown value is dropped loudly- // rather than stored as a mystery chip.- const surfaceRaw = firstString(item.surface);- const surface = surfaceRaw ? normalizeVerifySurface(surfaceRaw) : null;- if (surfaceRaw && !surface) {- log.warn(- `plan item "${id}": surface "${surfaceRaw}" names no product surface (expected ${verifySurfaces.join('/')}) — dropping it`,- );- }-- // The acceptance union groups by category and folds superseded ids into- // the new item's iteration timeline — both authored by the harness.- const category = firstString(item.category, item.group);- const supersedes = Array.isArray(item.supersedes)- ? item.supersedes.filter((value: unknown): value is string => typeof value === 'string')- : [];-- return [- {- ...(category === undefined ? {} : { category }),- description: firstString(item.description),- sourceCriterionId: firstString(item.sourceCriterionId),- definition:- item.definition === undefined- ? undefined- : verifyCheckDefinitionSchema.parse(item.definition),- id,- index,- onFail: 'manual' as const,- required: typeof item.required === 'boolean' ? item.required : true,- ...(supersedes.length > 0 ? { supersedes } : {}),- title,- verifierConfig: {- ...(method === undefined ? {} : { method }),- ...(expected === undefined ? {} : { expected }),- ...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),- ...(surface ? { surface } : {}),- },- verifierType,- },- ];- });-- // `[]` is meaningful — it clears a stale plan. Only an absent `plan` field- // (handled above) means "don't touch what's stored".- return items;-}--interface ExistingAcceptanceCheck {- id: string;- planItem?: { id?: string; sourceCriterionId?: string | null } | null;-}--/**- * Line a new round's plan up with the checks its acceptance already holds.- * The server mints a fresh criterion for every item that arrives without one,- * and the union keys rows by criterion — so a re-verification that skips this- * lands every check as a brand-new row instead of the next entry in its history.- */-export function reuseSourceCriteria<T extends { id: string; sourceCriterionId?: string | null }>(- plan: T[] | undefined,- checks: ExistingAcceptanceCheck[] | null | undefined,-): T[] | undefined {- if (!plan || !checks?.length) return plan;-- return plan.map((item) => ({- ...item,- sourceCriterionId:- item.sourceCriterionId ??- checks.find((check) => check.id === item.id || check.planItem?.id === item.id)?.planItem- ?.sourceCriterionId ??- undefined,- }));-}--interface ExistingAcceptanceRound {- report?: { content?: string | null; summary?: string | null } | null;- run: {- id: string;- plan?: { id: string; title: string }[] | null;- roundIndex?: number | null;- };-}--/**- * The acceptance's latest round when it already publishes exactly this report.- * Re-running the same ingest (a retry loop, a re-sent command) would otherwise- * stack identical rounds on the page. Compares what the author wrote — body,- * conclusion and plan — not the published counts, which the ingest derives- * later from evidence uploads. Only a report with a body counts: without one,- * two genuinely different runs of the same plan are indistinguishable here.- */-export function findIdenticalLatestRound(- rounds: ExistingAcceptanceRound[] | null | undefined,- incoming: {- plan?: { id: string; title: string }[];- report: { content?: string; summary?: string };- },-): ExistingAcceptanceRound['run'] | undefined {- if (!incoming.report.content || !rounds?.length) return undefined;-- const latest = rounds.reduce((a, b) =>- (b.run.roundIndex ?? 0) > (a.run.roundIndex ?? 0) ? b : a,- );- const published = latest.report;- if (!published) return undefined;-- const same = (a: unknown, b: unknown) => (a ?? null) === (b ?? null);- const planKey = (items: { id: string; title: string }[] | null | undefined) =>- JSON.stringify((items ?? []).map(({ id, title }) => [id, title]));-- const identical =- same(published.content, incoming.report.content) &&- same(published.summary, incoming.report.summary) &&- planKey(latest.run.plan) === planKey(incoming.plan);-- return identical ? latest.run : undefined;-}--/**- * The LobeHub conversation this harness is running inside, read off the env the- * agent runtime echoes into the child process. Lets a report published from an- * in-app agent link back to the session that produced it with no flags to- * remember. Absent (a plain terminal) → no origin, which is not an error.- *- * Reads the env and ONLY the env. `--operation` is the opposite relation — the- * Agent Run this session *verifies* — so letting it fall through to here would- * attribute the report to the run under test instead of the run that wrote it,- * corrupting the very provenance this records. The two ids are independent and- * may legitimately differ in the same publish.- */-export function originFromEnv(): VerifyRunOrigin | undefined {- const origin: VerifyRunOrigin = {- agentId: firstString(process.env.LOBEHUB_AGENT_ID),- operationId: firstString(process.env.LOBEHUB_OPERATION_ID),- topicId: firstString(process.env.LOBEHUB_TOPIC_ID),- };-- return Object.values(origin).some(Boolean) ? origin : undefined;-}--/**- * 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,- origin?: VerifyRunOrigin,-): Record<string, unknown> | undefined {- const hasInteractionCost = Object.prototype.hasOwnProperty.call(result, 'interactionCost');- // Nothing to write is not the same as writing an empty metadata bag.- if (!hasInteractionCost && !origin) return undefined;-- const metadata = { ...objectValue(existingMetadata) };-- if (hasInteractionCost) {- const interactionCost = objectValue(result.interactionCost);-- if (interactionCost) {- metadata.interactionCost = interactionCost;- } else {- delete metadata.interactionCost;- }- }-- if (origin) metadata.origin = origin;-- return metadata;-}--/** A parsed acceptance subject reference (`task:<id>` / `topic:<id>` / `document:<id>`). */-export interface AcceptanceSubjectRef {- subjectId: string;- subjectType: AcceptanceSubjectType;-}--/**- * Parse a `type:id` subject reference. Returns null on anything malformed —- * callers decide whether that is an error (an explicit `--subject`) or a- * silently absent field (result.json).- */-export function parseSubjectRef(raw: unknown): AcceptanceSubjectRef | null {- if (typeof raw !== 'string') return null;- const idx = raw.indexOf(':');- if (idx <= 0) return null;- const type = raw.slice(0, idx).trim().toLowerCase();- const id = raw.slice(idx + 1).trim();- if (!id || !(acceptanceSubjectTypes as readonly string[]).includes(type)) return null;- return { subjectId: id, subjectType: type as AcceptanceSubjectType };-}--/**- * The acceptance subject a report attributes itself to, from result.json's- * `subject` field — either `"task:<id>"` or `{ type, id, requirement? }`. An- * explicit `--subject` flag wins over this.- */-export function subjectFromResult(result: Record<string, unknown>): {- ref: AcceptanceSubjectRef;- requirement?: string;-} | null {- const raw = result.subject;- if (typeof raw === 'string') {- const ref = parseSubjectRef(raw);- return ref ? { ref } : null;- }- const value = objectValue(raw);- if (!value) return null;- const ref = parseSubjectRef(`${firstString(value.type) ?? ''}:${firstString(value.id) ?? ''}`);- return ref ? { ref, requirement: firstString(value.requirement) } : null;-}--/** Default acceptance subject for a report authored inside a LobeHub topic. */-export function subjectFromEnv(): AcceptanceSubjectRef | null {- const topicId = firstString(process.env.LOBEHUB_TOPIC_ID);- return topicId ? { subjectId: topicId, subjectType: 'topic' } : null;-}--export function printResults(results: any[]): void {- printTable(- results.map((r) => [- truncate(r.checkItemTitle || r.checkItemId, 50),- statusColor(r.status),- r.verdict ?? '',- r.confidence != null ? String(r.confidence) : '',- r.required ? 'gate' : 'soft',- truncate(r.suggestion || '', 40),- ]),- ['CHECK', 'STATUS', 'VERDICT', 'CONF', 'BLOCK', 'SUGGESTION'],- );-}--export function statusColor(status: string): string {- if (status === 'passed') return pc.green(status);- if (status === 'failed') return pc.red(status);- if (status === 'running') return pc.yellow(status);- return pc.dim(status);-}--/** A region a reviewer circled on one evidence image, or on one video frame or span. */-export interface ReviewAnnotationRegion {- comment?: string;- /** The agent chapter the reviewer disagrees with. */- disputes?: { kind?: string; note?: string; t?: number };- evidenceId?: string;- rect?: { height?: number; width?: number; x?: number; y?: number };- time?: { end?: number; start?: number };-}--/** `m:ss.cc` — shared with the acceptance page so both read the same moment. */-export const formatVideoTime = formatVideoTimestamp;--const isSeconds = (value?: number): value is number =>- typeof value === 'number' && Number.isFinite(value) && value >= 0;--const asPercent = (value?: number) =>- typeof value === 'number' && Number.isFinite(value) ? `${Math.round(value * 100)}%` : undefined;--/**- * Where a review annotation points, rendered for a terminal.- *- * The comment alone is not enough to act on: a screenshot usually has several- * plausible targets, and without the image and the rect the reader has to guess- * which one was circled. `rect` is normalized to the image box (0–1), so it is- * printed as percentages. On a video the frame or span comes first, since the- * reader has to seek there before any region means anything.- *- * Returns `undefined` when the annotation carries no location at all — an older- * review, or one made before regions existed.- */-export function formatAnnotationRegion(- annotation: ReviewAnnotationRegion,- evidenceLabels?: Map<string, string>,-): string | undefined {- const label = annotation.evidenceId- ? (evidenceLabels?.get(annotation.evidenceId) ?? annotation.evidenceId)- : undefined;-- const { rect, time } = annotation;- let moment: string | undefined;- if (isSeconds(time?.start))- moment = isSeconds(time.end)- ? `${formatVideoTime(time.start)}–${formatVideoTime(time.end)}`- : `frame at ${formatVideoTime(time.start)}`;- // A video note that marks a moment without circling an area spans the whole- // frame; printing "0%,0% · 100%×100%" would read as a real region.- const wholeFrame =- moment !== undefined &&- rect !== undefined &&- isFullFrameRect({- height: rect.height ?? 0,- width: rect.width ?? 0,- x: rect.x ?? -1,- y: rect.y ?? -1,- });-- const x = asPercent(rect?.x);- const y = asPercent(rect?.y);- const width = asPercent(rect?.width);- const height = asPercent(rect?.height);- const at = x && y ? `${x},${y}` : undefined;- const size = width && height ? `${width}×${height}` : undefined;- const position = [moment, wholeFrame ? undefined : at, wholeFrame ? undefined : size]- .filter(Boolean)- .join(' · ');-- if (!label && !position) return undefined;- if (!position) return label;- return label ? `${label} @ ${position}` : position;-}--/**- * The agent's own claim a reviewer objected to, quoted back so the repair run- * sees exactly which of its statements was judged wrong.- */-export function formatDisputedChapter(disputes?: ReviewAnnotationRegion['disputes']) {- if (!disputes?.note) return undefined;- const at = isSeconds(disputes.t) ? ` at ${formatVideoTime(disputes.t)}` : '';- return `your ${disputes.kind ?? 'claim'}${at}: "${disputes.note}"`;-}--/** Keep file identity when small text artifacts are stored inline. */-export function evidenceDescriptionForFile(- description?: string,- file?: string,-): string | undefined {- return description?.trim() || (file ? path.basename(file) : undefined);-}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 3334b57a711..2e9924ff5b8 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -1,5 +1,7 @@import { Command } from 'commander';+import { registerAcceptanceCommands } from './commands/acceptance';+import { registerVerifyCommand } from './commands/acceptance/deprecatedVerify';import { registerAgentCommand } from './commands/agent';import { registerAgentGroupCommand } from './commands/agent-group';import { registerAgentSignalCommand } from './commands/agent-signal';@@ -39,8 +41,6 @@ import { registerTopicCommand } from './commands/topic';import { registerTraceCommand } from './commands/trace';import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';-import { registerVerifyCommand } from './commands/verify';-import { registerAcceptanceCommands } from './commands/verifyAcceptance';import { registerWidgetCommand } from './commands/widget';import { registerWorkspaceCommand } from './commands/workspace';import { CLI_DISPLAY_NAME, CLI_PRIMARY_BIN, CLI_PRODUCT_NAME } from './constants/identity';diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/verify/index.test.tssimilarity index 70%rename from apps/server/src/routers/lambda/__tests__/verify.test.tsrename to apps/server/src/routers/lambda/verify/index.test.tsindex 6d8318ff185..f18b2ed9bd3 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/verify/index.test.ts@@ -4,10 +4,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as FileModelModule from '@/database/models/file';import { createTRPCErrorLogger } from '@/libs/trpc/utils/errorLogger';-import { verifyRouter } from '@/server/routers/lambda/verify';import { FileService } from '@/server/services/file';import type * as VerifyServiceModule from '@/server/services/verify';+import { verifyRouter } from '.';+const modelMocks = vi.hoisted(() => ({createEvidence: vi.fn(),purgeVerifyRun: vi.fn(),@@ -542,275 +543,6 @@ describe('verifyRouter', () => {});});- describe('submitCheckEvidence', () => {- it("rejects a run outside the caller's scope before upserting", async () => {- modelMocks.findRunById.mockResolvedValueOnce(undefined);-- await expect(- createCaller().submitCheckEvidence({- checkItemId: 'item-1',- verdict: 'passed',- verifyRunId: 'other-user-run',- }),- ).rejects.toThrow('Verification run not found');-- expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();- expect(modelMocks.createEvidence).not.toHaveBeenCalled();- });-- it('rejects an evidence item with both inline content and fileId', async () => {- await expect(- createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ content: 'inline', fileId: 'files-1', type: 'text' }],- verifyRunId: 'run-1',- }),- ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');- });-- it('lazily upserts the check result and attaches evidence in one call', async () => {- modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verdict: 'passed' });- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });-- const res = await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ fileId: 'files-1', type: 'screenshot' }],- verdict: 'passed',- verifyRunId: 'run-1',- });-- expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(- expect.objectContaining({ checkItemId: 'item-1', verdict: 'passed', verifyRunId: 'run-1' }),- );- expect(modelMocks.createEvidence).toHaveBeenCalledWith(- expect.objectContaining({- checkResultId: 'result-1',- fileId: 'files-1',- type: 'screenshot',- }),- );- expect(res).toEqual({- checkResult: { id: 'result-1', verdict: 'passed' },- evidence: [{ id: 'evidence-1' }],- });- });-- it('allows a verdict-only submit with no evidence', async () => {- modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verdict: 'failed' });-- const res = await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- verdict: 'failed',- verifyRunId: 'run-1',- });-- expect(modelMocks.createEvidence).not.toHaveBeenCalled();- expect(res.evidence).toEqual([]);- });-- it('requires either verifyRunId or operationId', async () => {- await expect(- createCaller().submitCheckEvidence({ checkItemId: 'item-1', verdict: 'passed' } as any),- ).rejects.toThrow('Provide either `verifyRunId` or `operationId`.');- });-- it('resolves the run from operationId when no verifyRunId is given', async () => {- modelMocks.findRunByOperation.mockResolvedValueOnce({ id: 'run-9', plan: [] });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-9' });-- await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- operationId: 'op-1',- verdict: 'passed',- });-- expect(modelMocks.findRunByOperation).toHaveBeenCalledWith('op-1');- expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(- expect.objectContaining({ verifyRunId: 'run-9' }),- );- });-- it('does NOT reset required/status on an evidence-only submit (no clobber)', async () => {- modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });-- await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ content: 'note', type: 'text' }],- verifyRunId: 'run-1',- });-- const arg = modelMocks.upsertByCheckItem.mock.calls[0][0];- // Both omitted → drizzle preserves the existing row's values / DB defaults.- expect(arg.required).toBeUndefined();- expect(arg.status).toBeUndefined();- });-- it('hydrates required/verifierType/title from the run plan item', async () => {- modelMocks.findRunById.mockResolvedValueOnce({- id: 'run-1',- plan: [- { id: 'item-1', index: 2, required: false, title: 'soft check', verifierType: 'llm' },- ],- });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });-- await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ content: 'note', type: 'text' }],- verifyRunId: 'run-1',- });-- expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(- expect.objectContaining({- checkItemIndex: 2,- checkItemTitle: 'soft check',- required: false,- verifierType: 'llm',- }),- );- });-- it('lands evidence for a repaired check on the repair round, not the settled one', async () => {- const plan = [{ id: 'item-1', index: 0, required: true, title: 'mutation gif' }];- modelMocks.findRunById.mockResolvedValueOnce({ id: 'round-1', plan, status: 'failed' });- modelMocks.listResultsByRun.mockImplementation(async (runId: string) =>- runId === 'round-1'- ? [{ checkItemId: 'item-1', repairOperationId: 'repair-op-2' }]- : [{ checkItemId: 'item-1', repairOperationId: null }],- );- modelMocks.findRunByOperation.mockResolvedValueOnce({- id: 'round-2',- plan,- status: 'planned',- });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({- id: 'result-2',- verifyRunId: 'round-2',- });- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });-- await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ fileId: 'files-1', type: 'gif' }],- verifyRunId: 'round-1',- });-- expect(modelMocks.findRunByOperation).toHaveBeenCalledWith('repair-op-2');- expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(- expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'round-2' }),- );- expect(modelMocks.createEvidence).toHaveBeenCalledWith(- expect.objectContaining({ checkResultId: 'result-2', type: 'gif' }),- );- });-- it('stores a GIF uploaded as video as a gif, not a video', async () => {- // Builders without a gif type labelled their GIFs `video`; the acceptance- // page then played an animated image in a video player that failed to load.- modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });- modelMocks.findFileById.mockResolvedValueOnce({- fileType: 'image/gif',- id: 'files-gif',- name: 'rename.gif',- });- modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });-- await createCaller().submitCheckEvidence({- checkItemId: 'item-1',- evidence: [{ fileId: 'files-gif', type: 'video' }],- verifyRunId: 'run-1',- });-- expect(modelMocks.findFileById).toHaveBeenCalledWith('files-gif');- expect(modelMocks.createEvidence).toHaveBeenCalledWith(- expect.objectContaining({ fileId: 'files-gif', type: 'gif' }),- );- });-- it('rejects a check item that is not in the run plan instead of minting a required row', async () => {- modelMocks.findRunById.mockResolvedValueOnce({- id: 'run-1',- plan: [{ id: 'item-1', index: 0, required: true, title: 'gateway matrix' }],- });-- await expect(- createCaller().submitCheckEvidence({- checkItemId: 'pglite-classification',- evidence: [{ content: 'grep output', type: 'text' }],- verdict: 'passed',- verifyRunId: 'run-1',- }),- ).rejects.toThrow(- 'Check item "pglite-classification" is not in this verification run\'s plan. Use one of: item-1 (gateway matrix)',- );-- expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();- expect(modelMocks.createEvidence).not.toHaveBeenCalled();- });- });-- describe('uploadEvidence', () => {- it('rejects evidence with both inline content and fileId', async () => {- await expect(- createCaller().uploadEvidence({- checkResultId: 'result-1',- content: 'inline payload',- fileId: 'files-1',- type: 'text',- }),- ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');- });-- it('stores only well-formed chapters, and only on video evidence', async () => {- const chapters = [- { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },- { kind: 'step', label: 'Scroll #1', t: 2 },- { kind: 'check', t: 3 }, // a claim without a note says nothing- { kind: 'guess', note: 'unknown kind', t: 4 },- { kind: 'flag', note: 'negative time', t: -1 },- ];- modelMocks.findResultById.mockResolvedValue({ id: 'result-1' });-- await createCaller().uploadEvidence({- checkResultId: 'result-1',- fileId: 'files-video',- metadata: { chapters, comparison: { id: 'pair', role: 'after' } },- type: 'video',- });- await createCaller().uploadEvidence({- checkResultId: 'result-1',- fileId: 'files-shot',- metadata: { chapters },- type: 'screenshot',- });-- expect(modelMocks.createEvidence.mock.calls.map(([row]) => row.metadata)).toEqual([- {- chapters: [- { kind: 'step', label: 'Scroll #1', t: 2 },- { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },- ],- comparison: { id: 'pair', role: 'after' },- },- null,- ]);- modelMocks.findResultById.mockReset();- });-- it('rejects evidence without inline content or fileId', async () => {- await expect(- createCaller().uploadEvidence({- checkResultId: 'result-1',- type: 'text',- }),- ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');- });- });-describe('getReportBundle', () => {// The real column is uuid-typed and the router guards malformed ids before// querying, so the fixture id must be a well-formed uuid.diff --git a/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts b/apps/server/src/routers/lambda/verify/ingest.evidence.test.tsnew file mode 100644index 00000000000..ac53a9af613--- /dev/null+++ b/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts@@ -0,0 +1,371 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as FileModelModule from '@/database/models/file';++import { verifyRouter } from '.';++const modelMocks = vi.hoisted(() => ({+ createEvidence: vi.fn(),+ findFileById: vi.fn(),+ findResultById: vi.fn(),+ findRunById: vi.fn(),+ findRunByOperation: vi.fn(),+ listResultsByRun: vi.fn(),+ upsertByCheckItem: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));++vi.mock('@/database/models/verifyCheckResult', () => ({+ VerifyCheckResultModel: vi.fn(function () {+ return {+ findById: modelMocks.findResultById,+ listByRun: modelMocks.listResultsByRun,+ upsertByCheckItem: modelMocks.upsertByCheckItem,+ };+ }),+}));++vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(function () {+ return {+ findByOperation: modelMocks.findRunByOperation,+ findById: modelMocks.findRunById,+ };+ }),+}));++// Only the instance lookup the evidence write path uses is stubbed.+vi.mock('@/database/models/file', async (importOriginal) => {+ const actual = await importOriginal<typeof FileModelModule>();+ class FileModel extends actual.FileModel {+ findById = modelMocks.findFileById as unknown as actual.FileModel['findById'];+ }+ return { ...actual, FileModel };+});++vi.mock('@/database/models/verifyEvidence', () => ({+ VerifyEvidenceModel: vi.fn(function () {+ return { create: modelMocks.createEvidence };+ }),+}));++// The router context builds a FileService, which needs S3 env without this.+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return { getFullFileUrl: vi.fn() };+ }),+}));++const createCaller = () => verifyRouter.createCaller({ userId: 'verify-router-test-user' } as any);++describe('verifyRouter evidence writes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ modelMocks.listResultsByRun.mockResolvedValue([]);+ modelMocks.findFileById.mockResolvedValue(undefined);+ });++ describe('submitCheckEvidence', () => {+ it("rejects a run outside the caller's scope before upserting", async () => {+ modelMocks.findRunById.mockResolvedValueOnce(undefined);++ await expect(+ createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ verdict: 'passed',+ verifyRunId: 'other-user-run',+ }),+ ).rejects.toThrow('Verification run not found');++ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();+ expect(modelMocks.createEvidence).not.toHaveBeenCalled();+ });++ it('rejects an evidence item with both inline content and fileId', async () => {+ await expect(+ createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ content: 'inline', fileId: 'files-1', type: 'text' }],+ verifyRunId: 'run-1',+ }),+ ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');+ });++ it('lazily upserts the check result and attaches evidence in one call', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verdict: 'passed' });+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });++ const res = await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ fileId: 'files-1', type: 'screenshot' }],+ verdict: 'passed',+ verifyRunId: 'run-1',+ });++ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({ checkItemId: 'item-1', verdict: 'passed', verifyRunId: 'run-1' }),+ );+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(+ expect.objectContaining({+ checkResultId: 'result-1',+ fileId: 'files-1',+ type: 'screenshot',+ }),+ );+ expect(res).toEqual({+ checkResult: { id: 'result-1', verdict: 'passed' },+ evidence: [{ id: 'evidence-1' }],+ });+ });++ it('allows a verdict-only submit with no evidence', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verdict: 'failed' });++ const res = await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ verdict: 'failed',+ verifyRunId: 'run-1',+ });++ expect(modelMocks.createEvidence).not.toHaveBeenCalled();+ expect(res.evidence).toEqual([]);+ });++ it('requires either verifyRunId or operationId', async () => {+ await expect(+ createCaller().submitCheckEvidence({ checkItemId: 'item-1', verdict: 'passed' } as any),+ ).rejects.toThrow('Provide either `verifyRunId` or `operationId`.');+ });++ it('resolves the run from operationId when no verifyRunId is given', async () => {+ modelMocks.findRunByOperation.mockResolvedValueOnce({ id: 'run-9', plan: [] });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-9' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ operationId: 'op-1',+ verdict: 'passed',+ });++ expect(modelMocks.findRunByOperation).toHaveBeenCalledWith('op-1');+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({ verifyRunId: 'run-9' }),+ );+ });++ it('does NOT reset required/status on an evidence-only submit (no clobber)', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ content: 'note', type: 'text' }],+ verifyRunId: 'run-1',+ });++ const arg = modelMocks.upsertByCheckItem.mock.calls[0][0];+ // Both omitted → drizzle preserves the existing row's values / DB defaults.+ expect(arg.required).toBeUndefined();+ expect(arg.status).toBeUndefined();+ });++ it('hydrates required/verifierType/title from the run plan item', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({+ id: 'run-1',+ plan: [+ { id: 'item-1', index: 2, required: false, title: 'soft check', verifierType: 'llm' },+ ],+ });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ content: 'note', type: 'text' }],+ verifyRunId: 'run-1',+ });++ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({+ checkItemIndex: 2,+ checkItemTitle: 'soft check',+ required: false,+ verifierType: 'llm',+ }),+ );+ });++ it('lands evidence for a repaired check on the repair round, not the settled one', async () => {+ const plan = [{ id: 'item-1', index: 0, required: true, title: 'mutation gif' }];+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'round-1', plan, status: 'failed' });+ modelMocks.listResultsByRun.mockImplementation(async (runId: string) =>+ runId === 'round-1'+ ? [{ checkItemId: 'item-1', repairOperationId: 'repair-op-2' }]+ : [{ checkItemId: 'item-1', repairOperationId: null }],+ );+ modelMocks.findRunByOperation.mockResolvedValueOnce({+ id: 'round-2',+ plan,+ status: 'planned',+ });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({+ id: 'result-2',+ verifyRunId: 'round-2',+ });+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ fileId: 'files-1', type: 'gif' }],+ verifyRunId: 'round-1',+ });++ expect(modelMocks.findRunByOperation).toHaveBeenCalledWith('repair-op-2');+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'round-2' }),+ );+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(+ expect.objectContaining({ checkResultId: 'result-2', type: 'gif' }),+ );+ });++ it('stores a GIF uploaded as video as a gif, not a video', async () => {+ // Builders without a gif type labelled their GIFs `video`; the acceptance+ // page then played an animated image in a video player that failed to load.+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });+ modelMocks.findFileById.mockResolvedValueOnce({+ fileType: 'image/gif',+ id: 'files-gif',+ name: 'rename.gif',+ });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ fileId: 'files-gif', type: 'video' }],+ verifyRunId: 'run-1',+ });++ expect(modelMocks.findFileById).toHaveBeenCalledWith('files-gif');+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(+ expect.objectContaining({ fileId: 'files-gif', type: 'gif' }),+ );+ });++ it('keeps the chapters a plan-round video is submitted with', async () => {+ // A Task's builder submits through this procedure; without metadata its+ // recordings reached the reviewer with no timeline to seek along.+ const chapters = [+ { kind: 'check', note: 'device chip renders on the first frame', t: 2.4 },+ { kind: 'step', label: 'Reload with listDevices held', t: 1.2 },+ { kind: 'check', t: 3 },+ ];+ modelMocks.findRunByOperation.mockResolvedValueOnce({ id: 'run-1', plan: [] });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });+ modelMocks.createEvidence+ .mockResolvedValueOnce({ id: 'evidence-1' })+ .mockResolvedValueOnce({ id: 'evidence-2' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [+ { fileId: 'files-video', metadata: { chapters }, type: 'video' },+ { fileId: 'files-shot', metadata: { chapters }, type: 'screenshot' },+ ],+ operationId: 'op-1',+ });++ expect(modelMocks.createEvidence.mock.calls.map(([row]) => row.metadata)).toEqual([+ {+ chapters: [+ { kind: 'step', label: 'Reload with listDevices held', t: 1.2 },+ { kind: 'check', note: 'device chip renders on the first frame', t: 2.4 },+ ],+ },+ null,+ ]);+ });++ it('rejects a check item that is not in the run plan instead of minting a required row', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({+ id: 'run-1',+ plan: [{ id: 'item-1', index: 0, required: true, title: 'gateway matrix' }],+ });++ await expect(+ createCaller().submitCheckEvidence({+ checkItemId: 'pglite-classification',+ evidence: [{ content: 'grep output', type: 'text' }],+ verdict: 'passed',+ verifyRunId: 'run-1',+ }),+ ).rejects.toThrow(+ 'Check item "pglite-classification" is not in this verification run\'s plan. Use one of: item-1 (gateway matrix)',+ );++ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();+ expect(modelMocks.createEvidence).not.toHaveBeenCalled();+ });+ });++ describe('uploadEvidence', () => {+ it('rejects evidence with both inline content and fileId', async () => {+ await expect(+ createCaller().uploadEvidence({+ checkResultId: 'result-1',+ content: 'inline payload',+ fileId: 'files-1',+ type: 'text',+ }),+ ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');+ });++ it('stores only well-formed chapters, and only on video evidence', async () => {+ const chapters = [+ { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', t: 3 }, // a claim without a note says nothing+ { kind: 'guess', note: 'unknown kind', t: 4 },+ { kind: 'flag', note: 'negative time', t: -1 },+ ];+ modelMocks.findResultById.mockResolvedValue({ id: 'result-1' });++ await createCaller().uploadEvidence({+ checkResultId: 'result-1',+ fileId: 'files-video',+ metadata: { chapters, comparison: { id: 'pair', role: 'after' } },+ type: 'video',+ });+ await createCaller().uploadEvidence({+ checkResultId: 'result-1',+ fileId: 'files-shot',+ metadata: { chapters },+ type: 'screenshot',+ });++ expect(modelMocks.createEvidence.mock.calls.map(([row]) => row.metadata)).toEqual([+ {+ chapters: [+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },+ ],+ comparison: { id: 'pair', role: 'after' },+ },+ null,+ ]);+ modelMocks.findResultById.mockReset();+ });++ it('rejects evidence without inline content or fileId', async () => {+ await expect(+ createCaller().uploadEvidence({+ checkResultId: 'result-1',+ type: 'text',+ }),+ ).rejects.toThrow('Provide exactly one of `content` or `fileId`.');+ });+ });+});diff --git a/apps/server/src/routers/lambda/verify/ingest.ts b/apps/server/src/routers/lambda/verify/ingest.tsindex b87e49f1e79..c0f11f1a8c0 100644--- a/apps/server/src/routers/lambda/verify/ingest.ts+++ b/apps/server/src/routers/lambda/verify/ingest.ts@@ -2,6 +2,7 @@ import { normalizeEvidenceMetadata } from '@lobechat/const/verify';import type {VerifyCheckItem,VerifyCheckResultMetadata,+ VerifyEvidenceCapturedBy,VerifyEvidenceType,} from '@lobechat/types';import { TRPCError } from '@trpc/server';@@ -9,6 +10,7 @@ import pMap from 'p-map';import { z } from 'zod';import type { FileModel } from '@/database/models/file';+import type { VerifyEvidenceModel } from '@/database/models/verifyEvidence';import type { VerifyRunModel } from '@/database/models/verifyRun';import { router } from '@/libs/trpc/lambda';import { evidenceTypeForStoredFile, resolveLiveRoundForItem } from '@/server/services/verify';@@ -83,13 +85,41 @@ const resolveRunByOperation = async (ctx: { runModel: VerifyRunModel }, operatioreturn run;};-/** Store a file-backed artifact under the medium of the file itself, not the caller's label. */-const storedEvidenceType = async (- ctx: { fileModel: FileModel },- type: VerifyEvidenceType,- fileId?: string | null,-): Promise<VerifyEvidenceType> =>- fileId ? evidenceTypeForStoredFile(type, await ctx.fileModel.findById(fileId)) : type;+interface VerifyEvidenceRowInput {+ capturedBy?: VerifyEvidenceCapturedBy | null;+ content?: string | null;+ description?: string | null;+ fileId?: string | null;+ metadata?: unknown;+ type: VerifyEvidenceType;+}++/**+ * Store one evidence artifact on a check result — the single write path behind+ * `uploadEvidence` and `submitCheckEvidence`. A file-backed artifact is stored+ * under the medium of the file itself, not the caller's label, and its metadata+ * (a video's chapters, a comparison pair) is normalized for that medium.+ */+const createVerifyEvidenceRow = async (+ ctx: { evidenceModel: VerifyEvidenceModel; fileModel: FileModel },+ checkResultId: string,+ input: VerifyEvidenceRowInput,+) => {+ const type = input.fileId+ ? evidenceTypeForStoredFile(input.type, await ctx.fileModel.findById(input.fileId))+ : input.type;++ return ctx.evidenceModel.create({+ capturedAt: new Date(),+ capturedBy: input.capturedBy ?? null,+ checkResultId,+ content: input.content ?? null,+ description: input.description ?? null,+ fileId: input.fileId ?? null,+ metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,+ type,+ });+};// A submitted result carries a runtime-sized evidence list; cap the per-entry// file lookup + insert.@@ -169,18 +199,8 @@ export const ingestRouter = router({// Attaching evidence mutates another member's result — creator-scoped,// mirroring submitCheckEvidence.assertWorkspaceRowManageable(ctx, result.userId, 'verify result');- const type = await storedEvidenceType(ctx, input.type, input.fileId);- return ctx.evidenceModel.create({- capturedAt: new Date(),- capturedBy: input.capturedBy ?? null,- checkResultId: result.id,- content: input.content ?? null,- description: input.description ?? null,- fileId: input.fileId ?? null,- metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,- type,- });+ return createVerifyEvidenceRow(ctx, result.id, input);}),/*** Builder self-evidence contract: submit a check item's verdict AND its@@ -205,6 +225,7 @@ export const ingestRouter = router({content: z.string().min(1).optional(),description: z.string().optional(),fileId: z.string().min(1).optional(),+ metadata: z.unknown().optional(), // as on uploadEvidence: a video's chapterstype: evidenceTypeSchema,}).refine((e) => Boolean(e.content) !== Boolean(e.fileId), {@@ -278,16 +299,7 @@ export const ingestRouter = router({const evidence = input.evidence?.length? await pMap(input.evidence,- async (e) =>- ctx.evidenceModel.create({- capturedAt: new Date(),- capturedBy: e.capturedBy ?? null,- checkResultId: checkResult.id,- content: e.content ?? null,- description: e.description ?? null,- fileId: e.fileId ?? null,- type: await storedEvidenceType(ctx, e.type, e.fileId),- }),+ (e) => createVerifyEvidenceRow(ctx, checkResult.id, e),{ concurrency: EVIDENCE_WRITE_CONCURRENCY },): [];diff --git a/apps/server/src/services/verify/__tests__/executor.test.ts b/apps/server/src/services/verify/__tests__/executor.test.tsindex 0cc9ef9f698..9abc6bbd863 100644--- a/apps/server/src/services/verify/__tests__/executor.test.ts+++ b/apps/server/src/services/verify/__tests__/executor.test.ts@@ -298,6 +298,45 @@ describe('VerifyExecutorService', () => {);});+ it('asks for chapters when the missing run evidence is a video', async () => {+ mocks.runEnsureForOperation.mockResolvedValue({+ id: 'run-1',+ plan: [+ {+ id: 'video-check',+ index: 0,+ onFail: 'auto_repair',+ required: true,+ title: 'Recording',+ verifierConfig: {+ requiredEvidence: [{ modality: 'video', scope: 'run_evidence', type: 'video' }],+ },+ verifierType: 'llm',+ },+ ],+ planConfirmedAt: new Date(),+ });++ await new VerifyExecutorService({} as never, 'user-1').execute({+ deliverable: 'ui change',+ goal: 'verify ui',+ modelConfig: { model: 'model', provider: 'provider' },+ operationId: 'builder-op-video',+ runVerifierAgent: vi.fn().mockResolvedValue({ verifierOperationId: 'verifier-op-video' }),+ });++ expect(mocks.resultUpdateByCheckItem).toHaveBeenCalledWith(+ 'run-1',+ 'video-check',+ expect.objectContaining({+ suggestion: expect.stringContaining(+ 'lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item video-check --type video --file <path> --chapters <file>',+ ),+ verdict: 'uncertain',+ }),+ );+ });+it('routes file-backed text evidence to an agent that can inspect the stored artifact', async () => {mocks.runEnsureForOperation.mockResolvedValue({id: 'run-1',diff --git a/apps/server/src/services/verify/evidenceCoverage.ts b/apps/server/src/services/verify/evidenceCoverage.tsindex 4edb12c22cd..6f855d36237 100644--- a/apps/server/src/services/verify/evidenceCoverage.ts+++ b/apps/server/src/services/verify/evidenceCoverage.ts@@ -1,67 +1,10 @@-import type { RequiredEvidenceSpec, VerifyEvidenceType } from '@lobechat/types';+import { readRequiredEvidence as readSpecs } from '@lobechat/const/verify';+import type { RequiredEvidenceSpec } from '@lobechat/types';-/**- * Read the (optional) evidence requirement a criterion declares on its config.- * Evidence-driven criteria list the artifact types they need under- * `verifierConfig.requiredEvidence`; everything else returns undefined.- */-export const readRequiredEvidence = (- config: Record<string, unknown> | undefined | null,-): RequiredEvidenceSpec[] | undefined => {- const raw = config?.requiredEvidence;- return Array.isArray(raw) ? (raw as RequiredEvidenceSpec[]) : undefined;-};--/**- * Same-medium types that also satisfy a declared requirement. The gate checks- * that an artifact of the right medium exists; whether it proves the criterion- * is the judge's call. Without this, a recording uploaded as `video` against a- * `gif` requirement, or a CLI log uploaded as `text` against `transcript`,- * failed every repair round on a label while the judge never saw the artifact.- * A GIF is a run of screenshots, and judges receive it as a frame sheet (see- * `renderGifFrameSheet`), so it also answers a `screenshot` requirement — a GIF- * uploaded as `screenshot` is stored as `gif`, which otherwise failed the gate- * on the very artifact it asked for. `dom_snapshot` and `audio` have no- * substitute.- */-const SATISFIED_BY: Partial<Record<VerifyEvidenceType, VerifyEvidenceType[]>> = {- gif: ['video'],- markdown: ['text', 'transcript'],- screenshot: ['gif'],- text: ['markdown', 'transcript'],- transcript: ['text', 'markdown'],- video: ['gif'],-};+// The coverage rule lives in `@lobechat/const/verify` so the CLI reports the+// same gaps the verifier's structural gate enforces.+export { coverageGaps, runEvidenceGaps } from '@lobechat/const/verify';-/**- * Which required evidence types are still missing for a criterion — pure, so the- * structural gate is unit-testable without a database. Returns `[]` when the- * item declares no evidence requirement (nothing to gate on).- */-export const coverageGaps = (- required: RequiredEvidenceSpec[] | undefined,- evidence: { type: VerifyEvidenceType }[],-): VerifyEvidenceType[] => {- if (!required?.length) return [];- const present = new Set(evidence.map((e) => e.type));- return [...new Set(required.map((r) => r.type))].filter(- (t) => !present.has(t) && !SATISFIED_BY[t]?.some((alt) => present.has(alt)),- );-};--/**- * Run-evidence types a criterion still misses. `deliverable` / `task_artifacts`- * requirements are resolved by the verifier from the operation's documents and- * files, so only `run_evidence` must exist as verify_evidence rows. This is the- * one coverage rule shared by the builder handoff and the structural gate:- * when they disagree, a builder that already evidenced a criterion is treated- * as missing evidence and gets its final report pasted into every check.- */-export const runEvidenceGaps = (+export const readRequiredEvidence = (config: Record<string, unknown> | undefined | null,- evidence: { type: VerifyEvidenceType }[],-): VerifyEvidenceType[] =>- coverageGaps(- readRequiredEvidence(config)?.filter((spec) => !spec.scope || spec.scope === 'run_evidence'),- evidence,- );+): RequiredEvidenceSpec[] | undefined => readSpecs<RequiredEvidenceSpec>(config);diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.tsindex bc80fcb6d7e..514ade59b25 100644--- a/apps/server/src/services/verify/executor.ts+++ b/apps/server/src/services/verify/executor.ts@@ -305,7 +305,7 @@ export class VerifyExecutorService {// round of its own, so the command targets the caller's operation, not// this run: naming this (settled) run sent every repair's evidence one// round behind the round its gate checks.- suggestion: `Capture and upload the missing evidence (${missing}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${gaps.length === 1 ? gaps[0] : `<${gaps.join('|')}>`} --file <path>\`.`,+ suggestion: `Capture and upload the missing evidence (${missing}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${gaps.length === 1 ? gaps[0] : `<${gaps.join('|')}>`} --file <path>${gaps.includes('video') ? ' --chapters <file>' : ''}\`.`,toulmin: { limitation: `Required evidence not provided: ${missing}.` },verdict: 'uncertain',});diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.tsindex 54b3b839fe6..af104a04dd5 100644--- a/packages/const/src/verify.ts+++ b/packages/const/src/verify.ts@@ -370,6 +370,78 @@ export const verifyEvidenceTypes = [] as const;export type VerifyEvidenceType = (typeof verifyEvidenceTypes)[number];+/** The part of a criterion's `requiredEvidence` entry the coverage gate reads. */+export interface RequiredEvidenceCoverageSpec {+ scope?: 'deliverable' | 'run_evidence' | 'task_artifacts';+ type: VerifyEvidenceType;+}++/**+ * Same-medium types that also satisfy a declared requirement. The gate checks+ * that an artifact of the right medium exists; whether it proves the criterion+ * is the judge's call. Without this, a recording uploaded as `video` against a+ * `gif` requirement, or a CLI log uploaded as `text` against `transcript`,+ * failed every repair round on a label while the judge never saw the artifact.+ * A GIF is a run of screenshots, and judges receive it as a frame sheet (see+ * `renderGifFrameSheet`), so it also answers a `screenshot` requirement — a GIF+ * uploaded as `screenshot` is stored as `gif`, which otherwise failed the gate+ * on the very artifact it asked for. `dom_snapshot` and `audio` have no+ * substitute.+ */+const EVIDENCE_SATISFIED_BY: Partial<Record<VerifyEvidenceType, VerifyEvidenceType[]>> = {+ gif: ['video'],+ markdown: ['text', 'transcript'],+ screenshot: ['gif'],+ text: ['markdown', 'transcript'],+ transcript: ['text', 'markdown'],+ video: ['gif'],+};++/**+ * Read the (optional) evidence requirement a criterion declares on its config.+ * Evidence-driven criteria list the artifact types they need under+ * `verifierConfig.requiredEvidence`; everything else returns undefined.+ */+export const readRequiredEvidence = <T extends RequiredEvidenceCoverageSpec>(+ config: Record<string, unknown> | undefined | null,+): T[] | undefined => {+ const raw = config?.requiredEvidence;+ return Array.isArray(raw) ? (raw as T[]) : undefined;+};++/**+ * Which required evidence types are still missing for a criterion — pure, so the+ * structural gate is unit-testable without a database. Returns `[]` when the+ * item declares no evidence requirement (nothing to gate on).+ */+export const coverageGaps = (+ required: RequiredEvidenceCoverageSpec[] | undefined,+ evidence: { type: VerifyEvidenceType }[],+): VerifyEvidenceType[] => {+ if (!required?.length) return [];+ const present = new Set(evidence.map((e) => e.type));+ return [...new Set(required.map((r) => r.type))].filter(+ (t) => !present.has(t) && !EVIDENCE_SATISFIED_BY[t]?.some((alt) => present.has(alt)),+ );+};++/**+ * Run-evidence types a criterion still misses. `deliverable` / `task_artifacts`+ * requirements are resolved by the verifier from the operation's documents and+ * files, so only `run_evidence` must exist as verify_evidence rows. This is the+ * one coverage rule shared by the builder handoff, the CLI's publish report and+ * the structural gate: when they disagree, a builder that already evidenced a+ * criterion is treated as missing evidence.+ */+export const runEvidenceGaps = (+ config: Record<string, unknown> | undefined | null,+ evidence: { type: VerifyEvidenceType }[],+): VerifyEvidenceType[] =>+ coverageGaps(+ readRequiredEvidence(config)?.filter((spec) => !spec.scope || spec.scope === 'run_evidence'),+ evidence,+ );+/** Who / what captured an evidence artifact (provenance). */export const verifyEvidenceCapturedBy = ['agent',diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.tsindex 8a5c5591415..f0b7d26e7e6 100644--- a/packages/prompts/src/prompts/task/index.test.ts+++ b/packages/prompts/src/prompts/task/index.test.ts@@ -461,8 +461,8 @@ describe('buildTaskRunPrompt', () => {expect(result).toContain('include artifact paths, commands, and observed results');expect(result).toContain('an independent verifier decides whether this Task is complete');expect(result).toContain('Run the Acceptance inside this Task, not after it');- expect(result).toContain('lh acceptance install');- expect(result).toContain('lh acceptance run result submit');+ expect(result).toMatch(/`lh acceptance install`.*plan path.*chapters on every recording/);+ expect(result).not.toContain('lh acceptance run result submit'); // the skill owns publishingexpect(result).toContain('proved by a screenshot or recording');// The portable skill is pulled to disk by CLI builders and is absent from// `builtinSkills`, so it must never be named as an unconditional step.@@ -487,7 +487,7 @@ describe('buildTaskRunPrompt', () => {expect(result).toContain('Verify — delivery acceptance');expect(result).toContain('Run the Acceptance inside this Task, not after it');expect(result).toContain('Criterion ids are minted when this run starts');- expect(result).toContain('lh verify plan state');+ expect(result).toContain('lh acceptance plan state');});it('should omit the verify section when verify is disabled', () => {diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.tsindex c0caeed8584..2b0772f9209 100644--- a/packages/prompts/src/prompts/task/index.ts+++ b/packages/prompts/src/prompts/task/index.ts@@ -776,17 +776,17 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin}}taskLines.push(- ' Run the Acceptance inside this Task, not after it: drive the real product surface and submit each artifact as soon as the criterion it proves is provable.',+ ' Run the Acceptance inside this Task, not after it: drive the real product surface, capture each artifact as soon as the criterion it proves is provable, and publish before you finish.',);taskLines.push(- ' Criterion ids are minted when this run starts, so they are not listed above. Read them at runtime with `listCriteria`, or `lh verify plan state "$LOBEHUB_OPERATION_ID" --json` if you have a shell.',+ ' Criterion ids are minted when this run starts, so they are not listed above. Read them at runtime with `listCriteria`, or `lh acceptance plan state "$LOBEHUB_OPERATION_ID" --json` if you have a shell.',);// Two builder shapes, two toolchains. The portable `acceptance` skill is- // pulled to disk by external CLI builders and is deliberately absent from- // `builtinSkills`, so naming it unconditionally hands the in-product agent- // an instruction it cannot act on.+ // pulled to disk by CLI builders and absent from `builtinSkills`, so only a+ // shell builder is pointed at it — and given no inline commands, which let+ // builders skip the skill's capture (chapters) and publishing rules.taskLines.push(- ' With a shell: `lh acceptance install` gives you the `acceptance` skill, and `lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item <checkItemId> --type screenshot --file <path>` uploads a captured artifact.',+ " With a shell: load the `acceptance` skill (`lh acceptance install` if it is not available) and follow its plan path for operation `$LOBEHUB_OPERATION_ID`. It owns reading the criteria, capturing evidence — chapters on every recording included — writing the round report, and publishing it into this run's round.",);taskLines.push(' Without a shell: drive the product with your own tools and cite artifacts by id through `submitEvidence`.',diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex d4a7070f6ff..b334f8d9c5c 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -505,7 +505,7 @@ export interface VerifyCodingScope {branch?: string;/** Git commit (short sha) of the code under test. */commit?: string;- /** Entry point / command exercised, e.g. "lh verify ingest-report". */+ /** Entry point / command exercised, e.g. "lh acceptance run ingest". */entry?: string;/** Associated pull request, when the verification run has one. */pullRequest?: VerifyCodingPullRequest;diff --git a/src/features/Portal/VerifyResult/useMoreMenu.ts b/src/features/Portal/VerifyResult/useMoreMenu.tsindex 0edc3183bc1..4ac8119ada8 100644--- a/src/features/Portal/VerifyResult/useMoreMenu.ts+++ b/src/features/Portal/VerifyResult/useMoreMenu.ts@@ -10,7 +10,7 @@ export const useVerifyResultMoreMenu = (): PortalMoreMenuConfig | undefined => {if (!operationId || !checkItemId) return;return {- // The plan item id — the handle `lh verify` commands and evidence take.+ // The plan item id — the handle `lh acceptance` commands and evidence take.copyId: checkItemId,// Title reads the plan (state), the badge and body read the results — one replica entry.refresh: () => useVerifyStore.getState().refreshVerifyRun(operationId),diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.tsindex 3ad337b6958..55249709583 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts@@ -9,7 +9,7 @@* spawns (`lh`, a script, a test harness), and each one can attribute its output* back to this topic without the agent having to pass ids it cannot see.*- * Read by `lh verify ingest-report`, which stamps them onto the report's+ * Read by `lh acceptance run ingest`, which stamps them onto the report's* `metadata.origin`.*/export interface LobeHubSessionEnvIds {