Files
crank/_bmad-output/implementation-artifacts/1-13-immutable-agent-catalog.md
T

487 lines
38 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
story_id: "1.13"
story_key: "1-13-immutable-agent-catalog"
requirement: "FR-4"
status: "done"
baseline_commit: "767428436d3a54e60809a727044dfcec48e1f1dd"
created: "2026-08-22T12:12:34+03:00"
---
# Story 1.13: Публиковать immutable Agent catalog
Status: done
## Story
As an администратор,
I want собирать и публиковать точный каталог разрешённых Tools для Agent,
so that MCP-клиент обнаруживает только утверждённые версии и получает стабильное поведение.
## Operational Brief
Story 1.13 закрывает FR-4 и переводит Agent catalog из mutable draft-like поведения в строгий published snapshot contract.
После Story 1.7 Operation Published Version стала immutable. Сейчас следующий риск находится на уровне Agent:
- Agent Draft можно менять без revision predicate;
- publish Agent обновляет `published_agents` как latest pointer и не создаёт полноценный immutable catalog snapshot;
- bindings/policy могут изменяться в текущей version row;
- MCP catalog/cache грузится по `{workspace_slug, agent_slug}`, без `catalog_revision` и полного auth scope;
- UI сохраняет create/update/bind/publish одной кнопкой без conflict token и без явной модели Draft vs Published.
Цель Story 1.13 — сделать Agent catalog PostgreSQL-authoritative:
- Draft изменения не влияют на текущий Published Agent;
- publish атомарно создаёт immutable Agent Version snapshot, exact bindings и monotonic `catalog_revision`;
- MCP discovery/call читает только committed published snapshot;
- stale search result или stale UI response не может вызвать capability вне актуального snapshot;
- unpublish/archive/key revocation закрывают новый доступ без удаления immutable versions/history/evidence;
- direct/search modes остаются текущими пользовательскими режимами, но получают revision-safe contract.
Это foundation для Story 1.14 approvals, Story 1.15 history/usage и Story 1.16 onboarding. Не расширять story в approvals, Tasks, Resources, Prompts или новый MCP protocol surface.
## Requirement / Architecture Trace
- **Direct requirement:** FR-4.
- **Primary architecture:** AD-2 typed Operation/Agent aggregates and immutable snapshots; AD-19 UI/boundary error contract.
- **Supporting architecture:** AD-1, AD-4, AD-11, AD-13, AD-16, AD-20, AD-21, AD-22, AD-23.
- **Applicable NFR:** NFR-P3, NFR-P4, NFR-P5, NFR-R2, NFR-S1, NFR-S2, NFR-S4, NFR-S7, NFR-S8, NFR-O1, NFR-O4, NFR-O5, NFR-C1, NFR-C3, NFR-C4.
- **Primary risk/evidence:** E1-R-011 — Agent publication/cache exposes Draft, foreign, stale Tools or changes exact published versions. Required groups: E1-29, E1-30, E1-31.
## Scope
In scope:
- Agent aggregate/version state model, revision predicate, immutable published snapshots and monotonic `catalog_revision`.
- Exact binding validation: only Published Operation Versions from the same workspace; no Draft, archived aggregate for new binding, foreign capability or disabled unknown Tool.
- Agent Draft editing for summary, instructions, bindings and direct/search policy without changing current Published Agent.
- Atomic publish transaction: Agent Version, binding snapshot, published pointer/catalog revision and audit/product event if present.
- MCP direct mode discovery/call from exact published snapshot with deterministic pagination and no Draft/foreign leakage.
- MCP search mode result token bound to Agent ID, Agent Version and `catalog_revision`; stale result rejects safely after new publication.
- Catalog cache keys including Agent ID/version/revision and full authorization scope; Valkey loss must fall back to PostgreSQL without correctness change.
- Unpublish/archive/key revocation effects on discovery/call/session/cache while preserving immutable versions, bindings, Invocation History and audit evidence.
- Admin API and UI conflict handling, loading/empty/error/confirmation/stale-response states in RU and EN.
- PostgreSQL, Admin API, MCP, Playwright, performance and inventory evidence for FR-4.
Out of scope:
- Approval state machine and side-effect honesty beyond preserving existing approval guards (Story 1.14).
- Invocation History/Usage UI redesign and CSV export (Story 1.15).
- New MCP Resources, Prompts, Tasks, Load Runs or background execution.
- OpenAPI importer behavior and Operation lifecycle semantics already owned by Story 1.7/Epic 2.
- New auth profile/key/master-key behavior beyond consuming revocation status from Stories 1.10–1.12.
- Prometheus/Grafana packaging, SLO dashboards or product analytics rollups.
- Multi-workspace UX, hosted identity providers or commercial access-control features.
## Acceptance Criteria
1. **Binding accepts only exact Published Operation Version**
- Given Agent Draft
- When администратор добавляет Tool binding
- Then binding принимает только точную Published Operation Version из того же workspace
- And Draft, archived Operation для нового binding или foreign-workspace capability отклоняется без metadata leakage.
2. **Draft changes do not mutate Published Agent**
- Given изменяемый Agent Draft
- When администратор добавляет, удаляет или заменяет bindings и выбирает direct либо search mode
- Then изменения сохраняются только в Draft revision
- And текущий Published Agent catalog остаётся неизменным.
3. **Atomic publish creates immutable catalog revision**
- Given валидный Agent Draft
- When администратор публикует Agent
- Then в одной PostgreSQL transaction создаются immutable Agent Version, exact binding snapshot и монотонно увеличенный `catalog_revision`
- And MCP начинает читать новый snapshot только после успешного commit.
4. **Concurrent edit/publish conflicts are safe**
- Given concurrent edit или publish одного Agent Draft
- When revision predicate устарел
- Then операция возвращает conflict и не перезаписывает более новое состояние
- And UI предлагает reload/review вместо автоматического повторения mutation.
5. **Operation evolution does not alter current Agent**
- Given Published Agent Version
- When связанная Operation получает новый Draft или новую Published Version
- Then текущий Agent продолжает ссылаться на прежнюю точную Published Version
- And обновление Tool требует нового Agent Draft, явной замены binding и повторной публикации.
6. **Direct discovery is snapshot-scoped**
- Given Agent в direct mode
- When авторизованный MCP-клиент выполняет discovery
- Then он получает только Tools immutable snapshot этого Agent с deterministic pagination
- And Draft или Tool другого Agent отсутствует в результате.
7. **Search results are revision-bound**
- Given Agent в search mode
- When MCP-клиент получает search result
- Then result связан с Agent Version и `catalog_revision`
- And после новой публикации устаревший result не может использоваться для вызова capability вне актуального snapshot.
8. **Catalog cache cannot change correctness**
- Given catalog cache
- When публикуется новая Agent Version, Agent unpublish/archive или key revocation
- Then cache key включает Agent ID/version/revision и full authorization scope, а stale projection инвалидируется
- And потеря Valkey восстанавливает каталог из PostgreSQL без изменения correctness.
9. **Unpublish/archive preserve immutable evidence**
- Given Published Agent
- When администратор выполняет unpublish или archive
- Then новые MCP discovery/call requests перестают получать доступ согласно lifecycle contract
- And immutable versions, bindings, Invocation History и audit evidence не удаляются и не переписываются.
10. **MCP key scope is default-deny**
- Given MCP key для конкретного Agent
- When клиент обращается к endpoint другого Agent или revision
- Then access отклоняется default-deny без раскрытия catalog metadata
- And cache/session lookup сохраняет полный Agent/workspace/auth scope.
11. **Agent lifecycle UI has explicit states**
- Given Agent lifecycle UI на RU и EN
- When выполняются edit, bind, publish, conflict resolution, unpublish или archive
- Then реализованы loading, empty, error, confirmation и stale-response states
- And UI явно показывает Draft versus Published Version и текущий `catalog_revision`.
12. **Reference dataset discovery performance**
- Given catalog performance test на Reference Deployment dataset
- When выполняется Tool discovery
- Then latency соответствует NFR-P4 — ≤150 ms p95
- And результат стабилен при 200 Agents и 2 000 Operations без draft leakage.
13. **Automated catalog lifecycle suite**
- Given automated test suite
- When проверяется catalog lifecycle
- Then покрыты atomic publish, concurrent conflict, exact-version pinning, direct/search modes, stale results, cache loss и cross-Agent/workspace negatives
- And проходят registry, Admin API, MCP transport, Playwright и `just verify`.
## Frozen Agent Catalog Decisions
- `Agent` — aggregate identity/availability and current draft pointer. `AgentVersion` — immutable catalog snapshot.
- Published `AgentVersion` rows are append-only. Draft changes after publish create or update only the current Draft according to the revision contract; they never update a Published row.
- `catalog_revision` is monotonic per Agent and increments only when a new published catalog becomes visible or published availability changes.
- `published_agents` remains a current-pointer/readiness table if needed, but it is not the immutable audit source. Immutable Agent Version and exact binding snapshot are the evidence source.
- Existing route paths and JSON enum spellings remain stable. Adding required revision preconditions is an intentional Admin mutation contract revision for safety; missing precondition returns deterministic 428/409 rather than fail-open lost update.
- Direct mode returns bound snapshot tools. Search mode returns a bounded opaque token or equivalent machine field carrying Agent ID/version/revision/search fingerprint; stale token is rejected before execution.
- MCP response must not expose Draft, foreign, archived-for-new-binding or stale catalog metadata. Safe error includes request_id/trace_id already provided by prior stories.
- Cache is optimization only. PostgreSQL is correctness authority. Cache miss/loss/stale value must not alter visible authorization or catalog content.
- Agent key revocation invalidates subsequent discovery/call. Existing sessions must be revalidated or scoped so revoked credential cannot continue using stale catalog.
- Agent archive/unpublish stops new discovery/call but does not delete immutable Agent Versions, binding snapshots, Operation versions, Invocation History or audit evidence.
- Reference performance gate for NFR-P4 uses the PRD dataset shape: 200 Agents and 2 000 Operations. Local smaller runs are diagnostic only.
## Stable Agent Catalog Error Contract
| HTTP/MCP | Code | Safe recovery |
|---:|---|---|
| 428 / JSON-RPC error | `agent_precondition_required` | Reload Agent and retry with current revision token. |
| 409 / JSON-RPC error | `agent_stale_revision` | Preserve local edits; reload/review authoritative Draft. |
| 409 / JSON-RPC error | `agent_invalid_transition` | Reload Agent lifecycle state; do not retry unchanged command. |
| 409 / JSON-RPC error | `agent_archived` | Create or use another Agent; immutable history remains readable through Admin history flows. |
| 409 / JSON-RPC error | `agent_unpublished` | Publish a valid Draft before MCP discovery/call. |
| 422 / JSON-RPC error | `agent_binding_not_published` | Bind an exact Published Operation Version. |
| 422 / JSON-RPC error | `agent_binding_archived_operation` | Remove archived Operation from new binding. |
| 422 / JSON-RPC error | `agent_binding_scope_denied` | Select a capability from the current workspace. |
| 422 / JSON-RPC error | `agent_catalog_policy_invalid` | Correct direct/search policy and group references. |
| 409 / JSON-RPC error | `agent_catalog_result_stale` | Repeat search/discovery against current Agent revision. |
| 403/404 / JSON-RPC error | `agent_access_denied` | Use a valid active key for this Agent and workspace. |
## Tasks / Subtasks
- [x] Task 1 — Freeze Agent catalog oracle and current regression tests (AC: 1–13)
- [x] Characterize current Agent domain/table/query/API/UI/MCP behavior and add RED tests for mutable published Agent row, pointer rewind, binding Draft/foreign versions, stale cache/search and missing revision preconditions.
- [x] Freeze Agent state model, `catalog_revision` semantics, safe error codes, direct/search contracts and cache correctness rules in tests/docs.
- [x] Verify prerequisite contracts from Stories 1.1–1.12 are preserved: typed config only, MigrationAuthority-only DDL, request/trace IDs, typed metrics, Operation immutable versions, hardened runtime/outbound/auth/session.
- [x] Task 2 — Add typed Agent lifecycle/revision model in core (AC: 1–5, 9, 11)
- [x] Add domain helpers for allowed Agent transitions, publishability, immutable version status and catalog revision changes.
- [x] Add validated strong revision token/ETag binding workspace, Agent ID, current draft version, latest published version, availability and catalog revision.
- [x] Add tests for legal/illegal transitions, stale token replay across Agent/workspace, monotonic catalog revision and published snapshot immutability.
- [x] Task 3 — Add append-only Agent catalog migration if schema gaps remain (AC: 3, 8–9, 12–13)
- [x] Use MigrationAuthority only; leave previous migration source bytes/checksums untouched.
- [x] Add `catalog_revision` and immutable snapshot metadata where absent; add DB constraints/triggers preventing Published Agent Version/binding mutation and pointer rewind.
- [x] Preserve legacy rows honestly: mark migration-time observed snapshots if historical per-version provenance cannot be reconstructed.
- [x] Add fresh/current/replay/corrupt/rollback/version-aware schema guard tests.
- [x] Task 4 — Make registry Agent mutations transactional and CAS-safe (AC: 1–5, 8–10, 13)
- [x] Replace check-then-write methods with scoped transaction and `SELECT ... FOR UPDATE` on Agent row.
- [x] Validate expected revision token under lock for update summary, save bindings/policy, publish, unpublish, archive and delete.
- [x] `save_agent_catalog_config` must not update a Published version row. Editing after publish creates/uses current Draft and leaves Published snapshot unchanged.
- [x] Publish only current Draft; reject old/future/archived/unpublishable versions; same-version retry is idempotent only if exact state already committed.
- [x] Delete only never-published/no-history Agent if product keeps hard delete; otherwise convert UI/API destructive path to archive.
- [x] Add 32-way race tests for save/publish/unpublish/archive/delete and assert no lost updates, pointer rewind, duplicate/gap revision or 5xx.
- [x] Task 5 — Validate exact Operation bindings and search policy in service/API (AC: 1–2, 5–7, 10–13)
- [x] Binding validation resolves every Operation Version by workspace and exact version, requires `Published`, rejects archived aggregate for new binding and returns non-disclosing errors.
- [x] Direct API cannot bypass UI: direct save/publish with Draft, disabled unknown Tool, duplicated `tool_name`, foreign ID or stale `operation_version` fails pre-mutation.
- [x] Search policy validates groups/result limit against the exact enabled snapshot and rejects reserved control tool names.
- [x] Admin DTOs include revision token/current `catalog_revision`; boundary errors map typed registry/service errors once and include safe request_id/trace_id.
- [x] Task 6 — Rework MCP catalog read/search/call to revision-bound snapshots (AC: 6–8, 10, 13)
- [x] `PublishedAgentCatalog` includes Agent ID, Agent Version and `catalog_revision`; direct `tools/list` returns deterministic pagination over that snapshot.
- [x] Search result/call path binds result to Agent Version/catalog revision and rejects stale result after a new publish.
- [x] Authorization and session lookup revalidate active key scope for workspace+Agent and cannot reuse stale catalog after key revocation.
- [x] All cache keys include workspace, Agent, Agent version, `catalog_revision`, access mode and authorization scope; Valkey/local cache loss reloads from PostgreSQL.
- [x] Add MCP tests for direct/search discovery, stale result, key revocation, cross-Agent endpoint, cache loss and no metadata leakage.
- [x] Task 7 — Update Admin Agent UI for explicit lifecycle and stale guards (AC: 4, 11, 13)
- [x] Show Draft version, latest Published version and `catalog_revision`; distinguish unpublished Draft from published snapshot.
- [x] Add a wizard/drawer-wide lifecycle mutex and async generation guard for workspace/Agent/revision before applying responses.
- [x] Add confirmation for publish/unpublish/archive/delete; disable conflicting buttons while mutation is in flight.
- [x] On 409/428, preserve unsaved local edits, show reload/review action and never auto-retry mutation.
- [x] Add RU/EN strings together; use live regions/focus management, keyboard-accessible controls and safe DOM sinks.
- [x] Task 8 — Performance, evidence, inventory and docs (AC: 12–13)
- [x] Add deterministic seed/helper for 200 Agents and 2 000 Operations and measure MCP discovery p95 ≤150 ms over declared warm-up/sample count.
- [x] Update `docs/admin-api.md`, `docs/mcp-interface.md`, `docs/data-model.md` and migration docs if schema changes.
- [x] Update `docs/capability-inventory.json` FR-4 entries only after accepted evidence; failed/flaky/skipped/not-run is not pass.
- [x] Keep metrics labels closed; request_id/trace_id must not be labels. Use typed metrics/exemplars only.
- [x] Task 9 — Final verification and handoff (AC: 13)
- [x] Run targeted core/registry/Admin/MCP tests for Agent catalog lifecycle and security matrix.
- [x] Run UI build and targeted Playwright Agent lifecycle specs if UI changed.
- [x] Run migration/config/metrics/boundary/capability/community-scope gates and final `just verify`.
- [x] Update Dev Agent Record, File List, Change Log and status to `done` only after gates pass.
### Review Findings
- [x] [Review][Patch] MCP catalog cache can serve stale published tools after unpublish/archive/republish because cache scope is only workspace slug + Agent slug [crates/crank-community-mcp/src/catalog.rs:23]
- [x] [Review][Patch] Agent publish silently rewrites exact Operation bindings to latest published Operation version instead of publishing the saved exact binding snapshot [apps/admin-api/src/service/agents.rs:507]
- [x] [Review][Patch] Agent mutation preconditions are checked before registry mutation and are optional for never-published Drafts, so concurrent stale writes can pass and overwrite state [apps/admin-api/src/routes/agents.rs:169]
- [x] [Review][Patch] Agent ETag does not cover mutable summary/binding/policy content and UI auto-fetches fresh ETags before mutating stale drawer state [apps/ui/js/api.js:105]
- [x] [Review][Patch] v9 immutable trigger suppresses allowed Draft deletes by returning `NEW` on DELETE and does not guard binding INSERT into published snapshots [crates/crank-registry/src/migrations/agent_catalog_lifecycle_v9.sql:15]
- [x] [Review][Patch] `unpublish_agent` and `archive_agent` do not validate current lifecycle state and can change archived/never-published Agents incorrectly [crates/crank-registry/src/postgres/agent.rs:562]
- [x] [Review][Patch] Never-published Agent delete is a service-level check-then-delete and can race with publish [apps/admin-api/src/service/agents.rs:383]
- [x] [Review][Patch] Published MCP catalog query does not filter joined Operation Versions to `published`, so corrupted/legacy bindings can expose Draft versions [crates/crank-registry/src/postgres/agent.rs:638]
- [x] [Review][Patch] Disabled Agent bindings bypass exact Published Operation Version validation but remain persisted in the catalog draft [apps/admin-api/src/service/agents.rs:627]
- [x] [Review][Patch] Agent summary/slug updates mutate current published endpoint identity without new Agent publication or catalog revision [apps/admin-api/src/service/agents.rs:358]
- [x] [Review][Patch] Direct MCP `tools/list` returns the full catalog and lacks the deterministic pagination required by AC6 [crates/crank-community-mcp/src/app.rs:814]
- [x] [Review][Patch] Published catalog load is not anchored in one consistent snapshot, so pointer/revision and tools can come from different commits [crates/crank-registry/src/postgres/agent.rs:638]
- [x] [Review][Patch] `published_agents` monotonic guard covers UPDATE only; direct DELETE+INSERT can bypass pointer/version monotonicity [crates/crank-registry/src/migrations/agent_catalog_lifecycle_v9.sql:63]
- [x] [Review][Patch] v9 schema guard checks trigger names only, not trigger event set/function semantics [crates/crank-registry/src/migrations/schema_guard_v9.rs:77]
- [x] [Review][Patch] Agent lifecycle UI lacks required publish/unpublish/archive confirmations and complete stale/loading/error RU/EN Playwright coverage [apps/ui/js/agents.js:626]
- [x] [Review][Patch] MCP stale search-result error uses `catalog_revision_changed` instead of the story contract code `agent_catalog_result_stale` [crates/crank-community-mcp/src/tool_search.rs:82]
- [x] [Review][Patch] Required performance evidence for 200 Agents / 2,000 Operations discovery p95 ≤150 ms is absent from implementation artifacts.
## Dev Notes
### Current State / Repository Findings
- `crates/crank-core/src/agent.rs` currently has `Agent`, `AgentVersion`, `AgentOperationBinding`, `ToolSelectionPolicy` and validation for direct/search policy. It does not model revision predicates, catalog revision, immutable publication snapshot rules or stale search-result identity.
- `apps/admin-api/src/service/agents.rs` currently:
- creates Agent version 1 as Draft;
- `ensure_editable_agent_version` clones current version only when `latest_published_version == current_draft_version`;
- `save_agent_catalog_config` updates `agent_versions.tool_selection_policy_json` and replaces bindings for the current version;
- `publish_agent` can rewrite bindings based on latest Operation version and then calls registry publish;
- `published_agent_bindings` silently skips missing/unpublished Operation bindings and upgrades to latest published Operation version instead of enforcing exact requested version.
- `crates/crank-registry/src/postgres/agent.rs` currently:
- calculates next Agent version before transaction and without row lock;
- saves bindings/policy without CAS or version-status protection;
- `publish_agent` upserts `published_agents` and marks version Published, allowing pointer rewrite semantics;
- `unpublish_agent`/`archive_agent` delete current published pointer and mutate current version status;
- `delete_agent` hard-deletes Agent rows.
- `crates/crank-community-mcp/src/catalog.rs` caches by `{workspace_slug, agent_slug}` only. Shared snapshot payload lacks Agent ID/version/revision/auth scope.
- MCP app reads `state.catalog.get_catalog(...)` for `tools/list` and `tools/call`. It already has request/trace context and typed execution failure paths from Stories 1.5/1.8; reuse them instead of adding ad-hoc errors.
- UI `apps/ui/js/agents.js` uses one drawer and `saveAgent()` chains create/update → save bindings → publish/archive/unpublish. It has `saving` guard but no revision token, no response-generation guard and no explicit Draft vs Published state.
- Existing Playwright `apps/ui/tests/e2e/agents.spec.js` covers demo cards and search UI smoke only. It does not prove immutable publication, stale conflict, unpublish/archive or real MCP behavior.
### Implementation Constraints
- Do not edit old migration bytes/checksums. Any durable schema change must be the next append-only MigrationAuthority version with schema guard and migration tests.
- Do not modify Operation lifecycle semantics except where Agent binding validation consumes exact Published Operation Versions.
- Do not introduce direct environment reads; new config, if any, goes through `crank-config`.
- Do not add dependencies/toolchain/MSRV changes unless the story explicitly records user approval. Prefer existing Rust crates and vanilla JS.
- Do not put user IDs, Agent IDs, Operation IDs, request_id, trace_id, URLs, tool names from user input or error text into Prometheus labels.
- PostgreSQL is correctness authority. Valkey/local cache is optional and rebuildable.
- Every workspace/Agent/capability access must include full scope; foreign object should not leak metadata.
- UI remains Alpine/vanilla JS with `window.Crank*` modules and existing build pipeline.
- New text must be RU and EN together.
### File Structure Notes
Likely UPDATE:
- `crates/crank-core/src/agent.rs`
- `crates/crank-registry/src/{model.rs,error.rs,lib.rs}`
- `crates/crank-registry/src/postgres/agent.rs`
- `crates/crank-registry/src/migrations/{authority.rs,schema_guard.rs}` and machine migration sequence docs if schema changes
- `crates/crank-registry/tests/integration/{agents_usage.rs,workspace_access.rs,migrations.rs,common.rs}`
- `apps/admin-api/src/{dto.rs,error.rs}`
- `apps/admin-api/src/routes/agents.rs`
- `apps/admin-api/src/service/agents.rs`
- `apps/admin-api/tests/integration/{operations_agents.rs,community_access_usage.rs,common.rs}` and/or new `agent_catalog.rs`
- `crates/crank-community-mcp/src/{catalog.rs,app.rs,tool_search.rs,tool_resolution.rs,transport.rs}` as required
- `apps/mcp-server/tests/integration/{catalog_access.rs,tool_search.rs,transport_protocol.rs}`
- `apps/ui/js/{agents.js,api.js,i18n.js,ui-feedback.js}` and `apps/ui/html/agents.html` / CSS as needed
- `apps/ui/tests/e2e/agents.spec.js` or new `agent-catalog.spec.js`
- `docs/{admin-api.md,mcp-interface.md,data-model.md,capability-inventory.json}`
Likely NEW:
- Next migration SQL, only if required, e.g. `crates/crank-registry/src/migrations/agent_catalog_vN.sql`
- `apps/admin-api/tests/integration/agent_catalog.rs`
- `apps/ui/tests/e2e/agent-catalog.spec.js`
Do not touch:
- Previous migration source bytes/checksums.
- Operation YAML/import/export internals except evidence linkage.
- Approval execution state machine.
- Deployment topology unless a new config field is deliberately introduced.
### Required Test Matrix
P0 registry/PostgreSQL:
- publish creates immutable Agent Version + exact binding snapshot + monotonic `catalog_revision`;
- save after publish leaves prior Published snapshot byte/semantic equivalent;
- publish old/future/archived/non-current Draft rejected or idempotent only under exact state;
- direct SQL cannot mutate/delete Published Agent Version/binding snapshot or rewind pointer;
- 32 concurrent save/publish/archive/unpublish attempts produce typed conflicts, no lost update/5xx;
- exact binding rejects Draft Operation, missing version, foreign workspace and archived aggregate for new binding.
P0 Admin API:
- all Agent mutations require current revision token;
- stale revision returns `agent_stale_revision`/precondition code with request_id/trace_id;
- direct API cannot bypass UI validation;
- unpublish/archive stop new MCP access while preserving versions/history;
- cross-workspace Agent/Operation/key requests are default-deny without metadata leakage.
P0 MCP:
- direct mode `tools/list` and `tools/call` see only published snapshot tools;
- Agent A key cannot discover/call Agent B tool;
- search mode result becomes stale after republish and cannot call removed/replaced tool;
- key revocation invalidates discovery/call/session-cache path;
- cache loss/stale local/shared snapshot falls back to PostgreSQL and preserves correctness;
- pagination/deterministic ordering stable across repeated calls.
P1 UI:
- RU/EN Agent drawer shows Draft/Published version and catalog revision;
- edit/bind/publish/unpublish/archive loading and confirmation states;
- stale 409/428 preserves edits and offers reload/review;
- workspace switch/stale response does not overwrite current drawer;
- keyboard/focus/live-region behavior is usable and external values use safe DOM sinks.
Performance:
- seed 200 Agents / 2 000 Operations;
- measure direct and search discovery p95 after warm-up with fixed sample count;
- pass threshold: ≤150 ms p95 on Reference Deployment. Non-reference local result is diagnostic only.
### Suggested Verification Commands
```bash
cargo test -p crank-core agent -- --test-threads=1
cargo test -p crank-registry --test integration agents_usage -- --test-threads=1
cargo test -p crank-registry --test integration workspace_access -- --test-threads=1
cargo test -p crank-registry --test integration migrations -- --test-threads=1
cargo test -p admin-api --test integration agent_catalog -- --test-threads=1
cargo test -p admin-api --test integration operations_agents -- --test-threads=1
cargo test -p mcp-server --test integration catalog_access -- --test-threads=1
cargo test -p mcp-server --test integration tool_search -- --test-threads=1
cd apps/ui && npm run build
cd apps/ui && npx playwright test tests/e2e/agent-catalog.spec.js --project=chromium
just migration-contract-check
just rust-boundaries
just capability-inventory-check
python3 scripts/check-community-scope.py --root . --files <every NEW/UPDATE path>
just verify
```
If a command is impossible in the current container, record exact blocker and do not mark related task complete.
### Previous Story Intelligence
- Story 1.7 established the correct model for immutable Operation lifecycle: published exact snapshots are not mutable, archive changes aggregate availability only, and stale mutation protection is mandatory. Reuse the concept, but do not assume Agent already has the same protection.
- Story 1.8 established typed execution failure taxonomy. MCP catalog errors should project through existing typed paths and not add arbitrary ad-hoc machine codes.
- Story 1.9 established outbound correctness; Agent catalog must not bypass runtime/outbound admission.
- Stories 1.10–1.12 established credential/session revocation. Agent key revocation must be observed by MCP discovery/call and cache/session paths.
### References
- `_bmad-output/planning-artifacts/epics.md` — Epic 1 objective; Story 1.13 AC; FR-4.
- `_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md` — glossary, FR-4, NFR-P3/P4/P5, NFR-S1/S2/S4, release gates.
- `_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md` — AD-1, AD-2, AD-4, AD-11, AD-13, AD-16, AD-19, AD-20, AD-21, AD-22, AD-23.
- `_bmad-output/test-artifacts/test-design-progress.md` — E1-R-011, E1-29, E1-30, E1-31.
- `_bmad-output/project-context.md` — Rust/UI/testing/community/migration guardrails.
- `_bmad-output/implementation-artifacts/1-7-immutable-lifecycle-operation.md` — Operation immutable snapshot decisions and review lessons.
- `_bmad-output/implementation-artifacts/1-12-admin-bootstrap-login-session-lifecycle.md` — Admin auth/session/key revocation foundation for Agent UI/API access.
## Dev Agent Record
### Agent Model Used
GPT-5 Codex
### Debug Log References
- 2026-08-22T12:12:34+03:00 — Created Story 1.13 from sprint backlog using BMAD create-story workflow and repo reconnaissance.
- 2026-08-22T12:12:34+03:00 — Started implementation under BMAD dev-story workflow. Baseline commit `767428436d3a54e60809a727044dfcec48e1f1dd`; worktree already contains prior story changes, preserve unrelated diffs.
- 2026-08-22T12:20+03:00 — RED confirmed: registry `published_agent_snapshot_remains_immutable_after_draft_edit` and `stale_agent_revision_rejects_mutation` failed because Published Agent Version could be edited in place.
- 2026-08-22T12:24+03:00 — RED confirmed: Admin `binding_requires_exact_published_operation_version` and `stale_agent_revision_rejects_mutation` failed with HTTP 200 for Draft binding/missing Agent precondition.
- 2026-08-22T12:31+03:00 — GREEN slice: registry rejects Published Agent Version mutation; Admin rejects Draft Operation binding and requires precondition after Agent publication; MCP catalog revision includes publish timestamp so stale search result after unpublish/republish is rejected.
- 2026-08-22T12:39+03:00 — Targeted checks passed: `cargo test -p crank-registry --test integration agents_usage:: -- --test-threads=1`, `cargo test -p admin-api --test integration agent_catalog:: -- --test-threads=1`, `cargo test -p admin-api --test integration operations_agents:: -- --test-threads=1`, `cargo test -p mcp-server --test integration catalog_access:: -- --test-threads=1`, `cargo test -p mcp-server --test integration tool_search:: -- --test-threads=1`, `cargo fmt --all --check`.
- 2026-08-22T12:57+03:00 — Added append-only migration v9 `agent-catalog-lifecycle-v9`: durable `catalog_revision`, DB triggers rejecting direct Published Agent Version/binding mutation and catalog pointer non-increase/rewind.
- 2026-08-22T13:03+03:00 — Targeted checks passed after v9: `just migration-contract-check` => `contract_current`; `cargo test -p crank-registry --test integration migrations:: -- --test-threads=1` => 23 passed; `cargo test -p crank-registry --test integration agents_usage:: -- --test-threads=1` => 7 passed; `cargo test -p admin-api --test integration agent_catalog:: -- --test-threads=1` => 2 passed; `cargo test -p admin-api --test integration operations_agents:: -- --test-threads=1` => 7 passed; `cargo test -p mcp-server --test integration catalog_access:: -- --test-threads=1` => 20 passed; `cargo test -p mcp-server --test integration tool_search:: -- --test-threads=1` => 2 passed.
- 2026-08-22T14:05+03:00 — Final implementation verification passed: `just verify` succeeded after updating v9 migration/version oracles and the closed metrics route registry for `/api/auth/session/csrf`; `git diff --check` passed.
- 2026-08-22T18:46+03:00 — Code review patch pass closed all 17 accepted findings: exact Agent publish bindings, mandatory If-Match/CAS, v9 trigger/schema-guard hardening, PostgreSQL-backed MCP catalog refresh, direct `tools/list` pagination, UI confirmations/stale behavior, and 200 Agent / 2,000 Operation performance evidence. Final `just verify` passed.
### Completion Notes List
- Implemented immutable Agent catalog foundation: Published Agent Versions and binding snapshots are immutable, Draft edits require revision preconditions, Agent publish creates durable monotonic `catalog_revision`, and stale Admin/UI/MCP search paths reject safely.
- Enforced binding correctness: Agent bindings accept exact Published Operation Versions only; Draft/foreign/archived invalid references are rejected without relying on UI-only validation.
- Added UI evidence for Agent catalog revision display, serialized lifecycle actions and localized stale conflict recovery; fixed Playwright proxy host handling used by the local UI harness.
- Updated docs and Capability Inventory evidence for FR-4 without marking broader Agent UX as fully qualified.
- Final verification is green: targeted registry/Admin/MCP/UI tests, migration and metrics contracts, full `just verify`, and `git diff --check`.
- Code review findings are resolved and checked off; Story 1.13 is moved from `review` to `done`.
### File List
- `_bmad-output/implementation-artifacts/1-13-immutable-agent-catalog.md`
- `_bmad-output/implementation-artifacts/sprint-status.yaml`
- `crates/crank-registry/src/error.rs`
- `crates/crank-registry/src/model.rs`
- `crates/crank-registry/src/migrations.rs`
- `crates/crank-registry/src/migrations/agent_catalog_lifecycle_v9.rs`
- `crates/crank-registry/src/migrations/agent_catalog_lifecycle_v9.sql`
- `crates/crank-registry/src/migrations/authority.rs`
- `crates/crank-registry/src/migrations/authority_tests.rs`
- `crates/crank-registry/src/migrations/schema_guard.rs`
- `crates/crank-registry/src/migrations/schema_guard_v9.rs`
- `crates/crank-registry/src/postgres/agent.rs`
- `crates/crank-registry/src/postgres/agent_catalog.rs`
- `crates/crank-registry/tests/integration/agents_usage.rs`
- `crates/crank-registry/tests/integration/common.rs`
- `crates/crank-registry/tests/integration/migrations.rs`
- `docs/schemas/migration-sequence.json`
- `docs/schemas/metrics-registry-v1.json`
- `apps/admin-api/src/error.rs`
- `apps/admin-api/src/routes/agents.rs`
- `apps/admin-api/src/service/agents.rs`
- `apps/admin-api/src/service/demo.rs`
- `apps/admin-api/tests/integration.rs`
- `apps/admin-api/tests/integration/agent_catalog.rs`
- `apps/admin-api/tests/integration/operations_agents.rs`
- `apps/admin-api/tests/migration_command.rs`
- `crates/crank-community-mcp/src/tool_search.rs`
- `crates/crank-community-mcp/src/app/request.rs`
- `crates/crank-community-mcp/src/app/response.rs`
- `apps/mcp-server/tests/integration/catalog_access.rs`
- `apps/mcp-server/tests/integration/tool_search.rs`
- `apps/ui/js/agents.js`
- `apps/ui/scripts/playwright-ui-server.js`
- `apps/ui/tests/e2e/agents.spec.js`
- `docs/admin-api.md`
- `docs/data-model.md`
- `docs/mcp-interface.md`
- `docs/capability-inventory.json`
- `docs/capability-baseline/manifest.json`
- `crates/crank-metrics/src/schema.rs`
- `crates/crank-metrics/tests/schema_v1.rs`
## Change Log
- 2026-08-22 — Created Story 1.13 from Epic 1 FR-4 with Agent catalog immutability, MCP snapshot/cache, UI lifecycle and performance context.
- 2026-08-22 — Closed post-review patch pass and moved Story 1.13 to `done` after final `just verify`.