Skip to content

Self-improving AI Employees for everyone

docs: reflect credentials refactor (Wave 13)

trohitg20d756ab0a50
diff --git a/CLAUDE.md b/CLAUDE.md
index c9f92f57..bd303090 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5141,7 +5141,7 @@ This function:
- **Temporal Activity Heartbeats**: Activities send `activity.heartbeat()` on every non-matching WebSocket broadcast inside the read loop in `services/temporal/activities.py`. This keeps long-running DeepAgent and browser operations alive past the 2-minute `heartbeat_timeout`. Start/end heartbeats alone were causing `TIMEOUT_TYPE_HEARTBEAT` failures on ops taking 5-10 minutes. Connection config: `heartbeat=30`, `receive_timeout=540` (fits within 10-min `start_to_close_timeout`).
- **WebSocket `_safe_send` Guard**: `server/routers/websocket.py` checks `websocket.client_state.name != "CONNECTED"` before sending and logs at `debug` level (not `error`) on failure. Prevents "ASGI message after websocket.close" errors when broadcasts race with disconnects.
- **Claude Code CLI Flag**: `server/services/claude_code_service.py` uses `--max-budget-usd <amount>` (previously incorrectly `--max-cost`, which caused "unknown option" errors on every run).
-- **Persisted-prefix cache contract**: `PersistQueryClientProvider` hydrates entries with the QueryClient's *default* options, so any prefix in `PERSISTED_KEY_PREFIXES` (`client/src/lib/queryPersist.ts`) MUST also have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in `client/src/lib/queryClient.ts`. Per-call options don't apply on hydration. Canonical set: `nodeSpec`, `nodeGroups`, `credentialValues`, `skillContent`. `credentialCatalogue` has its own `idb-keyval` warm-start path so it is intentionally not in either list.
+- **Persisted-prefix cache contract**: `PersistQueryClientProvider` hydrates entries with the QueryClient's *default* options, so any prefix in `PERSISTED_KEY_PREFIXES` (`client/src/lib/queryPersist.ts`) MUST also have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in `client/src/lib/queryClient.ts`. Per-call options don't apply on hydration. Canonical set: `nodeSpec`, `nodeGroups`, `skillContent`. `credentialValues` was previously persisted here but was removed per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — decrypted API keys must never live in `localStorage`. The in-memory TanStack Query cache (`gcTime: ∞`) keeps the credentials form populated for the session lifetime; on reload the panel refetches via WS. `credentialCatalogue` has its own `idb-keyval` warm-start path so it is intentionally not in either list.
- **WebSocket `sendRequest` replay queue**: when the socket is not open, requests enqueue with `AbortController`-backed per-request timeouts (default 30s) and replay on reconnect inside `ws.onopen` before `setIsReady(true)`. Queue capped at 200 with FIFO eviction. Intentional close (`event.code === 1000`) drops the queue; transient closes preserve it. Eliminates indefinite spinners during the 3s reconnect window. Implementation in `client/src/contexts/WebSocketContext.tsx` (`pendingSendQueueRef` + `drainPendingSends`).
- **`currentWorkflowId` single source**: lives in `useAppStore.currentWorkflow.id` only. Non-React listeners (WS handlers) read via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from one `useEffect` in `Dashboard.tsx`. Removed the prior `currentWorkflowIdRef` mirror inside WebSocketContext that misrouted broadcasts during workflow switches.
- **Execution correlation IDs**: `handle_execute_node` issues a `uuid4().hex` token at request entry, propagates it through every `node_status` / `node_output` broadcast for the run, and returns it in the response payload as `execution_id`. Frontend `ExecutionResult.executionId` carries it; `OutputSection` dedups runs by it instead of `JSON.stringify(outputs)` (which collapsed distinct executions whose payloads matched). Same trace-id pattern as OpenTelemetry / HTTP request ids.
@@ -5156,4 +5156,5 @@ This function:
- **Auto-derived `isConfigNode` uiHint**: `_derive_auto_ui_hints(group)` in `services/plugin/base.py` automatically sets `uiHints.isConfigNode: True` on any plugin whose `group` tuple contains `memory` or `tool` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`). Explicit `cls.ui_hints` always wins (merge order: auto first, then `dict.update`). Frontend `InputSection.tsx` and `OutputPanel.tsx` consume the flag via `definition?.uiHints?.isConfigNode === true` — the old `groups.includes('memory') || groups.includes('tool')` heuristic is gone. Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name. Adding a new auxiliary node type costs zero per-plugin code; opting out costs one line (`ui_hints = {"isConfigNode": False}`).
- **`isMasterSkillEditor` uiHint replaces `node.type === 'masterSkill'` checks**: 6 frontend callsites (`Dashboard.tsx:98` component dispatch, `useAutoSkillEdges.ts` constant + edge filter, `MiddleSection.tsx` × 3) now read `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true` instead of comparing the type string. The `MasterSkillNode` plugin already declared the hint — no backend change. Renaming the plugin's `type` is now a single backend edit followed by a NodeSpec deploy; the frontend never needs to know the string.
- **`--action-X-hover` triplet + ActionButton zero-arithmetic**: each of the 6 action roles (`run`/`stop`/`save`/`config`/`secret`/`tools`) now exposes a `-hover` variant (0.25 alpha) alongside the existing `-soft` (0.15) and `-border` (0.6). ActionButton's CVA reads `hover:bg-action-X-hover` directly; disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class. No per-token `/25`, `/40`, `/10` opacity arithmetic at any call site. Credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`) and the skill / tool-schema editors (`SkillEditorModal`, `ToolSchemaEditor`) consume `<ActionButton intent="...">` directly. `ActionDef` carries an `intent` key; the catalogue adapter maps server-sent `theme_color` palette strings to intents via `SERVER_COLOR_TO_INTENT`.
+- **Credentials: DB as single source of truth + symmetric broadcasts + cache dedup**: `CredentialsDatabase` (encrypted SQLite) is canonical; every other layer is a derived cache with explicit invalidation. Backend `AuthService._memory_cache + _models_cache` collapsed into one `_api_key_cache: Dict[str, ApiKeyCacheEntry]` dataclass — single write/evict site. Per RFC 9700 (OAuth 2.0 BCP, 2024) the `_oauth_cache` no longer carries `refresh_token`; new `get_oauth_refresh_token(provider, customer)` reads from the encrypted DB on every call. `validate_api_key`, `save_api_key`, `delete_api_key`, `twitter_logout`, `google_logout` now broadcast symmetrically: `update_api_key_status` (in-memory map) + `broadcast_credential_event(...)` (refetch signal) wrapping `WorkflowEvent` (CloudEvents v1.0 from `services/events/envelope.py`, the same envelope the Wave 12 EventSource framework uses). The dead-letter `credential_catalogue_updated` event is finally emitted by the backend. Frontend retired the 200-LOC `client/src/components/credentials/providers.tsx` static fallback — `useCatalogueQuery` is the only source; cold-boot renders `<Skeleton>`, server-unreachable shows an explicit error state. `ApiKeyStatus.hasKey` mirror dropped (duplicated catalogue's `provider.stored`); two new selector hooks (`useProviderStored`, `useStoredProviderCount`) read the catalogue. Pytest invariant `test_credential_broadcasts.py` (14 tests) locks the broadcast contract via `inspect.getsource` introspection + the CloudEvents v1.0 envelope shape + AuthService DB-write-then-cache-update ordering + the no-refresh-token-in-cache rule.
- never use emojis in prints
\ No newline at end of file
diff --git a/docs-internal/credentials_panel.md b/docs-internal/credentials_panel.md
index 2e332967..76418231 100644
--- a/docs-internal/credentials_panel.md
+++ b/docs-internal/credentials_panel.md
@@ -60,7 +60,7 @@ backend handle_validate_api_key (websocket.py:990):
-> ai_service.fetch_models(provider, key) // hits provider /v1/models endpoint
-> auth_service.store_api_key(provider, key, models, session_id='default')
-> credentials_db.save_api_key -> EncryptionService.encrypt -> EncryptedAPIKey row
- -> _memory_cache[session_id_provider] = key
+ -> _api_key_cache[session_id_provider] = ApiKeyCacheEntry(key=..., models=[...])
-> broadcaster.update_api_key_status(provider, valid=True, has_key=True, models=[...])
-> return {valid: True, models: [...]}
Frontend resolves Promise:
@@ -314,8 +314,8 @@ All handlers registered in [server/routers/websocket.py](../server/routers/webso
### 4.2 Single point of access
All credential reads/writes go through [`AuthService`](../server/services/auth.py):
- API keys: `store_api_key(provider, api_key, models, session_id='default')` / `get_api_key(provider, session_id)` / `remove_api_key(provider, session_id)` / `get_stored_models(provider, session_id)`.
-- OAuth tokens: `store_oauth_tokens(provider, access, refresh, email=None, name=None, scopes=None, customer_id='owner')` / `get_oauth_tokens(provider, customer_id)` / `remove_oauth_tokens(provider, customer_id)`.
-- Memory caches: `_memory_cache` (API keys), `_models_cache` (models lists), `_oauth_cache` (OAuth tokens). All hit BEFORE the encrypted DB. `clear_cache()` empties all three (called on logout).
+- OAuth tokens: `store_oauth_tokens(provider, access, refresh, email=None, name=None, scopes=None, customer_id='owner')` / `get_oauth_tokens(provider, customer_id)` / `remove_oauth_tokens(provider, customer_id)` / `get_oauth_refresh_token(provider, customer_id)` (DB-only — see RFC 9700 below).
+- Memory caches: `_api_key_cache: Dict[str, ApiKeyCacheEntry]` (decrypted API keys + models in one dataclass entry per `{session}_{provider}`) and `_oauth_cache` (access tokens + display fields only). Both hit BEFORE the encrypted DB; `clear_cache()` empties both (called on logout). Per RFC 9700 (OAuth 2.0 BCP, 2024) the `_oauth_cache` does NOT carry `refresh_token` — refresh tokens are long-lived secrets and must not live in process memory; `get_oauth_refresh_token()` reads from the encrypted DB on every call. Pre-Wave-12 the cache was split into `_memory_cache` (key) + `_models_cache` (models) sharing the same key shape with no shared invalidation; now collapsed into one entry so the two values can never drift.
### 4.3 Two-table split
@@ -345,7 +345,7 @@ Provider × table examples:
These are the non-negotiable behaviours the test suite enforces. The refactor is acceptable iff every test in [server/tests/credentials/](../server/tests/credentials) and [client/src/test/](../client/src/test) still passes without modification.
-1. **WebSocket message types** for save/validate/delete/get of any API key are exactly `validate_api_key` / `save_api_key` / `get_stored_api_key` / `delete_api_key`, with payload shape `{provider, api_key, [session_id], [models]}`. The response of `get_stored_api_key` exposes `has_key` (snake_case) and the WebSocketContext maps it to `hasKey`.
+1. **WebSocket message types** for save/validate/delete/get of any API key are exactly `validate_api_key` / `save_api_key` / `get_stored_api_key` / `delete_api_key`, with payload shape `{provider, api_key, [session_id], [models]}`. The response of `get_stored_api_key` exposes `hasKey` (camelCase post-Wave-12; the WebSocketContext consumes it directly). Note: `ApiKeyStatus.hasKey` was retired on the frontend — "is stored" comes from the catalogue's `provider.stored` flag via `useProviderStored(id)` (single source of truth).
2. **OAuth login flows** never expose `client_secret` in the rendered DOM after save — the input is replaced by a "Configured" indicator.
3. **Google tokens** are read exclusively via `auth_service.get_oauth_tokens('google')`. No call site uses `get_api_key('google_access_token')` or any equivalent.
4. **Email** with `email_provider='custom'` writes BOTH `email_imap_*` and `email_smtp_*` keys (host + port + encryption for each side). With any other provider, those keys MUST NOT be written.
diff --git a/docs-internal/credentials_scaling/architecture.md b/docs-internal/credentials_scaling/architecture.md
index 374073b8..32ddf6cf 100644
--- a/docs-internal/credentials_scaling/architecture.md
+++ b/docs-internal/credentials_scaling/architecture.md
@@ -279,9 +279,9 @@ MachinaOs uses JSON for all backend config (`email_providers.json`, `llm_default
refactor cherry-picked on top. No changes to main until verified.
2. **Original import site preserved**: `client/src/components/CredentialsModal.tsx`
remains a 1-line re-export. All existing usages unchanged.
-3. **Backwards-compatible YAML**: can serve the current 20 providers from YAML while
+3. **Backwards-compatible YAML**: ~~can serve the current 20 providers from YAML while
the old `providers.tsx` is still present. Flip the switch when the YAML path is
- proven. Delete `providers.tsx` only after manual verification.
+ proven. Delete `providers.tsx` only after manual verification.~~ **DONE (Wave 12 follow-up)** — `providers.tsx` deleted; the server-driven catalogue (`server/config/credential_providers.json` → `useCatalogueQuery`) is the single source of truth. Cold-boot renders a `<Skeleton>` palette; server-unreachable shows an explicit error state.
4. **Feature flag** (optional): `VITE_USE_YAML_CREDENTIALS=true` — gates the new
Zustand store fetch vs the old inline array. Enables A/B testing in dev.
5. **No main branch touches** until the full verification checklist passes.
@@ -296,7 +296,7 @@ section "Critical files to modify/create" for the exhaustive list.
Summary:
- **New**: 9 files (3 research MDs, 1 YAML, 4 Python, 2 TypeScript stores, 1 palette, 1 schema helper)
- **Modified**: 8 files (worktree credentials module + package.json + CLAUDE.md)
-- **Deleted**: 1 file (`credentials/providers.tsx` after YAML migration verified)
+- **Deleted**: 1 file (`credentials/providers.tsx`) — done in Wave 12 follow-up commit `c94a610`. Server-driven catalogue is now the single source of truth.
---
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index aaf1d9bf..146a62c1 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -368,14 +368,16 @@ components/credentials/CredentialsModal.tsx
- **TanStack Query** owns the server state (catalogue, usage summaries, etc).
- **idb-keyval** cache seeds first paint — opened modal renders from IndexedDB in <50 ms before the WS roundtrip completes.
- **`requestIdleCallback`** writes back to IDB so saves don't block first paint.
+- **DB is the single source of truth.** The retired `client/src/components/credentials/providers.tsx` static fallback is gone — `useCatalogueQuery` is the only source. Cold-boot with no IDB cache renders a `<Skeleton>` palette while the WS catalogue arrives; server-unreachable shows an explicit error state, never stale fallback data.
+- **`provider.stored` is the canonical "do we have a credential for X?".** The retired `apiKeyStatuses[id].hasKey` mirror duplicated this answer with no synchronisation contract. Two new selector hooks (`useProviderStored(id)`, `useStoredProviderCount()`) read the catalogue. `apiKeyStatuses[id]` now narrowly carries the validation result (`valid`, `models`, `message`, `timestamp`).
-**App-wide query persistence ([client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts)):** the QueryClient is wrapped in `<PersistQueryClientProvider>` ([main.tsx](../client/src/main.tsx)) with a localStorage persister + `__APP_VERSION__` buster + 24h SWR window. Only queries with key prefixes `nodeSpec` / `nodeGroups` / `pluginCatalogue` are dehydrated -- high-frequency / per-session queries stay in-memory. Hard refresh paints from cached specs **before** the WebSocket connects, so canvas nodes never flash placeholder icons. The credentials catalogue uses its own dedicated `idb-keyval` warm-start (above) because its payload is large enough that localStorage's 5-10MB cap is a real constraint.
+**App-wide query persistence ([client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts)):** the QueryClient is wrapped in `<PersistQueryClientProvider>` ([main.tsx](../client/src/main.tsx)) with a localStorage persister + `__APP_VERSION__` buster + 24h SWR window. Only queries with key prefixes `nodeSpec` / `nodeGroups` / `skillContent` are dehydrated -- high-frequency / per-session queries stay in-memory. Hard refresh paints from cached specs **before** the WebSocket connects, so canvas nodes never flash placeholder icons. The credentials catalogue uses its own dedicated `idb-keyval` warm-start (above) because its payload is large enough that localStorage's 5-10MB cap is a real constraint. **Decrypted credential values are NOT persisted** (was the retired `'credentialValues'` prefix) per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — plaintext API keys in `localStorage` are readable via DevTools on shared / compromised browsers; the in-memory TanStack Query cache (`gcTime: ∞`) keeps the form populated for the session lifetime, on reload the panel refetches via WS.
**`useNodeSpec` is a slice subscription, not a `useQuery`** ([client/src/lib/nodeSpec.ts](../client/src/lib/nodeSpec.ts)): reads via `useSyncExternalStore` filtered by `hashKey(['nodeSpec', type])`. Per-spec observer count is **0**; only the matching slot triggers a re-render. Lazy fetch is one-shot via `useEffect` gated on `isReady`. Do not re-introduce `useQuery(['nodeSpec', type])` -- N consumers create N observers, all woken on every cache write.
**Slice-subscribed cache entries MUST set `gcTime: GC_TIME.FOREVER`.** Slice subscribers don't register as TanStack observers, so without this override the cache entry is garbage-collected after the default `gcTime` (5 min) and every consumer reads `undefined`. The user-visible regression is "canvas nodes lose their icons / handles after idle." Applies to `fetchNodeSpec`, `fetchNodeGroups`, and the `useNodeGroups` `useQuery`; the persistor in `lib/queryPersist.ts` only handles cross-reload survival.
-**Anchor cache contracts at the prefix root via `setQueryDefaults`, not per-call options.** `PersistQueryClientProvider` hydrates entries from localStorage with the QueryClient's *default* options, so per-call `staleTime: FOREVER` does not stop `gcTime: 5min` eviction on hydration. Every persisted prefix must have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in [client/src/lib/queryClient.ts](../client/src/lib/queryClient.ts). The current canonical set is `['nodeSpec']`, `['nodeGroups']`, `['credentialValues']`, `['skillContent']`. The persistor whitelist in [client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts) must mirror it; a string in the whitelist that doesn't match a real query key (the prior `'pluginCatalogue'` typo) is silently dead. `credentialCatalogue` is intentionally NOT in either list -- it has its own `idb-keyval` warm-start.
+**Anchor cache contracts at the prefix root via `setQueryDefaults`, not per-call options.** `PersistQueryClientProvider` hydrates entries from localStorage with the QueryClient's *default* options, so per-call `staleTime: FOREVER` does not stop `gcTime: 5min` eviction on hydration. Every persisted prefix must have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in [client/src/lib/queryClient.ts](../client/src/lib/queryClient.ts). The current canonical set is `['nodeSpec']`, `['nodeGroups']`, `['skillContent']`. The persistor whitelist in [client/src/lib/queryPersist.ts](../client/src/lib/queryPersist.ts) must mirror it; a string in the whitelist that doesn't match a real query key (the prior `'pluginCatalogue'` typo) is silently dead. `credentialCatalogue` is intentionally NOT in either list — it has its own `idb-keyval` warm-start. `credentialValues` keeps `gcTime: FOREVER` for the in-memory cache so the credentials form survives idle, but it is intentionally NOT persisted (OWASP — see "Persistence layers" above).
**Component rules:**
- `PanelRenderer` lazy-loads each panel type so the initial JS payload doesn't grow linearly with provider count.
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index ed27b5a0..779a209f 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -574,9 +574,12 @@ The frontend identifies plugin commands by **WebSocket message type**
strings (`telegram_connect`, `telegram_status`, …). Moving the handler
implementation between Python files is invisible to the frontend so
long as the registered keys stay the same. The
-`credential_providers.json` declarative config and the
-`credentials/providers.tsx` registry are likewise stable across
-backend reorganisations.
+`server/config/credential_providers.json` declarative config — served
+to the frontend via `handle_get_credential_catalogue` and consumed by
+`useCatalogueQuery` — is likewise stable across backend reorganisations.
+(The pre-Wave-13 `client/src/components/credentials/providers.tsx`
+static fallback no longer exists; the server catalogue is the single
+source of truth for the credentials panel.)
This is why the telegram refactor changed zero frontend code despite
moving 754 lines out of `services/telegram_service.py`.
diff --git a/docs-internal/status_broadcaster.md b/docs-internal/status_broadcaster.md
index 82da0fb2..c45c9beb 100644
--- a/docs-internal/status_broadcaster.md
+++ b/docs-internal/status_broadcaster.md
@@ -136,7 +136,8 @@ Broadcasts are sent to all connected clients without a request-response correlat
| `variable_update` | Single variable changes | `{name, value}` |
| `variables_update` | Batch variable update | `{variables: Dict}` |
| `workflow_status` | Workflow start / progress / complete | `{executing, current_node, progress}` |
-| `api_key_status` | Credential validation result | `{provider, valid, models}` |
+| `api_key_status` | Credential validation result; also fired by `delete_api_key` to clear `apiKeyStatuses[provider]` | `{provider, data: {valid, hasKey, models, message, timestamp}}` |
+| `credential_catalogue_updated` | Credential mutation (save / delete / oauth-disconnect) — wraps `WorkflowEvent` (CloudEvents v1.0) from `services/events/envelope.py`. Outer `type` stays this string for FE back-compat; body's `type` follows `credential.<area>.<action>` (e.g. `credential.api_key.saved`). Frontend `WebSocketContext` invalidates `useCatalogueQuery` via the 300 ms `invalidateCatalogue` debounce. | `{specversion: "1.0", id, source: "machinaos://services/credentials", type, subject: provider, time, data: {provider, customer_id?}}` |
| `node_parameters_updated` | Parameters saved by another client | `{node_id, parameters}` |
| `token_usage_update` | AI execution updates token counters | `{session_id, data: {total, threshold, needs_compaction}}` |
| `compaction_starting` | Memory compaction begins | `{session_id, node_id}` |
diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.md
index beb5c268..f38a2d01 100644
--- a/docs-internal/ui_migration_plan.md
+++ b/docs-internal/ui_migration_plan.md
@@ -266,6 +266,40 @@ Closes the surviving pre-Wave-11 tribal patterns and the perf hotspots six paral
- Canvas animations have no light/dark branch and no hardcoded hexes. The `colors` arg coming from `theme.ts` carries everything.
- Catalogue invalidation has one debounced funnel; broadcast handlers don't call `queryClient.invalidateQueries` directly.
+## Wave 13 — Credentials: DB as single source of truth + symmetric broadcasts + cache dedup (May 2026)
+
+Driven by three sub-agent audits (broadcast asymmetry, duplicated caches, parallel sources of truth) plus a research pass against modern (2024–2025) standards (OWASP, RFC 9700, CloudEvents 1.0). Plan: [`.claude/plans/properly-fix-the-tech-dreamy-tarjan.md`](../../.claude/plans/properly-fix-the-tech-dreamy-tarjan.md). Commit `c94a610`. 17 files changed, +698 / -308.
+
+| Section | What it delivers | Where |
+|---|---|---|
+| A — Symmetric broadcasts (CloudEvents v1.0) | New `broadcaster.broadcast_credential_event(type, *, provider, customer_id)` helper wraps `WorkflowEvent` from `services/events/envelope.py` (the same envelope the Wave 12 EventSource framework uses). `handle_save_api_key` → `credential.api_key.saved`. `handle_delete_api_key` → BOTH `update_api_key_status(valid=False, has_key=False)` (clears `apiKeyStatuses[provider]`) AND `credential.api_key.deleted` (catalogue refetch). `handle_twitter_logout` + `handle_google_logout` → `credential.oauth.disconnected`. The dead-letter `credential_catalogue_updated` event the frontend already handled is finally emitted. | `services/status_broadcaster.py`, `routers/websocket.py`, `services/events/envelope.py` (reused) |
+| B — Backend cache dedup | `AuthService._memory_cache + _models_cache` collapsed into a single `_api_key_cache: Dict[str, ApiKeyCacheEntry]` dataclass — one write site, one evict site, no drift path. Per RFC 9700 (OAuth 2.0 BCP 2024) the `_oauth_cache` no longer carries `refresh_token`; new `get_oauth_refresh_token(provider, customer)` reads from the encrypted DB on every call. All 5 callers migrated (`routers/twitter.py`, `routers/websocket.py` × 2, `services/handlers/google_auth.py`). `ws_handler` decorator now uses `functools.wraps` so `__wrapped__` is set (enables introspection-based tests). | `services/auth.py`, `routers/{twitter,websocket}.py`, `services/handlers/google_auth.py` |
+| C — Frontend SoT + OWASP | Deleted 200-LOC `client/src/components/credentials/providers.tsx` static fallback — `useCatalogueQuery` is the only source. Cold-boot renders `<Skeleton>`; server-unreachable shows explicit error state. Dropped `ApiKeyStatus.hasKey` (duplicated catalogue's `provider.stored` with no synchronisation contract); two new selector hooks `useProviderStored(id)` + `useStoredProviderCount()` read the catalogue. **OWASP fix**: `'credentialValues'` removed from `PERSISTED_KEY_PREFIXES` per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — decrypted API keys must not live in `localStorage` (readable via DevTools on shared / compromised browsers). In-memory TanStack Query cache (`gcTime: ∞`) keeps the form populated for the session lifetime; on reload the panel refetches from the backend. | `CredentialsModal.tsx`, `WebSocketContext.tsx`, `useCatalogueQuery.ts`, `lib/queryPersist.ts`, `SquareNode.tsx`, `TopToolbar.tsx`, deleted `credentials/providers.tsx` |
+| D — Pytest invariant | New `server/tests/credentials/test_credential_broadcasts.py` (14 tests). Locks via `inspect.getsource`: every credential-mutation handler must call `update_api_key_status` or `broadcast_credential_event` (delete-style: both). Locks the CloudEvents v1.0 envelope shape (specversion / id / source / type / subject). Locks AuthService DB-write-then-cache-update ordering and the no-refresh-token-in-`_oauth_cache` rule. | `tests/credentials/test_credential_broadcasts.py` |
+| E — Docs | New "Source of Truth", "Broadcast Contract", "No hand-maintained frontend provider lists" sections in `credentials_encryption.md`. Notes-section entry in `CLAUDE.md`. Stale references corrected in `frontend_architecture.md`, `status_broadcaster.md`, `credentials_panel.md`, `credentials_scaling/architecture.md`. | `docs-internal/{credentials_encryption,frontend_architecture,status_broadcaster,credentials_panel,credentials_scaling/architecture}.md`, `CLAUDE.md` |
+
+**Wave 13 numbers:**
+- 4 retired patterns: silent `save_api_key` / silent `delete_api_key` / silent OAuth logout / dead-letter `credential_catalogue_updated`.
+- 2 split caches → 1 `_api_key_cache` dataclass.
+- 1 RFC-9700 violation fixed (`refresh_token` removed from `_oauth_cache`; DB-only helper added).
+- 1 OWASP violation fixed (`credentialValues` removed from `localStorage` persistence).
+- 1 200-LOC parallel registry deleted (`providers.tsx`).
+- 1 duplicated UI flag retired (`ApiKeyStatus.hasKey` → catalogue's `provider.stored`).
+- 14 new pytest invariants. 118/118 credentials tests pass. 108/108 NodeSpec invariants pass. `tsc --noEmit` clean.
+
+**Architectural delta (permanent):**
+- `CredentialsDatabase` (encrypted SQLite) is the **single canonical source** for every credential. `AuthService._api_key_cache` + `_oauth_cache` are derived caches with explicit invalidation contracts; no path lets them drift from the DB.
+- Every credential-mutation handler MUST emit `update_api_key_status` and/or `broadcast_credential_event`. Pytest invariant locks the contract.
+- All credential-broadcast bodies are CloudEvents v1.0 envelopes via the existing `WorkflowEvent` mirror — future EventBridge / Knative interop is a JSON-schema swap rather than a rewrite.
+- Frontend has zero hand-maintained provider lists. Adding a new provider is a backend-only change to `server/config/credential_providers.json`.
+- No decrypted credential value ever lands in `localStorage` (OWASP).
+
+**Out of scope (deferred, with rationale):**
+- **Argon2id KDF migration** (B5 in plan) — needs new dependency (`argon2-cffi`) + dedicated plan; PBKDF2 600k stays (OWASP-still-acceptable). Existing deployments can't migrate without re-encryption pass anyway.
+- **TTL on `_api_key_cache` / `_oauth_cache`** — `cachetools.TTLCache` adoption when staleness semantics for upstream-revoked keys are decided.
+- **`android_status` not invalidating catalogue** — separate handler bug; one-line follow-up.
+- **`broadcastQueryClient` (TanStack Query experimental)**, Zod runtime validation at the WS boundary, event-id dedup `Set` for reconnect replay, AsyncAPI 3.0 spec, RFC 9700 single-use refresh-token rotation. Each becomes its own focused plan when justified.
+
## Context
The MachinaOs frontend was coupled to Ant Design (40 files, 187-line theme file, `ConfigProvider` at root). Pre-migration audit + research docs (now deleted; see git history under commit `4cb3dd9` if needed) prescribed shadcn/ui (canonical components copied via CLI registry) + Radix primitives + Tailwind 4 + JSON Forms for a schema-driven inspector. Phase 0/1 commits (`2209dba`, `7ac69fe`) included hand-written primitives and a toast facade — those got deleted as part of corrected Phase 0 (`cdeebb4`).