Files
Kelx/ADPANEL-AGENT-WORKER-HANDOFF.md
2026-11-30 16:32:37 +00:00

113 lines
31 KiB
Markdown

# ADPanel Agent Worker: Implementation Handoff
## Current Tool Loop
This section describes the implemented server-page Agent. The original migration brief below is historical; its old route locations and inline execution notes are not the current path.
1. [The browser client](public/js/agent-live.js) submits a new message to [the live Agent router](routes/agent-live.js). [Admission](AgentWorker/admission.js) stores the prompt and job together under an account-bound request key. The server records the access mode for this turn. General access permits proposing allowed changes for review; Read only permits diagnostics and does not grant any new authority.
2. [The worker](AgentWorker/worker.js) claims the job. [The runner](AgentWorker/run-job.js) fetches current server identity and permissions from [the panel diagnostic dispatcher](AgentWorker/panel-diagnostics.js), then loads the owned transcript up to the submitted message. [The action schema](AgentWorker/action-proposal.js) and model instructions derive from the same permission rules. Reviewed changes are available only in live chats on supported node-backed servers; Planner and Scheduler remain diagnostic-only.
3. [The conversation loop](AgentWorker/conversation.js) supplies tools, validates calls, reads current state, and sends the results back to the model. [Provider adapters](AgentWorker/provider-turns.js) keep their respective call/result formats. A model without native calling can request the same offered tools through a standalone tagged JSON block. Tool results and historical chat are context, not authorization. [Run and provider budgets](AgentWorker/budgets.js) bound cost, latency, and corrective turns.
4. A proposal pauses the turn. [The panel review handler](AgentWorker/action-review.js) binds the exact action to the owner and server, checks current permissions and the one-use approval, and checks file versions before applying edits. [The job store](AgentWorker/job-store.js) records receipts and action history before resuming from the original request and recorded outcomes. The model can choose the next step, but only the panel can apply it. Unknown write outcomes are not replayed; a console delivery acknowledgement does not establish the command's effect.
## Edit Refusal Investigation
- **Availability was ambiguous.** An allowed file operation could coexist with a prompt saying `server status only`. The worker now gives the model separate diagnostic capabilities and the specific review actions it can propose. Read only, missing permissions, and unsupported targets have distinct explanations. The reported false refusal gets one recovery attempt when file actions are offered; repeated refusal does not become a success claim.
- **Gemini continuation was incorrect.** Gemini 2.5 Flash-Lite supports function calling. `generateContent` call IDs are optional; reply with the matching ID only when Google supplied one. Keep model-part ordering and opaque thought signatures unchanged. Do not dispatch from thought text, blocked or incomplete responses. A malformed native call can be regenerated once with the prior diagnostic results intact.
- **The text fallback was under-specified.** Its request now says how to call the same allowed tools without native functions. A tagged proposal rejected for invalid arguments can be corrected once with the validation feedback and prior read results still in context. A permission denial is not an argument to repair.
## Continuing Multi-Step Work
- **Keep the goal through clarification.** When the user supplies one missing detail, keep the rest of the requested outcomes. When the user delegates a harmless choice, choose within the requested scope and prepare the actual change for review. The prompt applies this to any supported file type; it never supplies authorization.
- **Return the recorded outcome for repeats.** Same-turn receipts stop re-proposing confirmed or declined creations and paths already refused as existing. A confirmed descendant can also settle an otherwise redundant parent creation. Return the reason to the model before it chooses the next step. Two consecutive duplicate-only native batches stop without another review; the text protocol has one in-context correction. An independent valid call in the same batch is still considered.
- **Carry history without replaying it.** Subsequent messages also receive a bounded file-outcome summary scoped to the chat owner, exact server, and account epoch. It contains action, path, and status, not raw file contents, commands, or approval tokens. It is historical evidence, not a current filesystem check or authority for a new request.
This separates flexible judgment from enforcement, as described in [Claude Code's published best practices](https://code.claude.com/docs/en/best-practices.md#deterministic-and-non-deterministic-instructions). [Aider's public edit prompt](https://github.com/Aider-AI/aider/blob/main/aider/coders/editblock_prompts.py) provides a useful example of precise edits grounded in existing file text. The isolated staging run makes a fixture provider repeat the first completed creation, checks that no duplicate review or write results, then verifies the remaining changes and a later read from the same chat.
### Reference And Verification
- [Gemini 2.5 Flash-Lite capabilities](https://aistudio.google.com/docs/models/gemini-2.5-flash-lite) and [Gemini GenerateContent REST types](https://aistudio.google.com/api-reference/generate-content#Resource:Content): use the contract for the API actually called. The newer Interactions API does not use the same payload. Don't force a tool on every turn; greetings and ordinary answers need no call.
- [OpenAI function calling](https://developers.openai.com/api/docs/guides/function-calling), [Claude tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls), and [How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works): the application owns the loop from context to tool call to verified result. Good tool descriptions and typed results help the model choose the next step.
- [Human-in-the-loop approvals](https://openai.github.io/openai-agents-python/human_in_the_loop/) and [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents): pause and resume using trusted server state, keep changes scoped to the reviewed operation, and stop on repeated failure or exhausted budgets.
- [Agent evaluations](https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents): check the actual outcome as well as the transcript. [The provider fixtures](tests/server-agent-provider-http.test.js) test exact refusals and protocol failures; `node scripts/verify-agent-worker-staging.js` runs authenticated requests through an isolated panel, worker, database, and synthetic node. Inspect exact resulting file bytes, zero writes before approval, and persisted history after resumption. These are deterministic integration tests, not a measurement of a live model's reliability. A live-model evaluation should use disposable data and multiple trials, never production credentials or files by default.
## Assignment
Implement and verify this **major ADPanel update**, not another proposal. Move the server-page ADPanel Agent into one separately supervised **Node.js** worker. The primary workload is messages sent by people in the **Agent scene**, not just jobs from Planner or Scheduler. Move the Agent-specific background execution too, so one switch really stops all server-page Agent execution. Keep the panel responsive while handling a burst of 300 live-chat submissions, and measure separately whether the deployment can sustain 300 runs actively generating at once. Do not claim either target before its acceptance test passes.
Add an operator-owned `.env` switch, `ADPANEL_AGENT_ENABLED=ON|OFF`. After either `systemctl restart adpanel` or a plain PM2 restart of the `adpanel` app, ON must start or reconcile the worker and restore the feature; OFF must stop the worker, block all Agent execution, and remove the Agent UI, including its Accounts-tab grant toggle. Install and manage the worker through **option 1, Initialize Panel**, in [initialize.sh](initialize.sh#L6043). Keep it independent of PM2 web-worker scaling and give it a resource budget.
Do not change the separate dashboard Assistant ([its route mount](index.js#L19698)), the SSH terminal, the node daemon's public interface, or ordinary Planner, Scheduler, and Accounts features. Do not reintroduce model-selected writes, console commands, power actions, or backup changes. Read [AGENTS.md](AGENTS.md) first: one implementation per responsibility, extract from the monoliths, share existing permission/relay helpers, and preserve wire and authorization tests. Do not provision or restart a real installation, edit its live `.env`, or send load to a paid provider without approval.
## Read This First
Line numbers identify the reviewed checkout; use the symbols and route strings if the revision has moved. Start with the first three rows before exploring background jobs.
| Area | Where to read and what it owns |
| --- | --- |
| **Actual Agent scene** | [views/bot.ejs, `#aiHelpModal`](views/bot.ejs#L6778) is `data-page-id="aihelp"` on the server page. [Provider setup](views/bot.ejs#L6807), [chat view](views/bot.ejs#L6949), and [composer](views/bot.ejs#L7010) live inside it. Launchers are [`#dockAiHelp`](views/bot.ejs#L4765), [`#aiHelpBtn`](views/bot.ejs#L5612), and [`#dockAiHelpBottom`](views/bot.ejs#L6663); all use `open-ai-help`. The authenticated [`GET /server/:server`](index.js#L56715) resolves the canonical server and [renders `bot`](index.js#L56774). The template [loads its Agent history helper and main browser script](views/bot.ejs#L72). |
| **Actual live send** | The [action registry](public/js/bot.js#L678) opens [`openAiHelpModal`](public/js/bot.js#L13415). [Enter](public/js/bot.js#L16692) and [Send](public/js/bot.js#L16717) call [`sendAiMessage`](public/js/bot.js#L14374). It selects a model, loads or creates a chat, saves the prompt, calls [`callAiBackendProxy`](public/js/bot.js#L15821), saves the reply, and refreshes history. [`stopAiGeneration`](public/js/bot.js#L14364) currently aborts the request. Read the [active-run and transcript caches](public/js/bot.js#L12960) for chat switching. The [legacy stream code](public/js/bot.js#L14891) references `/api/ai/agent/stream` and `/approve`; these are not the mounted live path. Do not base the migration on them. |
| **Live backend and providers** | [Pre-parser authentication and large-body dispatch](index.js#L11660) precede [`POST /api/ai/chat`](index.js#L34329), which awaits [`completeAiChatConversation`](index.js#L31931) in the web worker. Read the [provider registry](index.js#L28036), [discovery dispatcher](index.js#L28682), [provider-key routes](index.js#L28709), [model route](index.js#L34704), [conversation tool dispatcher](index.js#L30920), and [bounded provider HTTP transport](services/server-agent-provider-http.js#L5). Native adapters start at the [OpenAI-compatible turn](index.js#L30121); also trace Cohere, Google, and Anthropic, and the generic fallback. |
| **Diagnostics and live authority** | Read the [Agent tool definitions and prompt builder](utils/bot-ai-tools.js), the [background file dispatcher](index.js#L33337), [directive parser](services/server-agent-file-directives.js), [live job permission reader](services/server-agent-job-auth.js#L7), and [Planner permission envelope](utils/planner-agent-perms.js). [`getConsoleHistorySnapshot`](index.js#L61588) reads the node's authoritative stream for remote servers and a panel memory buffer for local servers. A separate process cannot read that memory by importing a module. |
| **Storage and accounting** | [`ai_chats`](mysql-schema.sql#L160), [`ai_messages`](mysql-schema.sql#L174), and [`ai_agent_jobs`](mysql-schema.sql#L200) are the durable records. Read [schema bootstrap](db.js#L287), [Agent runtime schema/migrations](index.js#L34803), [ownership and transcript paging](services/server-agent-chat-ownership.js), [chat CRUD](index.js#L35101), [model selection](index.js#L34251), and [owner-scoped job status](index.js#L34296). The [pool](db.js#L50) is shared with normal panel requests today. |
| **Background execution** | Existing [enqueue](index.js#L32500), [capacity/pump module](services/server-agent-queue.js), [pump wiring](index.js#L33295), [atomic claim](index.js#L33304), and [job execution](index.js#L33867) serve background jobs. The [web scheduler leader](index.js#L63635) starts this poll today; [shutdown](index.js#L15380) stops it. The current 200 + 5 adaptive limit belongs to **background** runs, not live chat. |
| **Planner and Scheduler** | [Planner cards](public/js/bot.js#L7980) dynamically create both card-click and button sends; [send logic](public/js/bot.js#L8375), [action-token mint](index.js#L35681), and [send route](index.js#L35822) are separate. [Scheduler action options](views/bot.ejs#L6395), [create route](index.js#L49727), [fire branches](index.js#L14753) and the enqueue helpers for [next Planner item](index.js#L32801) and [custom Agent prompt](index.js#L33040) handle `planner_next_to_agent` and `agent_prompt`. Do not disable the scheduler itself. |
| **Accounts and entitlement** | [Settings route](index.js#L46196) renders the [Accounts list container](views/settings.ejs#L1318). The actual toggle is produced by [`renderAccounts`](public/js/settings.js#L6760) as [`.agent-access-toggle`](public/js/settings.js#L6822), with a [submit handler](public/js/settings.js#L12679). Trace the [Accounts API](index.js#L54090), [grant route](index.js#L54426), and both [token mint sites](index.js#L25303) and [Accounts response mint](index.js#L54162). The server page reads permissions via [`fetchPerms`](public/js/bot.js#L2585). The stored `agent_access` flag and [`hasAgentAccess`](index.js#L28245) also serve [SSH](index.js#L22628); the feature switch is not a replacement for this entitlement. |
| **Install and supervision** | Option 1 calls [`initialize_panel`](initialize.sh#L5165), which [starts the panel](initialize.sh#L5566) after dependency, `.env`, and database setup. Read [systemd provisioning](initialize.sh#L1520), [uninstall](initialize.sh#L5640), the [PM2 startup launcher](scripts/adpanel-runtime.sh#L31), [ecosystem template](ecosystem.config.template.js), [size generator](scripts/generate-ecosystem.sh#L62), [autoscale reload](scripts/adpanel-autoscale-monitor.sh#L27), and [root-owned service helper source](privileged/adpanel-priv#L375). Begin panel startup integration at [`startServers`](index.js#L63042). |
## Architecture Decision
Use **a standalone Node.js entry point supervised by a sibling systemd unit**, not a second PM2 cluster and not a subprocess spawned by each web worker. Moving the existing JS is substantial but manageable. Porting it to Go would also rewrite nine provider configurations, four native tool protocols, response parsing, permission integration, timeouts, and recovery, and require compatibility testing for each. Node can already keep many small requests in flight. The shared CPU, DB, attachment bytes, and provider quotas do not disappear with a language change. Revisit Go only after profiling the isolated worker shows a bottleneck it can address.
The web app owns sessions, browser authorization, feature gating, server identity resolution, public read/status APIs, and bounded job admission. The worker owns model calls, model discovery and credential validation, diagnostic orchestration, job claims, cancellation, and result publication. Use the existing SQL queue as the durable source of truth and one authenticated private channel for any worker/panel calls that cannot use it. No public worker port, second execution engine, duplicated auth rules, or fallback that runs a model in the web process.
## Implementation Order
### 1. Establish the feature contract
- Document the switch in [.env.example](.env.example) and the operator guide. Parse the actual panel `.env` as data through one shared resolver, with a consistent absolute path, rather than trusting a stale PM2 `process.env` value or sourcing it as shell code. Accept the explicit `ON` and `OFF` values. Missing or invalid values mean OFF, with a helpful startup warning for invalid values and an upgrade notice when the key is missing. New installs write OFF; upgrades preserve explicit values and require opt-in when missing. Do not log file contents, expose secrets, or add a browser-admin switch.
- Apply configuration on restart. Define **OFF** as an unavailable feature even for admins and stale tabs. Define **ON but not ready** as a temporary worker error, not OFF and not permission denied; return a bounded retryable response and never execute inline. Keep desired state separate from readiness and verify the worker has the expected protocol/version and current state before accepting expensive work. The rest of the panel must start if the worker fails.
- Decide and test the OFF transition before wiring it: reject new work, stop claims, cancel or mark interrupted active and pending Agent work without deleting chats/keys/grants, and fence late results. Keep scheduled definitions; skip Agent occurrences due while OFF (including one-shot occurrences), and resume future occurrences without backfilling missed work or marking Planner items done. Use a durable fence or equivalent if a restart overlaps a schedule fire. Do not feed intentional skips into the Scheduler failure streak or delete unrelated tasks.
### 2. Extract execution without changing authority
- Move the provider registry/adapters, conversation loops, job runner, and execution-only timers into small services with injected dependencies. Do not `require` [index.js](index.js) from the worker: importing it starts panel services. Move or reuse the single implementations of job validation, reads, queue recovery, permissions, and provider transport. Use existing node HTTP/FS helpers with their timeouts, size limits, and origin/target checks. Keep schema migration ownership explicit; the worker may verify readiness but should not independently race the panel's DDL.
- Preserve session/account binding, account ID ownership, suspension and revocation checks, canonical server ID binding, Planner author/prompt revision validation, and file permission envelopes. Re-read authority at claim time, before protected diagnostic reads, and before publishing; a queued snapshot, model arguments, or a worker connection alone is not authorization. Do not expose general node forwarding. For local console history, use a typed, bounded, authenticated internal read against its existing owner; verify the correct source across multiple PM2 workers rather than inventing a second history.
- Use a private Unix-domain socket with restricted directory/peer access for bounded control or diagnostic RPC if needed. Authenticate the service and bind privileged reads to the job/account/server identity. Keep the public API same-origin through the panel. Provider-key writes remain admin-authorized, token-protected and securely persisted; do discovery/validation and other outbound provider I/O in the worker. Do not put credentials in jobs, client responses, arguments, or logs. Preserve provider hard timeouts, response bounds and cancellation.
### 3. Queue the live path end to end
- Make the actual `POST /api/ai/chat` validate the current session and server permission, verify the owned chat or create one, and atomically admit the job and store the user message. Return `202` with the canonical chat and job IDs. Use an idempotency key bound to the submitting account and submission, covering network retries and double-clicks. Reuse the existing authenticated queue/store code and its transaction invariants; do not use an unbounded queue in each web worker.
- Give the worker bounded context from the owned transcript and stored submission (for example a message watermark), not a client-supplied transcript replay. Store attachments once; enforce size, count, and retention limits before they amplify memory or DB I/O. Make the worker persist one assistant result and the terminal status under the same claim/attempt fence. No second browser-side writes for that exchange. Update the live browser send path and asset version together; a stale client must fail clearly or use an adapter to the same admission path, never start an inline or duplicate run.
- Reuse or extend owner-scoped job status for live chat; add owner-scoped cancellation with the same session/origin protections. Use bounded backoff polling or an existing push mechanism, not an unbounded poll per chat. Preserve attachments, chat switching, prompt/reply order, history paging, and **Stop** while queued and running. Handle Stop before submission acknowledgment via the request key or a pending cancellation when the job ID arrives. Abort current provider I/O on accepted cancellation and prevent new turns or a late result. Explicitly define the post-`202` disconnect behavior: switching tabs or reconnecting should not silently resubmit; cancellation is intentional. A provider may already have accepted or billed a request.
- Preserve single ownership of claims and transactional admission under concurrent accepts. Check existing SQL advisory-lock/transaction assumptions rather than treating admission counts as a distributed semaphore. Fence restart/reclaim/late writes with a claim identity and recover stale runs without silently replaying an ambiguous billable turn. Preserve Planner completion only after the proper claim publishes success. Update fresh-install schema and idempotent upgrade migrations together with backward compatibility for existing chats and job rows. Reuse one durable execution source; an optional wake-up notification is not a second queue.
### 4. Enforce OFF across ingress and the complete UI
- Add a central Agent feature gate before the large-body parser and any expensive admission. Cover chat, chat history, selection, job status/cancel, key/model configuration and discovery, Planner send and token mint, Agent Scheduler creation/fire and enqueue, and worker claim/start. Reject direct requests, even with valid admin sessions or previously minted tokens; account for Express route casing and trailing slashes. Do not weaken existing auth, CSRF, action tokens, or rate limits. Keep ordinary account deletion and data cleanup intact.
- Pass one server-owned feature boolean to both templates and any required API bootstrap. When OFF, omit the Agent scene and all launchers from the rendered DOM, do not start Agent fetches or polling, and remove both Agent options and their controls in Scheduler. Hide Agent schedule presentation while OFF without deleting its backing data. Remove Planner send buttons, whole-card send actions and send hints while leaving normal Planner CRUD and drag behavior intact. Check direct navigation to the scene, browser history, desktop/mobile docks, stale tabs, and no missing-DOM exceptions.
- Omit only the Agent grant toggle from Accounts, including dynamic refresh/search rows and the step-up entry for that action. Do not issue its action tokens or allow its mutation route while OFF. Leave manage access and other account actions in place. **Do not erase `agent_access`, invalidate unrelated permissions, or globally change `hasAgentAccess`.** Preserve the SSH behavior from before the switch. When ON, re-render the same controls and restore normal per-account authorization, not access for everyone.
### 5. Provision and reconcile the service
- Extend the idempotent option-1 provisioning after DB/env and dependencies are ready and before starting the main panel. Install a root-owned `adpanel-agent.service` running a fixed Node entry point as an unprivileged user, with no public listener and only required writable locations/credentials. Do not run panel-writable scripts as root or make the `.env` broadly readable. Provision the unit even when OFF without enabling it independently. Use `PartOf=adpanel.service` and appropriate systemd ordering/lifetime checks; `PartOf` propagates lifecycle events, it does not decide whether the unit should start. Do not create a dependency cycle or wait in a parent pre-start hook for a service ordered after it.
- Use **one serialized, idempotent reconciler**. On panel startup, read the authoritative flag under reconciliation, then start the fixed worker unit if ON or stop it if OFF. A plain `pm2 restart adpanel` does not rerun the systemd launcher or regenerate the ecosystem, so app startup must invoke this same reconciliation. Web-worker reloads and autoscaling must not start multiple workers, restart a healthy matching worker unnecessarily, or let a retiring worker with stale state re-enable it. Use the existing installer-owned privilege boundary with an exact-unit, fixed-action allowlist if needed; no generic `sudo systemctl` and no root execution of repo scripts. Guard worker startup itself against OFF, and use bounded readiness/stop timeouts without a restart loop when disabled.
- On OFF or operator stop, stop admissions/claims, abort active provider work, settle/recover owned rows, close resources, and ensure there is no worker left running after the bounded shutdown. `systemctl stop adpanel` must stop the worker; an intentionally disabled worker must stay down on reboot. Leave service management out of the browser request path. Extend upgrades and uninstall to install/remove the unit and reconcile in the correct order; do not require existing operators to rerun a destructive fresh install. Explicitly support OpenRC/SysV equivalents or document ON as unavailable there for this release, with no inline fallback.
### 6. Reserve capacity for the panel
- Give the Agent and web workers separate CPU/memory budgets. Configure systemd CPU weight and a bounded CPU quota as appropriate, memory high/max, and a Node heap target below the unit's memory ceiling. Adjust PM2's generator/autoscaler to leave RAM and CPU headroom for the Agent, DB, Redis, and OS instead of allocating the same host budget twice. No core pinning by default; use isolation/weights to protect ordinary page latency and tune from measurements. Give the Agent a separately sized DB pool and keep total connections within the shared database budget.
- Bound global and per-account pending/active work, per-provider request/token budgets, retry count, payload bytes, and full-run wall time. Use one place to allocate capacity. Separate live, scheduled/Planner, and discovery budgets; preserve interactive headroom and avoid starving background work. The existing background 200 + 5 setting is a logical policy, not proof of physical capacity: document any lower effective worker/provider ceiling. Do not apply that rule to interactive chats by accident. Surface busy/unavailable status and retry guidance before costs grow, rather than multiplying pools by web-worker count or making every request wait forever.
- Consolidate the current browser write/fetch amplification. The [large-body IP limiter](index.js#L11587) counts 120 requests per five minutes per effective IP; today prompt save, generation and reply save consume three counted POSTs, so a fresh bucket fits 40 complete sends, fewer when shared with other work. Reduce fan-out with atomic submission and server-side reply persistence. Validate NAT/reverse-proxy behavior for 300 legitimate users without removing the abuse brakes. Measure before increasing limits. A separate process is not a separate machine; add a separate host only after profiling shows same-host isolation is insufficient.
## Verification And Rollout
1. **Regression baseline.** Use the existing [live browser tests](tests/server-agent-stream.test.js), [provider latency/cancellation tests](tests/server-agent-provider-http.test.js), [chat ownership tests](tests/server-agent-chat-ownership.test.js), [job authorization tests](tests/server-agent-job-auth.test.js), [recovery tests](tests/ai-agent-job-reclaim.test.js), [leader wiring tests](tests/scheduler-leader-wiring.test.js), and [installer constraints](install_script_validation_test.go). Update source-pinned tests to point at an extracted owner while preserving what they check. Use synthetic providers/fixtures to verify parity across protocols, timeout, body bounds, invalid inputs, and diagnostic-only behavior. Run `npm test`, `go test .`, and `bash -n` for touched scripts.
2. **OFF/ON and isolation.** On a disposable installed host, start OFF and check the actual process list/cgroup, HTTP routes, rendered DOM, account token responses, job claims and zero Agent provider calls. Verify SSH, dashboard Assistant, and non-Agent actions are unaffected. Switch ON and verify a usable live chat and both Agent Scheduler/Planner paths. Switch back OFF with work queued/running, then ON again; confirm no stale results, lost stored history, or replay of missed occurrences. Exercise sticky/stale tabs and previous action tokens. Test all of this through **both** `systemctl restart adpanel` and `pm2 restart adpanel` using the installation's real PM2 user and `PM2_HOME`.
3. **Service and data failure cases.** Test PM2 scale/reload with multiple workers, unavailable or wrong-version Agent, missing/invalid env, DB/Redis unavailability, worker crash/recovery and race with cancel, duplicate submissions, account deletion/revocation, server replacement, and real install/upgrade/reboot/stop/uninstall. Prove one consumer, no execution in web workers, no orphaned worker, no double result, no unsafe replays, and that termination/readiness are bounded. Validate the generated unit in a real disposable systemd environment, not only with shell syntax checks.
4. **Load and capacity.** Benchmark idle and normal production-like panel traffic first. Ramp live **Agent-scene** submissions to 300 alongside page/API, local/remote console, and file-manager traffic. Use real application auth, queue and DB/Redis paths against a staging installation, controlled providers, and realistic text/attachment/tool mixes, including shared effective IPs. Measure panel p95/p99 versus an agreed baseline, chat success, queue delay, time to reply, CPU/RSS/event-loop lag, pool wait, provider throttling, and controlled overload behavior. Test sustained and burst traffic. Earlier loopback mocks completed 300 overlapping calls but bypassed production auth, DB, tools, and quotas; do not use them as acceptance. Verify 300 submissions with responsive pages first. Test 300 active generations separately if the host and provider budgets allow it.
5. **Cutover and rollback.** Back up DB and config. Install migrations and the worker unit without enabling it, and stop or drain the old in-panel consumer before the new one starts. Avoid mixing old and new versions that can both process the same rows or misread live-chat jobs. Verify OFF on the installed build, then enable for a small deployment, verify one executor, and raise budgets only after measurement. Immediate rollback is OFF plus restart on the new build. For a binary rollback, stop the new worker, fence/settle new job shapes, and verify schema compatibility before old code can consume rows; an old build may ignore the new flag. Do not drop history or credentials as a rollback shortcut.
Report the implemented routes and worker ownership, exact operator ON/OFF and status commands, effective resource/queue budgets, tests and measured staging results, upgrade compatibility, and any remaining gaps or decisions. Do not call the implementation done if the actual Agent scene still runs in the panel, the grant toggle is only hidden client-side, or either requested restart path does not honor the switch.
I did my best to trace the current checkout and give concrete starting points. Some assumptions can be wrong or go stale: verify call paths, service identity/permissions, `.env` precedence, both restart paths, queue recovery, and absence of provider work while OFF before deploying. Proceed carefully and document any deviation from this handoff.