File size: 17,005 Bytes
af1bee9
 
152e0c1
 
af1bee9
152e0c1
af1bee9
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
af1bee9
 
152e0c1
af1bee9
 
 
 
 
 
152e0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1bee9
 
 
152e0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1bee9
152e0c1
af1bee9
 
 
 
 
152e0c1
af1bee9
 
 
152e0c1
 
 
 
 
 
 
 
 
 
 
 
 
5ce1088
 
152e0c1
 
5ce1088
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
 
 
 
af1bee9
 
 
 
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
af1bee9
 
 
 
 
 
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# Deployment

One image (`Dockerfile`: a web build stage, then a Python 3.13 runtime with Node 22 and Chromium, running as a
non-root user under tini), two shapes:

| Shape | What it runs | Guide |
|---|---|---|
| **Hugging Face Space** (Docker) + remote browser runner + storage bucket | The running system: Fusion cycles, Agent Studio, the practice pod. Data is saved as an encrypted snapshot to OCI Object Storage or Supabase Storage. | this page, [REMOTE_RUNNER.md](REMOTE_RUNNER.md) |
| Docker Compose with Caddy (HTTPS) and Temporal, data on volumes | The practice pod only. **Fusion pods do not run in this shape today**: the Temporal execute activity (`coworker/workflows/activities.py`) starts the local practice pod and has no remote runner, per-area test users or pre-flight. | [deploy/DEPLOY.md](../deploy/DEPLOY.md) |

## Environments

Dev, staging and production differ only in settings, never in code:

| Setting | Development | Staging / production |
|---|---|---|
| `FPT_COOKIE_SECURE` | `auto` | `always` |
| `FPT_TRUST_PROXY` | `0` | `1` behind a proxy |
| `FPT_CORS_ORIGINS` | the Vite dev server | `[]` |
| `FPT_API_DOCS` | `1` | `0` |
| `FPT_REGISTRATION` / `FPT_REGISTER_ROLE` | as needed | `0`, or `viewer` |
| `OCI_STATE_PAR_URL` or `SUPABASE_BUCKET` | own bucket | one bucket per environment, never shared |
| `FPT_REMOTE_RUNNER_URL` | none (local browser) | one runner per environment |
| `FPT_ENVIRONMENT` | `development` | `staging` / `production` (labels error reports) |

Use one Space per environment. Promote by deploying the same commit.

## Hugging Face Space

The repository root is the Space: `README.md` front matter sets `sdk: docker` and `app_port: 8800`, and the
`Dockerfile` carries the Space settings (viewer sign-ups, trusted proxy, no CORS, docs off, public URL).

1. Space **variables**:
   - `FRONTIER_BASE_URL`, `FRONTIER_MODEL`, `FPT_ADMIN_EMAILS`, `SUPABASE_URL` (sign-in);
   - `FPT_FUSION_BASE_URL`, `FPT_FUSION_NAME`, `FPT_FUSION_MODULES`, `FPT_FUSION_RELEASE`;
   - `FPT_FUSION_AREA_USERS` (JSON, the test user per area, for example `{"PO": "prc_impl"}`; same password) and
     `FPT_FUSION_WORKERS` (browsers at once on the runner, 1 to 4; default 3);

   - `FPT_REMOTE_RUNNER_URL` (`https://<runner>`), `FPT_BROWSER_RUNS=1`, `FPT_BROWSER_SLOWMO_MS`.

2. Space **secrets**:

   - `FPT_BOOTSTRAP_ADMIN_USER`, `FPT_BOOTSTRAP_ADMIN_PASSWORD`;

   - `FPT_STATE_KEY`, the snapshot key (required with OCI, which has no service key to derive one from);

   - `OCI_STATE_PAR_URL`, the bucket's pre-authenticated request URL (or Supabase Storage, below);

   - `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_KEY` (sign-in, and the Supabase store);

   - `FPT_SECRET_FRONTIER_API_KEY`, `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD`,

     `FPT_SECRET_REMOTE_RUNNER_TOKEN`;

   - optionally `FPT_SECRET_METRICS_TOKEN`, `SENTRY_DSN`.


   Variables are public on a public Space; anything secret must be a secret.
3. Deploy (next section). The Space builds the image and starts it.
4. Check: `https://<space>.hf.space/api/ready` answers `"ready": true`; sign in; Test environments > Test connection
   on the Fusion pod shows all three checks.

### Every deploy or restart

A Space deploy or restart stops the container. A test run that is running is interrupted, and anything changed since
the last save is lost unless it is saved first.

