F FourIA latest 2026.10.29 GitHub ↗

Agent Guidelines

On this page

Guidelines for AI agents working on this codebase.

Project Overview

This is a Cloudflare Worker that runs OpenClaw (formerly Moltbot/Clawdbot) in a Cloudflare Sandbox container. It provides:

  • Proxying to the OpenClaw gateway (web UI + WebSocket)
  • Admin UI at /_admin/ for device management
  • API endpoints at /api/* for device pairing
  • Debug endpoints at /debug/* for troubleshooting

Note: The CLI tool and npm package are now named openclaw. Config files use .openclaw/openclaw.json. Legacy .clawdbot paths are supported for backward compatibility during transition.

Paso4 Extensions (moltlazy/)

The moltlazy/ module is fully owned by the Paso4 developers and provides two systems:

  1. Config Module (config/ + moltlazy/index.ts) — filesystem patcher used by start-openclaw.sh at container startup to write openclaw.json before the gateway launches.
  2. Features Module (sdk/) — RPC-based config applied to a running gateway via the Admin HTTP API. Supported feature packs: Knowledge Graph, CF Unified Billing.

Project Structure

src/
├── index.ts          # Main Hono app, route mounting
├── types.ts          # TypeScript type definitions (AUTOGENERATED by `bun run types`, do not apply changes directly here, instead re-run the command after implementing the rest of the features)
├── config.ts         # Constants (ports, timeouts, paths)
├── auth/             # Cloudflare Access authentication
│   ├── jwt.ts        # JWT verification
│   ├── jwks.ts       # JWKS fetching and caching
│   └── middleware.ts # Hono middleware for auth
├── gateway/          # OpenClaw gateway management
│   ├── process.ts    # Process lifecycle (find, start)
│   ├── env.ts        # Environment variable building
│   ├── r2.ts         # R2 bucket mounting
│   ├── sync.ts       # R2 backup sync logic
│   └── utils.ts      # Shared utilities (waitForProcess)
├── routes/           # API route handlers
│   ├── api.ts        # /api/* endpoints (devices, gateway)
│   ├── admin.ts      # /_admin/* static file serving
│   └── debug.ts      # /debug/* endpoints
└── client/           # React admin UI (Vite)
    ├── App.tsx
    ├── api.ts        # API client
    └── pages/
moltlazy/             # Paso4 proprietary configuration utilities
├── cli.ts            # CLI entry point for patching config
├── index.ts          # Main logic for config patching
├── types.ts          # Type definitions for OpenClaw config
├── config/
│   └── include.ts     # per-section $include injection (session/tools/logging)
├── config/
├── config/           # Configuration templates
├── agents/           # Agent configuration templates
│   ├── defaults.ts   # Default agent settings
│   └── premade/      # Pre-configured agent definitions
├── models/           # Provider-specific model configurations
├── sdk/              # SDK Module — typed RPC client over the Admin HTTP API
│   ├── client.ts     # Typed RPC client
│   └── (agents, channels, config, cron, devices, models, gateway, update, …)
└── tests/            # Tests for configuration utilities

Key Patterns

Environment Variables

  • DEV_MODE - Local-dev switch: skips CF Access auth AND bypasses device pairing
  • OPENCLAW_DEV_MODE - Explicit override for the dev-agents flag. Normally derived by the Worker from the instance’s own -dev hostname suffix (see src/dev-mode.ts), which enables the Fouria Builder/Q&A agents, client-doc materialization, and the opencode-credits automation without bypassing auth. Forwarded to the container as OPENCLAW_DEV_MODE; falls back to DEV_MODE for local development
  • DEBUG_ROUTES - Enables /debug/* routes (disabled by default)
  • See src/types.ts for full MoltbotEnv interface
  • See docs/schemas/secrets-manifest.schema.json for the secrets manifest

CLI Commands

On OpenClaw 2026.8.2 the CLI no longer accepts --url ws://localhost:18789 (and most local commands reject --token too). Commands run inside the container (the gateway host) either operate on local state or auto-connect to the local Gateway — auth resolves from the OPENCLAW_GATEWAY_TOKEN env SecretRef, so no connection flags are passed. Commands that require an owner on a multi-agent roster take --agent <id>. Never hardcode the id: resolve it at runtime via openclaw agents list --json (prefer main when present, else the first configured agent — e.g. the dev-only fouria-builder/fouria-qa premades when running with DEV_MODE=true; see resolveAgentFlag() in src/routes/api/shared.ts and resolveCliAgentId() in moltlazy/sdk/cli.ts):

// Sandbox SDK 1.0: exec takes argv and resolves on launch, not completion.
startShell(sandbox, 'openclaw devices list --json');
// multi-agent commands need an explicit, dynamically-resolved owner:
startShell(sandbox, `openclaw models list --json${await resolveAgentFlag(sandbox)}`);

Gateway-connecting commands (devices, cron, secrets reload) may still accept --url/--token when given together, but the 2026.8.2 guidance is to drop --url and let the CLI use the configured local target.

CLI commands take 10-15 seconds due to WebSocket connection overhead. Use waitForProcess() helper in src/routes/api.ts.

Success Detection

The CLI outputs “Approved” (capital A). Use case-insensitive checks:

stdout.toLowerCase().includes('approved');

Commands

bun run lint          # Run linting (oxlint)
bun run test          # Run tests (vitest)
bun run test:watch    # Run tests in watch mode
bun run test:client   # Run SPA component/page tests (jsdom, vitest.client.config.ts)
bun run test:ui       # Run the Playwright UI suite (Vite dev server + mocked API)
bun run test:ui:headed # Same, with a visible browser
bun run test:ui:render:local # Local-only plwr admin-UI component render timings
bun run test:gateway:boot     # Local gateway boot smoke test (Docker)
bun run test:gateway:boot:ai  # Same, with real AI Gateway onboard path (.dev.vars.e2e)
bun run build         # Build client (vite)
bun run build:all     # Build client + moltlazy
bun run build:docker  # Build all + install deps (pre-Docker build)
bun run deploy        # Build all and deploy to production
bun run deploy:dev    # Build all and deploy to dev
bun run dev           # Admin SPA Vite dev server (port 8787)
bun run dev:worker    # Worker dev server (Cloudflare Vite plugin, port 8788)
bun run start         # Build all + Worker dev server
bun run typecheck     # TypeScript check

Contribution Guidelines

Validation Requirements

Before submitting any contribution:

  1. Run lint and tests - All builds must pass:

    bun run lint
    bun run test
  2. Environment variable changes - If your contribution adds, updates, or deletes an environment variable, you MUST update it in all three locations:

    • README.md - Add to the secrets reference table
    • src/gateway/env.ts - Add to buildEnvVars() function if passed to container
    • .dev.vars.example - Add to the mapping comments and example

Testing

Tests use Vitest. Test files are colocated with source files (*.test.ts).

Current test coverage:

  • auth/jwt.test.ts - JWT decoding and validation
  • auth/jwks.test.ts - JWKS fetching and caching
  • auth/middleware.test.ts - Auth middleware behavior
  • gateway/env.test.ts - Environment variable building
  • gateway/process.test.ts - Process finding logic
  • gateway/r2.test.ts - R2 mounting logic
  • gateway/sync.test.ts - R2 backup sync logic
  • moltlazy/tests/index.test.ts - per-section $include injection and config generation

When adding new functionality, add corresponding tests.

The admin SPA also has a Playwright UI suite (test/ui/, config playwright.config.ts) run with bun run test:ui. It serves the real dashboard via the Vite dev server (bun run dev) and mocks every /api/* call per test, so it needs no Worker, container, or Cloudflare credentials. It covers the app shell, role-based navigation/redirects, every admin page’s render, and the notification bell. On NixOS the browsers come from PLAYWRIGHT_BROWSERS_PATH (see flake.nix); playwright.config.ts selects the newest chromium-* there so the Nix bundle can lag the npm playwright version without breaking the run.

A separate local-only cctr+plwr suite (test/e2e/ui_components_render.txt, bun run test:ui:render:local) validates the admin (root) UI components against the local worker and records their render times (openMs/componentMs/waitMs plus Navigation Timing/FCP) via fixture/ui-render-measure; it self-skips outside E2E_LOCAL=true. See docs/TESTING.md.

Code Style

  • Use TypeScript strict mode
  • Prefer explicit types over inference for function signatures
  • Keep route handlers thin - extract logic to separate modules
  • Use Hono’s context methods (c.json(), c.html()) for responses

Documentation

  • README.md - User-facing documentation (setup, configuration, usage)
  • AGENTS.md - This file, for AI agents

Development documentation goes in AGENTS.md, not README.md.


Architecture

Browser
   │
   ▼
┌─────────────────────────────────────┐
│     Cloudflare Worker (index.ts)    │
│  - Starts OpenClaw in sandbox       │
│  - Proxies HTTP/WebSocket requests  │
│  - Passes secrets as env vars       │
└──────────────┬──────────────────────┘
               │
               ▼
┌─────────────────────────────────────┐
│     Cloudflare Sandbox Container    │
│  ┌───────────────────────────────┐  │
│  │     OpenClaw Gateway          │  │
│  │  - Control UI on port 18789   │  │
│  │  - WebSocket RPC protocol     │  │
│  │  - Agent runtime              │  │
│  └───────────────────────────────┘  │
└─────────────────────────────────────┘

Key Files

FilePurpose
src/index.tsWorker that manages sandbox lifecycle and proxies requests
src/metrics.tsCost and usage metrics instrumentation for Analytics Engine
DockerfileContainer image based on cloudflare/sandbox with Node 22 + OpenClaw
start-openclaw.shStartup entry point: start is the production cold-start (acquire the container-wide startup lock before setup, hold fd 9 through the Gateway exec — a single owner covers setup and launch), post-start (dev automation + boot-log reset), setup/launch (standalone smoke/manual modes only), or full (legacy: setup + background gateway launch). The Worker drives production cold-start as one start-openclaw.sh start call then a detached post-start (never awaited, so it cannot block readiness); it no longer invokes setup/launch separately. setup/post-start must stay child-free (no tail -f/cloudflared) — the Worker waitForExits on them. start/setup/full serialize the slow setup body on the exclusive /tmp/openclaw-setup.lock, and start holds it through the Gateway exec (no release before launch); the standalone launch takes the dedicated /tmp/openclaw-gateway-launch.lock, held for the gateway’s whole lifetime (fd inherited by the exec’d gateway). Either way exactly one openclaw gateway run owner can exist — losers poll /health and exit 0 without launching a duplicate; the serial test/e2e/ac_gateway_startup_concurrency.txt asserts one owner and the absence of the migration-input-change and SQLite offline-maintenance errors. When the Worker passes OPENCLAW_RESTORED=true (a backup was restored), the setup body is skipped entirely and the restored state is launched directly. See docs/WORKER-DEVELOPMENT.md
wrangler.jsoncCloudflare Worker + Container configuration

Cost Observability

The Worker instruments cost metrics using Cloudflare Analytics Engine for per-client cost tracking:

Event TypeDimensionsMetrics
ai-querymodel, provider, customer, actionTypetokensIn, tokensOut, costUsd
container-activecustomer, instanceType, actionheartbeat count
r2-operationcustomer, opType, opClassbytesTransferred, durationMs
cron-triggercustomer, triggerReasonwokeContainer flag
ws-sessioncustomer, sessionIddurationSeconds, messagesCount

Analytics Engine Configuration

The ANALYTICS binding writes to dataset fourai_cost_metrics. Query via GraphQL:

query CostMetrics($accountTag: String!) {
  viewer {
    accounts(filter: { accountTag: $accountTag }) {
      analyticsEngineDatasets(filter: { name: "fourai_cost_metrics" }) {
        data(
          query: "SELECT blob1 as event_type, blob2 as customer, blob3 as model, SUM(double1) as tokens_in, SUM(double2) as tokens_out FROM fourai_cost_metrics WHERE timestamp > NOW() - INTERVAL 1 DAY GROUP BY blob1, blob2, blob3"
        ) {
          result
        }
      }
    }
  }
}

Cost API Endpoint

GET /api/admin/costs returns pricing constants and query examples for cost dashboards.

Local Development

npm install
cp .dev.vars.example .dev.vars
# Edit .dev.vars with your CLOUDFLARE_AI_GATEWAY_API_KEY + CLOUDFLARE_API_TOKEN + CF_AI_GATEWAY_ACCOUNT_ID + CF_AI_GATEWAY_GATEWAY_ID
npm run start

Environment Variables

For local development, create .dev.vars:

CLOUDFLARE_AI_GATEWAY_API_KEY=your-provider-api-key
CLOUDFLARE_API_TOKEN=your-ai-scoped-api-token  # REST transport; use the same AI-scoped credential locally
CF_AI_GATEWAY_ACCOUNT_ID=your-account-id
CF_AI_GATEWAY_GATEWAY_ID=your-gateway-id
DEV_MODE=true           # Skips CF Access auth + device pairing
DEBUG_ROUTES=true       # Enables /debug/* routes

WebSocket Limitations

Local development with the Vite dev server has issues proxying WebSocket connections through the sandbox. HTTP requests work but WebSocket connections may fail. Deploy to Cloudflare for full functionality.

Docker Image Caching

The Dockerfile includes a cache bust comment. When changing start-openclaw.sh, bump the version:

# Build cache bust: 2026-02-06-v28-openclaw-upgrade

Gateway Configuration

OpenClaw configuration is built at container startup:

  1. R2 backup is restored if available (with migration from legacy .clawdbot paths)
  2. If no config exists, openclaw onboard --non-interactive creates one based on env vars
  3. Feature flags come from the per-customer MOLTLAZY_FEATURE_FLAGS binding (managed via the FourIA API)
  4. start-openclaw.sh start runs moltlazy patch (after the restore/onboard above) which generates per-section include files (moltlazy-session/tools/logging.json) and injects them as per-section $include directives (no root $include); gateway.*/agents.* are written inline and the gateway token is an env SecretRef
  5. The Worker calls /usr/local/bin/start-openclaw.sh start once: that mode acquires the container-wide startup lock before running the setup body, runs the patch while holding it, then execs the supervised Gateway under the same lock (the exec replaces the wrapper, so the tracked process is the gateway) and runs start-openclaw.sh post-start afterward once the port is ready. The Worker no longer invokes setup then launch separately; those remain standalone smoke/manual modes only.

Feature Flag Configuration

Feature flags are managed via the FourIA API and applied as a per-customer binding (MOLTLAZY_FEATURE_FLAGS, a JSON string). The Worker reads the binding and passes it to the container via buildEnvVars(). The legacy CONFIG_BUCKET / config-cache.ts (R2 + ETag) mechanism was removed.

Feature Flags Example:

{
  "knowledgeGraph": true,
  "unifiedBilling": false,
  "softwareProvisioning": false
}

The container consumes MOLTLAZY_FEATURE_FLAGS at startup (moltlazy patch generates the per-section include files and injects them as per-section $include into openclaw.json). There is no worker-side cache — the binding is read directly.

Software provisioning (softwareProvisioning)

Software that agent skills install at runtime (plugins, apt/npm packages, downloaded binaries) lives in the container filesystem only, so it is lost on a container-version upgrade (fresh image) or idle-sleep (container destroyed).

