Skip to content
32 changes: 32 additions & 0 deletions .janus/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Janus deploy pipeline — runs on the Agrippa host itself.
#
# Deliberately not .janus/ci.yml (the default path): the GitCode webhook selects
# this file with ?pipeline_path=.janus/deploy.yml, which leaves ci.yml free if
# Janus ever runs tests for this repo too, rather than conflating deploy and CI.
#
# Trigger is the `deploy` branch, not main: main takes doc-only commits, and
# this is the only environment — going live should be a deliberate
# fast-forward, and rolling back is moving the branch.
#
# Janus checks the repo out into its own workspace as the `janus` user; that
# checkout is only the trigger vehicle. The deploy acts on /opt/agrippa, which
# is root-owned and holds the untracked .env. See docs/design/08-deployment.md
# for why the tree is not janus-writable.
name: deploy

on:
push:
branches: [deploy]

# Serialize deploys. infra/deploy.sh also takes a flock, which covers manual
# runs that never reach Janus; this stops the queue forming inside the script.
concurrency:
group: deploy-${{ branch }}

jobs:
deploy:
steps:
# Passing the exact SHA makes the deploy deterministic: it applies the
# commit that triggered this run, not whatever the branch tip has moved
# to since. sudo is a single NOPASSWD rule for this one script.
- run: sudo /opt/agrippa/infra/deploy.sh ${{ sha }}
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ All notable changes to Agrippa are documented here. The format follows

- **SSE keepalive frames** — `GET /runs/:id/events` emitted nothing between events, so a run parked on a long agent turn or an approval looked like a dead connection to every intermediary: nginx cuts at `proxy_read_timeout` (60s default) and Cloudflare at ~100s. The stream now sends a comment frame every 15s (`AGRIPPA_SSE_KEEPALIVE_MS` to tune). Comment frames carry no `id:`, so they cannot disturb the `Last-Event-ID` cursor a client reconnects with. Previously the failure was survivable but noisy — EventSource reconnects and replays — now it doesn't happen. The knob is forwarded through compose and listed in both configuration tables, so it is actually settable.

- **`infra/deploy.sh` — a real deploy path for the Compose topology, with rollback.** The VM had `infra/vm/deploy.sh`; Docker had nothing, so updating meant remembering that `git pull && docker compose up -d` is *wrong here* — the SPA and API are baked into the api image, so it restarts the old code and reports success. The script always builds, tags images with the deployed commit (via the `AGRIPPA_VERSION` plumbing compose already had), waits on `/healthz`, and **rolls back to the previous tag** when the new one doesn't come up. Previously rollback was impossible at all: `build` overwrote `:latest` and left the prior image dangling and unnameable. A `flock` serializes concurrent deploys; only the current and previous tags are kept, since each pair is ~4 GB.