1. **Check that nothing is running.** In the app, Home and Test runs show no run in progress and no pod card shows
   its screens being read. Or: `GET /api/runs?status=running` and `GET /api/runs?status=queued` return no items, and
   the runner's `GET https://<runner>/healthz` shows `"busy": false`. Wait, or cancel, before going on.
2. **Save the state** and wait for the answer: `POST /api/storage/save` (administrator). It answers
   `{"saved", "last_saved_at", "bytes"}`; 502 when the save failed, 409 when this server does not save its state.
3. **Deploy**: upload the repository contents, or push to the Space's git remote.
4. **Update the runner** on the same commit: `deploy/runner/sync.sh <ssh target> <ssh key> https://<runner>`
   ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)). Pre-flight stops a Fusion run when the runner has no scenario files.
5. **Check**: `/api/ready`; Settings > Storage and backups shows a save after the start; the runner's `/healthz` shows
   the deployed commit as `version` and `"cases": true`.

**Rollback**: every upload is a commit in the Space repository. Re-upload the previous revision (or revert it in the
Space's Files tab), then run `sync.sh` on that commit. The data is untouched because it lives in the bucket.

## Database migrations

SQL files in `coworker/platform/migrations/` are applied in order by `python -m coworker setup`, which the container
runs at every start. They are forward-only and additive (new tables and columns). To roll back a release that added a
migration: restore the snapshot taken before the upgrade (RUNBOOK "Restore"), then deploy the previous image.

## Backups

**Space (no disk).** `platform/statesync.py` saves an encrypted archive of `FPT_HOME` (databases, vault, runs,
evidence, tickets, screens, library) as `state/latest.bin` in the bucket, with `state/meta.json` beside it.

| Store | Settings |
|---|---|
| OCI Object Storage | `OCI_STATE_PAR_URL`: a pre-authenticated request on one private bucket, access "read and write objects", listing denied (`https://objectstorage.<region>.oraclecloud.com/p/<token>/n/<namespace>/b/<bucket>/o/`). Used when set. `FPT_STATE_KEY` is required. |
| Supabase Storage | `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `SUPABASE_BUCKET`. The key is `FPT_STATE_KEY`, or is derived from the service key when that is not set. |

When it saves:

- every `FPT_STATE_SYNC_INTERVAL` seconds (default 60) when the databases changed; at least every 300 s on OCI (the
  Always Free tier allows 50,000 requests a month), at least every 10 s on Supabase;
- at once when a screen read finishes, a run waits for a person, a run ends, or a run is cancelled;
- on shutdown (a forced save, after a running run has stopped at its next step, waiting at most
  `FPT_SHUTDOWN_RUN_WAIT_S`, default 20 s);
- on `POST /api/storage/save`, and with `python -m coworker state push`.

A save costs four requests: GET `state/meta.json` (the generation check), PUT `state/history/<time>.bin`, PUT
`state/latest.bin`, PUT `state/meta.json`. The first save of each process also copies what the bucket held to
`state/previous.bin`; once an hour history copies beyond `FPT_STATE_HISTORY` (default 5) are deleted (by the names in
`meta.json`, since the OCI address may not list). Each start writes `meta.json` once to take the next generation, so an
older container still running is refused at its next save instead of overwriting the newer state.

An archive above 45 MB leaves out the evidence, then the folders of finished runs: `meta.json` and `/api/storage`
(`left_out_detail`, `left_out_note`) say exactly what, once per change it is audited (`state.left_out`) and notified,
and after a restart those files answer 410. If the start-up restore fails, or another instance has taken over
(`paused_reason` `restore_failed` or `fenced`), saving pauses so the good copy is not overwritten. Status: Settings >
Storage and backups, `/api/ready` (`saved_state`, signed in), the metric `trio_backup_ok`,
`python -m coworker state status`.

**Compose.** `deploy/backup.sh /secure/backups` on a schedule. The archive is not encrypted and contains the secrets
vault: encrypt it and restrict who can read it.

Try a restore once per quarter (RUNBOOK "Restore").

## Reverse proxy and TLS

The app listens on plain http (port 8800). Put it behind a proxy that terminates TLS: Caddy in Compose
(`deploy/Caddyfile`), or the platform's proxy (Hugging Face). Set `FPT_TRUST_PROXY=1` only when the app is reachable
through that proxy alone, and `FPT_COOKIE_SECURE=always`.

Production run command (what the container runs): `python -m coworker api --host 0.0.0.0 --port 8800`, after
`python -m coworker state restore --soft` and `python -m coworker setup` (`deploy/entrypoint.sh`).

## Resources

| Workload | Memory | CPU |
|---|---|---|
| Quick simulations only | 512 MB (CI rehearses this limit) | 0.5 |
| Browser runs on the server itself (practice pod) | 2 GB minimum, 4 GB comfortable; `shm_size: 1gb` | 2 |
| Remote runner for Fusion pods, 3 to 4 browsers ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)) | 16 GB | 4 vCPU |

## Notifications (webhook)

Moments that need a person become notifications: a run waits for approval or for a decision, a run finished (with
Ready / Not ready / Held per area), failed or was stopped, a defect was raised. They are listed in the app
(`GET /api/notifications`) and, when `FPT_NOTIFY_WEBHOOK_URL` is set, POSTed to that URL (for example an n8n workflow
that forwards them to Telegram, Slack or e-mail).

- **Settings**: `FPT_NOTIFY_WEBHOOK_URL` (https; loopback http is allowed for local testing) and the secret
  `FPT_SECRET_NOTIFY_SECRET` (or `FPT_NOTIFY_SECRET`). No separate egress allowlist entry is needed: delivery goes only
  to the configured webhook's own host, through the egress gate, and is audited (`egress.notify`, `notify.delivered`,
  `notify.failed`). The emergency stop also stops deliveries.
- **What is sent** (JSON): `id`, `kind` (`run.waiting_approval`, `run.waiting_decision`, `run.finished`, `run.failed`,
  `run.stopped`, `defect.created`, `test`), `title`, `body`, `coworker`, `run_id`, `link` (absolute when `FPT_PUBLIC_URL`
  is set), `created_at`, `app`. Never secrets, credentials, test data values or screenshots; error sentences are redacted.
- **Headers**: `X-Patchwise-Event` (the kind), `X-Patchwise-Delivery` (the id; repeat deliveries carry the same id, so
  a receiver can drop duplicates) and, with a secret, `X-Patchwise-Signature: sha256=<hex HMAC-SHA256 of the raw body>`.
- **Retries**: any non-2xx answer or network error is retried after 30 s, 2 min, 10 min, then hourly; after 8
  attempts it is given up (it stays in the app's list). Administrators see the state under
  `GET /api/notifications/settings` and can send `POST /api/notifications/test`.

Verifying the signature (n8n Code node, Node.js):

```js

const crypto = require('crypto');

const raw = JSON.stringify($json.body);   // or the raw body if the webhook node keeps it

const expected = 'sha256=' + crypto.createHmac('sha256', $env.PATCHWISE_NOTIFY_SECRET).update(raw).digest('hex');

if (expected !== $json.headers['x-patchwise-signature']) throw new Error('bad signature');

```

The body is sent compact (`separators=(",", ":")`); verify against the exact bytes received when the receiver keeps
them.

## Notifications (Telegram)

Astra can send the same notifications to a Telegram chat itself, with no relay in between. Each message names the
coworker in bold, then the title and one sentence, with an **Open in Astra** button (only when `FPT_PUBLIC_URL` is
set, because Telegram accepts https links only).

1. In Telegram, open **@BotFather**, send `/newbot`, choose a name and a username. BotFather answers with the bot token.
2. Store the token as a **secret** on the Space (Settings > Variables and secrets): `FPT_TELEGRAM_BOT_TOKEN`. Never in a
   file, a commit or a chat message. (The vault name `TELEGRAM_BOT_TOKEN` and `FPT_SECRET_TELEGRAM_BOT_TOKEN` also work.)
   Restart the Space.
3. In Telegram, open your new bot and send `/start` (for a group: add the bot to the group and send a message there).
4. In Astra, open **Settings > Notifications > Find my chat**, pick the chat, and Astra sends a welcome message.
5. Press **Send a test message**.

- **Chat**: chosen in Settings (stored in the app's settings), or fixed with `FPT_TELEGRAM_CHAT_ID`, which wins.
- **Delivery**: its own state per event (`tg_*` columns), so a failing chat never holds back the webhook. Retries after
  30 s, 2 min, 10 min, then hourly, up to 8 attempts; a chat that refuses (HTTP 400 or 403: not found, bot blocked) is
  given up after 2 attempts, and Settings shows the reason.
- **No backlog**: a newly connected chat receives events from the hour before it was connected onwards, never more.
- **API** (administrators): `POST /api/notifications/telegram/discover` (the chats that wrote to the bot in the last
  24 hours), `POST /api/notifications/telegram/chat` `{chat_id, title?}`, `DELETE /api/notifications/telegram/chat`.
  `GET /api/notifications/settings` reports `telegram.token_set`, the chat and the last delivery; never the token.

## Monitoring

- **Health**: `/api/health` (public, small) and `/api/ready` (503 when not ready). Hugging Face ignores Docker
  `HEALTHCHECK`: point an external uptime monitor at `/api/ready`.
- **Metrics**: `/api/metrics` in Prometheus text format (runs by status, queue depth, users, emergency stop, backup).
  Scrape with `Authorization: Bearer <FPT_SECRET_METRICS_TOKEN>`.
- **Errors**: set `SENTRY_DSN` and install `sentry-sdk` in the image to send errors to Sentry or any compatible
  service; no request bodies or personal data are sent.
- **Logs**: JSON lines on stderr (ship them with the platform's log drain) and `$FPT_HOME/logs/api.jsonl`
  (rotated, 10 MB x 5). Every line carries a `request_id`, also returned to the browser for support.

## Notifications (Slack, Microsoft Teams, Google Chat, Discord)

Nothing to set on the server: an administrator opens **Integrations** in the sidebar, chooses the service, pastes its
incoming-webhook URL and presses **Send a test message**. The URL is kept in the vault (`/data/secrets/vault.json` on the
Space, saved with the state backup) and can be replaced or removed there at any time. The Space must be able to reach the
service's host (hooks.slack.com, *.webhook.office.com or *.logic.azure.com, chat.googleapis.com, discord.com).

## Two-way bot (Telegram)

With the bot token set, the app also reads what people send to the bot (long polling, so no public address is needed) and
answers as the Ask page does. Full design in [CHANNELS.md](CHANNELS.md).

**What each person does once to link their own chat:**
1. In Astra, open **Account > Telegram** and press **Get a link code**.
2. In Telegram, send the bot `/link CODE` within 10 minutes.

From then on they get the notifications about runs they may read, and can use `/status`, `/run Procure-to-Pay quick`, or plain questions. Starting a run or approving scenarios always needs a button press; sign-off and failure decisions stay in the app.

**Settings:**
- `FPT_TELEGRAM_POLLING=0` turns reading off (send only).
- **If the host can't reach api.telegram.org,** set `FPT_TELEGRAM_API_BASE` to an https relay that forwards `/bot<token>/<method>` unchanged (for example a small Cloudflare Worker). Some hosting platforms, Hugging Face Spaces among them, have been reported to block the Telegram API: messages are then queued and never sent.
- **Every failed attempt is printed** in the server log as `telegram delivery of … failed: <reason>`.
- **At start-up the log states the channels:** `notifications: webhook off; telegram on (token set, chat set, api api.telegram.org)`.

## MCP connector

Nothing to switch on: the endpoint is `https://<host>/mcp` and each person makes their own token in **Account >

Assistants**. Client set-up is in [MCP.md](MCP.md). Behind a reverse proxy, pass `/mcp` through like `/api` (no
buffering needed: answers are plain JSON) and keep `FPT_PUBLIC_URL` set, because links in tool answers and the allowed
browser origin come from it. The `api_tokens` and `mcp_proposals` tables are created by migration 015.

## A2A agent

Nothing to switch on. The agent card is at `https://<host>/.well-known/agent-card.json` and the endpoint at
`https://<host>/a2a`; callers use the same personal access tokens as MCP. Migration 017 creates `a2a_tasks`. Keep
`FPT_PUBLIC_URL` set (the card's `url` and every link come from it). Behind a reverse proxy, pass `/a2a` and `/.well-known/`
through, allow 256 KB bodies, and turn response buffering off for `/a2a` (`message/stream` and `tasks/resubscribe` answer
with server-sent events for up to 10 minutes). Details: [A2A.md](A2A.md).

## Custom test cases

Nothing to switch on. Migration 016 creates the `custom_case_batches` and `custom_cases` tables; batches are removed 14
days after they are made (approved scenarios stay in the script library). Excel upload needs `python-multipart`, now in
`coworker/requirements.txt`: rebuild the image. Behind a reverse proxy, allow request bodies of at least 2.1 MB on
`/api/custom-cases/parse`. Promotion into the library follows `FPT_CASE_WRITEBACK` like approved AI scenarios: with it
off, approved custom scenarios stay in staging and can't be started as a run. Details: [CUSTOM_CASES.md](CUSTOM_CASES.md).