The per-customer softwareProvisioning flag fixes this:

  1. The tenant’s manifest (customers/<slug>/software.json in the BACKUP_BUCKET, uploaded via PUT /api/admin/software/manifest) declares each package with its actual install command: { id, check, install, verify?, timeoutSec? }.
  2. On cold start, ensureGatewayImpl materializes the manifest into /home/openclaw/.openclaw/software.json and — only when the flag is on — spawns moltlazy software provision as an independent supervised process through the Sandbox SDK (void spawnSoftwareProvision(...)), not a step in start-openclaw.sh. It runs in parallel with the gateway boot, never blocks readiness, and is non-fatal (per-package timeouts; failures recorded, not raised).
  3. It writes live ticks to /tmp/software-progress.log (read by GET /api/startup-progress / /api/startup/ws as softwareLog) and a structured report to /tmp/software-report.json (surfaced by GET /api/admin/software/report as the homepage Software widget). Each run truncates the progress log first (resetProgressLog), because /tmp survives an in-place restart (/debug/restart-openclaw), which would otherwise interleave ticks from earlier boots.
  4. POST /api/admin/software/provision (ADMIN/ROOT) reconciles the manifest on demand, so a manifest uploaded or corrected mid-life does not need a restart. It re-materializes the current R2 manifest, runs the same CLI to completion bounded by SOFTWARE_PROVISION_RUN_TIMEOUT_MS (5 min), and returns the fresh report; 409 when the flag is off (disabled) or nothing is declared (no_manifest), 502 when the run fails.
  5. Both GET endpoints carry enabled (the flag), so the dashboard can tell “switched off”, “asleep”, “not run yet” and “nothing declared” apart instead of showing one empty state. The widget exposes a Run provisioning button to ADMIN/ROOT when the flag is on.

The manifest is arbitrary shell executed inside the tenant container, so the upload endpoint is ADMIN/ROOT-only (never exposed to readers), timeoutSec is per package, and the on-demand run is bounded by the route.

Key modules: src/gateway/software-provisioning.ts (flag + spawn + on-demand run + report parsing), src/services/software-manifest/ (R2 store + materialization), src/routes/api/software.ts (manifest read/upload, report, on-demand provision), packages/moltlazy/src/software/ (the CLI).

AI Provider

Cloudflare AI Gateway is the only provisioned AI provider path. The startup script configures auth when all of these env vars are set:

  1. Cloudflare AI Gateway (native): CLOUDFLARE_AI_GATEWAY_API_KEY + CF_AI_GATEWAY_ACCOUNT_ID + CF_AI_GATEWAY_GATEWAY_ID

Container Environment Variables

These are the env vars passed TO the container (internal names):

VariableConfig PathNotes
CLOUDFLARE_AI_GATEWAY_API_KEY(env var)Native AI Gateway key
CLOUDFLARE_API_TOKEN(env var)AI Gateway REST API Bearer token; tenant binding is derived from the AI key
CF_AI_GATEWAY_ACCOUNT_ID(env var)Account ID for AI Gateway
CF_AI_GATEWAY_GATEWAY_ID(env var)Gateway ID for AI Gateway
OPENCLAW_GATEWAY_TOKEN--token flagMapped from MOLTBOT_GATEWAY_TOKEN
OPENCLAW_DEV_MODE(dev-agents flag)Derived from the -dev hostname or an OPENCLAW_DEV_MODE override; DEV_MODE local
OPENCLAW_RESTORED(zero-data-loss signal)true when a cold start restored an R2 backup (hadBackup && restored); makes start-openclaw.sh skip the setup body
TELEGRAM_BOT_TOKENchannels.telegram.botToken@deprecated — E2E only. Use integrations dashboard in production.
DISCORD_BOT_TOKENchannels.discord.token@deprecated — E2E only. Use integrations dashboard in production.
SLACK_BOT_TOKENchannels.slack.botToken@deprecated — E2E only. Use integrations dashboard in production.
SLACK_APP_TOKENchannels.slack.appToken@deprecated — E2E only. Use integrations dashboard in production.

OpenClaw Config Schema

OpenClaw has strict config validation. Common gotchas:

  • agents.defaults.model must be { "primary": "model/name" } not a string
  • gateway.mode must be "local" for headless operation
  • No webchat channel - the Control UI is served automatically
  • gateway.bind is not a config option - use --bind CLI flag

See OpenClaw docs for full schema.

Common Tasks

Adding a New API Endpoint

  1. Add route handler in src/routes/api.ts
  2. Add types if needed in src/types.ts
  3. Update client API in src/client/api.ts if frontend needs it
  4. Add tests

Adding a New Environment Variable

  1. Add to MoltbotEnv interface in src/types.ts
  2. If passed to container, add to buildEnvVars() in src/gateway/env.ts
  3. Update .dev.vars.example
  4. Document in README.md secrets table

Debugging

# View live logs
npx wrangler tail

# Check secrets
npx wrangler secret list

Enable debug routes with DEBUG_ROUTES=true and check /debug/processes.

R2 Backup Encryption (F4E1)

When BACKUP_ENCRYPTION_KEY (base64 32-byte secret) is set, the Worker post-encrypts every snapshot after sandbox.createBackup(): backups/<id>/data.sqsh is replaced by data.sqsh.enc (chunked AES-256-GCM, per-object HKDF key) and meta.json is flagged encrypted: true (kept readable — the SDK needs it). Restores decrypt transiently and delete the plaintext in a finally block. Config versions under configs/ are encrypted with customMetadata.encrypted='true'. Legacy plaintext backups remain restorable. Set BACKUP_ENCRYPTION_REQUIRED=true to fail closed. Crypto lives in src/crypto/.

workerd’s R2Bucket.put() rejects ReadableStream bodies of unknown length, so uploads wrap the ciphertext/plaintext stream in a FixedLengthStream whose size is computed from the source object (encryptedLength) or the F4E1 header (decryptedLength). This keeps backup/restore memory-bounded (no whole-archive buffering) while satisfying R2. See src/crypto/r2-backup.ts. See docs/plans/r2-encryption-at-rest.md.

R2 Storage Notes

Persistence uses the Sandbox SDK createBackup() / restoreBackup() API with the BACKUP_BUCKET binding. The snapshot root is /home/openclaw; it is not an s3fs mount and there is no /data/moltbot runtime path.

Never delete tenant backup objects outside the retention or decommission procedure. Hard restarts must checkpoint before killing the gateway.

  • Process status: The sandbox API’s proc.status may not update immediately after a process completes. Instead of checking proc.status === 'completed', verify success by checking for expected output (e.g., timestamp file exists after sync).

  • R2 prefix migration: Backups are now stored under openclaw/ prefix in R2 (was clawdbot/). The startup script handles restoring from both old and new prefixes with automatic migration.

  • Snapshot lease + admin snapshot mode (F5): the shared R2 backup-lock TTL is STEP_DEADLINE_MS (12 minutes), with a serialized heartbeat every quarter-TTL and explicit renewals around slow snapshot/restore boundaries. Renewal events are structured; renewal failure is best-effort and does not abort work. The longer TTL intentionally favors avoiding false expiry during a live durable step, at the cost of a longer stale-holder takeover window. POST /api/admin/storage/sync enqueues a durable job by default when ACTIVITY is available; use ?inline=1 only when synchronous completion is required (?async=1 keeps its prior behavior). Without ACTIVITY, the route falls back to inline work.

Cloudflare Tunnel Setup (Manual Flow)

This section documents how to expose an internal service (e.g. the Obsidian sync port 18790) via a Cloudflare Tunnel with a public hostname. Follow this end-to-end when setting up a new tunnel route.

1. Register and Add a Domain

You need a domain zone in your Cloudflare account before any DNS record can be created.

  1. Register a domain (e.g. via Cloudflare Registrar or a third-party registrar like Spaceship/Namecheap).
  2. In the Cloudflare Dashboard, select the Paso4 account → Websites → Add a site.
  3. Enter the domain name and choose the Free plan.
  4. Cloudflare will assign two nameservers, e.g.:
    • albert.ns.cloudflare.com
    • priscilla.ns.cloudflare.com
  5. At your registrar, replace the existing nameservers with the Cloudflare ones.
  6. Wait for DNS propagation (typically 5–30 minutes). The zone status will change from pending to active.

Current domain: paso4.io (zone ID: 6ce23f544f57a1909578032abcda18dd, account: Paso4)

2. Create the Cloudflare Tunnel

If the tunnel does not yet exist, create it with cloudflared:

cloudflared tunnel create obsidian-sync

This prints a tunnel UUID and writes credentials to ~/.cloudflared/<UUID>.json.

Current tunnel: obsidian-sync — UUID 90792969-7077-40a8-ae10-28e716290d9d

To get the tunnel token (needed for CLOUDFLARE_TUNNEL_TOKEN):

cloudflared tunnel token 90792969-7077-40a8-ae10-28e716290d9d

Set it as a Worker secret:

npx wrangler secret put CLOUDFLARE_TUNNEL_TOKEN

3. Create the DNS CNAME Record

A CNAME record must point from your public subdomain to <UUID>.cfargotunnel.com.

Via Cloudflare Dashboard:

  1. Go to paso4.io → DNS → Records → Add record.

  2. Fill in:

    FieldValue
    TypeCNAME
    Nameobsidian-sync
    Target90792969-7077-40a8-ae10-28e716290d9d.cfargotunnel.com
    Proxy statusProxied (orange cloud — required)
    TTLAuto
  3. Save. Public URL becomes https://obsidian-sync.paso4.io.

Via MCP API (requires DNS:Edit on the API token):

cloudflare.request({
  method: 'POST',
  path: `/zones/6ce23f544f57a1909578032abcda18dd/dns_records`,
  body: {
    type: 'CNAME',
    name: 'obsidian-sync',
    content: '90792969-7077-40a8-ae10-28e716290d9d.cfargotunnel.com',
    proxied: true,
    comment: 'Cloudflare Tunnel route for obsidian-sync',
  },
});

To grant DNS:Edit to the MCP token: https://dash.cloudflare.com/profile/api-tokens → edit the token → add Zone → DNS → Edit.

4. Configure the Tunnel Ingress

Create or update ~/.cloudflared/config.yml on the host running cloudflared:

tunnel: 90792969-7077-40a8-ae10-28e716290d9d
credentials-file: /root/.cloudflared/90792969-7077-40a8-ae10-28e716290d9d.json

ingress:
  - hostname: obsidian-sync.paso4.io
    service: http://localhost:18790
  - service: http_status:404

Then run:

cloudflared tunnel run obsidian-sync

5. Verify

# Check tunnel is connected
cloudflared tunnel info obsidian-sync

# Test the public endpoint
curl -I https://obsidian-sync.paso4.io

Gotchas

  • The cfargotunnel.com CNAME only routes traffic for DNS records in the same Cloudflare account as the tunnel. Cross-account routing is blocked.
  • The zone must be active (nameservers delegated) for public DNS to resolve. A pending zone means nameserver propagation is not complete yet.
  • If the tunnel stops, the DNS record is not deleted — visitors will see a Cloudflare 1016 error.
  • The CLOUDFLARE_TUNNEL_TOKEN secret in the Worker is used by start-openclaw.sh to run cloudflared inside the container, exposing port 18790 to the tunnel.

FourIA offers Private Cloud only (Business On Premise is not offered at this time). Pricing is credit-based: Credits are the exclusive billable unit, consumed by completed messages and automations. Credits do NOT include AI costs — AI expenses are managed separately via BYOL or AI Gateway billing. Reader users are unlimited and free. Builder seats (users who can create and edit agents) are plan-limited. The v1.0-beta is delivered through the Design Partner Program with a single engaged partner. Partners pay a fixed credit fee negotiated with sales. See docs/VISION.md for the full pricing definition.

Active Technologies

  • OpenTofu 1.6+ (HCL) + cloudflare provider (Terraform/OpenTofu) (001-opentofu-deploy)
  • Cloudflare R2 (for FourIA data), OpenTofu Local/Remote State (for infrastructure tracking) (001-opentofu-deploy)