Pre-deploy dumps live in a `0700` directory with mode `0600`: they are a full copy of production, and the host also runs an unprivileged CI user that the deploy design treats as untrusted, so an inherited umask would have exposed them. The restore procedure is printed on **every** failure path — including the one where the rolled-back stack is also unhealthy, which is exactly when an irreversible migration is the cause — and it stops the app first, since `pg_restore --clean` cannot drop objects the api and worker still hold connections to.
Images are tagged with the full commit SHA rather than a 7-char prefix, so a prefix collision cannot overwrite a tag that is someone's rollback target, and a stale `:latest` is pruned once it is no longer that target.
It deploys **only commits reachable from `deploy`**: the script runs as root via a NOPASSWD sudoers rule, so an unconstrained argument would let its caller deploy any branch — including a compose file that mounts the host — and root-owning the tree would buy nothing. Verification covers both services (the api's compose healthcheck plus a fresh `executor_registrations` heartbeat), because a worker-only regression would otherwise deploy "successfully" and prune the image that worked. Rollback restores the previous commit's code *and config*, since re-upping old images against the failed commit's compose file is a mismatched state. It does **not** revert the database — the api migrates on boot before health is exposed and some migrations are irreversible — so a `pg_dump` is taken before every deploy and the exact restore command is printed on rollback rather than the schema being silently left behind.

- **`.janus/deploy.yml` — push to `deploy`, and the server updates itself.** A [Janus](https://github.com/hutusi/janus) pipeline running on the host calls `deploy.sh` with the exact triggering SHA, so a deploy applies the commit that triggered it rather than whatever the branch tip drifted to. Trigger is the `deploy` branch rather than `main`, because `main` takes doc-only commits and this is the only environment — going live is a deliberate fast-forward, and rolling back is moving the branch. Janus reaches root through a single `NOPASSWD` sudoers entry for that one script, and the deploy tree stays root-owned: a janus-writable tree plus `sudo docker compose up` would let janus mount any host path as root, which would make the narrow rule worthless.

- **`.dockerignore`** — both images `COPY apps ./apps` / `COPY packages ./packages`, so every workspace `node_modules` in a developer's tree entered the build context and host-native binaries were layered into a Linux image. CI never caught it because it builds from a fresh checkout. Patterns are matched from the context root, so secrets and noise are listed in their `**/` form too: an unqualified `.env` would not have covered a git-ignored `apps/api/.env.local`.

- **Template format v3 — flat authoring format (ADR-0016)** — templates can now be authored in a flat, GitHub-Actions-style `version: 3` format with no `apiVersion`/`kind`/`metadata`/`spec` wrappers: top-level `slug`/`scenario`/`name`, `faber`-or-`slots` agent declaration, flat `skills`/`mcpServers`/`subagents`, `models` (no `.roles` wrapper), top-level `limits`, and `outputs` (no `.artifacts` wrapper). v3 is source-only — `normalizeV3ToCompiled` flattens it into the unchanged v2 IR (`CompiledTemplate`), so the engine, API, and DB are untouched; `compileTemplate` routes on `version: 3` before the existing `apiVersion` branches. Six builtins converted (`pm/status-report`, `pm/plan-breakdown`, `swdev/requirement-delivery`, `swdev/requirements-dev`, `test/test-plan`, `test/regression-verify`); `swdev/bug-localize-fix.yaml` is intentionally kept on v1 as the v1→v2 upgrade-path fixture. v1/v2 sources keep working; the bilingual template-authoring manual and `docs/design/02` now teach v3 first.
Expand Down
15 changes: 14 additions & 1 deletion docs/design/08-deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,20 @@ Secrets policy: the master key and the deployment's **fallback** provider API ke

- **First-run onboarding**: self-registration is closed (invite-only — see [05](05-api-and-auth.md#authentication)). The api/worker do **not** create users on boot. An operator runs `apps/api/src/cli/bootstrap-admin.ts` once (reads `AGRIPPA_BOOTSTRAP_EMAIL`/`PASSWORD` from the env file, creates the first `org_admin`, idempotent on email) — then signs in and invites members from the UI. Runbook in [Operations → First-run](../manual/en/06-operations.md#first-run-create-the-admin).
- **Backup**: Postgres volume (pg_dump schedule is the operator's choice) + `ARTIFACT_STORAGE_ROOT` volume + the `AGRIPPA_SECRET_KEY`. Redis is disposable.
- **Upgrade**: pull images → `docker compose up -d` → api migrates on boot. Workers drain gracefully (in-flight runs resume on new workers via step-granular resume — see [04](04-execution-runtime.md)); the compose `stop_grace_period` must exceed the drain, so it is set to 60s rather than the 10s default.
- **Upgrade (Compose)**: `infra/deploy.sh [<commit>]` — fetches from GitCode, builds images tagged
with the deployed commit, `up -d`, waits on `/healthz`, and **rolls back to the previous tag** if
that fails. It always builds: the SPA and API are baked into the api image, so a bare
`git pull && docker compose up -d` restarts the *old* code and reports success. A `flock` keeps
concurrent deploys from racing on the image tags. Automated by Janus on push to the `deploy`
branch (`.janus/deploy.yml`); the same script is the supported manual path.
It refuses any commit **not reachable from `deploy`** — the sudoers rule that lets Janus call it
as root would otherwise make every branch deployable, and root-owning the tree would buy nothing.
Verification covers **both** services: the api's compose healthcheck, and a fresh
`executor_registrations` heartbeat proving the worker registered its executors. Rollback restores
the previous commit's *code and config*, not the database — the api migrates on boot before it is
healthy and some migrations are irreversible, so Postgres is dumped beforehand and the restore
command is printed if a rollback happens.
- **Upgrade (images)**: pull images → `docker compose up -d` → api migrates on boot. Workers drain gracefully (in-flight runs resume on new workers via step-granular resume — see [04](04-execution-runtime.md)); the compose `stop_grace_period` must exceed the drain, so it is set to 60s rather than the 10s default.
- **TLS / ingress**: out of scope; operators front the stack with their own reverse proxy. SSE requires the proxy to disable response buffering for `/api/v1/runs/*/events`, or live progress arrives in bursts. The stream emits a comment frame every 15s (`AGRIPPA_SSE_KEEPALIVE_MS`) so an idle run — a long agent turn, or one parked on an approval — never looks like a dead connection; a generous `proxy_read_timeout` remains worth setting as defence in depth for intermediaries whose idle limits you do not control.
- **Health**: `GET /healthz` (api: DB ping). A per-worker heartbeat row for the admin UI is deferred past M1. Executor availability is observable via `executor_registrations` (workers upsert at boot and on the 60s sweeper tick).
- **Sandboxing under Docker — bubblewrap does not work, and that is the accepted posture.** The worker image installs bubblewrap, but under Docker's default profiles it cannot create the namespaces it needs, and both executors treat an unavailable sandbox as a **silent** degradation (the Claude SDK is configured `failIfUnavailable: false`). Measured on Ubuntu 24.04 / Docker 29: the default seccomp profile blocks namespace creation outright; with `seccomp=unconfined` the namespace is created but mount setup then fails (`Failed to make / slave`) without `CAP_SYS_ADMIN`. Restoring the inner sandbox therefore costs `seccomp=unconfined` **plus** `CAP_SYS_ADMIN` — dismantling most of the outer boundary to rebuild a weaker inner one, which is a bad trade. **The container is the boundary**: the container itself, the non-root `bun` user, `/app` staying root-owned, the throwaway per-run workspace, and the env allow-list that keeps `DATABASE_URL`/`AGRIPPA_SECRET_KEY` out of agent subprocesses. Deployments that want OS-level sandboxing on top should use the VM/systemd topology, where bwrap works. Probe with `docker compose exec worker bwrap --unshare-all --ro-bind / / /bin/true` if you need to confirm the state on a given host.
Expand Down
16 changes: 16 additions & 0 deletions docs/manual/en/06-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,22 @@ A registered executor still needs a credential for the provider a step resolves

## Upgrades & scaling

Compose deployments use **`sudo infra/deploy.sh [<commit>]`**: it fetches from GitCode, builds images tagged with the deployed commit, starts them, waits on `/healthz`, and **rolls back to the previous tag** if the new one doesn't come up. Run it by hand any time; pushing to the `deploy` branch runs the same script automatically via Janus (`.janus/deploy.yml`).

It always rebuilds, deliberately: the SPA and the API are baked into the api image, so a bare `git pull && docker compose up -d` restarts the **old** code and looks like it worked. Build cache keeps a docs-only deploy cheap. A `flock` serializes concurrent deploys, and only the current and previous image tags are kept (each pair is ~4 GB).

Two things it will not do. It **only deploys commits reachable from the `deploy` branch** — an arbitrary SHA is refused, which is what keeps the root-level sudo rule meaningful. And **rollback does not revert the database**: the API applies migrations on boot before it is healthy, and some are irreversible.

The script therefore takes a `pg_dump` before every deploy, into `/var/lib/agrippa-deploy` (mode `0700`, dumps `0600`, last 5 retained — they are a full copy of production and the host also runs an unprivileged CI user). On any failure it prints the restore procedure rather than implying the schema came back:

```sh
docker compose ... stop api worker # pg_restore --clean needs the app's connections gone
docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < <dump>
docker compose ... start api worker
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

A deploy is reported successful only once the api reports healthy **and** every expected worker replica is running **and** a worker has registered its executors. The replica count matters because the worker registers before it starts consuming the queue, so a fresh registration alone would pass a worker that died during startup. Residual gap: a worker that stays up but wedges after registering is not detected.

Pull new images and `docker compose up -d` (VM: `sudo /opt/agrippa/infra/vm/deploy.sh`, which restarts the api first — see the VM section above). The api migrates on boot under an advisory lock, so rolling multiple replicas is safe. Draining workers is safe too: a killed worker's in-flight runs stay `running`, the queue retries them, and the engine **resumes step-granularly** — completed steps are never re-executed and token usage is never double-counted. Scale run throughput with `WORKER_REPLICAS` × `WORKER_SLOTS`.

### Upgrading from a deployment created before the compose project was named
Expand Down
16 changes: 16 additions & 0 deletions docs/manual/zh-CN/06-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,22 @@ docker compose exec -T postgres psql -U agrippa -d agrippa \

## 升级与扩容

Compose 部署请使用 **`sudo infra/deploy.sh [<commit>]`**:它从 GitCode 拉取代码、构建以所部署提交号打标签的镜像、启动、等待 `/healthz`,若新版本起不来则**回滚到上一个标签**。可随时手动执行;向 `deploy` 分支推送时,Janus 会通过 `.janus/deploy.yml` 自动运行同一个脚本。

它每次都会重新构建,这是刻意为之:SPA 与 API 都在构建镜像时打包进 api 镜像,因此单纯的 `git pull && docker compose up -d` 会重启**旧**代码,且看起来像是成功了。构建缓存让纯文档变更的部署依然很快。脚本用 `flock` 串行化并发部署,并且只保留当前与上一个镜像标签(每组约 4 GB)。

有两点它不会做。它**只部署能从 `deploy` 分支追溯到的提交**——任意 SHA 会被拒绝,这正是那条 root 级 sudo 规则得以成立的前提。以及**回滚不会还原数据库**:API 在启动、尚未健康之前就会执行迁移,其中部分不可逆。

因此脚本会在每次部署前做一次 `pg_dump`,存放于 `/var/lib/agrippa-deploy`(目录 `0700`、转储文件 `0600`,保留最近 5 份——它们是生产数据的完整副本,而本机上还运行着非特权的 CI 用户)。任何失败都会打印还原步骤,而不是让人误以为数据库也一并还原了:

```sh
docker compose ... stop api worker # pg_restore --clean 需要先断开应用连接
docker compose ... exec -T postgres pg_restore -U agrippa -d agrippa --clean --if-exists < <dump>
docker compose ... start api worker
```

只有当 api 报告健康、**且**每个预期的 worker 副本都在运行、**且**已有 worker 注册了执行器时,部署才算成功。副本数之所以重要,是因为 worker 在开始消费队列之前就会先注册,仅凭一条新注册记录会放过一个启动途中就挂掉的 worker。已知残留缺口:worker 起来了但注册后卡死,这种情况检测不到。

拉取新镜像后 `docker compose up -d` 即可(虚拟机:`sudo /opt/agrippa/infra/vm/deploy.sh`,会先重启 api——见上文虚拟机一节)。api 在启动时于咨询锁下迁移,多副本滚动升级安全。worker 排空同样安全:被终止的 worker 上进行中的执行保持 `running`,队列会重试,引擎**按步骤粒度续跑**——已完成的步骤不会重跑,Token 用量也不会重复计入。吞吐量 = `WORKER_REPLICAS` × `WORKER_SLOTS`。

### 从「compose 项目未命名」时期的部署升级
Expand Down
Loading
Loading