Skip to content

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

🐛 fix: classify and capture empty model completions (#17700)

YuTengjing7e8b60fc56bc
diff --git a/.agents/skills/deep-review/SKILL.md b/.agents/skills/deep-review/SKILL.md
index 02d49205a0f..304665fe35e 100644
--- a/.agents/skills/deep-review/SKILL.md
+++ b/.agents/skills/deep-review/SKILL.md
@@ -1,11 +1,13 @@
---
name: deep-review
-description: 'Multi-dimensional code review. Use when the user asks to review, evaluate, or audit a PR, diff, branch, or pasted change — including informal review asks like "look at this change for problems" — via light mode: inline review against the dimension quick checklists. Not for explain-only questions about what a change does or why. Deep mode runs only on explicit invocation (/deep-review): one review subagent per dimension plus independent verification subagents that falsify findings before reporting.'
+description: 'Multi-dimensional code review. Use when the user asks to review, evaluate, or audit a PR, diff, branch, or pasted change — including informal review asks like "look at this change for problems" — via light mode: inline review against the dimension quick checklists. Not for explain-only questions about what a change does or why. Deep mode runs only on explicit invocation (/deep-review): independent dimension coverage, adversarial verification, and global duplicate consolidation before reporting.'
---
# Deep Review
-Multi-dimensional code review built on independent subagents. Review breadth comes from parallel per-dimension reviewers; precision comes from an adversarial verification pass that falsifies findings before they reach the report.
+Multi-dimensional code review built on independent subagents. Review breadth comes from parallel
+dimension coverage; precision comes from adversarial verification and global duplicate
+consolidation before findings reach the report.
## Core principles
@@ -19,31 +21,35 @@ Every design choice below serves one of these. When unsure how to execute a step
## Two entry modes
-| Mode | Trigger | What runs |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
-| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review — but not explain-only questions about a change | Main agent reviews inline against the **Quick checklist** section of each applicable dimension file. No subagents. |
-| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: per-dimension review subagents → pipelined verify subagents → structured report → interactive fix flow. |
+| Mode | Trigger | What runs |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
+| **Light** (default) | Any ordinary review ask: "review this PR", an informal "look at this change for problems", a diff pasted for review — but not explain-only questions about a change | Main agent reviews inline against the **Quick checklist** section of each applicable dimension file. No subagents. |
+| **Deep** | Explicit only: `/deep-review`, "run deep review", "full multi-agent review" | Full orchestration: dimension review agents → pipelined verification → global consolidation → structured report → interactive fix flow. |
Do not auto-escalate light to deep. Do not run deep mode for a casual "看看这个改动" — that is light mode.
## Dimensions
-Rules live in one place: [`references/dimensions/`](references/dimensions/), one file per dimension. Both modes read the same files (light mode reads only the `Quick checklist` section; deep-mode subagents read the full file plus its listed rule sources).
-
-| Dimension | id prefix | Covers | Verified? |
-| ----------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
-| [code-style](references/dimensions/code-style.md) | `style` | naming, readability, dead code, comments, i18n hardcoding, UI-library and styling conventions | yes |
-| [logic](references/dimensions/logic.md) | `logic` | logic correctness: edge cases, null, races, error handling, state machines, requirement deviation, test coverage | yes |
-| [business-logic](references/dimensions/business-logic.md) | `design` | design judgment: framework misuse, best-practice violations, solution-weight mismatch, self-inflicted complexity | yes |
-| [reuse-architecture](references/dimensions/reuse-architecture.md) | `reuse` | duplicate implementations, unused existing patterns, extensibility, architectural boundaries | yes |
-| [performance](references/dimensions/performance.md) | `perf` | N+1, blocking calls, resource leaks, render-path waste, **DB migration locking and idempotency** | yes |
-| [release-risk](references/dimensions/release-risk.md) | `risk` | ship/no-ship gate: irreversible persisted state (incl. schemaless shape drift), dev-cycle migration residue, in-flight work & config at deploy time, irreversible outbound effects, prompt/tool-description behavior shifts, shared-surface and high-frequency-UI blast radius, PR purity | yes + checks |
-| [security](references/dimensions/security.md) | `sec` | injection, auth bypass, secret/PII leakage, business-slot confidentiality | yes |
-| [compatibility](references/dimensions/compatibility.md) | `compat` | light/dark theme, desktop app / web (desktop, mobile) / RN, released-client API compatibility, client vs server agent runtime (gateway on/off), Vercel vs Docker deploys, paired router configs | yes |
-| [ux](references/dimensions/ux.md) | `ux` | empty/loading/error states, async feedback, confirmation flows, design-value adherence | yes |
-| [observability](references/dimensions/observability.md) | `obs` | debug: unexplained fixes, uncommented hacks, silent catches, missing logs; product: analytics on qualifying new capabilities; perf: monitoring on high-frequency / high-traffic / polling paths | yes |
-| [workflow](references/dimensions/workflow.md) | `flow` | issue tracking state, PR description freshness, undocumented key decisions, CI / preview build status | no (objective state) |
-| [skill-freshness](references/dimensions/skill-freshness.md) | `skill` | agent skills invalidated by this diff, knowledge worth distilling into a new skill | no (advisory) |
+Rules live in one place: [`references/dimensions/`](references/dimensions/), one file per dimension.
+Both modes read the same files. Light mode reads the full `Quick checklist` section, including
+nested example subsections; deep-mode agents read the full dimension file plus only the rule
+sources and routed references applicable to the touched surface.
+
+| Dimension | id prefix | Covers | Verified? |
+| --------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
+| [ai-coding-bad-habits](references/dimensions/ai-coding-bad-habits.md) | `ai` | narrow special cases in generic code, partial refactors, redundant type guards/aliases, comment narration, and precedent-blind implementation | yes |
+| [code-style](references/dimensions/code-style.md) | `style` | naming, readability, dead code, comments, i18n hardcoding, UI-library and styling conventions | yes |
+| [logic](references/dimensions/logic.md) | `logic` | logic correctness: edge cases, null, races, error handling, state machines, requirement deviation, test coverage | yes |
+| [business-logic](references/dimensions/business-logic.md) | `design` | design judgment: framework misuse, best-practice violations, solution-weight mismatch, self-inflicted complexity | yes |
+| [reuse-architecture](references/dimensions/reuse-architecture.md) | `reuse` | duplicate implementations, unused existing patterns, extensibility, architectural boundaries | yes |
+| [performance](references/dimensions/performance.md) | `perf` | N+1, blocking calls, resource leaks, render-path waste, **DB migration locking and idempotency** | yes |
+| [release-risk](references/dimensions/release-risk.md) | `risk` | ship/no-ship gate: irreversible persisted state (incl. schemaless shape drift), dev-cycle migration residue, in-flight work & config at deploy time, irreversible outbound effects, prompt/tool-description behavior shifts, shared-surface and high-frequency-UI blast radius, PR purity | yes + checks |
+| [security](references/dimensions/security.md) | `sec` | injection, auth bypass, secret/PII leakage, business-slot confidentiality | yes |
+| [compatibility](references/dimensions/compatibility.md) | `compat` | light/dark theme, desktop app / web (desktop, mobile) / RN, released-client API compatibility, client vs server agent runtime (gateway on/off), Vercel vs Docker deploys, paired router configs | yes |
+| [ux](references/dimensions/ux.md) | `ux` | empty/loading/error states, async feedback, confirmation flows, design-value adherence | yes |
+| [observability](references/dimensions/observability.md) | `obs` | debug: unexplained fixes, uncommented hacks, silent catches, missing logs; product: analytics on qualifying new capabilities; perf: monitoring on high-frequency / high-traffic / polling paths | yes |
+| [workflow](references/dimensions/workflow.md) | `flow` | issue tracking state, PR description freshness, undocumented key decisions, CI / preview build status | no (objective state) |
+| [skill-freshness](references/dimensions/skill-freshness.md) | `skill` | agent skills invalidated by this diff, knowledge worth distilling into a new skill | no (advisory) |
`Verified? no` means findings from that dimension are objective state checks or advisories — they skip the verify pass and go straight to the report. `yes + checks` means the dimension's findings are verified normally, but it also emits a second, unverified output — `release_checks`, pre-deploy confirmation items about production state the repo cannot answer (see its dimension file).
@@ -51,17 +57,17 @@ Rules live in one place: [`references/dimensions/`](references/dimensions/), one
Before spawning, the main agent prunes dimensions that cannot apply to the diff. List pruned dimensions and the one-line reason in the report header. When in doubt, run the dimension.
-| Dimension | Skip when |
-| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| code-style, logic, business-logic, reuse-architecture | never (skip only for docs/lockfile-only diffs) |
-| performance | no server/db/loop/render-path code touched (e.g. docs, copy, pure type changes) |
-| release-risk | no DB schema/migration, no schemaless persisted payload, no queue/cron/config/outbound dependency, no prompt or tool-description text, no shared component or package public API, no high-frequency user surface, and the diff has one obvious purpose |
-| security | lockfile/generated-only diff — docs and copy still run it (text is a leak vector: secrets, internal URLs, commercial details) |
-| compatibility | diff touches no UI theming/routing, no API contract, no deployment config, no runtime-branching code |
-| ux | no user-facing surface changed (components, styles, copy, interaction flows) |
-| observability | no error handling, async flow, server code, new user-facing capability, or perf-sensitive path touched |
-| workflow | never in deep mode (cheap external-state checks) |
-| skill-freshness | never in deep mode (cheap) |
+| Dimension | Skip when |
+| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| ai-coding-bad-habits, code-style, logic, business-logic, reuse-architecture | never (skip only for docs/lockfile-only diffs) |
+| performance | no server/db/loop/render-path code touched (e.g. docs, copy, pure type changes) |
+| release-risk | no DB schema/migration, no schemaless persisted payload, no queue/cron/config/outbound dependency, no prompt or tool-description text, no shared component or package public API, no high-frequency user surface, and the diff has one obvious purpose |
+| security | lockfile/generated-only diff — docs and copy still run it (text is a leak vector: secrets, internal URLs, commercial details) |
+| compatibility | diff touches no UI theming/routing, no API contract, no deployment config, no runtime-branching code |
+| ux | no user-facing surface changed (components, styles, copy, interaction flows) |
+| observability | no error handling, async flow, server code, new user-facing capability, or perf-sensitive path touched |
+| workflow | light: no PR/issue/CI context is available; deep: never (cheap external-state checks) |
+| skill-freshness | light: the diff neither changes agent instructions nor changes behavior/conventions covered by an existing skill; deep: never (cheap) |
**"Docs-only" means human-facing prose only.** Files that are executable instructions for agents — `.agents/skills/**`, `AGENTS.md` / `CLAUDE.md`, prompt templates, orchestration manuals — count as code for pruning purposes: their "prose" carries control flow, contracts, and rules whose contradictions are exactly what logic / business-logic / reuse-architecture exist to catch. A diff touching them is never docs-only.
@@ -82,6 +88,9 @@ A wrapping repository (e.g. a private deployment that vendors this repo as a sub
2. Apply the pruning table; read the `Quick checklist` section of each surviving dimension file, plus extension-pack counterparts.
3. Review inline. Findings must cite a rule source or code evidence; respect the codebase-calibration principle.
4. Label every finding on the same two axes deep mode uses, and let them drive the recommendation:
+ - **Severity** — use only P0 (incident-level impact), P1 (must fix in this change), or P2
+ (real but deferrable). Never invent additional levels. State whether each finding blocks
+ release.
- **Introduced or pre-existing** — if the problem lives in code this diff did not change, do not fix it here. Say who introduced it (`git blame` / `git log -L` on the location) and offer to file a Linear issue for that owner. The only exception is an old bug this diff makes reachable or harmful for the first time, at P0.
- **Likelihood** — high / medium / low, judged on the real production path. State it next to the severity. A `low`-likelihood, non-blocking finding is a follow-up, not a fix-now item; on a repeat review of the same change, list it in one line and move on instead of re-arguing it.
5. Output in your environment's normal review format (light mode does NOT use the deep report template). When `release-risk` produced pre-deploy confirmation items, list them as a short checklist separate from the findings — they are questions about production state, not defects. Mention that deep mode exists if findings suggest the diff deserves a full pass.
diff --git a/.agents/skills/deep-review/references/claude-code/main.md b/.agents/skills/deep-review/references/claude-code/main.md
index 64d5648cf62..56f3470fe13 100644
--- a/.agents/skills/deep-review/references/claude-code/main.md
+++ b/.agents/skills/deep-review/references/claude-code/main.md
@@ -1,81 +1,110 @@
# Deep Review · Claude Code Manual
-Deep mode in Claude Code, end to end. "Subagent" below means a Task-tool agent: subagents share no context with the main agent, so every prompt must be self-contained (scope summary, changes or fetch commands, return format — all included).
+Deep mode in Claude Code, end to end. Every Task prompt is self-contained; never rely on inherited
+conversation context.
-Model tier: review and verify subagents run fine on a balanced/fast tier — quality comes from the dimension rules, not model brains. If the harness supports per-Task model selection, prefer the balanced tier (e.g. sonnet-class) over the largest model.
+Use a balanced/fast model tier for review and verification. Rules carry the quality.
-## Step 0 — Scope & background
+## Step 0 — Scope and background
-Follow [`../scoping.md`](../scoping.md). Outputs: the `{changes}` payload (diff text or fetch commands), the ≤ 200-word scope summary, and PR metadata in PR mode.
+Follow [`../scoping.md`](../scoping.md). Produce `{changes}`, a ≤ 200-word scope summary, and PR
+metadata in PR mode.
## Step 1 — Select dimensions
-1. Apply the pruning table in `SKILL.md` to the changed-file list; note each pruned dimension and its one-line reason (they go in the report header).
-2. Detect extension packs: list sibling `deep-review-*` directories in the active skills root (e.g. `.agents/skills/deep-review-cloud/`). For each surviving dimension, collect its rule-file paths: built-in `references/dimensions/<name>.md` plus any extension counterpart; extension-only files add new dimensions (prune those with the same table logic, using their frontmatter `skip_when`).
+1. Apply `SKILL.md` pruning and record each skipped dimension with one reason.
+2. Detect sibling `deep-review-*` extension packs. Collect built-in plus extension paths for every
+ surviving dimension; extension-only files add dimensions.
-## Step 2 — Spawn all reviewers in one wave
+## Step 2 — Spawn reviewers
-**Hard requirement: launch every selected dimension's review Task concurrently in a single response.** One dimension per Task keeps each reviewer's attention undivided; parallel latency ≈ the slowest single dimension.
+Launch every selected dimension concurrently in one response, one Task per dimension.
-Per Task:
+Instantiate [`../review-prompt.md`](../review-prompt.md) with `{dimensions}`, `{dimension_files}`,
+`{scope_summary}`, and `{changes}`. Use `description: review: <dimension>` and
+`subagent_type: general-purpose`.
-1. Read [`../review-prompt.md`](../review-prompt.md) once; instantiate per dimension:
- - `{dimensions}` → the dimension id
- - `{dimension_files}` → that dimension's rule-file paths from step 1
- - `{scope_summary}` / `{changes}` → step 0 outputs
-2. The substituted text is the Task's entire prompt.
-3. `description`: `review: <dimension>`; `subagent_type`: `general-purpose`.
+## Step 3 — Validate, aggregate, and verify
-## Step 3 — Pipelined verification
+Maintain these accumulators for the entire run:
-Verification is per-dimension and starts the moment that dimension's reviewer returns — never wait for the other reviewers (no global barrier).
+- `reportPool`
+- `releaseChecks`
+- `missingSources`
+- `workflowFeedback`
+- `needsContext`
+- verification statistics
-On each reviewer's return:
+On every reviewer return:
-1. Extract the ` ```json ` fence, `JSON.parse` it. Parse failure or wrong schema → reject and re-spawn that reviewer with the same prompt (malformed JSON is itself a laziness signal).
-2. Dimension marked `verify: false` (workflow, skill-freshness) → findings go straight to the report pool. A returned `release_checks` array (release-risk only) likewise bypasses verification entirely — never feed it to a verify subagent; it holds questions about production state, not claims to falsify.
-3. Zero findings → done with this dimension.
-4. Otherwise spawn a verify Task immediately: read [`../verify-prompt.md`](../verify-prompt.md), substitute `{issues}` (this reviewer's findings array), `{scope_summary}`, `{changes}`; `description`: `verify: <dimension>`.
+1. Validate the fenced payload with
+ `bun run .agents/skills/deep-review/scripts/validate-output.ts review`, passing the response on
+ stdin or through a task-scoped temp file. Validation failure → reject and re-spawn the reviewer
+ with the same prompt.
+2. Append `missing_sources`, `release_checks`, and `workflow_feedback` to their accumulators before
+ partitioning findings.
+3. Findings from `verify: false` dimensions go directly to `reportPool`.
+4. For verifiable findings, instantiate [`../verify-prompt.md`](../verify-prompt.md). Include only
+ the dimension-specific verification addenda that the payload requires. Spawn verification as
+ soon as that reviewer returns; do not wait for other reviewers.
-Anti-shortcut validation on each verify return:
+On every verifier return:
-- Extract + parse the JSON; `verifications.length` must equal the input count, ids matching one-to-one (Set difference finds gaps).
-- Mismatch → spawn a fresh verify Task carrying only the missing ids' original findings and the full verify prompt (every Task is a new subagent; re-supply full context). Do not loosen the check.
-- > 20 findings from one reviewer → split verification into 2 batches by id order (rare; default is one batch).
+1. Validate with `validate-output.ts verify`.
+2. Compare input and output ids one-to-one. Missing, duplicate, or invented ids → spawn a fresh
+ verifier for the unresolved original ids.
+3. Apply `severity_override` and the nature/exposure overrides before cross-checking invariants:
+ effective P0 must block release, effective P2 must not, and effective `release-risk` or
+ `exposed_legacy` findings must not be auto-fixes. Re-spawn a verifier only when the effective
+ values still violate these invariants.
+4. Append verifier `workflow_feedback`.
+5. `confirmed` → `reportPool` after applying overrides; `false_positive` → statistics only;
+ `need_more_context` → `needsContext`.
-Verdict handling: `confirmed` → report pool (apply `fix_options_override` / `nature_override` / `exposure_override` / `likelihood_override` / `same_root_as`); `false_positive` → drop; `need_more_context` → "Needs your input" appendix. Never let the main agent "fill in context" and re-verify by itself — that pollutes the main context and violates the independence principle; escalate through the appendix instead.
+Split a verifier payload only when it exceeds 20 findings. Never let the main agent re-verify a
+candidate.
-## Step 4 — Render the report
+## Step 4 — Consolidate duplicate roots
-Render strictly per [`../report-template.md`](../report-template.md) — structure, ordering, P2 cap, unverified-dimension sections, statistics, and the PR-mode merge verdict (decision table lives in the template; the main agent fills it, never a subagent). Run the template's pre-send self-check before sending.
+When at least two confirmed findings remain, spawn one fresh Task using
+[`../consolidate-prompt.md`](../consolidate-prompt.md). Pass confirmed findings after verifier
+overrides, in report order.
-## Step 5 — Ask about the "safe to fix now" batch
+Validate the result with `validate-output.ts consolidate`, then reject any invented id, self-map,
+cycle, or root that occurs after its duplicate. Invalid output → re-spawn consolidation. Apply the
+map only after validation.
-When the batch is non-empty, use `AskUserQuestion` (don't just write "want me to fix these?" in prose):
+Zero or one confirmed finding skips this step.
-- Question: `"Safe to fix now" has N low-risk findings — apply them all in one pass?`
-- Options: `Fix all` (recommended; apply each finding's fix option) / `Not now` (report only). Partial picks arrive via the built-in "Other" answer.
+## Step 5 — Render the report
+
+Render strictly per [`../report-template.md`](../report-template.md). Include the aggregated missing
+sources and workflow feedback, optional consolidation in the execution line, statistics, and the
+PR-mode merge verdict. Run the template's pre-send self-check.
-`Fix all` → apply each fix, add regression tests where `need_test: true`, one line per fix in the reply. Empty batch → skip this step silently.
+## Step 6 — Offer the safe batch
-## Step 6 — Walk the remaining decisions
+When `Safe to fix now` is non-empty, use `AskUserQuestion`:
+
+- Question: `"Safe to fix now" has N low-risk findings — apply them all in one pass?`
+- Options: `Fix all` / `Not now`; free text covers partial picks.
-Confirmed findings with `can_auto_fix: false` plus the `need_more_context` appendix need user decisions. When non-empty, drive them through `AskUserQuestion`:
+Apply selected fixes and regression tests where `need_test: true`. Empty batch skips silently.
-- ≤ 4 questions per call; order by P0 → P1 → P2, `blocks_release: true` first; tell the user when more remain for the next round.
-- **Only in-scope findings enter this loop.** Everything rendered under `Hand off to owner` is excluded — never offer to fix a pre-existing problem here, and never let a fix-option question quietly pull legacy code into the diff. Low-likelihood non-blocking findings go last, and on a repeat review they are skipped entirely unless the user asks.
-- One finding = one question: confirmed items offer their `fix_options` as options (single option → `Apply the fix` / `Skip this round`); `need_more_context` items ask for the missing context (`I'll provide it` / `Park it`).
-- Apply whatever the user picks (tests included where flagged); park the rest.
+## Step 7 — Walk remaining decisions
-Both lists empty → skip this step silently and go to Step 7; the hand-off question stands on its own.
+Ask about confirmed `can_auto_fix: false` findings and `needsContext`, up to four questions per
+call. Order P0 → P1 → P2, blocking first. Exclude every legacy hand-off item. Skip low-likelihood,
+non-blocking items on repeat review unless the user asks.
-## Step 7 — Offer to file the hand-off issues
+## Step 8 — Offer legacy hand-off issues
-Runs whether or not Step 6 asked anything — only condition is that `Hand off to owner` is non-empty. One `AskUserQuestion`: `N pre-existing problems belong to other owners — create Linear issues for them?` with options `Create all` / `Pick some` / `Not now`. Do not create anything before the user answers. On approval, follow the `linear` skill: Chinese content, one issue per finding, description carrying location + culprit commit/author/date + scenario + likelihood + the evidence from verification, assigned to the culprit author when identified. Report the created issue keys.
+When `Hand off to owner` is non-empty, ask once whether to create all, some, or no Linear issues.
+Create nothing before approval. On approval, use the `linear` skill and include location, culprit,
+scenario, likelihood, and verification evidence.
## Notes
-- **Self-containment**: any information a subagent needs must be in its prompt — especially the scope summary and changes payload.
-- **Small vs large diff**: ≤ 200 lines AND ≤ 5 files → inline diff text into prompts; larger → pass fetch commands (very-large check first — see scoping.md).
-- **PR mode trigger**: GitHub PR URL in the user's message only.
-- **Do not degrade**: if Tasks cannot be spawned in this environment, stop and tell the user to use light mode — a main-agent-only "deep review" violates the skill's core principles.
+- Small diff: ≤ 200 lines and ≤ 5 files; inline it. Otherwise pass fetch commands.
+- PR mode: GitHub URL or unambiguous `PR #123` / `pr 123` / `pull request 123`; a bare `#123` is not.
+- If Tasks cannot be spawned, stop and offer light mode. Never simulate deep mode in the main agent.
diff --git a/.agents/skills/deep-review/references/codex/main.md b/.agents/skills/deep-review/references/codex/main.md
index be5d426fe91..65142a302d2 100644
--- a/.agents/skills/deep-review/references/codex/main.md
+++ b/.agents/skills/deep-review/references/codex/main.md
@@ -1,105 +1,158 @@
# Deep Review · Codex Manual
-Deep mode in Codex, end to end. "Subagent" below means a `spawn_agent` agent. Every prompt is written to be self-contained, which is correct under any Codex version.
+Deep mode in Codex, end to end. Every spawned agent receives a self-contained prompt.
-The multi-agent API differs across Codex versions — tool names, parameters, and defaults all move. **Everything in this section is a claim to verify against the session you are actually in, not a fact to rely on.** Read the discovered tools' real schemas before step 2 and bind the manual's verbs and parameters to what exists.
+## Runtime contract
-- **Tool discovery first**: names vary — e.g. surfaced via `tool_search` as `multi_agent_v1.spawn_agent` / `wait_agent` / `close_agent`, or exposed directly as `spawn_agent` / `wait` / `close_agent`. Search/list the session's tools and bind the spawn/wait/close verbs used below to the names actually exposed; do not assume this manual's names exist verbatim. If no multi-agent tools can be surfaced, stop and offer light mode.
-- **Context inheritance is the one default you must not guess.** Independent reviewers are the whole point of deep mode — a subagent that inherits the main agent's context has already seen your reasoning and will confirm it rather than review it. That failure is silent: the flow completes, the report looks normal, the independence is gone. So read the spawn tool's schema for whatever controls inheritance (`fork_turns`, `fork_context`, or a version-specific equivalent) and set it explicitly to **no inheritance** — never rely on the default being off. If the tool exposes no such control and inheritance cannot be turned off, say so in the report: the verify pass is then not adversarial and its `confirmed` verdicts are weaker than they look.
-- **Concurrency budget**: multi\_agent\_v2 caps concurrent threads per session (default 4 including the root — 3 usable subagent slots); the legacy `agents.max_threads` default is 6. The flow therefore runs dimensions as **3 composite groups** in a single wave instead of one agent per dimension.
-- **Slot lifecycle decides which step-3 algorithm you run.** Where a close verb exists, a finished agent holds its slot until closed, and closing promptly is what lets review and verify pipeline (step 3, Lane A). Where the session exposes no close verb, slot recycling is not yours to drive: run the two-wave algorithm instead (Lane B). Settle which during tool discovery, before step 2 — the two lanes differ throughout, so half of each does not compose.
-- **Delegation policy**: Codex spawns subagents only when the user explicitly allows agent delegation. Deep mode is explicitly invoked, which is that permission; if your session policy still forbids spawning, stop and offer light mode — never degrade to a single-agent "deep review".
-- Model per agent: balanced tier is enough (rules carry the quality); use a faster/mini tier for the `process` group, which is scan-heavy.
+Inspect the collaboration tools already exposed in the session before spawning. Use deferred-tool
+discovery only when the session explicitly says collaboration tools are deferred.
+
+Bind these capabilities from the real schemas:
+
+- spawn
+- wait for any completion
+- optional explicit close/release
+- context inheritance control
+- active concurrency limit
+
+Set context inheritance explicitly to none. If inheritance cannot be disabled, disclose weakened
+independence in the report. If spawning is unavailable, stop and offer light mode.
+
+Define one `release(agent)` operation from the documented lifecycle:
+
+- completion automatically releases an active slot → no-op;
+- a finished agent holds its slot until explicit close → close it;
+- slot reuse cannot be determined or achieved → stop and offer light mode.
+
+Do not select the algorithm merely from whether a close verb exists. Slot reuse is the capability
+that matters.
## Group table
-Dimension rules stay one-per-file; Codex only changes how they are **packed**:
+Codex packs related dimensions to fit the normal three usable subagent slots:
+
+| Group | Dimensions |
+| ------------- | ------------------------------------------------------------------------ |
+| `quality` | ai-coding-bad-habits, code-style, reuse-architecture, business-logic, ux |
+| `correctness` | logic, performance, security, compatibility |
+| `release` | release-risk |
+| `process` | workflow, skill-freshness, observability |
-| Group | Dimensions (in prompt order) |
-| ------------- | --------------------------------------------------------- |
-| `quality` | code-style, reuse-architecture, business-logic, ux |
-| `correctness` | logic, performance, security, compatibility, release-risk |
-| `process` | workflow, skill-freshness, observability |
+Pruning removes dimensions; empty groups disappear. Start `release`, `correctness`, and `quality`
+first so the largest evidence passes begin immediately; queue `process`. Use a fast tier for
+`process` and a balanced tier elsewhere.
-Pruning removes dimensions from a group; a fully pruned group is not spawned. The table is a starting point — recalibrate the packing in this file if group runtimes drift far apart. `release-risk` sits with `performance` on purpose: both read the migration files, from opposite angles (cost vs reversibility), so one agent reads them once. Keep the angle separation their dimension files define — one shared agent must still emit two distinct findings, never a merged one.
+Extension-only dimensions form an `extras` group and join the same queue. Never drop it.
-Extension packs can also **add** dimensions (a `deep-review-*/dimensions/` file whose name matches no built-in). Added dimensions have no row in the table: collect them into a dynamic fourth group, `extras`. It exceeds the slot budget unless a built-in group was fully pruned, so step 3 schedules it — first freed slot in Lane A, next batch in Lane B — but it is never dropped. Its verify routing follows each dimension file's own `verify` frontmatter flag (default: verified).
+## Step 0 — Scope and background
-## Step 0 — Scope & background
+Follow [`../scoping.md`](../scoping.md). Produce `{changes}`, a ≤ 200-word scope summary, and PR
+metadata in PR mode.
-Follow [`../scoping.md`](../scoping.md). Outputs: `{changes}` (diff text or fetch commands), the ≤ 200-word scope summary, PR metadata in PR mode.
+## Step 1 — Select dimensions and references
-## Step 1 — Select dimensions
+Apply `SKILL.md` pruning, detect sibling extension packs, and collect built-in plus extension paths.
+Dimension files may route to surface-specific references; agents read only the routes matching the
+diff.
-Same as the pruning + extension-pack procedure in `SKILL.md`: apply the pruning table, detect sibling `deep-review-*` extension packs, collect each surviving dimension's rule-file paths (built-in + extension counterpart). Map surviving dimensions onto the group table; extension-added dimensions go to the `extras` group (see above) so downstream rules never get silently dropped.
+## Step 2 — Build prompts
-## Step 2 — Build every agent prompt
+For every non-empty group, instantiate [`../review-prompt.md`](../review-prompt.md) with
+`{dimensions}`, `{dimension_files}`, `{scope_summary}`, and `{changes}`. Set the discovered
+inheritance control to none.
-Per group (built-in groups plus a non-empty `extras`):
+## Step 3 — Run the work queue
-1. Read [`../review-prompt.md`](../review-prompt.md); instantiate:
- - `{dimensions}` → the group's surviving dimension ids (comma-separated)
- - `{dimension_files}` → all their rule-file paths
- - `{scope_summary}` / `{changes}` → step 0 outputs
-2. Substituted text → `spawn_agent.message`. Prompts are self-contained, so set the inheritance control discovered in the constraints section to **no inheritance** — this is the step where reviewer independence is won or silently lost.
+Maintain:
-## Step 3 — Run review and verify
+- `pendingWork`: not-yet-spawned review, review-retry, verify, and verify-retry items
+- `active`: spawned work keyed by agent id
+- `reportPool`
+- `releaseChecks`
+- `missingSources`
+- `workflowFeedback`
+- `needsContext`
+- verification statistics
-Which algorithm you run depends on **one** thing settled during tool discovery: does the session expose a verb that closes/releases a finished agent? Pick a lane now and stay in it — do not mix.
+Seed `pendingWork` in this order: `release`, `correctness`, `quality`, `process`, `extras`. Fill every
+usable slot.
-Both lanes share the same per-result handling, referred to below as **consume(agent)**:
+Whenever an agent completes:
-1. Extract the ` ```json ` fence and parse. Parse failure / wrong schema → reject and re-spawn that group with the same prompt. **A retry is a review agent like any other** — it joins Lane A's review wait set, and in Lane B it extends the review wave. Neither lane may begin verification while a retry is outstanding: that group's findings and release checks would be absent from the report entirely, which is worse than unverified.
-2. Partition its findings by dimension `verify` flag: `verify: false` dimensions (workflow, skill-freshness) go straight to the report pool; zero verifiable findings → done with this group. A returned `release_checks` array (release-risk only) also bypasses verification — never include it in `{issues}`; it holds questions about production state, not claims to falsify.
-3. The remainder becomes that group's verify payload: [`../verify-prompt.md`](../verify-prompt.md) with `{issues}` = this group's verifiable findings, plus `{scope_summary}` / `{changes}`.
+1. Call `release(agent)`.
+2. Remove it from `active`.
+3. Validate its fenced payload with
+ `bun run .agents/skills/deep-review/scripts/validate-output.ts <review|verify>`, passing the
+ response on stdin or through a task-scoped temp file.
+4. On invalid review output, prepend the identical review retry to `pendingWork`. On invalid verify
+ output, prepend a retry for the unresolved original ids.
+5. Handle valid output as described below.
+6. Refill every free slot from `pendingWork`.
-And the same verify-return handling: validate `verifications.length` against the input count with ids one-to-one (Set difference). Mismatch → spawn a fresh verify agent with the missing ids' findings and the full prompt; do not loosen. Verdicts: `confirmed` → report pool (apply overrides / `same_root_as`); `false_positive` → drop; `need_more_context` → "Needs your input" appendix. The main agent never re-verifies findings itself.
+The loop ends only when `active` and `pendingWork` are both empty.
-### Lane A — a close verb exists (pipelined)
+### Valid review output
-Slots are held until closed, so closing promptly is what buys the pipelining.
+Append `missing_sources`, `release_checks`, and `workflow_feedback` before partitioning findings.
-Keep **two explicit queues** for the whole lane: `pendingSpawn` (a queued `extras` group, if any) and `pendingVerify` (verify payloads waiting for a slot). Once the wave is running, nothing is spawned except by taking from a queue — "spawn it in the next available slot" is not a step you can leave implicit, because the work item has to survive in writing until a slot actually exists.
+- `verify: false` findings → `reportPool`
+- verifiable findings → append one verify item using [`../verify-prompt.md`](../verify-prompt.md),
+ including only the required verification addenda
+- zero verifiable findings → no verify item
-1. Spawn the three built-in groups concurrently in one turn (≤ 3 agents — fits the default budget). A non-empty `extras` goes into `pendingSpawn`, not into this wave.
-2. Loop `wait` (wait-any — call it repeatedly). On each returned **review** agent: close it → `consume(agent)` → append its verify payload, if any, to `pendingVerify` → then **service the freed slot** (below).
-3. On each returned **verify** agent: close it → apply the shared verify-return handling → then service the freed slot.
-4. **Service the freed slot** — one item, in this priority: `pendingSpawn` first (an `extras` review joins the review wait set), otherwise the oldest entry in `pendingVerify`. Empty queues → leave the slot idle.
-5. The loop ends only when all three of these hold: every review agent has returned, both queues are empty, and every spawned verifier has returned. **A group whose payload is still in `pendingVerify` has not been verified** — its findings stay out of the report pool until its verifier returns. Reaching step 4 of the report with a non-empty queue means findings shipped unverified, which is the one failure this flow exists to prevent.
+### Valid verify output
-Slot arithmetic: up to 3 review agents spawn together; every later spawn fills a slot freed by a close, so the flow never exceeds 3 concurrent agents and never deadlocks. When `extras` takes priority over `pendingVerify`, it delays a verifier rather than dropping it — that is exactly what the queue is for.
+Compare input and output ids one-to-one. Missing, duplicate, or invented ids invalidate those
+entries; prepend a fresh verify item for unresolved original ids.
-### Lane B — no close verb (two plain waves)
+- Apply `severity_override` and the nature/exposure overrides before cross-checking invariants:
+ effective P0 must block release, effective P2 must not, and effective `release-risk` or
+ `exposed_legacy` findings must not be auto-fixes. Only a mismatch in the effective values returns
+ that id to the verify queue.
+- append verifier `workflow_feedback`
+- `confirmed` → apply overrides and append to `reportPool`
+- `false_positive` → statistics only
+- `need_more_context` → `needsContext`
-Nothing frees a slot on demand, so pipelining is not available. Do not emit close calls; do not reason about freed slots.
+The main agent never re-verifies a candidate.
-1. **Review wave**: spawn review groups up to the concurrency budget and `wait` for all of them. More groups than slots (built-ins + `extras` > 3) → run them as consecutive batches, each batch fully awaited before the next spawns. `extras` is just another group here — it takes its turn in batch order rather than racing for a freed slot.
-2. `consume(agent)` for every returned review agent, collecting all verify payloads before spawning any verifier. A re-spawn from step 1 of `consume` **stays inside the review wave**: it becomes an extra batch, awaited and consumed like the rest, and the wave is over only when every group has produced a parsed result. Moving to step 3 with a retry still in flight silently drops that whole group — its dimensions vanish from the report with no unverified-dimension section to mark the hole.
-3. **Verify wave**: spawn one verifier per group with a non-empty payload, again batched to the budget, and `wait` for all of them. Then apply the shared verify-return handling.
+## Step 4 — Consolidate duplicate roots
-This costs one barrier's worth of wall-clock versus Lane A and changes nothing about coverage or independence — which is the contract. Never drop verification to buy back the time.
+After the queue drains, if at least two confirmed findings remain, spawn one fresh agent using
+[`../consolidate-prompt.md`](../consolidate-prompt.md). Pass confirmed findings after overrides and
+in report order.
-## Step 4 — Render the report
+Validate with `validate-output.ts consolidate`. Reject invented ids, self-maps, cycles, or roots
+that occur after their duplicates; retry consolidation until valid. Apply the map only after those
+checks. Zero or one confirmed finding skips consolidation.
-Render strictly per [`../report-template.md`](../report-template.md) — structure, P2 cap, unverified-dimension sections, statistics, PR-mode merge verdict (main agent fills the decision table; never delegated). Run the template's pre-send self-check. Do not fall back to Codex's default findings format.
+## Step 5 — Render
-## Step 5 — Ask about the "safe to fix now" batch
+Render strictly per [`../report-template.md`](../report-template.md), including aggregated missing
+sources and workflow feedback, optional consolidation, statistics, and PR-mode merge verdict. Run
+the pre-send self-check.
-Non-empty batch → one `request_user_input` (allowed regardless of delegation policy): `"Safe to fix now" has N low-risk findings — apply them all in one pass?` with options `Fix all` (recommended) / `Not now`; free-text covers partial picks. `Fix all` → apply each fix option, add regression tests where `need_test: true`, one line per fix. Empty → skip silently.
+## Step 6 — Offer the safe batch
-## Step 6 — Walk the remaining decisions
+When non-empty, use `request_user_input` once:
+`"Safe to fix now" has N low-risk findings — apply them all in one pass?`
+with `Fix all` / `Not now`; free text covers partial picks. Apply tests where `need_test: true`.
-`can_auto_fix: false` confirmed findings + the `need_more_context` appendix, when non-empty, go through `request_user_input` one finding at a time — P0 → P1 → P2, `blocks_release: true` first; offer the finding's `fix_options` as the choices. Apply what the user picks; park the rest. Both lists empty → skip silently and go to Step 7.
+## Step 7 — Walk remaining decisions
-**Only in-scope findings enter this loop.** Everything under `Hand off to owner` is excluded — never offer to fix a pre-existing problem here. Low-likelihood non-blocking findings go last, and are skipped entirely on a repeat review unless the user asks.
+Ask one finding at a time for confirmed `can_auto_fix: false` items and `needsContext`, ordered P0 →
+P1 → P2 and blocking first. Exclude legacy hand-offs. Skip low-likelihood, non-blocking items on
+repeat review unless requested.
-## Step 7 — Offer to file the hand-off issues
+## Step 8 — Offer legacy hand-off issues
-Runs whether or not Step 6 asked anything — only condition is that `Hand off to owner` is non-empty. One `request_user_input`: `N pre-existing problems belong to other owners — create Linear issues for them?` with options `Create all` / `Pick some` / `Not now`. Create nothing before the user answers. On approval, follow the `linear` skill: Chinese content, one issue per finding, description carrying location + culprit commit/author/date + scenario + likelihood + verification evidence, assigned to the culprit author when identified. Report the created issue keys.
+When legacy hand-offs exist, ask once whether to create all, some, or no Linear issues. Create
+nothing before approval. On approval, use the `linear` skill and include location, culprit,
+scenario, likelihood, and verification evidence.
## Notes
-- **Self-containment**: everything a subagent needs lives in its prompt — especially scope summary and changes payload.
-- **Small vs large diff**: ≤ 200 lines AND ≤ 5 files → inline the diff; larger → pass fetch commands (very-large check first — see scoping.md).
-- **PR mode trigger**: GitHub PR URL in the user's message only.
-- Raising `agents.max_threads` shortens nothing here (the wave already fits 3 slots) — keep the group table as the execution grain for predictability.
+- Small diff: ≤ 200 lines and ≤ 5 files; inline it. Otherwise pass fetch commands.
+- PR mode: GitHub URL or unambiguous `PR #123` / `pr 123` / `pull request 123`; a bare `#123` is not.
+- Increasing concurrency may start all four built-in groups together; the same queue algorithm
+ remains valid.
diff --git a/.agents/skills/deep-review/references/consolidate-prompt.md b/.agents/skills/deep-review/references/consolidate-prompt.md
new file mode 100644
index 00000000000..85c1aed6950
--- /dev/null
+++ b/.agents/skills/deep-review/references/consolidate-prompt.md
@@ -0,0 +1,44 @@
+# Global Finding Consolidation Prompt
+
+Run once after verification only when at least two confirmed findings remain. This pass does not
+re-verify correctness; it identifies roots duplicated across verifier payloads.
+
+Instantiate `{confirmed_findings}` with the confirmed findings after applying verifier overrides,
+including id, dimension, location, summary, evidence, and fix options.
+
+---
+
+````text
+Consolidate duplicate code-review findings. Do not change verdicts, severity, likelihood, evidence,
+or fix options.
+
+## Confirmed findings
+{confirmed_findings}
+
+Two findings share a root only when one concrete fix resolves both. Similar location, theme, or
+dimension is not enough.
+
+Choose the earliest finding in input order as the root. Return only later duplicate ids. Never:
+
+- map an id to itself;
+- invent an id;
+- create a cycle;
+- merge findings that require separate fixes; or
+- merge a release-risk consequence with a code defect when fixing the defect would not also remove
+ the release consequence.
+
+Return exactly one valid JSON object in a `json` fence. No prose or comments.
+
+```json
+{
+ "same_root": [
+ {
+ "id": "style-2",
+ "same_root_as": "ai-1"
+ }
+ ]
+}
+```
+
+When no duplicates exist, return `{"same_root":[]}`.
+````
diff --git a/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md b/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md
new file mode 100644
index 00000000000..40c57674a4a
--- /dev/null
+++ b/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md
@@ -0,0 +1,184 @@
+---
+id_prefix: ai
+verify: true
+skip_when: docs/lockfile-only diff
+---
+
+# AI Coding Bad Habits
+
+Detect locally plausible but mechanically incomplete code: changes that compile in isolation while
+ignoring semantic scope, static type information, refactor closure, explanatory comments, or
+repository precedent. "AI coding" names the recurring implementation habits, not the author or
+provenance — review observable code and never speculate about who wrote it.
+
+This dimension is not a license to report personal taste. Every finding must identify a concrete
+cost: misleading reading flow, duplicated policy, stale names, redundant runtime work, a missed
+compatibility boundary, or divergence from an established repository pattern.
+
+Use this dimension for the specifically mechanical pattern: code that is locally plausible but
+globally unfinished. If the same root cause is fully covered by `code-style` (an isolated
+readability issue) or `reuse-architecture` (a proven duplicate, wrong layer, or bypassed extension
+seam), report it there instead; never emit the same finding twice.
+
+## Quick checklist
+
+- **Narrow special case inside generic code**: a provider/model/call-site-specific condition, helper,
+ or name is embedded in a shared abstraction and makes the generic contract harder to read or
+ extend. Pay special attention to one-off helpers that hide a single narrow branch at a generic
+ property such as `type`, `status`, or `mode`; keep variant policy in its owning layer or make the
+ exceptional condition explicit at the decision point.
+- **Partial refactor**: a renamed concept leaves stale filenames, tests, exports, docs, or adjacent
+ identifiers; a compatibility alias, forwarding wrapper, or `const newName = oldName` remains even
+ though no caller needs it. Complete the semantic rename across the affected unit, following the
+ repository's file-naming convention.
+- **Defensive type noise despite known types**: repeated `typeof`, `in`, `isRecord`, defensive
+ optional chaining, or cast-and-check logic revalidates values whose static type and callers
+ already guarantee the shape. Confirm the type with LSP/type definitions first. For genuinely
+ untrusted structured input, validate once at the boundary — prefer an existing schema (often Zod
+ in this repo) over scattered ad-hoc guards.
+- **Commentary that narrates coding instead of explaining code**: comments preserve the author's
+ thought process, edit history, numbered implementation steps, or restate the next line, while the
+ actual workaround, invariant, trade-off, or non-obvious constraint is left unexplained. Keep
+ durable "why"; delete transient narration.
+- **Precedent-blind implementation**: naming, file layout, error handling, data flow, or abstraction
+ shape is invented locally without checking the nearest same-kind implementation or relevant repo
+ skill. Require concrete repository precedent before calling a deviation wrong; intentional
+ deviations with a stated reason are valid.
+
+### Examples
+
+Use these examples to recognize the shape of a bad habit, not as keyword-matching rules. Verify the
+declared types, callers, repository convention, and compatibility boundary before reporting.
+
+### Narrow special case hidden behind a generic property
+
+```ts
+const getBlockErrorType = (reason: string) =>
+ reason === 'IMAGE_PROHIBITED_CONTENT' ? ErrorType.ContentPolicyViolation : undefined;
+
+// Inside a shared stream parser:
+type: getBlockErrorType(finishReason);
+```
+
+`type` and `getBlockErrorType` read like the generic owner of error classification, but the helper
+only hides one image-generation condition. Keep the condition explicit at the decision point when
+that is clearest, or move the policy into the image/provider adapter that owns it.
+
+### Rename that stops at the exported symbol
+
+```ts
+// register-file-work.ts
+export const registerWork = async () => {
+ // ...
+};
+
+export const registerFileWork = registerWork;
+```
+
+If no released caller needs compatibility, rename the file, tests, imports, and adjacent concepts
+according to repository convention, then remove the alias. Renaming only the export leaves two
+names for one concept and makes readers search for a migration that does not exist.
+
+### Runtime guards around an already-known type
+
+```ts
+interface Work {
+ id: string;
+}
+
+const getWorkId = (work: Work) =>
+ isRecord(work) && typeof work.id === 'string' ? work.id : undefined;
+```
+
+`work.id` is already guaranteed by the in-process type. Use it directly. If the value came from
+JSON, an SDK, or another trust boundary, parse it once with the existing `WorkSchema` and pass the
+validated `Work` onward instead of repeating guards at every use.
+
+### Comments that preserve the coding transcript
+
+```ts
+// First check whether the cache has a value.
+// If it does, return it.
+if (cached) return cached;
+```
+
+Delete narration that merely restates control flow. Keep a comment when it explains the durable
+reason, for example: `// Ignore v1 cache entries because they lack the workspace isolation key.`
+
+### A locally plausible implementation that ignores repository precedent
+
+```ts
+useEffect(() => {
+ lambdaClient.work.list.query().then(setWorks);
+}, []);
+```
+
+If same-kind features in the repository use a store SWR hook → service → `lambdaClient` pipeline,
+the direct component call is precedent-blind even though it works locally. Follow the established
+route, or document the constraint that makes this feature different.
+
+## Rule sources (deep mode: read before reviewing)
+
+- Repo root `AGENTS.md` / `CLAUDE.md` — repository-wide naming, comment, and workflow conventions
+- `.agents/skills/typescript/SKILL.md` — static typing, runtime validation, and type-guard conventions
+- `.agents/skills/project-overview/SKILL.md` — ownership and layer boundaries
+- The category skill matching the changed code (`testing`, `drizzle`, `trpc-router`, `zustand`,
+ `builtin-tool`, etc.) — use its established pattern as the primary precedent
+- The nearest same-kind sibling implementation and the changed symbol's callers
+
+## How to check
+
+Run five focused passes:
+
+1. **Scope locality**: name each new condition/helper and ask whether its vocabulary is narrower than
+ the file or abstraction containing it. Trace the pipeline and existing extension seams before
+ deciding the code belongs elsewhere. A narrow report does not prove the root cause is narrow.
+2. **Refactor closure**: for renamed concepts, search both old and new names across symbols,
+ filenames, exports, tests, docs, and import paths. Search every alias/wrapper for callers. Keep a
+ compatibility shim only when a released caller or staged migration needs it, and require a
+ deprecation/removal story.
+3. **Type confidence**: use LSP hover/go-to-definition when available; otherwise read the declared
+ type and representative callers. Distinguish trusted in-process values from external JSON,
+ database JSON, SDK payloads, and other untrusted boundaries. Do not remove guards merely because
+ TypeScript compiles.
+4. **Comment intent**: read added comments without the diff narrative. Keep comments that explain
+ why the code cannot be simpler, an invariant, a compatibility constraint, or an external
+ reference. Flag narration that will be stale after the next edit, especially when the real
+ workaround remains undocumented.
+5. **Repository precedent**: identify the nearest same-kind implementation and relevant skill.
+ Compare naming, layering, validation, error handling, and tests. No concrete precedent means no
+ precedent-blind finding.
+
+## Violations
+
+- A narrow variant concern pollutes a generic layer or is hidden behind a one-use indirection,
+ making the shared decision harder to understand or extend.
+- A rename/refactor leaves contradictory names or no-op aliases/wrappers with no compatibility
+ caller.
+- Runtime guards duplicate guarantees already established by the declared type and trusted callers,
+ obscuring the actual business logic.
+- Added comments record implementation narration while omitting the non-obvious reason the code
+ exists.
+- The diff invents a local pattern despite a clearly applicable repository precedent or skill.
+
+## Not violations
+
+- A variant-specific rule implemented inside that variant's adapter/provider/module.
+- A filename that names the broader module rather than one exported function.
+- An alias or wrapper preserving a released public API, plugin contract, serialized name, or
+ multi-PR migration, with evidence that callers still depend on it.
+- Runtime validation at a real trust boundary, including parsed JSON, database JSON, network/SDK
+ payloads, IPC, plugin/tool input, or legacy persisted data. Static types do not make external data
+ trustworthy.
+- A small inline type guard that narrows a genuine union more clearly than a schema would.
+- Comments explaining a workaround, invariant, trade-off, compatibility constraint, or source
+ reference.
+- An intentional departure from precedent whose constraint is documented in code or the PR.
+
+## Severity calibration
+
+- Use P1 only when the habit creates a concrete correctness, compatibility, or shared-abstraction
+ risk.
+- Use P2 for maintainability/readability debt that is likely to mislead the next change.
+- Do not report "looks AI-generated." The habit is only a lead; the finding must name the
+ code-level consequence and evidence.
diff --git a/.agents/skills/deep-review/references/dimensions/release-risk.md b/.agents/skills/deep-review/references/dimensions/release-risk.md
index 127cce3560c..b42ca370724 100644
--- a/.agents/skills/deep-review/references/dimensions/release-risk.md
+++ b/.agents/skills/deep-review/references/dimensions/release-risk.md
@@ -6,196 +6,84 @@ skip_when: diff touches no DB schema/migration, no schemaless persisted payload,
# Release Risk
-The last gate before shipping. Every other dimension asks "is this code correct?" — this one asks **"if we merge and deploy this today and it turns out wrong, how bad is the recovery?"** A change can be flawless and still be a bad thing to ship in one piece.
-
-Seven risk classes, each with its own irreversibility profile:
-
-1. **Persisted state** — wrong code can be reverted in minutes; wrong data cannot
-2. **Dev-cycle drift** — a requirement that was reworked several times leaves residue in the migration history and in the dev database, and production will not replay that history
-3. **Deploy-moment state** — work already in flight, and configuration that must exist before the code runs
-4. **Prompt surface** — prompts are production behavior with no type system and no test that fails; a wording change reaches every conversation on the next request
-5. **Rollback granularity** — whether undoing this means reverting a whole PR or flipping one switch
-6. **Shared surface and high-frequency UI** — a base component, an exported API, or a screen every user touches daily multiplies any defect by its reach
-7. **PR purity** — a PR carrying several unrelated sub-requirements can only be reviewed, approved, and rolled back as a single unit, at the risk level of its most dangerous part
-
-Findings here are release decisions, not just defects: alongside `fix_options`, propose the de-risking move (split the PR, ship behind a flag, land the migration in a separate earlier PR, backfill in a separate job, stage the rollout).
-
-## Two output shapes
-
-Much of this dimension's subject matter is **not visible in the diff** — the shape of rows already in production, whether an env var is set in each deploy target, what is sitting in the queue right now. Do not force those into findings; asserting facts you cannot read is exactly the hallucination the verify pass exists to catch.
-
-- **Finding** (the normal `issues` entry): you can point at the diff and argue the consequence. Use this whenever the evidence is in the code.
-- **Release check** (the `release_checks` array): an objective pre-deploy confirmation item — "this change depends on X; confirm X before deploying". No severity, no verification, straight to the report as a checklist for the human. Use when the answer lives in production state or in a system outside the repo.
-
-A release check is not a downgraded finding. If the code itself is wrong, it is a finding. If the code is fine but shipping it safely depends on something you cannot see, it is a check.
+Judge recovery cost when correct-looking code turns out to be wrong after deployment. Findings must
+name the concrete rollback, repair, or blast-radius consequence; reach alone is not a defect.
## Quick checklist
-**Persisted state**
-
-- New migration SQL, or a schema change that will generate one, is the part of the diff `git revert` cannot undo — so it always gets **read**, in full. But reading it is not reporting it: an additive, reversible migration (nullable column, new table, concurrent index) with no ordering hazard produces **no output at all** — not a finding, and not a release check either, because there is nothing for a human to confirm. It earns a finding through one of the specific hazards below, or a release check when shipping it safely depends on production state you cannot read (row counts, existing data shape, whether a backfill already ran)
-- Destructive DDL: `DROP COLUMN` / `DROP TABLE` / `RENAME`, narrowing `ALTER COLUMN TYPE`, removing an enum value — old data is gone or unreadable once applied
-- Data-mutating statements in a migration (`UPDATE` / `DELETE` over existing rows) with no dry-run count, no backup path, and no way to reconstruct the old values
-- Constraints added to populated tables (`NOT NULL`, `UNIQUE`, `CHECK`, new FK) — these fail at deploy time on dirty production data that dev fixtures never contained
-- `ON DELETE CASCADE` on a new FK: a single row deletion now silently removes rows in other tables
-- **Schemaless persisted state changing shape** — the highest-miss-rate item here, because there is no DDL and no migration file, so it passes review invisibly. Old records keep the old shape forever and every reader must handle both. Carriers to check:
- - `jsonb` columns: keys added/renamed inside the column, or a value's type changed
- - Cache values: a Redis key whose stored payload is a structured object, not a scalar — nothing migrates it, and the old shape stays until the TTL expires (or forever, if there is none)
- - Client-side persistence: `localStorage`, IndexedDB, persisted store state. Worst case of all — the data lives on the user's machine, you cannot migrate it, and on desktop you cannot even force the client to update
- - Blobs in object storage: manifests and config JSON written by an older version
- Flag any writer-side shape change whose reader does not defend against the legacy shape, and say which carrier it is — the recovery options differ per carrier.
-- Rollback asymmetry: after deploy, is reverting the code alone safe while the schema stays migrated? If the new schema breaks the previous code version, say so — that is a one-way door
-- Deploy ordering: does the new code require the migration to have run first (or vice versa)? Name the required order
-
-**Dev-cycle drift**
-
-This class only exists because features get reworked. When a requirement went through several design iterations before landing, the branch accumulates two kinds of residue — one in the committed migrations, one in the developer's local database — and only the first is visible in the diff. Both are worth checking precisely on the PRs that feel most finished.
-
-- **Dev-phase compatibility carried into production migrations.** Production has never seen the intermediate states of an unshipped feature, so a migration that adds a column, a later one that renames it, and a third that drops it are three statements where one belongs. Look for a migration series inside this PR that mutates objects the same PR created: `ADD COLUMN` then `DROP COLUMN`, a table created then renamed, a backfill for rows that only exist on someone's laptop, a `DROP ... IF EXISTS` guarding an object that never shipped. Recommend squashing into the final shape — the churn is not free: every extra statement is another lock, another failure point, and a false record of the schema's history
-- **Migrations written to accommodate a dev database, not production.** Defensive clauses whose only purpose is to survive a local database in an unknown state (`IF EXISTS` on an object the migration itself just created, a delete-then-recreate to avoid a local conflict, a data fix-up for a shape only local iterations produced) should not ship. They are dead weight in production and they hide the real precondition
-- **Local-only schema residue.** The counterpart risk: the developer's database still carries tables, columns, or enum values from an earlier version of the plan, so the code runs locally against objects that no committed migration creates. Production starts from the committed migrations only. Two checks — does the diff reference any table/column not present in the schema files, and would a clean database reach the same state by replaying the migration folder? What you cannot settle from the repo (what is actually sitting in someone's dev DB, whether the migration was regenerated after the last schema edit) goes to `release_checks` as "verify against a freshly migrated database"
-- **Sequence and ordering damage from rebases.** A long-lived branch that was rebased repeatedly can end up with migration files whose ordering no longer matches the trunk's. The failure appears only when the trunk's migrations run first — which is to say, only in production
-
-**Deploy-moment state**
-
-- **In-flight async work**: queued messages and mid-execution workflows were produced by the _old_ code. A changed job/message payload shape, or added/removed/reordered workflow steps, meets messages already in the queue and workflows resuming from a step index that no longer means the same thing. `git revert` cannot recall a message already in flight — check that the consumer accepts the old payload for at least one deploy cycle, or that the change is drain-and-deploy
-- **Scheduled jobs**: a cron whose schedule, idempotency assumptions, or scope changed — the next tick fires with production-scale data, not fixtures
-- **New configuration dependency**: an env var, secret, feature flag, or third-party setting the new code reads. It is invisible in the diff by definition, and an unset value in one deploy target means a 5xx on boot. Check every target this repo deploys to, not just the one you're thinking of, and check the failure mode: does it crash loudly at startup, or fail silently at the first request?
-- **Irreversible outbound side effects**: emails, push notifications, payment calls, third-party webhooks. Once sent, nothing recalls them. The dangerous shape is not the obvious "send email" endpoint — it is a backfill, migration, or bulk operation that _incidentally_ triggers a notification path for every touched row. Trace whether the new write path fans out to any outbound sender
-
-**Prompt surface**
-
-A prompt edit is a one-line diff that changes the product's behavior for every user, and it is the change class with the **weakest safety net in the entire repo**: no type checks it, no unit test fails on it, and code review reads it as prose rather than as the control logic it actually is. Treat any diff touching a system role, tool description, parameter description, or context-assembly template as a behavior change of the same weight as editing a core function — a reviewer nodding at "the wording reads better" is not review.
-
-Where they live: `packages/prompts/src/prompts/**` (systemRole, tools, planning, memory, and the rest), each builtin tool's `manifest.ts` + `systemRole.ts` under `packages/builtin-tool-*/`, and the assembly/injection order in `packages/context-engine/`.
-
-- **Tool and parameter descriptions are the model's only API documentation.** They decide _whether_ the model calls a tool, _when_, and \*with what arguments. Rewording a description to be clearer to a human can make a tool fire more or less often — the effect is statistical, invisible in the diff, and surfaces as "the agent got worse" days later with nobody linking it to this PR. Say which tool's selection rate the change can move, and in which direction
-- **Removing or narrowing an instruction is riskier than adding one.** A sentence in a system prompt is usually there because something went wrong once. Deleting it as "redundant" re-opens whatever it was patching, and the commit that added it is the only record of why. Check `git log -S` on the removed sentence before accepting a deletion as harmless
-- **Constraints and safety wording** (what the model must refuse, must not fabricate, must not expose) are enforcement, not tone. A weakened constraint is a `security` finding; the release angle is that it reaches production instantly with no gate
-- **Assembly-order and injection-point changes** (where a fragment lands relative to tools, history, and user input) change behavior even when no word changes. A moved block is a real change, not a refactor
-- **Persisted copies of prompts.** A default system role that was copied into user-owned records at creation time does not update when the default changes — existing agents keep the old text forever. Decide which is intended and say so; if the change is meant to reach existing records, that is a backfill, i.e. the Persisted-state class
-- **Cost and cache.** Prompt text is paid on every request by every user, and prefix changes invalidate prompt caching. A longer system prompt is a spend change with no code path to point at — the arithmetic belongs to `observability`, but flag here that it ships with no gradual rollout
-- **Validation.** A prompt change cannot be verified by reading it. What would show a regression — an eval run, a before/after transcript on a real case, a staged rollout? If the PR has none of the three, that is the finding. This is also the change class where a flag is most useful and most often skipped, because it looks like a text edit
-
-**Rollback granularity (feature flags)**
+- **Persisted state**: destructive or data-mutating migrations, constraints against populated data,
+ schemaless payload changes (`jsonb`, cache objects, client persistence, stored manifests), code
+ rollback that cannot run against the migrated state, or an undocumented deploy order.
+- **Dev-cycle drift**: this PR creates and later reworks the same schema object, carries local-only
+ compatibility statements, references schema no committed migration creates, or collides with
+ trunk migration ordering.
+- **Deploy-moment state**: consumers reject payloads already queued by the old code, workflow step
+ positions change underneath in-flight runs, scheduled jobs overlap or process a production-scale
+ backlog, required configuration is absent from a target, or bulk writes fan out to irreversible
+ outbound effects.
+- **Prompt surface**: system/tool/parameter text or assembly order changes model behavior without an
+ eval, representative transcript, or staged rollout; default prompt changes disagree with
+ persisted copies.
+- **Rollback granularity**: a user-visible, incompletely testable main-path change can only be undone
+ by reverting a large PR even though a scoped runtime flag could provide staged rollout and fast
+ disablement.
+- **Shared and first-minute surfaces**: an established contract or interaction changes across a
+ measured set of call sites or a surface most users reach immediately, with no rollout control.
+- **PR purity**: a large or risky sub-requirement is independently buildable and deployable but
+ bundled with unrelated work, forcing one review and rollback unit.
+
+Read every relevant routed reference below before reviewing. Do not read unrelated references:
+
+| Changed surface | Required reference |
+| ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
+| Migration, schema, persisted object, queue/workflow, cron, config, outbound sender | [`../release-risk/persisted-state.md`](../release-risk/persisted-state.md) |
+| Prompt, tool/parameter description, context assembly, persisted prompt default | [`../release-risk/prompt-surface.md`](../release-risk/prompt-surface.md) |
+| Shared API/component, first-minute UI, feature flag, mixed PR scope | [`../release-risk/rollout-surface.md`](../release-risk/rollout-surface.md) |
-The question is not "is a flag nice to have" — it is **what does undoing this cost, and can that cost be lowered**. Reverting a PR means a revert commit, a rebuild, a redeploy, and it takes everything else in that PR with it. Turning a flag off is seconds and surgical, and this repo can flip flags at runtime through edge config without a deploy at all (`packages/app-config/src/featureFlags/`, `packages/edge-config/`).
-
-Recommend gating when **all** of these hold:
-
-- The change alters a user-visible main path, and its bad outcome is "works, but wrong" rather than "crashes" — crashes get caught by monitoring, silent wrongness does not
-- It cannot be fully validated before shipping: it depends on production data volume, real traffic patterns, or a third-party system
-- Undoing it by revert is disproportionately expensive — the PR carries other work, or the revert would have to drag a migration with it
-
-Also recommend one when the rollout should be staged (small cohort first, watch a metric, then widen) — that is a capability a revert cannot give you at all.
-
-Do **not** recommend a flag when:
-
-- It is a plain bug fix. Gating a fix keeps the buggy path alive and doubles the states to reason about
-- The change is internal-only: scripts, dev tooling, agent skills, anything with no user-facing surface
-- A migration is the risky part. **A flag does not gate a schema change** — the DDL either ran or it did not. Gating the _reader_ while the schema already changed is a false sense of safety; say so instead of proposing a flag
-- An equivalent switch already exists — check before adding a second one for the same surface
-- The flag plumbing would be more complex or longer-lived than the change it guards. Every flag is a branch someone must delete later; a flag with no removal condition is technical debt with a straight face
-
-When you do recommend one, state the removal condition in the same breath: what observation makes it safe to delete the flag and the old path.
-
-**Shared surface and high-frequency UI**
-
-Two different multipliers, same class. A base component's reach is its call-site count; a high-frequency screen's reach is the number of users who hit it every day. The second one has no import graph to measure it, which is why it gets skipped.
-
-High-frequency surfaces — the entry screen after auth, the main chat/work surface, the global navigation and sidebar, the command palette, the composer/input, anything on the path a user walks within seconds of opening the product:
-
-- A defect here has no soak period. It is not "some users eventually"; it is everyone, within minutes of deploy, on the flow they use most
-- Interaction changes on these surfaces cost more than their code suggests. Moved or removed controls, changed keyboard/shortcut behavior, a new confirmation step, an altered default, a changed submit/Enter semantic — users have muscle memory here, and "it still works, it just moved" is a support and trust cost that no revert undoes for people who already hit it
-- The failure mode is usually _not_ a crash: layout that breaks at one viewport, a state that no longer restores, an action that silently does nothing. Monitoring does not catch these; users do
-- This is the strongest case in the whole dimension for staged rollout or a flag, because it is the change whose bad outcome arrives fastest and reaches furthest
-- Judge the _reach and reversibility_, not the design. Whether the new interaction is better belongs to `ux`; whether shipping it all at once is wise belongs here
-
-Shared surfaces — measured by call sites:
-
-- Files under `src/components/`, anything exported from a `packages/*` public entry, shared hooks/utils/contexts, and design-system wrappers — treat these as base surfaces regardless of how small the diff is
-- Behavior change to an existing prop: new default value, changed fallback, altered event timing. Every existing call site silently inherits it without appearing in the diff
-- Signature change: new required prop, renamed prop, narrowed type — breaks call sites; check whether all of them were updated, including `.desktop`/`.mobile` variants and other packages
-- Cost added inside a base component (a new hook, effect, context subscription, observer, or per-render computation) — it is paid once per call site per render, so a "small" addition multiplies
-- Extensibility regression: a variant hardcoded with an `if`/switch on a specific caller, or logic that belongs to one consumer pushed down into the shared component — the next variant can only be another branch
-- Visual/interaction regression radius: a style or layout change in a base component reaches surfaces nobody listed in the PR description
+## Two output shapes
-**PR purity**
+- Emit an `issues` finding when the code or diff proves a recovery hazard.
+- Emit a `release_checks` item when safe deployment depends on production or external state the repo
+ cannot answer, such as existing row shape, live configuration, or current queue contents.
-- Count the independent sub-requirements in the diff (group by domain/feature, not by file count). Two or more that could each stand alone is the signal to look closer
-- Recommend a split when: a sub-requirement is large or high-risk on its own, **and** it has no compile-time or runtime dependency on the rest of the diff
-- Mixed risk levels in one PR: a DB migration or base-component change riding along with copy tweaks or unrelated refactors. The whole PR now inherits the highest risk level for review, approval, and rollback
-- Drive-by refactors, formatting sweeps, or dependency bumps that bury the actual change — reviewers cannot separate intent from noise, and a rollback takes the unrelated work with it
-- A PR whose description lists one goal but whose diff implements several
+A release check is not a weak finding. Additive and reversible migrations with no concrete ordering
+or production-state dependency produce neither output.
-## Rule sources (deep mode: read before reviewing)
+## Rule sources (deep mode: read only when the touched surface requires them)
-- `.agents/skills/db-migrations/SKILL.md` — rollout strategy, online index creation, backfills, what makes a migration safe
-- `.agents/skills/drizzle/SKILL.md` — schema conventions, what generates a migration
-- `.agents/skills/upstash-workflow/SKILL.md` — workflow/queue semantics, what a step change means for runs already in progress
-- `.agents/skills/pr/SKILL.md` — stacked-PR workflow and layer ordering; the concrete mechanics for any split you recommend
-- `.agents/skills/react/SKILL.md` — component layering, which surfaces count as shared
-- `.agents/skills/builtin-tool/SKILL.md` — manifest/description conventions, how a tool's text reaches the model
-- `.agents/skills/agent-tracing/SKILL.md` — pulling real transcripts, the only way to show a prompt change's before/after
+- `.agents/skills/db-migrations/SKILL.md`, `.agents/skills/drizzle/SKILL.md` — schema and migration
+ changes
+- `.agents/skills/upstash-workflow/SKILL.md` — queue and workflow changes
+- `.agents/skills/builtin-tool/SKILL.md`, `.agents/skills/agent-tracing/SKILL.md` — prompt and tool
+ behavior
+- `.agents/skills/react/SKILL.md` — shared UI surfaces
+- `.agents/skills/pr/SKILL.md` — independently shippable PR splits
## How to check
-1. **Persisted state**: list every migration file and schema change in the diff. For each statement, ask three questions — does it destroy or rewrite existing data; does it fail on production data that fixtures lack; can the previous code version still run against the new schema? Then find the schemaless writes: grep the diff for `jsonb` column writes, cache `set` calls with object payloads, and client-persistence writes, and compare each written shape against what its reader accepts.
-2. **Dev-cycle drift**: read the PR's migration files **in order as a series**, not one at a time, and ask what a clean database ends up with — any object created and then altered/renamed/dropped within the same PR is churn to squash. Then cross-check the schema files against the code: every table/column the diff reads or writes must be created by a committed migration, not assumed to exist. If the PR history shows several rounds of rework, add a `release_checks` item to replay the migrations on a fresh database before deploying.
-3. **Deploy-moment state**: grep the diff for changed job/message payload types and workflow step definitions; for each, ask what happens to an item enqueued five minutes before deploy. Then collect every config value the new code reads (`process.env`, env schema files, flag lookups) and check whether the diff also adds it to the example/schema files — an env var read but never declared is a release check at minimum. Finally, trace new bulk write paths for outbound senders (mail, notification, payment, webhook).
-4. **Prompt surface**: read every changed prompt string as a **behavior diff**, not as copy — for each edit, say what the model did before and what it will do now. Removed or weakened sentences get `git log -S '<removed phrase>'` to recover why they were added. For a tool/parameter description, name the tool and the direction of the selection-rate change. Then check the PR for any evidence of validation (eval, transcript, staged rollout); none of the three on a user-facing prompt is itself the finding.
-5. **Rollback granularity**: for the riskiest change in the diff, write the actual undo procedure in one sentence. If that sentence is "revert the PR and redeploy" and the change is user-visible and unvalidatable, ask whether a flag is warranted against the criteria above — and check whether one already exists for that surface before proposing a new one.
-6. **Shared surface**: for each touched file that qualifies as a base surface, count its call sites (`rg -l "from '.*<Component>'"` or the package's import graph) and state the number in the finding — blast radius is the evidence. Then diff the props/behavior contract, not just the implementation.
-7. **High-frequency UI**: for each changed user-facing surface, place it on the user's path — how soon after opening the product is it reached, and can the flow be completed without it? For anything on the first-minute path, state what a user with existing habits experiences on the first load after deploy, and whether that experience is recoverable without a redeploy.
-8. **PR purity**: cluster the changed files by domain and name each cluster's sub-requirement in one phrase. For any cluster you propose splitting out, prove independence by checking that nothing outside it imports what it adds — an unprovable split is not a finding.
-9. For every finding, state the recovery cost explicitly: what it takes to undo this after it reaches production.
-10. Whatever you could not settle from the repo alone — production data shape, whether a config value is set per target, current queue depth — goes to `release_checks`, phrased as something a human can confirm in one action. Never guess it into a finding.
-
-## Severity and likelihood calibration
-
-This dimension is the easiest one to turn into a rubber stamp that blocks every PR touching the database. Hold the line:
-
-- **p0** — genuinely unrecoverable: destructive DDL with no backup or reconstruction path, a migration that will fail against real production data, or a schema change that breaks the currently deployed code with no compatibility window. "Cannot be undone after deploy" is the bar, not "involves SQL".
-- **p1** — recoverable but expensive: a reader that will throw on legacy-shaped records, a consumer that rejects payloads already in the queue, a base-surface contract change with call sites left unupdated, an independently shippable large sub-requirement bundled in, a first-minute-path interaction change shipped all-at-once with no gate, a prompt edit that removes an existing constraint or moves a tool's selection behavior with nothing validating it.
-- **p2** — advisory: split suggestions for smaller sub-requirements, mixed risk levels, missing rollback notes on an otherwise safe change, migration churn to squash.
-
-Purity findings cap at p1 and are normally `blocks_release: false` — a split is a process improvement, not a shipping blocker, unless the bundled part is itself a p0 risk.
-
-Prompt findings sit at p1 by default. p0 only when the edit removes a safety/refusal constraint or breaks a contract another system parses (a tool schema, a structured-output format) — "the model may behave differently" is p1 at most, because it is recoverable by a redeploy even though the outputs it already produced are not.
+1. Classify the touched surfaces and read only their routed references and rule sources.
+2. Write the actual recovery procedure for every candidate finding.
+3. Separate evidence in code from unknown production state; route the latter to `release_checks`.
+4. Keep dimension ownership sharp: locking/cost belongs to `performance`, design quality to `ux`,
+ abstraction ownership to `reuse-architecture`, and PR metadata to `workflow`.
-`likelihood` here means **how likely the risk materializes**, not how often the code runs. A migration executes exactly once with certainty, but whether it damages anything depends on the production data: `high` when the hazard depends on data that certainly exists (any populated table), `medium` when it depends on data shapes we plausibly have, `low` when it needs a state the product has probably never produced.
+## Severity and likelihood
-## Violations
+- **P0**: catastrophic and effectively irreversible data loss, financial loss, auth/safety failure,
+ or an incompatible deploy with no recovery window.
+- **P1**: real but recoverable breakage requiring migration, backfill, drain, coordinated deploy,
+ staged rollout, or a costly split/revert.
+- **P2**: advisory rollout, rollback-note, migration-churn, or small purity improvement.
-- An irreversible or hard-to-reverse data change shipped without a stated rollback/backfill plan or deploy ordering.
-- A schemaless shape change (jsonb, cache payload, client persistence, stored blob) whose readers do not handle records written before it.
-- A payload or workflow-step change that breaks items already enqueued or mid-run at deploy time.
-- A bulk write path that fans out to an outbound sender with no guard on volume or recipient set.
-- A migration series inside this PR that ships the development iteration itself — an object created then renamed or dropped by a later migration in the same PR, or a defensive clause that exists only to survive a local database.
-- Code that reads or writes a table/column no committed migration creates.
-- A prompt edit that deletes or weakens an existing instruction without recovering why it was added, or that changes a tool/parameter description in a way that moves when the model calls it — shipped with no eval, no before/after transcript, and no staged rollout.
-- A prompt or assembly-order change presented as a wording cleanup or refactor when it changes what the model does.
-- A default prompt change that is meant to reach existing user-owned records but has no backfill, or that silently does reach them when it should not.
-- A base-surface change whose blast radius (named call-site count) exceeds what the PR description and tests account for.
-- A change to a first-minute user path (entry screen, main work surface, navigation, composer, command palette) that alters an established interaction and ships ungated, where the failure mode is silent rather than a crash.
-- A PR bundling an independently shippable, large-or-risky sub-requirement that has no dependency on the rest.
-- An unvalidatable, user-visible main-path change shipped with revert as its only undo, where a flag would have made the undo surgical.
+Likelihood is the chance the hazard materializes, not how often the code executes. Production state
+that is unknown becomes a release check instead of a guessed likelihood.
## Not violations
-- Additive, reversible schema changes that ship with the code that uses them: a nullable column, a new table, a new index created concurrently. Adding a column is not a finding merely because it touches the database.
-- Lock duration, migration idempotency, and query cost — those belong to the `performance` dimension. Report the data-safety and reversibility angle here and do not restate the locking analysis.
-- A new env var that the diff also declares in the env schema and example files, with a sane default or a loud startup failure — that is a release check at most, not a finding.
-- Cache payload changes on a key with a short TTL where the reader tolerates a miss: the old shape drains on its own. Say so instead of reporting it.
-- A missing feature flag on a change that is small, verifiable before shipping, or cheap to revert. "Could be flagged" is not a finding — only "revert is the only undo and revert is expensive" is.
-- Genuinely non-behavioral prompt edits: a typo, a broken template variable, formatting, or a translation of text the model never reads differently. Not every string in a prompt file is a prompt.
-- Prompt changes that are themselves the requirement, where the PR states the intended behavior change. Review the rollout (validation, reach, what already-produced outputs look like), not whether the new instruction is the right one — that is a product decision.
-- Whether the new wording is well written, better structured, or more token-efficient — that is `code-style` and `observability`. This dimension asks only what happens to users on the next request and how it is taken back.
-- Multiple migrations in one PR that each do a distinct, forward-only thing — a series is only churn when a later statement undoes or reworks what an earlier one in the _same PR_ created.
-- Idempotency guards (`IF NOT EXISTS` / `IF EXISTS`) on objects the migration did not create — those are the repo's convention and belong to `performance`'s idempotency rule, not here. Only guards protecting against a state that exists solely on a developer's machine are a finding.
-- Whether a UI change is a good design, whether the new copy reads well, whether the interaction is discoverable — that is `ux`. This dimension judges only how far and how fast a bad outcome would spread, and what it costs to pull back.
-- A high-frequency surface touched in a purely additive or internal way: a new optional element, a refactor with no interaction change, a style fix. Reach alone is not a finding; a changed established behavior on that reach is.
-- Whether a shared abstraction is the _right_ one, or duplicates an existing implementation — that is `reuse-architecture`. This dimension only judges the blast radius of changing it.
-- PR description drift and issue/CI state — that is `workflow`. Purity is about the diff's internal composition, not its paperwork.
-- A large diff that is large because one requirement genuinely spans many files. Size alone is never a purity finding; independence is the test.
-- Splits that would create a broken intermediate state — a stacked PR whose lower layer does not build or deploy on its own is worse than one honest PR.
+- Additive, reversible migrations without a concrete hazard.
+- A new env var declared for every target with a sane default or loud startup failure.
+- Short-TTL cache changes whose readers tolerate a miss.
+- Small, verifiable, cheap-to-revert behavior changes without a feature flag.
+- Product-authorized prompt behavior changes with proportionate validation and rollout.
+- Additive/internal UI work that does not change an established interaction.
+- Large but coherent changes that cannot ship independently.
diff --git a/.agents/skills/deep-review/references/release-risk/persisted-state.md b/.agents/skills/deep-review/references/release-risk/persisted-state.md
new file mode 100644
index 00000000000..854c4745457
--- /dev/null
+++ b/.agents/skills/deep-review/references/release-risk/persisted-state.md
@@ -0,0 +1,66 @@
+# Persisted State and Deploy-Moment Risk
+
+Read this reference when the diff touches migrations, schema, structured values stored without a
+schema migration, queues, workflows, cron jobs, configuration, or outbound side effects.
+
+## Persisted state
+
+- Read every migration and generated SQL statement in full. Additive, reversible changes such as a
+ nullable column, new table, or concurrent index produce no finding or release check unless a
+ concrete ordering or production-state dependency exists.
+- Flag destructive DDL (`DROP`, narrowing type changes, enum-value removal), data-mutating
+ migrations without a reconstruction path, and constraints that may reject existing rows.
+- Check `ON DELETE CASCADE` additions for newly widened deletion effects.
+- Treat structured values without DDL as persisted contracts:
+ - `jsonb` keys and value types
+ - Redis/cache objects
+ - localStorage, IndexedDB, and persisted stores
+ - manifests or JSON blobs in object storage
+ Compare the writer's new shape with every reader. Old values remain until explicitly migrated or
+ expired; a reader must tolerate the legacy shape.
+- State rollback asymmetry and deploy ordering explicitly. If reverting code while keeping the new
+ schema breaks the previous version, the release has crossed a one-way compatibility boundary.
+
+## Dev-cycle drift
+
+- Read this PR's migrations as a series. If the same PR creates an object and later renames, drops,
+ or reworks it, squash the unshipped intermediate states into the final shape.
+- Reject migration statements whose only purpose is accommodating a developer database state that
+ production has never seen.
+- Cross-check every table and column used by the diff against committed schema and migrations. A
+ local database can contain residue that production will never create.
+- Check ordering after rebases: trunk migrations must run first without colliding with this branch.
+- What cannot be settled from the repo becomes one precise release check, such as replaying the
+ migrations on a clean database or counting rows that would violate a new constraint.
+
+Do not recommend squashing migrations that already ran in any shared environment. They are history,
+not development residue.
+
+## Deploy-moment state
+
+- Queued messages and in-flight workflows were produced by the old code. When payload fields or
+ workflow-step ordering change, keep consumers backward-compatible for at least one deploy cycle
+ or document a drain-and-deploy procedure.
+- A cron or scheduled job runs against production-scale backlog on its first tick. Check
+ idempotency, scope, and whether a schedule change can overlap the old schedule.
+- For new configuration, verify declaration, default/failure behavior, and every deployment target.
+ Unknown live values become release checks; missing declarations in code are findings.
+- Trace bulk writes for irreversible fan-out: email, push, payment calls, and third-party webhooks.
+ A rollback cannot recall an outbound effect.
+
+## Verification guidance
+
+- Confirm data hazards from the actual SQL and readers, not from the presence of a migration.
+- A `jsonb` or cache-shape finding survives only when a real legacy value reaches a reader that
+ cannot handle it.
+- Dev-cycle churn exists only when this PR both creates and later reworks the same object.
+- Separate migration cost and locking (`performance`) from reversibility and recovery cost (this
+ dimension).
+
+## Severity
+
+- **P0**: destructive or incompatible change that cannot be safely undone, or a migration that will
+ fail against data known to exist.
+- **P1**: legacy records or in-flight payloads can break, but recovery is possible with an explicit
+ migration, compatibility reader, or drain procedure.
+- **P2**: unshipped migration churn or a missing rollback note with no demonstrated runtime failure.
diff --git a/.agents/skills/deep-review/references/release-risk/prompt-surface.md b/.agents/skills/deep-review/references/release-risk/prompt-surface.md
new file mode 100644
index 00000000000..09d8d0b9102
--- /dev/null
+++ b/.agents/skills/deep-review/references/release-risk/prompt-surface.md
@@ -0,0 +1,47 @@
+# Prompt-Surface Risk
+
+Read this reference when the diff changes system roles, tool or parameter descriptions, context
+assembly, prompt injection order, or defaults copied into user-owned records.
+
+Prompts are production behavior without compiler enforcement. Review the behavioral delta, not the
+writing style.
+
+## Checks
+
+- Tool and parameter descriptions decide whether the model calls a tool and with which arguments.
+ Name the affected tool and the expected direction of the selection-rate change.
+- For a removed or weakened instruction, run `git log -S` on the removed text and recover why it was
+ added. Confirm the instruction was not moved elsewhere in the assembled prompt.
+- Treat safety and refusal constraints as enforcement. A weakened security constraint also belongs
+ to the security dimension.
+- Treat assembly-order and injection-point changes as behavior changes even when no words changed.
+- Determine whether the prompt is read dynamically or copied into persisted user records. A default
+ change does not update existing copies without a backfill.
+- Account for prompt length and prefix-cache invalidation. Cost arithmetic belongs to
+ `observability`; rollout and recovery belong here.
+- Require one validation path for a user-facing prompt change: an eval, a before/after transcript on
+ a real case, or a staged rollout.
+
+## Findings and non-findings
+
+Report a finding when the diff:
+
+- removes or weakens an instruction without recovering its original reason;
+- changes tool-selection or argument behavior with no validation;
+- presents an assembly-order or behavioral change as a wording cleanup;
+- intends to update persisted prompt copies without a backfill; or
+- reaches every user immediately while revert is the only validation and recovery mechanism.
+
+Do not report:
+
+- typo, formatting, template-variable, or translation fixes with no model-visible behavioral delta;
+- product-authorized behavior changes merely because the old wording was different; review their
+ validation and rollout instead;
+- writing-quality or token-efficiency preferences; or
+- a prompt change already covered by a representative eval or staged validation plan.
+
+## Severity
+
+- **P0** only for removed safety/refusal constraints or broken machine-parsed contracts.
+- **P1** for unvalidated behavioral, tool-selection, or assembly-order changes.
+- Prompt findings are never safe auto-fixes; wording is a behavior decision.
diff --git a/.agents/skills/deep-review/references/release-risk/rollout-surface.md b/.agents/skills/deep-review/references/release-risk/rollout-surface.md
new file mode 100644
index 00000000000..032ab014f5c
--- /dev/null
+++ b/.agents/skills/deep-review/references/release-risk/rollout-surface.md
@@ -0,0 +1,63 @@
+# Rollout, Shared-Surface, and PR-Purity Risk
+
+Read this reference when the diff changes a user-visible main path, a shared component or package
+API, a first-minute interaction, or several independent requirements.
+
+## Rollback granularity
+
+Recommend a feature flag only when all of these hold:
+
+- the change alters a user-visible main path;
+- the bad outcome is silent wrongness rather than an obvious crash;
+- production data, traffic, or a third party prevents complete pre-ship validation; and
+- reverting the whole PR is disproportionately expensive.
+
+Also recommend a flag for a staged cohort rollout. State the observation that permits removing the
+flag and the old path.
+
+Do not recommend a flag for:
+
+- a plain bug fix;
+- scripts, dev tooling, agent skills, or other internal-only changes;
+- schema changes themselves;
+- a surface already covered by an equivalent switch; or
+- a change where flag plumbing costs more than reverting it.
+
+## Shared surfaces
+
+Treat files under shared component directories, exported package APIs, hooks, utilities, and
+contexts as shared surfaces.
+
+- Count call sites and include the count in the finding.
+- Check changed defaults, fallback behavior, event timing, and required/narrowed props.
+- Include platform variants and package consumers, not only the current app.
+- Multiply added render/effect/subscription cost by call-site count.
+- Flag caller-specific branches pushed into a generic shared abstraction; abstraction ownership
+ belongs to `reuse-architecture`, while this dimension reports recovery and blast radius.
+
+No measurable blast radius or unchanged existing contract means no release-risk finding.
+
+## First-minute UI
+
+First-minute surfaces include the post-auth entry screen, main work/chat surface, navigation,
+sidebar, command palette, and composer.
+
+- Report only changed established behavior: moved/removed controls, altered defaults, new
+ confirmation steps, or changed keyboard/submit semantics.
+- State what an existing user experiences on the first load after deploy and how quickly the defect
+ reaches the user base.
+- Purely additive elements, internal refactors, and style fixes are not release-risk findings.
+- Design quality belongs to `ux`; this dimension judges reach and recovery.
+
+## PR purity
+
+- Cluster changed files by independent sub-requirement, not by directory.
+- Recommend a split only when a cluster is independently buildable/deployable and large or risky
+ enough to justify separate review and rollback.
+- Mixed-risk drive-by refactors, formatting, dependency bumps, or unrelated copy changes increase
+ rollback cost and can be findings.
+- Do not report size alone. A requirement that legitimately spans many files is one coherent scope.
+- Do not propose a split that creates a broken intermediate state.
+
+Purity findings cap at P1 and normally do not block release unless the bundled part independently
+creates a P0 risk.
diff --git a/.agents/skills/deep-review/references/report-template.md b/.agents/skills/deep-review/references/report-template.md
index b1f8201f3bf..c8bfa5b4bfe 100644
--- a/.agents/skills/deep-review/references/report-template.md
+++ b/.agents/skills/deep-review/references/report-template.md
@@ -16,8 +16,12 @@ Only `verdict: confirmed` findings are rendered (plus unverified dimensions —
- **Blocks release** renders verify's `blocks_release` (`yes`/`no`) on every confirmed finding — this is the user's ship/no-ship signal; never omit. Same-root merged entries take the value belonging to the highest merged severity.
- **Existing implementations** line only for `reuse-architecture` dedup findings, listing all entries.
- **Rule source** line renders the finding's `rule_source` when present.
-- Apply `fix_options_override` / `nature_override` / `exposure_override` / `likelihood_override` before rendering.
-- **Same-root merge**: findings with `same_root_as: X` fold into X's entry — no separate number; add `**Same root**: id (location, issue_type), ...` at the entry's end; entry severity upgrades to the highest among merged; statistics count merged entries once.
+- Apply `fix_options_override` / `severity_override` / `nature_override` / `exposure_override` /
+ `likelihood_override` before rendering, then apply the global consolidation map.
+- **Same-root merge**: findings mapped to `same_root_as: X` by the global consolidation pass fold
+ into X's entry — no separate number; add `**Same root**: id (location, issue_type), ...` at the
+ entry's end; entry severity upgrades to the highest among merged; statistics count merged entries
+ once.
- **P2 cap (noise control)**: if confirmed P2 count > 6, render the top 6 fully and collapse the rest into one line each under `More P2`: `**#n** [issue_type] summary (file:line)`. Rank `low` likelihood last when choosing which 6 to render fully.
- **Hand off to owner**: every `exposed_legacy` finding except triggered-P0 renders here. Do NOT create the Linear issues — render the draft and let the user decide; a deep review can surface several legacy items and auto-filing them is noisy and duplicates existing issues. The culprit comes from verify's `culprit` field (the verifier already had the file open) — render it verbatim; `culprit: null` renders "attribution unclear" and no suggested assignee. Do not re-run `git blame` in the render phase.
- Empty severity buckets omit their heading entirely.
@@ -25,7 +29,9 @@ Only `verdict: confirmed` findings are rendered (plus unverified dimensions —
- **Unverified dimensions**: `workflow` findings render under `Process`, `skill-freshness` under `Skill updates` — outside the severity buckets, excluded from P0/P1/P2 statistics. These findings use the same JSON schema as everything else; render one line each mapped from those fields: fact = `summary`, evidence = `location` (plus `scenario` when present), suggested action = the first `fix_options` entry. Their `severity` is advisory and never rendered.
- **Missing sources**: if any reviewer returned `missing_sources`, append a note recommending the listed rule files be fixed/restored.
- **Workflow feedback**: merge equivalent suggestions across subagents, accumulate sources (`sources: code-style, verify`), render at the end; omit the section when empty.
-- **PR mode** (the user's message contains a GitHub PR URL): render `Merge verdict` between TL;DR and Findings. Otherwise omit the section entirely. Bare `#123` / `pr 123` do NOT trigger PR mode.
+- **PR mode**: render `Merge verdict` when the user supplies a GitHub PR URL or an unambiguous PR
+ reference such as `PR #123`, `pr 123`, or `pull request 123`. A bare `#123` remains ambiguous and
+ does not trigger PR mode.
### Merge verdict decision table (PR mode; main agent fills, never delegated)
@@ -65,7 +71,7 @@ Before sending, confirm every item; fix and re-render if any is missing:
**Scope**: {e.g. `feat/user-batch-delete` vs local `main`, 8 files +240/-37, incl. submodule lobehub}
**Background**: {1-2 sentence core of the step-0 scope summary}
-**Execution**: {N} dimension reviewers ({list}) + {M} verifiers; pruned: {dimension — one-line reason, or "none"}
+**Execution**: {N} dimension reviewers ({list}) + {M} verifiers{ + global consolidation when run}; pruned: {dimension — one-line reason, or "none"}
## TL;DR
diff --git a/.agents/skills/deep-review/references/review-prompt.md b/.agents/skills/deep-review/references/review-prompt.md
index 34c5d2df66e..65510cd0ed3 100644
--- a/.agents/skills/deep-review/references/review-prompt.md
+++ b/.agents/skills/deep-review/references/review-prompt.md
@@ -29,7 +29,10 @@ After you have the diff, read whatever surrounding files you need for context.
## Mandatory preparation
-Read every rule file listed below IN FULL, then read the rule sources each file lists (skills, docs). These files define how to check, what counts as a violation, and — equally important — what does NOT count:
+Read every dimension file listed below IN FULL. Follow each file's routing table: read every routed
+reference required by the touched surface IN FULL, and skip unrelated routed references. Then read
+only the relevant sections of the external rule sources it lists (skills, docs). These files define
+how to check, what counts as a violation, and — equally important — what does NOT count:
{dimension_files}
@@ -59,45 +62,51 @@ Evidence gathering is bounded — you are a finder, not the final judge:
- Once a finding has concrete `file:line` evidence, stop expanding; do not keep browsing to make it stronger.
- Deep falsification belongs to the independent verify pass, not to you: when settling a suspicion would take more than a handful of targeted file reads, report it with your best evidence instead of running a multi-file proof campaign.
-- Read rule sources selectively — the sections relevant to the touched surfaces — not cover to cover.
+- Read external rule sources selectively — the sections relevant to the touched surfaces — not cover
+ to cover. Routed deep-review references selected above are still read in full.
## Return format (strict JSON)
Output exactly ONE JSON object inside a ```` ```json ```` fence (the main agent extracts and `JSON.parse`s it). Valid JSON only: escape quotes/backslashes, no comments, no trailing commas, no single quotes.
+Every issue requires `id`, `dimension`, `issue_type`, `nature`, `severity`, `likelihood`,
+`location`, `summary`, `core_problem`, `fix_cost`, at least one `fix_options` entry, and
+`need_test`.
+
+Conditional fields:
+
+- `exposure` and `scenario` when `nature` is `exposed_legacy`
+- `scenario` when likelihood is `low`
+- `existing_implementations` for reuse-architecture dedup findings
+- `rule_source` for style or convention findings
+
+```json
{
- "missing_sources": ["path"], // only when a listed rule source could not be read; omit otherwise
"issues": [
{
- "id": "logic-1", // required; dimension id_prefix + ordinal (prefix defined in the dimension file)
- "dimension": "logic", // required; one of your assigned dimension ids
- "issue_type": "edge case", // required; a precise short phrase (2-5 words), NOT the dimension name — e.g. "missing auth scope", "N+1 query", "stale comment"
- "nature": "introduced", // required; introduced | exposed_legacy
- "exposure": "triggered", // required when nature=exposed_legacy; triggered | bystander. Omit for introduced
- "severity": "p1", // required; p0 | p1 | p2 (definitions below)
- "likelihood": "medium", // required; high | medium | low (definitions below) — how often the scenario actually fires in production
- "location": "src/api/user.ts:87", // required; exact file:line
- "summary": "1-2 technical sentences for a reviewer who reads code", // required
- "core_problem": "≤ 2 plain-language sentences: impact + cause, understandable without reading code", // required
- "scenario": "concrete trigger scenario", // optional; required when nature=exposed_legacy or likelihood=low
- "existing_implementations": ["src/foo.ts:62-138"], // required (≥ 1 entry) only for dimension=reuse-architecture dedup findings; omit otherwise
- "rule_source": "dimensions/code-style.md → antd import rule", // required for style/convention findings: which rule this violates; omit for logic bugs proven by evidence
- "fix_cost": "low", // required; low | medium | high
- "fix_options": ["option A", "option B"], // required; ≥ 1
- "need_test": true // required; does the fix need an accompanying test
- }
- ],
- "release_checks": [ // optional; ONLY the release-risk dimension emits these; omit entirely when empty
- {
- "item": "confirm S3_ENDPOINT is set in every deploy target", // one action a human can take before deploying
- "why": "src/server/upload.ts:14 reads it and throws on boot when unset; the diff does not add it to the env example",
- "blocks_deploy": true // true when deploying without confirming risks a production failure
+ "id": "logic-1",
+ "dimension": "logic",
+ "issue_type": "empty input",
+ "nature": "introduced",
+ "severity": "p1",
+ "likelihood": "high",
+ "location": "src/api/user.ts:87",
+ "summary": "Batch delete accepts an empty id list and builds invalid SQL.",
+ "core_problem": "Because empty input is not rejected, submitting an empty selection returns a server error.",
+ "scenario": "The bulk-action UI submits after the final selected row is deselected.",
+ "fix_cost": "low",
+ "fix_options": ["Require at least one id in the input schema"],
+ "need_test": true
}
- ],
- "workflow_feedback": [ // optional; omit entirely when empty
- { "suggestion": "concrete, actionable improvement to a named skill file/section", "why": "what happened this run" }
]
}
+```
+
+Optional top-level fields:
+
+- `missing_sources`: string paths that could not be read
+- `release_checks`: release-risk only; entries require `item`, `why`, and `blocks_deploy`
+- `workflow_feedback`: entries require `suggestion` and `why`
### release_checks
@@ -107,10 +116,11 @@ Do not use it as a place to park weak findings. If the problem is in the code, i
### severity definitions
-Severity is **impact only** — how bad it is when it fires. How often it fires is `likelihood`, scored separately below; never let a rare trigger pull the severity down.
+Severity is **impact only** — how bad it is when it fires. Requirement gating is decided later via
+`blocks_release`; never inflate severity merely because an acceptance criterion exists.
-- p0: when it fires it is a production incident (data corruption / financial loss / auth bypass / outage), or it directly violates the stated requirement and acceptance criteria
-- p1: a real bug that should be fixed in this change
+- p0: when it fires it is a production incident (data corruption / financial loss / auth bypass / outage)
+- p1: a real bug or requirement deviation that should be fixed in this change
- p2: real but deferrable; bookkeeping level
### likelihood definitions
@@ -131,29 +141,4 @@ Precise beats broad ("rename missed import" not "code style"). Short beats long
## When you find nothing
Return `{"issues": []}`. No silence, no pleasantries.
-
-## Example finding (format alignment)
-
-{
- "issues": [
- {
- "id": "logic-1",
- "dimension": "logic",
- "issue_type": "edge case",
- "nature": "introduced",
- "severity": "p1",
- "likelihood": "high",
- "location": "src/api/user.ts:87",
- "summary": "Batch delete endpoint doesn't validate userIds length; an empty array builds `DELETE FROM users WHERE id IN ()` which is a SQL syntax error.",
- "core_problem": "Because input validation misses the empty-array branch, a UI that submits an empty selection gets a 500 and looks like a server outage.",
- "scenario": "Front end submits an empty selection list; endpoint 500s instead of returning a friendly no-op.",
- "fix_cost": "low",
- "fix_options": [
- "Add z.array(z.string()).min(1) at the input layer",
- "Early-return in the service for empty arrays"
- ],
- "need_test": true
- }
- ]
-}
`````
diff --git a/.agents/skills/deep-review/references/scoping.md b/.agents/skills/deep-review/references/scoping.md
index c5c20141160..06f5c187b99 100644
--- a/.agents/skills/deep-review/references/scoping.md
+++ b/.agents/skills/deep-review/references/scoping.md
@@ -24,7 +24,10 @@ Note the asymmetry, it is the easiest mistake here: `log` wants **two** dots whe
## 2. Pick the full-diff command by review target
-1. **User named a PR by URL** → `gh pr diff <num>`. Also fetch `gh pr view <num> --json mergeable,isDraft,reviewDecision,statusCheckRollup` and append those fields to the scope summary (feeds the merge-verdict table). URL only — bare `#123` does not trigger PR mode.
+1. **User named a PR by URL or an unambiguous PR phrase** (`PR #123`, `pr 123`,
+ `pull request 123`) → `gh pr diff <num>`. Also fetch
+ `gh pr view <num> --json mergeable,isDraft,reviewDecision,statusCheckRollup` and append those
+ fields to the scope summary. A bare `#123` remains ambiguous and does not trigger PR mode.
2. **User named a specific commit or range** (a SHA, `abc123..def456`) → review exactly that object: `git show <sha> --stat` then `git show <sha>` for a single commit, `git diff <a>..<b>` for a range. The named object IS the scope — ignore branch/worktree state and do not fall through to the rules below.
3. **Non-default branch AND uncommitted changes both exist** → ask the user which to review: uncommitted only (`git diff HEAD` + untracked files read separately), committed branch work (`git diff <base>...HEAD`), or both (`git diff $(git merge-base <base> HEAD)` — worktree against the merge-base; the plain one-commit form `git diff <base>` would re-import default-branch advances as reverse diffs). Gitlink-only entries (`M <submodule>` where `git status` shows `(new commits)` and nothing else changed) do NOT count as uncommitted changes — a superproject tracking an in-flight submodule branch shows this permanently; route them through §4 instead of triggering this question.
4. **Uncommitted changes on the default branch** → `git diff HEAD`; list untracked via `git ls-files --others --exclude-standard` (§3 defines how their contents join `{changes}` — `git diff HEAD` alone misses them entirely).
diff --git a/.agents/skills/deep-review/references/verification/release-risk.md b/.agents/skills/deep-review/references/verification/release-risk.md
new file mode 100644
index 00000000000..92677ddd383
--- /dev/null
+++ b/.agents/skills/deep-review/references/verification/release-risk.md
@@ -0,0 +1,19 @@
+# Release-Risk Verification Addendum
+
+Apply only to findings with `dimension: "release-risk"`.
+
+- **Data layer**: read the actual SQL and reader. Additive, reversible changes are false positives
+ unless a concrete ordering or rollback hazard survives. For schemaless state, confirm a real
+ legacy value reaches a reader that cannot handle it.
+- **Dev-cycle churn**: confirm this PR both creates and later reworks the same object. An object that
+ existed on trunk is a normal forward migration.
+- **Prompt surface**: require a named behavioral delta. Confirm removed instructions were not moved
+ elsewhere. Prompt findings are never auto-fixes.
+- **High-frequency UI**: confirm the surface is on a first-minute path and an established behavior
+ changed. Additive-only work and design preferences are false positives.
+- **Shared surface**: reproduce the call-site count. No measurable blast radius or unchanged
+ existing contract means false positive.
+- **PR purity**: prove the proposed split builds and deploys independently. Shared dependencies or a
+ broken intermediate state invalidate the finding.
+
+Release-risk findings always use `can_auto_fix: false`.
diff --git a/.agents/skills/deep-review/references/verification/reuse-architecture.md b/.agents/skills/deep-review/references/verification/reuse-architecture.md
new file mode 100644
index 00000000000..1ed0f31261f
--- /dev/null
+++ b/.agents/skills/deep-review/references/verification/reuse-architecture.md
@@ -0,0 +1,14 @@
+# Reuse-Architecture Verification Addendum
+
+Apply only to `reuse-architecture` dedup findings.
+
+Open every entry in `existing_implementations` with enough surrounding context to compare behavior:
+
+- At least one implementation has equivalent input, output, and side effects → `confirmed`.
+- All implementations are merely syntactically similar → `false_positive`, naming the semantic
+ difference.
+- Required context is unavailable → `need_more_context`.
+
+Reuse-architecture findings default to `can_auto_fix: false` because caller migration changes the
+blast radius. A constant or single-import swap with no signature change may be auto-fixable when the
+evidence says why.
diff --git a/.agents/skills/deep-review/references/verify-prompt.md b/.agents/skills/deep-review/references/verify-prompt.md
index 9209093e650..de3086cbe5f 100644
--- a/.agents/skills/deep-review/references/verify-prompt.md
+++ b/.agents/skills/deep-review/references/verify-prompt.md
@@ -1,119 +1,119 @@
# Verify Subagent Prompt Template
-Verification is the anti-hallucination backbone: review agents deliberately over-report; the verify agent independently falsifies each candidate. Review and verify must never share an agent — their goals are opposite, and one agent doing both collapses into confirmation bias.
+Verification independently falsifies candidate findings. Review and verify must never share an
+agent.
-Verification is pipelined per dimension (or per Codex group): as soon as a review subagent returns findings, spawn its verify subagent — do not wait for other reviewers. Dimensions whose file says `verify: false` (workflow, skill-freshness) skip verification entirely.
+Instantiate:
-How to instantiate:
-
-1. `{issues}` → the JSON array of that reviewer's findings (wrap in a ` ```json ` fence), keeping original ids
-2. `{scope_summary}` → the same scope summary from step 0
-3. `{changes}` → the same diff text or fetch command(s) the reviewer received
+1. `{issues}` → this reviewer's findings as valid JSON, preserving ids
+2. `{scope_summary}` / `{changes}` → the same values the reviewer received
+3. `{verification_addenda}` → include
+ [`verification/release-risk.md`](verification/release-risk.md) when the payload contains a
+ release-risk finding, [`verification/reuse-architecture.md`](verification/reuse-architecture.md)
+ when it contains a reuse-architecture finding, both when needed, or `None`
---
-`````text
-Verify the following code-review findings. Do not fix anything — judge only.
+````text
+Verify the following code-review findings. Do not fix anything.
## Scope summary
{scope_summary}
-## Changes (needed to judge `+` lines)
-Diff text or fetch command(s) — check the head, run commands yourself if needed:
+## Changes
+Use the diff directly, or run every fetch command when commands were supplied:
{changes}
-## Findings to verify (process each id independently)
+## Findings
{issues}
-## Verification actions (execute fully for EVERY finding)
-
-1. Open the finding's `location` file and read ≥ 30 lines of context on each side.
-2. Chase the relevant call chain, type definitions, and existing tests.
-3. Check whether the described scenario actually triggers.
-4. Validate the `nature` field against the actual location: `+` line → should be `introduced`; context/old line → should be `exposed_legacy`. Fix mislabels with `nature_override`.
-5. **Validate `exposure` on every `exposed_legacy` finding** — this decides whether the finding blocks this PR or is handed to the code's owner, so treat an inflated label as seriously as a false positive. `triggered` requires a concrete before/after argument: name what this diff changed (new caller, new input shape, new config, widened path) that makes the old problem reachable or harmful when it previously was not. Cannot produce that argument → it is a `bystander`; set `exposure_override: "bystander"`. Bystander finds survive only as obvious p0 production bugs; anything less → `false_positive` with reason starting `out-of-scope legacy:`.
- Then, for every `exposed_legacy` finding you `confirm`, **attribute the culprit while you already have the file open**: `git log -L <start>,<end>:<file>` or `git blame -L <start>,<end> <file>` on the finding's location; return commit + author + date in `culprit`. Attribution that fails or is ambiguous (bulk move, formatting commit, vendored code) returns `culprit: null` — never guess an author. The main agent renders what you return; it will not re-run blame.
-6. **Validate `likelihood`** against the real production path, not the theoretical one: who can reach this code, what state/timing/permission is required, what upstream validation already blocks it. `low` means a hand-crafted input, a state the product cannot currently produce, an improbable race, an environment we don't ship, or a guarantee that already holds upstream. Reviewers were told to over-report and tend to inflate this — downgrade with `likelihood_override` whenever the preconditions you actually read are narrower than the finding claims. Consistency: `likelihood: "low"` and `blocks_release: true` can coexist only when the impact is catastrophic and irreversible (data corruption, financial loss, auth bypass); otherwise a `low` finding is `blocks_release: false`.
-7. **Over-scrutiny filter** (skip for findings from dimension files marked `calibration_exempt: true`): if the finding holds the diff to a standard the surrounding codebase itself does not meet — the flagged pattern is widespread in equivalent existing code and this diff does not make it worse — verdict `false_positive` with reason starting `over-scrutiny:`. Same verdict for lifespan mismatch: the finding demands configurability, extensibility, or expiry automation from code the scope summary / PR / comments declare temporary (time-boxed campaign, experiment, one-off script) — reason starting `over-scrutiny: lifespan`; the only temporary-code findings that survive are those whose damage persists beyond the window (billing/credit/data writes). This filter exists because reviewers were instructed to over-report; you are the noise gate.
-8. **Extra steps for `dimension: release-risk` findings**, which claim a release consequence rather than a code defect — verify the consequence, not the code:
- - *Data-layer*: read the actual migration/schema statement and confirm the claimed irreversibility. Additive and reversible (nullable column, new table, concurrent index) → `false_positive` unless a stated rollback/ordering hazard survives. For a `jsonb` shape claim, open the reader and confirm it really does not defend against the legacy shape.
- - *Dev-cycle churn*: read the PR's migrations as a series and confirm the same PR both creates and later reworks the object. An object the PR only alters (it existed on trunk before) is a normal forward migration → `false_positive`. Same for a "code reads an uncreated table" claim: grep the schema files yourself before confirming.
- - *Prompt surface*: the finding must name a **behavioral** delta, not a stylistic one — which instruction was removed/weakened, or which tool's selection behavior moves and in which direction. A finding that only says the prompt changed, or that argues the new wording is worse writing, is `false_positive`. For a "removed instruction" claim, check the text really is gone rather than moved elsewhere in the assembled prompt. Confirmed prompt findings are never `can_auto_fix: true` — rewording a prompt back is a behavior decision, not a batch edit.
- - *High-frequency UI*: confirm two things independently — that the surface really is on the first-minute path (name it), and that an **established** behavior changed rather than something being added. Additive-only, or a surface reached through several deliberate steps → `false_positive`. A finding that merely restates that the change is user-visible, or that argues the new design is worse, is `false_positive` with reason starting `out-of-scope: ux`.
- - *Shared surface*: the finding must carry a call-site count — reproduce it (grep the imports). No measurable blast radius, or the contract is unchanged for existing callers → `false_positive`.
- - *PR purity*: confirm independence yourself — check that nothing outside the proposed split imports what it adds, and that the split-out part would build and deploy alone. Cannot prove independence, or the "sub-requirements" share a dependency → `false_positive`. Splitting is expensive; only a provable, worthwhile split survives.
-9. **Extra steps for `dimension: reuse-architecture` dedup findings**: open EVERY file in `existing_implementations` (≥ 30 lines context each) and compare behavioral equivalence — same input → same output/side effects. At least one true equivalent → `confirmed`; all merely syntactically similar → `false_positive` naming the semantic difference; unable to tell without missing context → `need_more_context`.
-
-## Anti-shortcut red lines
-
-- Every finding gets the full procedure; no shared conclusions across findings, even in the same file.
-- No "skim all files once, then batch-label".
-- Verdicts must not infect each other (A false_positive says nothing about B).
-
-Violating any red line invalidates the verification. Slow is acceptable; shortcuts are not.
-
-## Stance: falsify by default
-
-Look for the counterexample first: existing validation, early return, upstream guarantee, framework behavior, type constraint that prevents the scenario. Found one → `false_positive`. `confirmed` requires evidence you actually read (file:line or snippet), not "sounds plausible". If you are about to confirm an entire batch, stop and ask whether you are rubber-stamping. A `false_positive` is high-value output, not an insult to the reviewer.
-
-Keep it pragmatic: `reason` is one sentence; `evidence` is file:line + the shortest necessary argument (do not restate summary/scenario). Unsure → `need_more_context`, never a guessed `confirmed`. `fix_options_override` only when clearly better (found a reusable util, original option introduces a new bug, misses a necessary edge).
-
-## can_auto_fix (confirmed only)
-
-The main agent lists `can_auto_fix: true` findings in the "safe to fix now" batch. You judge it — you read the files. ALL four must hold:
-
-1. `fix_cost: low`
-2. Single obvious fix — one option, or several that are equivalent implementation details (no product/architecture trade-off)
-3. No external resource or product decision needed (no third-party setup, env values, threshold choices, fail-open vs fail-closed calls)
-4. Small blast radius — none of: 3+ files changed, architecture-layer changes (service split/merge, router restructure, store slice shape, core hook/context signature), database schema/migration, external contracts (API params, webhook payloads, third-party calls), user-perceivable behavior (UI flows, routes, hotkeys, end-user copy, permission boundaries)
-
-Any miss → `can_auto_fix: false` with `auto_fix_reason` naming the failed criterion. `reuse-architecture` findings default to `false` (caller migration violates #4); the rare exception (constant swap, single import switch, no signature change) needs its justification in `auto_fix_reason`.
-
-`release-risk` findings are always `can_auto_fix: false` — a PR split, a migration rollout plan, or a base-component contract change is a release decision for the human, never a batch edit.
-
-`nature: "exposed_legacy"` is always `can_auto_fix: false` (`auto_fix_reason: "legacy code — not this PR's scope"`), regardless of how trivial the fix looks. Patching someone else's old code from an unrelated PR is a scope decision for the human, never an auto-applied batch edit.
-
-## blocks_release (confirmed only)
-
-Would shipping without this fix be unacceptable? `true`: production incident / data corruption / security hole / auth bypass, or breaks acceptance criteria or a main user path. `false`: real but shippable — rare edges, degraded-but-working flows, internal/bookkeeping, code quality.
-
-Consistency: p0 → must be `true`; p2 → must be `false`; p1 → your call. A `likelihood: "low"` finding is `false` unless the impact is catastrophic and irreversible.
-
-## same_root_as (dedup, confirmed only)
-
-Multiple reviewers (or dimensions) often report the same underlying problem from different angles, or a set of findings one fix would resolve together. Process findings in input order; the first occurrence of a root cause returns normally; subsequent same-root findings add `same_root_as: <first id>`. "One fix resolves both" is the test — same location not required. Their `evidence` may be shorthand (`same root as style-1`).
-
-## Return format (strict JSON)
-
-One JSON object in a ```` ```json ```` fence. Valid JSON only.
-
+## Dimension-specific verification
+{verification_addenda}
+
+## Required procedure for every finding
+
+1. Open the location and read enough surrounding context to understand the function or contract.
+2. Chase the relevant callers, types, validation, and tests.
+3. Look for the counterexample first: an upstream guarantee, early return, framework behavior, or
+ existing validation that prevents the scenario.
+4. Validate `nature`: a changed `+` line is normally `introduced`; old code is
+ `exposed_legacy`. Use `nature_override` when the reviewer mislabeled it.
+5. For `exposed_legacy`, require a concrete before/after trigger. Without one, override exposure to
+ `bystander` with `exposure_override`. Bystander findings survive only when they are obvious P0
+ production bugs; otherwise return `false_positive` with reason beginning `out-of-scope legacy:`.
+6. Attribute confirmed legacy code with `git log -L` or `git blame`. Return commit, author, and date,
+ or `null` when attribution is ambiguous.
+7. Validate likelihood against the real production path and use `likelihood_override` when needed.
+ `low` requires a concrete precondition chain. Low-likelihood findings block release only for
+ catastrophic, irreversible impact.
+8. Validate severity as impact only. Use `severity_override` when the reviewer's P0/P1/P2 label is
+ wrong; judge `blocks_release` against the effective severity after that override.
+9. Apply the codebase and lifespan calibration unless the dimension declares
+ `calibration_exempt: true`. Widespread and not worsened, or permanent-code standards applied to
+ declared temporary code, means `false_positive` with reason beginning `over-scrutiny:`.
+10. Apply every supplied dimension-specific addendum.
+
+Process findings independently. Do not batch-label them or let one verdict influence another.
+Confirmed verdicts require file-and-line evidence. Uncertainty is `need_more_context`, never a
+guessed confirmation.
+
+## can_auto_fix
+
+Set `can_auto_fix: true` only when all are true:
+
+- `fix_cost` is low;
+- one obvious fix exists;
+- no external resource or product decision is needed; and
+- the change touches fewer than three files and no architecture layer, database schema, external
+ contract, user-visible behavior, route, hotkey, copy, or permission boundary.
+
+`release-risk` and `exposed_legacy` findings are never auto-fixes.
+
+## blocks_release
+
+- `true`: production incident, data corruption, security/auth failure, or a broken acceptance
+ criterion/main user path.
+- `false`: shippable rare edge, degraded-but-working behavior, or code-quality/bookkeeping debt.
+
+P0 must block; P2 must not. Low likelihood is non-blocking unless impact is catastrophic and
+irreversible.
+
+## Return format
+
+Return exactly one valid JSON object in a `json` fence. No comments, prose, trailing commas, or
+invented ids.
+
+Each input id must appear exactly once. Use only fields belonging to the selected verdict:
+
+- `confirmed`: `id`, `verdict`, `evidence`, `can_auto_fix`, `blocks_release`; add
+ `auto_fix_reason` when false. Optional corrections use these exact fields:
+ `severity_override` (`p0` / `p1` / `p2`), `nature_override` (`introduced` /
+ `exposed_legacy`), `exposure_override` (`triggered` / `bystander`), `likelihood_override`
+ (`high` / `medium` / `low`), and `fix_options_override` (string array). Add `culprit` or `note`
+ when applicable.
+- `false_positive`: `id`, `verdict`, `reason`.
+- `need_more_context`: `id`, `verdict`, `missing`.
+
+```json
{
"verifications": [
{
- "id": "logic-1", // must match an input id exactly
- "verdict": "confirmed", // confirmed | false_positive | need_more_context
- "evidence": "src/api/user.ts:87 — upstream zod schema lacks min(1); empty array reaches SQL", // confirmed only
- "can_auto_fix": true, // confirmed only
- "auto_fix_reason": null, // only when can_auto_fix=false: which criterion failed
- "blocks_release": true, // confirmed only
- "nature_override": null, // only when the original nature is mislabeled
- "exposure_override": null, // only when the original exposure is mislabeled; triggered | bystander
- "likelihood_override": null, // only when the original likelihood is inflated or understated; high | medium | low
- "culprit": null, // confirmed exposed_legacy only: "<short sha> <author> <YYYY-MM-DD>", or null when attribution is ambiguous
- "same_root_as": null, // optional; first-occurrence id of the shared root
- "fix_options_override": null, // optional; string array, only when clearly better
- "note": null, // optional caveat/risk remark
-
- "reason": null, // false_positive only: one sentence why it does not hold
- "missing": null // need_more_context only: what context is missing
+ "id": "logic-1",
+ "verdict": "confirmed",
+ "evidence": "src/api/user.ts:87 — the input schema accepts an empty array and the SQL builder receives it",
+ "can_auto_fix": true,
+ "blocks_release": true
+ },
+ {
+ "id": "style-1",
+ "verdict": "false_positive",
+ "reason": "over-scrutiny: equivalent files use the same convention and this diff does not worsen it"
}
- ],
- "workflow_feedback": [ // optional; omit when empty
- { "suggestion": "...", "why": "..." }
]
}
+```
-### Completeness (hard constraint)
-`verifications` must contain exactly one entry per input finding, ids matching one-to-one — no omissions, no inventions, no merging. A missing id means the task is incomplete; the main agent will reject the result and re-run verification for missing ids.
-`````
+Optional top-level `workflow_feedback` entries use
+`{"suggestion":"...","why":"..."}`.
+````
diff --git a/.agents/skills/deep-review/scripts/validate-output.test.ts b/.agents/skills/deep-review/scripts/validate-output.test.ts
new file mode 100644
index 00000000000..623736e1862
--- /dev/null
+++ b/.agents/skills/deep-review/scripts/validate-output.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractJsonPayload, validateOutput } from './validate-output';
+
+const validReviewIssue = {
+ core_problem: 'Because empty input is accepted, the caller reaches invalid SQL.',
+ dimension: 'logic',
+ fix_cost: 'low',
+ fix_options: ['Reject empty input'],
+ id: 'logic-1',
+ issue_type: 'empty input',
+ likelihood: 'high',
+ location: 'src/api/user.ts:87',
+ nature: 'introduced',
+ need_test: true,
+ severity: 'p1',
+ summary: 'Empty input reaches invalid SQL.',
+} as const;
+
+describe('extractJsonPayload', () => {
+ it('extracts a fenced JSON object', () => {
+ expect(extractJsonPayload('```json\n{"issues":[]}\n```')).toBe('{"issues":[]}');
+ });
+
+ it('accepts an unfenced JSON object for direct CLI input', () => {
+ expect(extractJsonPayload(' {"issues":[]} ')).toBe('{"issues":[]}');
+ });
+
+ it('rejects an unclosed fence', () => {
+ expect(() => extractJsonPayload('```json\n{"issues":[]}')).toThrow('JSON fence is not closed');
+ });
+
+ it('extracts one fenced payload from surrounding prose', () => {
+ expect(extractJsonPayload('Result:\n```json\n{"issues":[]}\n```\nDone')).toBe('{"issues":[]}');
+ });
+
+ it('rejects multiple JSON fences', () => {
+ expect(() =>
+ extractJsonPayload('```json\n{"issues":[]}\n```\n```json\n{"issues":[]}\n```'),
+ ).toThrow('Multiple JSON fences found');
+ });
+});
+
+describe('validateOutput', () => {
+ it('accepts a complete review payload', () => {
+ expect(() => validateOutput('review', { issues: [validReviewIssue] })).not.toThrow();
+ });
+
+ it('rejects severity levels outside the review contract', () => {
+ expect(() =>
+ validateOutput('review', {
+ issues: [{ ...validReviewIssue, severity: 'p3' }],
+ }),
+ ).toThrow();
+ });
+
+ it('requires exposed legacy findings to explain their exposure', () => {
+ expect(() =>
+ validateOutput('review', {
+ issues: [{ ...validReviewIssue, nature: 'exposed_legacy' }],
+ }),
+ ).toThrow();
+ });
+
+ it('keeps verification fields specific to their verdict', () => {
+ expect(() =>
+ validateOutput('verify', {
+ verifications: [
+ {
+ id: 'logic-1',
+ reason: 'The input schema already rejects empty arrays.',
+ verdict: 'false_positive',
+ },
+ ],
+ }),
+ ).not.toThrow();
+
+ expect(() =>
+ validateOutput('verify', {
+ verifications: [
+ {
+ evidence: 'This field does not belong to a false-positive verdict.',
+ id: 'logic-1',
+ reason: 'The input schema already rejects empty arrays.',
+ verdict: 'false_positive',
+ },
+ ],
+ }),
+ ).toThrow();
+ });
+
+ it('accepts a severity correction on a confirmed finding', () => {
+ expect(() =>
+ validateOutput('verify', {
+ verifications: [
+ {
+ blocks_release: false,
+ can_auto_fix: true,
+ evidence: 'The failure is recoverable and does not affect the main path.',
+ id: 'logic-1',
+ severity_override: 'p2',
+ verdict: 'confirmed',
+ },
+ ],
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects duplicate consolidation ids', () => {
+ expect(() =>
+ validateOutput('consolidate', {
+ same_root: [
+ { id: 'style-2', same_root_as: 'ai-1' },
+ { id: 'style-2', same_root_as: 'logic-1' },
+ ],
+ }),
+ ).toThrow();
+ });
+});
diff --git a/.agents/skills/deep-review/scripts/validate-output.ts b/.agents/skills/deep-review/scripts/validate-output.ts
new file mode 100644
index 00000000000..dc66a6219fd
--- /dev/null
+++ b/.agents/skills/deep-review/scripts/validate-output.ts
@@ -0,0 +1,220 @@
+import { readFile } from 'node:fs/promises';
+
+import { z } from 'zod';
+
+const WorkflowFeedbackSchema = z
+ .object({
+ suggestion: z.string().min(1),
+ why: z.string().min(1),
+ })
+ .strict();
+
+const ReviewIssueSchema = z
+ .object({
+ core_problem: z.string().min(1),
+ dimension: z.string().min(1),
+ existing_implementations: z.array(z.string().min(1)).min(1).optional(),
+ exposure: z.enum(['triggered', 'bystander']).optional(),
+ fix_cost: z.enum(['low', 'medium', 'high']),
+ fix_options: z.array(z.string().min(1)).min(1),
+ id: z.string().min(1),
+ issue_type: z.string().min(1),
+ likelihood: z.enum(['high', 'medium', 'low']),
+ location: z.string().min(1),
+ nature: z.enum(['introduced', 'exposed_legacy']),
+ need_test: z.boolean(),
+ rule_source: z.string().min(1).optional(),
+ scenario: z.string().min(1).optional(),
+ severity: z.enum(['p0', 'p1', 'p2']),
+ summary: z.string().min(1),
+ })
+ .strict()
+ .superRefine((issue, context) => {
+ if (issue.nature === 'exposed_legacy' && (!issue.exposure || !issue.scenario)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'exposed_legacy findings require exposure and scenario',
+ });
+ }
+
+ if (issue.nature === 'introduced' && issue.exposure) {
+ context.addIssue({
+ code: 'custom',
+ message: 'introduced findings must omit exposure',
+ });
+ }
+
+ if (issue.likelihood === 'low' && !issue.scenario) {
+ context.addIssue({
+ code: 'custom',
+ message: 'low-likelihood findings require scenario',
+ });
+ }
+
+ if (issue.dimension === 'reuse-architecture' && !issue.existing_implementations) {
+ context.addIssue({
+ code: 'custom',
+ message: 'reuse-architecture findings require existing_implementations',
+ });
+ }
+ });
+
+const ReviewOutputSchema = z
+ .object({
+ issues: z.array(ReviewIssueSchema),
+ missing_sources: z.array(z.string().min(1)).optional(),
+ release_checks: z
+ .array(
+ z
+ .object({
+ blocks_deploy: z.boolean(),
+ item: z.string().min(1),
+ why: z.string().min(1),
+ })
+ .strict(),
+ )
+ .optional(),
+ workflow_feedback: z.array(WorkflowFeedbackSchema).optional(),
+ })
+ .strict()
+ .superRefine(({ issues }, context) => {
+ const ids = issues.map(({ id }) => id);
+ if (new Set(ids).size !== ids.length) {
+ context.addIssue({ code: 'custom', message: 'issue ids must be unique' });
+ }
+ });
+
+const ConfirmedVerificationSchema = z
+ .object({
+ auto_fix_reason: z.string().min(1).nullable().optional(),
+ blocks_release: z.boolean(),
+ can_auto_fix: z.boolean(),
+ culprit: z.string().min(1).nullable().optional(),
+ evidence: z.string().min(1),
+ exposure_override: z.enum(['triggered', 'bystander']).nullable().optional(),
+ fix_options_override: z.array(z.string().min(1)).min(1).nullable().optional(),
+ id: z.string().min(1),
+ likelihood_override: z.enum(['high', 'medium', 'low']).nullable().optional(),
+ nature_override: z.enum(['introduced', 'exposed_legacy']).nullable().optional(),
+ note: z.string().min(1).nullable().optional(),
+ severity_override: z.enum(['p0', 'p1', 'p2']).nullable().optional(),
+ verdict: z.literal('confirmed'),
+ })
+ .strict()
+ .superRefine((verification, context) => {
+ if (!verification.can_auto_fix && !verification.auto_fix_reason) {
+ context.addIssue({
+ code: 'custom',
+ message: 'non-auto-fix confirmations require auto_fix_reason',
+ });
+ }
+ });
+
+const VerificationOutputSchema = z
+ .object({
+ verifications: z.array(
+ z.discriminatedUnion('verdict', [
+ ConfirmedVerificationSchema,
+ z
+ .object({
+ id: z.string().min(1),
+ reason: z.string().min(1),
+ verdict: z.literal('false_positive'),
+ })
+ .strict(),
+ z
+ .object({
+ id: z.string().min(1),
+ missing: z.string().min(1),
+ verdict: z.literal('need_more_context'),
+ })
+ .strict(),
+ ]),
+ ),
+ workflow_feedback: z.array(WorkflowFeedbackSchema).optional(),
+ })
+ .strict()
+ .superRefine(({ verifications }, context) => {
+ const ids = verifications.map(({ id }) => id);
+ if (new Set(ids).size !== ids.length) {
+ context.addIssue({ code: 'custom', message: 'verification ids must be unique' });
+ }
+ });
+
+const ConsolidationOutputSchema = z
+ .object({
+ same_root: z.array(
+ z
+ .object({
+ id: z.string().min(1),
+ same_root_as: z.string().min(1),
+ })
+ .strict(),
+ ),
+ })
+ .strict()
+ .superRefine(({ same_root }, context) => {
+ const ids = same_root.map(({ id }) => id);
+ if (new Set(ids).size !== ids.length) {
+ context.addIssue({ code: 'custom', message: 'consolidation ids must be unique' });
+ }
+ });
+
+const schemas = {
+ consolidate: ConsolidationOutputSchema,
+ review: ReviewOutputSchema,
+ verify: VerificationOutputSchema,
+} as const;
+
+export type OutputKind = keyof typeof schemas;
+
+export const extractJsonPayload = (raw: string) => {
+ const trimmed = raw.trim();
+ const normalized = trimmed.toLowerCase();
+ const fenceStart = normalized.indexOf('```json');
+ if (fenceStart === -1) return trimmed;
+ if (normalized.includes('```json', fenceStart + '```json'.length)) {
+ throw new Error('Multiple JSON fences found');
+ }
+
+ const payloadStart = fenceStart + '```json'.length;
+ const fenceEnd = trimmed.indexOf('```', payloadStart);
+ if (fenceEnd === -1) throw new Error('JSON fence is not closed');
+
+ return trimmed.slice(payloadStart, fenceEnd).trim();
+};
+
+export const validateOutput = (kind: OutputKind, value: unknown) => schemas[kind].parse(value);
+
+const readStdin = async () => {
+ process.stdin.setEncoding('utf8');
+
+ let input = '';
+ for await (const chunk of process.stdin as AsyncIterable<string>) input += chunk;
+ return input;
+};
+
+const run = async () => {
+ const kind = process.argv[2] as OutputKind | undefined;
+ const inputPath = process.argv[3];
+
+ if (!kind || !(kind in schemas)) {
+ throw new Error('Usage: validate-output.ts <review|verify|consolidate> [input-file]');
+ }
+
+ const raw = inputPath ? await readFile(inputPath, 'utf8') : await readStdin();
+ const value = JSON.parse(extractJsonPayload(raw));
+ validateOutput(kind, value);
+ console.log(`Valid ${kind} output`);
+};
+
+if (import.meta.main) {
+ await run().catch((error) => {
+ if (error instanceof z.ZodError) {
+ console.error(JSON.stringify(error.issues, null, 2));
+ } else {
+ console.error(error instanceof Error ? error.message : String(error));
+ }
+ process.exitCode = 1;
+ });
+}
diff --git a/.agents/skills/deep-review/scripts/vitest.config.ts b/.agents/skills/deep-review/scripts/vitest.config.ts
new file mode 100644
index 00000000000..a5ca1a7c6f6
--- /dev/null
+++ b/.agents/skills/deep-review/scripts/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ include: ['validate-output.test.ts'],
+ },
+});
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
index 24d2840eaa4..859c79524eb 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
@@ -1,4 +1,4 @@
-import { ModelEmptyError } from '@lobechat/model-runtime';
+import { ModelEmptyError, ModelRefusalError } from '@lobechat/model-runtime';
import { describe, expect, it } from 'vitest';
import { classifyLLMError } from '../llmErrorClassification';
@@ -73,6 +73,7 @@ describe('classifyLLMError', () => {
['LocationNotSupportError', 'service unavailable in this region'],
['ExceededToolLimit', 'tools array exceeds limit'],
['ModelEmptyCompletion', 'model returned an empty completion'],
+ ['ModelRefusal', 'model declined to answer'],
])('classifies %s as stop (no HTTP status)', (errorType, message) => {
expect(classifyLLMError({ errorType, message }).kind).toBe('stop');
});
@@ -90,6 +91,10 @@ describe('classifyLLMError', () => {
it('classifies a thrown ModelEmptyError instance as stop', () => {
expect(classifyLLMError(new ModelEmptyError()).kind).toBe('stop');
});
+
+ it('classifies a thrown ModelRefusalError instance as stop', () => {
+ expect(classifyLLMError(new ModelRefusalError()).kind).toBe('stop');
+ });
});
describe('legacy retry overrides', () => {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
index 03860ae3f27..c5e12059f95 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
@@ -7,15 +7,28 @@ import type { RuntimeExecutorContext } from '../context';
import { createServerCallLlmAttempt } from './serverCallLlmAttempt';
import type { ServerCallLlmTooling } from './serverCallLlmTooling';
+const recordModelCompletionFailureMock = vi.hoisted(() => vi.fn());
+
vi.mock('@lobechat/model-runtime', async () => {
const { isEmptyModelCompletion, ModelEmptyError } =
await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');
+ const { ModelRefusalError } =
+ await import('../../../../../../packages/model-runtime/src/errors/modelRefusal');
const { consumeStreamUntilDone } =
await import('../../../../../../packages/model-runtime/src/utils/consumeStream');
- return { consumeStreamUntilDone, isEmptyModelCompletion, ModelEmptyError };
+ return {
+ consumeStreamUntilDone,
+ isEmptyModelCompletion,
+ ModelEmptyError,
+ ModelRefusalError,
+ };
});
+vi.mock('@/business/server/recordModelCompletionFailure', () => ({
+ recordModelCompletionFailure: recordModelCompletionFailureMock,
+}));
+
vi.mock('@/envs/file', () => ({
fileEnv: { NEXT_PUBLIC_S3_FILE_PATH: 'files' },
}));
@@ -319,4 +332,132 @@ describe('ServerCallLlmAttempt', () => {
}),
);
});
+
+ it('classifies an empty refusal separately and records complete normalized evidence', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onContentPart?.({
+ content: '',
+ partType: 'text',
+ thoughtSignature: 'content-thought-signature',
+ });
+ await callback?.onReasoningPart?.({
+ content: '',
+ partType: 'text',
+ thoughtSignature: 'reasoning-thought-signature',
+ });
+ await callback?.onCompletion?.({
+ finishReason: 'refusal',
+ reasoning: { content: '', signature: 'reasoning-signature' },
+ text: '',
+ usage: { totalInputTokens: 10, totalOutputTokens: 0, totalTokens: 10 },
+ });
+ });
+
+ await expect(attempt.execute()).rejects.toMatchObject({
+ errorType: 'ModelRefusal',
+ message: 'The model declined to answer this request.',
+ });
+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ attempt: 1,
+ maxAttempts: 3,
+ model: 'test-model',
+ operationId: 'operation-1',
+ operationLogId: 'operation-1:2',
+ provider: 'test-provider',
+ reason: 'refusal',
+ request: expect.objectContaining({
+ messages: [{ content: 'Question', role: 'user' }],
+ }),
+ response: {
+ base64ImageEvents: [],
+ completion: expect.objectContaining({
+ finishReason: 'refusal',
+ reasoning: { content: '', signature: 'reasoning-signature' },
+ }),
+ contentPartEvents: [
+ {
+ content: '',
+ partType: 'text',
+ thoughtSignature: 'content-thought-signature',
+ },
+ ],
+ output: expect.objectContaining({
+ finishReason: 'refusal',
+ reasoning: { content: '', signature: 'reasoning-signature' },
+ }),
+ reasoningPartEvents: [
+ {
+ content: '',
+ partType: 'text',
+ thoughtSignature: 'reasoning-thought-signature',
+ },
+ ],
+ },
+ stepIndex: 2,
+ topicId: 'topic-1',
+ trigger: 'user',
+ userId: 'user-1',
+ }),
+ );
+ });
+
+ it('keeps a refusal with visible provider text as a normal completion', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onText?.('I cannot help with that request.');
+ await callback?.onCompletion?.({
+ finishReason: 'refusal',
+ text: 'I cannot help with that request.',
+ usage: { totalOutputTokens: 8 },
+ });
+ });
+
+ await expect(attempt.execute()).resolves.toBeUndefined();
+ expect(attempt.snapshot().content).toBe('I cannot help with that request.');
+ expect(recordModelCompletionFailureMock).not.toHaveBeenCalled();
+ });
+
+ it('classifies a refusal with only hidden reasoning as ModelRefusal', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onThinking?.('Internal refusal analysis');
+ await callback?.onCompletion?.({
+ finishReason: 'refusal',
+ reasoning: { content: 'Internal refusal analysis', signature: 'reasoning-signature' },
+ text: '',
+ usage: { totalOutputTokens: 12 },
+ });
+ });
+
+ await expect(attempt.execute()).rejects.toMatchObject({
+ diagnostics: expect.objectContaining({ reasoningLength: 25 }),
+ errorType: 'ModelRefusal',
+ });
+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(
+ expect.objectContaining({ reason: 'refusal' }),
+ );
+ });
+
+ it('records an unexplained blank completion before throwing ModelEmptyError', async () => {
+ const { attempt } = createAttempt(async ({ callback }) => {
+ await callback?.onCompletion?.({
+ finishReason: 'stop',
+ text: '',
+ usage: { totalInputTokens: 5, totalOutputTokens: 0, totalTokens: 5 },
+ });
+ });
+
+ await expect(attempt.execute()).rejects.toMatchObject({
+ errorType: 'ModelEmptyCompletion',
+ message: 'The model provider returned an empty completion.',
+ });
+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ reason: 'empty_completion',
+ response: expect.objectContaining({
+ completion: expect.objectContaining({ finishReason: 'stop' }),
+ output: expect.objectContaining({ finishReason: 'stop' }),
+ }),
+ }),
+ );
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index 688a1da088a..64ca198a914 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -1,10 +1,17 @@
import type { AgentEvent, BlobStore, LLMAttemptOutput } from '@lobechat/agent-runtime';
import { ToolNameResolver } from '@lobechat/context-engine';
-import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
+import type {
+ Base64ImageData,
+ ChatStreamPayload,
+ ContentPartData,
+ ModelRuntime,
+ OnFinishData,
+} from '@lobechat/model-runtime';
import {
consumeStreamUntilDone,
isEmptyModelCompletion,
ModelEmptyError,
+ ModelRefusalError,
} from '@lobechat/model-runtime';
import type {
ChatImageItem,
@@ -17,6 +24,9 @@ import type {
} from '@lobechat/types';
import { pickString, toRecord } from '@lobechat/utils/object';
+import type { ModelCompletionFailureReason } from '@/business/server/recordModelCompletionFailure';
+import { recordModelCompletionFailure } from '@/business/server/recordModelCompletionFailure';
+
import type { RuntimeExecutorContext } from '../context';
import { isOperationInterrupted, log, timing } from '../executorHelpers';
import {
@@ -65,8 +75,11 @@ const createStreamExecutionError = (errorData: unknown) => {
export class ServerCallLlmAttempt {
private answerSalvagedFromReasoning = false;
private readonly attempt: number;
+ private readonly base64ImageEvents: Base64ImageData[] = [];
private readonly chatPayload: ChatStreamPayload;
private readonly clientIp?: string;
+ private completion?: OnFinishData;
+ private readonly contentPartEvents: ContentPartData[] = [];
private readonly ctx: RuntimeExecutorContext;
private finishReason?: string;
private grounding: GroundingSearch | null = null;
@@ -79,6 +92,7 @@ export class ServerCallLlmAttempt {
private readonly operationLogId: string;
private readonly provider: string;
private reasoning?: ModelReasoning;
+ private readonly reasoningPartEvents: ContentPartData[] = [];
private readonly resolved: ServerCallLlmTooling['resolved'];
private speed?: ModelPerformance;
private readonly streamSink: ServerCallLlmStreamSink;
@@ -147,9 +161,11 @@ export class ServerCallLlmAttempt {
callback: {
onBase64Image: async ({ image }) => {
this.onFirstChunk();
+ this.base64ImageEvents.push({ ...image });
await this.streamSink.appendBase64Image(image);
},
onCompletion: async (data) => {
+ this.completion = data;
if (data.usage) this.usage = data.usage;
if (data.speed) this.speed = data.speed;
if (data.finishReason) this.finishReason = data.finishReason;
@@ -157,6 +173,7 @@ export class ServerCallLlmAttempt {
},
onContentPart: async (part) => {
this.onFirstChunk();
+ this.contentPartEvents.push({ ...part });
await this.streamSink.appendContentPart(part);
},
onError: async (errorData) => {
@@ -178,6 +195,7 @@ export class ServerCallLlmAttempt {
},
onReasoningPart: async (part) => {
this.onFirstChunk();
+ this.reasoningPartEvents.push({ ...part });
await this.streamSink.appendReasoningPart(part);
},
onText: async (text) => {
@@ -279,38 +297,57 @@ export class ServerCallLlmAttempt {
private async assertNonEmptyCompletion() {
const imageCount = this.getOutputImageCount();
+ const isRefusal = this.finishReason?.toLowerCase() === 'refusal';
+ /**
+ * A refusal needs ordinary response output to count as a successful
+ * completion. Provider-internal reasoning alone must not turn a blank
+ * refusal into a successful assistant message.
+ */
+ const visibleReasoning = isRefusal ? '' : this.streamSink.thinkingContent;
+ const isEmpty = isEmptyModelCompletion({
+ content: this.streamSink.content,
+ hasGrounding: !!this.grounding,
+ imageCount,
+ outputTokens: this.usage?.totalOutputTokens,
+ reasoning: visibleReasoning,
+ toolCallCount: this.toolsCalling.length + this.toolCalls.length,
+ });
- if (
- isEmptyModelCompletion({
- content: this.streamSink.content,
- hasGrounding: !!this.grounding,
- imageCount,
- outputTokens: this.usage?.totalOutputTokens,
- reasoning: this.streamSink.thinkingContent,
- toolCallCount: this.toolsCalling.length + this.toolCalls.length,
- }) &&
- !(await isOperationInterrupted(this.ctx))
- ) {
+ if (!isEmpty || (await isOperationInterrupted(this.ctx))) return;
+
+ const diagnostics = {
+ attempt: this.attempt,
+ contentLength: this.streamSink.content.length,
+ cost: this.usage?.cost,
+ finishReason: this.finishReason,
+ imageCount,
+ maxAttempts: this.maxAttempts,
+ model: this.model,
+ outputTokens: this.usage?.totalOutputTokens,
+ provider: this.provider,
+ reasoningLength: this.streamSink.thinkingContent.length,
+ toolCallCount: this.toolsCalling.length + this.toolCalls.length,
+ };
+
+ await this.recordCompletionFailure(isRefusal ? 'refusal' : 'empty_completion');
+
+ if (isRefusal) {
log(
- '[%s] Model returned an empty completion (attempt %d/%d) — throwing terminal ModelEmptyError',
+ '[%s] Model explicitly refused an empty completion (attempt %d/%d) — throwing terminal ModelRefusalError',
this.operationLogId,
this.attempt,
this.maxAttempts,
);
- throw new ModelEmptyError(undefined, {
- attempt: this.attempt,
- contentLength: this.streamSink.content.length,
- cost: this.usage?.cost,
- finishReason: this.finishReason,
- imageCount,
- maxAttempts: this.maxAttempts,
- model: this.model,
- outputTokens: this.usage?.totalOutputTokens,
- provider: this.provider,
- reasoningLength: this.streamSink.thinkingContent.length,
- toolCallCount: this.toolsCalling.length + this.toolCalls.length,
- });
+ throw new ModelRefusalError(undefined, diagnostics);
}
+
+ log(
+ '[%s] Model returned an empty completion (attempt %d/%d) — throwing terminal ModelEmptyError',
+ this.operationLogId,
+ this.attempt,
+ this.maxAttempts,
+ );
+ throw new ModelEmptyError(undefined, diagnostics);
}
/**
@@ -326,6 +363,39 @@ export class ServerCallLlmAttempt {
return this.imageList.length + contentPartImageCount;
}
+ private async recordCompletionFailure(reason: ModelCompletionFailureReason) {
+ try {
+ await recordModelCompletionFailure({
+ attempt: this.attempt,
+ maxAttempts: this.maxAttempts,
+ model: this.model,
+ operationId: this.ctx.operationId,
+ operationLogId: this.operationLogId,
+ provider: this.provider,
+ reason,
+ request: this.chatPayload,
+ response: {
+ base64ImageEvents: [...this.base64ImageEvents],
+ completion: this.completion,
+ contentPartEvents: [...this.contentPartEvents],
+ output: this.snapshot(),
+ reasoningPartEvents: [...this.reasoningPartEvents],
+ },
+ stepIndex: this.ctx.stepIndex,
+ topicId: this.topicId,
+ trigger: this.trigger,
+ userId: this.ctx.userId,
+ workspaceId: this.ctx.workspaceId,
+ });
+ } catch (error) {
+ console.error('[ModelCompletionFailure] Failed to record completion evidence.', {
+ error: error instanceof Error ? error.message : String(error),
+ operationId: this.ctx.operationId,
+ stepIndex: this.ctx.stepIndex,
+ });
+ }
+ }
+
private logResult() {
log(
'[%s] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s',
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
index 5d8bb3b25b0..3bc59199f00 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
@@ -1,4 +1,4 @@
-import { ModelEmptyError } from '@lobechat/model-runtime';
+import { ModelEmptyError, ModelRefusalError } from '@lobechat/model-runtime';
import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
@@ -112,6 +112,35 @@ describe('formatErrorForState', () => {
});
});
+ it('enriches a thrown ModelRefusalError without counting it as an operational failure', () => {
+ const result = formatErrorForState(
+ new ModelRefusalError(undefined, {
+ attempt: 1,
+ finishReason: 'refusal',
+ model: 'fable',
+ provider: 'lobehub',
+ }),
+ );
+
+ expect(result).toMatchObject({
+ attribution: 'provider',
+ body: {
+ diagnostics: {
+ attempt: 1,
+ finishReason: 'refusal',
+ model: 'fable',
+ provider: 'lobehub',
+ },
+ },
+ category: 'provider',
+ countAsFailure: false,
+ httpStatus: 471,
+ numericId: 8015,
+ retryable: false,
+ type: AgentRuntimeErrorType.ModelRefusal,
+ });
+ });
+
it('marks provider-side rate limits as retryable with provider attribution', () => {
const result = formatErrorForState({
errorType: AgentRuntimeErrorType.RateLimitExceeded,
diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
index 82c8be4ac12..eef390ebda3 100644
--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts
@@ -532,6 +532,38 @@ describe('replyTemplate', () => {
);
});
+ it('renders model refusals without blaming provider availability', () => {
+ const en = renderAgentError('ModelRefusal', undefined, 'op-1', 'en-US', 'provider');
+ expect(en).toContain('declined to answer');
+ expect(en).not.toContain('temporarily unavailable');
+
+ const zh = renderAgentError('ModelRefusal', undefined, 'op-1', 'zh-CN', 'provider');
+ expect(zh).toContain('模型拒绝回答');
+ expect(zh).not.toContain('暂时不可用');
+ });
+
+ it('renders provider content-policy violations as content moderation blocks', () => {
+ const en = renderAgentError(
+ 'ProviderContentPolicyViolation',
+ undefined,
+ 'op-1',
+ 'en-US',
+ 'provider',
+ );
+ expect(en).toContain('content-safety filter');
+ expect(en).not.toContain('temporarily unavailable');
+
+ const zh = renderAgentError(
+ 'ProviderContentPolicyViolation',
+ undefined,
+ 'op-1',
+ 'zh-CN',
+ 'provider',
+ );
+ expect(zh).toContain('内容安全策略拦截');
+ expect(zh).not.toContain('暂时不可用');
+ });
+
it('gives OperationInactivityTimeout retry-oriented copy', () => {
expect(renderAgentError('OperationInactivityTimeout', undefined, 'op-1')).toContain(
'timed out',
diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.ts
index e9b9c7cf98a..775b60217a4 100644
--- a/apps/server/src/services/bot/replyTemplate.ts
+++ b/apps/server/src/services/bot/replyTemplate.ts
@@ -239,6 +239,7 @@ type SystemStrings = {
errorCommandConnectionClosed: string;
errorContentModeration: string;
errorEmptyCompletion: string;
+ errorModelRefusal: string;
errorHarnessInternal: string;
errorInsufficientCredits: string;
errorLocationNotSupported: string;
@@ -307,6 +308,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {
"**Blocked by the content-safety filter.**\nThe model provider's safety filter rejected the request or response. Please rephrase and try again.",
errorEmptyCompletion:
"**The model provider returned an empty response.**\nEven without visible content, this request may still incur charges. You can retry, or switch models in the agent's settings and try again.",
+ errorModelRefusal:
+ '**The model declined to answer this request.**\nTry rephrasing it, or switch models in the agent settings and try again.',
errorHarnessInternal:
'**Something went wrong on our side.**\nThe agent run hit an internal error, which has been logged. Please try again — if it keeps happening, share the Operation ID below with support.',
errorInsufficientCredits:
@@ -384,6 +387,8 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {
'**被内容安全策略拦截**\n模型 Provider 的安全策略拒绝了本次请求或回复。请调整内容后重试。',
errorEmptyCompletion:
'**模型供应商返回了空内容**\n即使没有可显示的内容,本次请求仍可能产生费用。你可以重试,或在 Agent 设置中切换模型后再试。',
+ errorModelRefusal:
+ '**模型拒绝回答该请求**\n请尝试调整表述,或在 Agent 设置中切换其他模型后重试。',
errorHarnessInternal:
'**我们这边出了点问题**\nAgent 执行遇到内部错误,已记录。请重试;如果持续出现,请把下方 Operation ID 提供给支持人员。',
errorInsufficientCredits:
@@ -464,7 +469,9 @@ const FRIENDLY_ERROR_BY_TYPE: Record<string, keyof SystemStrings> = {
QuotaLimitReached: 'errorQuotaLimitReached',
// ── transient provider / capacity (attribution: provider) ──
ModelEmptyCompletion: 'errorEmptyCompletion',
+ ModelRefusal: 'errorModelRefusal',
NoAvailableChannel: 'errorProviderUnavailable',
+ ProviderContentPolicyViolation: 'errorContentModeration',
ProviderServiceUnavailable: 'errorProviderUnavailable',
RateLimitExceeded: 'errorRateLimited',
// ── network / infra (attribution: system) ──
diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.json
index fd7d3b8cc77..e89aa4ef050 100644
--- a/locales/en-US/modelRuntime.json
+++ b/locales/en-US/modelRuntime.json
@@ -25,12 +25,14 @@
"ModelEmptyCompletion": "The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.",
"ModelEmptyCompletionWithCost": "The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.",
"ModelNotFound": "Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.",
+ "ModelRefusal": "The model declined to answer this request. Try rephrasing it or choose another model.",
"NoAvailableChannel": "Sorry, the proxy or router has no available channel for the requested model. Please switch the channel/key configuration or try again later.",
"OllamaBizError": "Error requesting Ollama service, please troubleshoot or retry based on the following information",
"OllamaServiceUnavailable": "Ollama service is unavailable. Please check if Ollama is running properly or if the cross-origin configuration of Ollama is set correctly.",
"OperationInactivityTimeout": "The agent operation was idle for too long and was terminated. Please retry the request.",
"PermissionDenied": "Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.",
"ProviderBizError": "Error requesting {{provider}} service, please troubleshoot or retry based on the following information",
+ "ProviderContentPolicyViolation": "The provider blocked this request or its output due to content policy. Please revise your prompt and try again.",
"ProviderNetworkError": "Connection to the provider timed out or was dropped. Please check your network and try again.",
"ProviderServiceUnavailable": "The provider is temporarily overloaded or unavailable. Please try again shortly.",
"QuotaLimitReached": "Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.",
diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.json
index df63b36da3b..382285d4da3 100644
--- a/locales/zh-CN/modelRuntime.json
+++ b/locales/zh-CN/modelRuntime.json
@@ -25,12 +25,14 @@
"ModelEmptyCompletion": "模型供应商返回了空内容。即使没有可显示的内容,本次请求仍可能产生费用。你可以重试,或切换模型后再试。",
"ModelEmptyCompletionWithCost": "模型供应商返回空内容,本次费用为 {{credits}} 积分。重试可能产生相近费用,也可切换模型。",
"ModelNotFound": "抱歉,未找到请求的模型。可能是模型不存在或您没有必要的访问权限。请在更改API密钥或调整访问权限后重试。",
+ "ModelRefusal": "模型明确拒绝回答此请求。请尝试改写请求,或切换其他模型。",
"NoAvailableChannel": "抱歉,代理或路由器没有可用的通道来请求此模型。请切换通道/密钥配置或稍后重试。",
"OllamaBizError": "请求Ollama服务时发生错误,请根据以下信息进行排查或重试。",
"OllamaServiceUnavailable": "Ollama服务不可用。请检查Ollama是否正常运行或Ollama的跨域配置是否正确设置。",
"OperationInactivityTimeout": "代理操作闲置时间过长,已被终止。请重试请求。",
"PermissionDenied": "抱歉,您没有权限访问此服务。请检查您的密钥是否具有必要的访问权限。",
"ProviderBizError": "请求{{provider}}服务时发生错误,请根据以下信息进行排查或重试。",
+ "ProviderContentPolicyViolation": "供应商因内容政策拦截了此请求或其输出。请修改提示词后重试。",
"ProviderNetworkError": "与提供商的连接超时或被中断。请检查您的网络并重试。",
"ProviderServiceUnavailable": "提供商暂时过载或不可用。请稍后重试。",
"QuotaLimitReached": "抱歉,此密钥的令牌使用量或请求次数已达到配额限制。请增加密钥配额或稍后重试。",
diff --git a/packages/business-server/src/recordModelCompletionFailure.ts b/packages/business-server/src/recordModelCompletionFailure.ts
new file mode 100644
index 00000000000..c271ccdad3b
--- /dev/null
+++ b/packages/business-server/src/recordModelCompletionFailure.ts
@@ -0,0 +1,27 @@
+export type ModelCompletionFailureReason = 'empty_completion' | 'refusal';
+
+export interface RecordModelCompletionFailureParams {
+ attempt: number;
+ maxAttempts: number;
+ model: string;
+ operationId: string;
+ operationLogId: string;
+ provider: string;
+ reason: ModelCompletionFailureReason;
+ /**
+ * The model payload only. Provider credentials and transport headers are
+ * deliberately not accepted by this hook.
+ */
+ request: unknown;
+ /** Full normalized completion output and callback evidence. */
+ response: unknown;
+ stepIndex: number;
+ topicId?: string;
+ trigger?: unknown;
+ userId?: string;
+ workspaceId?: string;
+}
+
+export const recordModelCompletionFailure = async (
+ _params: RecordModelCompletionFailureParams,
+): Promise<void> => {};
diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.ts
index 6771d9ab000..e6503f53fd0 100644
--- a/packages/locales/src/default/modelRuntime.ts
+++ b/packages/locales/src/default/modelRuntime.ts
@@ -47,6 +47,8 @@ export default {
'The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.',
ModelEmptyCompletionWithCost:
'The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.',
+ ModelRefusal:
+ 'The model declined to answer this request. Try rephrasing it or choose another model.',
ModelNotFound:
'Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.',
NoAvailableChannel:
@@ -61,6 +63,8 @@ export default {
'Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.',
ProviderBizError:
'Error requesting {{provider}} service, please troubleshoot or retry based on the following information',
+ ProviderContentPolicyViolation:
+ 'The provider blocked this request or its output due to content policy. Please revise your prompt and try again.',
ProviderNetworkError:
'Connection to the provider timed out or was dropped. Please check your network and try again.',
ProviderServiceUnavailable:
diff --git a/packages/model-runtime/src/core/streams/google/const.ts b/packages/model-runtime/src/core/streams/google/const.ts
index 69edaac3350..82d4cee1dc6 100644
--- a/packages/model-runtime/src/core/streams/google/const.ts
+++ b/packages/model-runtime/src/core/streams/google/const.ts
@@ -2,6 +2,8 @@ export const GOOGLE_AI_BLOCK_REASON = {
BLOCKLIST: 'The content includes blocked terms. Please rephrase and try again.',
IMAGE_SAFETY:
'The generated image was blocked for safety reasons. Please try modifying your request.',
+ IMAGE_PROHIBITED_CONTENT:
+ 'The generated image was blocked due to prohibited content. Please modify your request and try again.',
LANGUAGE: "The requested language isn't supported. Please try again in a supported language.",
OTHER: 'The content was blocked for an unknown reason. Please rephrase and try again.',
PROHIBITED_CONTENT: 'The content may contain prohibited content. Please adjust it and try again.',
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index ccb32c74c13..313245d214d 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -1744,6 +1744,42 @@ describe('GoogleGenerativeAIStream', () => {
]);
});
+ it('should classify IMAGE_PROHIBITED_CONTENT as a content policy violation', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ candidates: [
+ {
+ content: {},
+ finishReason: 'IMAGE_PROHIBITED_CONTENT',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ candidatesTokenCount: 0,
+ promptTokenCount: 10,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ totalTokenCount: 10,
+ },
+ });
+ controller.close();
+ },
+ });
+
+ const chunks = await decodeStreamChunks(GoogleGenerativeAIStream(mockGoogleStream));
+
+ expect(chunks).toEqual([
+ 'id: chat_1\n',
+ 'event: usage\n',
+ `data: {"inputTextTokens":10,"outputImageTokens":0,"outputTextTokens":0,"totalInputTokens":10,"totalOutputTokens":0,"totalTokens":10}\n\n`,
+ 'id: chat_1\n',
+ 'event: error\n',
+ `data: {"body":{"context":{"finishReason":"IMAGE_PROHIBITED_CONTENT"},"message":"The generated image was blocked due to prohibited content. Please modify your request and try again.","provider":"google"},"type":"ProviderContentPolicyViolation"}\n\n`,
+ ]);
+ });
+
it('should pass through injected lobe error marker', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index a53c1e73a6f..8a2f3f37363 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -2,6 +2,7 @@ import type { GenerateContentResponse, Part } from '@google/genai';
import type { GroundingSearch } from '@lobechat/types';
import type { ChatStreamCallbacks } from '../../../types';
+import { AgentRuntimeErrorType } from '../../../types/error';
import { serializeScopedSignature } from '../../../utils/signatureScope';
import { nanoid } from '../../../utils/uuid';
import { convertGoogleAIUsage } from '../../usageConverters/google-ai';
@@ -59,6 +60,10 @@ const transformGoogleGenerativeAIStream = (
// Handle promptFeedback with blockReason (e.g., PROHIBITED_CONTENT)
if ('promptFeedback' in chunk && (chunk as any).promptFeedback?.blockReason) {
const blockReason = (chunk as any).promptFeedback.blockReason;
+ const errorType =
+ blockReason === 'IMAGE_PROHIBITED_CONTENT'
+ ? AgentRuntimeErrorType.ProviderContentPolicyViolation
+ : AgentRuntimeErrorType.ProviderBizError;
const humanFriendlyMessage = getBlockReasonMessage(blockReason);
return {
@@ -70,7 +75,7 @@ const transformGoogleGenerativeAIStream = (
message: humanFriendlyMessage,
provider: 'google',
},
- type: 'ProviderBizError',
+ type: errorType,
},
id: context?.id || 'error',
type: 'error',
@@ -89,6 +94,10 @@ const transformGoogleGenerativeAIStream = (
const convertedUsage = usageMetadata
? convertGoogleAIUsage(usageMetadata, payload?.pricing)
: undefined;
+ const errorType =
+ blockedReason === 'IMAGE_PROHIBITED_CONTENT'
+ ? AgentRuntimeErrorType.ProviderContentPolicyViolation
+ : AgentRuntimeErrorType.ProviderBizError;
const humanFriendlyMessage = getBlockReasonMessage(blockedReason);
return [
@@ -105,7 +114,7 @@ const transformGoogleGenerativeAIStream = (
message: humanFriendlyMessage,
provider: 'google',
},
- type: 'ProviderBizError',
+ type: errorType,
},
id: context?.id || 'error',
type: 'error' as const,
diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.ts
index 2e66b9ce3ff..93dea0813c5 100644
--- a/packages/model-runtime/src/errors/index.ts
+++ b/packages/model-runtime/src/errors/index.ts
@@ -1,6 +1,7 @@
export { ErrorClassifier, type ErrorClassifierType } from './classifier';
export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';
export { isEmptyModelCompletion, ModelEmptyError } from './modelEmptyCompletion';
+export { ModelRefusalError } from './modelRefusal';
export { ERROR_PATTERNS, type ErrorPattern } from './patterns';
export { refineErrorCode, type RefineErrorInput } from './refine';
export {
diff --git a/packages/model-runtime/src/errors/modelRefusal.test.ts b/packages/model-runtime/src/errors/modelRefusal.test.ts
new file mode 100644
index 00000000000..61c33b0622a
--- /dev/null
+++ b/packages/model-runtime/src/errors/modelRefusal.test.ts
@@ -0,0 +1,22 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { ModelRefusalError } from './modelRefusal';
+
+describe('ModelRefusalError', () => {
+ it('exposes the formal refusal type and diagnostics', () => {
+ const diagnostics = {
+ finishReason: 'refusal',
+ model: 'fable',
+ provider: 'lobehub',
+ };
+ const error = new ModelRefusalError(undefined, diagnostics);
+
+ expect(error).toMatchObject({
+ diagnostics,
+ errorType: AgentRuntimeErrorType.ModelRefusal,
+ message: 'The model declined to answer this request.',
+ name: 'ModelRefusalError',
+ });
+ });
+});
diff --git a/packages/model-runtime/src/errors/modelRefusal.ts b/packages/model-runtime/src/errors/modelRefusal.ts
new file mode 100644
index 00000000000..68ac4092e3d
--- /dev/null
+++ b/packages/model-runtime/src/errors/modelRefusal.ts
@@ -0,0 +1,24 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+import type { ModelEmptyCompletionDiagnostics } from './modelEmptyCompletion';
+
+export type ModelRefusalDiagnostics = ModelEmptyCompletionDiagnostics;
+
+/**
+ * Thrown when the provider explicitly refuses an otherwise empty completion.
+ * Refusals with user-visible text remain normal completions so the provider's
+ * explanation is not discarded.
+ */
+export class ModelRefusalError extends Error {
+ readonly errorType = AgentRuntimeErrorType.ModelRefusal;
+ readonly diagnostics?: ModelRefusalDiagnostics;
+
+ constructor(
+ message = 'The model declined to answer this request.',
+ diagnostics?: ModelRefusalDiagnostics,
+ ) {
+ super(message);
+ this.name = 'ModelRefusalError';
+ this.diagnostics = diagnostics;
+ }
+}
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index 1f59c9dc1fc..8c10e8d6799 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -542,7 +542,7 @@ export const ERROR_CODE_SPECS: SpecMap = {
httpStatus: 471,
retryable: false,
countAsFailure: false,
- description: 'Image-generation provider blocked the request due to content policy.',
+ description: 'Provider blocked the request or generated output due to content policy.',
},
[AgentRuntimeErrorType.UpstreamGatewayError]: {
code: AgentRuntimeErrorType.UpstreamGatewayError,
@@ -599,6 +599,17 @@ export const ERROR_CODE_SPECS: SpecMap = {
description:
'Provider returned a completion with no user-visible content, tool calls, images, or grounding.',
},
+ [AgentRuntimeErrorType.ModelRefusal]: {
+ code: AgentRuntimeErrorType.ModelRefusal,
+ numericId: 8015,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 471,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Provider explicitly refused to produce an otherwise empty completion.',
+ },
// ─── 9xxx Config ──────────────────────────────────────────────────────
[AgentRuntimeErrorType.InvalidOllamaArgs]: {
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index 3e3875de015..7dac521dc6c 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -27,6 +27,7 @@ export {
type MatchInput,
type MatchResult,
ModelEmptyError,
+ ModelRefusalError,
parseErrorRef,
refineErrorCode,
type RefineErrorInput,
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index ea9bddb7b69..314b43e436b 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -127,6 +127,13 @@ export const AgentRuntimeErrorType = {
* tokens, no text, and no tool calls.
*/
ModelEmptyCompletion: 'ModelEmptyCompletion',
+ /**
+ * The model explicitly refused an otherwise empty completion. This stays
+ * separate from ModelEmptyCompletion so users receive an actionable refusal
+ * message and operations can distinguish intentional provider behavior from
+ * unexplained blank responses.
+ */
+ ModelRefusal: 'ModelRefusal',
/**
* A persistence-layer query / transaction failed (Drizzle "Failed query:
* …"). Harness-side: the DB write/read or txn could not complete and