Recent Changes

  • Gateway memory is observable from the Worker, and a dev instance self-heals before the container limit. Investigating a tenant-tarjetero-dev “reboot” required SSH-ing into the container to read /proc, dmesg and the gateway log, because nothing exposed the gateway’s RSS. (1) Observability (plan Phase 1): src/gateway/memory.ts reads VmRSS + Threads from /proc/<pid>/status for the gateway server (pgrep -x 'openclaw-gatewa', the same exact comm the soft reload targets, zombies skipped) in ONE shell exec, throttled to GATEWAY_RESOURCE_SAMPLE_INTERVAL_MS (60s) so the frequent health poll adds at most one exec per interval. attachGatewayResources() (routes/public.ts) attaches it to /api/health, /api/health-snapshot and /api/health-ws as gateway: { pid, rssBytes, threads } — only while the snapshot is running, so a sleeping tenant is never woken — and writes a gateway-resources Analytics Engine row (double1 = RSS bytes, double2 = threads). (2) Watchdog (plan Phase 2.4): on a dev instance (isDevAgentsEnabled) at GATEWAY_RSS_RESTART_BYTES (3 GiB of the 4 GiB container) the gateway is replaced via killGateway + resetStartupCache + ensureGateway({ skipRestore: true, bypassMaintenance: true }) — the only lever that reclaims the per-worker_thread V8 heaps — with a 30-minute cooldown claimed before acting so concurrent health polls cannot double-restart, dispatched detached so a multi-minute replacement never delays a health response. Deliberate design: the threshold guards the container limit, not OpenClaw’s 1.5 GiB rss_threshold warning (which fires permanently on a healthy ~2.1 GiB dev gateway and would make the watchdog a restart loop), and there is no soft-reload step (a measured in-process SIGUSR2 restart does not reclaim RSS: 1.14 → 1.38 → 1.18 GiB). Production is excluded. Tests: src/gateway/memory.test.ts, src/metrics.test.ts (trackGatewayResources), src/routes/public.test.ts (sample attached + AE row, one read per interval, no sample when not running, no watchdog on a non-dev instance); corpus test/business-rules/operational-modes.txt; docs docs/plans/sandbox-memory-usage.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md (§5.4d).

  • OpenClaw migrated to 2026.10.8 (catalog.openclaw + the @openclaw/gateway-client / @openclaw/gateway-protocol pins in the root package.json; the plugin repo tracks and publishes the same release). 2026.10.8 is a bug-fix/security release: plugin lifecycle repairs (older plugins can process incoming messages again after an upgrade, scheduled plugin work no longer stops after startup/reload, and Gateway startup repairs stale managed plugin links left by an external OpenClaw reinstall — the state a warm R2 restore can produce), session-store fixes (relative session-store paths no longer fork a second database; openclaw doctor --fix repairs an already-split store), Doctor robustness on very large retained session histories (stack overflow / retained memory), and a trusted-proxy browser-auth fix that no longer writes gateway.auth.password or restarts the Gateway on first browser use. It also hardens POSIX exec allowlists (test -v / [ -v are no longer auto-trusted; moltlazy writes no exec allowlist, and the dev-only security.installPolicy allow is unaffected). No config-schema changes — the moltlazy openclaw config validate cctr contract passes unchanged, so no packages/moltlazy source change was needed — and the Node engine floor is unchanged at >=24.22.1 <25 || >=26.12.1, so no Dockerfile change. No component CalVer bump — the release train handles that.

  • Software provisioning is now usable mid-life and honest about its state. Three gaps closed around the softwareProvisioning feature. (1) On-demand reconcile: POST /api/admin/software/provision (ADMIN/ROOT) re-materializes the current R2 manifest, runs moltlazy software provision to completion (bounded by SOFTWARE_PROVISION_RUN_TIMEOUT_MS, 5 min) and returns the fresh report, so a manifest uploaded or corrected mid-life no longer waits for the next cold start; 409 { code: 'disabled' | 'no_manifest' } and 502 { code: 'failed', error } are distinct outcomes. (2) No cross-boot tick bleed: runSoftwareProvision truncates /tmp/software-progress.log before every run (resetProgressLog) — /tmp survives an in-place /debug/restart-openclaw, so the boot terminal used to interleave ticks from earlier boots. (3) Truthful dashboard states: GET /api/admin/software/{manifest,report} now return enabled (the flag), and the homepage widget separates “provisioning is disabled”, “instance is asleep”, “no report yet” and “no software declared”, with a Run provisioning button (ADMIN/ROOT) that renders the on-demand report and surfaces its error. parseSoftwareReport moved into src/gateway/software-provisioning.ts so the report, run and route paths share one shape check. Tests: src/gateway/software-provisioning.test.ts, src/routes/api/software.test.ts, src/client/pages/__tests__/HomePage.test.tsx, packages/moltlazy/tests/software/run.test.ts (progress-log reset), E2E test/e2e/zzz_software_provisioning.txt (on-demand run must install the new package and skip the already-installed one); corpus test/business-rules/dashboard-api-contract.txt, operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Lerma deploys are idempotent around Cloudflare DO migration conflicts (#516). A tenant Worker’s Durable Object class set was derived from the script’s bindings, but Cloudflare validates new_sqlite_classes against the script’s migration history, so the two can diverge: an upgrade redeploy that binds fewer classes (or a rollback that deletes the script while leaving its classes migrated) made every subsequent deploy re-declare TelegramIngress and fail with 400 code 10074 — deterministically, so provisioning could not recover on its own. Lerma.Cloudflare.DispatchNamespace.upload_script/6 now retries the upload without any class Cloudflare reports as already migrated (10074 names it), switching an implicit full first-deploy set to an explicit new_sqlite_classes list; each retry removes at least one class, so it terminates, and the retry is logged. Lerma.Instances.instance_bindings/2 now re-declares the same DO set as provisioning (Sandbox, ACTIVITY, TELEGRAM_INGRESS, plus BACKUP_WATCH while the flag is on) so an upgrade cannot detach a migrated class from its binding. Provisioning cleanup and a failed atomic deploy tear the classes down first via delete_durable_object_namespaces/2 (never on an upgrade rollback, whose Durable Objects hold the live tenant’s state: preserve_do_namespaces). Tests: apps/lerma/test/lerma/cloudflare/dispatch_namespace_test.exs (migrated-but-unbound re-deploy, resurrected first deploy, unrelated error not retried), containers_test.exs, tenant_provisioner_pipeline_test.exs; docs apps/lerma/README.md.

  • OpenClaw migrated to 2026.10.6 (catalog.openclaw + the @openclaw/gateway-client / @openclaw/gateway-protocol pins in the root package.json; the plugin repo tracks and publishes the same release). 2026.10.6 is a security patch release (eMudhra certificate-compromise remediation, Windows setup/Doctor/Gateway startup fixes, Discord command and iPhone Talk fixes) with no config-schema changes: the moltlazy openclaw config validate cctr contract passes unchanged, so no packages/moltlazy source change was needed. It does raise OpenClaw’s Node engine floor from >=24.16.0 <25 || >=26.1.0 to >=24.22.1 <25 || >=26.12.1, so apps/fouria/Dockerfile now installs Node v24.22.1 (from v24.20.0) and its version gate compares major/minor/patch (24.22.0 is rejected). No component CalVer bump — the release train handles that.

  • Idle-sleep no longer re-archives an unchanged tenant, and deprovision snapshots reset the cadence. TenantSandbox.onActivityExpired() used to enqueue a full deprovision snapshot on every idle expiry; on a 422 MB tenant the snapshot’s own RPCs renewed the DO activity window, so stopIfIdle() refused, the next expiry snapshotted again, and the container never stopped (observed on tenant-tarjetero-dev: three 422 MB archives at 02:35/02:39/02:44 UTC plus three more at 05:39/05:43/05:49, ~3 GB/day, container running since Oct 21). The hook now reads the catalog first (hasRecentSnapshot() in src/persistence.ts, a pure read): a committed snapshot inside the idle window (resolveSleepAfterMs() — staging 15m, dev 2h, production 6h) already covers the unchanged filesystem, so it stops inline through stopIfIdle() without a new archive; no bucket or a read failure falls back to the durable backup-then-stop job (fail closed). Deprovision finalize now passes stampScheduled: true too, so a committed archive resets lastScheduledBackup and the next cron tick does not archive the same state again. Tests: src/sandbox-do.test.ts (recent snapshot stops inline, probe failure snapshots, no bucket skips the probe), src/persistence.test.ts (hasRecentSnapshot), src/activity/scheduler.test.ts (deprovision stamps), src/build-sandbox-options.test.ts (resolveSleepAfterMs); corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • The dev Fouria Builder heartbeat is reconciled to its intended cadence. OpenClaw 2026.10.5 retired agents.entries.*.heartbeat: heartbeats are ordinary automation jobs, and config reloads/restarts never rewrite an existing job. The migrated heartbeat-fouria-builder job therefore kept the default 30-minute cadence for 9 days on tenant-tarjetero-dev despite moltlazy’s heartbeat.every: 12h, running full agent turns on the main session (~317k tokens each) until the OpenCode subscription hit 0% (402 Insufficient account funds → agent-runner-failure). start-openclaw.sh gains a dev-only ensure_dev_heartbeat_cadence (post-start) that reads openclaw automations get <id> --json, compares schedule.everyMs / sessionTarget / payload.lightContext, and only then edits the job to --every 12h --session isolated --light-context (split so a rejected --light-context cannot lose the cadence fix). Idempotent: a matching job is never touched, so the schedule anchor is not reset on every boot. Docs packages/moltlazy/AGENTS.md, apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Backup catalog reads are pure; catalog healing has an explicit entry point (audit finding F3). GET /api/admin/storage/backups (getBackupHistory) used to run reconcileOrphanedBackups on every dashboard poll — listing backups/, reading meta.json, adopting orphans, deleting over-cap archives, and writing backup-handle.json from a GET. It now performs three parallel reads (getPersistenceStore, getStableBackup, isRecoveryHeld) and nothing else. The write path is reconcileCatalogState (adoption + retention prune inside the etag-CAS mutation, reporting the ids it changed) → repairBackupCatalog (sweep metadata-less uploads + in-place encryption) → refreshed history, exposed as reconcileBackupCatalog; the durable repair step now runs it before the gate step of every scheduled snapshot, so the catalog still self-heals after a killed invocation (issue #344). Restore/schedule keep their inline reconcile, debug/reprovision reconciles before deciding nothing is restorable (a crashed upload must not look unrecoverable), and operators get POST /api/admin/storage/reconcile (ADMIN/ROOT). The history panel polls GET /api/admin/storage/jobs/:id (getBackupJobStatus) while a snapshot is in flight instead of re-listing the catalog every 5s, falling back to the history diff when no job id is returned. Tests: src/persistence.test.ts, src/persistence-encryption.test.ts, src/routes/api/storage.test.ts, src/activity/scheduler.test.ts, src/routes/debug.test.ts, src/client/components/__tests__/BackupHistoryPanel.test.tsx; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md, docs/plans/durable-agents-rules-audit.md.

  • A config repair is deferred until a restore settles and the gateway is up on the restored state, and the restored config becomes the stable/latest config version. A restore replaces the writable layer but launches nothing, so a doctor --fix applied around it was silently overwritten by the next re-apply of the recovery point (suspected on tenant-tarjetero-dev after a config fix). (1) Every successful restore (restoreIfNeeded, restoreBackupById) writes a durable restore-config-pending.json marker. (2) The boot job, the durable restore job, and the sync/async-fallback admin restore route finish through the shared launchRestoredState (src/post-restore.ts): ensureGateway({ waitForReady: true }) on the restored state, then captureRestoredConfigVersion writes configs/<ts>.json + stable/config.json (the newest/stable version) and clears the marker. A gateway-launch failure does not re-run the destructive restore: restore jobs succeed with detail: "gateway-launch-pending", the sync route returns gatewayReady: false, and the marker drives the next tick. (3) doctor-repair checks an active restore job, getPersistenceBusyReason (maintenance window / restore in flight), and the pending marker before running; when blocked it throws MaintenanceJobDeferredError, and runMaintenanceJobAlarm reschedules it every 60s without consuming an attempt (previously three deferrals would have failed the job before the restore finished). Tests: src/activity/maintenance-jobs.test.ts, src/activity/scheduler.test.ts, src/persistence.test.ts, src/routes/api/storage.test.ts; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md.

  • Diagnostics dashboard is skip-not-park and non-blocking. DiagnosticDashboard only dispatches its container reads (/api/admin/config/raw, /api/admin/config) while the gateway is actually running (useGatewayRunning() — snapshot.readiness.ok, ignoring the ROOT breaker bypass) and re-runs them when it comes back; the debug-routes flag (Worker-local) still loads. Every load is deferred after paint (scheduleAfterPaint → requestIdleCallback, setTimeout(0) fallback), so no widget waits on a container response: ConfigSection gained a gatewayReady prop and now keeps its tabs/editor visible with a non-blocking “Loading configuration…” / “Waiting for the gateway to start…” notice instead of swapping the whole panel for a spinner; devices render a waiting state; config loads never clobber text typed before the response arrived. Gateway-only actions (device list/approve, config save, channel probe) are guarded, and the Debug Tools that only make sense against a live gateway (gateway-api, stop-gateway) are skipped with an inline explanation — container diagnostics (logs/processes/version/sqlite) and recovery actions (restart/rescue/destroy) stay available so a down gateway can still be inspected and revived. Repair stays available outside the editor: doctor --fix is the recovery action for a down gateway, so runRepair no longer requires a running gateway, a dedicated Repair Environment bar (data-testid="repair-environment-button", ADMIN/ROOT) sits above the widgets and is disabled only while a repair is in flight, and ConfigSection’s repair button stays enabled while gatewayReady is false. Tests: src/client/pages/__tests__/DiagnosticDashboard.test.tsx, src/client/components/__tests__/ConfigSection.test.tsx, src/client/GatewayHealthContext.test.tsx; corpus test/business-rules/dashboard-api-contract.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/TESTING.md.

  • Billable emission: staging always emits, BILLABLE_EVENTS opts a dev instance in. Both emit sites (POST /api/otel/v1/traces and the CRON_BILLABLE_DRAIN cron drain) previously gated on the strict billable cost axis (resolveInstanceDimensions(env).billable = production platform + production environment), so staging and dev instances could never exercise the billing pipeline. They now call isBillableEventsEnabled(env) (src/dev-mode.ts): billable production always emits and cannot be opted out, the staging platform always emits in every environment (mirroring production so billing is validated before release; the rows land in the staging Analytics Engine dataset), and a dev environment emits only with BILLABLE_EVENTS=true. Emission only: getCostContext keeps the real platform/environment dimensions (staging/dev remain non-billable cost axes) and shouldAutoSleep is untouched, so staging keeps its 15m idle timeout and an opted-in dev instance its 2h one. The emitting path omits the guard’s billable: false marker (the local-E2E skip, whose worker is a dev instance via DEV_MODE, is unaffected). Tests: src/dev-mode.test.ts, src/routes/otel-traces.test.ts (staging emits, dev opt-in emits), src/index.test.ts (cron drain: dev drops, staging and dev-with-override emit), src/build-sandbox-options.test.ts (sleep policy unchanged); corpus test/business-rules/dev-expense.txt; docs docs/ENV-VARIABLES.md, docs/TESTING.md, apps/fouria/README.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, .dev.vars.example.

  • Request paths never run a destructive archive restore, and a container stops only on verified inactivity (investigated on tenant-tarjetero-dev, which appeared to “reboot” while in active use). (1) The container instance had not restarted (started_at 00:18, still running); what died was the gateway process ([Gateway] Gateway process … has terminal state: exited), and the follow-up boot ran a 350 MB archive restore under request execution contexts. sandbox.restoreBackup was aborted at ~30.1 s (backup.restore error … The operation was aborted (30177ms), plus sandbox.exec … The operation was aborted (30001ms) for health probes/umount and the workerd “promise resolved in a different request context” warning) because Cloudflare cancels a request’s background continuations shortly after the response — so the restore never finished and every reload re-attempted it (6 boot jobs + 8 restore errors in one hour). Fix: restoreIfNeeded(..., { restoreOwner: 'request' }) (the ensureGateway default) performs only the cheap non-destructive checks (the restore-needed latch + containerHasState()) and otherwise throws RestoreDeferredToBootJobError; ensureGateway requests the durable boot job and throws GatewayBootPendingError (proxy answers 503/loading). Durable callers (ActivityScheduler boot/wake jobs, the queue consumer) pass restoreOwner: 'durable'. The proxy’s three inline restoreIfNeeded calls (proxy.request, proxy.websocket-recovery, proxy.fetch-recovery) were removed. (2) A container is now stopped only after a stop-time inactivity check: TenantSandbox.stopIfIdle() re-reads the DO’s own idle window (renewed by every request) and the process list, and the deprovision job calls it after its multi-minute snapshot instead of sandbox.stop(); if the tenant became active meanwhile the job is skipped (active:<reason>). Refusals: activity, transient-activity, probe-failed, billable-production, not-running. Tests: src/sandbox-do.test.ts (stopIfIdle cases), src/activity/scheduler.test.ts (stop-time skip), src/gateway/process.test.ts (deferral + restoreOwner), src/persistence.test.ts (request deferral / state-present short-circuit), src/index.test.ts (proxy no longer restores); corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md, webs/fouria-docs/.../worker-development.md, operator-guide.md.

  • Fouria Builder build-method skill. The dev-only fouria-builder agent now seeds fouria-product-build as a per-agent workspace skill (packages/moltlazy/workspace/skills/fouria-product-build.ts → <workspace>/fouria-builder/skills/fouria-product-build/SKILL.md, plus an entry in its skills allowlist) that sequences the build method: frame the production roster → tool-first restriction model (each capability names the exact tool; no tool means no capability) → smallest MCP tool surface with preview/apply pairs → 3–6 channel quick actions (Telegram inline buttons; a callback is untrusted input, never authorization) → per-client tone matrix before writing a client-facing SOUL.md → one vertical slice → cctr acceptance corpus → POC.md handoff. Workspace skills are OpenClaw’s highest-precedence skill source and are per-agent, and workspace/fouria-builder is excluded from promotions, so no production roster changes. seedWorkspaceFiles now creates parent directories so workspace-file keys can be nested paths. This supersedes the pending Skill Workshop proposal fouria-product-build-20261021-bf543e21c1: a workspace copy of the same name shadows a workshop skill, so the repo copy is authoritative. Tests: packages/moltlazy/tests/agents.test.ts; docs packages/moltlazy/AGENTS.md, packages/moltlazy/src/agents/README.md, docs/DEVELOPMENT.md.

  • Cloudflare Observability destination ingestion (issue #337). Account-level Observability → Destinations now push Workers Logs and Workers Traces to Lerma over OTLP/HTTP JSON, giving event-driven worker diagnostics and uptime statistics that scale with traffic instead of tenant count. (1) Config: apps/fouria/wrangler.jsonc (env.staging → lerma-worker-logs/lerma-worker-traces, env.production → lerma-worker-logs-prod/lerma-worker-traces-prod) and Lerma.Cloudflare.Observability.worker_metadata/0 reference the environment’s destination names, with per-signal head sampling (10% at rollout) and persist: false when a destination is configured (Lerma is the destination of record). The Lerma CD passes the matching names to staging and production, and the token to both; it also reconciles the account-level destination pairs (mix lerma.observability.destinations --warn-only) before each deploy so a fresh environment self-heals once the Cloudflare credential has Workers Observability Write. New WORKER_OBSERVABILITY_LOGS/TRACES_DESTINATIONS, *_SAMPLING_RATE and *_PERSIST env vars. (2) Ingest: new POST /api/ingest/otel/v1/logs and /v1/traces (bearer OTEL_INGEST_TOKEN, constant-time compare, fail closed; OTLP/HTTP JSON only — protobuf → 415 + hint; 202 {accepted, skipped} so Cloudflare never retry-loops). Lerma.Observability.Otlp is a pure allowlist parser: it keeps script/dispatch namespace/outcome/handler/status/exception class names/cpu+wall/trace+span+invocation ids/timestamps, drops log text, stacks, URLs/query strings, user agents, request/response bodies and DB query text, and keeps only invocation root spans. Rows land in observability_events with a unique dedupe_key + ON CONFLICT DO NOTHING, so replayed batches (at-least-once delivery) add no rows. Cloudflare gzips each OTLP/HTTP JSON batch while keeping Content-Type: application/json; LermaWeb.Plugs.OtlpBodyReader decompresses it before Plug.Parsers (otherwise the destination retries on a 400 forever). (3) Uptime: GET /api/analytics/v1/uptime/:script_name?window=24h|7d|30d|<n>h|<n>d computes uptime/failure ratios from pushed root spans only; no events observed (including under sampling) → null ratios + status: "unknown", never downtime. The instance page gained a Worker telemetry widget (window selector + uptime/failure/invocation/CPU/wall), and Lerma.Observability.Pruner sweeps 90-day retention daily. HealthMonitor and billing flows are untouched. Tests: test/lerma/observability/otlp_test.exs, telemetry_test.exs, test/lerma/cloudflare/observability_test.exs, test/lerma_web/controllers/api/otlp_ingest_controller_test.exs, observability_controller_test.exs, test/lerma_web/components/worker_telemetry_widget_test.exs, test/lerma_web/live/instance_live_test.exs; docs docs/CLOUD-ARCHITECTURE.md, docs/ENV-VARIABLES.md, docs/TESTING.md, apps/fouria/public/articles/PRIVACY.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, SECRETS.example.yaml, docs/schemas/secrets-manifest.schema.json, apps/lerma/.env.example.

  • OpenClaw migrated to 2026.10.5 (catalog.openclaw + the @openclaw/gateway-client / @openclaw/gateway-protocol pins in the root package.json; the plugin repo tracks the same release). One breaking change hit moltlazy: the 2026.10.5 config schema retired agents.defaults.compaction.enabled (embedded auto-compaction is no longer toggleable) and retired compaction.truncateAfterCompaction (“byte-triggered compaction now opts in via maxActiveTranscriptBytes alone”) — openclaw config validate rejects both keys with Invalid input, which broke the moltlazy cctr config-save contract. AGENT_DEFAULTS.compaction now emits only maxActiveTranscriptBytes: '20mb' + keepRecentTokens: 20000, preserving the sandbox OOM transcript bound. The runtime zod schema still accepts the retired keys, so only the config validate contract (and the published schema) caught it. Tests: packages/moltlazy/tests/agents.test.ts (asserts neither retired key is emitted); docs packages/moltlazy/AGENTS.md.

  • Local development runs on the Cloudflare Vite plugin instead of wrangler dev. bun run dev:worker / bun start start the Worker with vite dev (vite.config.ts), the same plugin bun run build already used; bun run dev serves the admin SPA from vite.ui.config.ts (:8787) and proxies to the Worker (:8788). Local E2E fixtures (test/e2e/fixture/server/start-local, start-local-pair) launch vite dev, pass the old --var overrides through the plugin’s config hook (E2E_WORKER_NAME, PERSIST_STATE_PATH, VITE_CACHE_DIR, VITE_INSPECTOR_PORT), install test/e2e/.dev.vars into the Worker config directory for the run (the plugin has no --env-file; stop-local* restores the developer’s file), and fire cron ticks through /cdn-cgi/local/scheduled instead of /__scheduled. --env is gone from the deploy/dry-run scripts: CLOUDFLARE_ENV=… selects the environment at build time and wrangler deploy discovers the generated dist/fouria/wrangler.json via .wrangler/deploy/config.json. Docs: README.md, docs/DEVELOPMENT.md, docs/TESTING.md, apps/fouria/README.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md, test/e2e*/README.md.

  • /healthz is now a real, fast liveness route. It previously fell through to the gateway-proxy catch-all (app.all('*')), which ran restoreIfNeeded + ensureGateway + a waitForGatewayReady port wait — on a cold/sleeping instance GET /healthz took ~108 s and was killed by the platform before responding (Workers Observability on tenant-client-dev: GET /healthz → 503 @ ~108 s avg, 348 requests in 2 h). The new GET /healthz does exactly one non-waking isRuntimeActive() read and returns 200 { ok, ts, status } (active | idle) sub-second, never warming the container or probing the gateway; readiness stays on /api/health. It sits on the tenant hostname, so it stays behind the host Access app (not public). Tests: src/routes/public.test.ts (/healthz 200 + no ensureGateway/exec/listProcesses; idle when the runtime is off); docs apps/fouria/README.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/WORKER-HEALTH.md.

  • Browser health endpoints moved to Access-safe sibling paths (/api/health-ws, /api/health-snapshot, /api/health-components). On tenant hostnames every browser WebSocket and fetch() under /api/health or /api/health/* failed (WebSocket connection to 'wss://…/api/health/ws?passive=1' failed, plus CORS/redirect failures on GET /api/health/components and GET /api/health): the path-scoped FourIA Health - <slug> Access app shadows those paths and its AUD is distinct from the host app’s (Cloudflare ignores a requested aud on create and update — verified against the live API — so the AUDs cannot be unified). A browser logged into the host app therefore gets a cross-origin 302 login redirect to *.cloudflareaccess.com on /api/health*, which WebSocket handshakes cannot follow and browser fetch() rejects on CORS. The sibling paths /api/health-ws, /api/health-snapshot, and /api/health-components sit outside the health app’s path prefix, so the host-app session the browser already holds passes (verified against live staging-client-dev.fouria.io: /api/health-* resolves to the host app kid, while /api/health and /api/health/* resolve to the health app kid). The Worker mounts the handlers at both path sets (healthHandler, healthComponentsHandler, healthWsHandler in src/routes/public.ts); api.ts (subscribeHealth, getHealth, getCloudflareComponents) and loading.html use the - sibling paths, while /api/health, /api/health/ws, and /api/health/components remain for headless service-token clients (lerma). Tests: src/routes/public.test.ts, src/assets/loading.test.ts, UI stubs test/ui/support/api.ts + test/ui/cloudflare-components.spec.ts; docs apps/fouria/README.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/WORKER-HEALTH.md, docs/TESTING.md; lerma access_policy.ex documents the constraint.

  • Telegram ingress queue observability: notification-bell entry + home status widget. The per-tenant TelegramIngress DO now records every ingress event (bounded counters + last 20) — queued (a cold update was enqueued and woke the container), forwarded (hot path), delivered, and failed — via telegram-ingress/status.ts, wired from the webhook route (queued/forwarded) and the queue consumer (delivered/failed). GET /api/admin/telegram-ingress/status returns the snapshot and GET /api/admin/telegram-ingress/ws streams it (a frame per change, TELEGRAM_INGRESS_WS_POLL_INTERVAL_MS, rotated). The admin shell’s TelegramIngressProvider opens the socket only while the feature is in use (an account is registered or activity exists) and raises a notification-bell entry (“Telegram message queued — waking your instance”, or a delivery-failure alert); the new TelegramIngressWidget on the home page shows state + queued/delivered/failed + last event, hidden until in use. Tests: src/telegram-ingress/status.test.ts, src/routes/api/telegram-ingress.test.ts, src/client/__tests__/telegram-ingress-context.test.tsx, src/client/components/__tests__/TelegramIngressWidget.test.tsx, src/client/pages/__tests__/HomePage.test.tsx; corpus test/business-rules/dashboard-api-contract.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Homepage no longer crashes with Cannot read properties of undefined (reading 'length'). GET /api/admin/software/report ran cat <report> 2>/dev/null || echo '{}', so a tenant whose moltlazy software provision had never run got a truthy report: {}; the homepage Software widget then read software.packages.length and threw on render (only for ADMIN — ROOT lands on diagnostics). The route now returns report: null unless the payload is a real report (an object with a packages array), and HomePage reads software?.packages ?? [] defensively. Tests: src/routes/api/software.test.ts (missing/partial report → null), src/client/pages/__tests__/HomePage.test.tsx (truthy {} renders the empty state instead of crashing).

  • Release CD promotes the already-built artifacts instead of rebuilding. deploy-fouria.yml used to docker build the container image from source and re-build the wrangler bundle at release time; it now promotes what CI already built: it resolves the release’s develop-mainline build commit (git rev-list -n1 --first-parent --invert-grep --grep='^chore: release' <tag> -- apps/fouria/ .github/workflows/test.yml), retags the Cloudflare registry image fouria:unstable-<sha> → fouria:<tag> + latest (minting short-lived pull+push registry credentials via POST /accounts/{id}/containers/registries/{host}/credentials, mirroring Lerma’s ImageRegistry), and copies the CI bundle fouria-bundles:unstable-<sha>/fouria.mjs → <tag>/ + latest/ in R2. deploy-dashboard.yml now tags the develop build with an immutable lerma:sha-<sha> in addition to :latest-pre, and its promote job pins to that per-commit image (resolving the release’s lerma build commit the same way) instead of the floating :latest-pre (falling back only for the first release after the tag is introduced). Docs: docs/DEVELOPMENT.md, docs/TESTING.md, apps/lerma/DEPLOY.md, apps/fouria/docs/WORKER-DEVELOPMENT.md. Both workflows validated with actionlint.

  • Durable doctor-repair/SQLite jobs start immediately, and their status streams over a WebSocket instead of 2s polling. A doctor-repair job enqueued at 12:57:30 only began at 13:02:11 — exactly the previous boot job’s 14-minute lease — because the ActivityScheduler owns one alarm and a stale arm (the alarm handler’s trailing re-arm, or a warm-path refresh) could read “no pending job”, then execute its setAlarm(later)/deleteAlarm() after the just-enqueued job’s setAlarm(now), postponing it. scheduleCombinedAlarm now writes through armWithGenerationGuard (activity/alarm.ts): it bumps a stored generation, and a superseded arm abandons its stale write so the newest arm (fresh read) owns the alarm. The dashboard no longer polls GET /api/admin/config/fix/jobs/:id every 2s (one request + Worker log line per tick for the whole multi-minute repair): a new GET /api/admin/config/fix/jobs/:id/ws (and the /debug/sqlite-integrity/jobs/:id/ws variant) streams the job (routes/api/maintenance-ws.ts) — a frame only on status change, close 1000 when terminal, and a rearm() self-heal while active. The client’s subscribeMaintenanceJob is WS-first with a slow HTTP fallback only while the socket is down, and DiagnosticDashboard renders a live MaintenanceJobModal (queued/running/attempt/elapsed, run-in-background) instead of a bare spinner, with a banner to reopen it after backgrounding. Tests: src/activity/alarm.test.ts, src/activity/scheduler.test.ts, src/routes/api/maintenance-ws.test.ts, src/client/__tests__/maintenance-job-subscription.test.tsx, src/client/pages/__tests__/DiagnosticDashboard.test.tsx; corpus test/business-rules/dashboard-api-contract.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Sandbox memory OOM mitigation (dev instance). A dev instance grew RSS past OpenClaw’s 1.5 GiB rss_threshold (worker-thread V8 heaps + native arenas, not the main isolate) driven by cron-replayed heavy agentTurn jobs. (1) packages/moltlazy AGENT_DEFAULTS.compaction sets enabled: true, maxActiveTranscriptBytes: '20mb', keepRecentTokens: 20000 so a provider-side-managed session can no longer grow its persisted transcript unbounded (the fouria-builder:main ~407k-token session inflates the SQLite history and worker heaps). (2) The dev-only Fouria Builder entry sets heartbeat.every: '12h' plus isolatedSession: true / lightContext: true — OpenClaw’s default 30m heartbeat is a full agent turn ~48×/day that also triggers memory-core dreaming reconciliation. (3) start-openclaw.sh slows memory-core’s dreaming sweep to weekly (frequency: "0 3 * * 1", dev-gated) — the ~6-min daily sweep is replayed on every wake (cron: running missed jobs after restart) and produced the 1.6 → 2.08 GiB RSS spike. (4) ensure_opencode_credits_automation dedupes via openclaw cron list --all --json in addition to the legacy automations list (which missed a prior boot’s job, creating two duplicate opencode-credits-check cron jobs). Tests: packages/moltlazy/tests/agents.test.ts; docs packages/moltlazy/AGENTS.md, apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Boot log streams gateway-launch progress (fixes “Launching the gateway — no progress for 6 min”). start-openclaw.sh now starts a start_boot_log_stream mirror in launch_gateway_process that tails the gateway’s own --verbose stdout (/tmp/gateway-stdout.log) into the curated boot log (/tmp/startup.log) — so the loading page can follow SQLite migration → plugin load → port bind instead of going blank the moment start/launch execs the gateway. post-start/full stop the mirror (stop_boot_log_stream) and truncate the buffer at readiness. The Worker’s /api/startup/ws stream now reads the boot log while processType === 'gateway' (not just 'script'), and loading.html shows the log panel during gateway startup — restyled as a vintage CRT terminal (title bar + traffic lights + phosphor text + scanlines) — instead of hiding it behind the logo. Tests: src/assets/loading.test.ts, src/routes/public.test.ts; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Loading page no longer gives up on its own. loading.html had two client-side budget specs — a 5-error retry cap (maxConsecutiveErrors, Retrying... (n/5)) and an 8-minute wall-clock deadline (MAX_WAIT_MS / deadline → runDoctorAndShow()). Since the cold boot moved to the durable ActivityScheduler boot job (which owns retries and terminal failure), the page’s self-imposed give-up only interrupted a legitimately long startup: it now waits indefinitely (WebSocket push, with an unlimited 5s HTTP-poll fallback) and reports terminal failure solely from boot.status === 'failed' and permanent degraded container errors. Removed the now-dead runDoctorAndShow/showStructuredError/showError helpers. Tests: src/assets/loading.test.ts; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Health endpoints no longer require the ROOT role at the edge. A tenant ADMIN opening /_admin was 302’d to the Cloudflare Access login for GET /api/health and GET /api/health/ws (the dashboard’s health stream), because the per-tenant FourIA Health - <slug> Access app on <slug>.fouria.io/api/health allowed only the Paso4 Root Users group plus lerma’s health-monitor service token. The health app (and the platform-wide *.fouria.io/api/health / *.dev.fouria.io/api/health IaC apps) now carries no role requirement: an allow policy on everyone (any authenticated user) plus the existing non_identity service token, so the dashboard and lerma’s headless probe both work. AccessPolicy.health_policies/1 drops the root-group policy (the host app keeps it); access.tf public_health matches. Tests: test/lerma/cloudflare/access_policy_test.exs, apps/fouria/iac/tests/access_app.tftest.hcl; docs apps/lerma/README.md, apps/fouria/iac/README.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/ENV-VARIABLES.md. Existing tenants were reconciled in place via the Cloudflare API (aud preserved).

  • Restore decrypt no longer exhausts the Worker CPU budget, and interrupted restores are labelled honestly. A large recovery archive (tenant-tarjetero-dev) was killed with Worker exceeded CPU time limit mid-Decrypting backup … and retried in a loop. encryptStream/decryptStream (src/crypto/backup-encryption.ts) grew each 4 MiB chunk with concat on every ~64 KB R2 read, recopying the pending chunk ~64× over; a ByteQueue now copies each byte once (96 MiB decrypt: 1.5 s → 0.14 s at 64 KB reads, 5.6 s → 0.14 s at 16 KB). The R2 binding delivers the archive in 4 KiB reads (64 MiB → 16,385 reads), which is why the per-read copy dominated; each restore now logs [crypto] Decrypt read profile (reads, bytes, max/avg read, chunks) so the pattern can be checked on a live tenant. The loading bar also showed the last durable phase (Waiting for the backup lock 3%) as if still live: a failed attempt is now labelled Restore attempt failed during "<phase>" — retrying (recordRestoreFailure), and an idle record gets — no progress for N min (describeRestoreProgressIdle); the fraction never moves backward. Tests: src/crypto/backup-encryption.test.ts, src/activity/restore-progress.test.ts, src/activity/scheduler.test.ts; docs docs/WORKER-DEVELOPMENT.md.

  • Recovery progress bar synchronized with the durable object’s events. During a restore the loading page showed a generic spinner; it now shows a progress bar driven by the ActivityScheduler DO’s own phase events, not a client-side timer. restoreIfNeeded/restoreBackupById call their onProgress(phase) hook on every persistence.phase; the DO wires it to recordRestoreProgress, which maps the phase to a label + a monotonic fraction (describeRestoreProgress in activity/restore-progress.ts, cumulative phase weights) and exposes it via getRestoreProgress(). /api/startup/ws (and non-passive /api/health, plus /api/admin/boot-state) push restoreProgress: { phase, label, fraction }; loading.html renders the bar and hides the stepper while a restore is in flight, then switches back to the container’s startup-progress.json stepper once the gateway launch begins (an indeterminate bar covers a request-scoped restore with no DO feed). Also declares getBootJob/getRestoreProgress on ActivitySchedulerStub (fixing the public.ts type error). Tests: src/activity/restore-progress.test.ts, src/activity/scheduler.test.ts, src/routes/public.test.ts, src/routes/api/misc.test.ts, src/assets/loading.test.ts; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md.

  • Restore legibility: name the backup + date being loaded (and mark the recovery point). A cold restore showed only a generic “Restoring data from backup…” spinner, so an operator could not tell which snapshot was loading. (1) Durable recovery state. restoreIfNeeded/restoreBackupById now write restore-target.json (the archive being applied) just before sandbox.restoreBackup and clear it on success; readRecoveryState(bucket) returns { restoring, committed } (committed = stable-backup.json). It is read from R2, not the per-isolate restoreStatus, because the durable boot/restore runs in the ActivityScheduler DO whose in-memory state the request isolate cannot see. (2) Surfaced on the loading page. /api/health (non-passive, not-yet-ready) and /api/startup/ws attach recovery (bounded by RECOVERY_STATE_TIMEOUT_MS, fail-soft to null; lerma’s passive poll never pays the read); loading.html renders “Restoring backup — ” (or “Recovery point …”) and its isRestoring also honours recovery.restoring. (3) Dashboard. BackupsPage threads stableBackupId to BackupHistoryPanel, which marks the recovery point with a recovery point badge + a “A cold boot restores — ” summary. Tests: src/persistence.test.ts (readRecoveryState, restore-target publish/clear), src/assets/loading.test.ts, src/client/components/__tests__/BackupHistoryPanel.test.tsx, src/routes/public.test.ts; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md.

  • Manual-restore hardening: recovery-point flag, writer quiesce, and no restore loop. Restoring an older archive from the Backups page could not be applied without either making it permanent or being silently undone. Three fixes in src/persistence.ts + the storage route/durable job. (1) setCurrent flag. POST /api/admin/storage/restore/:id?setCurrent=0 (also ?async=1&setCurrent=0) passes { setRecoveryPoint: false } to restoreBackupById so the archive is applied without force-promoting it to stable-backup.json (the default still promotes; the durable BackupJobRequest/BackupJobRecord carry the flag so a retried job keeps the intent). The Backups page exposes it as a Set as recovery point checkbox (checked by default). (2) Stop writers on the lease. restoreBackupById now opens a cross-isolate maintenance window (maintenance/replacement.json, operation restore) and stops the gateway the moment it takes the shared restore lease (the route no longer pre-kills before the lock), closing the window in a finally; a live gateway/automation/channel therefore cannot keep writing while sandbox.restoreBackup replaces the writable layer. (3) No remount loop. restoreIfNeeded refuses to run while any maintenance window is active (and ensureGateway already refuses to launch), so a health/proxy refetch cannot restart the gateway and re-run the restore against the committed recovery point — the restore → stop → refetch → remount-the-latest loop. Tests: src/persistence.test.ts (set-recovery-point, maintenance window, deferred restore), src/persistence-encryption.test.ts, src/routes/api/storage.test.ts, src/activity/scheduler.test.ts, src/activity/backup-jobs.test.ts, src/client/components/__tests__/BackupHistoryPanel.test.tsx; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md.

  • Durable cold-boot job + slim health probe (observed on tenant-client-dev: start-openclaw.sh never ran; phase=restore, age=686365ms; 141 waitUntil() tasks did not complete; /api/health?passive=1 at error level ×98). (1) Durable boot. The cold boot (R2 restore → gateway launch) was driven from a request’s ctx.waitUntil(), which Cloudflare cancels shortly after the response — so a restore that outlived it was killed mid-flight (Decrypting backup … ×14) and start-openclaw.sh was never reached while every poll parked on the stuck start promise. It is now a durable job on the ActivityScheduler DO (src/activity/boot-job.ts): /api/warmup, non-passive /api/health, and /api/startup/ws only request it (deduped) and return; the DO alarm performs restoreIfNeeded → ensureGateway and retries on a bounded lease. Falls back to the request-scoped boot when ACTIVITY is absent. (2) sandbox.restoreBackup is bounded by RESTORE_BACKUP_TIMEOUT_MS (a hung control channel fails fast instead of holding the restore phase for 11 min). (3) The restore reports sub-phase progress so isGatewayStartStuck judges restore on GATEWAY_RESTORE_NO_PROGRESS_MS of no progress (setGatewayStartProgress) — a slow-but-advancing restore is not killed. (4) withLease releases the shared R2 lease when its request aborts (PersistenceDiagnosticContext.signal), so a cancelled operation can’t leave restore-needed + a held backup-lock re-triggering the loop. Also: /api/health now issues one gateway /health exec shared by readiness + liveness (was a duplicate curl pair per poll) and the passive path skips the container + R2 component probe (lerma’s frequent probe never reads components). Tests: src/activity/boot-job.test.ts, src/gateway/process.test.ts, src/gateway/health-probes.test.ts, src/routes/public.test.ts, src/persistence.test.ts; corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Slimmer /api/health (frequent lerma probe). Two per-poll costs removed. (1) Readiness and liveness each ran the same gateway /health curl, so every poll spawned a pair of identical curl processes (visible as paired entries in /debug/processes); getHealthSnapshot now fetches the process scan and the /health probe once, in parallel, and reuses both across the probes (new HealthProbeOptions.health). (2) The component probe (an isRuntimeActive read + an R2 HEAD of backup-handle.json) was built on every /api/health, including lerma’s frequent ?passive=1 poll — which never reads components; the passive path now skips componentsForHealth entirely (the non-passive path and the dedicated GET /api/health/components are unchanged). Tests: src/gateway/health-probes.test.ts (single shared exec), src/routes/public.test.ts (passive omits components); corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md.

  • Restore config guard + recovery-point promotion (observed on tenant-tarjetero-dev). After the v2026.10.13 container rollout, an explicit restore of an older known-good backup did not stick: the redeploy changed the container runtime mid-restore, and a concurrent scheduled snapshot captured the partially-restored state and was auto-promoted to the stable recovery point, so the next cold boot restored the wrong archive and launched the gateway with no config. Three fixes: (1) start-openclaw.sh only honours OPENCLAW_RESTORED=true when $CONFIG_FILE exists — otherwise it runs the setup body — so a “restored” boot with no materialized config (interrupted restore, or restoreIfNeeded’s “container already holds tenant state” short-circuit) can no longer launch OpenClaw configless. (2) restoreBackupById now force-promotes the restored archive to stable-backup.json (promoteStableBackup(bucket, entry, { force: true })) so an explicit restore becomes the recovery point even when it predates the current one; the default pointer still only advances forward in time. (3) the pre-backup config cleanup used .${CONFIG_DIR} with CONFIG_DIR='.openclaw', building /home/openclaw/..openclaw/… (a never-existent path, so the cleanup silently no-oped) — it now uses ${CONFIG_DIR}. Tests: src/persistence.test.ts (force-promote; cleanup path); corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, apps/fouria/docs/OPERATOR-GUIDE.md.

  • Cold-start latency + boot legibility (a full non-restored boot on staging-client-dev took ~14 min). Two causes, both fixed, plus a loading-page alert. (1) Non-owner killed the booting gateway. A non-owner isolate that observed the start-openclaw.sh start wrapper waited a fresh STARTUP_TIMEOUT_MS (300s) from its own observation, but the wrapper’s real boot is setup (~290s) + gateway bootstrap (~45s) ≈ 335s — so the waiter timed out ~35s early and kill()ed the process just as it had execed into the gateway, releasing the startup lock and making the waiting second wrapper re-run the whole setup. Confirmed via Workers Observability: Startup script present but gateway never became reachable … killing and restarting = 1 while the warm-probe start/catch = 0/0 (ruling out the 30s warm probe). Fixed with STARTUP_WRAPPER_STUCK_BUDGET_MS (STARTUP_TIMEOUT_MS + GATEWAY_START_STUCK_GRACE_MS): the non-owner’s stuck check and readiness wait are measured from the wrapper’s startedAt (mirroring the owner’s watchdog) and a /health re-probe runs immediately before any kill. Tests: src/gateway/process.test.ts, src/gateway/process-extra.test.ts. (2) Plugin detection read the hanging registry. plugin_is_installed ran openclaw plugins list --json, which hangs for its full CLI_TIMEOUT and reads as “not installed” on a hung/partial list, so the pre-installed guard fell through and triggered a needless network install (ai-gateway ~57s + otel ~74s). Replaced with plugin_extension_present (the extensions/<id> dir the gateway actually loads). (3) Bootup-UI alert. The loading page now shows a non-fatal slow-step notice (step name + elapsed seconds) once a step overruns SLOW_STEP_MS (120s), so a slow-but-progressing boot is distinguishable from a stuck one without opening logs. Tests: src/assets/loading.test.ts. Corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/plans/cold-start-latency.md.

  • The tenant Usage & Billing widget no longer 403s on Analytics Engine. GET /api/admin/costs/v2/summary resolved its AE SQL token as ANALYTICS_ENGINE_API_TOKEN ?? CLOUDFLARE_API_TOKEN, but Lerma never provisioned the dedicated token, so the query fell back to CLOUDFLARE_API_TOKEN — the AI Gateway credential alias, which lacks Account Analytics:Read — and logged [cost-summary] Analytics Engine query failed with HTTP 403 on every load (observed on tenant-client-dev), zeroing the widget. The token is now a Lerma platform secret (tenant_provisioner.ex @platform_secrets), read from Lerma’s environment and deployed per-tenant as a secret_text binding; the deploy path wires it through mix lerma.deploy, Ansible app-config, docker-compose.prod.yml/.pre.yml, and deploy-dashboard.yml, and the secrets manifest. Optional: when unset the worker still degrades to an all-zero summary. Tests: tenant_provisioner_pipeline_test.exs, tenant_provisioner_integration_test.exs; docs docs/ENV-VARIABLES.md, apps/lerma/README.md, apps/fouria/docs/cost-observability.md, SECRETS.example.yaml, docs/schemas/secrets-manifest.schema.json.

  • Zero-data-loss: a restored container skips the setup body. The R2 restore runs in the Worker (restoreIfNeeded → sandbox.restoreBackup()) before start-openclaw.sh; when that restore actually restored a backup, ensureGateway now passes OPENCLAW_RESTORED=true in the launch env (gated on getRestoreStatus().hadBackup && restored, so a brand-new tenant with no backup still onboards), and the script skips the whole setup body — onboard → plugin installs → moltlazy patch → config validate — emitting those phases as skipped and launching the gateway directly from the restored filesystem. The restored state is authoritative: the cold-start budget is spent launching it, not re-mutating it (which could diverge from or clobber the snapshot). Each boot rewrites a durable receipt at /tmp/openclaw-restored-setup-skipped (written on the skip path, removed on the setup path). Tests: src/gateway/process.test.ts; E2E test/e2e-backup/zzz_backup_restore_skip_setup.txt (opt-in E2E_BACKUP_RESTORE=1; sync → destroy → restore, asserts the receipt + unchanged restored setup state); corpus test/business-rules/operational-modes.txt; docs apps/fouria/docs/WORKER-DEVELOPMENT.md, test/e2e-backup/README.md, test/e2e/BACKUP-E2E-DESIGN.md.

  • The dashboard Usage & Billing widget now reflects emitted billable actions. GET /api/admin/costs/v2/summary was a stub returning totalCostUsd: 0; it now aggregates the tenant’s billable-action Analytics Engine rows via the AE SQL API (src/cost-summary.ts → getCostSummary()), returning totalCostUsd, totalCredits, actionCount, byTriggerType, and byCostCategory. Config mirrors Lerma: ANALYTICS_DATASET (default fourai_cost_metrics), ANALYTICS_ENGINE_BASE_URL, and ANALYTICS_ENGINE_API_TOKEN (falls back to CLOUDFLARE_API_TOKEN; needs Account Analytics:Read). A missing credential/transport error/non-200 degrades to an all-zero summary, so the widget never breaks. The widget surfaces the billable action/credit rollup when data is present. Tests: src/cost-summary.test.ts, src/routes/api/costs.test.ts, src/client/pages/__tests__/HomePage.test.tsx, src/client/pages/__tests__/AccountPage.test.tsx, test/ui/billing-widget.spec.ts; corpus test/business-rules/dashboard-api-contract.txt; docs apps/fouria/docs/cost-observability.md, docs/ENV-VARIABLES.md, docs/TESTING.md.

  • The version surfaces now report the Worker’s own build identity. GET /api/admin/version and GET /debug/version return fouria_version (component CalVer from apps/fouria/package.json) and fouria_commit (short git SHA) alongside the container’s OpenClaw/Node versions; the DiagnosticDashboard Version Info tool surfaces them. Both values are injected at build time by vite.config.ts (__FOURIA_VERSION__ / __FOURIA_COMMIT__, consumed via src/build-info.ts; GITHUB_SHA wins in CI, git rev-parse --short HEAD locally). Tests: src/routes/debug.test.ts, src/routes/api/misc.test.ts; docs docs/WORKER-DEVELOPMENT.md, docs/OPERATOR-GUIDE.md.

  • Expected CLI non-zero exits are no longer logged as failures. waitForProcess (like runShell) now takes reportNonZeroExit; the knowledge wiki status probe sets it false (operation knowledge.wiki-status) because openclaw wiki status exits non-zero for an uninitialized vault — which /api/admin/knowledge/tree handles as a normal initialized: false result — yet every load emitted Error [SandboxProcessError]: sandbox.waitForProcess failed (non-zero-exit, exit=1). Timeouts still log. Tests: src/gateway/utils.test.ts; corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md.

  • The prelaunch gateway port probe no longer logs a false failure. isGatewayPortOpen ran curl -sf …/health through runShell, whose logCommandFailure emitted a structured sandbox.process.failed error for the expected closed-port exit (curl 7 = connection refused). Every cold start therefore surfaced a scary Error [SandboxProcessError]: shell failed (non-zero-exit, exit=7) for the normal “gateway down, start it” outcome. It now passes reportNonZeroExit: false with operation: 'gateway.port-probe' (matching the existing gateway.health-probe), so a closed port is quiet while a probe timeout (a hung gateway) still logs. Test: src/gateway/process.test.ts (does not log a structured failure for the expected closed-port exit); corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md.

  • OpenClaw is installed globally with bun, not npm. bun install --global --trust openclaw runs with BUN_INSTALL=/usr/local: bun’s default global prefix is $HOME/.bun/bin, which is not on PATH in this image, so BUN_INSTALL=/usr/local puts the binary at /usr/local/bin/openclaw (on PATH) and the package under /usr/local/install/global/node_modules/openclaw. bun pm cache rm resolves the current project and hard-fails without a package.json — the base image’s WORKDIR /container-server has none — so it runs from /tmp (which holds the copied repo package.json). The dead-weight trim now targets bun’s hoisted global layout (<prefix>/install/global/node_modules), and start-openclaw.sh resolves the package by following the installed binary (command -v openclaw + readlink -f) instead of npm root -g, so the runtime-version log stays accurate.

  • post-start no longer blocks readiness. After the port wait succeeds the gateway is already serving /health 200, but ensureGatewayImpl still awaited start-openclaw.sh post-start (dev automation + boot-log reset, bounded by GATEWAY_POST_START_TIMEOUT_MS = 60s). On dev instances that phase runs openclaw automations list/create (30–60s), so every request logged Gateway start already in progress … (phase=post-start) and waited on the shared start promise even though the gateway was up. It is now dispatched detached (void runGatewayPostStart(...), not awaited) right after markGatewayReady; startShell dispatches the sandbox.exec synchronously before its first await, so the work still runs server-side if the isolate is evicted, and runGatewayPostStart swallows its own errors. The post-start phase is no longer set on the start tracker (the start is complete). Test: src/gateway/process.test.ts (does not extend the shared start promise with the detached post-start phase); docs docs/WORKER-DEVELOPMENT.md.

  • ClawHub plugin pre-install is best-effort so the image still builds. The unpinned clawhub:@openclaw/cloudflare-ai-gateway-provider resolved to 2026.9.9, which requires a newer plugin API than the pinned 2026.9.8 runtime, so openclaw plugins install failed and aborted the whole Docker build (Plugin … requires plugin API >=2026.9.9, but this OpenClaw runtime exposes 2026.9.8). The Dockerfile now wraps each pre-install in a warn-and-continue guard, and start-openclaw.sh’s single enablement config patch only enables a plugin whose extension directory is present (CF_AI_GATEWAY_PLUGIN_PRESENT / UNIFIED_BILLING_PLUGIN_PRESENT), so a failed install can neither fail the build nor invalidate the patch. Root-cause follow-up: bump catalog.openclaw to the plugin-compatible release (openclaw-migration skill) or pin the specs; until then a build on the pinned runtime ships without the Cloudflare provider plugins. Corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md, docs/OPENCLAW-PLUGINS.md.

  • Gateway start watchdog + process-count hygiene. A cold start is one shared ensureGateway promise (restore → supervised start-openclaw.sh start → port wait); a wrapper that never execs the gateway, or a control-channel drop, left it “in progress” for ~20 min while every request logged Gateway start already in progress … waiting... and waited on it (observed on tenant-client-dev: 64 processes, port closed, curl health probes exiting 7 every ~5s, [PROXY] Failed to start gateway stack-only). The start is now tracked per sandbox key with a phase (probe → restore → launch → port-wait; post-start runs detached after readiness, not tracked) and a per-phase budget; isGatewayStartStuck trips when a phase overruns its budget + GATEWAY_START_STUCK_GRACE_MS. Before resetting port-wait, recoverStuckGatewayStart rechecks /health: a late-positive response emits gateway.start.late-ready and is adopted without killing, while a failed/unknown recheck emits gateway.start.health-recheck-failed and defers reset. Confirmed stuck starts emit gateway.start.stuck, kill the process (killGateway), clear startup/readiness caches, and reprovision after GATEWAY_START_STUCK_MAX_ATTEMPTS resets (recoverStaleSandbox). findExistingGatewayProcess also uses the pure classifyGatewayStart to kill a start-openclaw.sh start wrapper older than STARTUP_TIMEOUT_MS with the port closed, instead of waiting out another readiness budget. Because listProcesses() includes exited/error entries the Worker never GCs (the SDK exposes no cleanup), the raw count is append-only and must not gate health: the log now reads listProcesses returned <total> processes (<running> running) and every decision considers only running entries. Emits gateway.start.begin/phase/stuck/late-ready/health-recheck-failed. Tests: src/gateway/classify.test.ts, src/gateway/process.test.ts; corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md, docs/OPERATOR-GUIDE.md.

  • Legacy bridge excludes the image-provided shared OpenClaw package. extensions/<id>/node_modules/openclaw is a symlink to the image’s /usr/local/lib/node_modules/openclaw; archiving it is pointless and (when an old dereferencing stage expanded it into a full package copy) made the restore materialization a multi-minute copy that blocked the gateway launch, left restore-needed set, and re-ran the restore on every boot (observed on staging-client-dev: cp -a … /root/openclaw/.openclaw/ running 8m45s, 65 Worker probe processes, no start-openclaw.sh/gateway). Both stageLegacyRootsForBackup and materializeLegacyRootsAfterRestore now use a symlink-preserving tar pipe with --exclude='*/node_modules/openclaw' (a copy-then-rm -rf is equally slow — deleting a squashfs-lower tree requires copy-up), so old and new archives restore fast. restoreIfNeeded also deletes the restore-needed marker immediately after a successful materialization (before the analytics bookkeeping) so an isolate eviction can no longer leave a stale marker. Tests: src/persistence.test.ts; corpus test/business-rules/operational-modes.txt.

  • Legacy restore bridge preserves symlinks (backup/restore fix). The legacy state bridge staged /root/openclaw/.openclaw with cp -aL, which dereferenced the plugin extensions/*/node_modules/openclaw symlinks (→ /usr/local/lib/node_modules/openclaw) into full OpenClaw package copies. That bloated every archive (the package three times over), timed out the pre-snapshot stage (600s) — surfacing to the dashboard as a backup-create Internal Server Error — and made restore fail because cp cannot overwrite the image’s symlink with a directory (cp: cannot overwrite non-directory … with directory), leaving the tenant looping on a failed restore (staging-client-dev). The stage and the restore materialization now use cp -a (preserve symlinks); the restore additionally removes any destination symlink the stage replaces with a real directory first, so backups created by the old dereferencing stage still restore. Tests: src/persistence.test.ts; corpus test/business-rules/operational-modes.txt. Also: the admin API client (src/client/api.ts) now reads the response body once and surfaces a plain-text platform error (e.g. Internal Server Error) instead of throwing Unexpected token 'I', "Internal S"... is not valid JSON; tests src/client/api.test.ts.

  • Recurring-error hardening: credential redaction, bounded-RPC cleanup, live-gateway logs, and idempotent WS teardown. Investigation of the recurring ReadableStream received over RPC disconnected prematurely / [WS] Client error telemetry found four concrete causes. (1) Credential logging: the catch-all proxy logged the full forwarded header map (Object.fromEntries(httpHeaders.entries())), writing CF Access JWT/assertions, cookies, and the tenant metadata blob to Workers Logs; it now logs only an allowlisted subset (safeHeaderLog, src/utils/logging.ts). (2) Late container RPCs: a bounded containerFetch/wsConnect whose timeout won could still settle later with a live body/socket that was never drained/closed; withTimeoutAndCleanup (src/utils/timeout.ts) plus containerFetchWithTimeout/wsConnectWithTimeout (src/utils/container-rpc.ts) cancel the late body / close the late socket, applied to the public proxy, diagnostics, and the gateway-api probes. (3) Live gateway logs: a running gateway’s SDK log stream never settles, so reading it opened an RPC stream that was later disconnected; a running GatewayProcess.getLogs() now tails /tmp/gateway-stdout.log, and /debug/processes?logs=true / /api/admin/logs?id= refuse a live stream for a still-running process. (4) WS teardown: both peer close handlers recorded the same session metric twice, and a client tab disconnect was logged at error; a single settleSession() now records the metric once and client disconnects log at warn with the sessionId. Tests: src/utils/container-rpc.test.ts, src/utils/timeout.test.ts, src/logging.test.ts, src/index.test.ts, src/gateway/process.test.ts, src/routes/api/misc.test.ts, src/routes/debug.test.ts; local observability canary test/e2e/ad_observability_canary.txt + test/e2e/fixture/observability-query; corpus test/business-rules/operational-modes.txt; docs docs/TESTING.md.

  • Two local-E2E self-skip fixes. provision_and_dispatch’s first scenario (%require) echoed a SKIP: line and exit 1 in local mode, so it failed instead of skipping — and because it is %require, that failure skipped every later scenario in the file. It now emits the same PASS: … (skipped - local E2E mode) line and exit 0 the other local skips in the file use. p_otel_billing_queue asserted emitted >= 1, but a dev-environment/staging-platform instance is non-billable by design (resolveInstanceDimensions, src/routes/otel.ts): the receiver accepts + ignores approved spans (200) and returns billable: false without emitting. The local worker (DEV_MODE=true, no routable WORKER_URL) is always non-billable, so the test now skips on billable == false (like its existing missing-secret/401 skip); the emit path stays asserted by the cloud profile and src/routes/otel-traces.test.ts. Corpus: test/business-rules/operational-modes.txt, test/business-rules/dev-expense.txt; docs docs/TESTING.md.

  • Local E2E readiness gate accepts a reachable-but-starting Worker. fixture/server/start-local waited for /api/health with curl -sf -m 5 (60×2s), but a cold boot legitimately answers 503 while the container/gateway starts (the non-waking-health semantics) and the non-passive probe can block on container provisioning — so the gate misread a live-but-starting Worker as dead. Worse, the non-passive probe on every 2s poll re-triggered restoreIfNeeded/ensureGateway, launching overlapping R2 restores that abort each other with OperationInterruptedError: ... runtime changed. The gate now probes the fast, non-waking GET /api/health?passive=1 and accepts any HTTP status (200/503/…) via the shared e2e_worker_reachable helper (test/lib/e2e-helpers.sh), failing only on a connection failure (status 000); the window is overridable with E2E_STARTUP_TIMEOUT_SECS (default 120s) and the “local dev server died” check still fails fast. The real gateway wait (startup.ok + readiness.ok) stays in the _setup.txt readiness step. Tests: src/e2e-helpers.test.ts; corpus test/business-rules/operational-modes.txt; docs docs/TESTING.md.

  • Restore failures are logged as structured persistence.restore.failed events with backupId, errorName, and errorMessage; manual route failures also include the Cloudflare Ray ID as storage.restore.failed. This keeps the backup identity searchable and correlates async failures to the originating request. Tests: src/persistence.test.ts, src/routes/api/storage.test.ts.

  • Backup retention is enforced on catalog reads, and restores survive a failed pre-restore umount. Live fouria-backup-tarjetero-dev held 7 archives under maxVersions: 3: every snapshot was killed after sandbox.createBackup() (260 MB) but before its commit, so a later read adopted all 7 as orphans, and every scheduled snapshot after that failed at the legacy stage before its own prune — the cap was only ever applied on the happy snapshot path. reconcileOrphanedBackups now runs cleanupOldBackups after merging, so the invariant holds on every read (getBackupHistory included) and no write/delete happens when the catalog is already within the cap. Restores failed in a loop on [persistence] Restore of … failed: … runShell … restoreIfNeeded: the best-effort umount (|| true guards the shell, not the exec RPC) threw a cold-start/platform interruption and aborted the restore before restoreBackup, keeping restore-needed and failing the startup barrier. The umount is now caught + logged in restoreIfNeeded and restoreBackupById; an empty catalog read no longer deletes restore-needed (a transient reconcile list failure silently dropped an operator restore) — the marker clears only after a successful restore. Tests: src/persistence.test.ts (over-cap prune, adopted-orphan prune, no-delete within cap, marker retention, umount-failure restore); corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md, docs/OPERATOR-GUIDE.md.

  • Async admin backup/restore + non-blocking Backups page. A manual snapshot/restore can wait up to the 120s R2 lease and then transfer a large archive; holding the admin HTTP request open surfaced as a bare 500 after ~132s (restore) with the error dropped. POST /api/admin/storage/sync?async=1 and POST /api/admin/storage/restore/:id?async=1 now acknowledge 202 { accepted: true } and run in executionCtx.waitUntil (default stays synchronous for the E2E checkpoint). BackupsPage paints every section independently and reads the fast GET /api/admin/config/raw instead of the slow structured /api/admin/config (which awaits ensureGateway + up to two 30s shell waits) — so no single request blocks the page. BackupHistoryPanel fires the async endpoints, pushes a “started” bell notification, then polls GET /storage/backups (snapshot) / /api/health (restore) and pushes success/failure via NotificationProvider (survives navigation). Restore failures are reported as structured storage.restore.failed events. Tests: src/routes/api/storage.test.ts, src/client/components/__tests__/BackupHistoryPanel.test.tsx, src/client/pages/__tests__/BackupsPage.test.tsx; corpus test/business-rules/operational-modes.txt; docs docs/WORKER-DEVELOPMENT.md.

  • Startup-stream and dashboard polling back-off. /api/startup/ws now drops the 2-exec startup-progress read and backs off to STARTUP_WS_READY_POLL_INTERVAL_MS (30s) once the gateway is ready — the 5s cadence plus a per-push listProcesses/exec probe burst is a large share of the Sandbox DO control-channel churn (Establishing RPC connection) during a boot. useGatewayHealth now stops its HTTP fallback polling when a /api/health/ws snapshot arrives (it previously kept double-polling after the socket recovered). transformErrorMessage maps the gateway’s 1008 device token mismatch close to a “re-open /_admin/ to re-approve this browser” message instead of a reconnect loop. Tests: src/client/hooks/useGatewayHealth.test.tsx; corpus test/business-rules/operational-modes.txt.

  • Backup local-bucket mode is decoupled from DEV_MODE. isLocalBucketDevMode() keyed createBackup({ localBucket }) on process.env.DEV_MODE, and with nodejs_compat_populate_process_env the cloud E2E’s DEV_MODE=true var (set only to bypass Access on a bare workers.dev host) made every E2E snapshot land in the Sandbox local binding bucket — invisible to the Worker’s BACKUP_BUCKET HEAD, so restore logged Backup <id> missing from R2 and booted without tenant state. It is now isLocalBucketBackupMode(env): an explicit BACKUP_LOCAL_BUCKET=true opt-in that falls back to DEV_MODE only when unset; the E2E deploy pins BACKUP_LOCAL_BUCKET=false. resolveRestoreEntry threads env through. Tests: src/persistence.test.ts (explicit override wins); corpus test/business-rules/operational-modes.txt; docs docs/ENV-VARIABLES.md, docs/OPERATOR-GUIDE.md, docs/WORKER-DEVELOPMENT.md, .dev.vars.example.

  • A dropped port probe no longer spawns a duplicate gateway. When the DO↔container control channel flapped (Network connection lost. on every exec), ensureGatewayImpl’s prelaunch isGatewayPortOpenResilient throw was treated as “gateway absent”, so it re-ran start-openclaw.sh start on each request even though listProcesses matched the gateway running — piling lock contention and RPC load onto the unhealthy channel. A transport-classified probe failure is now “unknown”: the Worker logs Port probe transport drop … and returns without spawning, retrying on the next request. Test: src/gateway/process.test.ts (ensureGateway transport-drop resilience); corpus test/business-rules/operational-modes.txt.

  • E2E ac_gateway_startup_concurrency accepts the 503 cold-boot health response. The concurrent non-passive /api/health fan-out used curl -f, which fails on any non-2xx, but /api/health answers 503 while starting (JSON snapshot present) since the non-waking-health change — so a healthy cold boot always reported probes_ok=0. The probes now accept 200/503 with a shaped {startup, readiness} body; the ready-wait and single-owner assertions are unchanged. Docs/corpus updated.

  • Health is not a routing gate; ROOT operators can always reach a tenant. Tenant containers are loaded lazily by the User Worker, so a failed health probe is not an outage — yet the dispatch route gate treated clients.status/instances.status = error as non-operational (and lerma’s HealthMonitor / HealthPoller wrote that error), which locked operators out of a reachable tenant (observed on tenant-tarjetero-dev). workers/fouria-dispatch tenantRouteGate now never blocks on a health-derived error (production client or dev instance), keeps frozen/stopped gated only for non-ROOT callers (a ROOT operator is exempt so they can revive a stopped tenant), and runs after authentication so the exemption can be applied. apps/lerma HealthMonitor and TenantProvisioner.verify_health are now observability-only on failure: they record the down transition for the instance uptime widget but never change instance/client status (a successful probe still marks the instance running and recovers a client left in error by a provisioning failure). The now-meaningless HEALTH_MONITOR_FAILURE_THRESHOLD env var is removed. Tests: workers/fouria-dispatch/test/integration/resolution.test.ts, apps/lerma/test/lerma/provisioning/health_monitor_test.exs, tenant_provisioner_pipeline_test.exs; corpus test/business-rules/operational-modes.txt; docs workers/fouria-dispatch/README.md, docs/CLOUD-ARCHITECTURE.md, docs/ENV-VARIABLES.md.

  • Sandbox→R2 bridges resolve the tenant from the per-tenant Worker env, not the fixed sandbox id. The leads.r2.internal and docs.r2.internal bridges (src/sandbox-leads-bridge.ts, src/sandbox-docs-bridge.ts) scoped every path to the caller’s <slug>/ using ctx.containerId, but production provisions the sandbox under the fixed id openclaw (getSandbox(..., 'openclaw') in src/index.ts, src/tasks/index.ts, src/activity/scheduler.ts), so listings resolved to openclaw/ and always returned empty. Added resolveTenantSlug / tenantSlugFromEnv in src/sandbox-tenant.ts: an explicit customer-<slug> container id still wins (legacy multi-tenant), otherwise the slug is derived from the per-tenant Worker env — CUSTOMER_SLUG, WORKER_NAME via deriveCustomerSlug, or the always-provisioned WORKER_URL hostname (strips tenant- / staging- prefixes and the -dev suffix, so tenant-tarjetero-dev / https://tarjetero-dev.fouria.io → tarjetero). Tests: src/sandbox-tenant.test.ts, src/sandbox-leads-bridge.test.ts, src/sandbox-docs-bridge.test.ts; corpus test/business-rules/tenant-isolation.txt; docs docs/WORKER-DEVELOPMENT.md.

  • Dev-agent personas source the client proposal via the fouria-leads skill. The Fouria Builder and Q&A personas (packages/moltlazy/workspace/fouria-builder.ts + fouria-qa.ts) now read the skill first and fetch the proposal through the sandbox leads.r2.internal bridge (global paso4-leads R2 bucket) instead of the legacy /home/openclaw/clawd/client-docs/ path; the Worker’s dev-only docs materialization (materializeClientDocsIfDev) is no longer the personas’ input path. Docs updated alongside (packages/moltlazy/src/agents/README.md, packages/moltlazy/AGENTS.md, docs/DEVELOPMENT.md).

  • Crash-consistent backup cataloging (issue #344). The scheduled backup control action runs the full snapshot orchestration inside one tenant request and could exceed the Worker CPU budget after sandbox.createBackup() had uploaded backups/<id>/… but before the handle was written — leaving an orphaned snapshot, a missing backup-handle.json (and empty configs/), a live backup-lock, and a dispatch [cron] Failed to trigger backup. createSnapshotUnlocked now commits the catalog entry immediately after the archive is created (after encryption, before the config-version capture and retention prune), and reconcileOrphanedBackups rebuilds entries from backups/*/meta.json on read (getBackupHistory, restoreIfNeeded, scheduleBackupIfNeeded) so pre-existing orphans self-heal and stay restorable. The Dispatch Worker gives the backup action a dedicated CPU budget (BACKUP_CONTROL_CPU_MS) and logs the underlying error on a thrown control fetch. Tests: src/persistence.test.ts (commit ordering, config-save failure, reconciliation), workers/fouria-dispatch/test/unit/control.test.ts, cron-fanout.test.ts; corpus test/business-rules/operational-modes.txt; docs docs/OPERATOR-GUIDE.md, docs/WORKER-DEVELOPMENT.md.

  • Transport-resilient backup stage (issue #344 follow-up). The pre-snapshot legacy-stage shell now waits via runShellResilient (→ waitForExitResilient): a transient Sandbox DO↔container transport drop mid-stage reattaches to the process by id and resumes within the stage deadline, instead of ending the /control backup request (observed on staging-client-dev: the stage ran ~5 min then the request ended with a Network connection lost. drop and no Creating backup...). The Dispatch backup CPU budget (BACKUP_CONTROL_CPU_MS) is raised 300s → 600s to match the 10-minute stage bound. Tests: src/persistence.test.ts (transport-drop retry); corpus test/business-rules/operational-modes.txt; docs docs/OPERATOR-GUIDE.md, docs/WORKER-DEVELOPMENT.md.

  • Legacy-stage backup robustness + diagnosability (issue #344 follow-up). The scheduled backup stage shell (stageLegacyRootsForBackup → runLegacyStageShell) copies /root/openclaw/.openclaw + /root/clawd with cp -aL and runs a node:sqlite online backup; on a large tenant it exceeded the old 300 s bound and killed the backup (tenant-tarjetero, observed at exactly 300 s). LEGACY_STAGE_TIMEOUT_MS is now env-overridable (default 600000 / 10 min), the idempotent stage is retried once on a transient timeout/transport failure, and stage failures log exit/timedOut/stderr plus a structured sandbox.process.failed Worker event with processId and a stable operation label. The process id joins Worker Logs to the Containers dataset without exposing the raw command/output. Tests: src/persistence.test.ts (retry, no-retry, timeout override, error logging); corpus test/business-rules/operational-modes.txt; docs docs/OPERATOR-GUIDE.md, docs/WORKER-DEVELOPMENT.md, docs/ENV-VARIABLES.md.

  • Sleeping tenants + non-waking health. /api/health now answers 503 unless the gateway is ready, and a passive probe (?passive=1) short-circuits on the non-waking isRuntimeActive() read and reports status: "sleeping" (HTTP 200, healthy-idle) for an idle container instead of running the exec RPCs that auto-start it — so Lerma’s HealthMonitor (which now probes ?passive=1) never wakes a tenant. Non-billable tenants (staging 15m, dev 2h) sleep per a derived idle timeout (the Sandbox SDK 1.0 setInactivityTimeout() platform cap; there is no SANDBOX_SLEEP_AFTER binding; the value comes from the instance hostname via src/dev-mode.ts), and the ActivityScheduler DO alarm wakes/heals ahead of the next automation and runs an interval-gated R2 checkpoint after the wake. Billable production (platform === 'production' && environment === 'production') does not auto-sleep; the container stays awake and is stopped only by an explicit lerma freeze (POST /control → sandbox.destroy()), so a warmed gateway never incurs a cold-start/downtime window after an idle period. Runtime cutover is gated by SANDBOX_RUNTIME (legacy default | v1); SandboxV1 is still scaffold-only, so resolveSandboxRuntime() reports v1 as pending and the legacy class keeps serving (src/sandbox-runtime.ts). Tests: src/routes/public.test.ts, src/gateway/health-probes.test.ts, src/activity/alarm.test.ts, src/sandbox-runtime.test.ts, src/sandbox-do.test.ts, src/build-sandbox-options.test.ts; corpus test/business-rules/operational-modes.txt; lerma health_monitor_test.exs, health_poller_test.exs, tenant_provisioner_pipeline_test.exs. See docs/WORKER-DEVELOPMENT.md.

  • Single-owner gateway launch (start-openclaw.sh start): the production cold-start mode acquires the container-wide startup lock before config setup and holds fd 9 through the Gateway exec, so one owner covers setup and launch. The lock is inherited by the gateway process and released exactly when it exits, so only one owner can run — the OpenClaw 2026.9.8 state-DB single-owner migration otherwise caused concurrent launches (from different Worker isolates) to lose the migration, exit before binding the port, and leave the boot forever unhealthy (state.sqlite is undergoing offline maintenance). Losers poll the local /health (bounded) and exit 0 without a duplicate launch, or take over if the owner dies and releases the lock; the log-mirror tail -f closes fd 9 (9>&-) so it cannot hold the lock. The launch mode remains a standalone smoke/manual entry point with its dedicated /tmp/openclaw-gateway-launch.lock; full routes through the same lock in background mode. Regression: the serial test/e2e/ac_gateway_startup_concurrency.txt (phaseD_startup) asserts exactly one owner and the absence of both the migration-input-change error and the SQLite offline-maintenance error. See docs/WORKER-DEVELOPMENT.md.

  • Fixed the develop cold-boot stall introduced by #318 (startup.ok=false / readiness.ok=false for the whole E2E readiness budget; 68 processes, start-openclaw.sh setup exited 0, curl /health always exit 7, no openclaw gateway run ever present). Root cause: #318 had split the boot so the Worker launched the gateway after start-openclaw.sh setup exited (supervised exec) — this was the former behavior; current production collapses setup and launch into the atomic start-openclaw.sh start described above (startup lock acquired before setup, held through the Gateway exec). /api/health is bounded to a 5s snapshot, so the request returned long before the ~24s setup finished; when the response was sent, workerd cancelled the unregistered ensureGateway continuation, so the container-side setup completed but the Worker never resumed to launch the gateway. Fix: /api/health (and /api/warmup) now register the in-flight boot with c.executionCtx.waitUntil(ensureGateway(sandbox, env, { waitForReady: true })) so the setup → gateway-launch sequence survives past the response; waitForReady: true returns the shared start promise unwrapped and dedupes onto the one the snapshot already started. Also hardened the RPC-first health probe (getRpcHealthSnapshot, src/gateway/health-probes.ts) to run only once a gateway process is detected — sandbox.containerFetch auto-starts the container and blocks on the closed gateway port during a cold boot, piling port-waits on the Sandbox DO control channel. buildHealthSnapshot (src/routes/public.ts) passes its already-fetched findGatewayProcess result as { proc }. Bisected: production E2E boot green at ad9ad4a5 (#317), red at 9ae5f66c (#318). See apps/fouria/docs/WORKER-DEVELOPMENT.md §Admin RPC.

  • Startup resilience to Sandbox DO code updates: a Worker/DO redeploy (e.g. a Lerma redeploy of a tenant script) resets the DO↔container control session while the container keeps running, so the supervised waitForPort on the atomic start-openclaw.sh start process rejected with Network connection lost. and the cold start was aborted — killing a gateway that would have completed. The atomic start path has no separate setup-process wait (one supervised process spans config setup through the gateway’s whole life), so only the port wait is transport-resilient: ensureGateway waits with waitForPortResilient (src/gateway/sandbox-exec.ts), which reattaches to the process by id via getProcess(id) and resumes the wait within the shared STARTUP_TIMEOUT_MS deadline; only a non-transport error, an un-reattachable process, or an exhausted deadline fails. The generic waitForExitResilient helper remains in sandbox-exec.ts for the legacy/boot-smoke supervised waits. The loading page’s GET /api/startup/ws stream also treats a transport-drop snapshot as transient: it re-sends the last known state (or a synthetic starting view) and backs off exponentially (STARTUP_WS_POLL_INTERVAL_MS → STARTUP_WS_MAX_BACKOFF_MS, 30s) instead of re-probing and re-logging the same error every 5s.

  • Backups run only on running instances; health is observability-only. GET /api/health no longer schedules snapshots (passive or active) — the lerma HealthMonitor is a pure probe and MUST NOT alter the R2 catalog. The Dispatch Worker cron (workers/fouria-dispatch, 15 min prod / hourly staging) fans a backup control action (POST /control, X-FourIA-Control: backup) out to every non-frozen tenant; the tenant asserts sandbox.isRuntimeActive() (a non-waking bridge read) and skips a sleeping container rather than waking it (an idle instance has no workload or filesystem changes, and waking would restart billing), then runs the interval/lock-gated scheduleBackupIfNeeded. POST /debug/reprovision now checkpoints only a live runtime, bounded by REPROVISION_CHECKPOINT_TIMEOUT_MS, verifies restorability by HEADing the newest catalog entries’ meta.json, and fails closed (409) unless a restorable backup exists; {"force":true} overrides for an already-unrecoverable container. Root cause of the empty buckets: the old health-triggered path scheduled a snapshot regardless of readiness.ok, so a booting/stopped container could start sandbox.createBackup(), hang, and leave a stale backup-lock (observed in fouria-backup-tarjetero); dev instances the HealthMonitor does not monitor had no trigger at all. Tests: src/routes/public.test.ts, src/routes/debug.test.ts, src/index.test.ts, workers/fouria-dispatch/test/unit/control.test.ts; corpus test/business-rules/operational-modes.txt; docs docs/OPERATOR-GUIDE.md, apps/fouria/docs/WORKER-DEVELOPMENT.md, docs/CLOUD-ARCHITECTURE.md, workers/fouria-dispatch/README.md. E2E: test/e2e-backup/zz_reprovision_guard.txt + test/e2e-backup/zzz_backup_cold_restore.txt + test/e2e-backup/zzz_backup_semantics.txt (separate test/e2e-backup/ corpus, excluded from the default test/e2e run; run locally with bun run test:e2e:backup; registered in phaseE_restore, reprovision guard first), the dispatch fan-out unit test workers/fouria-dispatch/test/unit/cron-fanout.test.ts, deterministic E2E backup env in test/e2e/fixture/server/deploy, and POST /_control/:slug/backup on the dispatch worker; design in test/e2e/BACKUP-E2E-DESIGN.md. Dispatch note: vitest.config.ts now has unit (node) + integration (workerd) projects so the fan-out logic is testable without Miniflare.

  • PR E2E scope: the e2e job now sets E2E_BOOT_ONLY=1 for pull requests, so run-parallel.sh provisions the worker and only asserts the gateway reaches startup.ok + readiness.ok, then tears down without running any cctr group. develop and a manual workflow_dispatch (new full_tests input, default checked) run the full corpus. See apps/fouria/test/e2e-parallel/run-parallel.sh and docs/TESTING.md.

  • Paso4-exclusive instances + agent: lerma can now provision internal scope: "paso4" instances (nullable client_id, no billing plan, @paso4.io-only Access), and moltlazy ships an opt-in paso4-dev agent (PASO4_AGENTS, gated by MOLTLAZY_PASO4_AGENTS=true and named in MOLTLAZY_AGENTS) that picks up GitHub issues via the bundled github skill (gh CLI, installed in the image) authenticated by GITHUB_TOKEN. The Dispatch Worker resolves paso4 tenants from instances (no clients row) and rejects non-@paso4.io emails. See apps/lerma/README.md and docs/ENV-VARIABLES.md.

  • Setup serialization (start-openclaw.sh): start, setup, and full take an exclusive flock on /tmp/openclaw-setup.lock (~900s wait; OPENCLAW_SETUP_LOCK_TIMEOUT override) right after the gateway fast-path, then re-check the fast-path and exit 0 if a concurrent invocation brought the gateway up while they waited. In production, start acquires this lock before the setup body and holds it through the Gateway exec, so one owner serializes setup and launch. The Worker’s gatewayStartPromises guard is per-isolate, so an E2E cold-start burst lands several runs in different isolates at once; without the lock they ran the slow setup body concurrently, contended on OpenClaw’s native config/state locks, and stalled cold start for ~18 min (run 36692775633 — [SandboxRecovery] never fired because the admission-failure streak is also per-isolate). full releases fd 9 before backgrounding the gateway so the child does not inherit the lock; post-start is outside it. Degrades to the previous unserialized behaviour when flock is absent.

  • Native supervised gateway launch (src/gateway/process.ts): the Worker’s production cold start is one atomic supervised sandbox.exec of start-openclaw.sh start, which acquires the container-wide startup lock before the setup body (R2 restore → onboard → plugin installs → moltlazy patch) and holds it through the gateway exec — /bin/bash -lc 'touch /tmp/gateway-stdout.log; pgrep … || ( tail -f … & ); exec openclaw gateway run … >> /tmp/gateway-stdout.log 2>&1' — instead of the script backgrounding it with &. exec replaces the bash wrapper so the supervised process is the gateway (listProcesses/getProcess track it for the life of the container; kill() targets it directly); the guarded tail starts the container-stdout log mirror as a sibling (safe because the Worker never waitForExits on the gateway handle), and the redirect preserves the ops-readable log file. After the port is ready the Worker dispatches start-openclaw.sh post-start (dev automation + boot-log reset, best-effort) detached (void, not awaited) on every cold start — the gateway is already serving, so post-start must not extend the shared start promise (dev instances run openclaw automations list/create there, 30–60s, and awaiting it left every request logging Gateway start already in progress … waiting... while /health already returned 200); because it is dispatched unconditionally, a /api/health-triggered boot (waitForReady:false) still creates the dev automation even though its caller returned early. start-openclaw.sh gains setup/post-start modes; the default full mode keeps the legacy background launch for manual runs and test:gateway:boot. A shared STARTUP_TIMEOUT_MS deadline bounds setup + port wait; launchWithRecovery centralizes the stale/orphan/transport retry policy shared by both phases. The setup/post-start phases must stay child-free: the SDK’s waitForExit only settles once the supervised terminal exits, which never happens while the script leaves a live background child (a tail -f log mirror or a background cloudflared there stalled every cold start for the full STARTUP_TIMEOUT_MS, re-running setup until the ~11-minute mark). The mirror is started by the native launch; cloudflared is detached with setsid. Never call output()/runShell on the live gateway handle (it never exits): read diagnostics from the /tmp/gateway-stdout.log / /tmp/startup.log tails instead (readLogTail).

  • All three ClawHub plugins (cloudflare-ai-gateway provider, diagnostics-otel, cloudflare-unified-billing) are pre-installed into the container image at Docker build time (unpinned → latest ClawHub release; capability consent recorded in the image). This moves the per-boot network installs off the latency-critical startup path: start-openclaw.sh detects them via the extension dir + plugins list and only falls back to a ClawHub install when that state is missing (e.g. a warm R2 restore replaced it). The Dockerfile does not copy the Paso4 plugin source — it downloads the published ClawHub artifact — so the image stays source-free. The plugin’s source and tests now live in Paso4/openclaw-plugins (removed from this repo); see docs/OPENCLAW-PLUGINS.md. Runtime enablement is written by a single working config patch that also enables admin-http-rpc and disables diagnostics-otel unless its endpoint is set (the patch must not carry plugins.bundledDiscovery — removed in 2026.9.x, it fails validation and drops the whole patch — nor plugins.allow, which disables every bundled provider not listed). Memory search is disabled via the top-level memory.search.enabled=false (the old agents.defaults.memorySearch key is gone in 2026.9.x). Measured local cold boot: 35s vs 56s before

  • v0.3.x $include Configuration: immutable per-section $include files (session/tools/logging); gateway/agents inline; gateway token via env SecretRef

  • Gateway restart split: POST /api/admin/gateway/restart is the soft reload — sends SIGUSR2 to the live openclaw gateway run process (in-process, no connection drop, no port rebind) via softReloadGateway and falls back to signalRestoreNeeded only when no live gateway is found; POST /debug/restart-openclaw (DEBUG_ROUTES=true, ROOT) is the hard restart — killGateway + resetStartupCache + signalRestoreNeeded + start-openclaw.sh reprovision (in-place, no startGatewayDirect) so existing client tokens keep working. SIGUSR1 is not a restart signal (it opens Node’s inspector on 127.0.0.1:9229); the E2E n_gateway_soft_reload.txt asserts the inspector stays closed after a soft reload. The reload targets the server, not the openclaw gateway run launcher: buildSoftReloadScript signals the exact comm (pgrep -x 'openclaw-gatewa', Linux 15-char truncation, plus a defensive openclaw-gateway), because signalling the launcher kills it and orphans the server without restarting it (readiness never dips while the endpoint still reports reloaded: true). The E2E therefore requires both a stable /api/status.processId and an increased http server listening count, since processId alone survives a broken reload. Issue #463: OPENCLAW_NO_RESPAWN stays — removing it cannot enable process-level restarts inside a container (see the decision record in docs/plans/sandbox-memory-usage.md)

  • OPENCLAW_NO_RESPAWN=1 is set in the Dockerfile as explicit intent only: inside a container OpenClaw already resolves restart mode to in-process (isContainerEnvironment() → disabled / unmanaged), so removing the flag cannot enable process-level restarts or reclaim memory (#463); softReloadGateway only signals live processes and skips zombies

  • Sandbox SDK 1.0 preview (@cloudflare/sandbox@0.13.0-next.776.1 + cloudflare/sandbox:0.13.0-next.776.1 image): startProcess/execStream/getLogs() and SANDBOX_TRANSPORT are gone. All command execution goes through sandbox.exec(argv) (which resolves on launch, not completion); src/gateway/sandbox-exec.ts centralizes the shapes (startShell for a handle, runShell for buffered output, outputOf, collectLogs). listProcesses() now returns ProcessStatus[] (.state, argv .command) and a live handle is fetched via getProcess(id); findExistingGatewayProcess returns a GatewayProcess wrapper. waitForProcess delegates to waitForExit({timeout}) and kills on timeout. SandboxOptions.labels was removed upstream. Deploy cutover requires wrangler deploy --containers-rollout=immediate (stable/1.0 control protocols are incompatible)

  • Stale sandbox recovery (src/gateway/sandbox-recovery.ts): when the platform terminates the container behind a live Sandbox DO, every RPC fails with sandbox.exec error … HTTP error! status: 500 — isStaleContainerError classifies these and recoverStaleSandbox destroys the dead instance + resets startup/persistence caches so the next RPC auto-provisions a fresh container; wired into findExistingGatewayProcess, checkGatewayHealth and the ensureGateway startShell retry; cooldown-guarded (60s), never fires for deploy OperationInterruptedError or transient provisioning errors. It also matches the control-protocol mismatch ('utils.getRuntimeMetadata' is not a function, activateControlSession, RuntimeControlProtocolError) seen during a deploy cutover while the still-running container predates the new SDK’s control handshake — the SDK logs a sandbox.exec error … line but re-throws the bare TypeError, so the message patterns are matched directly and the stale instance is reprovisioned instead of failing until the platform rollout replaces it

  • Dev-only Fouria agents + client docs: moltlazy ships no production premade agents (vanilla researcher/coder removed) and injects Fouria Builder (fouria-builder) + Fouria Q&A agent (fouria-qa) only when the instance is a dev environment (OPENCLAW_DEV_MODE=true on the container, derived by the Worker from the instance’s -dev hostname — see src/dev-mode.ts); per-tenant client documentation lives in R2 under customers/<slug>/docs/ and is materialized by the Worker into /home/openclaw/clawd/client-docs/ before gateway start (src/services/fouria-docs/, materializeClientDocsIfDev), with a dev-only admin API at /api/admin/fouria-docs (404 outside dev); the Dockerfile installs the cctr binary, platform docs are fetched from the docs site (https://fouria.io, fallback https://fouria-docs.pages.dev, starting at /llms.txt), and start-openclaw.sh keeps security.installPolicy allow in dev so the Builder can self-install plugins

  • Orphaned-instance recovery (src/gateway/sandbox-recovery.ts): a container destroyed out-of-band (Cloudflare Containers dashboard “Destroy”, failed force-stop) leaves the DO alive pointing at a dead placement and surfaces the SDK’s retryable admission errors (no container instance available, max container instances exceeded) instead of the 500 signature. isContainerUnavailableError + trackProvisioningFailure escalate to a recovery only once the streak reaches ORPHANED_INSTANCE_MIN_FAILURES and spans ORPHANED_INSTANCE_GRACE_MS (120s, > the SDK’s ≈110s provisioning budget, so slow-but-healthy cold starts are never cancelled); maybeRecoverSandbox unifies both failure classes and clears the streak whenever a sandbox RPC succeeds. Operator lever: POST /debug/reprovision (DEBUG_ROUTES, ROOT) destroys the instance + clears caches + resets the streak without touching the gateway, so it works when the container is entirely gone

  • Activity-driven wake (src/activity/): automations run inside the Gateway, so it must be running for schedules to fire. A per-tenant ActivityScheduler Durable Object (binding ACTIVITY, SQLite-backed, separate from the SDK Sandbox DO whose alarm drives sleepAfter) mirrors the tenant’s schedule (openclaw automations list --json, refreshed on warm /api/health when readiness.ok, throttled to 5 min) and arms one alarm CRON_WAKE_AHEAD_MINUTES (default 10) before the next enabled job. On fire it wakes + heals via ensureGateway (recovering an orphaned instance) then re-arms; no enabled jobs → alarm cleared → container sleeps. Healing/wakeup is independent of user traffic, gated on job activity, and free when idle (src/activity/alarm.ts state machine is unit-tested; the DO is a thin adapter). Requires the ACTIVITY binding in wrangler.jsonc + lerma (tenant_provisioner.ex resource_bindings, dispatch_namespace.ex @do_sqlite_classes)

  • Container image build profiles: the Dockerfile takes a BUILD_PROFILE build arg (default production → slim, only xz-utils; dev → adds the optional pandoc + weasyprint PDF/document stack, ~760 MB, used by the dev-only Fouria Builder fouria-leads skill). The profile is selected per wrangler environment via image_vars (equivalent to docker build --build-arg): env.staging (dev/test) sets dev; env.production and the default/local config keep the slim default. The release CD builds the slim default, and the E2E basic (PR) and production (develop) profiles both provision the slim production image on the same standard-2 instance (differ by env only)

  • Sandbox → leads R2 bridge (src/sandbox-leads-bridge.ts, leads.r2.internal): the fouria-leads skill now reaches the global paso4-leads bucket through the Sandbox outboundByHost bridge (plain HTTP resolved in the Workers runtime with the LEADS_BUCKET binding — no R2 creds in the container, no public route) instead of the public wss://<worker>/api/leads/ws proxy. The proxy is intercepted by Cloudflare Access on tenant hostnames (a per-tenant Access app shadows the *.fouria.io/<path> apps — confirmed via the login redirect’s kid) and is retained only for the host-side E2E fixture. Related: lerma’s HealthMonitor now probes with redirect: false, so a shadowed /api/health 302 (Access login page) is surfaced instead of being followed and misreported as healthy

  • Client docs hardening + operations (dev-only): tenant-isolated the leads.r2.internal bridge (src/sandbox-leads-bridge.ts resolves the caller slug via the shared src/sandbox-tenant.ts resolver and treats every agent path as relative to <slug>/, so a sandboxed agent can only reach its own proposal; the shared build-pdf.sh stays read-only). Added the Admin Client Docs page (/_admin/docs, ADMIN, dev-only) + the extended src/routes/api/fouria-docs.ts managing docs (customers/<slug>/docs/) and leads directly from the Worker (no CLI) with markdown rendering (marked + DOMPurify), native-browser PDF opening via /raw, and multipart uploads; HTML/SVG raw downloads are forced to attachment + sandbox CSP. Added Worker-side git-like versioning (DocsGitStore: content-addressed blobs/commits/refs, GET /commits, POST /rollback/:sha as a non-destructive revert) and backups (DocsBackupStore: POST /backup, GET /backups, POST /backups/:id/restore, retention 10). See docs/WORKER-DEVELOPMENT.md §“Client Docs (dev-only admin surface)”

  • ECONNRESET from the sandbox R2 bridges fixed: the tenant’s LEADS_BUCKET was provisioned as a plain-text var (the bucket name) instead of an r2_bucket binding, so env.LEADS_BUCKET was a string, bucket.list() threw inside the outboundByHost handler, and the escaping exception surfaced to the container as an opaque ECONNRESET. Two fixes: (1) the bridges (leads/docs/releases) now validate the binding with isR2Bucket (src/r2-binding.ts) and wrap their bodies in try/catch, returning a structured JSON 503/500 instead of resetting the socket; (2) lerma (instances.ex instance_bindings/2, config LEADS_R2_BUCKET default paso4-leads) now provisions LEADS_BUCKET as an r2_bucket binding on every tenant worker (redeploy existing tenants to replace the stray var)

  • Admin RPC-first read path (src/gateway/admin-rpc.ts): the hot dashboard reads/writes now go through OpenClaw’s bundled admin-http-rpc plugin (POST /api/v1/admin/rpc) over sandbox.containerFetch, reusing the typed moltlazy/sdk HTTP RpcClient (which gained an injectable fetcher). This removes the ~10–15s per-call CLI spawn/WS-reconnect on GET /api/admin/devices, POST .../approve, GET /api/admin/models, and GET /api/admin/channels/probe (measured locally: ~1.3–2.5s CLI → ~30–40ms RPC), each of which keeps its CLI path as a fallback (createAdminRpcClient returns null / throws → existing parser runs). start-openclaw.sh enables the plugin with a dedicated plugins.entries["admin-http-rpc"].enabled=true patch — NOT plugins.allow, which disables every bundled provider not listed (and the nearby batched plugin patch is rejected upstream for the removed plugins.bundledDiscovery key). src/index.ts shadows /api/v1/admin/rpc with a 404 before the public catch-all proxy so the operator surface stays container-local. The home-grown moltlazy/sdk WebSocket client is intentionally not used for admin RPC

  • Gateway WebSocket RPC (src/gateway/gateway-rpc.ts): methods outside the admin-http-rpc allowlist (notably audit.activity.list) are reached with OpenClaw’s official @openclaw/gateway-client/browser reference client + @openclaw/gateway-protocol types, bridged over sandbox.wsConnect and authenticated with the shared gateway token as an operator. The wire-v4 handshake (connect.challenge → connect → hello-ok) is owned by the official client; the connect frame’s client.version comes from __OPENCLAW_VERSION__, injected by vite.config.ts from catalog.openclaw. RPC-first with CLI fallback: GET /api/admin/audit-logs (audit.activity.list) and the agent board (agents.create/agents.delete/agents.update, model via config.patch). GET /api/admin/integrations is deliberately WebSocket-free (the gateway drops these sockets): channels/agents over the admin HTTP RPC, plugin enabled-state from config.get, toggles/config via config.patch, secrets reload via the CLI. theme, agent bindings, secrets.apply, and channels list --all have no RPC method and stay on the CLI. The two packages are pinned in catalog.@openclaw/gateway-client / catalog.@openclaw/gateway-protocol and must track catalog.openclaw

  • Realtime device-pairing notifications (src/gateway/gateway-rpc.ts openGatewayEventStream, src/routes/api/devices.ts GET /ws): the dashboard NotificationBell now subscribes to GET /api/admin/devices/ws, which pushes an initial { pending, paired } snapshot then relays Gateway device.pair.* events (reconnecting via the official gateway client over sandbox.wsConnect). Admins approve/reject pending devices inline from the bell via POST /api/admin/devices/:requestId/approve / .../reject (RPC-first; the reject route was added). Also fixed secrets apply invocations (integrations/dreaming): current OpenClaw removed --yes (only --from, --dry-run, --allow-exec, --json)

  • CLI→RPC sweep (finishing the RPC-first migration): config set/unset use config.patch; dreaming config writes use config.patch (shared patchConfigViaRpc in src/routes/api/shared.ts); secrets.reload uses the WS secrets.reload; and resolveAgentFlag (used by models/knowledge) resolves the roster via agents.list instead of openclaw agents list. CLI fallbacks are retained everywhere. Remaining CLI-only paths have no Gateway RPC method: secrets apply/audit, openclaw wiki *, agent bind/unbind/bindings, and openclaw --version