Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

docs: streamline agent guidance and reviews

Josh Corbett0298c02b4cbb
diff --git a/.github/AGENTS.md b/.github/AGENTS.md
index 62d272874c..976b2b0c1a 100644
--- a/.github/AGENTS.md
+++ b/.github/AGENTS.md
@@ -1,11 +1,11 @@
# CI and contributions
-- Shared engineering and package rules live in the root `AGENTS.md`. Read the affected package's guidance before changing checks.
-- Preserve supported events: pull requests, main pushes, merge groups, manual dispatch, and reusable workflow calls. Never assume `github.base_ref` is populated outside a PR event.
-- Include the workflow itself and relevant shared actions/configuration in change detection. Test-only and tooling-only changes must reach their owning checks; skipped work must not hide required validation.
-- Use existing Node/Python/pnpm/uv versions and lockfiles. Keep dependency installs reproducible and respect hardware/platform matrices. Preserve pinned action revisions where used.
-- Prefer package completion commands over reproducing their internals in YAML. Webv2's `pnpm check:release` includes architecture, tests, performance/build, project files, and accessibility; install Chromium and required Linux dependencies first.
-- Preserve diagnostic artifacts on failure with `always()` where appropriate. Keep generated review/performance artifacts out of Git. Distinguish real checks from skipped or unavailable checks.
-- Keep hooks aligned with CI's Ruff version/configuration. Do not add formatter rewrites to validation or silently relax failures/budgets to make a new gate green.
-- PR descriptions use `pull_request_template.md` in this directory as written. Summary leads with the problem and resulting behavior; QA Instructions list actual commands and results and state skipped, failing, or unavailable checks; Review summarizes material findings resolved and the final blocker-only result; Compatibility / Rollout appears only when applicable. Include relevant UI evidence or performance measurements. Keep summaries short; do not attach planning logs.
-- Workflow files add checks but do not configure hosted branch protection or install local hooks. Do not claim either happened without verification.
+- Read affected package guidance before changing checks.
+- Preserve PR, main-push, merge-group, manual-dispatch, and reusable-workflow events. `github.base_ref` is not always populated outside PRs.
+- Change detection must include workflows and relevant shared actions/configuration; test-only and tooling-only changes must trigger owning checks.
+- Preserve tool versions, lockfiles, reproducible installs, hardware/platform matrices, and pinned action revisions.
+- Prefer package completion commands over duplicating them in YAML. For webv2's `pnpm check:release`, install Chromium and required Linux dependencies first.
+- Preserve failure diagnostics with `always()` where appropriate; keep generated review/performance artifacts out of Git.
+- Match hooks to CI's Ruff version/configuration; validation must not rewrite formatting.
+- Follow [the PR template](pull_request_template.md); keep summaries short and omit subagent counts, tiers, and process narration.
+- Workflow changes do not configure hosted branch protection or install local hooks; verify before claiming either.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 2fab6d6c56..c63bc70eb0 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -12,7 +12,7 @@
## Review
-<!-- Summarize material findings resolved and the final blocker-only review result. For agent-assisted work, identify independent review focuses or disclose the self-review fallback. Do not attach review transcripts or work logs. -->
+<!-- Summarize material findings resolved and remaining risks or limitations. If there were no material findings, say so briefly. Omit subagent counts, review tiers, and review-process narration. Do not attach review transcripts or work logs. -->
## Compatibility / Rollout
diff --git a/AGENTS.md b/AGENTS.md
index 127611c0d1..e052eb2ab5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,13 +2,12 @@
## Communication
-- Speak plainly and matter-of-factly. Assume readers benefit from short, skimmable updates; avoid filler, ceremony, and repeated status summaries.
-- Ask only when a decision cannot be inferred safely from the repository or request. Continue authorized work without repeated permission requests.
-- Lead with outcomes, blockers, and concrete evidence. Distinguish verified results from assumptions and checks you could not run.
+- Give plain, concise updates led by outcomes, blockers, and evidence. Distinguish verified results, assumptions, and unavailable checks.
+- Ask only when a decision cannot be inferred safely from the repository or request; continue authorized work without repeated permission requests.
## Find the right owner
-Before editing, read the applicable `AGENTS.md` files along each target path, even when starting at the repository root. Scoped guidance adds to these rules. `CLAUDE.md` files only import their sibling `AGENTS.md`; keep policy canonical here.
+Before editing, read `AGENTS.md` along each target path; scoped rules supplement this file. Keep policy in `AGENTS.md`; `CLAUDE.md` files only import their sibling.
| Area | Guidance and source of truth |
| --- | --- |
@@ -20,67 +19,67 @@ Before editing, read the applicable `AGENTS.md` files along each target path, ev
| CI and contribution tooling | [.github/AGENTS.md](.github/AGENTS.md) |
| Documentation | `docs/README.md` and `docs/package.json`; keep documentation about the implemented product current |
-Ordinary frontend features and fixes target **webv2**. The backend serves it when launched with `--webv2`; a default launch still selects legacy web. Verify the build and launch target when investigating UI behavior. Legacy web still owns generated OpenAPI/type artifacts.
+Ordinary frontend work targets **webv2**, served with `--webv2`; default launches select legacy web. Verify build/launch targets for UI investigations. Legacy web owns generated OpenAPI/type artifacts.
## Engineering standard
-- Produce correct, functional, efficient, maintainable, DRY, production-quality code. Inspect implementations, callers, contracts, and existing tests before designing changes.
-- Define the observable outcome and relevant validation. For bugs, establish a reproduction or failing behavioral test where feasible, then address the root cause. Reconsider the design when narrow fixes keep accumulating.
-- Consider edge cases, failure modes, data lifecycle, and operational limits. Keep ownership explicit and concentrate behavior behind small interfaces.
-- Every function, abstraction, dependency, fallback, and test must earn its place. Avoid pass-through wrappers, speculative extensibility, redundant validation, unnecessary configuration, and one-use abstractions that hide no meaningful complexity.
-- Small adapters are useful when they translate contracts, isolate dependencies, or own a lifecycle. Extract shared behavior when it prevents drift or simplifies callers; do not abstract merely because code looks similar.
-- Remove code, tests, and scaffolding made obsolete by the change. Preserve unrelated work and avoid drive-by rewrites.
-- Comment only non-obvious intent, constraints, or trade-offs. Do not narrate code.
-- Tests should protect meaningful behavior and catch a plausible regression. Avoid trivial constant/type/re-export assertions, expected values recomputed by the implementation's algorithm, and mocks that only verify internal choreography.
-- Test through the interface that owns the behavior. Prefer real lightweight dependencies and isolated fixtures; use doubles for expensive or external systems. Choose regression coverage for value, not test counts.
-- Keep dependencies and lockfile changes intentional. Do not weaken assertions, gates, architecture policy, or performance budgets just to pass. Explain existing failures and verification limits.
-- Keep durable architecture/reference documentation aligned with implemented behavior. Installed skills are optional helpers, not prerequisites; adapt their principles to this repository's stack and interfaces. Do not import personal paths or generic skill ceremony into the workflow.
+- Inspect implementations, callers, contracts, and tests before designing changes. Define observable outcomes and validation; reproduce bugs where feasible, fix root causes, and reconsider designs that accumulate patches.
+- Keep ownership and interfaces clear. Account for edge cases, failures, data lifecycles, and operational limits.
+- Every function, dependency, fallback, and test must earn its place. Add abstractions to translate contracts, isolate dependencies, own lifecycles, prevent drift, or simplify callers; avoid pass-through wrappers, speculative extensibility, redundant validation/configuration, and abstractions justified only by similar-looking code.
+- Remove obsolete code, tests, and scaffolding; preserve unrelated work. Comment only non-obvious intent, constraints, or trade-offs.
+- Test meaningful behavior through its owning interface with independent expectations that catch plausible regressions. Avoid trivial constant/type/re-export assertions, incidental snapshots, duplicate coverage, and mock choreography. Prefer real lightweight dependencies and isolated fixtures; use doubles for expensive/external systems. Optimize test value, not count.
+- Keep dependency/lockfile changes intentional. Never weaken assertions, gates, architecture policy, or performance budgets to pass; explain existing failures and verification limits.
+- Keep architecture/reference docs aligned with implementation. Skills are optional helpers: adapt them to this stack without importing personal paths or generic ceremony.
## Performance and efficiency
-- Actively inspect the PR's affected hot paths and immediate callers for efficiency wins: repeated work, unnecessary renders/subscriptions, request waterfalls, excess queries, serialization/copies, unbounded collections, and retained resources.
-- For inference, consider device transfers, dtype conversions, peak memory, model/cache lifetimes, and unnecessary synchronization.
-- Implement clear, low-risk improvements within the PR's scope. Larger optimizations must directly serve its outcome; mention unrelated opportunities briefly without expanding the PR.
-- Measure nontrivial optimizations and performance claims using existing budgets, representative fixtures, query counts, profiling, or focused benchmarks. Report material before/after results and their limits.
-- Preserve correctness and clarity. Add caching, memoization, concurrency, or batching only with understood invalidation, lifetimes, ordering, and cost. Do not invent an optimization or benchmark to satisfy a checklist.
+- Inspect affected hot paths and immediate callers for repeated work, renders/subscriptions, waterfalls, queries, serialization/copies, unbounded collections, and retained resources.
+- Implement clear, low-risk improvements in scope; larger optimizations must serve the task. Briefly note unrelated opportunities without expanding scope.
+- Measure nontrivial optimizations and performance claims with existing budgets and representative fixtures, query counts, profiling, or focused benchmarks. Report material before/after results and limits.
+- Preserve correctness and clarity. Require understood invalidation, lifetimes, ordering, and cost for caching, memoization, concurrency, or batching. Do not invent optimizations or benchmarks for a checklist.
## Product quality
-InvokeAI is a polished professional creative product. Maintain a first-class desktop experience: deliberate layouts, responsive interactions, cohesive controls, accessibility, and performance. Complete loading, empty, error, and recovery states. Verify changed interactions in the browser; automated checks do not establish visual quality by themselves.
+Maintain a polished desktop experience: deliberate layouts, responsive interactions, cohesive accessible controls, and complete loading/empty/error/recovery states. Verify changed interactions in the browser; automated checks alone do not establish visual quality.
## Milestones and code review rules
-A milestone is one coherent, commit-ready unit of work. Before calling it commit-worthy:
+A milestone is one coherent, commit-ready unit. Run relevant checks and self-review every change. Choose review depth by the complete task's behavior, blast radius, and failure consequences—not file/line counts or directory alone. Do not split risky work to avoid review.
-1. Run relevant checks, then spawn three independent, read-only review subagents with distinct focuses: correctness/spec conformance; architecture/operational safety/performance/unnecessary complexity; and test value/gaps/product quality (including accessibility for UI changes).
-2. Give each reviewer the same fixed comparison base, acceptance criteria, and complete candidate changes, including staged, unstaged, and new files. Reviewers inspect independently and do not edit, commit, or recursively delegate reviews.
-3. Require concrete locations, impact, and a failure scenario or engineering cost. Material findings affect behavior, safety, maintainability, efficiency, or meaningful coverage; style preferences alone are not blockers.
-4. Resolve every material finding, add useful regression coverage, and rerun affected checks. Request final blocker-only review of the resulting candidate. Further edits invalidate the relevant review results.
-5. Do not call work commit-worthy with material findings or unexplained failing gates. Report what passed, what failed or was unavailable, and material remaining limitations.
+| Review depth | When to use it |
+| --- | --- |
+| **Self-review; no subagents** | Local, low-risk edits with straightforward verification: copy, docs, styling, or an input minimum without shared validation, persistence, or API contract changes. |
+| **One independent reviewer** | Substantive features, fixes, or refactors with bounded impact and no high-risk trigger. |
+| **Three independent reviewers** | Behavior changes affecting authentication/authorization, account isolation, persisted-data compatibility/migrations, destructive operations, concurrency/resource lifecycles, shared API compatibility, inference numerical/device/memory behavior, or substantial architecture across owners. |
+
+Review focuses: correctness/spec conformance; architecture/operational safety/performance/unnecessary complexity; test value/gaps/product quality, including UI accessibility. One reviewer covers all; three divide them. User instructions override defaults. Select the tier without asking permission; briefly explain spawning. Required checks and browser verification apply at every tier.
+
+1. Review once per coherent candidate after checks. Supply the same fixed base, acceptance criteria, and complete task-owned diff (staged, unstaged, new files); identify unrelated changes. Use focused briefs and entry points, not full conversation inheritance.
+2. Reviewers inspect independently, including necessary callers/contracts. They are read-only: no edits, commits, or recursive delegation. Findings need locations, impact, and failure scenarios or engineering costs; style preferences alone are not blockers.
+3. Resolve all material findings, add useful regression coverage, and rerun affected checks. A clean review is final for an unchanged candidate. For subsequent edits, seek blocker-only follow-up from affected reviewers on changes and consequences. Broaden review and reassess the tier only when scope/risk materially changes.
+4. Do not declare readiness with material findings or unexplained failing gates. Report resolved findings, passed/failed/unavailable checks, and remaining limitations. PRs omit subagent counts, tiers, and process narration.
-If the environment cannot spawn subagents, perform separate self-review passes with the same focuses and explicitly disclose that independent review was unavailable. Never represent self-review as independent review. Delegating implementation is optional; use it for independently useful tasks with clear ownership.
+If required independent review is unavailable, self-review the corresponding focuses and disclose this to the user; ordinary low-risk self-review needs no such disclaimer. Never label self-review independent. Implementation delegation is optional for independently useful tasks with clear ownership.
## Commands and environments
-- Use **pnpm 10**, never npm/yarn, for frontends and docs. Each package owns its lockfile. Use `pnpm -C <package> ...`; `.nvmrc` records the development Node version. Read the package scripts instead of assuming root Makefile frontend commands target webv2.
-- Use the existing Python environment and `uv.lock`. For a fresh test environment: `uv sync --locked --extra test`; do not replace a configured accelerator environment with a different backend as routine setup.
-- From the root: `uv tool run [email protected] check <paths>` and `uv tool run [email protected] format --check <paths>`. Python uses 120-column formatting and absolute imports. Respect configured vendored-code exclusions.
-- Run focused Python tests with `uv run --no-sync pytest <test-paths>`; the full CI suite is `uv run --no-sync pytest -n logical` (xdist; each file's tests stay on a single worker). Slow tests are excluded by default: `slow` is the lane for what needs a development machine -- real accelerator hardware, or a quiet one for timing -- and is run there with `-m slow`, not by CI.
-- `uv run --no-sync mypy scripts/invokeai-web.py` is an additional diagnostic using the current exclusions, not an enforced CI gate. Do not describe it as comprehensive type coverage.
-- Choose checks by changed behavior. Broaden to the milestone's required gates before review; do not repeatedly rerun unchanged checks without a reason.
-- Install local hooks with `uv run --no-sync pre-commit install` after test dependencies are available. Hook installation is local to each checkout and is not implied by committing the configuration.
+- Use **pnpm 10**, never npm/yarn, with package-owned lockfiles and `pnpm -C <package> ...`. Use `.nvmrc`'s Node version; consult package scripts, not root Makefile assumptions about webv2.
+- Preserve the existing Python/accelerator environment and `uv.lock`. Fresh test setup: `uv sync --locked --extra test`; do not routinely replace accelerator backends.
+- Root Python checks: `uv tool run [email protected] check <paths>` and `uv tool run [email protected] format --check <paths>`. Use 120-column formatting, absolute imports, and configured vendored-code exclusions.
+- Focused tests: `uv run --no-sync pytest <test-paths>`; full CI: `uv run --no-sync pytest -n logical`. Hardware/quiet-machine timing tests use `-m slow` on development machines; excluded by default and CI. See `tests/AGENTS.md` for isolation rules.
+- `uv run --no-sync mypy scripts/invokeai-web.py` uses current exclusions; it is an optional diagnostic, not a CI gate or comprehensive type coverage.
+- Select checks by behavior; run required milestone gates before review. Repeat unchanged checks only for a reason.
+- After test dependencies are available, install hooks per checkout: `uv run --no-sync pre-commit install`. Committing configuration does not install hooks.
## Scratch files and repository hygiene
-- Never commit task plans, work logs, investigation notes, review transcripts, or handoffs, regardless of filename. Use `.scratch/agents/<task>/` if persistence is useful; creating these files is optional.
-- Durable documentation of implemented architecture, decisions, APIs, and setup belongs in version control. Do not turn scratch logs into permanent docs merely to bypass this rule.
-- Ignore rules keep recognized scratch/planning paths out of ordinary staging; they do not prevent force-adds or remove files already tracked by Git.
-- Inspect the staged diff and new files for planning material, including unexpected filenames. Never force-add planning artifacts or introduce `package-lock.json`/`yarn.lock`.
+- Never commit plans, work logs, investigation notes, review transcripts, or handoffs under any filename. Optional scratch belongs in `.scratch/agents/<task>/`; do not relabel it as durable docs.
+- Version durable documentation of implemented architecture, decisions, APIs, and setup.
+- Inspect staged diffs and new files for planning material. Ignore rules neither remove tracked files nor prevent force-adds. Never force-add planning artifacts or introduce `package-lock.json`/`yarn.lock`.
## Commits and pull requests
-- Commit readiness does not itself authorize committing or pushing. Follow the request's existing authorization; do not add an automatic commit/push step to each subtask.
-- Use Conventional Commits with the shortest descriptive, skimmable subject that states the outcome.
-- Follow the subject with one to three short, factual lines summarizing material changes; use bullets when useful. Omit implementation narration and details already clear from the subject.
-- Leave authorship to the configured Git author. Do not add agent attribution or co-author trailers.
-- Pull request descriptions follow `.github/pull_request_template.md`: keep its headings in order, fill every applicable section per its inline guidance, and omit only the sections the template marks as conditional. Tick a checklist item only when it is true for the PR.
+- Readiness does not authorize commits/pushes; follow existing user authorization without automatic per-subtask commits.
+- Use Conventional Commits: short outcome-focused subject, then one to three factual lines of material changes without repetition or process narration.
+- Use the configured Git author; no agent attribution or co-author trailers.
+- Follow `.github/pull_request_template.md`: ordered headings, all applicable sections and inline guidance, omit only conditional sections, and tick only true checklist items.
diff --git a/invokeai/app/AGENTS.md b/invokeai/app/AGENTS.md
index 29f5376d65..426c670a27 100644
--- a/invokeai/app/AGENTS.md
+++ b/invokeai/app/AGENTS.md
@@ -2,24 +2,24 @@
## Ownership and contracts
-- API routers validate requests, enforce authentication/authorization, and map service errors to HTTP responses. Services own domain behavior; storage implementations own persistence. Keep reusable policy out of route handlers.
-- Inspect `api/dependencies.py`, the affected router, service base/default/storage implementations, and corresponding tests before changing a flow. Follow existing dependency and start/stop lifecycles rather than creating parallel global services.
-- Authorize access to every account-owned resource on the server. Preserve ownership filtering for queries, writes, events, exports, and recovery; a UI guard is insufficient.
-- Pydantic models, invocation fields/versions, HTTP DTOs, and socket events are contracts. Trace frontend and saved-workflow consumers before changing names, defaults, validation, or errors.
-- API changes may require regenerating `frontend/web/openapi.json` and `frontend/web/src/services/api/schema.ts` (under `invokeai/`) even when the feature UI lives in webv2. Never hand-edit generated output. Read the legacy frontend guidance for commands.
+- Routers validate requests, enforce authentication/authorization, and map service errors to HTTP. Services own domain policy; storage owns persistence.
+- Before changing flows, inspect `api/dependencies.py`, affected routers, service base/default/storage implementations, and tests. Preserve dependency/start/stop lifecycles; avoid parallel global services.
+- Server-authorize every account-owned resource, including queries, writes, events, exports, and recovery; UI guards are insufficient.
+- Trace frontend/saved-workflow consumers before changing Pydantic models, invocation fields/versions, HTTP DTOs, or socket-event names, defaults, validation, or errors.
+- API changes may require regenerating `frontend/web/openapi.json` and `frontend/web/src/services/api/schema.ts` under `invokeai/`, even for webv2. Follow legacy frontend generation guidance; never hand-edit output.
## Persistence and lifecycle
-- Preserve atomicity, revision checks, idempotency, and explicit conflict behavior. Inspect migrations and old-record readers before changing stored data; add migration/compatibility tests when needed.
-- SQLite transactions are not automatically composable. Read `services/shared/sqlite/sqlite_database.py` and `services/project_records/project_records_sqlite.py`: nested service calls that open transactions can commit an outer operation prematurely. Keep multi-record writes under one transaction owner and pass its cursor where the design supports it.
-- Preserve project/account isolation, bounded document sizes, queue admission/receipt semantics, and lost-response retry safety. Do not silently discard recovery data or turn conflicting writes into last-write-wins saves.
-- Long-running work needs bounded concurrency, cancellation, appropriate timeouts/retries, and reliable cleanup of files, subprocesses, listeners, and task state. Avoid blocking the async server loop with CPU or blocking I/O work.
-- Preserve file/path validation, existing remote-fetch protections, and sanitized errors. Tests and debugging must not modify a user's real models, database, outputs, or credentials.
+- Preserve atomicity, revision checks, idempotency, and explicit conflicts. Inspect migrations/old-record readers for stored-data changes; add needed migration/compatibility tests.
+- Read `services/shared/sqlite/sqlite_database.py` and `services/project_records/project_records_sqlite.py`: nested transactions can prematurely commit outer operations. Use one transaction owner for multi-record writes, passing its cursor where supported.
+- Preserve project/account isolation, document bounds, queue admission/receipts, and lost-response retry safety. Never silently discard recovery data or resolve conflicts with last-write-wins.
+- Bound concurrency; support cancellation, timeouts/retries, and file/process/listener/task cleanup. Keep CPU/blocking I/O off the async server loop.
+- Preserve file/path validation, remote-fetch protections, and sanitized errors. Never modify real user models, databases, outputs, or credentials during tests/debugging.
## Efficiency and verification
-- Examine affected queries for repeated lookups, unnecessary full scans/materialization, missing bounds, and excessive serialization. Use representative data and query counts/measurements before adding caches or indexes.
-- Use real temporary SQLite storage for transaction, migration, revision, and ownership tests. Cover malformed input, cross-user access, cancellation, repeated requests, and partial failure when relevant; do not mock away the behavior being protected.
-- Tests normally live under `tests/app/` or the existing owning suite in `tests/`; read `tests/AGENTS.md`. Run focused pytest plus root Ruff checks. Broaden to relevant service/router/invocation suites for a milestone.
-- Graph execution changes should consult `services/shared/README.md` and test scheduling and invocation lifecycle through their owning interfaces.
-- Report API/schema generation results, migration validation, and unavailable integration/hardware checks honestly. Root mypy is an additional diagnostic, not an existing CI requirement.
+- Inspect queries for repeated lookups, full scans/materialization, missing bounds, and serialization. Measure representative data/query counts before adding caches or indexes.
+- Use real temporary SQLite for transaction, migration, revision, and ownership tests; cover affected malformed input, cross-user access, cancellation, repeated requests, and partial failures.
+- Read `tests/AGENTS.md`; use `tests/app/` or the existing owning suite. Run focused pytest and root Ruff; broaden to relevant service/router/invocation suites for milestones.
+- For graph execution, consult `services/shared/README.md`; test scheduling and invocation lifecycles through owning interfaces.
+- Report schema generation, migration validation, and unavailable integration/hardware checks.
diff --git a/invokeai/backend/AGENTS.md b/invokeai/backend/AGENTS.md
index 78f6dc95a0..a253e065fc 100644
--- a/invokeai/backend/AGENTS.md
+++ b/invokeai/backend/AGENTS.md
@@ -2,22 +2,22 @@
## Design and resources
-- Trace the caller, model loader/cache, tensor shapes, device/dtype handling, and cleanup before changing inference. Keep reusable model/inference policy here rather than in UI or API adapters.
-- Use existing device selection and model-management abstractions, including `util/devices.py`. Do not hardcode CUDA, GPU zero, or a dtype when CPU, MPS, ROCm, XPU, or multiple devices need to work.
-- Respect session/thread device ownership. Restore temporary model patches, device state, hooks, and allocations on success, cancellation, and exceptions. Avoid request-specific mutable process-wide state.
-- Keep model/cache lifetimes and working-memory estimates explicit. Bound queues, caches, downloads, batches, and temporary buffers; consider peak memory as well as throughput.
-- Preserve model format validation and loading safeguards. Respect vendored-code exclusions and upstream provenance; avoid unrelated formatting or rewrites in vendored modules.
+- Trace callers, loaders/caches, tensor shapes, device/dtype handling, and cleanup before inference changes. Reusable model/inference policy belongs here, not UI/API adapters.
+- Use existing device/model-management abstractions, including `util/devices.py`; preserve CPU/MPS/ROCm/XPU/multi-device support without hardcoded CUDA, GPU zero, or dtype assumptions.
+- Respect session/thread device ownership. Restore temporary model patches, device state, hooks, and allocations on success/cancellation/exceptions; avoid request-specific mutable globals.
+- Define model/cache lifetimes and working-memory estimates. Bound queues, caches, downloads, batches, and buffers; consider peak memory and throughput.
+- Preserve model validation/loading safeguards, vendored exclusions, and upstream provenance; avoid unrelated vendored rewrites/formatting.
## Performance
-- Hunt for efficiency wins on the affected inference path: duplicate work, device transfers, dtype conversions, tensor copies, CPU/GPU synchronization, repeated loading, and retained tensors.
-- Use representative shapes, resolutions, batch sizes, and supported device paths. Measure material latency/throughput and peak-memory changes; distinguish cold loading/compilation from warmed inference.
-- Retain numerical correctness with appropriate tolerances and reproducible seeds where supported. A faster path is not an improvement if it changes output semantics, breaks cancellation, or shifts failures to larger inputs.
-- Do not add speculative kernels, caches, compilation, or concurrent execution without a demonstrated benefit and clear fallback/lifecycle behavior.
+- Inspect duplicate work, device transfers, dtype conversions, tensor copies, synchronization, repeated loading, and retained tensors.
+- Measure material latency/throughput/peak-memory changes with representative shapes, resolutions, batches, and devices; distinguish cold loading/compilation from warm inference.
+- Preserve output semantics, cancellation, and correctness at larger inputs, using appropriate numerical tolerances and reproducible seeds where supported.
+- Kernels, caches, compilation, or concurrency need demonstrated benefit and clear fallback/lifecycle behavior.
## Verification
-- Read `tests/AGENTS.md` and the relevant existing suites under `tests/backend/`, `tests/model_identification/`, or `tests/test_model_manager/`.
-- Use small CPU fixtures for logic where possible, plus targeted hardware checks for device-specific behavior. Test real tensor operations when mocks would hide shape, dtype, numerical, or memory errors.
-- Cover failure cleanup, unsupported configurations, boundary shapes, and cancellation where affected. Do not download large models or use the user's model/output directories as routine unit-test setup.
-- Run focused pytest and root Ruff checks. Record tested hardware, dtype, shapes, and measurements for material inference changes. Explicitly state untested platforms and model paths; CPU tests do not prove accelerator behavior.
+- Read `tests/AGENTS.md` and relevant suites in `tests/backend/`, `tests/model_identification/`, or `tests/test_model_manager/`.
+- Use small CPU fixtures and targeted device checks; real tensor operations must expose shape/dtype/numerical/memory errors mocks would hide.
+- Cover affected failure cleanup, unsupported configurations, boundary shapes, and cancellation. No routine large-model downloads or user model/output directories for unit tests.
+- Run focused pytest and root Ruff. For material inference changes, report hardware, dtype, shapes, measurements, and untested platforms/model paths; CPU passes do not prove accelerator behavior.
diff --git a/invokeai/frontend/web/AGENTS.md b/invokeai/frontend/web/AGENTS.md
index 4f2a4621db..4296f0e465 100644
--- a/invokeai/frontend/web/AGENTS.md
+++ b/invokeai/frontend/web/AGENTS.md
@@ -1,19 +1,17 @@
# Legacy frontend
-Ordinary frontend feature and bugfix work targets `../webv2/`; read its guidance. Change legacy UI only when explicitly requested or a shared compatibility change requires it. The backend still selects legacy web without `--webv2`.
+Change legacy UI only when explicitly requested or required for shared compatibility. Ordinary frontend work belongs in `../webv2/`; read its guidance.
-This package still owns `openapi.json`, generated `src/services/api/schema.ts`, and their generation tooling. Updating these for backend contract changes is expected and does not imply implementing the UI here.
+This package owns `openapi.json`, generated `src/services/api/schema.ts`, and generation tooling, including for backend contracts consumed by webv2.
## Commands
-Run from this directory, with pnpm 10 and this package's lockfile:
+Run from this directory with this package's lockfile:
- `pnpm lint`: legacy TypeScript, dependency-cycle, ESLint, Prettier, and unused-dependency checks.
-- `pnpm test:no-watch`: legacy Vitest suite; colocate meaningful tests using existing conventions.
+- `pnpm test:no-watch`: legacy Vitest; colocate tests following existing conventions.
- `pnpm build`: legacy production build.
-- From an activated repository Python environment, `python ../../../scripts/generate_openapi_schema.py > openapi.json` then `pnpm exec prettier --write openapi.json` regenerates the schema.
-- From that same environment, `python ../../../scripts/generate_openapi_schema.py | pnpm typegen` regenerates frontend types. Use a shell with pipeline failure propagation and verify generator success; never hand-edit generated files.
+- In the activated repository Python environment, regenerate schema: `python ../../../scripts/generate_openapi_schema.py > openapi.json`, then `pnpm exec prettier --write openapi.json`.
+- Regenerate types in that environment: `python ../../../scripts/generate_openapi_schema.py | pnpm typegen`. Enable shell pipeline failure propagation and verify generator success; never hand-edit generated files.
-Use root Ruff/pytest commands for associated Python changes. Do not apply webv2's Chakra version, @dnd-kit APIs, Oxc commands, or browser-test assumptions here. Preserve existing persisted-state migrations when changing legacy state behavior.
-
-Shared review, scratch, performance, test-value, and commit rules apply. There is no mandatory work log, automatic commit, or requirement for named vendor-specific agents.
+Use root Ruff/pytest for Python changes. Do not apply webv2's Chakra version, @dnd-kit APIs, Oxc commands, or browser-test assumptions here. Preserve existing persisted-state migrations when changing legacy state.
diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.md
index 71ce397623..4c466bc61b 100644
--- a/invokeai/frontend/webv2/AGENTS.md
+++ b/invokeai/frontend/webv2/AGENTS.md
@@ -1,33 +1,33 @@
# Webv2
-Read [ARCHITECTURE.md](ARCHITECTURE.md) before changing module ownership or interfaces. Read the affected owner-local README for lifecycle/persistence behavior. This is a React 19, Vite, Chakra UI 3, TanStack Query/Router, and @dnd-kit application; legacy web uses different libraries and commands.
+Read [ARCHITECTURE.md](ARCHITECTURE.md) for ownership/interface changes and affected owner-local READMEs for lifecycle/persistence. Stack: React 19, Vite, Chakra UI 3, TanStack Query/Router, @dnd-kit; legacy web differs.
## Ownership and state
-- Follow `app -> workbench/features -> platform` and the executable policy in `src/architecture/`. App composes dependencies; Platform owns domain-neutral infrastructure; Features own domain behavior; Workbench owns the project aggregate, shell, and Canvas.
-- Import Features through their registered top-level public entries. Do not deep-import another owner's implementation to follow generic advice against barrel imports. Pure cores stay independent of React, UI, and transport, including type-only dependencies.
-- Production Canvas callers use `canvas-engine/api.ts`. Keep contracts with the owner of their invariants. Consult the ownership manifest before adding Workbench modules.
-- Keep wire DTOs and persisted schemas behind explicit mappings/serializers. Do not grow compatibility re-exports into implementations or add architecture exceptions to make a check pass.
-- TanStack Query owns backend read models; non-React runtimes own orchestration and lifecycle policy. Use stable, narrowly selected external-store snapshots instead of mirroring broad stores in component state.
-- Preserve account/project isolation, stale-result fencing, revision conflicts, reconnect behavior, and start/dispose ownership. No process-wide mutable caches for per-account/project lifetimes.
-- Read `src/workbench/projects/README.md` for persistence changes: backend authority, bounded recovery storage, cross-tab ownership, durable queue receipts, and explicit conflict decisions are behavioral contracts.
+- Follow `app -> workbench/features -> platform` and `src/architecture/` policy. App composes dependencies; Platform owns domain-neutral infrastructure; Features own domain behavior; Workbench owns the project aggregate, shell, and Canvas.
+- Import Features through registered top-level public entries, never another owner's internals to avoid barrels. Pure cores exclude React/UI/transport dependencies, including type-only imports.
+- Production Canvas callers use `canvas-engine/api.ts`. Contracts belong with their invariants' owner; consult the ownership manifest before adding Workbench modules.
+- Map/serialize wire DTOs and persisted schemas explicitly. Do not turn compatibility re-exports into implementations or add architecture exceptions to pass checks.
+- Query owns backend read models; non-React runtimes own orchestration/lifecycles. Use stable, narrowly selected external-store snapshots, not broad component-state mirrors.
+- Preserve account/project isolation, stale-result fencing, revision conflicts, reconnects, and start/dispose ownership. No process-wide mutable per-account/project caches.
+- For persistence, read `src/workbench/projects/README.md`: preserve backend authority, bounded recovery, cross-tab ownership, durable queue receipts, and explicit conflicts.
## React and product quality
-- Add no direct `useEffect` calls. Derive values during render, handle actions in event handlers, fetch through Query, and subscribe through external-store adapters.
-- Use the existing `@platform/react/useMountEffect` only for genuine mount/unmount registration with stable dependencies and complete cleanup. Do not hide changing dependencies in refs, introduce wrapper aliases, or use layout effects to evade this rule. Layout effects are reserved for required pre-paint DOM measurement.
-- Migrate an existing effect when changing its behavior; do not sweep unrelated effects. When an identity changes, use the appropriate store/runtime lifecycle or deliberate keyed remount without losing user state accidentally.
-- Reuse Platform UI controls, Chakra/theme tokens, icons, and established interaction patterns. Do not introduce a second styling system or adopt Next.js/SWR examples from generic skills.
-- Finish loading, empty, error, disabled, and recovery states. Keep keyboard operation, visible focus, focus restoration, accessible names, and alternatives to pointer-only interactions intact.
-- Maintain a dense, usable desktop layout across window sizes and zoom levels. Check overflow, long/localized text, selected/hover/active states, and theme consistency. Use existing localization conventions.
-- Keep frequent interactions immediate and motion restrained, interruptible, and compatible with reduced-motion preferences. Specify transition properties; avoid animation that delays editing or is the only state cue.
-- Inspect changed flows in a browser and provide relevant visual evidence. Browser tests and axe checks complement visual/interaction review rather than replacing it.
+- No direct `useEffect`: derive during render, act in event handlers, fetch through Query, subscribe via external-store adapters.
+- `@platform/react/useMountEffect` is only for mount/unmount registration with stable dependencies and complete cleanup. No changing-dependency refs, wrapper aliases, or layout-effect evasions; layout effects require pre-paint DOM measurement.
+- Migrate effects when changing their behavior, without unrelated sweeps. Identity changes use store/runtime lifecycles or deliberate keyed remounts without accidental state loss.
+- Reuse Platform controls, Chakra/theme tokens, icons, and interactions; no second styling system or generic Next.js/SWR patterns.
+- Include disabled states; preserve keyboard operation, visible/restored focus, accessible names, and pointer alternatives.
+- Keep dense layouts usable across window sizes/zoom. Check overflow, long/localized text, selected/hover/active states, and themes; follow localization conventions.
+- Keep interactions immediate and motion restrained, interruptible, and reduced-motion compatible. Specify transition properties; animation must neither delay editing nor be the sole state cue.
+- Provide visual evidence of browser-inspected flows; browser tests and axe do not replace visual/interaction review.
## Performance and validation
-- Inspect affected render/subscription paths, large galleries/lists, pointer handlers, Canvas resources, lazy module loading, and request scheduling for related efficiency wins. Use existing virtualization and lazy boundaries; do not add memoization without an identified cost.
-- Preserve resource disposal, bounded memory, account transitions, and responsive input. Measure material performance claims with the existing budgets and representative fixtures. Do not casually update goldens or baselines to hide regressions.
-- Commands below run from this directory (or use `pnpm -C invokeai/frontend/webv2`). Install using `pnpm install --frozen-lockfile` with the existing lockfile.
+- Inspect rendering/subscriptions, galleries/lists, pointer handlers, Canvas resources, lazy loading, and request scheduling. Use existing virtualization/lazy boundaries; memoize only identified costs.
+- Preserve disposal, bounded memory, account transitions, and responsive input. Never update goldens/baselines to hide regressions.
+- Run commands here or via `pnpm -C invokeai/frontend/webv2`. Install with `pnpm install --frozen-lockfile`.
| Change/check | Command |
| ------------------------------------- | ------------------------------------------------------------------ |
@@ -39,6 +39,6 @@ Read [ARCHITECTURE.md](ARCHITECTURE.md) before changing module ownership or inte
| Accessibility in a fresh build | `pnpm test:accessibility` |
| Milestone/release completion | `pnpm check:release` |
-Install Chromium with `pnpm exec playwright install chromium` if missing (`--with-deps` in Linux CI). Unit tests are colocated `*.test.ts`/`*.test.tsx`; real-browser tests are `*.browser.test.ts`/`*.browser.test.tsx`. Test real IndexedDB, Web Locks, focus, pointer, and rendering behavior where mocks cannot establish correctness.
+Install missing Chromium: `pnpm exec playwright install chromium` (`--with-deps` in Linux CI). Colocate unit `*.test.ts`/`*.test.tsx` and browser `*.browser.test.ts`/`*.browser.test.tsx` tests. Use real IndexedDB, Web Locks, focus, pointer, and rendering where mocks cannot establish correctness.
-`check:release` includes lint, all tests, architecture performance/build, project-file journeys, and accessibility. Architecture inventories and performance reports go to ignored `artifacts/`; do not commit them. Run focused checks during development, then the completion gate before calling a code milestone ready. Documentation-only changes need formatting/link review, not unrelated application tests.
+Run focused checks during development and `check:release` before code-milestone readiness: lint, all tests, architecture performance/build, project-file journeys, and accessibility. Docs-only changes need formatting/link review, not application tests. Keep architecture inventories/performance reports in ignored `artifacts/`, never committed.
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index 123090b1ac..f2dc37b183 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -1,13 +1,10 @@
# Python tests
-- Read guidance for the production code under test. Follow existing suite placement (`tests/app/`, `tests/backend/`, or the owning root suite) and reuse appropriate fixtures from `conftest.py` and `fixtures/`. Keep tests inside the Python tree's contracts: UI copy and docs prose belong to their own packages' checks. A test that must read a file outside `tests/`, `scripts/`, or the Python package tree (a shared contract fixture, for example) must add that path to the change filter in `.github/workflows/python-tests.yml`, or CI skips pytest when only that file changes.
-- Protect observable behavior at the interface that owns it. A test should fail for a plausible regression, use independently derived expectations, and survive implementation refactors that preserve the contract.
-- Avoid trivial type/constant/re-export tests, snapshots of incidental structure, duplicate coverage, implementation-shaped mock choreography, and benchmarks without a meaningful question. Remove obsolete tests.
-- Reproduce bugs with a focused failing case when feasible. Add edge/failure cases where they protect real behavior, not every imaginable branch. Use names describing outcomes.
-- Prefer real temporary SQLite/filesystem/tensor operations when they establish the behavior. Mock external services, expensive models, or unavailable hardware at an appropriate interface; never mock away the transaction, authorization, concurrency, or numerical behavior being checked.
-- Isolate filesystem paths, databases, account identities, clocks, random seeds, environment changes, and network behavior. Clean up subprocesses, listeners, patches, and resources. Never use production model/database/output directories.
-- Exercise rollback, revisions, cross-user isolation, retries, cancellation, resource bounds, and cleanup when affected. Frontend IndexedDB, Web Locks, focus, and rendering belong in webv2's real-browser tests.
-- Run `uv run --no-sync pytest <test-paths>` from the root for focused checks; CI uses `uv run --no-sync pytest -n logical`, which runs the suite across xdist workers (one per vCPU). Configuration excludes `slow` by default: the marker is the lane for tests that need a development machine -- real accelerator hardware, or a quiet one for timing -- and CI does not run them. Run them there with `-m slow` for a selection, or `-m ""` to include everything.
-- Tests must pass under parallel execution, in any file order. `--dist loadfile` (set in `addopts`) keeps a file's tests on one worker, but which files a worker gets is arbitrary: a file must establish its own process-global state (the JWT secret, for example) instead of inheriting it from a file that happens to run earlier. Verify a new file passes when run on its own.
-- In the default run, assert behavior rather than throughput or latency: those measure the runner once workers share its cores. A generous ceiling separating "finishes" from "hangs" is fine, and CPU time survives contention where wall clock does not. A measurement that only holds on a quiet machine, or that needs real hardware, belongs behind `slow` rather than at a tuned threshold.
-- Hardware tests need explicit prerequisites and honest reporting of skips/unavailable devices. Passing mocked or CPU tests does not establish CUDA/ROCm/MPS/XPU behavior.
+- Read production-code guidance; use existing suites (`tests/app/`, `tests/backend/`, or the owning root suite) and appropriate `conftest.py`/`fixtures/` fixtures. UI copy and docs checks belong to their packages.
+- Tests reading outside `tests/`, `scripts/`, or the Python package tree must add those paths to `.github/workflows/python-tests.yml` change filters so fixture-only changes trigger pytest.
+- Name tests by outcome; cover meaningful edge/failure cases and survive behavior-preserving refactors. Prefer real temporary SQLite/filesystem/tensor operations. Mock external services, expensive models, or unavailable hardware without mocking the transaction, authorization, concurrency, or numerical behavior under test.
+- Isolate paths, databases, accounts, clocks, seeds, environment, and network behavior. Clean up subprocesses, listeners, patches, and resources; never use production model/database/output directories.
+- Cover affected rollback, revisions, cross-user isolation, retries, cancellation, bounds, and cleanup. IndexedDB, Web Locks, focus, and rendering belong in webv2 browser tests.
+- Use root pytest commands. CI runs xdist workers per vCPU; `--dist loadfile` in `addopts` keeps each file on one worker, with arbitrary file assignment/order. Each file must establish its own process-global state (e.g. JWT secret) and pass alone; verify new files independently.
+- Default tests assert behavior, not throughput/latency under runner contention. Generous hang ceilings are acceptable; CPU time tolerates contention better than wall time. Hardware/quiet-machine measurements require `slow`, excluded by default and CI. On development machines, use `-m slow` for that lane or `-m ""` for everything.
+- State hardware prerequisites and skipped/unavailable devices. CPU/mocked passes do not establish CUDA/ROCm/MPS/XPU behavior.