Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: approvals that wait for the owner, and the Phase 1b record (RFC-0007 AP.6)
trohitga290bf2dccba
diff --git a/CLAUDE.md b/CLAUDE.mdindex bbed78e5..25b47fdb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,8 +15,8 @@ OpenCompany is an open-source operating system for self-improving AI employees.| **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). || **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). || **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |-| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, the same three themes and theme button as the editor), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Stop is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the live Ask first rule (`workflow_rules`, the chat's Ask first chip via `set_ask_first`; app replies wait in `approvalGate`, sending tool calls are held as drafts by `services/approvals/tool_calls.py` and sent after a 5 s Undo window by `ApprovedToolCallWorkflow`; cards in the chat; builder v3 gates every app reply, attaches every app tool and gives the talk agent `chatUi` and the registry's `talk_send` tools, with instructions identical whatever the rule; older employees are upgraded on Apply / Turn on Talk / Start by `services/employees/upgrade.py`), run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone; a footer timeline of the employee's steps from the step log `services/workspace_steps.py`, read with `workspace_steps_list` and again on `workspace_step`, and Take over, which takes the screen and stops the employee until Hand back), the "Web browser" app (attached whole, each call read-only while the owner asks first through its approval spec's `restrict_while_asking`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` / `workspace_step` broadcasts. |-| **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast; a standalone worker sends its run events, `chat.updated` and `approval_lifecycle` to the backend over `/ws/internal` (`services/chat/relay.py`, `chat_run_publish`, ordered, dropped events resynced). A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note. Branches (`services/chat/branches.py`): `get_chat_messages` returns the path to the thread's active leaf, each message with its versions (`siblings`), `editable` and the owner's rating; `edit_chat_message` / `regenerate_chat_reply` / `switch_chat_branch` move the path in one reserved transaction under the conversation store's lock, taking each agent's stored conversation back to the cursor its run recorded at `prepare_payload` (`chat_runs.context_cursors`) or restoring the branch's kept copy (`chat_branch_snapshots`), refused on `revision_conflict`, `run_in_progress`, `cannot_rewind`, `branch_unavailable` or `older_generation`; `set_chat_feedback` keeps a rating and tells the next turn (`[feedback]` note). Attachments (`services/chat/attachments.py`): the chat uploads files under `uploads/` and sends only their paths, the server rebuilds each reference from the file (refusing anything else, at most six), the answering agent reads an `[attachments]` line and images ride the opening user message for a provider with `vision.user_images`; `options.web: false` drops the `search` tools for that run; Home's model picker (`services/chat/choice.py`, `get_chat_models`) sends `options.model` / `options.effort`, resolved at admission (Auto = the owner's default model; refused with `model_unavailable`, never swapped) and applied only to the answering agent, effort only to a provider's `effort_models`; `get_chat_context` gives slash commands (generic plus the apps' `commands`) and capabilities; dictation is the speech plugin's `dictation_status` / `transcribe_audio`. Lists every event, handler, part and error code (among them `engine_unavailable`: with Temporal not connected a workflow's chat saves nothing, since nothing could deliver it). |+| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, the same three themes and theme button as the editor), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Stop is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the live Ask first rule (`workflow_rules`, the chat's Ask first chip via `set_ask_first`; app replies wait in `approvalGate`, sending tool calls are held as drafts by `services/approvals/tool_calls.py` and sent after a 5 s Undo window by `ApprovedToolCallWorkflow`; cards in the chat; builder v3 gates every app reply, attaches every app tool and gives the talk agent `chatUi` and the registry's `talk_send` tools, with instructions identical whatever the rule; older employees are upgraded on Apply / Turn on Talk / Start by `services/employees/upgrade.py`; in a generation that waits for the owner (RFC-0007, `approval_wait_version` 1, which Start does not write yet) Ask first becomes a mode over a class table (`services/approvals/classes.py`) minus always-allow rules (`allows.py`), the agent answering a chat run waits in its turn on `ApprovalWorkflow` and runs the allowed call itself, and the gate no longer holds Stop), run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone; a footer timeline of the employee's steps from the step log `services/workspace_steps.py`, read with `workspace_steps_list` and again on `workspace_step`, and Take over, which takes the screen and stops the employee until Hand back), the "Web browser" app (attached whole, each call read-only while the owner asks first through its approval spec's `restrict_while_asking`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` / `workspace_step` broadcasts. |+| **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast; a standalone worker sends its run events, `chat.updated` and `approval_lifecycle` to the backend over `/ws/internal` (`services/chat/relay.py`, `chat_run_publish`, ordered, dropped events resynced). A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note; in a generation that waits for the owner (RFC-0007, not yet written by Start) the mode and the call's class decide what asks, the agent answering the run waits in its turn for Allow or Decline (`services/approvals/waiting.py`; a message sent meanwhile declines the call and answers `declined`), and the watchdog does not time the wait out. Branches (`services/chat/branches.py`): `get_chat_messages` returns the path to the thread's active leaf, each message with its versions (`siblings`), `editable` and the owner's rating; `edit_chat_message` / `regenerate_chat_reply` / `switch_chat_branch` move the path in one reserved transaction under the conversation store's lock, taking each agent's stored conversation back to the cursor its run recorded at `prepare_payload` (`chat_runs.context_cursors`) or restoring the branch's kept copy (`chat_branch_snapshots`), refused on `revision_conflict`, `run_in_progress`, `cannot_rewind`, `branch_unavailable` or `older_generation`; `set_chat_feedback` keeps a rating and tells the next turn (`[feedback]` note). Attachments (`services/chat/attachments.py`): the chat uploads files under `uploads/` and sends only their paths, the server rebuilds each reference from the file (refusing anything else, at most six), the answering agent reads an `[attachments]` line and images ride the opening user message for a provider with `vision.user_images`; `options.web: false` drops the `search` tools for that run; Home's model picker (`services/chat/choice.py`, `get_chat_models`) sends `options.model` / `options.effort`, resolved at admission (Auto = the owner's default model; refused with `model_unavailable`, never swapped) and applied only to the answering agent, effort only to a provider's `effort_models`; `get_chat_context` gives slash commands (generic plus the apps' `commands`) and capabilities; dictation is the speech plugin's `dictation_status` / `transcribe_audio`. Lists every event, handler, part and error code (among them `engine_unavailable`: with Temporal not connected a workflow's chat saves nothing, since nothing could deliver it). || **[Theme System](./docs-internal/theme_system.md)** | Three themes — the base `light` and `dark` plus one stylized skin, `atomic` (the design handoff's nine other skins were removed on 2026-10-12) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Home, the editor and the sign-in screen all show the chosen theme, and one theme button ([components/ui/ThemeButton.tsx](./client/src/components/ui/ThemeButton.tsx)) in the Home header, the editor's toolbar and the sign-in screen steps Light → Dark → Atomic (`cycleTheme`; every theme name comes from `THEME_LABEL` in `ThemeContext.tsx`). 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), the `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, per-component decoration hooks (`.canvas-host`, `.toolbar`, `.sq-node`, …; Atomic's panel edges, starburst canvas and node styling), **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, **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `App.tsx` above the sign-in gate so it covers every screen, while the page is hidden per the Page Visibility API, never merely because the window lost focus; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyphs** (Atomic's 29 inline SVG glyphs in [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts), read by theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), scrollbars from the global token rules plus Atomic's own, 9-event WebAudio sound system (3 packs — parchment, terminal, vibraphone — 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/opencompany/index.html`), theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 3 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/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/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. 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`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |@@ -756,7 +756,7 @@ Workflows execute via Temporal for durability and horizontal scaling, gated by `Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the F4.B `agent.*` activities (unsuffixed since the AgentWorkflow fold; read the live set from `collect_agent_activities()` rather than a hardcoded count), heartbeat semantics, delegation input contract, the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).-**Months-long durability contract (July 2026).** Running and paused deployments survive backend restarts, are never auto-terminated, and keep executing for months. Load-bearing invariants: (1) `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` stays `false` (debug-only sweep; even enabled, any control row in the shared `WORKFLOW_CONTROL_ACTIVE_STATES` — including `resetting` — vetoes it). (2) New child workflow starts carry **no** `execution_timeout`/`run_timeout` — Temporal's timeout timers keep ticking through a cooperative pause, so lifetime caps silently terminated paused runs; liveness comes from activity heartbeats (30s beat / 2min timeout), never from workflow lifetime caps. Changing an activity's or child's timeouts, retry policy, task queue or parent close policy needs no patch: on replay Temporal compares only a command's kind, its activity or child type, and its id (RFC-0006 §5 rule 6). A cancellation type is the exception when a recorded history can contain a cancel of that activity or child, and any change to which commands run needs a `workflow.patched(...)` guard (list the live markers with `grep -rn "workflow.patched(" server/services/temporal`; [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) says what each one gates). (3) Every long-lived workflow loop must continue-as-new under history pressure (`is_continue_as_new_suggested()` + a soft cap) — Temporal hard-terminates around ~51,200 history events; `WorkflowControlWorkflow` carries triggers/queued events/seen-ids/control state across rollovers, so controller handles are addressed **by workflow id only, never run_id-pinned**. (4) `dispatch.emit` skips controllers whose `ControlEventTypes` Search Attribute doesn't match the event (absent attribute = legacy match-all). (5) The Temporal lifecycle is owned by [services/temporal/lifecycle.py](./server/services/temporal/lifecycle.py) (`main.py` only schedules it): dev-server supervision + resident watchdog (`TEMPORAL_HEALTH_MONITOR_INTERVAL_SECONDS`), worker crash-restarts that REBUILD the single-use SDK `Worker` per attempt (manager + every pool queue worker), and the boot-time `reconcile_active_controls_on_boot` pass (converges crash-stranded `starting` rows, re-arms running/paused generations from the persisted graph snapshot). (6) **Recovery policies** (env-driven, defaults in `.env.template`; full semantics in [temporal-workflow-control.md → Recovery policies](./docs-internal/temporal-workflow-control.md)): `WORKFLOW_CONTROL_CRASH_RECOVERY=pause` — after a kill/crash (dirty-bit marker cleared only by graceful teardown) boot recovers running generations as **paused** so the user consciously resumes; `WORKFLOW_CONTROL_MISSING_CONTROLLER=pause` — a killed/vanished controller converges the generation to paused and **Resume rebuilds the controller** (`WorkflowIdConflictPolicy.USE_EXISTING`, re-arm from snapshot) instead of forcing a state-archiving Reset; `WORKFLOW_CONTROL_PAUSE_ON_FAILURE=true` — repeatedly-failing trigger-spawned runs pause their deployment via the `workflow_control.pause_on_failure` activity (circuit breaker; trips only after `WORKFLOW_CONTROL_PAUSE_ON_FAILURE_THRESHOLD` (default 3) failures inside a rolling `_WINDOW_SECONDS` (default 600) so one node hiccup never pauses anything; Resume resets the streak; manual canvas runs never qualify). Temporal's native Pause/Unpause (server 1.28+) is deliberately NOT used — no Python SDK surface, and it halts workflow-task dispatch so a natively-paused controller couldn't process the resume Update. (7) **Workflow-scoped event delivery**: an envelope whose `workflow_id` is set by its producer's call site reaches only that workflow's consumers (`dispatch.emit` narrows both Visibility clauses by `EventWorkflowId`); chat is the first scoped producer and delegated-task completion (`nodes/agent/_events.py`) the second, whose broadcast frame carries only the task's identity — the decision lives in `routers/websocket.py`, the narrowing in core dispatch, and plugin `_events.py` factories only plumb the field (see [event_framework.md](./docs-internal/event_framework.md)). (8) **Canvas editability is the server-owned `can_edit` capability** emitted by `serialize_control` (paused = editable; starting/running/transitional = locked); the FE renders it via `lib/canvasLock.ts` + Dashboard's `guardCanvasEdit` and never re-derives the rule from state strings (see [temporal-workflow-control.md → Canvas editability](./docs-internal/temporal-workflow-control.md)). Locked by `tests/temporal/test_durability_hardening.py` + `test_worker_restart.py`.+**Months-long durability contract (July 2026).** Running and paused deployments survive backend restarts, are never auto-terminated, and keep executing for months. Load-bearing invariants: (1) `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` stays `false` (debug-only sweep; even enabled, any control row in the shared `WORKFLOW_CONTROL_ACTIVE_STATES` — including `resetting` — vetoes it). (2) New child workflow starts carry **no** `execution_timeout`/`run_timeout` — Temporal's timeout timers keep ticking through a cooperative pause, so lifetime caps silently terminated paused runs; liveness comes from activity heartbeats (30s beat / 2min timeout), never from workflow lifetime caps. Changing an activity's or child's timeouts, retry policy, task queue or parent close policy needs no patch: on replay Temporal compares only a command's kind, its activity or child type, and its id (RFC-0006 §5 rule 6). A cancellation type is the exception when a recorded history can contain a cancel of that activity or child, and any change to which commands run needs a `workflow.patched(...)` guard or, for new generations only, a generation flag frozen at Start (`workflow.GENERATION_FLAGS`, RFC-0005 §24.1 rule 2) (list the live markers with `grep -rn "workflow.patched(" server/services/temporal`; [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) says what each one gates). (3) Every long-lived workflow loop must continue-as-new under history pressure (`is_continue_as_new_suggested()` + a soft cap) — Temporal hard-terminates around ~51,200 history events; `WorkflowControlWorkflow` carries triggers/queued events/seen-ids/control state across rollovers, so controller handles are addressed **by workflow id only, never run_id-pinned**. (4) `dispatch.emit` skips controllers whose `ControlEventTypes` Search Attribute doesn't match the event (absent attribute = legacy match-all). (5) The Temporal lifecycle is owned by [services/temporal/lifecycle.py](./server/services/temporal/lifecycle.py) (`main.py` only schedules it): dev-server supervision + resident watchdog (`TEMPORAL_HEALTH_MONITOR_INTERVAL_SECONDS`), worker crash-restarts that REBUILD the single-use SDK `Worker` per attempt (manager + every pool queue worker), and the boot-time `reconcile_active_controls_on_boot` pass (converges crash-stranded `starting` rows, re-arms running/paused generations from the persisted graph snapshot). (6) **Recovery policies** (env-driven, defaults in `.env.template`; full semantics in [temporal-workflow-control.md → Recovery policies](./docs-internal/temporal-workflow-control.md)): `WORKFLOW_CONTROL_CRASH_RECOVERY=pause` — after a kill/crash (dirty-bit marker cleared only by graceful teardown) boot recovers running generations as **paused** so the user consciously resumes; `WORKFLOW_CONTROL_MISSING_CONTROLLER=pause` — a killed/vanished controller converges the generation to paused and **Resume rebuilds the controller** (`WorkflowIdConflictPolicy.USE_EXISTING`, re-arm from snapshot) instead of forcing a state-archiving Reset; `WORKFLOW_CONTROL_PAUSE_ON_FAILURE=true` — repeatedly-failing trigger-spawned runs pause their deployment via the `workflow_control.pause_on_failure` activity (circuit breaker; trips only after `WORKFLOW_CONTROL_PAUSE_ON_FAILURE_THRESHOLD` (default 3) failures inside a rolling `_WINDOW_SECONDS` (default 600) so one node hiccup never pauses anything; Resume resets the streak; manual canvas runs never qualify). Temporal's native Pause/Unpause (server 1.28+) is deliberately NOT used — no Python SDK surface, and it halts workflow-task dispatch so a natively-paused controller couldn't process the resume Update. (7) **Workflow-scoped event delivery**: an envelope whose `workflow_id` is set by its producer's call site reaches only that workflow's consumers (`dispatch.emit` narrows both Visibility clauses by `EventWorkflowId`); chat is the first scoped producer and delegated-task completion (`nodes/agent/_events.py`) the second, whose broadcast frame carries only the task's identity — the decision lives in `routers/websocket.py`, the narrowing in core dispatch, and plugin `_events.py` factories only plumb the field (see [event_framework.md](./docs-internal/event_framework.md)). (8) **Canvas editability is the server-owned `can_edit` capability** emitted by `serialize_control` (paused = editable; starting/running/transitional = locked); the FE renders it via `lib/canvasLock.ts` + Dashboard's `guardCanvasEdit` and never re-derives the rule from state strings (see [temporal-workflow-control.md → Canvas editability](./docs-internal/temporal-workflow-control.md)). Locked by `tests/temporal/test_durability_hardening.py` + `test_worker_restart.py`.**Temporal tracing ownership is strict.** Register the SDK `TracingInterceptor` exactly once on the shared `Client.connect(...)`; the Python SDK automatically prepends compatible client interceptors to every worker. Never repeat `TracingInterceptor` in `Worker(..., interceptors=...)`. Worker lists contain the distinct `ObservabilityWorkerInterceptor` and plugin-specific worker interceptors only. Exact paired `StartActivity` / `RunActivity` / `CompleteWorkflow` console spans with identical Temporal identities indicate duplicate instrumentation, not duplicate execution; use Temporal Event History and the `node.<type>.execute` application span to verify actual attempts. See the tracing and debugging sections in [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) and [errors.md](./docs-internal/errors.md).diff --git a/RFC-0005-EVENT-OS-ON-TEMPORAL.md b/RFC-0005-EVENT-OS-ON-TEMPORAL.mdindex 060bd0d2..d9db0a02 100644--- a/RFC-0005-EVENT-OS-ON-TEMPORAL.md+++ b/RFC-0005-EVENT-OS-ON-TEMPORAL.md@@ -1184,6 +1184,20 @@ Phase 1 ended on 2026-10-24. Commit 49177427 came from another session.| WhatsApp and Drive downloads | 276d833b | A security fix outside the numbered items. WhatsApp media files stay inside the workspace, and the WhatsApp and Drive downloads check their URLs through `services/netpolicy.py` (`fetch_policy`, `resolved_url_block_reason`), which 1b.33 reuses for the HTTP request node. || 1b.45a The patch rule in CLAUDE.md | 24c2907f | CLAUDE.md's durability contract says option and retry-policy changes need no patch (RFC-0006 §5 rule 6). The rest of 1b.45 runs last. || 1b.1a The repeat table | f76b1dc3 | `services/approvals/repeats.py`: `REPEATABLE`, `REPEATABLE_WHEN` and `repeatable(node_cls, data, *, tool_call)`. An unlisted node type is unsafe to repeat, and no plugin declares anything; this replaces RFC-0006's per-plugin effect classes. 1b.1b calls it. |+| 1b.1c The client's effect card | 4e0f1675 | The `effect` kind and the `dismiss` decision in the client: "{name} tried to …", "May have happened", then Dismiss. It came before 1b.1b, because the client read an unknown kind as `gate`. |+| 1b.1b The redo guard and recording | e02cc61f | A later attempt of a call that is not safe to repeat answers `SendOutcomeUnknown` or `OutcomeUnknown` (`tool_calls.redo_refusal`). `record_unknown` leaves an `unknown` card; an `effect` row is keyed `e:`. The guard runs in `BaseNode.as_activity`, the Coding Agent's workspace tools and the legacy node activity. API keys are still injected before template resolution. |+| 1b.2 Cancellation reaches the activity | 8f1db2df | A cancel inside `_node_activity` records `unknown` for a call that is not safe to repeat, and so does a worker shutdown mid-call, answering at once. The cron and Timer nodes no longer turn a cancel into a `RuntimeError`. |+| RFC-0007 AP.1 The class table | a9a85fde | `services/approvals/classes.py`: read, write, send, money, and a type it does not list is a send. It classes 157 types. A spec's `when` lowers only `send` to `write`, never `money` (RFC-0007 §4.1). |+| 1b.31 The sanitized Start snapshot | 461e9e56 | Landed whole before AP.2a. The sanitizer drops `authorization`, `proxyauthorization` and `cookie`, and `restore_dropped` puts them back where a run reads the saved settings. 1b.32 lands before the next release. |+| RFC-0007 AP.2a Modes and classes | fc4b11f4 | `workflow_rules.mode` and `set_mode` (on PostgreSQL the new column needs a manual `ALTER`). In a v1 generation `tool_calls.check` asks by mode and class for every tool, on a generic card when it has no spec. It writes turn rows, and holds the Browser only when it fetches a URL. `get_ask_first` and `set_ask_first` carry `mode`. |+| RFC-0007 AP.2b Turn rows and rules | 1ee6c023, 6ec3522d | A turn row gets no Undo, Restore, `ApprovedToolCallWorkflow` or `[update]` note. Decline carries a note (`approval_requests.note`, a manual `ALTER` on PostgreSQL). Always-allow rules: `services/approvals/allows.py`, the `approval_allows` table and three WS commands. They are offered only on turn rows, never for money. |+| RFC-0007 AP.2c CLI and in-process drafts | af9c0607, 334fceff | In v1, `check_in_process` holds a draft keyed by the call id (an MCP call's request digest) instead of refusing. CLI agents read the chat's notes (`with_chat_notes`); the Claude Code node passes its chat stream, a one-argument edit. |+| RFC-0007 AP.3 The client | 4568fc7e, 1e94a3f8, 22d767fa, 3152dfd4 | The card's class pill, Always allow, and Decline with a note. Where the generation is v1, the Ask first menu with "Allowed without asking". A waiting turn reads "Waiting for your OK" and keeps its cards, and the composer sends a message as the owner's answer while a call waits. |+| 1b.42 Plugin task queues in the golden | 8d308b9a | `write_golden` records each plugin's task queue, and a test keeps the release's queues. |+| RFC-0007 AP.4a `ApprovalWorkflow` | 0374b5b7 | `services/temporal/approval_workflow.py`: unsandboxed, with Signal `nudge`, every wait timed to the row's expiry. `services/approvals/waiting.py` reads the row. The chat watchdog re-nudges a decided row its wait has not read, and Stop's tree walk skips the child. The golden accepts a reviewed entry that names a new type. |+| RFC-0007 AP.4b The turn's wait | dfdff73b | AgentWorkflow ends the call's admitted action and waits in `ApprovalWorkflow`. Allowed, it claims, runs and records the call itself through `run_approved_call`, which `ApprovedToolCallWorkflow` shares; that workflow's commands replay as recorded. The flag rides `GENERATION_FLAGS`, and the golden accepts a reviewed flag. Reset cancels the rows its turns waited on. CLI and RLM tool calls get the flag inside the Pi inline scope. |+| RFC-0007 AP.4c The chat side | 9d43d7aa | A message sent while the turn waits declines the call (`declined`, no thread row). The watchdog doesn't time out a waiting run, and the owner's answer restarts its window. A closed run cancels its waits. |+| RFC-0007 AP.5 The gate outside Stop | 2fabb9ea | In a v1 generation the Approval node's activity is no admitted action, so Stop completes while it waits; the node after it runs after Resume. |## 25. Defaults chosen and open itemsdiff --git a/RFC-0006-TEMPORAL-DESIGN-PATTERNS.md b/RFC-0006-TEMPORAL-DESIGN-PATTERNS.mdindex d16b8be7..0e8ce61b 100644--- a/RFC-0006-TEMPORAL-DESIGN-PATTERNS.md+++ b/RFC-0006-TEMPORAL-DESIGN-PATTERNS.md@@ -6219,7 +6219,9 @@ Phase 1b is new to RFC-0005's rollout (§20).- 1b.11 (0194d836);- 1b.45a (24c2907f);- 1b.1a (f76b1dc3);- - the WhatsApp and Drive download fix (276d833b).+ - the WhatsApp and Drive download fix (276d833b);+ - 1b.1c (4e0f1675), 1b.1b (e02cc61f), 1b.2 (8f1db2df);+ - RFC-0007 AP.1 (a9a85fde), 1b.31 (461e9e56), AP.2a (fc4b11f4), AP.2b (1ee6c023, 6ec3522d), AP.2c (af9c0607, 334fceff), AP.3 (4568fc7e, 1e94a3f8, 22d767fa, 3152dfd4), 1b.42 (8d308b9a), AP.4a (0374b5b7), AP.4b (dfdff73b), AP.4c (9d43d7aa), AP.5 (2fabb9ea). RFC-0005 §24.4 says what each changed.2. **Batch A:**- 1b.1c, 1b.1b, 1b.2;- then RFC-0007 AP.1, 1b.31 (from batch C), AP.2a, AP.2b, AP.2c, AP.3, 1b.42, AP.4a, AP.4b, AP.4c, AP.5, AP.6;diff --git a/RFC-0007-APPROVALS-ON-TEMPORAL.md b/RFC-0007-APPROVALS-ON-TEMPORAL.mdindex 6bfb6d7c..3d505ad0 100644--- a/RFC-0007-APPROVALS-ON-TEMPORAL.md+++ b/RFC-0007-APPROVALS-ON-TEMPORAL.md@@ -353,10 +353,10 @@ In a v1 generation, for every caller: agent tool calls, CLI calls and in-process**The flag.** `begin_generation` writes `approval_wait_version: 1` into `resource_manifest` (`services/deployment/control.py:160`). The write is AP.7, the last step (§7). The flag follows `pi_harness_version`'s path (C3 §3.4):- `freeze_generation_harness` copies it into the payload and into `_temporal_routing_v1`. It is called at three sites: `manager.py:949-951`, `manager.py:1117-1119` and `temporal/executor.py:166-167`.-- `_frozen_routing_from_input` keeps it (`workflow.py:175-195`).+- `_frozen_routing_from_input` keeps it (`workflow.py:175-195`; every flag in `GENERATION_FLAGS`).- MachinaWorkflow sets it on the agent and node contexts after `workflow.py:762-763`.- `_INHERITED_SCOPE_KEYS` (`agent_workflow.py:295-325`) carries it into tool payloads, the Task Manager preflight, delegated children and continue-as-new.-- The MCP bridge entry carries it beside `pi_harness_version` (`services/cli_agent/workflow_tools.py:335`), and so does the in-process tool path.+- CLI and RLM tool calls get it inside the Pi inline scope (`INLINE_SCOPE_KEYS`). In a Pi generation, the Claude Code node and RLM's tool wrapper forward that scope into each call. Every generation Start admits is a Pi generation, so Start keeps writing `pi_harness_version` beside this flag; no bridge-entry hop is needed. The in-process tool path copies it into the plugin's context.- `serialize_control` exposes it to the client (`control.py:47-71`).Team jobs, Workspace tasks and manual Runs do not carry it, so their calls stay v0.@@ -380,8 +380,8 @@ Team jobs, Workspace tasks and manual Runs do not carry it, so their calls stay- **`run(ref)` loops:**- It clears the nudge flag, then reads the row through `approvals.read`, a new 30 s activity on `BOOKKEEPING_RETRY`.- That activity applies the row's expiry first (`decisions.expire_if_due`), so nothing spins at the deadline.- - When it returns a final answer, it stamps `consumed_at`.- - Once the row is no longer pending, it returns one of `approved{revision}`, `declined{note}`, `expired` or `cancelled`.+ - When it returns a final answer other than `approved`, it stamps `consumed_at`; the claim stamps an approved row.+ - Once the row is no longer pending, it returns the row's answer, `{status, revision, note?, by_message?}`. The status is the row's own: `approved`, `discarded` (declined, with the owner's note; `by_message` when a message declined it, §4.7), `expired` or `cancelled`.- Otherwise it waits with `workflow.wait_condition(lambda: self._nudged, timeout=max(expires_at - now, 1 s))`, then reads again.- **Its one message is the Signal `nudge()`,** with no payload. Duplicates are harmless, and nothing needs validating.- **Every wait has a timeout.** Switching a wait between `timeout=None` and a timeout is a nondeterministic change.@@ -432,7 +432,7 @@ Team jobs, Workspace tasks and manual Runs do not carry it, so their calls stay- the wait keys by the approval id, because `call_key` is not unique when a provider repeats a tool id (C3 P14).**7. Replay and the test gates.**-- **The new type:** register `ApprovalWorkflow` in `framework_workflows` (`services/temporal/workflow_registry.py:20-25`). Record it in the golden identity file: `workflow_types`, its identities, and `signal:nudge`.+- **The new type:** register `ApprovalWorkflow` in `framework_workflows` (`services/temporal/workflow_registry.py:20-25`). The golden identity file records it (`workflow_types`, its identities and `signal:nudge`) when the next release regenerates the golden; until then a reviewed `patch_entries` entry names it in `new_types`.- **Two test gates change,** in tests and data only:- `test_replay_corpus.py:69` requires N-1 histories only for the types the previous release had.- `test_workflow_identity_golden.py:26-35` accepts a reviewed entry that names a new type or a generation flag in place of a `workflow.patched` marker.@@ -446,19 +446,18 @@ Team jobs, Workspace tasks and manual Runs do not carry it, so their calls stay- A run is not timed out while a pending turn row carries its `run_id`.- The window restarts at the owner's latest decision on the run's rows. That is `decided_at`, ignoring `approved_by == "auto"`, the same way the window restarts at Resume (`:744`, `:763-765`).- The closure check stays (`:768-778`).- - One store helper, `run_wait`, answers both questions.+ - One helper, `waiting.run_waited`, answers both questions, for a run already past its window. It counts turn rows only: since AP.2c a CLI draft carries its run id too.- 1b.14's cancel goes inside the same branch, after AP.4c.-- **A closed run:** when the watchdog ends a v1 run whose workflow closed (`:768-778`), it cancels the run's pending rows.+- **A closed run:** when the watchdog ends a run whose workflow closed (`:768-778`), it cancels the rows its turns waited on (`waiting.cancel_waits`). Its drafts stay for the owner to send.- **Chat Stop** is the employee's pause (D13; `services/chat/handlers.py:471-487`). Nothing in chat changes, and `request_stop` stays legacy-only.- **A new owner message while a run waits** (D3, D14):- - It is handled in the `RunInProgress` arm (`handlers.py:318-319`). Three conditions must all hold:- - the lane run's generation is v1;+ - It is handled in the `RunInProgress` arm (`handlers.py:318-319`). Two conditions must both hold:- the message is plain text, with no button press and no attachments;- - the run has pending turn rows.+ - the lane run has pending turn rows, which only a v1 generation makes.- Then `send_chat_message` declines those rows, with the text as the note and the decision key `chat:<client_message_uid>`.+ Then `send_chat_message` declines those rows (`waiting.decline_with_message`), with the text as the note and the decision key `chat:<client_message_uid>`. The wait reads `by_message`, because the row's decision key starts with `chat:`, and the turn reads "The owner sent a message instead of answering; nothing happened. Their message: …", with nothing about trying again.- It saves no chat row and starts no run.- - A resend with the same `client_message_id` finds the decision by its key and gets the same answer.+ - A resend with the same `client_message_id` finds the declined rows by that key before admission (`waiting.declined_with`), so it gets the same answer even once the run has ended.- Otherwise, or when the decline loses the race to the card, it answers `run_in_progress`, as today.- The answer is `{success: true, message_id: null, run_id: null, declined: {run_id, approval_ids}, delivery: "now" | "queued"}`. O5 is settled.- **The client** (AP.3):diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.mdindex 755f1078..9e4ee234 100644--- a/docs-internal/chat_protocol.md+++ b/docs-internal/chat_protocol.md@@ -116,7 +116,7 @@ All are WebSocket request/response handlers with snake_case payloads. Failures a| Handler | Request | Response ||---|---|---|-| `send_chat_message` | `{session_id, message, role: "user", timestamp?, client_message_id?, attachments?: [{path}], options?: Options, ui_event?: {part_id, element_id, action, params}}` | `{success, message_id, run_id, delivery: "now" \| "queued", timestamp}`; `run_id` is null when the message starts no run; `attachment_rejected` for files that cannot go (see [Attachments](#attachments)); `model_unavailable` for a model that can't answer (see [Model and thinking](#model-and-thinking)) |+| `send_chat_message` | `{session_id, message, role: "user", timestamp?, client_message_id?, attachments?: [{path}], options?: Options, ui_event?: {part_id, element_id, action, params}}` | `{success, message_id, run_id, delivery: "now" \| "queued", timestamp}`; `run_id` is null when the message starts no run; `{success, message_id: null, run_id: null, declined: {run_id, approval_ids}, delivery, timestamp}` when it answered a call the lane run waits on (see [Approvals](#approvals)); `attachment_rejected` for files that cannot go (see [Attachments](#attachments)); `model_unavailable` for a model that can't answer (see [Model and thinking](#model-and-thinking)) || `get_chat_messages` | `{session_id, limit?, all_generations?}` | `{success, protocol_version, session_id, messages, thread: {active_leaf_id, revision}, active_runs: [RunSnapshot]}` || `chat_subscribe` | `{session_id}` | `{success, session_id, hub_epoch, active_runs: [RunSnapshot]}` || `chat_unsubscribe` | `{session_id}` | `{success, session_id, hub_epoch}` |@@ -159,22 +159,30 @@ chat reducer remain terminal even when a control snapshot is present.|---|---|---|| `list_approvals` | `{workflow_id?, status?: <row status> \| "open" \| "recent", run_id?, kind?: "gate" \| "tool_call" \| "effect", limit? (at most 100)}`; `status` defaults to `pending` | `{success, approvals, counts: {workflow_id: pending}, server_time}` || `get_approvals` | `{approval_ids}` (at most 100) | `{success, approvals, server_time}` |-| `decide_approval` | `{approval_id, decision: "send" \| "undo" \| "discard" \| "restore" \| "retry" \| "dismiss", decision_key, text?, subject?, confirm?}` | `{success, approval, idempotent?, will_send_on_resume}` |-| `get_ask_first` | `{workflow_id}` | `{success, workflow_id, ask_first: bool \| null, revision}` (null: the workflow has no rule) |-| `set_ask_first` | `{workflow_id, ask_first, expected_revision?}` | `{success, workflow_id, ask_first, revision, replies_gated, needs_apply}`; `rule_conflict` (with the current value) when it moved |+| `decide_approval` | `{approval_id, decision: "send" \| "undo" \| "discard" \| "restore" \| "retry" \| "dismiss", decision_key, text?, subject?, confirm?, note?, always?}` | `{success, approval, idempotent?, will_send_on_resume}` |+| `get_ask_first` | `{workflow_id}` | `{success, workflow_id, ask_first: bool \| null, mode: "outside" \| "everything" \| "money_only" \| null, revision}` (null: the workflow has no rule) |+| `set_ask_first` | `{workflow_id, ask_first \| mode, expected_revision?}` | `{success, workflow_id, ask_first, mode, revision, replies_gated, needs_apply}`; `rule_conflict` (with the current values) when it moved |+| `list_approval_allows` | `{workflow_id}` | `{success, workflow_id, allows: [{id, node_type, operation, scope_kind: "host" \| "recipient" \| "operation" \| "tool", scope_value, label, created_at}], money: [{node_type, operation, label, allow_id}]}`; `money` is the employee's money tools and operations, `allow_id` set where one is switched on |+| `add_approval_allow` | `{workflow_id, node_type, operation?}`, one of the `money` options | `{success, allow}`; `invalid_request` for anything else |+| `remove_approval_allow` | `{workflow_id, allow_id}` | `{success}`; `not_found` |`open` lists what the owner may still act on, or is on its way: pending, approved and not handed on, sending,failed, and discarded while it can be restored. `recent` lists everything, newest first. Only the owner's own draftsand workflows answer; any other id reads as `not_found`. `decide_approval` errors: `already_decided`, `expired`,`cancelled`, `too_late` (Undo after it went, Restore after its window), `confirm_required` (a retry of a send thatbroke off), `approval_conflict`, `send_unavailable` (nothing could start the send; the draft is back as it was),-`not_found`, `invalid_request`. The same `decision_key` again answers `idempotent` with the row as it is.+`not_found`, `invalid_request` (also for `always` on a card that offers no rule, and a `note` over 50,000+characters). The same `decision_key` again answers `idempotent` with the row as it is. `note` goes with `discard`;+`always` with `send` saves the rule the card offers (`always` in its summary).**ApprovalSummary**: `{approval_id, workflow_id, node_id, kind: "gate" | "tool_call" | "effect", status, channel,channel_label, action?, recipient, recipient_label, body, subject?, context_excerpt?, details: [{label, value}],created_at, expires_at, revision, max_length, editable, approved_by?: "owner" | "auto", edited?, undo_until?,restore_until?, consumed_at?, outcome?: {certainty: "sent" | "not_sent" | "unknown", error?, at?},-outcome_labels: {sent, failed}, run_id?, tool_call_id?, ui_part_id?, agent_node_id?, deployment_state?}`. `status`+outcome_labels: {sent, failed}, run_id?, tool_call_id?, ui_part_id?, agent_node_id?, deployment_state?, note?}`, and+on a `tool_call` row `approval_class: "read" | "write" | "send" | "money" | null`, `generic` (a tool with no spec: the+card shows what it runs with), `waits` (its turn waits on it) and `always: {label, scope} | null` (the rule Always+allow would save). `status`is `pending`, `approved`, `sending`, `sent`, `failed`, `discarded`, `expired` or `cancelled`; see[Approvals](#approvals). `outcome_labels` is what the card says once it went and when it did not: a held toolcall's plugin words it (its `ApprovalSpec.outcome_labels`, "Email sent" for the email apps), a gate's draft says@@ -604,6 +612,38 @@ What an employee sends to someone waits for the owner's OK while its workflow as(`DEFAULT_TIMEOUT_HOURS`); the chat watchdog ends it on its next round (`reconcile.expire_due`), announces it andtells the employee. A decision that reaches a draft past its expiry ends it the same way and answers `expired`.Rows are kept until their workflow is deleted.+- **Generations that wait for the owner** (RFC-0007, `approval_wait_version` 1, frozen per generation). Start does+ not write it yet, so every generation works as above until it does. In such a generation:+ - **What asks** is the workflow's mode (`workflow_rules.mode`), applied to the call's class+ (`services/approvals/classes.py`), for every tool an agent calls, with or without a spec.+ - `outside` asks before sends and money, `everything` before writes too, and `money_only` before money and+ deletes only. A rule with no mode follows Ask first: on is `outside`, off is `money_only`.+ - A read never asks, and a tool the class table does not list is a send.+ - A tool with no spec asks on a generic card. The browser asks only when it fetches a URL, and otherwise runs+ read-only. Stripe asks instead of being refused.+ - **Always-allow rules** (`approval_allows`, `services/approvals/allows.py`) let a matching call run unasked.+ - A card whose turn waits on it offers one (Always allow), but never for money: the employee's list switches+ money tools on instead (`list_approval_allows`).+ - The chat shows the Ask first menu, with "Allowed without asking", in place of the chip while the latest+ generation waits (`approval_wait_version` in the control snapshot, from `serialize_control`).+ - **The agent answering a chat run waits in its turn** (a `turn` row, `waits: true`). AgentWorkflow waits in+ `ApprovalWorkflow` for the answer ([Temporal Architecture](./TEMPORAL_ARCHITECTURE.md)).+ - Allow runs the call in the turn, once, and the model reads its real result. There is no Undo, no+ `ApprovedToolCallWorkflow`, no Restore and no `[update]` note.+ - Decline (with an optional `note`), expiry and a cancel tell the model that nothing ran.+ - Chat Stop pauses the employee while the call waits; a call allowed meanwhile runs after Resume.+ - **Every other held call** (another run's, a teammate's, a CLI or in-process agent's) is a draft. A CLI or+ in-process draft is keyed by its call id (an MCP call's request digest), and a call without one is refused.+ - **A message sent while the turn waits** declines the call instead of starting a run.+ - The message is the note, nothing is saved in the thread, and `send_chat_message` answers `declined`. The same+ `client_message_id` again answers the same.+ - The model reads that the owner sent a message instead of answering.+ - A message with files, or a button press, answers `run_in_progress`.+ - **The run's clock.** The chat watchdog does not time out a run whose turn waits, and the owner's answer starts+ its window again. When the run's workflow closes, or a Reset ends its generation, the calls its turns waited on+ are cancelled (`waiting.cancel_waits`).+ - **The approvalGate** waits outside Stop's checkpoint: Stop completes while it waits, and the node after it runs+ after Resume.- **Broadcast.** `approval_lifecycle` (source `opencompany://services/approvals`, type`com.opencompany.approval.<stage>`: requested, decided, undone, restored, sending, sent, failed, expired,cancelled), identity only, with the chat run when there is one.diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex d6be9cb4..03f770fb 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -115,7 +115,10 @@ and never starts loops then. Toasts are a second sonner toasterover `--dur-toast-out` (`.pill-toaster` in index.css replaces sonner's slide).Start, Resume and Stop say they went through ("{Name} started" / "resumed" /"stopped"), and so does turning Ask first on or off in the chat ("{Name} will-ask before sending" / "will send without asking").+ask before sending" / "will send without asking"). Where the chat shows the+mode menu instead (see [Asking before sending](#asking-before-sending)),+choosing a mode says "{Name} will ask before anything outside" / "before+everything" / "only before money and deletes".### Deleting an employee@@ -918,6 +921,26 @@ unless it was approved, and the recipient always comes from the run'strigger. Full contract: [Chat Protocol, Approvals](./chat_protocol.md#approvals)and [approvalGate](./node-logic-flows/workflow_triggers/approvalGate.md).+A generation that waits for the owner (RFC-0007, `approval_wait_version` 1)+works differently. Start does not write that flag yet; it turns on one release+after the code that reads it.+- **Ask first becomes a mode,** chosen from a menu in place of the chip+ (`composer/AskModeMenu.tsx`): "Before anything outside" (`outside`, what Ask+ first on meant), "Before everything" (`everything`, its own files and notes+ too) or "Only for money and deletes" (`money_only`, what Ask first off+ became).+- **Every tool an agent calls** asks by its class (read, write, send, money;+ `services/approvals/classes.py`), with or without an `approval` spec.+- **The employee answering the owner in chat waits for the answer in its+ turn,** then goes on with the real result. Allow runs the call at once, with+ no Undo. Decline can carry a note. A message typed while it waits declines+ the call, the message its note.+- **Always allow** on a card adds a rule. The menu's "Allowed without asking"+ lists the rules and switches money tools on.+- **Stop pauses the employee** while a call waits. The call keeps waiting, and+ a call allowed meanwhile runs after Resume. An `approvalGate` no longer+ holds Stop.+The summary's `asks_first` follows the live rule (for a workflow built in Devmode with no rule, whether it has an approval gate), shown in a line under theemployee's page. A graph an older builder made (`builder_version` below 3) is@@ -1052,13 +1075,13 @@ WebSocket requests (snake_case; failures come back as `success: false` with an| `apply_employee_changes` | `{workflow_id, idempotency_key}` | `{employee}`: running ends running, paused or failed ends ready, ready is left alone. Errors: `invalid_request`, `not_found`, `conflict`, `restart_failed` (the last two with `employee`) || `rename_employee` | `{workflow_id, name}` (spaces collapsed, at most 40 characters) | `{employee}`: renames the workflow (a new slug, the workspace folder moved, `workflow.renamed` sent), and each agent's instructions a hire wrote take the new name in their opening ("You are <name>, ..."); instructions the owner rewrote keep their words. Agents read them on every run, so nothing restarts. Errors: `invalid_request`, `not_found`, `save_failed` || `set_employee_photo` | `{workflow_id, path \| null}` | `{employee}`: `path` is a PNG, JPEG, WebP or GIF the owner uploaded under `uploads/` (`POST /api/workspace/{workflow_id}/uploads`), at most 5 MB (`EMPLOYEE_PHOTO_MAX_BYTES`); `null` takes the photo away. Errors: `invalid_request`, `not_found`, `invalid_photo` (with `detail`), `unsupported` (a workflow built in the editor has no employee row to keep it on) |-| `send_chat_message` | `{message, role: "user", session_id: <workflow_id>, timestamp, client_message_id?, options?: {web?, model?, effort?}}` (`model_unavailable` with `detail` when the model chosen can't answer) | `{timestamp, delivery, message_id, run_id}`: `"now"` while running, starting or resuming; `"queued"` while paused or pausing (it runs on Resume). In any other state `not_running`, and nothing is saved or sent; `run_in_progress` (with the live `run_id`) while a run is live. `run_id` is null when no deployed chat trigger answers the session. Session `"default"` works as before, with no `delivery` |+| `send_chat_message` | `{message, role: "user", session_id: <workflow_id>, timestamp, client_message_id?, options?: {web?, model?, effort?}}` (`model_unavailable` with `detail` when the model chosen can't answer) | `{timestamp, delivery, message_id, run_id}`: `"now"` while running, starting or resuming; `"queued"` while paused or pausing (it runs on Resume). In any other state `not_running`, and nothing is saved or sent; `run_in_progress` (with the live `run_id`) while a run is live, unless its turn waits on the owner's answer to a call: then a plain message declines that call and answers `{message_id: null, run_id: null, declined: {run_id, approval_ids}, delivery}` ([chat_protocol.md](./chat_protocol.md#approvals)). `run_id` is null when no deployed chat trigger answers the session. Session `"default"` works as before, with no `delivery` || `get_chat_messages` | `{session_id, limit?, all_generations?}` | `{protocol_version: 2, messages, thread, active_runs}`, messages oldest first, each `{id, role, message, timestamp, run_key, ...}` (the full shape is in [chat_protocol.md](./chat_protocol.md#messages)). Controlled active run snapshots also include their owning `workflow_control`. Timestamps carry their UTC offset; `run_key` is the generation the row was written in. Without `all_generations`, only the latest generation's rows (none after a Reset; every row when the workflow was never started). A failed read answers `read_failed`, never an empty thread || `stop_chat_run` | `{run_id, expected_revision, idempotency_key}` for controlled runs; `{run_id}` for legacy | Controlled: generation Stop payload with `run_id` and `resumable: true`; the owning root is checked. Legacy: terminal chat `stopping` / `stopped`. Full acknowledgement and error contract: [chat_protocol.md](./chat_protocol.md#controlled-stop-acknowledgement) || `get_chat_models` | `{session_id: <workflow_id>}` | `{auto, models, efforts}`: the model picker's rows, each `{id, name, short, description, effort, effort_note, available, reason}`; the owner's choice is `chat_model` / `chat_effort` in `get_user_settings`, saved with `save_user_settings` (refused with `chat_choice_refused` and `detail`) || `workspace_steps_list` | `{workflow_id}` | `{workflow_id, steps}`, oldest first, each `{id, surface: "browser" \| "canvas" \| "mobile", text, node_id, at}` (`at` an ISO time). Only the workflow's owner reads them (`access_denied` otherwise, and always for the internal worker socket) || `list_approvals` | `{workflow_id?, status?, limit <= 100}` | `{approvals, counts, server_time}` |-| `decide_approval` | `{approval_id, decision, text?, subject?, decision_key}` | `{approval, will_send_on_resume}` |+| `decide_approval` | `{approval_id, decision, text?, subject?, note?, always?, decision_key}` | `{approval, will_send_on_resume}` || `delete_workflow` | `{workflow_id}` | `{workflow_id, contexts_archived, context_archives_pending}`; `DELETE /api/database/workflows/{id}` is the same handler. Error `workflow_shutdown_failed` (with `detail`) when stopping the employee failed: nothing was deleted |Broadcasts, all CloudEvents events broadcast directly (no Temporal