Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: catch up on recent invariants + purge stale handler-path references
trohitgf64429f14075
diff --git a/CLAUDE.md b/CLAUDE.mdindex d7f755a6..3c9a8184 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -16,7 +16,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.machina-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (toggled by Dashboard's `visibilitychange` listener; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 SVGs across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. || **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/machinaos/index.html`), and 12-theme docs (`guidelines/THEMES.md`, `reference/themes/`). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). || **[Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md)** | Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Live invariant total via `pytest --collect-only`. |-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 18 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `google_auth.py`, `triggers.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 18 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. || **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + **canonical folder-per-plugin shape (telegram is the reference implementation)** + contract invariants + common pitfalls. Lives next to the plugin files. || **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one self-contained folder per plugin under `server/nodes/<group>/<plugin>/`, rooted at `__init__.py`. Multi-file split (`_service.py` / `_handlers.py` / etc.) when the plugin owns long-lived state. Zero frontend edits, zero core-services edits. Auto-registers via `BaseNode.__init_subclass__` + the six `register_*` hooks. Covers tool nodes, dual-purpose nodes (workflow + AI tool), and specialized agents as variations of the same recipe. || **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute via the plain-async `_run_agent_loop` |@@ -130,11 +130,11 @@ server/services/│ # nodes/agent/claude_code_agent/_oauth.py — CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/)├── tracked_http.py # HTTPX event hooks for automatic API cost tracking├── whatsapp_service.py # WhatsApp RPC proxy helpers (used by nodes/whatsapp/*, not an APIRouter)-├── handlers/ # Cross-cutting orchestration only (Wave 11: 16 → 4 files, 12.8K → 1.1K LOC)+├── handlers/ # Cross-cutting orchestration only (Wave 11: 16 → 3 files, 12.8K → 1.1K LOC)│ ├── tools.py # AI-tool dispatch + agent delegation (~821 LOC)│ ├── triggers.py # Generic event-trigger handler-│ ├── google_auth.py # Shared OAuth credential helper-│ └── __init__.py # Docstring only+│ ├── todo.py # writeTodos execution shim (used by every agent)+│ └── __init__.py # Docstring only (google_auth.py retired into nodes/google/_auth_helper.py)├── llm/ # Native LLM provider SDKs (replaces LangChain for chat)│ ├── __init__.py # Public API exports│ ├── protocol.py # ThinkingConfig, Message, LLMResponse, LLMProvider Protocol@@ -2492,6 +2492,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins| `node_status` | Node execution status change || `node_output` | Node execution output data || `agent_progress` | CloudEvents v1.0 envelope (type=`agent.progress`) — per-step agent-loop iteration count, drives the live "N / max" badge on AI Agent canvas nodes |+| `deployment_snapshot` | CloudEvents v1.0 envelope (type=`workflow.deployment.snapshot`) — pushed once per WS connect from `broadcaster._send_deployment_snapshot`; lets the FE reconcile stale `deploymentStatus.isRunning=true` after a backend restart wiped `DeploymentManager._deployments`. Empty list is meaningful (forces reset). || `variable_update` | Single variable value change || `workflow_status` | Workflow execution progress || `api_key_status` | API key validation status |@@ -2766,4 +2767,7 @@ This function:- **Plugin-identifier shape validator (`services/plugin/identifiers.py`)** (`7700f87`): `NODE_TYPE_PATTERN = r"^[A-Za-z_][A-Za-z0-9_]*$"` + `is_valid_node_type(value)`. Single source of truth used by FastAPI URL routes (`Path(pattern=NODE_TYPE_PATTERN)` in `routers/schemas.py`) AND internal helpers (`nodes/_visuals.py::get_plugin_meta` / `get_plugin_icon_path`). Closes CodeQL `py/path-injection` alerts on the icon-resolution endpoints: the registry lookup `get_node_class(node_type)` already gates the taint in practice, but CodeQL can't follow registry-mediated sanitization — adding `fullmatch` at the function boundary is the canonical pattern its rule docs prescribe. Contract test (`tests/services/test_identifiers.py`, 47 cases) locks the regex against `../etc/passwd`, `..\windows\system32`, `foo\x00bar`, `%2e%2e%2fetc`, `foo;bar`, `${HOME}`, `` foo`bar ``, CRLF, and non-string input.- **CLI recovery-resilience invariants** (May 2026): `python -m cli clean` must run end-to-end on a system Python with no third-party deps. Achieved by: (a) every verb in [`cli/cli.py`](./cli/cli.py) is a lazy stub that imports its impl inside the function body — `import cli.cli` does NOT pull in `anyio` / `psutil` / `cli.supervisor` / sibling verb modules (300 → 131 modules at boot). (b) [`cli/_common.py`](./cli/_common.py) defers `cli.run` + `cli.supervisor` imports inside `build_backend_spec` so importing `cli._common` (and therefore `clean.py`) doesn't drag in rich. (c) [`cli/platform_.py`](./cli/platform_.py) lazy-imports `platformdirs` inside the four `user_*_dir` helpers — module loads without the wheel. (d) [`cli/commands/clean.py`](./cli/commands/clean.py) uses stdlib `print()` (no rich) + lazy `cli.ports` import inside `_kill_running_processes` wrapped in `try/except ImportError` (skip-with-warning if psutil is missing). (e) [`cli/commands/_temporal_specs.py`](./cli/commands/_temporal_specs.py) reads `os.environ["TEMPORAL_*"]` inside `temporal_specs()`, not at module load — so importing the module is safe before `load_config()` has run. (f) The supervised-runtime shim moved from `cli/commands/_supervised_runtime.py` to [`server/services/temporal/_supervised_runtime.py`](./server/services/temporal/_supervised_runtime.py) (colocated with the factories it imports). (g) `daemon` is now a verb-per-file package ([`cli/commands/daemon/`](./cli/commands/daemon/) — `_state.py` + `start.py` + `stop.py` + `status.py` + `restart.py`) following pdm's `commands/venv/` shape; PID-file resolution is a function (`pid_dir()`) not a module-level attribute so platformdirs only loads at call time.- **Wave 13 canary fixes** — six load-bearing corrections to the Wave 12 event framework. See [docs-internal/event_framework.md → Wave 13 fixes](./docs-internal/event_framework.md#wave-13-fixes) for the full breakdown. Key invariants to remember when working on canary triggers: (1) `register_canary_trigger_type(node_type, cloudevent_type)` requires the CloudEvents reverse-DNS string as second arg — must match the producer's `WorkflowEvent.type` exactly or the deployment manager's `EventType` SA won't match `dispatch.emit`'s Visibility query (silent firing failure). Diverging re-registration raises `ValueError` so plugin upgrades surface loudly. (2) Plugin `_events.py` for canary-registered triggers is canary-only — no `event_waiter.dispatch` / `send_custom_event` calls (those have zero consumers in canary-on mode). `dispatch.emit(envelope, wire_routing_key=...)` handles BOTH Temporal Signal fan-out AND in-process WS broadcast. (3) `TriggerListenerWorkflow` + `PollingTriggerWorkflow` call `broadcast_trigger_status_activity` before/after each child spawn for firing-pulse UX (matches legacy `triggers.py` collector/processor). (4) `PollingTriggerNode.as_poll_activity` returns `seen_ids: list(current)` — NOT `list(prior_seen | current)` (the latter grows unboundedly; Gmail at ~100/day hit ~36K entries in a year). The legacy `_build_poll_coroutine` does `seen = set(current)` at end of cycle for the same reason. Visibility-filtered providers (Gmail-unread) re-emit on re-surface, which is correct. (5) Canary trigger output persistence: `MachinaWorkflow.run`'s pre-executed loop schedules `store_node_output_activity` for every firing trigger so `ParameterResolver` can resolve `{{triggerNode.field}}` in downstream nodes (the legacy `_execute_from_trigger` did this via `_store_output(trigger_node_id, "output_0", ...)`; canary skipped it pre-fix). Skips non-firing siblings (`_trigger_output={"not_triggered": True}`). (6) `DeploymentManager.cancel` sweeps stuck node statuses via `_clear_stuck_node_statuses(workflow_id, include_waiting=True)` + emits terminal `update_workflow_status(executing=False, workflow_id=...)`. Without these the FE leaves downstream nodes glowing forever after deployment cancel and the toolbar Start/Stop indicator stays at `executing=True`. The delegation guard inside `_clear_stuck_node_statuses` still protects in-flight fire-and-forget child agents.+- **Deployment reconcile snapshot on WS connect** (de8df87): a stale FE `deploymentStatus.isRunning=true` used to survive a backend restart because the in-memory `DeploymentManager._deployments` dict was wiped (no recovery wiring — the `RecoverySweeper.set_recovery_callback` extension point exists but is intentionally unwired; see the "workflow status not properly recognized" investigation). The Start button therefore stayed showing "Stop" forever. Fix: new `WorkflowEvent.deployment_snapshot(running_workflow_ids)` typed factory (`source = machinaos://services/workflow`, `type = workflow.deployment.snapshot`) + `broadcaster._send_deployment_snapshot(websocket)` that runs at the tail of `broadcaster.connect()` (single-target, NOT fan-out — only the just-connecting client needs to reconcile). FE `case 'deployment_snapshot'` in `WebSocketContext.tsx` iterates `useAppStore.workflowUIStates` and clears `isExecuting=true` on any workflow NOT in the snapshot's running set (empty list is meaningful — this is the load-bearing reset). Also reconciles `deploymentStatus.isRunning` for the active workflow. Distinct from `workflow_lifecycle("deployment.started")` (state-transition edge event) — the snapshot is an idempotent state dump tied to client connect, not a transition.+- **Agent progress badge — defensive status invariant** (15b8d9d): `AIAgentNode`'s "N / max" iteration badge is gated on `isExecuting && typeof iteration === 'number' && typeof maxIterations === 'number'` where `isExecuting = nodeStatus?.status === 'executing'`. The `agent_progress` handler USED to only set `data.iteration` / `data.max_iterations`, relying on a prior `node_status='executing'` broadcast to have already stamped the status. If agent_progress arrived first (race, single-step agent completion, out-of-order Temporal activity delivery), `status` stayed undefined and the badge was hidden even though the iteration data was populated. Fix: the agent_progress handler now defensively sets `status='executing'` on the slot — but preserves `'success'` / `'error'` if a later terminal broadcast already flipped the slot (terminal states win over the resurrection).+- **Temporal Worker tuner exclusivity** (Wave 16.4, 190c896): `Worker.__init__` rejects `tuner` alongside ANY of `max_concurrent_workflow_tasks` / `max_concurrent_activities` / `max_concurrent_local_activities` / `max_concurrent_nexus_tasks` — the tuner OWNS every slot supplier via its `WorkerTuner.create_composite(workflow_supplier, activity_supplier, local_activity_supplier, nexus_supplier)` and cannot coexist with the individual max-count kwargs. In `TemporalWorkerPool.start`, ALL FOUR max-count kwargs must be pulled from the base `worker_kwargs` when `tuner=` is added; the ai-heavy / browser queues use the tuner and preserve their 10-workflow-slot ceiling via `_tuner_for -> FixedSizeSlotSupplier(10)` on the workflow_supplier slot. The framework worker at `worker.py:188` does NOT use a tuner, so it keeps the plain `max_concurrent_workflow_tasks=10` + `max_concurrent_activities=self.pool_size` kwargs directly. `TEMPORAL_WORKER_POOL_ENABLED` defaulted to True in the same commit (`test_task_queue_coverage.py::TestWorkerPoolDefaultOn` locks the default via source-introspection so the flip survives a hasty revert).- never use emojis in prints\ No newline at end of filediff --git a/docs-internal/credentials_encryption.md b/docs-internal/credentials_encryption.mdindex 35d7ca3f..64aa98d6 100644--- a/docs-internal/credentials_encryption.md+++ b/docs-internal/credentials_encryption.md@@ -102,7 +102,7 @@ For tokens obtained via OAuth 2.0 flows (Google Workspace, Twitter/X, Claude.ai)### The Mistake to Avoid-Google access tokens live in the OAuth system, not the API key system. Reading them via `get_api_key("google_access_token")` returns None even if the user is fully logged in. All Google Workspace handlers must use `get_google_credentials()` from `server/services/handlers/google_auth.py`, which calls `get_oauth_tokens("google")` internally.+Google access tokens live in the OAuth system, not the API key system. Reading them via `get_api_key("google_access_token")` returns None even if the user is fully logged in. All Google Workspace handlers must use `get_google_credentials()` from `server/nodes/google/_auth_helper.py` (post-Wave-11.I, this replaced the retired `server/services/handlers/google_auth.py`), which calls `get_oauth_tokens("google")` internally.Twitter has the same split: `twitter_client_id` and `twitter_client_secret` are in the API key system, but `twitter_access_token` is in the OAuth system.diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex de5253ef..716124fe 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -388,6 +388,7 @@ See [ui_migration_plan.md](./ui_migration_plan.md) Phase 6.- All modifying operations go through WebSocket — REST is reserved for auth + webhooks.- No polling. If a component wants fresh data, call `sendRequest` once (or use TanStack Query with `staleTime: Infinity` + manual `invalidate`).- **`sendRequest` queues during disconnect with backpressure.** When the socket is not open, the request enqueues with an `AbortController`-backed per-request timeout (default 30s) and replays on reconnect inside `ws.onopen` before `setIsReady(true)`. Queue caps at 200 with FIFO eviction (rejects oldest with `backpressure: too many queued requests`). Intentional close (`event.code === 1000`) drops the queue; transient closes preserve it. Eliminates indefinite spinners during the 3-second reconnect window. Implementation: `pendingSendQueueRef` + `drainPendingSends` in `WebSocketContext.tsx`.+- **Deployment state reconciles on every WS connect.** When a backend restarts (or the socket transiently drops) the in-memory `DeploymentManager._deployments` dict is wiped and NEVER re-fires a `deployment_status: 'stopped'` broadcast because it has nothing to broadcast about. Before the fix (de8df87), the FE `deploymentStatus.isRunning=true` carried forward and the toolbar Start button stayed on "Stop" forever. Now `broadcaster.connect()` calls `_send_deployment_snapshot(websocket)` right after `initial_status` — a single-target push (NOT fan-out) carrying a CloudEvents envelope (`type = workflow.deployment.snapshot`) with the current `running_workflow_ids`. FE `case 'deployment_snapshot'` in `WebSocketContext.tsx` iterates `useAppStore.workflowUIStates` and clears `isExecuting=true` on any workflow NOT in that list (empty list is meaningful — this is the load-bearing reset). Distinct from `workflow_lifecycle("deployment.started")` (state-transition edge event) — the snapshot is an idempotent state dump tied to client connect.- **`currentWorkflowId` lives in `useAppStore` only.** Non-React listeners (WS handlers) read it via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch (https://github.com/pmndrs/zustand#read-state-without-subscription). The previous `currentWorkflowIdRef` mirror inside WebSocketContext was a one-render-late copy that misrouted broadcasts during workflow switches. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from a single `useEffect` in `Dashboard.tsx`.## Ownership boundary: TanStack Query vs Zustand vs WebSocketContextdiff --git a/docs-internal/rlm_service.md b/docs-internal/rlm_service.mdindex e8884aa7..094a9806 100644--- a/docs-internal/rlm_service.md+++ b/docs-internal/rlm_service.md@@ -49,10 +49,11 @@ Execution Flow================================NodeExecutor._dispatch()- -> handle_rlm_agent() [server/services/handlers/rlm.py]- |- +-- _collect_agent_connections() [REUSE from handlers/ai.py]- +-- _format_task_context() [REUSE from handlers/ai.py]+ -> RLMAgentNode.execute_op() [server/nodes/agent/rlm_agent.py]+ | (post-Wave-11 replacement for the+ | retired server/services/handlers/rlm.py)+ +-- collect_agent_connections() [services/plugin/edge_walker.py]+ +-- _format_task_context() [nodes/agent/_inline.py — prepare_agent_call]+-- tool stripping on completion [REUSE pattern]+-- auto-prompt fallback [REUSE pattern]|@@ -241,14 +242,14 @@ return await ai_service.rlm_service.execute(node_id, parameters, ...)| Function | Source | Purpose in RLM ||----------|--------|----------------|-| `_collect_agent_connections()` | `handlers/ai.py:17` | Discover memory, skills, tools, input, task connections |-| `_format_task_context()` | `handlers/ai.py:352` | Format delegated task results as prompt context |-| `_build_skill_system_prompt()` | `ai.py:833` | Build system prompt from connected skill nodes |-| `is_model_valid_for_provider()` | `ai.py:362` | Validate model name for provider |-| `get_default_model_async()` | `ai.py:377` | Look up default model from DB or config |+| `collect_agent_connections()` | `services/plugin/edge_walker.py` | Discover memory, skills, tools, input, task connections (renamed Wave-11 successor to `handlers/ai.py::_collect_agent_connections`; the old handler file is gone) |+| `prepare_agent_call()` | `nodes/agent/_inline.py` | Shared pre-dispatch helper — collects connections + injects task context + auto-prompt from upstream input |+| `_build_skill_system_prompt()` | `services/ai.py` | Build system prompt from connected skill nodes |+| `is_model_valid_for_provider()` | `services/ai.py` | Validate model name for provider |+| `get_default_model_async()` | `services/ai.py` | Look up default model from DB or config || `self.auth.get_api_key()` | AIService | Retrieve API key from credential store || `save_message()` | `memory_store.py` | Persist conversation to memory |-| `execute_tool()` | `handlers/tools.py:34` | Dispatch tool execution (used by ToolBridgeAdapter) |+| `execute_tool()` | `services/handlers/tools.py` | Dispatch tool execution (used by ToolBridgeAdapter) || `broadcaster.update_node_status()` | `status_broadcaster.py` | Real-time UI status updates |---diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.mdindex ab6f2c2b..fc8e9bef 100644--- a/docs-internal/ui_migration_plan.md+++ b/docs-internal/ui_migration_plan.md@@ -273,7 +273,7 @@ Driven by three sub-agent audits (broadcast asymmetry, duplicated caches, parall| 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` |+| 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, `nodes/google/_auth_helper.py` — post-Wave-11.I this replaced the retired `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`, `nodes/google/_auth_helper.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` |