Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
docs: reconcile every doc with what the code actually does (#212)
OKNOTOK7eec2be2d973
diff --git a/.github/wif-setup.md b/.github/wif-setup.mdindex 5ce785c..d1d18f8 100644--- a/.github/wif-setup.md+++ b/.github/wif-setup.md@@ -2,12 +2,19 @@GitHub Actions authenticates to GCP without any long-lived service-accountkey. Instead, GitHub mints a short-lived OIDC token, and a Workload Identity-Pool maps it to a real GCP service account. The repo only needs to know two-values, both stored as repo secrets:+Pool maps it to a real GCP service account. **GCP authentication** needs only+two values, both stored as repo secrets:- `GCP_WIF_PROVIDER` — the full Workload Identity Provider resource name- `GCP_DEPLOY_SA` — the email of the GCP service account GH Actions impersonates+The Deploy workflow has two further prerequisites beyond GCP auth:++- Repo secrets `CUMORA_SMOKE_TOKEN` and `CUMORA_SMOKE_COMPANY_ID`, used by the+ post-rollout authenticated smoke check that gates automatic rollback+- A GitHub **environment** named `production` (`deploy.yml` declares+ `environment: production`), which supplies the independent approval step+Run the steps below **once**, in your terminal (not in CI).```sh@@ -66,8 +73,11 @@ Or do it via the web UI: https://github.com/yetone/cumora/settings/secrets/actio### Once that's set up- Every push to `main` triggers the Build workflow → images appear in AR-- Manual deploy: GitHub → Actions → Deploy → Run workflow → pick a tag-- Tag deploy: `git tag v0.1.0 && git push origin v0.1.0` → auto-rolls that version+- Deploy is **always** a manual dispatch: GitHub → Actions → Deploy → Run+ workflow → pick a tag. `deploy.yml` has no `push` trigger at all, by design —+ a bad commit on `main` must not auto-ship to prod.+- Pushing a `v*` tag fires the **Release** workflow only (the Electron desktop+ hand-off to `yetone/cumora-releases`). It does not touch GKE.### Tightening laterdiff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex ae3a7b6..ca66630 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -7,8 +7,8 @@# the agent runtime is unaffected by typical UI / docs / k8s changes.## This workflow ONLY builds. Deploy is a separate manual workflow-# (deploy.yml) so a bad commit on main doesn't auto-ship to prod —-# trade-off chosen explicitly: "手动触发" / tag push.+# (deploy.yml, workflow_dispatch only) so a bad commit on main doesn't+# auto-ship to prod — trade-off chosen explicitly: "手动触发".name: Builddiff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 4cd0ccf..1c60038 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -3,8 +3,10 @@# Why this exists: the npm account has 2FA (auth + writes), so a manual# `npm publish` prompts for an interactive OTP every release. An npm# *automation* token bypasses 2FA for writes, so CI can publish without a-# human-entered code — mirroring how the server already auto-deploys on-# push to main (build.yml → deploy.yml).+# human-entered code. Unlike the server (build.yml produces a candidate image+# that deploy.yml then rolls out on an explicit dispatch), the CLI publishes+# straight from a push to main — an npm version is immutable and additive, so+# there's no production state to mutate.## Setup (one-time): create an automation token at# npmjs.com → Access Tokens → Generate → "Automation"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 7514867..8f869c5 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -4,8 +4,8 @@ name: Release# Hand off to yetone/cumora-releases which has the matrix runners that# build + sign + publish the Electron app for every platform.#-# The existing deploy.yml ALSO triggers on `v*` — it handles the GKE-# backend roll-out. The two are orthogonal; both run from the same tag.+# The GKE backend roll-out is deliberately NOT tied to this tag: deploy.yml+# is `workflow_dispatch` only, so a desktop release never mutates production.on:push:diff --git a/.gitignore b/.gitignoreindex 6fc0f6d..f903a02 100644--- a/.gitignore+++ b/.gitignore@@ -18,6 +18,7 @@ lerna-debug.log**.sln*.sw?.claude/+.codex/# Dependenciesnode_modulesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e787226..e86e6c4 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -9,8 +9,10 @@ project's [MIT License](LICENSE).## Getting set up-You need **Node ≥ 18** (CI runs on Node 24), plus **Postgres** and **Redis**-running locally.+You need **Node ≥ 22** (CI runs on Node 24), plus **Postgres** and **Redis**+running locally. Node 18 and 20 can no longer install the dependency tree —+`@capacitor/cli` requires `node >= 22` and `@aws-sdk/client-s3` requires+`node >= 20`.```bashcreatedb -h localhost cumora@@ -38,13 +40,25 @@ daemon), `MOBILE_IOS.md`, `PUSH_NOTIFICATIONS.md`, `email.md`.Run the same gates CI runs. All of these must pass:```bash-npm run lint # Biome lint (autofix with `npm run lint:fix`)-npm run typecheck # frontend types-npm run server:typecheck # server types-npm test # unit tests (node:test) for server + workers-npm run test:integration # integration suite (needs local Postgres + Redis)-npm run guard:big-brain # architecture guard, see below-npm run guard:llm-tracked # architecture guard, see below+npm run lint # Biome lint (autofix with `npm run lint:fix`)+npm run typecheck # frontend types+npm run server:typecheck # server types+npm test # unit tests (node:test) for server + workers + frontend lib+npm run test:integration # integration suite, see the env var below+npm run guard:big-brain # architecture guard, see below+npm run guard:llm-tracked # architecture guard, see below+npm run guard:engine-registry # architecture guard, see below+```++`npm run test:integration` needs a **dedicated** database and does nothing+without `INTEGRATION_DATABASE_URL` — it prints `[integration] skipped` and+exits 0, which looks exactly like a pass. The suite `TRUNCATE`s every table,+so point it at a throwaway DB:++```bash+createdb -h localhost cumora_test+INTEGRATION_DATABASE_URL=postgres://$USER@localhost:5432/cumora_test \+ npm run test:integration```Biome is configured (`biome.json`) as a **linter only** — it is not a@@ -54,11 +68,14 @@ rules are on; noisy or intentional-pattern style rules are off, while the a11yrules are enforced incrementally (useButtonType, ARIA roles/props, and coreaccessibility rules are active).-Both TypeScript projects are `strict`. There are no frontend unit tests yet;-server and worker logic is covered by `server/src/__tests__` and-`server/src/__integration__`.+Both TypeScript projects are `strict`. Tests live in four places, and+`npm test` runs the first, third and fourth: `tests/` (frontend lib units),+`server/src/__integration__` (integration, opt-in via the env var above),+`server/src/__tests__` (server units), and `workers/email-gate/src`+(Worker units — this is why you want `npm run setup` over a bare+`npm install`).-## Two architecture invariants (enforced in CI)+## Three architecture invariants (enforced in CI)These aren't style preferences — they're the product's core cost model, and aguard script will fail your build if you break them:@@ -71,6 +88,10 @@ guard script will fail your build if you break them:2. **Every LLM call must be tracked** in the cost ledger. Untracked spend is acorrectness bug here, not just an oversight. `npm run guard:llm-tracked`checks this.+3. **A BYOA engine is wired into all of its registries or none.** A+ half-wired engine does not error — `normalizeByoaSource()` maps anything+ unknown to `byoa-claude`, so its runs quietly bill to the wrong engine.+ `npm run guard:engine-registry` checks this.The multi-agent coordination model (how N agents share a room withoutcolliding, and why the prompt is kept deliberately minimal) is documented indiff --git a/README.md b/README.mdindex 2d308b7..013a687 100644--- a/README.md+++ b/README.md@@ -40,7 +40,7 @@ Two "brain" paths:```- **Frontend** (`src/`) is pure UI: React 18 + Vite + TypeScript + Tailwind, with `desktop/`, `mobile/`, `web/`, and `admin/` shells over the same components.-- **Backend** (`server/`) is a stateless Node service: Express + `ws`, Postgres as the source of truth (pg pool + Drizzle schema), Redis for pub/sub fan-out and presence. Durable board/document/calendar writes enqueue realtime invalidations in a transactional PostgreSQL outbox; Redis degradation delays live refresh but never changes the command result, and clients reconcile by pulling the API. Any number of instances can drain the outbox through leased `SKIP LOCKED` claims. See [ADR 0001](docs/decisions/0001-transactional-realtime-outbox.md).+- **Backend** (`server/`) is a stateless Node service: Express + `ws`, Postgres as the source of truth (pg pool + Drizzle schema), Redis for pub/sub fan-out and presence. Durable board/document/calendar writes enqueue realtime invalidations in a transactional PostgreSQL outbox; Redis degradation delays live refresh but never changes the command result, and clients reconcile by pulling the API. Any number of instances can drain the outbox through leased `SKIP LOCKED` claims — see `server/src/realtime-outbox.ts`.- **Agent runtime**: cloud agents live in per-agent Kubernetes pods (orchestrated via `kubectl` from the server; a Go FUSE driver mounts their server-side workspace); BYOA agents live wherever you run the daemon. Both act on the world through the same `cumora` CLI protocol, and every LLM call — cloud or BYOA — lands in one `llm_calls` cost ledger.- **Coordination**: agents in the same room don't trample each other. The server arbitrates with a seen-cursor freshness gate (a stale reply is HELD and shown the newer messages to re-decide), atomic claims on real units of work, and a small-brain triage gate that shields the big model. Design notes in [`docs/COORDINATION.md`](docs/COORDINATION.md).@@ -71,17 +71,24 @@ Database migrations are applied via `npm run migrate` (run automatically by `npm| `OPENAI_MODEL` / `OPENAI_MODEL_SUPPORT` | big-brain / support-brain models || `PORT` | `5181` |-Optional feature groups (OAuth login, email via Resend + Cloudflare Email Routing, R2 storage/CDN, APNs/FCM push, the sub2api per-user LLM gateway, waitlist/invites, metrics) are documented inline in [`.env.example`](.env.example) and `server/src/env.ts`.+Optional feature groups (OAuth login, email via Resend + Cloudflare Email Routing, R2 storage/CDN, APNs/FCM push, the sub2api per-user LLM gateway, invites, metrics) are declared in `server/src/env.ts`, which is the authoritative list. [`.env.example`](.env.example) annotates a commonly-edited subset of them.### Tests```bash-npm test # unit tests (node:test) for server + workers-npm run test:integration # integration suite (needs local Postgres/Redis)+npm test # unit tests (node:test) for server + workers + frontend libnpm run typecheck && npm run server:typechecknpm run guard:big-brain # CI guard: only agent turns may use the big model++# Integration suite. Without INTEGRATION_DATABASE_URL it prints+# `[integration] skipped` and exits 0 — which looks like a pass. It+# TRUNCATEs every table, so give it a throwaway database.+INTEGRATION_DATABASE_URL=postgres://$USER@localhost:5432/cumora_test \+ npm run test:integration```+[`CONTRIBUTING.md`](CONTRIBUTING.md) lists the full set of gates CI runs.+## Repo layout| path | what it is |@@ -95,6 +102,8 @@ npm run guard:big-brain # CI guard: only agent turns may use the big model| `workers/` | Cloudflare Workers: `email-gate` (inbound mail) and `r2-gate` (signed CDN) || `website/` | marketing site for cumora.ai (Cloudflare Pages) || `benchmarks/` | real-LLM multi-agent coordination benchmarks (chain / counting / werewolf / kanban) |+| `tests/` | frontend lib unit tests (run by `npm test`) |+| `scripts/` | CI guard scripts + one-off generators || `server/k8s/` | deployment manifests + GKE notes |## Docsdiff --git a/SECURITY.md b/SECURITY.mdindex a973024..d65c581 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -78,4 +78,7 @@ If you self-host, at minimum:`EMAIL_INBOUND_HMAC_SECRET`, `R2_URL_SIGNING_SECRET`, APNs/FCM credentials)out of the repo and in your deployment's secret store.-See [`.env.example`](.env.example) for the full annotated list.+`server/src/env.ts` is the authoritative list of every variable the server+reads, including the ones above. [`.env.example`](.env.example) annotates a+commonly-edited subset and does **not** cover `AGENT_RUNTIME_SECRET` or the+APNs/FCM credentials.diff --git a/agent-cli/README.md b/agent-cli/README.mdindex 8fb1c07..831db4d 100644--- a/agent-cli/README.md+++ b/agent-cli/README.md@@ -13,15 +13,18 @@ In Cumora: **You → Computers → Add a computer** to get a pairing code, thenon the machine you want to host agents:```sh-npx cumora agent computer --pair <code> --server <your-server-url>+npx cumora agent computer --pair <code> [--server <your-server-url>]```Then start the daemon (after pairing, the config is saved):```sh-npx cumora agent computer --server <your-server-url>+npx cumora agent computer [--server <your-server-url>]```+`--server` is optional; it defaults to `https://api.cumora.ai`. Pass it when+you self-host.+Requires **Node ≥ 18** and a supported CLI on your `PATH`. Secure mode supportsClaude Code **≥ 2.1.248** on macOS/Linux/WSL2 and Codex **≥ 0.138.0** onmacOS/Linux/WSL2/native Windows. Older CLIs fail closed instead of falling backdiff --git a/benchmarks/README.md b/benchmarks/README.mdindex abaa54a..e9a77b5 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -85,11 +85,12 @@ Opus 4.7 on a 7-agent roster (the standard test rig as of 2026-06):| `werewolf` | 15-25 min | $15-25 | 2 | $30-50 || `kanban` | 20-30 min | $8-15 | 2 | $16-30 |-**Weekly cycle running all four scenarios: ~$58-101.** Weekly chain-+ counting only: ~$12-21 (cheap regression watch). Daily all-four:-$240-400/month (aggressive). Tune `BENCH_*_TRIALS` env vars or-narrow scenarios on a given schedule to trade statistical confidence-for cost.+**One cycle running all four scenarios: ~$58-101.** At a weekly cadence+that's ~$250-440/month; chain + counting only is ~$12-21 per cycle+(~$52-91/month — a cheap regression watch). Running all four *daily* is+~$1,740-3,030/month, which is why the schedule below doesn't. Tune+`BENCH_*_TRIALS` env vars or narrow scenarios on a given schedule to trade+statistical confidence for cost.The default workflow runs `chain counting` only on schedule (thecheap pair); use `workflow_dispatch` with an explicit scenario listdiff --git a/docs/BYOA.md b/docs/BYOA.mdindex 6230932..5bcf58d 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -272,16 +272,21 @@ fail-closed host boundary:isolation, an empty strict network allowlist, no Bash/PowerShell/web tools,no unsandboxed retry, and an explicit deny list for every inheritedenvironment variable not needed by the fixed Cumora MCP bridge. Because- restricted mode ignores user settings, the daemon imports only- `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, and- `ANTHROPIC_SMALL_FAST_MODEL` plus the three `ANTHROPIC_DEFAULT_*_MODEL`- aliases from Claude's user settings into the trusted- Claude core; those names remain denied to model-spawned subprocesses and- Cumora never serializes the values into argv, its logs, Agent files, or server- reports. Claude Code- 2.1.248 or newer is required. Linux/WSL2 also requires `bubblewrap` and- `socat`; a missing dependency fails the turn. See- [ADR 0005](decisions/0005-secure-claude-provider-bootstrap.md).+ restricted mode ignores user settings, the daemon imports a fixed+ seven-key allowlist from Claude's user settings into the trusted Claude+ core — `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`,+ `ANTHROPIC_SMALL_FAST_MODEL`, and the three `ANTHROPIC_DEFAULT_*_MODEL`+ aliases (`CLAUDE_CORE_ENV_KEYS` in+ `server/src/agents/computer/claude-user-settings.ts`). Those names remain+ denied to model-spawned subprocesses and Cumora never serializes the values+ into argv, its logs, Agent files, or server reports. Explicit daemon+ environment values take precedence over the settings file; a missing,+ malformed, relative-config-root, or oversized settings file fails soft and+ preserves Claude's native first-party OAuth/keychain behavior. Note that+ `api.anthropic.com` is *not* treated as a custom provider, while a+ `ANTHROPIC_BASE_URL` that won't parse is (it fails toward "custom"). Claude+ Code 2.1.248 or newer is required. Linux/WSL2 also requires `bubblewrap` and+ `socat`; a missing dependency fails the turn.- Codex runs one-shot with user config and exec-policy rules ignored. A custompermission profile permits minimal runtime reads and writes only under theagent home, disables command network, and gives model-spawned commands only@@ -342,8 +347,7 @@ An inherited effort is a preference, not a guarantee of thinking tokens:Claude can cap effort for a model or organization, and Opus 5 with thinkingdisabled may send `high` even when `xhigh` is saved. To request deeperreasoning, enable thinking as well as setting effort. See-[Claude model configuration](https://code.claude.com/docs/en/model-config#adjust-effort-level)-and [ADR 0007](decisions/0007-claude-turn-preferences.md).+[Claude model configuration](https://code.claude.com/docs/en/model-config#adjust-effort-level).### Running against a custom provider@@ -537,16 +541,29 @@ npx cumora@latest agent computer --pair <code> [--server <url>]```- `agent-cli/` builds `dist/cli.js` — a single self-contained ESM file- (~140KB, zero runtime dependencies) that esbuild-bundles the daemon+ (~330KB, zero runtime dependencies) that esbuild-bundles the daemonsource from `server/src/agents/computer/` — one source of truth, noseparate copy. The repo's root `package.json` stays `private`; only- this thin package is published.-- `--install-service` installs the daemon as a supervised service- (launchd `io.cumora.daemon` on macOS, `systemd --user` on Linux, a per-user- Task Scheduler watchdog on Windows) so it restarts at user login (including- after a reboot) and — on macOS — runs in the GUI domain where the engine's- keychain-backed login actually works.-- `--doctor` probes the big/small models and the wake path end-to-end.+ this thin package is published. `.github/workflows/publish.yml` pushes it+ to npm on any push to `main` touching `agent-cli/**` (see+ [`RELEASE.md`](RELEASE.md)).+- Setup flags: `--pair <code>`, `--server <url>`, `--engine <id>` (force one+ of the registered engines instead of auto-detecting).+- Service flags: `--install-service` installs the daemon as a supervised+ service (launchd `io.cumora.daemon` on macOS, `systemd --user` on Linux, a+ per-user Task Scheduler watchdog on Windows) so it restarts at user login+ (including after a reboot) and — on macOS — runs in the GUI domain where the+ engine's keychain-backed login actually works.+ `--uninstall-service`, `--restart`, `--stop`, `--status`, and `--logs`+ manage and inspect it.+- Diagnostics: `--doctor` probes the big/small models and the wake path+ end-to-end; `--version` / `-v` and `--help` / `-h` are one-shot too.+- `--stop`, `--restart`, and `--pair` kill only the **long-running** daemon.+ Every one-shot invocation — `--doctor`, `--help`, `--status`, and the rest of+ `ONE_SHOT_FLAGS` — is excluded by `isStoppableDaemonCommand`, so a+ concurrently running `--doctor` survives a `--stop` instead of dying+ mid-probe.+- With no flags the daemon runs in the foreground (pair first).- In-repo dev uses `./bin/cumora agent computer …` (tsx) — the samecode, unbundled.diff --git a/docs/COORDINATION.md b/docs/COORDINATION.mdindex d215e19..d5d5bf3 100644--- a/docs/COORDINATION.md+++ b/docs/COORDINATION.md@@ -68,12 +68,15 @@ an Anthropic model into another namespace.more cautious about prompt-injection-like patterns and behaves differently inmulti-agent flows. Withoutthe pin, every user's behavior drifts whenever Anthropic ships a model.-Override per-agent by setting `participants.model` for a specific id. Secure-Claude provider bootstrap and the reason credentials stay outside model tools-are recorded in [ADR 0005](decisions/0005-secure-claude-provider-bootstrap.md).+Override per-agent by setting `participants.model` for a specific id. Provider+credentials for a custom Claude endpoint are bootstrapped from a fixed+seven-key allowlist in Claude's user settings, enter only the trusted Claude+core process, and stay denied to every model-spawned subprocess — see+`server/src/agents/computer/claude-user-settings.ts`.Agent turns now inherit validated Claude effort/thinking preferences instead-of forcing thinking off. Triage retains its separate cheap-call policy; see-[ADR 0007](decisions/0007-claude-turn-preferences.md) for precedence and scope.+of forcing thinking off. Triage retains its separate cheap-call policy; the+inherited keys, their validation, and the daemon-env-wins precedence rule are+tabulated in [`BYOA.md`](BYOA.md).### 2. Per-computer big-brain concurrency cap (daemon)`CUMORA_BYOA_MAX_CONCURRENT_BIG_BRAIN` (default **6**; drop to 2-4 on very@@ -799,3 +802,5 @@ fallback) and absent-member coverage (team-adapts principle).| `server/src/agents/runtime/server.ts` | `/runtime/inbox` endpoint with `?probe=1` flag for non-advancing reads. `/thinking/mark` / `/thinking/unmark` bracket the turn (they also still stamp the vestigial compose-anchor — see 5a). `/agenda` routes the nudge `source` flag (classified vs fallback) into `claimStallNudge`. || `server/src/agents/runtime/inproc-client.ts` | `loadInbox()` — must remain a PURE READ. No more recordSeen side-effect (that broke a6e69aa). `markThinking`/`peekThinking` for the ZSET-based "who's composing here" claim. || `server/src/agents/computer/registry.ts` | `listAgentsForComputer` with per-engine `CUMORA_DEFAULT_*_MODEL` fallbacks. |+| `server/src/agents/computer/claude-user-settings.ts` | `CLAUDE_CORE_ENV_KEYS` (the seven-key provider bootstrap allowlist), `CLAUDE_TURN_ENV_KEYS` + their validation, and `isCustomAnthropicEndpoint()` — which treats `api.anthropic.com` as first-party and an unparseable base URL as custom (§1). |+| `server/src/agents/computer/model-catalog.ts` | Reports the engine's configured defaults, including whether a custom endpoint owns an unnamed default, so a custom-provider default can outrank the deployment-level pin (§1). |diff --git a/docs/MOBILE_IOS.md b/docs/MOBILE_IOS.mdindex 9063bf2..618bb04 100644--- a/docs/MOBILE_IOS.md+++ b/docs/MOBILE_IOS.md@@ -2,7 +2,9 @@This document walks the end-to-end flow for building, testing andsubmitting the Cumora iOS app via Capacitor. It assumes a clean macOS-machine with Xcode 15+ and Ruby/CocoaPods installed.+machine with Xcode 15+. There is no Podfile and no CocoaPods step — native+dependencies are Swift Package Manager packages, resolved into+`ios/App/CapApp-SPM/Package.swift` by `npx cap sync ios`.## Architecture summary@@ -33,7 +35,9 @@ npm installnpm install --no-save sharpnode scripts-gen-ios-assets.mjs-# Build the web bundle and copy native assets/plugins into ios/.+# Build the web bundle, then copy assets and resolve native plugins.+# `mobile:sync` is `npm run build && npx cap sync` — no platform+# argument, so it syncs BOTH ios/ and android/.npm run mobile:sync```@@ -46,9 +50,10 @@ npm run mobile:syncnpm run mobile:ios:run```-To run against a remote dev API, temporarily uncomment a `server.url`-in capacitor.config.ts (don't commit) or set `cumora.serverUrl` via-localStorage in the in-WebView devtools.+To run against a remote dev API, temporarily **add** a `server.url` to+capacitor.config.ts (it is deliberately absent from the checked-in config —+don't commit one) or set `cumora.serverUrl` via localStorage in the in-WebView+devtools.## Release build for App Store / TestFlight@@ -94,8 +99,7 @@ localStorage in the in-WebView devtools.## Required Info.plist keys-Add these to `ios/App/App/Info.plist` before submission (the Capacitor-defaults are too minimal for App Review):+`ios/App/App/Info.plist` already declares the four keys App Review needs:```xml<key>NSCameraUsageDescription</key>@@ -104,14 +108,20 @@ defaults are too minimal for App Review):<string>Cumora needs access to your photo library to attach images to messages.</string><key>NSMicrophoneUsageDescription</key><string>Cumora can record short voice notes for your conversations.</string>-<key>NSUserTrackingUsageDescription</key>-<string>Cumora does not track you across other apps and websites.</string><key>ITSAppUsesNonExemptEncryption</key><false/>```-(Only include the camera/photo/mic strings if those features ship; App-Review rejects bundles that declare permissions they don't use.)+The one key **not** present is `NSUserTrackingUsageDescription`. Only add it+if the app actually calls App Tracking Transparency — today it doesn't, and+declaring a permission you don't use is itself a rejection reason:++```xml+<key>NSUserTrackingUsageDescription</key>+<string>Cumora does not track you across other apps and websites.</string>+```++Likewise, drop the camera/photo/mic strings if those features stop shipping.## App Store screenshots — required sizes@@ -172,4 +182,7 @@ npm run buildnpx cap doctor ios```-If `cap doctor` flags missing pods, run `cd ios/App && pod install`.+If `cap doctor` flags unresolved native dependencies, re-run+`npx cap sync ios` and let Xcode resolve the Swift packages+(File → Packages → Resolve Package Versions). There is no `pod install`+step in this project.diff --git a/docs/PUSH_NOTIFICATIONS.md b/docs/PUSH_NOTIFICATIONS.mdindex fc49a24..5441aad 100644--- a/docs/PUSH_NOTIFICATIONS.md+++ b/docs/PUSH_NOTIFICATIONS.md@@ -16,7 +16,7 @@ recipient calculation) is already in the repo.| Surface | Location || --- | --- |-| `@capacitor/push-notifications` plugin | `package.json` + `ios/App/Podfile`-equivalent SPM bundle (synced by `npx cap sync ios`) |+| `@capacitor/push-notifications` plugin | `package.json` + `ios/App/CapApp-SPM/Package.swift` (synced by `npx cap sync ios`) || AppDelegate APNs callbacks → Capacitor bridge | `ios/App/App/AppDelegate.swift` || `aps-environment` entitlement | `ios/App/App/App.Debug.entitlements` (development) + `ios/App/App/App.Release.entitlements` (production) — selected automatically by Xcode build config || `push_devices` table | `server/src/db/migrate.ts` |@@ -24,7 +24,7 @@ recipient calculation) is already in the repo.| APNs sender (HTTP/2 + ES256 JWT, no third-party lib) | `server/src/push.ts` || FCM sender (HTTP v1, service-account JWT) | `server/src/fcm.ts` || Recipient filter (skips author, currently-online users, muted convos) | `computeMessageRecipients` in `server/src/push.ts` |-| Outbound dispatch on new message | inside POST `/conversations/:id/messages` |+| Outbound dispatch on new message | `dispatchMessagePush` in `server/src/push.ts`, called from **both** POST `/conversations/:id/messages` (`server/src/api/router.ts`) and `cmdReply` (`server/src/agents/cli.ts`) — an agent's reply travels the second path only || Client lifecycle (request perms, register, deep-link, sign-out) | `src/lib/push.ts` + `src/mobile/MobileApp.tsx` + `src/mobile/MobileMe.tsx` || User preference `notify.push` (in-app kill switch) | `TOGGLE_PREFS` in `src/mobile/MobileMe.tsx` |@@ -82,11 +82,12 @@ Two Secrets:kubectl create secret generic cumora-apns-key \--from-file=AuthKey_<KEY_ID>.p8=/path/to/AuthKey_<KEY_ID>.p8```- The deployment mounts this at `/var/run/secrets/cumora-apns/` and- sets `APNS_KEY_PATH` accordingly (add the volume + mount to your- production deployment manifest).- The mount is declared `optional: true` so pods boot cleanly even- when this secret is absent — the push path soft-disables itself.+ `server/k8s/cumora-server.gke.yaml` does **not** yet declare this volume —+ it only wires `envFrom: secretRef: {name: cumora}`. Add the volume and+ mount yourself, at `/var/run/secrets/cumora-apns/`, and set+ `APNS_KEY_PATH` to the mounted file. Mark the volume `optional: true` so+ pods still boot when the secret is absent — the push path soft-disables+ itself.3. **Apply the deployment** to pick up the new volume mount:```sh@@ -154,13 +155,10 @@ like APNs.| 410 / device disabled | Expected; `push_devices.disabled_at` is set. Re-install or sign back in to re-register || Foreground app shows OS banner instead of in-app toast | Expected only when the app is backgrounded. Foreground deliveries fall through to `NotificationToasts`. || Push fires for a user looking at the chat | Their `participants.status` is not `'avail'` — check WS connectivity. The server suppresses pushes only for users marked `'avail'` |+| Flipped `notify.push` on but nothing arrives | The toggle only writes the preference. Unregistration/registration happens on the next `initPushNotifications` call — tap **Re-register** in You → Push status, or background and re-foreground the app (`installVisibilityHook` in `src/lib/push.ts` retries when there's no token). No relaunch needed |## Open items (deliberate)-- **Per-OS toggle persistence.** Flipping `notify.push` off currently- unregisters the device immediately, but flipping it back on requires- an app relaunch. Capacitor's plugin doesn't expose mid-session- re-register cleanly.- **Doc-mention pushes / calendar reminder pushes.** Both already haveWS events (`doc.mention`, `calendar.reminder`); wiring them into`notifyMessage`-style senders is a follow-up.diff --git a/docs/RELEASE.md b/docs/RELEASE.mdindex b64743e..7b4b924 100644--- a/docs/RELEASE.md+++ b/docs/RELEASE.md@@ -23,9 +23,11 @@ It does **not** deploy the API server. Backend production deploys are anexplicit, separately approved action; a desktop tag must never silently mutatethe backend.-The auto-updater in the desktop app reads from `cumora-releases`, so-once the release workflow finishes (~15–20 minutes), running clients-will pick it up on their next periodic update check.+The auto-updater in the desktop app reads from `https://updates.cumora.ai`+(the R2-backed `generic` feed), with the `cumora-releases` GitHub Release as a+fallback. Once the release workflow finishes (~15–20 minutes) and the R2 mirror+step has run, running clients will pick it up on their next periodic update+check.## Backend release: build candidate, then ignite production@@ -132,13 +134,41 @@ and still succeeds.### One-time Cumora-side wiring-- `build.publish` in `package.json` points at `yetone/cumora-releases`,- so the in-app auto-updater knows where to look.-- `build.mac.notarize.teamId` reads `APPLE_TEAM_ID` from the workflow+- `build.publish` in `package.json` is an **ordered array**: the first entry+ is the `generic` feed at `https://updates.cumora.ai` (R2-backed) and is what+ electron-updater actually polls; the `github` entry for+ `yetone/cumora-releases` is the fallback feed. See `electron/autoUpdater.cjs`.+- `build.mac.notarize` is `true`; electron-builder picks up `APPLE_TEAM_ID`+ (alongside `APPLE_ID` and `APPLE_APP_SPECIFIC_PASSWORD`) from the workflowenvironment.- `build/entitlements.mac.plist` declares the hardened-runtimeentitlements Electron needs (JIT, network access, dyld vars).+## Releasing the `cumora` CLI to npm++The BYOA daemon users install with `npx cumora@latest` is a **separate**+artifact from the desktop app: the npm package `cumora`, built from+`agent-cli/`. It has its own workflow and is not part of a `v*` tag release.++`.github/workflows/publish.yml` publishes it on any push to `main` that+touches `agent-cli/**` — typically the `chore(agent-cli): release cumora@X`+version bump in `agent-cli/package.json`. To cut a CLI release:++```bash+# Bump agent-cli/package.json's own "version", then merge to main.+# The workflow runs `node build.mjs` and `npm publish --access public`.+```++Notes:++- It publishes only if that exact version isn't already on the registry, so+ re-pushing `main` is a no-op rather than a failure.+- It needs the repo secret `NPM_TOKEN` (an npm **automation** token, which+ bypasses 2FA for writes). Until that secret exists the workflow no-ops+ cleanly instead of failing.+- `agent-cli/package.json`'s version is independent of the root+ `package.json` version. Keep them in step by convention, not by tooling.+## Manual rebuild of a past releaseIf a previous release needs a re-roll (signing failed, missing artifact,@@ -163,6 +193,6 @@ etc.), use the `workflow_dispatch` form on `yetone/cumora-releases`:- **`latest-mac.yml` mentions only one architecture.** One of the twoMac runners failed before producing the yml. Look at the `Uploadbuild artifacts` step on `build-mac-arm64` / `build-mac-x64`.-- **The desktop app doesn't see the update.** The autoupdater polls- every 10 minutes (default for `electron-builder`). Force it from the- app menu or restart.+- **The desktop app doesn't see the update.** The autoupdater checks 3+ seconds after launch and then every **30 minutes** (`electron/autoUpdater.cjs`+ sets that interval explicitly). Force it from the app menu or restart.diff --git a/docs/decisions/0001-transactional-realtime-outbox.md b/docs/decisions/0001-transactional-realtime-outbox.mddeleted file mode 100644index 2707524..0000000--- a/docs/decisions/0001-transactional-realtime-outbox.md+++ /dev/null@@ -1,56 +0,0 @@-# ADR 0001: Transactional outbox for durable realtime invalidations--- Status: Accepted-- Date: 2026-09-02--## Context--Boards, documents, and calendar commands persist their source-of-truth state-in PostgreSQL and notify connected clients through Redis pub/sub. Previously a-handler committed PostgreSQL and then awaited Redis. During a Redis outage the-command could return an error after it had already succeeded, encouraging a-retry that created a duplicate entity; a process crash between commit and-publish could also lose the invalidation.--Redis pub/sub is a realtime transport, not durable command state. Clients-already treat these events as thin invalidations and reconcile by reading the-PostgreSQL-backed API.--## Decision--- Durable board, document, and calendar mutations insert a fully formed event- into `realtime_outbox` in the same PostgreSQL transaction.-- A per-process worker claims rows with `FOR UPDATE SKIP LOCKED` and a lease,- then publishes through the bounded Redis command client after commit.-- Delivery is at-least-once. Every payload carries a stable `deliveryId`;- current consumers are naturally idempotent because they refetch or replace- entities by id.-- Failed delivery uses exponential backoff. Invalidations are discarded after- 12 attempts or 24 hours; clients recover on their next pull. Discards are- logged as errors rather than blocking writes forever.-- Board, document, and calendar create commands accept an actor-scoped- `requestId`. A payload hash rejects accidental key reuse, while a retry of- identical input returns the original entity.--## Consequences--- PostgreSQL commit is the only success boundary for these commands; Redis- latency and outages no longer change the response.-- Multiple server replicas can drain concurrently without publishing the same- claimed row under normal operation. A crash after publish but before the- acknowledgement may redeliver once, which consumers must tolerate.-- Operators can inspect pending rows, attempts, age, and `last_error` directly- in `realtime_outbox`. A growing pending queue means realtime is degraded, not- that durable writes are failing.-- The outbox adds a small PostgreSQL write per mutation. Bounded cleanup keeps- successful rows for 24 hours and discarded rows for seven days, providing an- operational window without allowing terminal history to grow indefinitely.--## Alternatives considered--- **Await Redis after commit:** rejected because it reports ambiguous command- outcomes and cannot close the commit/publish crash gap.-- **Fire-and-forget Redis only:** rejected because it removes request latency- but silently loses invalidations during outages.-- **A dedicated broker:** deferred; the current invalidation volume does not- justify another source of truth, and PostgreSQL already owns the transaction.diff --git a/docs/decisions/0002-fail-closed-agent-execution-placement.md b/docs/decisions/0002-fail-closed-agent-execution-placement.mddeleted file mode 100644index eea1787..0000000--- a/docs/decisions/0002-fail-closed-agent-execution-placement.md+++ /dev/null@@ -1,59 +0,0 @@-# ADR 0002: Fail-closed Agent execution placement--- Status: Accepted-- Date: 2026-09-03--## Context--An Agent can run either on a paired BYOA Computer (`local` or `vps`) or on a-managed Cumora Cloud Pod. An unassigned paid Agent is intentionally eligible-for managed execution, so `computer_id = NULL` is a valid placement state.--The scheduler previously converted every host-resolution exception into the-same nullable shape. A transient PostgreSQL failure could therefore look like-an unassigned Agent, omit the company tier check, and create a managed Pod for-an Agent that was actually assigned to BYOA. The scheduler's earlier lookup was-also the only policy check, leaving a race before `ensurePod` applied the-Kubernetes manifest.--## Decision--- Host resolution is a discriminated result: `found`, `missing`, or `error`.- A found result always includes a valid tenant and its tier; only an explicit- `computer_id = NULL` produces an unassigned host.-- Dangling, cross-tenant, revoked, or unknown Computer assignments are invalid- placement errors. They never fall back to cloud execution.-- The scheduler fails closed on errors. Transient lookup failures enter a- dedicated wake retry class that is safe for durable message wakes because no- execution location was selected or started.-- Managed-message triage and host selection live in the same retryable wake- operation, so a retry cannot bypass the managed-runtime gate.-- `ensurePod` independently verifies that the Agent is active, is not assigned- to BYOA, and belongs to a paid tenant. It checks at entry and again immediately- before the first Kubernetes write; the loaded persona must match the same- tenant.-- `ensurePod` failures carry machine-readable codes. Placement lookup failures- can be retried without treating ordinary Pod failures as safe message replays.--## Consequences--- A database outage delays a wake instead of changing its execution location.-- Assignment corruption is visible through an alert and cannot cross a tenant,- credential, or billing boundary.-- Host and tier resolution uses one database snapshot and adds a small cold-path- query at the final Pod boundary. `ensurePod` is already limited to resting- managed Agents, so the extra check is preferable to caching mutable policy.-- A BYOA reassignment or free-tier downgrade that races with Pod preparation is- observed before PVC or Pod creation. Existing Pods are not implicitly deleted;- lifecycle cleanup remains the assignment controller's responsibility.--## Alternatives considered--- **Catch lookup failures and assume cloud:** rejected because availability- cannot override execution-location authorization.-- **Trust only the scheduler check:** rejected because callers can invoke- `ensurePod` directly and placement can change before Kubernetes apply.-- **Cache host/tier decisions:** rejected because per-replica stale placement is- exactly the unsafe state this boundary is intended to prevent.-- **Hold a database lock across Kubernetes calls:** rejected because external- control-plane latency would create long transactions and lock contention.diff --git a/docs/decisions/0003-versioned-schema-migration-ownership.md b/docs/decisions/0003-versioned-schema-migration-ownership.mddeleted file mode 100644index 4cc7ce1..0000000--- a/docs/decisions/0003-versioned-schema-migration-ownership.md+++ /dev/null@@ -1,71 +0,0 @@-# ADR 0003: Versioned schema migrations with one deployment owner--- Status: Accepted-- Date: 2026-09-03--## Context--The server historically called one large idempotent DDL batch before opening-its HTTP listener. Kubernetes also ran the same command in every application-Pod's init container. An advisory lock serialized replicas, but restart,-autoscaling, rollout, and schema ownership still shared one failure domain.-Even a no-op batch requested locks across many hot tables, and a derived-sentinel probe had previously declared a partially upgraded schema current.--The repository already has a standalone migration entry point and a manually-approved Deploy workflow. Those are the appropriate ownership boundary; an-application replica has no reason to create or alter schema while starting.--## Decision--- Schema changes are an append-only ordered manifest. PostgreSQL records each- exact `version`, `name`, and SHA-256 checksum in `schema_migrations`.-- An applied entry may never be edited or reordered. A checksum mismatch,- missing prefix, or unknown future entry fails closed.-- One candidate-image Kubernetes Job runs `npm run migrate` before the Deploy- workflow mutates the application Deployment. Failure leaves the current- ReplicaSet untouched.-- The migration Job copies the production Cloud SQL proxy and workload identity- settings, runs required index validity gates, and exits before rollout.-- Application Pods contain no migration init container. Startup performs one- read-only ledger query and accepts only the schema range declared by that- application build.-- An advisory lock remains defense in depth for accidentally duplicated deploy- jobs; it is no longer coordination among application replicas.-- Future schema changes use expand/contract sequencing. A migration must remain- compatible with the old application revision serving during a rolling- update; destructive contraction occurs only after the old revision can no- longer be restored.--## Consequences--- Restarting or scaling the API does not acquire DDL locks and cannot replay- historical backfills.-- Deployment has an explicit schema promotion gate with durable, auditable- version identity and required-index health.-- A first adoption run executes the frozen legacy baseline once and records it.- Subsequent runs read the ledger and execute only newly appended versions.- The baseline is sent one statement at a time with per-statement lock- retries: as a single implicit transaction it holds AccessExclusiveLocks on- ~30 tables until commit and deadlocks against live traffic on every attempt- (the first v0.14.0 adoption Job failed that way). Every baseline statement- is idempotent, so a rerun after a partial batch resumes safely; versions- after the baseline keep their single-transaction atomicity.-- Local development and manual Kubernetes installation must run- `npm run migrate` before starting the server; `npm run dev:all` performs that- one explicit step automatically.-- Rollback compatibility is a release-design responsibility. A schema change- outside the old build's declared range can intentionally prevent unsafe- rollback rather than letting an old binary interpret unknown state.--## Alternatives considered--- **Keep DDL on every startup behind an advisory lock:** rejected because the- lock serializes writers but does not separate schema failure from replica- availability or prevent repeated hot-table lock attempts.-- **Keep a per-Pod migration init container:** rejected because every surge,- restart, and scale-out becomes a schema owner and delays readiness.-- **Infer currency from tables, columns, or sentinel indexes:** rejected because- absence lists drift and cannot prove which immutable transformation ran.-- **Allow checksum drift for idempotent SQL:** rejected because changing the- meaning of an applied version destroys reproducibility and rollback evidence.diff --git a/docs/decisions/0004-normalized-conversation-membership.md b/docs/decisions/0004-normalized-conversation-membership.mddeleted file mode 100644index 07fdde4..0000000--- a/docs/decisions/0004-normalized-conversation-membership.md+++ /dev/null@@ -1,73 +0,0 @@-# ADR 0004: Normalized conversation membership as authorization truth--- Status: Accepted-- Date: 2026-09-03--## Context--`conversations.members` was a JSONB array used simultaneously as an API-projection, an authorization boundary, and a routing index. It could not carry-tenant-scoped foreign keys. Invite, leave, and kick paths also rewrote the-whole array, so overlapping requests could lose a change, resurrect a removed-member, or commit a system notice that disagreed with the effective access-state. Correctness depended on every caller remembering the same predicates-and Redis publishing happened outside the membership transaction.--Email threads additionally used synthetic `external:<addr>` author markers in-the array. Those markers identify message authors, but they are not tenant-participants and must never become authorization principals.--## Decision--- `conversation_members` is the sole authorization and routing source. Its- composite foreign keys bind each row to both the conversation tenant and an- actual participant in that tenant.-- Membership changes insert or delete one normalized row while holding active- participant locks followed by the conversation lock. Authorization is- re-read in a separate statement after the conversation lock is acquired so- a lock wait cannot retain an obsolete statement snapshot.-- The membership row, derived JSONB projection, system audit message, sequence- counter, and realtime outbox record commit in one PostgreSQL transaction.-- `conversations.members` remains only as a response-shape compatibility- projection for the new application. A database function rebuilds it from- normalized rows. During the expand release, a trigger translates writes from- the previous application revision into tenant-validated normalized rows and- canonicalizes the projection under the same row lock.-- A conversation insert trigger converts the initial JSONB input into- normalized rows. Synthetic external email author markers are discarded;- any other missing or cross-tenant participant fails closed.-- Production authorization, recipient fan-out, member counts, and direct-pair- lookup use the normalized indexes. The former JSONB GIN path and its- session-level query-planner override are no longer runtime dependencies.--## Consequences--- PostgreSQL enforces tenant integrity and prevents orphan or foreign member- identifiers rather than relying on route-level convention.-- Concurrent invites, leaves, and kicks serialize without whole-array lost- updates; a failed audit or outbox write rolls the membership change back.-- Participant tenant reassignment must first detach the participant from old- conversations. This explicit cleanup replaces stale cross-tenant member ids.-- Legacy and API consumers may continue reading `conversations.members`, but- new code must not use that projection for authorization or routing.-- The expand release retains the legacy JSONB index and synchronization ingress- so the previous revision can serve safely during rollout or rollback. A later- contract release may reject projection writes and drop that index only after- the pre-0002 revision is outside the rollback window.-- Migration 0002 backfills and canonicalizes existing rows. It rejects unknown- internal member ids while intentionally removing external email markers.--## Alternatives considered--- **Keep JSONB and centralize array helpers:** rejected because application- helpers cannot provide foreign keys, prevent ad hoc writes, or give the- planner a relational tenant/member index.-- **Add only a JSONB projection trigger:** rejected because the array would- remain the writable truth and every authorization query would still depend- on denormalized containment semantics.-- **Use Redis sets as membership truth:** rejected because message, audit, and- access changes need one durable transaction; Redis cannot share PostgreSQL's- commit boundary.-- **Store external email addresses as participants:** rejected because an- inbound address is an author identity, not an authenticated workspace- principal, and would expand the authorization domain unnecessarily.diff --git a/docs/decisions/0005-secure-claude-provider-bootstrap.md b/docs/decisions/0005-secure-claude-provider-bootstrap.mddeleted file mode 100644index 1c7798c..0000000--- a/docs/decisions/0005-secure-claude-provider-bootstrap.md+++ /dev/null@@ -1,67 +0,0 @@-# ADR 0005: Bootstrap custom Claude providers without widening Agent tools--- Status: Accepted-- Date: 2026-09-05--## Context--Secure Claude BYOA turns use Claude Code's `--restricted` mode. It correctly-ignores user/project settings so an Agent cannot acquire the operator's hooks,-MCP servers, permissions, or tool configuration. It also ignores the `env`-section of `~/.claude/settings.json`, where tools such as CC Switch commonly-store `ANTHROPIC_BASE_URL` and an authentication value.--That produced a split-brain result: `claude auth status` and an ordinary-terminal turn worked, while the same account under Cumora reported `Not logged-in`. If authentication was bypassed, an unpinned Agent could still receive the-server's Anthropic deployment model even though the custom endpoint owned a-different model namespace.--## Decision--- In secure mode, the daemon reads only a fixed allowlist from Claude's user- settings: `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`,- `ANTHROPIC_BASE_URL`, and `ANTHROPIC_SMALL_FAST_MODEL`.-- Those values enter only the trusted Claude core process environment. The- inline restricted policy denies every imported name to model-spawned- subprocesses. Cumora never serializes the values into argv, its logs, the- Agent home, model-catalog reports, or its server.-- Explicit daemon environment values take precedence over the settings file.- Missing, malformed, relative-config-root, or oversized settings fail soft and- preserve Claude's native first-party OAuth/keychain behavior.-- Claude model discovery reports the configured defaults and whether a custom- endpoint owns an unnamed default. For an Agent without an explicit model pin,- that custom-provider default wins over a deployment-level vendor pin. The- same applies to its fast model; if either default is unnamed, no model flag is- injected. Explicit `participants.model` / `fast_model` values remain highest- priority, and older daemons without this signal retain the deployment- fallback.--## Consequences--- A custom Claude endpoint configured through the ordinary Claude settings file- works without enabling `CUMORA_BYOA_ALLOW_UNSANDBOXED`.-- The operator's complete Claude settings remain outside the Agent boundary;- executable configuration such as hooks, MCP servers, permissions, and- arbitrary environment entries is still ignored.-- The daemon is now trusted to read four provider bootstrap values from a- user-owned file. It already owns the Claude process and inherited equivalent- values when exported by the operator; this changes their source, not the- process trust boundary.-- A custom provider that needs additional environment variables remains- unsupported in secure mode until each variable receives an explicit security- review and is added to the allowlist.--## Alternatives considered--- **Enable unsandboxed compatibility mode:** rejected because authentication- availability must not grant model-generated tools host file, credential, and- network authority.-- **Pass the complete user settings file to restricted Claude:** rejected- because it restores the hooks, permissions, MCP, and tool configuration that- restricted mode intentionally excludes.-- **Embed provider values in `--settings` JSON:** rejected because secrets would- become visible in the process command line and diagnostic captures.-- **Always remove deployment model pins:** rejected because first-party BYOA- fleets use them to keep behavior stable across CLI upgrades. Only observed- custom-provider ownership takes precedence.diff --git a/docs/decisions/0006-bind-runtime-tokens-to-agent-placement.md b/docs/decisions/0006-bind-runtime-tokens-to-agent-placement.mddeleted file mode 100644index b069d61..0000000--- a/docs/decisions/0006-bind-runtime-tokens-to-agent-placement.md+++ /dev/null@@ -1,64 +0,0 @@-# ADR 0006: Bind runtime tokens to the exact Agent placement--- Status: Accepted-- Date: 2026-09-05--## Context--Agent runtime JWTs originally pinned only the globally stable Agent id and its-workspace. The runtime server rechecked that workspace and active-participant-state on every request, which revoked a token after a cross-workspace move but-not after a move between Computers in the same workspace. Revoking a paired-Computer likewise revoked its device credential while already minted Agent-JWTs remained usable until their one-hour expiry.--Checking only the Computer id is insufficient. Moving an Agent away and back to-the same Computer would make an older token valid again, and placement changes-can be written by onboarding and repair paths in addition to the main assignment-API.--## Decision--- Every participant row carries an opaque `runtime_assignment_id`. PostgreSQL- replaces it whenever the participant's workspace, Computer, kind, or active- departure state changes.-- Runtime JWTs pin `computerId` and `assignmentId` in addition to the Agent and- workspace ids. Tokens missing either placement claim are rejected.-- Every runtime request compares all four values with the live participant row.- Assigned Computers must also still exist in the same workspace and not be- revoked. The same check protects each long-lived wake stream before a ping or- event is delivered.-- Both BYOA daemons and managed pods mint tokens from the database placement- snapshot. A managed pod spawn aborts if that placement changes before the- Kubernetes mutation.-- The assignment rotation is a database trigger rather than application-only- bookkeeping so bulk and administrative SQL cannot accidentally omit it.--## Consequences--- Moving or offboarding an Agent and revoking its Computer invalidate every- previously minted runtime token immediately, including move-away/move-back- sequences.-- Deployment invalidates runtime tokens minted by older builds because they do- not carry placement claims. BYOA daemons obtain a new token from their- device-authenticated endpoint; managed pods are recreated through the normal- scheduler path.-- Every runtime request adds one indexed participant/Computer authorization- lookup, extending the existing live workspace check rather than adding a- second query.-- A future placement dimension that should revoke runtime authority must be- added to the trigger condition and, when independently meaningful, to the- signed claims.--## Alternatives considered--- **Bind only the workspace:** rejected because a removed or replaced host in- that workspace retains authority until token expiry.-- **Bind only the Computer id:** rejected because an away-and-back assignment- revives the old token.-- **Rotate only in `assignAgentToComputer`:** rejected because free-tier- onboarding, repair tooling, and administrative migrations also update- placement.-- **Keep a server-side JWT denylist:** rejected because it adds distributed- mutable state and cleanup work when the participant row is already the live- authorization source of truth.diff --git a/docs/decisions/0007-claude-turn-preferences.md b/docs/decisions/0007-claude-turn-preferences.mddeleted file mode 100644index a5ca739..0000000--- a/docs/decisions/0007-claude-turn-preferences.md+++ /dev/null@@ -1,60 +0,0 @@-# ADR 0007: Inherit Claude model preferences inside the restricted boundary--- Status: Accepted-- Date: 2026-09-05-- Amends: [ADR 0005](0005-secure-claude-provider-bootstrap.md), its bootstrap-only allowlist--## Context--The provider bootstrap fix restored authentication and model routing but did-not restore `effortLevel`. Restricted Claude ignores user settings, and Cumora-also defaulted every agent turn to `MAX_THINKING_TOKENS=0`. This silently-discarded the operator's reasoning preferences even for substantial agent work.-New Claude versions also save effort in `modelSettings`, so inheriting only the-global field would miss settings written by the native effort picker.--## Decision--- Import validated `effortLevel`, per-model effort entries,- `alwaysThinkingEnabled`, and `language` into Cumora's inline turn settings.- Rebuild nested model entries from allowed fields; never merge arbitrary- user settings into permissions, hooks, tools, or the sandbox.-- Import a fixed turn-only environment allowlist for effort, thinking budget,- output limit, and thinking/adaptive compatibility switches. Explicit daemon- environment values win. Every imported environment name remains denied to- model-spawned subprocesses. Provider credentials remain outside argv.-- Stop forcing thinking off for agent turns. Preserve an explicit disabled- setting, and otherwise let Claude choose its native default and apply its- model-specific and managed-policy rules. Inherit preferences, not an- assertion that the provider will honor a particular reasoning level.-- Preserve Opus/Sonnet/Haiku provider model aliases in the core environment.- The current Haiku alias is also used for catalog/triage fast-model defaults,- with the legacy small-fast setting as fallback; Agent pins still win.-- Keep triage and doctor thinking off and separate from turn preferences.- Read preferences when a process is spawned, for both one-shot and persistent- sessions; an existing persistent session requires a daemon restart to pick- up local edits.--## Consequences--Explicit high-effort or thinking preferences can increase turn latency and-cost; that is the operator's choice. Missing preferences no longer imply an-unadvertised Cumora thinking-off policy. `xhigh` plus thinking disabled can-still become `high` for Opus 5 under Claude's native compatibility handling.-The public server model catalog never receives these personal turn preferences.--## Alternatives considered--- **Load the complete settings file:** rejected; restores executable settings- and tool authority excluded by restricted mode.-- **Hard-code `--effort xhigh` or turn thinking on:** rejected; overrides- per-model, environment, and explicitly disabled preferences.-- **Forward output styles, fast mode, or ultracode:** deferred; styles can load- user-authored role prompts, and speed/workflow modes change billing or- orchestration beyond reasoning preference inheritance.--## References--- [Claude effort and thinking](https://code.claude.com/docs/en/model-config#adjust-effort-level)-- [Claude settings reference](https://code.claude.com/docs/en/settings-reference)-- [Claude environment variables](https://code.claude.com/docs/en/env-vars)diff --git a/docs/email.md b/docs/email.mdindex f98a61b..83ac8b8 100644--- a/docs/email.md+++ b/docs/email.md@@ -2,10 +2,12 @@Every agent has a real address (`<participantId>.<companySlug>@<EMAIL_DOMAIN>`)and can both send and receive mail. Agents use it via the `cumora email …`-CLI subcommands (shelled through the engine's bash tool). Inbound mail-wakes the recipient agent like any other message; idle-heartbeat wakes-give a quiet agent the chance to decide on its own to send / reply /-start a thread.+CLI subcommands, which reach the server over the fixed Cumora CLI bridge — in+secure mode that's the `cli(argv)` MCP tool, since the engine has no Bash tool+at all; the `cumora` shell shim only exists in unsandboxed compatibility mode.+Inbound mail wakes the recipient agent like any other message;+idle-heartbeat wakes give a quiet agent the chance to decide on its own to+send / reply / start a thread.## Architecture@@ -97,9 +99,11 @@ EMAIL_DOMAIN=cumora.aiEMAIL_INBOUND_HMAC_SECRET=<openssl rand -hex 32>```-Run `npm run migrate` once, then restart the server. The versioned migration-adds the `participants.email`, `email_messages`, and `email_contacts` tables;-normal server startup only verifies the migration ledger.+Run `npm run migrate` once, then restart the server. The `participants.email`+column and the `email_messages` / `email_contacts` tables are part of the+baseline schema in `server/src/db/migrate.ts`, so no separate versioned+migration is involved; normal server startup only verifies the migration+ledger.### 2. Resenddiff --git a/server/k8s/generic-device-plugin.note b/server/k8s/generic-device-plugin.noteindex 07044b6..0cb8b09 100644--- a/server/k8s/generic-device-plugin.note+++ b/server/k8s/generic-device-plugin.note@@ -28,7 +28,7 @@# The agent Pod manifest (orchestrator.ts) requests this resource# via `resources.limits["devic.es/fuse"]: 1` and adds CAP_SYS_ADMIN.# No `privileged: true`. Runtime admission still applies the lower-# app-level AGENT_POD_ADMISSION_MAX cap (default 200), so this device+# app-level AGENT_POD_ADMISSION_MAX cap (default 40), so this device# count is not the effective production pod ceiling.## DaemonSet lands in the `kube-system` namespace by default. Itdiff --git a/server/k8s/gke.md b/server/k8s/gke.mdindex 4fb6961..8cd6932 100644--- a/server/k8s/gke.md+++ b/server/k8s/gke.md@@ -6,17 +6,21 @@ Memorystore for Redis. The end state matches what we verified inOrbStack locally — server in K8s, per-agent Pods on-demand,FUSE-backed workspace via the cumora-fuse → /runtime/fs/* path.-Variables you'll fill in (replace `REPLACE-*` placeholders as you go):+Variables you'll fill in (replace `REPLACE-*` placeholders as you go). The+values shown are the ones production actually uses — note that the cluster is+**zonal**, so every `gcloud container clusters …` call takes `--location`+(a zone), not `--region`:```-PROJECT=your-gcp-project-id-REGION=us-central1-CLUSTER=cumora-prod+PROJECT=cumora # GCP project id+REGION=us-west2 # region for Cloud SQL / Memorystore / AR+LOCATION=us-west2-a # ZONE of the cluster (see --location below)+CLUSTER=cumora-prod-z+AR_REPO=cumora # Artifact Registry repositorySQL_INSTANCE=cumora-pg # Cloud SQL instance nameSQL_DB=cumora # database within the instanceSQL_USER=cumora # PG userREDIS_INSTANCE=cumora-redis # Memorystore instance-QUAY_USER=... # quay.io credentials (or use Artifact Registry)```---@@ -24,31 +28,40 @@ QUAY_USER=... # quay.io credentials (or use Artifact Registry)## 1. Cluster + image registry```sh-# Standard GKE cluster with Workload Identity enabled+# Standard GKE cluster with Workload Identity enabled.+# --location takes a zone for a zonal cluster, a region for a regional one.gcloud container clusters create $CLUSTER \- --region $REGION \+ --location $LOCATION \--workload-pool=$PROJECT.svc.id.goog \--release-channel regular \--num-nodes 2-gcloud container clusters get-credentials $CLUSTER --region $REGION+gcloud container clusters get-credentials $CLUSTER --location $LOCATION```-Push the two cumora images (use git sha or semver, NOT `:dev`):+Push the two cumora images to **Artifact Registry** — this is what+`build.yml` and `deploy.yml` use, and what production runs (use git sha or+semver, NOT `:dev`):```shTAG=$(git rev-parse --short HEAD)+AR=$REGION-docker.pkg.dev/$PROJECT/$AR_REPO++gcloud auth configure-docker $REGION-docker.pkg.devdocker build -f server/docker/cumora-server.Dockerfile \- -t quay.io/yetoneful/cumora-server:$TAG .-docker push quay.io/yetoneful/cumora-server:$TAG+ -t $AR/server:$TAG .+docker push $AR/server:$TAGnode server/src/scripts/build-agent-bundle.mjsdocker build -f server/docker/agent-computer.Dockerfile \- -t quay.io/yetoneful/cumora-agent-computer:$TAG .-docker push quay.io/yetoneful/cumora-agent-computer:$TAG+ -t $AR/agent-computer:$TAG .+docker push $AR/agent-computer:$TAG```+> Older revisions of this guide pushed to `quay.io/yetoneful/cumora-*`. That+> path is legacy: nothing in CI or production reads it any more.+Substitute `REPLACE-TAG` in `cumora-server.gke.yaml` with `$TAG`.When a change touches either the runtime API contract or@@ -78,10 +91,9 @@ To wipe a permanently off-boarded agent's PVC, call the orchestrator's`deleteChromeProfilePvc(agentId)` helper. The normal idle-exit pathdeliberately leaves the PVC bound so the next pod re-uses it.-If using Artifact Registry instead of quay.io, push to-`$REGION-docker.pkg.dev/$PROJECT/cumora/...` and drop the-`imagePullSecrets` / quay-pull steps below (GKE nodes pull from AR-with their default service account automatically).+GKE nodes pull from Artifact Registry with their default service account, so+no `imagePullSecrets` are needed. If you are resurrecting the legacy quay.io+path instead, you'll also need the `quay-pull` secret described in step 4.## 2. Cloud SQL + Memorystore@@ -151,11 +163,12 @@ kubectl create secret generic cumora \--from-literal=OPENAI_API_KEY="sk-..." \--from-literal=AGENT_RUNTIME_SECRET="$(openssl rand -hex 32)"-# Image pull secret for quay.io (skip if you switched to AR)-kubectl create secret docker-registry quay-pull \- --docker-server=quay.io \- --docker-username=$QUAY_USER \- --docker-password="$QUAY_PASSWORD"+# Not needed on the Artifact Registry path above. Only for the legacy+# quay.io registry, and only if you also set QUAY_USER / QUAY_PASSWORD:+# kubectl create secret docker-registry quay-pull \+# --docker-server=quay.io \+# --docker-username=$QUAY_USER \+# --docker-password="$QUAY_PASSWORD"```## 5. Generic Device Plugin (for FUSE)@@ -178,11 +191,20 @@ kubectl describe node <any-node> | grep devic.es/fuse# Allocatable: devic.es/fuse: 800```-The server still applies an app-level `AGENT_POD_ADMISSION_MAX`-ceiling (default `200`) before creating agent pods. Keep that lower+The server also applies an app-level `AGENT_POD_ADMISSION_MAX`+ceiling (default `40`) before creating agent pods. Keep that lowerthan the advertised FUSE count so bursts are bounded by Cumora's realCPU, memory, API-server, and provider concurrency budget.+> **The cluster-wide FUSE ceiling is inert under the shipped RBAC.**+> `getClusterFuseUtilization()` shells out to `kubectl get nodes`, and when+> that call fails it fails *open* — the cap becomes `Infinity`. Neither+> `cumora-server.gke.yaml` nor `cumora-server.orbstack.yaml` grants node reads:+> they bind a namespaced `Role` over `pods`, `pods/log`, and+> `persistentvolumeclaims` only. Until a `ClusterRole` ++> `ClusterRoleBinding` for `nodes: [get, list]` is added, only+> `AGENT_POD_ADMISSION_MAX` actually bounds admission.+On **GKE Autopilot**: the plugin DaemonSet works but Autopilot mayreject `securityContext.capabilities.add: [SYS_ADMIN]` depending onadmission policy. If so, switch to **GKE Standard**, OR fall back@@ -206,6 +228,24 @@ kubectl rollout status deployment/cumora-serverThe application Pods only read `schema_migrations` and refuse to start outsidetheir supported version range. They never execute DDL during startup.+> **Patch the liveness probe after applying.** The checked-in manifest still+> points `livenessProbe` at `/api/health`, which touches the database. The+> Deploy workflow patches it to `/api/livez` on every rollout precisely+> because a DB-backed liveness probe turned a connection-pool stall into a+> restart loop (2026-05-27). A manual `kubectl apply` re-introduces the bad+> config, so follow it with:+>+> ```sh+> kubectl patch deployment/cumora-server --type=json -p='[{+> "op": "replace",+> "path": "/spec/template/spec/containers/0/livenessProbe/httpGet/path",+> "value": "/api/livez"+> }]'+> ```+>+> Readiness should stay on `/api/health` — that one *should* pull a pod out of+> rotation when its dependencies are gone.+## 7. Verify end-to-end```shdiff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex 6e1cea8..6e5e9f8 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -2134,9 +2134,10 @@ export type BaselineStatementClient = { query(sql: string): Promise<unknown> }* AccessExclusiveLock and the transaction HOLDS all ~30 of them until commit.* Under sustained production traffic those waits close into a cycle and* Postgres aborts the whole batch with 40P01 — on every attempt. That is how- * the first ADR 0003 adoption Job (v0.14.0, 2026-09-03) failed eight times in- * a row without applying anything: the ledger was empty, so version 1 had to- * run, and version 1 could never commit. Before ADR 0003 the same batch ran on+ * the first versioned-migration adoption Job (v0.14.0, 2026-09-03) failed+ * eight times in a row without applying anything: the ledger was empty, so+ * version 1 had to run, and version 1 could never commit. Before versioned+ * migrations the same batch ran on* every boot and only ever got through production because a sentinel probe let* a deadlocked no-op pass; that hatch is gone, and it would not have helped* here anyway because the baseline had real columns to add.@@ -2145,7 +2146,8 @@ export type BaselineStatementClient = { query(sql: string): Promise<unknown> }* immediately, so a no-op cannot participate in a lock cycle, and a real* change waits at most `lock_timeout` (55P03) before this loop retries just* that statement. Every statement in the baseline is idempotent (it ran on- * every application boot before ADR 0003), so a statement retry — or a rerun+ * every application boot before the ledger existed), so a statement retry — or+ * a rerun* of the Job after a mid-batch failure — resumes safely; ensureSchema records* version 1 only after the entire batch completed. Versioned migrations after* the baseline keep their single-transaction atomicity.@@ -2345,7 +2347,7 @@ export async function checkConversationMembersResolvable(client: MigrationPrechenullCompanies > 0 ? `${nullCompanies} conversation(s) have no company_id` : null,].filter(Boolean).join(' and ')throw Object.assign(- new Error(`migration 0002 precondition failed: ${detail} — repair the data, then rerun the migration Job (see the precheck lines above and ADR 0004)`),+ new Error(`migration 0002 precondition failed: ${detail} — repair the data, then rerun the migration Job (see the precheck lines above)`),{ code: '23503' },)}@@ -2538,9 +2540,11 @@ async function buildConcurrentIndexes(client: import('pg').PoolClient): Promise<const indexes: Array<{ name: string; create: string }> = [{name: 'idx_conversations_members_gin',- // members @> [agentId] containment — the hottest read path (loadInbox /- // loadContext / inbox-triage, called per wake + poll). Without it each- // call seq-scans every conversation and saturates the pool.+ // Retained for the expand-release rollback window only. `loadInbox` /+ // `loadContext` / inbox-triage no longer read `members @> [agentId]` —+ // they resolve membership through the normalized `conversation_members`+ // participant index (see inproc-client.ts). Drop this index once the+ // rollback window closes.create: `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_conversations_members_ginON conversations USING gin (members jsonb_path_ops)`,},diff --git a/server/src/migrate-bin.ts b/server/src/migrate-bin.tsindex 5116363..1c290d1 100644--- a/server/src/migrate-bin.ts+++ b/server/src/migrate-bin.ts@@ -15,8 +15,8 @@* spec:* containers:* - name: migrate- * image: ghcr.io/yetoneful/cumora-server:<version>- * command: ["node", "/app/migrate-bin.cjs"]+ * image: us-west2-docker.pkg.dev/cumora/cumora/server@sha256:<digest>+ * command: ["npm", "run", "migrate"]* env:* - { name: DATABASE_URL, valueFrom: { secretKeyRef: ... } }*diff --git a/workers/email-gate/README.md b/workers/email-gate/README.mdindex 7b1a4c4..8beed28 100644--- a/workers/email-gate/README.md+++ b/workers/email-gate/README.md@@ -10,9 +10,9 @@ The worker:1. Rejects mail (`550`) for any recipient outside `EMAIL_ROOT_DOMAINS`.2. Reads the raw RFC 5322 message and parses it with `postal-mime`.-3. Builds a JSON payload (message-id, in-reply-to, references, from, to, cc, subject, text, html, raw size).+3. Builds a JSON payload (message-id, in-reply-to, references, from, to, cc, subject, text, html, raw size, `autoSubmitted` per RFC 3834, and `attachments[]` as base64 — capped at 10 MB per attachment and 18 MB in total).4. HMAC-signs the payload with `EMAIL_INBOUND_HMAC_SECRET` and POSTs to `CUMORA_INBOUND_URL`.-5. Translates the server's response into accept / bounce / tempfail.+5. Translates the server's response into accept or reject. Every rejection is **permanent** (`message.setReject`) — including the 5xx branch, which arguably should tempfail so the sender's MTA retries. See the note in `src/index.ts`.Outbound mail goes through Resend on the server side, **not** this worker — Cloudflare Email Workers can't send mail.diff --git a/workers/email-gate/src/index.ts b/workers/email-gate/src/index.tsindex 8316a8b..ee102da 100644--- a/workers/email-gate/src/index.ts+++ b/workers/email-gate/src/index.ts@@ -5,7 +5,8 @@* 1. Reject (550) if the recipient domain isn't in EMAIL_ROOT_DOMAINS.* 2. Stream the raw MIME, parse with postal-mime.* 3. Build a JSON payload (message-id, in-reply-to, references, from,- * to, cc, subject, text, html, raw size).+ * to, cc, subject, text, html, raw size, autoSubmitted, and+ * attachments[] as base64 — see MAX_ATTACHMENT_BYTES / the total cap).* 4. Sign with HMAC-SHA256(EMAIL_INBOUND_HMAC_SECRET, body) and POST* to CUMORA_INBOUND_URL.* 5. Reject (550) if the server says "no recipient resolved" so the@@ -235,7 +236,15 @@ export default {return}if (!res.ok) {- // 4xx other than 404, or 5xx → tempfail so the sender's MTA retries.+ // 4xx other than 404, or 5xx.+ //+ // KNOWN GAP: this *should* tempfail on 5xx so the sender's MTA retries,+ // but setReject() is a PERMANENT rejection — a single upstream blip+ // loses the mail for good. Cloudflare issues a temporary failure when+ // the handler throws, so the fix is to throw here on 5xx and keep+ // setReject for 4xx. Not changed yet because it flips real delivery+ // behaviour and wants its own test + rollout.+ //// Reading the body keeps the response from leaking; ctx.waitUntil so// we don't block the email return.ctx.waitUntil(res.text().then((t) => console.error(`[email-gate] upstream ${res.status}: ${t.slice(0, 400)}`)))