Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

chore: clean up deployment config

Rufus5bd5f2824c4f
diff --git a/.claude/agents/anvil-security-reviewer.md b/.claude/agents/anvil-security-reviewer.md
index e0cf5f00..61b26c89 100644
--- a/.claude/agents/anvil-security-reviewer.md
+++ b/.claude/agents/anvil-security-reviewer.md
@@ -21,7 +21,7 @@ Examine `git --no-pager diff --staged`. Look specifically for:
5. Unvalidated inputs reaching dangerous sinks
6. Error handling that leaks sensitive information
7. (Open Executive only — if the diff touches `prompts/cache_manager.py`, `prompts/executive_persona.py`, `memory/company_profile.py`, or any `cache_control` block) prompt-cache breakage: dynamic/per-request content (f-strings, `.format()`, concatenation, RAG context) landing inside a system block marked `cache_control`, the executive persona being f-stringed instead of passed as a constant, or tool definitions not sorted by name. Treat a cache break as HIGH — it silently ~10x's API cost.
-8. (Open Executive only) data exfiltration into git: **any removed or narrowed rule in `.gitignore`** (it protects `company/`, `packages/core/company/`, `.env`, `*.db`, `scripts/fly-secrets.sh`, `scripts/secrets.*.sh`, and `.gworkspace-credentials/` — the live refresh token); or a file under either `company/` path, a real `.env`, a SQLite file, or one of those secrets scripts appearing in the diff (only possible via `git add -f`); or real-looking credentials or company data in added lines of any file. `.env.example` edits with placeholder values are legitimate — do not flag them. Treat a genuine hit as CRITICAL.
+8. (Open Executive only) data exfiltration into git: **any removed or narrowed rule in `.gitignore`** (it protects `company/`, `packages/core/company/`, `.env`, `*.db`, `scripts/secrets.*.sh`, `.gworkspace-credentials/` — the live refresh token — and the untracked deployment config); or a file under either `company/` path, a real `.env`, a SQLite file, or one of those secrets scripts appearing in the diff (only possible via `git add -f`); or real-looking credentials or company data in added lines of any file. `.env.example` edits with placeholder values are legitimate — do not flag them. Treat a genuine hit as CRITICAL.
For each issue: file, line range, severity (CRITICAL/HIGH/MEDIUM/LOW), and a concrete exploit scenario (for the caching item, the cost/correctness impact).
If nothing: state "No security issues found." Do not invent issues.
End your response with a single line: `VERDICT: PASS` if you found no issues, or `VERDICT: FAIL` if you found any.
diff --git a/.claude/skills/flyctl/SKILL.md b/.claude/skills/flyctl/SKILL.md
deleted file mode 100644
index 639a3425..00000000
--- a/.claude/skills/flyctl/SKILL.md
+++ /dev/null
@@ -1,110 +0,0 @@
----
-name: flyctl
-description: Operate the two Fly.io apps for Open Executive (openexec-api-dev, openexec-ui-dev). Use this skill whenever the user asks to tail logs, SSH for SQLite inspection, list/set/unset secrets, check deploy status, restart machines, deploy, or rotate AUTH_SECRET. Covers the exact commands, SQLite paths, and known gotchas for this project. Tiered safety: read-only runs freely; destructive needs explicit user confirmation.
----
-
-# flyctl
-
-Quick-reference cheatsheet for operating Open Executive's two Fly.io apps. Pair skill: `openexec-api` (HTTP curl recipes against the FastAPI surface).
-
-## Apps
-
-| App | Stack | Key secrets | URL |
-|---|---|---|---|
-| `openexec-api-dev` | FastAPI (Python, port 8000) | `ANTHROPIC_API_KEY`, `HONCHO_API_KEY`, `HONCHO_BASE_URL` (optional), `BACKEND_SHARED_SECRET` | https://openexec-api-dev.fly.dev |
-| `openexec-ui-dev` | Next.js 15 (NextAuth + Google OAuth) | `AUTH_SECRET`, `AUTH_GOOGLE_ID/SECRET`, `BACKEND_SHARED_SECRET`, `BACKEND_URL` | https://openexec-ui-dev.fly.dev |
-
-No production-only apps exist today. Anything ending `-dev` is the live shared deployment.
-
-## Safety tiers
-
-- **Green — auto-run.** Read-only. `flyctl status / releases / logs / secrets list`; `flyctl ssh console -C` with a `SELECT`-only sqlite query.
-- **Yellow — confirm once per session.** `flyctl ssh console` interactive, `flyctl apps restart`, redeploys of a known image.
-- **Red — print the exact command and wait for explicit "go" each time, no chaining.** `flyctl secrets set/unset`, `flyctl machine destroy`, `flyctl apps destroy`, any `UPDATE/DELETE/INSERT/DROP` over ssh, `AUTH_SECRET` rotation, `flyctl deploy` from an unknown ref.
-
-If the user previously said "go" for a red command, it does NOT authorize the next red command. Each red command needs its own "go."
-
-## Green: status, logs, secrets list
-
-```bash
-flyctl status -a openexec-api-dev
-flyctl status -a openexec-ui-dev
-
-flyctl releases -a openexec-api-dev | head -10
-
-# Live tail
-flyctl logs -a openexec-api-dev
-
-# One-shot capture (recent only, exits)
-flyctl logs -a openexec-api-dev --no-tail
-
-# Secret NAMES only — never echoes values
-flyctl secrets list -a openexec-api-dev
-```
-
-## Green: SQLite inspection over SSH (SELECT-only)
-
-The api app's `/data` volume layout:
-
-| Path | Contents |
-|---|---|
-| `/data/episodic_memory.db` | chat messages, sessions, **people** (NOT a separate file), audit_log incl. peer_memory rows, scheduled_actions, alerts, decisions, initiatives, advice |
-| `/data/chroma/` | ChromaDB vector store |
-| `/data/_user_backup/.honcho_active_workspace.json` | current Honcho workspace override (null = use env default) |
-| `/data/_user_backup/` | fixture snapshot before demo loads |
-
-**SSH-with-shell gotcha.** `flyctl ssh console -a … -C "<cmd>"` does NOT spawn a shell, so pipes, redirects, quoted sqlite args fail silently or get mangled. Always wrap multi-token commands as `-C 'sh -c "<cmd>"'`.
-
-```bash
-# Recent peer_memory audit rows (Honcho sync_turn / prefetch / workspace_reset)
-flyctl ssh console -a openexec-api-dev -C 'sh -c "sqlite3 /data/episodic_memory.db \"SELECT ts, json_extract(details_json,'\''$.op'\''), json_extract(details_json,'\''$.outcome'\'') FROM audit_log WHERE event_type='\''peer_memory'\'' ORDER BY id DESC LIMIT 10;\""'
-
-# People roster
-flyctl ssh console -a openexec-api-dev -C 'sh -c "sqlite3 /data/episodic_memory.db \"SELECT id, name, email, archived_at FROM people ORDER BY id;\""'
-
-# Pending scheduled actions
-flyctl ssh console -a openexec-api-dev -C 'sh -c "sqlite3 /data/episodic_memory.db \"SELECT id, kind, status, run_at FROM scheduled_actions WHERE status='\''pending'\'' ORDER BY run_at LIMIT 10;\""'
-
-# Active Honcho workspace
-flyctl ssh console -a openexec-api-dev -C 'sh -c "cat /data/_user_backup/.honcho_active_workspace.json 2>/dev/null || echo null"'
-```
-
-When the query gets gnarly, drop a heredoc into an interactive ssh (yellow tier — confirm once). Avoid the temptation to escape quotes through three layers.
-
-## Red: SQLite writes
-
-Any `UPDATE / DELETE / INSERT / DROP` against `/data/episodic_memory.db` is red. Print the exact `sqlite3` command, wait for "go," do not chain.
-
-## Red: secrets set / unset
-
-`flyctl secrets set` and `unset` trigger an immediate redeploy. Tell the user this before you propose the command.
-
-```bash
-# Rotate NextAuth secret — invalidates ALL existing JWTs / logs everyone out
-flyctl secrets set AUTH_SECRET="$(openssl rand -base64 33)" -a openexec-ui-dev
-
-# Unset a secret (also redeploys)
-flyctl secrets unset HONCHO_BASE_URL -a openexec-api-dev
-```
-
-The full reference set lives in `scripts/fly-secrets.sh.example`. Reach for it when bootstrapping a new env, not for one-off changes.
-
-## Yellow: restart / deploy
-
-```bash
-# Warm restart all machines for an app
-flyctl apps restart openexec-api-dev
-
-# Redeploy current branch — needs a clean tree and CI green; never unattended
-flyctl deploy -a openexec-api-dev
-```
-
-GitHub Actions handles normal deploys via `.github/workflows/`. Manual `flyctl deploy` is a recovery tool, not the happy path.
-
-## Gotchas
-
-- `-C` bypasses the shell. Always `'sh -c "…"'` for pipes/quoted args.
-- macOS lacks `timeout(1)`. For bounded queries, use a `LIMIT` clause — don't try to wrap the ssh in a shell timeout.
-- `flyctl secrets list` redacts values. There is no `flyctl secrets get` for a reason — if you need to confirm a value, ask the user.
-- Always check whether the branch's PR is still open before pushing a follow-up: `gh pr list --head <branch> --state open --json number,url`. Mirrors global CLAUDE.md.
-- If `flyctl ssh console` hangs on connect, check `flyctl status -a <app>` — a machine may be `replacing` mid-deploy.
diff --git a/.claude/skills/openexec-api/SKILL.md b/.claude/skills/openexec-api/SKILL.md
index 7788ea7e..524cff7c 100644
--- a/.claude/skills/openexec-api/SKILL.md
+++ b/.claude/skills/openexec-api/SKILL.md
@@ -1,20 +1,20 @@
---
name: openexec-api
-description: Interact with the Open Executive FastAPI backend via curl. Use this skill when the user asks to hit /chat, /today, /people, /scheduled_actions, /architecture/*, /health/*, /fixtures/*, /audit/*, or any HTTP endpoint on openexec-api-dev.fly.dev (dev) or localhost:8000 (local). Authenticates via $BACKEND_SHARED_SECRET in the x-api-key header. Tiered safety: GET runs freely, mutating POSTs need explicit confirmation.
+description: Interact with the Open Executive FastAPI backend via curl. Use this skill when the user asks to hit /chat, /today, /people, /scheduled_actions, /architecture/*, /health/*, /fixtures/*, /audit/*, or any HTTP endpoint on the Open Executive API, local or deployed. Authenticates via $BACKEND_SHARED_SECRET in the x-api-key header. Tiered safety: GET runs freely, mutating POSTs need explicit confirmation.
---
# openexec-api
-Curl recipes against the FastAPI backend. Pair skill: `flyctl` (infra ops). When the user wants an SQLite row or to tail logs, that's flyctl. When they want to hit an HTTP route, that's this skill.
+Curl recipes against the FastAPI backend — for hitting HTTP routes, not for inspecting SQLite or tailing logs on a host.
## Base URLs
```bash
-export OE_API=https://openexec-api-dev.fly.dev # dev (default in this skill)
-export OE_API=http://localhost:8000 # local (`make dev` must be running)
+export OE_API=http://localhost:8000 # local (`make dev` must be running) — the default
+export OE_API=https://<your-host> # a deployed environment
```
-All recipes below use `$OE_API`. If the user doesn't specify, assume dev.
+All recipes below use `$OE_API`. If it is unset and the user doesn't specify, assume `http://localhost:8000`.
## Auth
diff --git a/.dockerignore b/.dockerignore
index 00ffd67f..fd4e3b7d 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,8 +1,8 @@
-# Build-context excludes for `flyctl deploy` / `docker build` (context root = repo root).
+# Build-context excludes for `docker build` (context root = repo root).
# Without this, a local deploy uploads the entire working tree (~31GB: .claude
# worktrees, .venv, node_modules, .next). The Dockerfiles install deps and build
# fresh, so none of the excluded paths are needed in the image. CI builds from a
-# clean checkout and never hit the bloat, but local `flyctl deploy` does.
+# clean checkout and never hit the bloat, but a local build does.
#
# Keep: packages/core/, packages/ui/, fixtures/, knowledge/, docker/ — i.e. only
# the paths the Dockerfiles COPY. Do NOT add those here.
@@ -24,7 +24,7 @@
**/node_modules
packages/ui/.next
-# Local runtime data & vector store (live on the Fly volume at runtime)
+# Local runtime data & vector store (live on the data volume at runtime)
**/*.db
chroma_db
**/chroma_db
diff --git a/.env.example b/.env.example
index 46d570d9..8c162be7 100644
--- a/.env.example
+++ b/.env.example
@@ -8,15 +8,15 @@ ANTHROPIC_API_KEY=sk-ant-your-key-here
# AUTH_GOOGLE_ID / AUTH_GOOGLE_SECRET come from a Google Cloud OAuth Client
# (Web application). Authorized redirect URIs must include:
# - http://localhost:3000/api/auth/callback/google
-# - https://<your-fly-app>.fly.dev/api/auth/callback/google
+# - https://<your-ui-host>/api/auth/callback/google
# ALLOWED_EMAILS = comma-separated list of Google-account emails permitted to
# sign in. Other emails (even with a valid Google login) are rejected.
# AUTH_TRUST_HOST = "true" is required when running behind a reverse proxy.
# AUTH_URL = public origin of the UI. LEAVE BLANK for local dev (localhost is
-# inferred). Required on Fly / any public deployment; AUTH_TRUST_HOST alone
+# inferred). Required on any public deployment; AUTH_TRUST_HOST alone
# isn't enough — without AUTH_URL the post-callback redirect lands on the
# container's bind address (0.0.0.0) instead of the public hostname,
-# e.g. AUTH_URL=https://your-ui-app.fly.dev
+# e.g. AUTH_URL=https://exec.example.com
AUTH_SECRET=
AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET=
@@ -35,9 +35,15 @@ BACKEND_SHARED_SECRET=
# always allowed. Deployment-only — LEAVE BLANK for local dev: with the
# shared-secret gate unset, listing a public origin here lets scripts on
# that origin read your local API with credentials.
-# On deploy: BACKEND_ALLOWED_ORIGINS=https://your-ui-app.fly.dev
+# On deploy: BACKEND_ALLOWED_ORIGINS=https://exec.example.com
BACKEND_ALLOWED_ORIGINS=
+# Declares this instance as internet-reachable. Set to 1 on every public
+# deployment: the API then REFUSES TO START without BACKEND_SHARED_SECRET,
+# instead of serving an unauthenticated API with only a log warning. Leave
+# blank for local dev. Any value other than 0/false/no/off arms the check.
+OE_PUBLIC_DEPLOYMENT=
+
# Model configuration (defaults shown)
DEFAULT_MODEL=claude-sonnet-5
DEEP_REASONING_MODEL=claude-opus-5
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 5eae5ef3..18385f6e 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -23,7 +23,7 @@ What you expected to happen instead.
## Environment
-- How you're running it: [ `make dev` / Docker / Fly deployment ]
+- How you're running it: [ `make dev` / Docker / self-hosted deployment ]
- OS:
- Python version (`python --version`):
- Relevant config (model overrides, enabled integrations) — **do not paste secrets**:
diff --git a/.github/workflows/deploy-qa.yml b/.github/workflows/deploy-qa.yml
deleted file mode 100644
index c12b58ac..00000000
--- a/.github/workflows/deploy-qa.yml
+++ /dev/null
@@ -1,89 +0,0 @@
-name: Deploy (qa)
-
-# QA is a stable environment promoted deliberately, separate from dev's
-# continuous deploy off `main`. Push (or merge) to the `qa` branch to ship a
-# vetted commit to the QA Fly apps. Honcho is hosted (not a Fly app) and
-# isolated per-environment via HONCHO_WORKSPACE_ID, so there is no honcho job.
-on:
- push:
- branches: [qa]
- workflow_dispatch:
- inputs:
- target:
- description: "Which app to deploy"
- required: true
- default: "both"
- type: choice
- options: [both, api, ui]
-
-# Mirror the dev workflow: this does NOT block on CI. Gate `qa` with branch
-# protection if you want a hard pre-deploy check.
-concurrency:
- group: deploy-qa-${{ github.ref }}
- cancel-in-progress: false
-
-permissions:
- contents: read
-
-jobs:
- changes:
- name: Detect changed paths
- runs-on: ubuntu-latest
- outputs:
- api: ${{ steps.filter.outputs.api }}
- ui: ${{ steps.filter.outputs.ui }}
- steps:
- - uses: actions/checkout@v7
- with:
- fetch-depth: 2
- - id: filter
- uses: dorny/paths-filter@v4
- with:
- filters: |
- api:
- - 'packages/core/**'
- - 'knowledge/**'
- - 'docker/Dockerfile'
- - 'fly.api.qa.toml'
- - '.github/workflows/deploy-qa.yml'
- ui:
- - 'packages/ui/**'
- - 'docker/Dockerfile.ui'
- - 'fly.ui.qa.toml'
- - '.github/workflows/deploy-qa.yml'
-
- deploy-api:
- name: Deploy API
- needs: changes
- if: >-
- (github.event_name == 'workflow_dispatch' && (inputs.target == 'both' || inputs.target == 'api'))
- || (github.event_name == 'push' && needs.changes.outputs.api == 'true')
- runs-on: ubuntu-latest
- concurrency:
- group: deploy-api-qa
- cancel-in-progress: false
- steps:
- - uses: actions/checkout@v7
- - uses: superfly/flyctl-actions/setup-flyctl@master
- - name: Deploy
- run: flyctl deploy --remote-only --config fly.api.qa.toml
- env:
- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN_API_QA }}
-
- deploy-ui:
- name: Deploy UI
- needs: changes
- if: >-
- (github.event_name == 'workflow_dispatch' && (inputs.target == 'both' || inputs.target == 'ui'))
- || (github.event_name == 'push' && needs.changes.outputs.ui == 'true')
- runs-on: ubuntu-latest
- concurrency:
- group: deploy-ui-qa
- cancel-in-progress: false
- steps:
- - uses: actions/checkout@v7
- - uses: superfly/flyctl-actions/setup-flyctl@master
- - name: Deploy
- run: flyctl deploy --remote-only --config fly.ui.qa.toml
- env:
- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN_UI_QA }}
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
deleted file mode 100644
index fff1e113..00000000
--- a/.github/workflows/deploy.yml
+++ /dev/null
@@ -1,141 +0,0 @@
-name: Deploy (dev)
-
-on:
- push:
- branches: [main]
- workflow_dispatch:
- inputs:
- target:
- description: "Which app to deploy"
- required: true
- default: "both"
- type: choice
- options: [both, api, ui, honcho]
-
-# NOTE: This workflow does NOT block on the CI workflow result. Branch
-# protection (`Require status checks to pass before merging` in the repo
-# settings) is what gates merges into main, so by the time this fires the
-# CI checks on the same SHA have already passed. If branch protection is
-# disabled the deploy will run alongside a failing CI — add a
-# `workflow_run` trigger here if that's a concern.
-concurrency:
- group: deploy-${{ github.ref }}
- cancel-in-progress: false
-
-permissions:
- contents: read
-
-jobs:
- changes:
- name: Detect changed paths
- runs-on: ubuntu-latest
- outputs:
- api: ${{ steps.filter.outputs.api }}
- ui: ${{ steps.filter.outputs.ui }}
- honcho: ${{ steps.filter.outputs.honcho }}
- steps:
- - uses: actions/checkout@v7
- with:
- fetch-depth: 2
- - id: filter
- uses: dorny/paths-filter@v4
- with:
- filters: |
- api:
- - 'packages/core/**'
- - 'knowledge/**'
- # Demo fixtures live at the repo root and are baked into the API
- # image (docker/Dockerfile COPYs fixtures/). A fixtures-only change
- # must redeploy the API or the new company won't appear in /fixtures.
- - 'fixtures/**'
- - 'docker/Dockerfile'
- # The Workspace MCP launcher is COPYed into the API image by
- # docker/Dockerfile, so a launcher-only change must redeploy the
- # API — otherwise it merges but Deploy API is skipped (the gap that
- # bit the WORKSPACE_MCP_PORT fix).
- - 'docker/workspace-mcp-launch.sh'
- - 'fly.api.toml'
- - '.github/workflows/deploy.yml'
- ui:
- - 'packages/ui/**'
- - 'docker/Dockerfile.ui'
- - 'fly.ui.toml'
- - '.github/workflows/deploy.yml'
- honcho:
- - 'docker/honcho/**'
- - 'fly.honcho.toml'
- - '.github/workflows/deploy.yml'
-
- deploy-api:
- name: Deploy API
- needs: changes
- if: >-
- (github.event_name == 'workflow_dispatch' && (inputs.target == 'both' || inputs.target == 'api'))
- || (github.event_name == 'push' && needs.changes.outputs.api == 'true')
- runs-on: ubuntu-latest
- concurrency:
- group: deploy-api
- cancel-in-progress: false
- steps:
- - uses: actions/checkout@v7
- - uses: superfly/flyctl-actions/setup-flyctl@master
- - name: Deploy
- run: flyctl deploy --remote-only --config fly.api.toml
- env:
- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN_API }}
-
- deploy-ui:
- name: Deploy UI
- needs: changes
- if: >-
- (github.event_name == 'workflow_dispatch' && (inputs.target == 'both' || inputs.target == 'ui'))
- || (github.event_name == 'push' && needs.changes.outputs.ui == 'true')
- runs-on: ubuntu-latest
- concurrency:
- group: deploy-ui
- cancel-in-progress: false
- steps:
- - uses: actions/checkout@v7
- - uses: superfly/flyctl-actions/setup-flyctl@master
- - name: Deploy
- run: flyctl deploy --remote-only --config fly.ui.toml
- env:
- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN_UI }}
-
- deploy-honcho:
- name: Deploy Honcho
- needs: changes
- # "both" intentionally excludes honcho — Honcho is a memory-layer
- # dep, not part of the app pair, and we don't want a routine api/ui
- # push to cycle the deriver mid-thought. Trigger explicitly via
- # `workflow_dispatch` with target=honcho, or auto-trigger when the
- # Honcho image / fly config changes.
- if: >-
- (github.event_name == 'workflow_dispatch' && inputs.target == 'honcho')
- || (github.event_name == 'push' && needs.changes.outputs.honcho == 'true')
- runs-on: ubuntu-latest
- concurrency:
- group: deploy-honcho
- cancel-in-progress: false
- steps:
- - uses: actions/checkout@v7
- - uses: superfly/flyctl-actions/setup-flyctl@master
- # Fail loud if the operator forgot to set FLY_API_TOKEN_HONCHO —
- # flyctl's own error for a missing token is opaque and easy to
- # miss in CI logs.
- - name: Preflight — token present
- run: |
- if [ -z "${{ secrets.FLY_API_TOKEN_HONCHO }}" ]; then
- echo "::error::FLY_API_TOKEN_HONCHO secret not set in repo Actions settings."
- echo "Generate via: flyctl tokens create deploy -a openexec-honcho-dev"
- exit 1
- fi
- - name: Deploy
- # Schema migrations + the configure_embeddings step run as Fly's
- # release_command (see fly.honcho.toml [deploy]). No SSH from CI.
- run: flyctl deploy --remote-only --config fly.honcho.toml
- env:
- # Separate token because Honcho is a separate Fly app; principle
- # of least authority means a compromised api/ui token can't
- # touch the memory app and vice versa.
- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN_HONCHO }}
diff --git a/.gitignore b/.gitignore
index 2da5ed1f..43908019 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,3 +78,15 @@ evals/results/
~/.claude/anvil/
*.db
packages/ui/tsconfig.tsbuildinfo
+
+# Private deployment substrate. These describe one specific hosting setup and
+# are not part of the open-source project. Kept on disk (untracked) so existing
+# environments can still be deployed by hand; see docs/deployment.md for the
+# generic self-host path.
+fly.*.toml
+scripts/fly-secrets.sh.example
+scripts/setup-flyctl.sh
+scripts/seed-google-workspace.sh
+.github/workflows/deploy.yml
+.github/workflows/deploy-qa.yml
+.vscode/
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
deleted file mode 100644
index db929b39..00000000
--- a/.vscode/extensions.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- // VS Code will prompt collaborators to install these on first open.
- // None are required to run the bash file directly from a terminal — they
- // just make the Fly tasks feel like notebook cells.
- "recommendations": [
- // Pins every task in .vscode/tasks.json to the status bar as a clickable
- // button. With this installed, "Fly: push OpenRouter pair" et al. show
- // up at the bottom of the editor for one-click invocation.
- "actboy168.tasks",
-
- // Standard bash linter — flags typos in fly-secrets.sh before you push
- // a half-broken function to Fly.
- "timonwong.shellcheck",
-
- // Hover docs + go-to-def for shell functions. Useful when reading the
- // sync_all helper to see what each topic function does.
- "mads-hartmann.bash-ide-vscode"
- ]
-}
diff --git a/.vscode/settings.json b/.vscode/settings.json
deleted file mode 100644
index d7e597b0..00000000
--- a/.vscode/settings.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- // Repo-wide editor settings shared across all collaborators. Personal
- // tweaks (theme, font, key bindings) belong in user settings, not here.
-
- // Status-bar-tasks (actboy168.tasks) groups tasks by label prefix. The
- // "Fly: " prefix on every task in .vscode/tasks.json lands them under a
- // single "Fly" dropdown in the status bar.
- "tasks.statusbar.default.color.run": "statusBar.foreground",
-
- // shellcheck the operator notebook the same way CI lints Python.
- "shellcheck.enable": true,
- "shellcheck.run": "onType"
-}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
deleted file mode 100644
index da19769e..00000000
--- a/.vscode/tasks.json
+++ /dev/null
@@ -1,130 +0,0 @@
-{
- // Each task wraps one function from scripts/fly-secrets.sh and runs it in
- // a dedicated terminal panel so output stays put between runs.
- //
- // How to fire:
- // - Cmd/Ctrl+Shift+P → "Tasks: Run Task" → pick one
- // - Or install the recommended `actboy168.tasks` extension (see
- // .vscode/extensions.json) to get one-click buttons in the status bar
- //
- // Each task re-sources fly-secrets.sh and .env on every invocation, so
- // editing either file takes effect on the next run without restarting
- // anything.
- "version": "2.0.0",
- "tasks": [
- {
- "label": "Fly: list secrets (both apps)",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && list_all",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: show non-secret env (both apps)",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && config_env_all",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: dump real env values — API",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && dump_env_api",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: dump real env values — UI",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && dump_env_ui",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: tail API logs",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && tail_api",
- "isBackground": true,
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: tail UI logs",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && tail_ui",
- "isBackground": true,
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push ANTHROPIC_API_KEY",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && anthropic_key",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push OpenRouter pair",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && openrouter",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push BACKEND_SHARED_SECRET (both apps)",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && backend_shared_secret",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push Slack tokens",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && slack",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push Email config",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && email",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push Telegram tokens",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && telegram",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push Discord tokens",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && discord",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: push Auth.js (UI)",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && auth",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: sync_all (push everything present in .env)",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && sync_all",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- },
- {
- "label": "Fly: check /agents/models",
- "type": "shell",
- "command": "source scripts/fly-secrets.sh && check_models",
- "presentation": { "panel": "dedicated", "clear": true, "reveal": "always" },
- "problemMatcher": []
- }
- ]
-}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4e01abfa..180b6d93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,7 +19,7 @@ Initial public release.
- Next.js 15 web UI (`packages/ui`), including the static `/architecture` page.
- Curated MBA knowledge base (`knowledge/`) and eval suite (`evals/`).
- Optional integrations: Slack, Discord, and email.
-- Docker and Fly.io deployment configuration.
+- Docker deployment configuration.
- Open-source project setup: Apache-2.0 license, contribution guide, code of
conduct, security policy, issue/PR templates, and CI.
diff --git a/CLAUDE.md b/CLAUDE.md
index 0960c3ff..105c0329 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -128,14 +128,19 @@ When your PR materially changes a documented topic, **re-author the affected `pr
Each `prebuilt/<id>.json` has the keys `section_id`, `title`, `markdown`, `mermaid` (a Mermaid string or `null`), and `generated_at`. The Markdown must not include the section heading (the UI renders the title). Validate edits with `python -m json.tool`.
-## Live Hosts
+## Local Hosts
-- **API** — FastAPI backend, Fly app `openexec-api-dev`: https://openexec-api-dev.fly.dev
+`make dev` serves both:
+
+- **API** — FastAPI backend on http://localhost:8000
- Sections list + availability: `GET /architecture/sections`
- Per-section content (static, pre-authored): `GET /architecture/sections/{id}`
- - SSH for SQLite / log inspection: `flyctl ssh console -a openexec-api-dev`
-- **UI** — Next.js frontend, Fly app `openexec-ui-dev`: https://openexec-ui-dev.fly.dev
- - Architecture page: https://openexec-ui-dev.fly.dev/architecture
+ - SQLite inspection: `sqlite3 ./episodic_memory.db` (or `$EPISODIC_DB_PATH`)
+- **UI** — Next.js frontend on http://localhost:3000
+ - Architecture page: http://localhost:3000/architecture
+
+Deployment topology and operations live in `docs/deployment.md`. Any host URLs
+and deploy configuration for a specific environment are kept outside this repo.
## Environment Variables
@@ -149,6 +154,12 @@ See `.env.example`. Required: `ANTHROPIC_API_KEY`. Optional integrations: `SLACK
> `env -u BACKEND_SHARED_SECRET uv run pytest tests/unit/` — to match CI (CI
> does not set it).
+> **`OE_PUBLIC_DEPLOYMENT` is the same trap, harder:** `api/main.py` runs
+> `app = create_app()` at module level, and with that var set and no
+> `BACKEND_SHARED_SECRET` the guard raises at **import** time — so the failure
+> is a collection error, not a test failure. `tests/conftest.py` pops it
+> defensively; keep it unset in your shell anyway.
+
> **Ad-hoc scripts:** `get_settings()` requires `EXEC_EMAIL_ADDRESS` (no
> default), so a one-off `uv run python` snippet needs it exported alongside
> `ANTHROPIC_API_KEY` — the test suite sets both in `tests/conftest.py`.
diff --git a/README.md b/README.md
index 432abcb8..cf5fd65a 100644
--- a/README.md
+++ b/README.md
@@ -90,11 +90,8 @@ openexecutive/
│ └── ui/ # Next.js 15 web UI
├── evals/ # Eval scenarios + LLM-as-judge runner
├── fixtures/ # Demo company fixtures (profiles, docs, rosters)
-├── scripts/ # Operator scripts (Fly secrets, Google auth)
+├── scripts/ # Operator scripts (Google auth)
├── docker/ # Dockerfile(s) + docker-compose.yml
-├── fly.api.toml / fly.ui.toml # Fly.io configs — dev API + UI apps
-├── fly.api.qa.toml / fly.ui.qa.toml # Fly.io configs — QA API + UI apps
-├── fly.honcho.toml # Fly.io config — Honcho memory app (optional)
└── docs/ # Architecture + deployment docs
```
@@ -160,18 +157,17 @@ Users can DM the bot, `@mention` it in a channel (replies in a thread), or use `
### Deploying to production
-Just set the secrets on the existing API app — no new Fly app required:
+The bot runs inside the existing API process — no extra service. Set these on the API and restart it:
-```bash
-flyctl secrets set -a openexec-api-dev \
- DISCORD_BOT_TOKEN=... \
- DISCORD_APP_ID=... \
- DISCORD_GUILD_IDS=...
+```
+DISCORD_BOT_TOKEN=...
+DISCORD_APP_ID=...
+DISCORD_GUILD_IDS=...
```
Discord user access is managed via the /people UI — add a Person row with `discord_user_id` set.
-The machine restarts and the bot starts on the next lifespan boot. To disable in prod: `flyctl secrets unset -a openexec-api-dev DISCORD_BOT_TOKEN`.
+The bot starts on the next lifespan boot. To disable it, unset `DISCORD_BOT_TOKEN` and restart.
## Onboarding Your Company
@@ -211,65 +207,25 @@ curl -X POST http://localhost:8000/documents \
-F "domain=strategy"
```
-## Deployment (Fly.io)
-
-Two environments, each a separate set of Fly apps, driven by branch:
-
-| Environment | Trigger | Workflow | Apps |
-|---|---|---|---|
-| **dev** | push/merge to `main` (continuous) | `.github/workflows/deploy.yml` | `openexec-api-dev`, `openexec-ui-dev` |
-| **qa** | push/merge to `qa` (deliberate promotion) | `.github/workflows/deploy-qa.yml` | `openexec-api-qa`, `openexec-ui-qa` |
-
-Both workflows use `dorny/paths-filter` to deploy only the changed app (API, UI, or both). QA is a stable twin of dev — same image and runtime, only the app name differs (`fly.api.qa.toml` / `fly.ui.qa.toml`) — so it lags `main` and stays vetted. An optional Honcho memory app (`fly.honcho.toml`) deploys independently.
-
-### Topology
-
-| App | Purpose | State |
-|-----|---------|-------|
-| `openexec-api-{dev,qa}` | FastAPI + scheduler | Persistent volume `executive_data` at `/data` |
-| `openexec-ui-{dev,qa}` | Next.js 15 | Stateless |
-| `openexec-honcho-dev` | Honcho per-person memory (optional) | Postgres-backed |
-
-> **⚠️ Single-instance only**: The scheduler claims rows via `UPDATE … RETURNING`. Running two API machines would double-fire scheduled actions. `max_machines_running = 1` is set in `fly.api.toml` / `fly.api.qa.toml` — do not override it.
+## Deployment
-### Required GitHub Actions secrets
+Two containers — the FastAPI backend and the Next.js UI — plus one persistent
+volume at `/data`. [docker/docker-compose.yml](docker/docker-compose.yml) is the
+reference topology and also what `make docker` runs locally, so the local and
+deployed shapes match.
-Deploys authenticate with per-app Fly deploy tokens stored as repo (or org) Actions secrets. Generate each with `flyctl tokens create deploy -a <app> -x 999999h`:
-
-| Secret | App | Used by |
-|---|---|---|
-| `FLY_API_TOKEN_API` | `openexec-api-dev` | dev |
-| `FLY_API_TOKEN_UI` | `openexec-ui-dev` | dev |
-| `FLY_API_TOKEN_HONCHO` | `openexec-honcho-dev` | dev (honcho job) |
-| `FLY_API_TOKEN_API_QA` | `openexec-api-qa` | qa |
-| `FLY_API_TOKEN_UI_QA` | `openexec-ui-qa` | qa |
-
-Per-app runtime secrets (`ANTHROPIC_API_KEY`, `BACKEND_SHARED_SECRET`, the `AUTH_*` set, integration tokens) are set directly on each Fly app — see `scripts/fly-secrets.sh.example`.
-
-### One-time bootstrap (dev)
-
-```bash
-# 1. Create apps and volume
-flyctl apps create openexec-api-dev
-flyctl apps create openexec-ui-dev
-flyctl volumes create executive_data --region iad --size 1 -a openexec-api-dev
-
-# 2. Set the required secret
-flyctl secrets set -a openexec-api-dev ANTHROPIC_API_KEY=sk-ant-...
-
-# 3. Create deploy tokens and add as GitHub secrets FLY_API_TOKEN_API and FLY_API_TOKEN_UI
-flyctl tokens create deploy -a openexec-api-dev -x 999999h
-flyctl tokens create deploy -a openexec-ui-dev -x 999999h
-
-# 4. First deploy
-gh workflow run "Deploy (dev)" -f target=both
-```
+> **⚠️ Single-instance only**: the scheduler claims rows via `UPDATE … RETURNING`,
+> which is not safe across processes. A second API replica double-fires every
+> scheduled action. Pin the API to one instance. The UI is stateless.
-QA bootstraps the same way against the `-qa` app names (push to the `qa` branch, or `gh workflow run "Deploy (qa)"`). See [docs/deployment.md](docs/deployment.md) for the full runbook (operations, rollback, common failure modes, why `.flycast` isn't used).
+Set `ANTHROPIC_API_KEY`, `BACKEND_SHARED_SECRET`, `BACKEND_ALLOWED_ORIGINS` and
+`OE_PUBLIC_DEPLOYMENT=1` on any internet-reachable instance. See
+[docs/deployment.md](docs/deployment.md) for the full guide — persistent state,
+health-check timing, resource sizing, operations, and common failure modes.
### Access control
-The deployed UI is gated behind Google sign-in with an email allow-list, and the public API is protected by a shared-secret header between the UI proxy and the FastAPI backend. See [docs/auth.md](docs/auth.md) for the full setup (Google Cloud Console steps, required Fly secrets, adding/removing users, rotating secrets, and a debugging table).
+The deployed UI is gated behind Google sign-in with an email allow-list, and the public API is protected by a shared-secret header between the UI proxy and the FastAPI backend. See [docs/auth.md](docs/auth.md) for the full setup (Google Cloud Console steps, required environment variables, adding/removing users, rotating secrets, and a debugging table).
## Configuration
@@ -421,7 +377,7 @@ pytest packages/core/tests/unit/ -v
## Privacy
-Everything in `company/` is gitignored — the profile YAML, uploaded documents, and the ChromaDB vector store. None of this leaves your local machine (or your own Fly volume in cloud deployments) except as part of prompts sent to the Anthropic API. Anthropic does not train on API data.
+Everything in `company/` is gitignored — the profile YAML, uploaded documents, and the ChromaDB vector store. None of this leaves your local machine (or your own volume in cloud deployments) except as part of prompts sent to the Anthropic API. Anthropic does not train on API data.
## Contributing
diff --git a/SECURITY.md b/SECURITY.md
index 4a0a85e4..d975f21a 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -36,7 +36,7 @@ A few things worth knowing when assessing or reporting:
- **Secrets** never belong in the repo. Runtime secrets (`ANTHROPIC_API_KEY`,
`BACKEND_SHARED_SECRET`, `AUTH_*`, integration tokens) are injected via
- environment variables / Fly secrets and are gitignored locally. If you find a
+ environment variables / platform secrets and are gitignored locally. If you find a
committed secret, report it privately rather than opening an issue.
- **Access control.** The deployed UI is gated by Google sign-in with an email
allow-list, and the API is protected by a shared-secret header between the UI
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 9258d758..8959ae96 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -43,7 +43,7 @@ RUN uv export --locked --no-dev --no-emit-project -q -o requirements.txt \
# Bake the embedding model the MCP gateway loads at startup
# (sentence-transformers/all-MiniLM-L6-v2). Without this the ~90 MB model is
# fetched from Hugging Face on every cold start, which dominates boot time —
-# see the health-check grace period note in fly.api.toml. extensible-mcp is
+# see the health-check grace period note in docs/deployment.md. extensible-mcp is
# launched via `uvx` and inherits this process's environment, so pointing
# HF_HOME at an image path lets that subprocess load the model from disk
# instead of the network. Runs right after the dependency install so the
@@ -96,7 +96,7 @@ COPY fixtures/ ./fixtures/
# Register the `openexecutive` console script (defined in
# [project.scripts] in pyproject.toml) so admin commands like
-# `openexecutive ingest-oer` are runnable via `flyctl ssh console`.
+# `openexecutive ingest-oer` are runnable via a shell on the container.
# Dependencies were already installed in the earlier layer, so --no-deps
# keeps this fast and cache-friendly.
RUN uv pip install --system --no-deps .
@@ -116,8 +116,8 @@ ENV HF_HUB_OFFLINE=1
ENV TRANSFORMERS_OFFLINE=1
# Defaults for the co-located workspace-mcp child. The credentials dir lives on
-# the /data volume so an OAuth token survives restarts; fly.api.toml [env] sets
-# the same values (and the per-install GWORKSPACE_AUTH_MODE / Google secrets).
+# the /data volume so an OAuth token survives restarts; a deployment sets the
+# same values (and the per-install GWORKSPACE_AUTH_MODE / Google secrets).
ENV WORKSPACE_MCP_CREDENTIALS_DIR=/data/google_credentials
ENV WORKSPACE_MCP_TOOL_TIER=complete
diff --git a/docker/honcho/Dockerfile b/docker/honcho/Dockerfile
index e53eea12..df3b8b7b 100644
--- a/docker/honcho/Dockerfile
+++ b/docker/honcho/Dockerfile
@@ -4,14 +4,14 @@
# uv 0.9.24) but pins the Honcho source to a specific release tag, bakes
# in OE's config.toml (OpenRouter routes every LLM call, dreaming on,
# AUTH_USE_AUTH=true), and bundles an embeddings sidecar
-# (`docker/honcho/embed_server.py`) that runs as the `embed` Fly process
-# group serving `BAAI/bge-small-en-v1.5` locally via fastembed/ONNX so
-# embeddings never leave Fly's private network.
+# (`docker/honcho/embed_server.py`) that runs as the `embed` process
+# serving `BAAI/bge-small-en-v1.5` locally via fastembed/ONNX so
+# embeddings never leave the deployment's private network.
#
# Build context is the repo root (so this file references
# docker/honcho/config.toml + embed_server.py from cwd). See
-# fly.honcho.toml for how Fly invokes the build + which process runs
-# which command.
+# README.md for the three process roles and which command
+# each one runs.
# Honcho's uv.lock pins Python 3.11 even though their own Dockerfile says
# 3.13 — they bake the missing interpreter from uv's managed-Python cache.
# We can't do that cleanly under our non-root `app` user (uv's cache lands
@@ -19,7 +19,7 @@
FROM python:3.11-slim-bookworm
# Bump deliberately — Honcho ships database migrations between minors and
-# the SDK's wire format can shift. The runbook (docs/honcho-hosting.md)
+# the SDK's wire format can shift. The runbook (README.md)
# covers the upgrade procedure.
ARG HONCHO_VERSION=v3.0.7
@@ -57,7 +57,7 @@ RUN uv sync --frozen --no-dev
# Embeddings sidecar deps: fastembed wraps ONNX-runtime models with no
# torch dependency, so the marginal image size is small (~130MB for
# bge-small-en-v1.5 weights + onnxruntime). Installed into Honcho's venv
-# so the same `embed` Fly process can `import fastembed` directly.
+# so the same `embed` process can `import fastembed` directly.
RUN uv pip install --python /app/.venv/bin/python "fastembed>=0.6.0,<1"
# Overlay OE's Honcho config and the embeddings sidecar source.
@@ -78,13 +78,13 @@ RUN useradd --create-home --shell /bin/bash app \
&& chown -R app:app /app
USER app
-# Put the uv-managed venv on PATH so Fly's `[processes]` commands can
+# Put the uv-managed venv on PATH so each process's command can
# invoke `fastapi` / `python` directly without an `uv run` prefix
# (matches Honcho's upstream CMD).
ENV PATH="/app/.venv/bin:$PATH"
EXPOSE 8000 8001
-# Default command is the API. Fly's [processes] block in fly.honcho.toml
-# overrides this per process (api / deriver / embed).
+# Default command is the API. Override it per process (api / deriver / embed)
+# — see README.md.
CMD ["fastapi", "run", "--host", "0.0.0.0", "src/main.py"]
diff --git a/docker/honcho/README.md b/docker/honcho/README.md
new file mode 100644
index 00000000..34270164
--- /dev/null
+++ b/docker/honcho/README.md
@@ -0,0 +1,80 @@
+# Self-hosted Honcho
+
+Per-person memory ("peer memory") is backed by [Honcho](https://honcho.dev). Open
+Executive talks to it over HTTP, so it works against either hosted Honcho or a
+self-hosted instance — set `HONCHO_API_KEY` and `HONCHO_BASE_URL` on the API and
+the application does not care which. Hosted is the simpler path; this directory
+is for running your own.
+
+## What's here
+
+| File | Purpose |
+|---|---|
+| `Dockerfile` | Builds Honcho, pinned via `ARG HONCHO_VERSION` (currently `v3.0.7`), with the embedding model baked into the image |
+| `config.toml` | Honcho's model configuration — which LLM serves each slot, and the embedding setup |
+| `embed_server.py` | A small OpenAI-compatible embeddings server (`fastembed` + `BAAI/bge-small-en-v1.5`), so embeddings need no external vendor |
+
+## Processes
+
+One image, three roles — run each as its own container/process from the same build:
+
+- **api** — Honcho's FastAPI service on `:8000`. The only one Open Executive talks to; keep it on a private network.
+- **deriver** — background worker running extraction and "dreaming". Set `DERIVER_WORKERS=2`; the default of 1 falls behind bursty load.
+- **embed** — the embeddings sidecar on `:8001`, reached by the deriver.
+
+## Requirements
+
+**Postgres with `pgvector`.** Honcho's migrations expect the extension to exist —
+`CREATE EXTENSION IF NOT EXISTS vector;` before first deploy.
+
+**Run the release steps on every deploy, before new containers serve traffic:**
+
+```bash
+python provision_db.py
+python configure_embeddings.py --yes
+```
+
+`configure_embeddings.py` reconciles the pgvector column with
+`EMBEDDING_VECTOR_DIMENSIONS`. Skipping it after a dimension change makes the
+deriver fail every embed call with a dimension mismatch.
+
+## Configuration
+
+| Variable | Notes |
+|---|---|
+| `DATABASE_URL` | Postgres connection string |
+| `AUTH_JWT_SECRET` | Every issued `HONCHO_API_KEY` derives from this — store it in a password manager; rotating it invalidates all keys |
+| `LLM_OPENAI_API_KEY` | Honcho's `openai` transport accepts any OpenAI-format endpoint, so this can be an OpenRouter key with `base_url` set per slot in `config.toml` |
+| `EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL` | Point at the `embed` process, e.g. `http://embed:8001/v1` |
+| `EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY` | The sidecar needs no auth, but the OpenAI client requires some string |
+| `EMBEDDING_VECTOR_DIMENSIONS` | `384` for `bge-small-en-v1.5`. Honcho's default schema is `Vector(1536)` |
+| `DERIVER_WORKERS` | `2` |
+
+Honcho uses nested pydantic-settings (`env_prefix="EMBEDDING_"`,
+`env_nested_delimiter="__"`), so a plain `EMBEDDING_BASE_URL` is **silently
+ignored**. Use the `__OVERRIDES__` form above.
+
+## Embedding quality
+
+The default `BAAI/bge-small-en-v1.5` (384-dim, ~130MB) scores roughly level with
+OpenAI's `text-embedding-3-small` on MTEB English, while staying local and
+English-only. If retrieval feels weak, climb before reaching for a vendor API:
+
+| Step | Model | Cost |
+|---|---|---|
+| Default | `BAAI/bge-small-en-v1.5` (384-dim) | baseline |
+| 1 | `BAAI/bge-base-en-v1.5` (768-dim) | +300MB image, +400MB RAM |
+| 2 | `BAAI/bge-large-en-v1.5` (1024-dim) | +1.2GB image, +1.2GB RAM |
+| 3 | A hosted embedding API (1536-dim) | a network hop and a data-residency change |
+
+`fastembed` needs the model in its cache, which is baked at build time, so steps
+1 and 2 require a rebuild — not just an env change. Any dimension change means
+re-running `configure_embeddings.py`, which **alters the pgvector column and
+destroys existing embeddings**. Back up first.
+
+## Upgrading Honcho
+
+Honcho ships breaking schema changes between minor versions. Read the
+[release notes](https://github.com/plastic-labs/honcho/releases), bump
+`ARG HONCHO_VERSION` in the `Dockerfile`, redeploy with the release steps above,
+and smoke a peer-memory round trip before considering it done.
diff --git a/docker/honcho/config.toml b/docker/honcho/config.toml
index c90416cd..9f9003b0 100644
--- a/docker/honcho/config.toml
+++ b/docker/honcho/config.toml
@@ -2,19 +2,19 @@
#
# Env vars override every key in this file (e.g. `DB_CONNECTION_URI=...`
# wins over `[db].CONNECTION_URI`), so secrets and per-environment values
-# come from Fly secrets at runtime — see docs/honcho-hosting.md.
+# come from environment variables at runtime — see README.md.
#
# Provider strategy:
# - All LLM calls (deriver, summary, dialectic levels, dream deduction)
# use Honcho's `openai` transport but point at OpenRouter. OpenRouter
-# fronts Anthropic / OpenAI / Voyage / etc., so a single Fly secret
+# fronts Anthropic / OpenAI / Voyage / etc., so a single secret
# (`LLM_OPENAI_API_KEY` = OE's existing OpenRouter key) drives every
# outbound LLM call. The `model` field uses OpenRouter slugs
# (`anthropic/claude-haiku-4.5`, etc.).
# - Embeddings come from a local fastembed sidecar (see
# docker/honcho/embed_server.py) — no external embedding vendor.
# Quality ladder + the OpenRouter fallback are documented in
-# docs/honcho-hosting.md ("Embedding quality ladder").
+# README.md ("Embedding quality ladder").
[app]
LOG_LEVEL = "INFO"
@@ -25,15 +25,15 @@ LOG_LEVEL = "INFO"
EMBED_MESSAGES = true
[db]
-# CONNECTION_URI is set per-environment via the DB_CONNECTION_URI Fly
-# secret (Fly Postgres attach injects DATABASE_URL; the runbook covers
+# CONNECTION_URI is set per-environment via the DB_CONNECTION_URI
+# variable (a managed Postgres usually injects DATABASE_URL; the README covers
# the postgres:// → postgresql+psycopg:// scheme rewrite). Pool sizing
# tuned for the 1-vCPU shared dev VM.
POOL_SIZE = 10
[auth]
-# Auth-in-depth: even on Fly's private 6PN network the API requires a
-# valid JWT. JWT_SECRET comes from a Fly secret; OE's HONCHO_API_KEY is
+# Auth-in-depth: even on a private network the API requires a
+# valid JWT. JWT_SECRET comes from the environment; OE's HONCHO_API_KEY is
# a token derived from it via src.security.create_admin_jwt().
USE_AUTH = true
@@ -95,18 +95,18 @@ base_url = "https://openrouter.ai/api/v1"
# -------------------------------------------------------------------- #
# Embeddings — local fastembed sidecar (embed_server.py running as the
-# `embed` Fly process group). The deriver hits it over Fly's internal
+# `embed` process). The deriver hits it over the internal
# 6PN at `embed.process.<app>.internal:8001/v1`. The base_url is set
# via the EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL secret (Honcho's
# nested-pydantic-settings convention — env_prefix=EMBEDDING_,
# env_nested_delimiter=__), so the deploy can swap to OpenRouter
-# without rebuilding the image. See docs/honcho-hosting.md.
+# without rebuilding the image. See README.md.
#
# IMPORTANT: bge-small-en-v1.5 emits 384-dim vectors but Honcho's
# schema defaults to Vector(1536). The runbook step "Configure vector
# dimensions" runs `scripts/configure_embeddings.py` to ALTER the
-# column once per deploy that changes the embedding dim. The Fly
-# release_command in fly.honcho.toml runs it on every deploy
+# column once per deploy that changes the embedding dim. Run it as a
+# release step on every deploy
# (idempotent — no-ops when current dim matches).
# -------------------------------------------------------------------- #
[embedding.model_config]
@@ -114,4 +114,4 @@ transport = "openai"
model = "BAAI/bge-small-en-v1.5"
# overrides.base_url + overrides.api_key intentionally omitted —
# set via EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL and
-# EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY Fly secrets.
+# EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY variables.
diff --git a/docker/honcho/embed_server.py b/docker/honcho/embed_server.py
index d4d01b67..5aa5f0ba 100644
--- a/docker/honcho/embed_server.py
+++ b/docker/honcho/embed_server.py
@@ -2,19 +2,19 @@
Honcho's deriver makes embedding calls through its `openai` transport. We
serve `BAAI/bge-small-en-v1.5` locally via fastembed (ONNX, no torch)
-behind this thin shim so embeddings stay inside the Fly private network —
+behind this thin shim so embeddings stay inside the private network —
no third-party embedding vendor, no per-call cost.
-Wire shape: Fly runs this as its own process group (`embed`); the deriver
-process resolves it via `embed.process.openexec-honcho-dev.internal:8001`.
-Honcho's `[embedding.model_config].base_url` points at that DNS.
+Wire shape: this runs as its own process (`embed`) and the deriver reaches it
+over the internal network on port 8001. Honcho's
+`[embedding.model_config].base_url` points at that address.
The endpoint mirrors OpenAI's `/v1/embeddings` shape just enough that the
`AsyncOpenAI` client Honcho uses (`src/embedding_client.py:175`) gets a
response it can deserialise. `model` in the request is accepted but
ignored — we always use the model the container was built with.
-Upgrade ladder is documented in `docs/honcho-hosting.md`: swap
+Upgrade ladder is documented in `README.md`: swap
`EMBED_MODEL` env var to `BAAI/bge-base-en-v1.5` / `bge-large-en-v1.5`
or flip `EMBEDDING_BASE_URL` on the Honcho app to OpenRouter, no code
change here.
@@ -82,7 +82,7 @@ class _EmbedResponse(BaseModel):
@app.get("/health")
def health() -> dict[str, Any]:
- """Liveness probe used by Fly's http_check."""
+ """Liveness probe for the platform health check."""
return {"status": "ok", "model": EMBED_MODEL}
diff --git a/docker/workspace-mcp-launch.sh b/docker/workspace-mcp-launch.sh
index f0933dac..e4ed67b9 100644
--- a/docker/workspace-mcp-launch.sh
+++ b/docker/workspace-mcp-launch.sh
@@ -8,7 +8,7 @@
# See docs/deployment.md → "Google Workspace (co-located in the API)".
#
# Two Google-auth modes, selected per install via GWORKSPACE_AUTH_MODE (an env
-# var / Fly secret — no image rebuild to switch):
+# var — no image rebuild to switch):
#
# oauth (default) Single-user OAuth. The exec account grants consent
# once; the refresh token persists under
diff --git a/docs/architecture.md b/docs/architecture.md
index c906e311..789a0b7b 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -271,7 +271,7 @@ A background polling loop that wakes the Executive when a `scheduled_actions` ro
**Startup sweep:** `requeue_orphaned_running()` resets any `running` rows left by a previous crash back to `pending`, so no action is permanently lost.
-**Single-instance constraint:** Do not run the scheduler in more than one process against the same database. The Fly.io API app is pinned to `max_machines_running = 1` for exactly this reason.
+**Single-instance constraint:** Do not run the scheduler in more than one process against the same database. Any deployment must pin the API to a single instance for exactly this reason.
```
SQLite scheduled_actions (status=pending, scheduled_for ≤ now)
@@ -601,4 +601,4 @@ Everything in `company/` is gitignored. This includes:
- `chroma_db/` — the vector store (contains embeddings of company documents)
- `episodic_memory.db` — decisions, initiatives, advice, alerts, audit log
-None of this leaves the local machine (or your own Fly volume in cloud deployments) except as part of prompts sent to the Anthropic API. Anthropic does not train on API data.
+None of this leaves the local machine (or your own volume in cloud deployments) except as part of prompts sent to the Anthropic API. Anthropic does not train on API data.
diff --git a/docs/auth.md b/docs/auth.md
index a6706716..4c490788 100644
--- a/docs/auth.md
+++ b/docs/auth.md
@@ -11,19 +11,19 @@ Two independent layers. Either one alone would be insufficient; together they fa
| Layer | What it does | Where |
|---|---|---|
| **UI: Auth.js v5 + Google OAuth** | Anyone hitting the public UI is redirected to `/signin`. Only Google accounts in `ALLOWED_EMAILS` can complete sign-in. | [packages/ui/src/auth.ts](../packages/ui/src/auth.ts), [packages/ui/src/middleware.ts](../packages/ui/src/middleware.ts), [packages/ui/src/app/signin/page.tsx](../packages/ui/src/app/signin/page.tsx) |
-| **API: shared-secret header** | The FastAPI backend is on a public Fly URL. It rejects every request whose `x-api-key` header doesn't match `BACKEND_SHARED_SECRET`. The UI proxy stamps this header on every upstream call. | [packages/core/openexecutive/api/main.py](../packages/core/openexecutive/api/main.py), [packages/ui/src/app/api/backend/[...path]/route.ts](../packages/ui/src/app/api/backend/%5B...path%5D/route.ts) |
+| **API: shared-secret header** | The FastAPI backend is reachable over the network. It rejects every request whose `x-api-key` header doesn't match `BACKEND_SHARED_SECRET`. The UI proxy stamps this header on every upstream call. | [packages/core/openexecutive/api/main.py](../packages/core/openexecutive/api/main.py), [packages/ui/src/app/api/backend/[...path]/route.ts](../packages/ui/src/app/api/backend/%5B...path%5D/route.ts) |
### Request flow
```
-Browser ──► openexec-ui-dev.fly.dev ──► (middleware: session check)
+Browser ──► exec.example.com (UI) ──► (middleware: session check)
│
├── no session ──► redirect to /signin → Google → callback → cookie set
│
└── has session ──► /api/backend/[...path] (proxy)
│ stamps x-api-key
▼
- openexec-api-dev.fly.dev (FastAPI)
+ api.example.com (FastAPI)
│ middleware verifies x-api-key (constant-time)
▼
route handler
@@ -33,7 +33,7 @@ Browser ──► openexec-ui-dev.fly.dev ──► (middleware: session check)
These bypass the shared-secret check because they're hit by external services that authenticate themselves:
-- `/health` — Fly's health checker
+- `/health` — the platform's health checker
- `/webhook/telegram` — verifies Telegram's own secret token
- `/webhook/google-chat` — verifies the GCP project's signed JWT
- `OPTIONS *` — CORS preflight (no auth headers possible)
@@ -49,8 +49,8 @@ See [`_UNAUTHENTICATED_PATHS`](../packages/core/openexecutive/api/main.py) — a
1. Create or pick a Google Cloud project.
2. Set up the consent screen (the **Google Auth Platform** page — formerly "OAuth consent screen"). External user type is fine; you don't need to add test users or publish the app because we only request basic scopes (`openid email profile`).
3. **APIs & Services → Clients → + Create Client → Web application**:
- - **Authorized JavaScript origins**: `http://localhost:3000`, `https://openexec-ui-dev.fly.dev`
- - **Authorized redirect URIs**: `http://localhost:3000/api/auth/callback/google`, `https://openexec-ui-dev.fly.dev/api/auth/callback/google`
+ - **Authorized JavaScript origins**: `http://localhost:3000`, plus your deployed UI origin (e.g. `https://exec.example.com`)
+ - **Authorized redirect URIs**: `http://localhost:3000/api/auth/callback/google`, plus `<your UI origin>/api/auth/callback/google`
4. Copy the Client ID and Client secret immediately — the secret is shown only once.
### Local dev (repo-root `.env`, gitignored)
@@ -97,34 +97,38 @@ entirely.
Plain `npm run dev` in `packages/ui` (without `make dev`) reads only
`packages/ui/.env*`, not the root `.env`.
-### Production (Fly secrets)
+### Production
+
+Generate both secrets once and set them on the two containers. `BACKEND_SHARED_SECRET` **must be byte-identical on the UI and the API** — a mismatch silently breaks every API call with `401`, so generate it once and paste the same value, rather than running the generator twice.
```bash
-# Generate once, reuse across both apps
SHARED=$(openssl rand -hex 32)
AUTH=$(openssl rand -base64 32)
+```
+
+**UI:**
-# UI
-flyctl secrets set -a openexec-ui-dev \
- AUTH_SECRET="$AUTH" \
- AUTH_GOOGLE_ID="<your client id>" \
- AUTH_GOOGLE_SECRET="<your client secret>" \
- AUTH_TRUST_HOST=true \
- AUTH_URL="https://openexec-ui-dev.fly.dev" \
- BACKEND_SHARED_SECRET="$SHARED"
-
-# API — same $SHARED value
-flyctl secrets set -a openexec-api-dev \
- BACKEND_SHARED_SECRET="$SHARED" \
- BACKEND_ALLOWED_ORIGINS="https://openexec-ui-dev.fly.dev"
```
+AUTH_SECRET=$AUTH
+AUTH_GOOGLE_ID=<your client id>
+AUTH_GOOGLE_SECRET=<your client secret>
+AUTH_TRUST_HOST=true
+AUTH_URL=https://exec.example.com
+BACKEND_SHARED_SECRET=$SHARED
+```
+
+**API** — the same `$SHARED` value:
-Run both `flyctl` commands in the **same terminal session** so `$SHARED` doesn't get re-generated between them — a mismatch silently breaks every API call with `401`.
+```
+BACKEND_SHARED_SECRET=$SHARED
+BACKEND_ALLOWED_ORIGINS=https://exec.example.com
+OE_PUBLIC_DEPLOYMENT=1
+```
-> **Why `AUTH_URL` is required (not just `AUTH_TRUST_HOST`)** — Behind Fly's edge, Auth.js builds the post-OAuth-callback redirect URL using the container's bind address (`0.0.0.0`) unless told the public origin explicitly. `AUTH_TRUST_HOST=true` is necessary but not sufficient on Fly. Symptom if missing: sign-in succeeds at Google, then the browser tries to load `http://0.0.0.0/...` and fails with `ERR_CONNECTION_REFUSED`.
+> **Why `AUTH_URL` is required (not just `AUTH_TRUST_HOST`)** — behind a reverse proxy or load balancer, Auth.js builds the post-OAuth-callback redirect URL from the container's bind address (`0.0.0.0`) unless told the public origin explicitly. `AUTH_TRUST_HOST=true` is necessary but not sufficient. Symptom if missing: sign-in succeeds at Google, then the browser tries to load `http://0.0.0.0/...` and fails with `ERR_CONNECTION_REFUSED`.
-> **Production fails closed.** If `BACKEND_SHARED_SECRET` is unset and `FLY_APP_NAME` is set (i.e. running on Fly), [api/main.py](../packages/core/openexecutive/api/main.py) raises `RuntimeError` at startup rather than serve traffic without auth.
+> **Production fails closed.** With `OE_PUBLIC_DEPLOYMENT` set and no `BACKEND_SHARED_SECRET`, [api/main.py](../packages/core/openexecutive/api/main.py) raises `RuntimeError` at startup rather than serve traffic without auth. Set it on every internet-reachable instance — see [deployment.md](deployment.md).
---
@@ -132,37 +136,37 @@ Run both `flyctl` commands in the **same terminal session** so `$SHARED` doesn't
### Add or remove a user
-```bash
-flyctl secrets set -a openexec-ui-dev ALLOWED_EMAILS="[email protected],[email protected],[email protected]"
+Update `ALLOWED_EMAILS` on the UI and restart it:
+
+```
```
-Fly redeploys automatically after a secret change. The list is read once at startup, so the new entry is live as soon as the rolling restart finishes (~30s).
+The list is read once at startup, so the new entry goes live when the restart finishes.
Rules: comma-separated, case-insensitive, whitespace around entries is stripped, trailing commas are harmless.
### Rotate the shared secret
-Do this if anyone with access to either Fly app leaves, or on a regular cadence.
+Do this if anyone with deployment access leaves, or on a regular cadence. Generate one value and set it on both containers, then restart both:
```bash
NEW=$(openssl rand -hex 32)
-flyctl secrets set -a openexec-ui-dev BACKEND_SHARED_SECRET="$NEW"
-flyctl secrets set -a openexec-api-dev BACKEND_SHARED_SECRET="$NEW"
```
-There's a brief window during the rolling restart where one app has the new value and the other has the old one. Calls during that window will 401. If that matters, take the UI down first (`flyctl scale count 0 -a openexec-ui-dev`), rotate both, then scale back up.
+There is a window during a rolling restart where one side has the new value and the other still has the old one; calls in that window return `401`. If that matters, stop the UI first, rotate both, then bring it back up.
### Rotate `AUTH_SECRET`
Invalidates all existing sessions (everyone is signed out and must re-auth). Use this if the secret may be compromised.
```bash
-flyctl secrets set -a openexec-ui-dev AUTH_SECRET="$(openssl rand -base64 32)"
+openssl rand -base64 32 # set as AUTH_SECRET on the UI, then restart it
```
### Revoke OAuth client
-If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients → your client → **Reset Secret**), then update both your local root `.env` (and `packages/ui/.env.local` if you use one) and the Fly secret. Old issued tokens stop working immediately.
+If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients → your client → **Reset Secret**), then update both your local root `.env` (and `packages/ui/.env.local` if you use one) and the deployed value. Old issued tokens stop working immediately.
---
@@ -172,27 +176,23 @@ If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients
|---|---|
| `OAuth client was not found` / `invalid_client` | `AUTH_GOOGLE_ID` typo, swapped with `AUTH_GOOGLE_SECRET`, or the client lives in a different GCP project |
| `redirect_uri_mismatch` | The Authorized redirect URI in Google Console doesn't exactly match `<origin>/api/auth/callback/google`. Wait 5 min for Google to propagate after edits |
-| Browser tries to load `0.0.0.0` after sign-in | `AUTH_URL` not set on Fly |
+| Browser tries to load `0.0.0.0` after sign-in | `AUTH_URL` not set on the UI |
| `AccessDenied` page after Google login | Email not in `ALLOWED_EMAILS`, or Google returned `email_verified !== true` |
| API returns `401` for every request | UI and API have different `BACKEND_SHARED_SECRET` values (very common after rotating in two separate terminal sessions) |
-| API refuses to start with `RuntimeError: BACKEND_SHARED_SECRET is required` | You're on Fly and forgot to set the secret. Set it; the next machine restart will boot |
-| Sign-in works but the chat stays empty | Backend is auth'd but `ANTHROPIC_API_KEY` is missing on `openexec-api-dev`. `flyctl logs -a openexec-api-dev` will show the error |
+| API refuses to start with `RuntimeError: BACKEND_SHARED_SECRET is required` | `OE_PUBLIC_DEPLOYMENT` is set and the secret is missing. Set it; the next restart will boot |
+| Sign-in works but the chat stays empty | Backend is auth'd but `ANTHROPIC_API_KEY` is missing on the API. Its logs will show the error |
### Useful commands
```bash
-# What secrets are set on each app (digests only, not values)
-flyctl secrets list -a openexec-ui-dev
-flyctl secrets list -a openexec-api-dev
-
# Live logs
-flyctl logs -a openexec-ui-dev
-flyctl logs -a openexec-api-dev
+docker compose logs -f ui
+docker compose logs -f api
-# Probe the public API without going through the UI
-curl -sv https://openexec-api-dev.fly.dev/health # should be 200
-curl -sv https://openexec-api-dev.fly.dev/sessions # should be 401
-curl -sv -H "x-api-key: $SHARED" https://openexec-api-dev.fly.dev/sessions # should be 200
+# Probe the API directly, without going through the UI
+curl -sv https://api.example.com/health # 200
+curl -sv https://api.example.com/sessions # 401
+curl -sv -H "x-api-key: $SHARED" https://api.example.com/sessions # 200
```
---
@@ -204,12 +204,12 @@ curl -sv -H "x-api-key: $SHARED" https://openexec-api-dev.fly.dev/sessions # sh
- A leaked UI URL being usable by anyone with a Google account (allowlist)
- Direct API hits bypassing the UI (shared secret)
- Cookie theft from one session leaking *another* user's data (each session is independent JWT; no shared state)
-- Missing-secret deploys silently exposing the API (Fly fail-closed guard)
+- Missing-secret deploys silently exposing the API (the `OE_PUBLIC_DEPLOYMENT` fail-closed guard)
**Does not mitigate:**
- A compromised `BACKEND_SHARED_SECRET` — anyone who learns it can hit the API as if they were the UI. Rotate if leaked.
- A compromised Google account on the allow-list — that user has full access to all shared data. The product is currently a **shared workspace**; there is no per-user data isolation.
-- A compromised Fly token — attacker can change secrets, redeploy, or read logs. Rotate Fly tokens if a CI workflow is compromised.
+- A compromised deploy credential — attacker can change secrets, redeploy, or read logs. Rotate deploy credentials if a CI workflow is compromised.
- Browser-side XSS — Auth.js sessions are httpOnly cookies, so JS can't read them, but a successful XSS could make authenticated requests from the victim's browser. Standard same-origin protections apply.
If/when per-user data isolation matters (e.g. private sessions per teammate), the change is non-trivial — see the original plan note in [PR #86](https://github.com/SenteLabsAI/OpenExecutive/pull/86) about adding `user_id` to the sessions table.
diff --git a/docs/deployment.md b/docs/deployment.md
index 4ef16b5e..fbd600f3 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -1,369 +1,192 @@
-# Dev Deployment — Fly.io + GitHub Actions
+# Deployment
-The `main` branch is continuously deployed to a shared dev environment on Fly.io. This doc covers how it works, how to set it up from scratch, and how to operate it.
+Open Executive ships as two containers — the FastAPI backend and the Next.js UI —
+plus one persistent volume. Anything that can run a Docker image and attach a
+disk will host it: `docker compose` on a single box, a container platform, or a
+Kubernetes deployment.
----
+[docker/docker-compose.yml](../docker/docker-compose.yml) is the reference
+topology. It is also what `make docker` runs locally, so the local and deployed
+shapes are the same.
-## Topology
+---
-Two Fly apps in the same org:
+## ⚠️ Single instance only
-| App | Source | Public URL | State |
-|---|---|---|---|
-| `openexec-api-dev` | [docker/Dockerfile](../docker/Dockerfile) — Python 3.11 + FastAPI + scheduler | `https://openexec-api-dev.fly.dev` | Persistent volume `executive_data` mounted at `/data` |
-| `openexec-ui-dev` | [docker/Dockerfile.ui](../docker/Dockerfile.ui) — Next.js 15 standalone build | `https://openexec-ui-dev.fly.dev` | Stateless |
+**The API must run exactly one replica.** The scheduler claims due rows with
+`UPDATE … RETURNING`, which is safe against concurrent claims *within* a process
+but not across processes: a second API container fires every scheduled action a
+second time — duplicate emails, duplicate Slack messages, duplicate briefings.
-The UI talks to the API only through its server-side proxy route at [packages/ui/src/app/api/backend/[...path]/route.ts](../packages/ui/src/app/api/backend/[...path]/route.ts), which reads `BACKEND_BASE_URL` at request time. Currently set to the public API URL — see "Why not `.flycast`?" below.
+There is no leader election. Whatever you deploy on, pin the API to one instance
+and use a replace-in-place rollout rather than one that briefly runs two
+containers. The UI is stateless and scales freely.
-### Why the API is pinned to one machine
+---
-The scheduler in [packages/core/openexecutive/scheduler](../packages/core/openexecutive/scheduler) claims due actions with `UPDATE … RETURNING`. Two machines running the same scheduler would double-fire (and double-bill the Anthropic API). The API app is configured to keep this from happening:
+## Topology
-```toml
-# fly.api.toml
-[deploy]
- strategy = "immediate" # replace in place; no overlap during rollout
+| Component | Image | State |
+|---|---|---|
+| API | [docker/Dockerfile](../docker/Dockerfile) | One persistent volume at `/data` |
+| UI | [docker/Dockerfile.ui](../docker/Dockerfile.ui) | Stateless |
-[http_service]
- min_machines_running = 1
- max_machines_running = 1
-```
+The UI never talks to the API directly from the browser. It proxies through its
+own server (`/api/backend/*`), stamping the shared secret on each upstream call,
+so only the UI origin needs to be public. See [auth.md](auth.md).
-Do **not** `flyctl scale count 2` on the API app. If horizontal scale is ever needed, gate the scheduler on machine identity first.
+---
-### Persistent state
+## Persistent state
-The volume `executive_data` is mounted at `/data`. Three things live there:
+One volume, mounted at `/data`:
- `/data/chroma_db/` — ChromaDB vector index (built-in knowledge + uploaded company docs)
-- `/data/episodic_memory.db` — SQLite for episodic memory, alerts, knowledge review, scheduled actions
+- `/data/episodic_memory.db` — SQLite: episodic memory, people, alerts, scheduled actions, audit log
- `/data/company/profile.yaml` + `/data/company/docs/` — onboarding output + uploaded docs
+- `/data/company/mcp_servers.json` — MCP gateway config
+- `/data/google_credentials/` — Google Workspace OAuth token, if that integration is enabled
-Path mappings come from these Fly env vars (set in [fly.api.toml](../fly.api.toml)):
+Nothing hardcodes those paths. Each is an env var, and the defaults are
+repo-relative so a local checkout works with no configuration:
-```toml
-VECTOR_STORE_PATH = "/data/chroma_db"
-EPISODIC_DB_PATH = "/data/episodic_memory.db"
-COMPANY_PROFILE_PATH = "/data/company/profile.yaml"
-MCP_SERVERS_CONFIG_PATH = "/data/company/mcp_servers.json"
```
-
-On first boot, the volume is empty — ChromaDB rebuilds the built-in knowledge index from files shipped inside the Python package at `openexecutive/knowledge/builtin/`. The episodic SQLite is created on demand. The company profile stays empty until you run the onboarding wizard against the dev URL.
-
----
-
-## How a push becomes a deploy
-
-[`.github/workflows/deploy.yml`](../.github/workflows/deploy.yml):
-
-1. **`changes` job** — runs `dorny/paths-filter@v3` against the pushed commit and computes two booleans:
-
- ```
- api: packages/core/**, knowledge/**, docker/Dockerfile, fly.api.toml, .github/workflows/deploy.yml
- ui: packages/ui/**, docker/Dockerfile.ui, fly.ui.toml, .github/workflows/deploy.yml
- ```
-
- Editing the workflow itself triggers both, by design.
-
-2. **`deploy-api`** runs `flyctl deploy --remote-only --config fly.api.toml` if `api == true`. Authenticated with the `FLY_API_TOKEN_API` repo secret (an app-scoped deploy token).
-
-3. **`deploy-ui`** runs `flyctl deploy --remote-only --config fly.ui.toml` if `ui == true`. Uses `FLY_API_TOKEN_UI`.
-
-Each job uses a `concurrency` group so two pushes can't deploy the same app simultaneously. The workflow does **not** block on CI — branch protection on `main` is the gate; if it's off, broken pushes can deploy.
-
-### Manually trigger a deploy
-
-```
-gh workflow run "Deploy (dev)" -f target=api # api only
-gh workflow run "Deploy (dev)" -f target=ui # ui only
-gh workflow run "Deploy (dev)" -f target=both # both
+VECTOR_STORE_PATH = /data/chroma_db
+EPISODIC_DB_PATH = /data/episodic_memory.db
+COMPANY_PROFILE_PATH = /data/company/profile.yaml
+MCP_SERVERS_CONFIG_PATH = /data/company/mcp_servers.json
+WORKSPACE_MCP_CREDENTIALS_DIR = /data/google_credentials
```
-Useful when you want to redeploy without a code change (e.g., after rotating a secret).
+On first boot the volume is empty. ChromaDB rebuilds the built-in knowledge index
+from files shipped inside the Python package (`openexecutive/knowledge/builtin/`),
+and the SQLite database is created on demand. The company profile stays empty
+until you run the onboarding wizard against the deployed URL — the wizard failing
+with "no company profile" on a fresh volume is expected, not a fault.
---
-## One-time setup (from scratch)
-
-These steps were done once to bootstrap the environment. They are documented here for the next person.
-
-### 1. Install flyctl
-
-```
-brew install flyctl
-flyctl auth login # or: flyctl auth signup
-```
-
-### 2. Create both apps
-
-```
-flyctl apps create openexec-api-dev
-flyctl apps create openexec-ui-dev
-```
-
-### 3. Create the volume
-
-```
-flyctl volumes create executive_data --region iad --size 1 -a openexec-api-dev
-```
-
-Answer `y` to the "two-volumes-for-HA" warning — single-instance is intentional.
-
-### 4. Set secrets on the API app
-
-Minimum to boot — all three are required. Without any one the app fails startup and crash-loops (uvicorn exit 3): missing `ANTHROPIC_API_KEY` or `EXEC_EMAIL_ADDRESS` is a pydantic `ValidationError`; missing `BACKEND_SHARED_SECRET` raises a `RuntimeError` on Fly.
-
-```
-flyctl secrets set -a openexec-api-dev \
- ANTHROPIC_API_KEY=sk-ant-... \
- BACKEND_SHARED_SECRET=$(openssl rand -hex 32) \
-```
-
-(`BACKEND_SHARED_SECRET` must match the UI app's value — see the auth note below; `EXEC_EMAIL_ADDRESS` is a required `Settings` field with no default.)
-
-Optional integrations (add only the ones you want active on dev — use *dev* credentials, not personal/prod):
-
-```
-flyctl secrets set -a openexec-api-dev \
- USER_TIMEZONE=America/Los_Angeles \
- TELEGRAM_BOT_TOKEN=... \
- TELEGRAM_WEBHOOK_SECRET=$(openssl rand -hex 16) \
- GOOGLE_OAUTH_CLIENT_ID=... \
- GOOGLE_OAUTH_CLIENT_SECRET=... \
- SLACK_BOT_TOKEN=xoxb-... \
- SLACK_APP_TOKEN=xapp-... \
- SCHEDULED_ADMIN_TOKEN=$(openssl rand -hex 32)
-```
-
-> Channel access (who can DM the bot via Email / Telegram / Discord /
-> Slack) is roster-driven now — manage allowed senders via the /people
-> UI by adding their channel ID to a Person row. The old env-var
-> allowlists (EMAIL_ALLOWED_SENDERS, TELEGRAM_ALLOWED_CHAT_IDS,
-> DISCORD_ALLOWED_USER_IDS) have been removed.
-
-See [.env.example](../.env.example) for the full list and what each one does.
-
-> **Auth secrets are not optional in production.** The UI app needs `AUTH_SECRET`, `AUTH_GOOGLE_ID`, `AUTH_GOOGLE_SECRET`, `AUTH_URL`, `AUTH_TRUST_HOST`, `ALLOWED_EMAILS`, and `BACKEND_SHARED_SECRET`. The API app needs `BACKEND_SHARED_SECRET` (same value) and `BACKEND_ALLOWED_ORIGINS`. The API will refuse to start on Fly without `BACKEND_SHARED_SECRET` set. See [auth.md](auth.md) for the full setup including Google Cloud Console steps.
-
-### 5. Create per-app deploy tokens and add them to GitHub
-
-```
-flyctl tokens create deploy -a openexec-api-dev -x 999999h
-flyctl tokens create deploy -a openexec-ui-dev -x 999999h
-```
-
-Each command outputs `FlyV1 <macaroon>`. The full string (including the `FlyV1 ` prefix and space) is the token value.
-
-In GitHub: **Settings → Secrets and variables → Actions → New repository secret**:
+## Required configuration
-| Secret name | Value |
+| Variable | Why |
|---|---|
-| `FLY_API_TOKEN_API` | token from the `openexec-api-dev` command |
-| `FLY_API_TOKEN_UI` | token from the `openexec-ui-dev` command |
+| `ANTHROPIC_API_KEY` | Every agent call. The app will not start without it. |
+| `BACKEND_SHARED_SECRET` | Gates every API route via `x-api-key`. Generate with `openssl rand -hex 32`; the UI needs the same value. |
+| `OE_PUBLIC_DEPLOYMENT=1` | **Set this on every internet-reachable instance.** See below. |
+| `BACKEND_ALLOWED_ORIGINS` | Comma-separated UI origins allowed through CORS, e.g. `https://exec.example.com`. |
+| `AUTH_SECRET`, `AUTH_GOOGLE_ID`, `AUTH_GOOGLE_SECRET`, `AUTH_URL`, `ALLOWED_EMAILS` | UI sign-in. See [auth.md](auth.md). |
-### 6. First deploy
+Integrations (Slack, Discord, email, Google Workspace) are all optional and off
+unless their variables are set. [.env.example](../.env.example) is the full list.
-Either merge a PR to `main` or trigger manually:
+### `OE_PUBLIC_DEPLOYMENT`
+
+If `BACKEND_SHARED_SECRET` is unset the API serves every route unauthenticated.
+That is the intended default for local development and a serious incident
+anywhere else, so a deployment declares itself public:
```
-gh workflow run "Deploy (dev)" -f target=both
+OE_PUBLIC_DEPLOYMENT=1
```
-### 7. Configure external webhooks
-
-Once the API is reachable, point any external services at it:
-
-- **Telegram**: `curl -F "url=https://openexec-api-dev.fly.dev/webhook/telegram" "https://api.telegram.org/bot<DEV_TOKEN>/setWebhook"`
-- **Google OAuth**: in the GCP console, add `https://openexec-api-dev.fly.dev/oauth/google/callback` as an authorized redirect URI on the OAuth client.
+With it set and no shared secret, `create_app()` raises at startup instead of
+booting an open API. The check is deliberately fail-safe — any value other than
+`0`/`false`/`no`/`off`/empty arms it, so a typo requires the secret rather than
+skipping the check.
---
-## QA environment
-
-QA is a second, **more stable** environment that updates only when you deliberately promote a known-good commit. Dev moves on every push to `main`; QA moves only on the `qa` branch.
-
-| App | Config | Public URL | State |
-|---|---|---|---|
-| `openexec-api-qa` | [fly.api.qa.toml](../fly.api.qa.toml) — same image as dev | `https://openexec-api-qa.fly.dev` | Persistent volume `executive_data` at `/data` |
-| `openexec-ui-qa` | [fly.ui.qa.toml](../fly.ui.qa.toml) — `BACKEND_BASE_URL` points at the QA API | `https://openexec-ui-qa.fly.dev` | Stateless |
+## Health checks
-The QA apps are byte-for-byte the same Docker images as dev — only the app name, the API URL the UI proxies to, the secrets, and the deploy trigger differ.
-
-### Promotion flow
-
-[`.github/workflows/deploy-qa.yml`](../.github/workflows/deploy-qa.yml) deploys QA on push to the `qa` branch (path-filtered, same logic as dev) or via manual `workflow_dispatch`. To promote a vetted commit:
+`GET /health` is exempt from the shared-secret gate so a platform health checker
+can reach it unauthenticated. It returns:
+```json
+{"status": "ok", "builtin_knowledge_chunks": 1234, "version": "0.1.0"}
```
-git push origin main:qa # fast-forward qa to a known-good main
-# or open and merge a main → qa pull request
-gh workflow run "Deploy (qa)" -f target=both # redeploy without a code change
-```
-
-Dev is untouched by any of this — it still tracks `main`. There is no QA Honcho job: Honcho is hosted, and QA is isolated from dev by a QA-specific `HONCHO_WORKSPACE_ID` (see secrets below).
-### One-time setup
-
-```
-flyctl apps create openexec-api-qa
-flyctl apps create openexec-ui-qa
-flyctl volumes create executive_data --region iad --size 1 -a openexec-api-qa
-flyctl tokens create deploy -a openexec-api-qa -x 999999h # → FLY_API_TOKEN_API_QA
-flyctl tokens create deploy -a openexec-ui-qa -x 999999h # → FLY_API_TOKEN_UI_QA
-```
+**Give it a startup grace period of about 5 minutes.** A cold container builds
+the MCP tool-discovery vector index and loads Chroma before it serves. The
+embedding model is baked into the image, so no network fetch is involved, but
+the work is real — a short grace period will kill the container mid-boot in a
+crash loop that looks like a deploy failure.
-Add the two tokens as GitHub repo secrets `FLY_API_TOKEN_API_QA` and `FLY_API_TOKEN_UI_QA`.
+## Resources
-QA-specific secrets (differences from dev):
-
-```
-# API — distinct shared secret, QA-scoped hosted-Honcho workspace, separate bot creds
-flyctl secrets set -a openexec-api-qa \
- ANTHROPIC_API_KEY=sk-ant-... \
- BACKEND_SHARED_SECRET=$(openssl rand -hex 32) \
- BACKEND_ALLOWED_ORIGINS=https://openexec-ui-qa.fly.dev \
- HONCHO_ENABLED=true HONCHO_API_KEY=... HONCHO_BASE_URL=... \
- HONCHO_WORKSPACE_ID=openexec-qa \
- TELEGRAM_BOT_TOKEN=<QA bot> SLACK_BOT_TOKEN=<QA bot> ... # separate QA bot apps only
-
-# UI — same BACKEND_SHARED_SECRET as the API; QA OAuth redirect URI added in GCP
-flyctl secrets set -a openexec-ui-qa \
- AUTH_SECRET=$(openssl rand -base64 32) \
- AUTH_GOOGLE_ID=... AUTH_GOOGLE_SECRET=... ALLOWED_EMAILS=... \
- AUTH_TRUST_HOST=true AUTH_URL=https://openexec-ui-qa.fly.dev \
- BACKEND_SHARED_SECRET=<same value as the API app>
-```
-
-Then add `https://openexec-ui-qa.fly.dev/api/auth/callback/google` as an authorized redirect URI on the OAuth client, create separate QA bot apps for any channels QA should run (so QA and dev never double-reply), and complete the onboarding wizard against the QA URL — QA starts with an empty volume by design.
+**2 GB of memory for the API.** 1 GB out-of-memories during ingest, where the
+ONNX embedder and Chroma writes run concurrently. One shared CPU is sufficient;
+the workload is I/O-bound on the Anthropic API.
---
-## Google Workspace (co-located in the API)
+## Google Workspace credentials
-The Executive's Gmail/Calendar/Drive tools come from `workspace-mcp`
-(taylorwilsdon/google_workspace_mcp) via the MCP gateway. It runs **co-located
-inside the API** as a stdio child of the gateway — not a separate service —
-because the product is single-tenant (one install = one company = one exec Google
-account), so the server is inherently one-per-install. `workspace-mcp` is baked
-into the API image and launched by [docker/workspace-mcp-launch.sh](../docker/workspace-mcp-launch.sh)
-from the `google_workspace` entry in `/data/company/mcp_servers.json`. Its OAuth
-token (if any) persists at `/data/google_credentials` on the API's existing
-`executive_data` volume. No second Fly app, deploy token, or deploy job.
+The Gmail/Calendar/Drive tools come from `workspace-mcp`, which runs co-located
+inside the API as a stdio child of the MCP gateway rather than as its own
+service — the product is single-tenant, so the server is inherently one per
+install. It is baked into the API image and launched by
+[docker/workspace-mcp-launch.sh](../docker/workspace-mcp-launch.sh) from the
+`google_workspace` entry in `/data/company/mcp_servers.json` (see
+[packages/core/mcp_servers.json.example](../packages/core/mcp_servers.json.example)
+for the exact block).
-### Configure per install
+`GWORKSPACE_AUTH_MODE` picks the auth mode; it defaults to `oauth`.
-Everything is set on the **API** app. Pick one auth mode — `GWORKSPACE_AUTH_MODE`
-selects it (default `oauth`, set in [fly.api.toml](../fly.api.toml) `[env]`; a
-secret overrides the env value). The gateway forwards these to the
-`workspace-mcp` child.
+**Option A — `oauth` (single user).** Set `GOOGLE_OAUTH_CLIENT_ID` and
+`GOOGLE_OAUTH_CLIENT_SECRET`. The API serves no OAuth callback, so the token has
+to be seeded: complete the flow once locally with `WORKSPACE_MCP_CREDENTIALS_DIR`
+pointed at a local folder, then copy the credential file onto the volume.
-**Option A — `oauth` (single-user).** Set the client credentials on the API:
-
-```
-flyctl secrets set -a openexec-api-dev \
- GOOGLE_OAUTH_CLIENT_ID=... \
- GOOGLE_OAUTH_CLIENT_SECRET=...
+```bash
+docker compose exec api mkdir -p /data/google_credentials
+docker compose cp <local-credentials-dir>/<token-file> api:/data/google_credentials/
+docker compose restart api # the gateway reads config and credentials at startup
```
-There is no Google OAuth callback served by the API, so **seed the token**:
-complete the OAuth flow once **locally** (`uvx workspace-mcp` with
-`WORKSPACE_MCP_CREDENTIALS_DIR` pointed at a local folder), then copy the
-resulting credential file(s) onto the API volume:
-
-```
-flyctl ssh console -a openexec-api-dev -C "mkdir -p /data/google_credentials"
-flyctl ssh sftp shell -a openexec-api-dev
-# put <local-credentials-dir>/<token-file> /data/google_credentials/<token-file>
-```
-
-**Option B — `service_account` (domain-wide delegation).** No browser flow —
-needs Workspace **admin** to authorize the service account's client ID for the
+**Option B — `service_account` (domain-wide delegation).** No browser flow, but a
+Workspace admin must authorize the service account's client ID for the
Gmail/Calendar/Drive scopes:
```
-flyctl secrets set -a openexec-api-dev \
- GWORKSPACE_AUTH_MODE=service_account \
- GOOGLE_SERVICE_ACCOUNT_KEY_JSON="$(cat service-account.json)"
+GWORKSPACE_AUTH_MODE=service_account
+GOOGLE_SERVICE_ACCOUNT_KEY_JSON=<contents of service-account.json>
```
-(`GOOGLE_SERVICE_ACCOUNT_KEY_FILE` — a path to a key on the volume — works too.
-The launcher fails fast if neither the key nor `USER_GOOGLE_EMAIL` is set.)
+(`GOOGLE_SERVICE_ACCOUNT_KEY_FILE`, a path to a key already on the volume, works
+too. The launcher fails fast if neither the key nor `USER_GOOGLE_EMAIL` is set.)
-### Wire the gateway config
-
-The live gateway config is on the API volume at `/data/company/mcp_servers.json`
-(gitignored). The `google_workspace` entry must point `command` at the launcher
-(see [packages/core/mcp_servers.json.example](../packages/core/mcp_servers.json.example)
-for the exact block). After setting secrets or editing the config:
-
-```
-flyctl apps restart openexec-api-dev # gateway reads the config + secrets at startup
-```
-
-Confirm: `flyctl logs -a openexec-api-dev` shows `MCPGateway started`, and a
-calendar/email/drive request resolves a `google_workspace__*` tool. Egress is
-gated — the Executive can only email/invite/share with People on the roster.
-
-### Migrating off the old separate app
-
-If a previous setup created `openexec-gworkspace-dev`, retire it after the
-co-located path works: revert the `google_workspace` entry in
-`/data/company/mcp_servers.json` to the launcher form, then
-`flyctl apps destroy openexec-gworkspace-dev` (this also removes its
-`gworkspace_creds` volume) and delete the `FLY_API_TOKEN_GWORKSPACE` repo secret.
+Outbound egress is gated either way: the Executive can only email, invite, or
+share with People on the roster.
---
## Operations
-> The commands below use the dev app names. For QA, swap `-a openexec-api-dev` → `-a openexec-api-qa` (and likewise for the UI app).
-
-### Tail logs
-
-```
-flyctl logs -a openexec-api-dev
-flyctl logs -a openexec-ui-dev
-```
-
-### Status
-
-```
-flyctl status -a openexec-api-dev # machine state, volume attach, last release
-flyctl releases -a openexec-api-dev # release history
-```
-
-### Smoke checks
+```bash
+# Logs
+docker compose logs -f api
-```
-curl https://openexec-api-dev.fly.dev/health
-# {"status":"ok","builtin_knowledge_chunks":...,"version":"0.1.0"}
-
-curl https://openexec-ui-dev.fly.dev/api/backend/health
-# Same JSON, proxied through the UI
-```
+# Smoke the API directly
+curl -s -H "x-api-key: $BACKEND_SHARED_SECRET" https://api.example.com/health
-### Rotate a secret
+# Same JSON, proxied through the UI (exercises the shared secret end to end)
+curl -s https://exec.example.com/api/backend/health
-```
-flyctl secrets set -a openexec-api-dev SOME_KEY=newvalue
+# Inspect state on the volume — SELECT only unless you mean it
+docker compose exec api sqlite3 /data/episodic_memory.db \
+ "SELECT id, kind, status, run_at FROM scheduled_actions WHERE status='pending' LIMIT 10;"
```
-Fly automatically rolls the API machine. No manual deploy needed.
+**Rollback** is an image-tag rollback: redeploy the previous tag. The volume is
+not versioned with the image, so a release that migrates schema forward is not
+undone by rolling the image back — check what changed under `*/store.py` before
+relying on it.
-### Rollback
-
-```
-flyctl releases -a openexec-api-dev
-flyctl release rollback <version> -a openexec-api-dev
-```
-
-### Roll the volume forward / get a shell on it
-
-```
-flyctl ssh console -a openexec-api-dev
-# inside: ls /data
-```
+**Backups.** There is no snapshot cron in this repo. `/data/episodic_memory.db`
+is the irreplaceable part (Chroma rebuilds from source documents), so back it up
+with `sqlite3 /data/episodic_memory.db ".backup /tmp/backup.db"` and copy it off
+the host — a plain file copy of a live SQLite database can be torn.
---
@@ -371,21 +194,18 @@ flyctl ssh console -a openexec-api-dev
| Symptom | Likely cause | Fix |
|---|---|---|
-| Actions log: `failed to calculate checksum of ref … "/knowledge": not found` | Stale Dockerfile reference | Already fixed in PR #64; if it returns, ensure `docker/Dockerfile` doesn't `COPY` non-existent top-level dirs |
-| Deploy step says success, `/health` times out | App crashed during boot — usually a missing env var | `flyctl logs -a openexec-api-dev`; look for a Pydantic `ValidationError` and add the missing secret |
-| UI loads but every request errors | UI proxy can't reach API | Check `BACKEND_BASE_URL` in [fly.ui.toml](../fly.ui.toml); we use the public `.fly.dev` URL because alpine's resolver had trouble with `.flycast` IPv6 |
-| Two scheduled actions firing at the same time | Two API machines running | `flyctl status -a openexec-api-dev` — if more than one machine, `flyctl scale count 1 -a openexec-api-dev` |
-| Onboarding wizard fails with "no company profile" | Volume empty (first boot) | Expected. Complete the wizard via the UI; output lands at `/data/company/profile.yaml` |
-
-### Why not `.flycast`?
-
-`http://openexec-api-dev.flycast:8000` is Fly's private IPv6 anycast routing — same org, no public hop. We tried it; node 22 on alpine inside the UI container failed to resolve the AAAA record reliably, surfacing as opaque 500s on every `/api/backend/*` call. Public `https://openexec-api-dev.fly.dev` adds ~50ms but is reliable. If you confirm IPv6 resolution works in a future image, switching back to flycast is a one-line change in [fly.ui.toml](../fly.ui.toml).
+| Deploy reports success, `/health` never responds | Crash during boot, usually a missing env var | Read the API logs; look for a Pydantic `ValidationError` naming the variable |
+| Container is killed and restarted repeatedly during startup | Health-check grace period too short | Raise it to ~5 minutes (see above) |
+| API refuses to start: `BACKEND_SHARED_SECRET is required` | `OE_PUBLIC_DEPLOYMENT` is set with no secret | Working as intended — set the secret |
+| Every UI request errors, API is healthy | UI proxy can't reach the API, or the shared secret differs between them | Check `BACKEND_BASE_URL` on the UI and that both sides carry the same `BACKEND_SHARED_SECRET` |
+| Browser console shows CORS errors | UI origin missing from `BACKEND_ALLOWED_ORIGINS` | Add the exact scheme + host |
+| Scheduled actions firing twice | More than one API replica | Scale the API to exactly 1 (see the warning at the top) |
+| Onboarding wizard says "no company profile" | Empty volume on first boot | Expected — complete the wizard; output lands at `/data/company/profile.yaml` |
---
-## What's not done yet
+## Optional: self-hosted Honcho
-- **Volume backups** — single 1GB volume, no snapshot cron. Fly's `Scheduled snapshots: true` (5 retained) covers the basics, but there's no off-site copy. For dev this is fine.
-- **CI gate on the deploy workflow** — currently relies on branch protection. If you want a hard pre-deploy gate, switch the trigger to `workflow_run` on CI completion.
-- **Per-PR preview environments** — out of scope; everything ships to a single shared dev env on merge to `main`.
-- **Prod split** — still out of scope. The QA environment above is the worked example of the pattern: copy `fly.api.toml`/`fly.ui.toml` to a `*.<env>.toml` pair, create separate Fly apps, and add a parallel deploy workflow gated on a dedicated branch. Repeat for `prod` (gated on a `prod` branch or tag) when needed.
+Per-person memory can run against hosted Honcho (set `HONCHO_API_KEY` and
+`HONCHO_BASE_URL`) or a self-hosted instance. [docker/honcho/](../docker/honcho/)
+carries the image and configuration for the self-hosted path.
diff --git a/docs/honcho-hosting.md b/docs/honcho-hosting.md
deleted file mode 100644
index e0d16eba..00000000
--- a/docs/honcho-hosting.md
+++ /dev/null
@@ -1,425 +0,0 @@
-# Self-hosted Honcho on Fly
-
-OE's per-person memory layer ([honcho.dev](https://honcho.dev)) runs as a
-private Fly app. The OE API talks to it over Fly's internal network; it
-has no public IP. This runbook covers first-time provisioning, day-2
-operations, and version bumps.
-
-OE-side wiring lives in
-[`packages/core/openexecutive/memory/honcho_client.py`](../packages/core/openexecutive/memory/honcho_client.py)
-and is gated by `HONCHO_ENABLED`. Until that flag flips to `true` in
-`openexec-api-dev`'s secrets, OE behaves identically to before.
-
-## Architecture
-
-```
-openexec-api-dev (Fly app)
- │
- │ POST/GET via httpx → http://openexec-honcho-dev.flycast:8000
- ▼
-openexec-honcho-dev (Fly app, this runbook)
- ├── api process — FastAPI on :8000, internal-only
- ├── deriver process — background worker; runs extraction + dreaming
- ├── embed process — local OpenAI-compatible embeddings sidecar on :8001
- │ (fastembed + BAAI/bge-small-en-v1.5). No external
- │ embedding vendor; deriver reaches it via
- │ embed.process.openexec-honcho-dev.internal:8001
- └── Postgres — Fly Postgres with pgvector, attached
-
-All LLM calls (deriver, summary, dialectic levels, dream deduction) go
-out via OpenRouter using Honcho's `openai` transport with a custom
-`base_url`. Single outbound credential (`LLM_OPENAI_API_KEY` = OE's
-existing OpenRouter key). Models are OpenRouter slugs in OE's existing
-convention (dotted, matching `packages/core/openexecutive/providers/
-registry.py`): `anthropic/claude-haiku-4.5` for cheap-tier work
-(deriver / summary / dialectic minimal+low) and
-`anthropic/claude-sonnet-4.6` for medium+high+max dialectic and dream
-deduction.
-```
-
-## First-time provisioning
-
-Everything below assumes you have `flyctl` and an authenticated `fly`
-org. Run from the repo root.
-
-### 1. Create the app
-
-```bash
-flyctl apps create openexec-honcho-dev --org <your-org>
-```
-
-### 2. Stand up Postgres with pgvector
-
-Fly's managed Postgres ships pgvector out of the box on recent images.
-
-```bash
-# Create a 1-vCPU / 1GB Postgres cluster in iad.
-flyctl postgres create \
- --name openexec-honcho-pg \
- --region iad \
- --org <your-org> \
- --vm-size shared-cpu-1x \
- --volume-size 10
-
-# Attach to the Honcho app. This creates a DATABASE_URL secret on
-# openexec-honcho-dev.
-flyctl postgres attach openexec-honcho-pg -a openexec-honcho-dev
-
-# Enable pgvector. Honcho's migrations expect the extension to exist.
-flyctl postgres connect -a openexec-honcho-pg \
- -- -c 'CREATE EXTENSION IF NOT EXISTS vector;'
-```
-
-Honcho's config expects `DB_CONNECTION_URI` with the SQLAlchemy
-psycopg driver scheme; Fly Postgres attach injects `DATABASE_URL=postgres://...`
-which the psycopg dialect lookup rejects. Rewrite the scheme during the
-alias step:
-
-```bash
-RAW_URL=$(flyctl ssh console -a openexec-honcho-dev -C 'printenv DATABASE_URL')
-SQLA_URL=$(echo "$RAW_URL" | sed 's|^postgres://|postgresql+psycopg://|')
-flyctl secrets set -a openexec-honcho-dev DB_CONNECTION_URI="$SQLA_URL"
-```
-
-(Yes, the ssh-into-the-machine-just-to-read-an-env-var step is ugly —
-Fly's secrets API doesn't let you read a secret you've already set, and
-without the scheme rewrite the API crashes at first DB connect with
-"Can't load plugin: sqlalchemy.dialects:postgres". The runbook copy is
-here so nobody has to figure it out twice.)
-
-### 3. Set the remaining secrets
-
-OpenRouter is the only outbound LLM vendor — same account OE already
-uses. Embeddings come from the local `embed` process group (no key
-needed for the sidecar itself, but Honcho's OpenAI client requires
-*some* API key string, so we pass a placeholder).
-
-```bash
-flyctl secrets set -a openexec-honcho-dev \
- LLM_OPENAI_API_KEY="$OPENROUTER_API_KEY" \
- AUTH_JWT_SECRET="$(openssl rand -hex 32)" \
- EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL="http://embed.process.openexec-honcho-dev.internal:8001/v1" \
- EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY="local-no-auth-needed" \
- EMBEDDING_VECTOR_DIMENSIONS=384 \
- DERIVER_WORKERS=2 \
- SENTRY_ENABLED=false
-```
-
-Why this exact set of variables:
-
-- `LLM_OPENAI_API_KEY` holds an OpenRouter key because Honcho's
- `openai` transport accepts any OpenAI-format endpoint (verified
- against `src/llm/registry.py:73`). `config.toml` sets the per-slot
- `base_url` to OpenRouter for every LLM call, so the client
- authenticates with OpenRouter's key but speaks OpenAI's wire
- format. Consolidates dev billing onto your existing OpenRouter
- account.
-- `EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL` uses Honcho's
- nested-pydantic-settings convention (`env_prefix="EMBEDDING_"`,
- `env_nested_delimiter="__"`). The path is
- `EmbeddingSettings.MODEL_CONFIG.overrides.base_url`. **Plain
- `EMBEDDING_BASE_URL` is silently ignored** — verified against
- Honcho's settings loader. Same convention for the dummy API key.
-- `EMBEDDING_VECTOR_DIMENSIONS=384` matches bge-small-en-v1.5's
- output dim. Honcho's default schema is `Vector(1536)`; without
- this override AND the corresponding `configure_embeddings.py`
- ALTER (run automatically by Fly's `release_command`, see step 4),
- the deriver crashes on every embed call with a dimension
- mismatch.
-- `DERIVER_WORKERS=2` lifts Honcho's default of 1 (`DeriverSettings.WORKERS`
- per `src/config.py:736`). Two workers handle the bursty extraction +
- dreaming load comfortably on the 2GB deriver VM.
-
-Store `AUTH_JWT_SECRET` in a password manager — every issued
-`HONCHO_API_KEY` (set in step 5) is derived from it, so a rotation
-invalidates everything.
-
-### 4. Deploy
-
-```bash
-flyctl deploy -c fly.honcho.toml
-```
-
-Fly's `[deploy].release_command` (configured in `fly.honcho.toml`) runs
-`python scripts/provision_db.py && python scripts/configure_embeddings.py --yes`
-in a one-shot machine **before** the new release machines become
-active. That covers:
-
-- Schema migrations (Alembic under the hood; idempotent — no-ops when
- nothing changed)
-- `configure_embeddings.py` ALTERs the pgvector column dim to match
- `EMBEDDING_VECTOR_DIMENSIONS` from your secrets. Also idempotent.
-
-If the release_command fails the deploy aborts and the previous
-release stays active — you won't end up with a half-migrated database
-serving a new image. Verify everything came up:
-
-```bash
-flyctl status -a openexec-honcho-dev
-# Expect three machines: one running `api`, one `deriver`, one `embed`.
-```
-
-### 5. Generate an API key + wire OE
-
-Honcho v3.0.7 does not ship a token-minting CLI command. Use the
-`create_admin_jwt()` Python helper from inside the running api container
-— it reads `AUTH_JWT_SECRET` from the environment and returns a signed
-admin JWT good against every workspace:
-
-```bash
-flyctl ssh console -a openexec-honcho-dev --process-group api \
- -C 'python -c "from src.security import create_admin_jwt; print(create_admin_jwt())"'
-# Outputs: eyJ... (a JWT string — use this verbatim as HONCHO_API_KEY)
-```
-
-**Security note**: an admin JWT is a master key for the entire Honcho
-instance — it can read any peer's memory, mint new tokens, and rotate
-keys. Using one as `HONCHO_API_KEY` in dev means anyone with read access
-to `openexec-api-dev`'s Fly secrets can take over the Honcho deployment.
-For a strictly-isolated dev environment that's acceptable, but if dev
-secrets sit next to any real-user PII pipe (a live Slack workspace, a
-shared Discord server), treat that as production and skip straight to
-workspace-scoped tokens.
-
-For prod, mint a workspace-scoped key by hitting `POST /v3/keys` with
-the admin JWT and a body limiting scope to the `openexec` workspace
-(see Honcho's API docs); never put an admin JWT in
-`openexec-api-prod`'s secrets. If a dev admin JWT leaks, rotate
-`AUTH_JWT_SECRET` immediately (see "Rotate the JWT secret" below) —
-that invalidates every issued token in one shot.
-
-Set OE-side secrets:
-
-```bash
-flyctl secrets set -a openexec-api-dev \
- HONCHO_ENABLED=true \
- HONCHO_API_KEY=hch-... \
- HONCHO_BASE_URL=http://openexec-honcho-dev.flycast:8000 \
- HONCHO_WORKSPACE_ID=openexec
-```
-
-OE's wrapper picks up the new env on the next deploy or restart.
-
-### 6. Smoke
-
-```bash
-# From inside openexec-api-dev:
-flyctl ssh console -a openexec-api-dev \
- -C 'curl -sf -H "Authorization: Bearer $HONCHO_API_KEY" \
- http://openexec-honcho-dev.flycast:8000/v3/workspaces'
-```
-
-Then exercise an end-to-end turn from the UI (or a Slack/Discord DM as
-a user with a matching `Person` row) and check the Honcho deriver logs
-for processed messages:
-
-```bash
-flyctl logs -a openexec-honcho-dev | grep -i deriver
-```
-
-## Day-2 operations
-
-### Inspect logs
-
-```bash
-flyctl logs -a openexec-honcho-dev # tail both processes
-flyctl logs -a openexec-honcho-dev --process-group api # api only
-flyctl logs -a openexec-honcho-dev --process-group deriver # deriver only
-```
-
-### Database backup
-
-Fly Postgres takes automatic volume snapshots (retention varies by plan
-— check the Fly dashboard for your cluster's current schedule). The
-current `flyctl` does not expose a "create backup now" subcommand;
-`flyctl postgres --help` only lists create/db/detach/events/failover/
-import/list/renew-certs/restart/users. For an ad-hoc snapshot before a
-risky change, take a `pg_dump`:
-
-```bash
-# Pull credentials the same way step 2 did — secrets aren't readable via
-# `flyctl secrets list`, so we ssh into the api container and parse the
-# already-aliased DB_CONNECTION_URI.
-DB_URL=$(flyctl ssh console -a openexec-honcho-dev --process-group api \
- -C 'printenv DB_CONNECTION_URI' \
- | sed 's|^postgresql+psycopg://|postgres://|') # pg_dump wants the bare scheme
-
-# Proxy the cluster locally, then dump.
-flyctl proxy 5432 -a openexec-honcho-pg & # tunnels Fly PG to localhost:5432
-PROXY_PID=$!
-pg_dump "$DB_URL" > honcho-$(date +%Y%m%d).sql
-kill $PROXY_PID
-```
-
-To restore, see Fly's PG runbook
-([fly.io/docs/postgres/managing](https://fly.io/docs/postgres/managing/));
-do not invent your own restore procedure here without testing on a
-throwaway cluster first.
-
-### Embedding quality ladder
-
-The default deploy uses `BAAI/bge-small-en-v1.5` (384-dim, ~130MB)
-served by the local `embed` process. On the MTEB English benchmark this
-is roughly tied with OpenAI's `text-embedding-3-small`, but it's smaller
-and English-only. If retrieval quality feels weak (use the quality
-probe below to confirm), climb the ladder before reaching for a vendor
-embedding API.
-
-| Step | Model | Image+RAM delta | How to switch |
-|---|---|---|---|
-| Default | `BAAI/bge-small-en-v1.5` (384-dim) | baseline | shipped |
-| 1 | `BAAI/bge-base-en-v1.5` (768-dim) | +300MB image, +400MB RAM | `flyctl secrets set -a openexec-honcho-dev EMBED_MODEL=BAAI/bge-base-en-v1.5` (then rebuild + redeploy — fastembed needs the model in its cache, which is baked at build time) |
-| 2 | `BAAI/bge-large-en-v1.5` (1024-dim) | +1.2GB image, +1.2GB RAM | same pattern; bump the `embed` VM to 2GB in `fly.honcho.toml` first |
-| 3 | OpenRouter `openai/text-embedding-3-small` (1536-dim) | network hop, ~$0.02/M tokens | `flyctl secrets set -a openexec-honcho-dev EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL=https://openrouter.ai/api/v1 EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY="$OPENROUTER_API_KEY" EMBEDDING_VECTOR_DIMENSIONS=1536` AND change `[embedding.model_config].model` in `config.toml` to `openai/text-embedding-3-small`. The vector-dim change triggers `configure_embeddings.py --yes` (run by `release_command`) to ALTER the pgvector column from 384 to 1536 — destructive on existing embeddings; back up first. |
-
-Step 3 reaches outside Fly's network for embeddings — only do it if
-local models genuinely underperform. The OpenRouter cost on dev volume
-is negligible (~$1-2/month) but the data-residency posture changes.
-
-### Quality probe
-
-The "is retrieval actually working" check, run once a week or before a
-config bump:
-
-1. Pick 5 turns from the past 7 days where a `Person` told the
- Executive something durable (preference, ongoing concern, factual
- claim). Note the message contents.
-2. Ask each of those Persons (or simulate via a dev account that maps
- to a `Person` row) a follow-up that *references* the earlier fact
- without naming it directly. Example: original "I prefer terse
- bullet points"; probe "summarize Q3 for me — what level of detail
- do you want?"
-3. Score each probe 0-2:
- - 2: peer_memory block clearly surfaced the relevant fact
- - 1: surfaced something tangentially related
- - 0: missed it entirely (irrelevant or empty block)
-4. Average across the 5 probes. If &lt; 1.5, climb the embedding ladder.
- If &gt; 1.7, you can probably tier down (or stay put).
-
-Capture results in a markdown table somewhere — the trend over time
-matters more than any single score.
-
-### Cost monitoring
-
-Two cost meters to watch:
-
-- **OpenRouter dashboard** — `LLM_OPENAI_API_KEY` (your OpenRouter key)
- drives every Honcho LLM call. Filter the OpenRouter usage view by the
- call pattern actually configured in `docker/honcho/config.toml`:
- **Haiku** for deriver / summary / dialectic minimal+low; **Sonnet**
- for dialectic medium+high+max and dream deduction. The biggest line
- items in practice are likely dreaming (continuous background, Sonnet)
- and the deriver (one Haiku call per inbound user message). Expect a
- few dollars per day on dev traffic — confirm with a week of real
- OpenRouter data before estimating prod-volume cost.
-- **Fly billing** — three machines (api 1.5GB, deriver 2GB, embed 1GB)
- plus the Postgres cluster. Sticker for the dev cluster lands roughly
- $25-35/month on shared-cpu instances.
-
-If OpenRouter spend spikes, the first knob to turn is dreaming
-frequency / on-off. Honcho exposes `[dream].FREQUENCY_HOURS` and the
-master switch `[dream].ENABLED`; setting `ENABLED=false` halts all
-background spend within a deriver tick (~1s).
-
-### Rotate the JWT secret
-
-```bash
-NEW_SECRET=$(openssl rand -hex 32)
-flyctl secrets set -a openexec-honcho-dev AUTH_JWT_SECRET="$NEW_SECRET"
-# Mint a new API key with the new secret (see step 5).
-flyctl secrets set -a openexec-api-dev HONCHO_API_KEY=hch-new-...
-```
-
-Rotation invalidates all previously-issued tokens. OE's wrapper will
-401 until both secrets are updated and the OE app restarts — schedule
-the rotation accordingly.
-
-### Bump Honcho version
-
-```bash
-# 1. Read the release notes — Honcho ships breaking schema changes
-# between minors. https://github.com/plastic-labs/honcho/releases
-#
-# 2. Update the pin in docker/honcho/Dockerfile:
-# ARG HONCHO_VERSION=v3.0.7 → v3.0.8 (or whatever)
-#
-# 3. Deploy. Fly's [deploy].release_command (configured in
-# fly.honcho.toml) runs provision_db.py + configure_embeddings.py --yes
-# automatically before new machines become active — no separate
-# migration step needed. If the release_command fails the deploy
-# aborts and the previous release stays serving.
-flyctl deploy -c fly.honcho.toml
-
-# 4. Smoke (step 6 above). Roll back via `flyctl releases rollback`
-# AND `alembic downgrade` if needed.
-```
-
-Don't bump Honcho versions in the same PR as OE-side changes — keep
-the upgrade isolated so a rollback is single-purpose.
-
-### GitHub Actions deploy
-
-`.github/workflows/deploy.yml` includes a `deploy-honcho` job that
-auto-deploys on push to `main` whenever files under `docker/honcho/**`,
-`fly.honcho.toml`, or the workflow itself change. Manual deploys are
-also available via the workflow's `workflow_dispatch` trigger — pick
-`honcho` as the target.
-
-Schema migrations + the `configure_embeddings.py` ALTER run as Fly's
-`[deploy].release_command` (configured in `fly.honcho.toml`) — a
-one-shot machine that runs before new release machines become active.
-The CI workflow itself doesn't SSH into the cluster; if the
-release_command fails, the deploy aborts and the previous release
-stays serving, so a bad migration never reaches user traffic.
-
-**One-time setup the operator must do**:
-
-1. Generate a Fly API token scoped to `openexec-honcho-dev`:
- ```bash
- flyctl tokens create deploy -a openexec-honcho-dev
- ```
-2. In the GitHub repo settings → Secrets and variables → Actions, add
- a new repository secret `FLY_API_TOKEN_HONCHO` with the token value.
-
-We use a separate per-app token (mirroring `FLY_API_TOKEN_API` /
-`FLY_API_TOKEN_UI`) so a compromised CI token for the api/ui can't
-also reach the memory app.
-
-**Note**: the `"both"` choice in the `workflow_dispatch` target dropdown
-intentionally does NOT include honcho — Honcho is a memory dep, not
-part of the app pair, and we don't want a routine `api`/`ui` push to
-cycle the deriver mid-thought. Bump Honcho explicitly.
-
-### Kill switch
-
-If Honcho is misbehaving (returning bad context, costing too much,
-whatever), flip the OE-side flag without touching the Honcho app:
-
-```bash
-flyctl secrets set -a openexec-api-dev HONCHO_ENABLED=false
-```
-
-OE's wrapper no-ops immediately on the next turn. The Honcho app keeps
-running but receives no traffic — fine for debugging without
-double-rollout pressure.
-
-## Graduating to prod
-
-When the dev app proves out, the prod equivalent is the same recipe with
-different names:
-
-- `openexec-honcho-prod` app.
-- `openexec-honcho-prod-pg` Postgres cluster (consider larger VM + larger
- volume; check pgvector index sizing first).
-- Separate `HONCHO_API_KEY` (don't share dev's).
-- Decide whether prod stays on the Haiku-cheap-tier / Sonnet-deep-tier
- split via OpenRouter (cheapest with what we already use) or
- diversifies the OpenRouter model slugs for the deriver tier (e.g.
- `google/gemini-2.5-flash` is meaningfully cheaper per token at
- comparable quality). Per-call routing through OpenRouter means
- swapping is a config-line change — no second vendor relationship.
-- Add the prod app to OE's deploy automation (CI workflow + Makefile
- target).
-
-A clean separation here matters: dev and prod must not share a Honcho
-workspace, or a malformed test turn pollutes a real user's peer card.
diff --git a/fly.api.qa.toml b/fly.api.qa.toml
deleted file mode 100644
index 098f72c1..00000000
--- a/fly.api.qa.toml
+++ /dev/null
@@ -1,67 +0,0 @@
-# Fly app config — Open Executive API, QA environment (FastAPI + scheduler)
-#
-# Stable twin of fly.api.toml. Identical image and runtime; only the app name
-# differs. QA is promoted deliberately by pushing to the `qa` branch (see
-# .github/workflows/deploy-qa.yml), so it lags dev and stays stable.
-#
-# Single-instance only: the scheduler claims rows with UPDATE…RETURNING and
-# would duplicate work if two machines were running. Do not scale `count`
-# above 1 without disabling the scheduler on the extra instances.
-#
-# Provision once:
-# flyctl apps create openexec-api-qa
-# flyctl volumes create executive_data --region iad --size 1 -a openexec-api-qa
-# flyctl secrets set -a openexec-api-qa ANTHROPIC_API_KEY=... BACKEND_SHARED_SECRET=... (etc.)
-
-app = "openexec-api-qa"
-primary_region = "iad"
-
-[build]
- dockerfile = "docker/Dockerfile"
-
-# "immediate" replaces in place rather than spinning up a second machine
-# during the rollout. Combined with min/max=1 below this guarantees the
-# scheduler is never running on two machines at once.
-[deploy]
- strategy = "immediate"
-
-[env]
- VECTOR_STORE_PATH = "/data/chroma_db"
- COMPANY_PROFILE_PATH = "/data/company/profile.yaml"
- EPISODIC_DB_PATH = "/data/episodic_memory.db"
- MCP_SERVERS_CONFIG_PATH = "/data/company/mcp_servers.json"
- ENABLE_CACHING = "true"
- SCHEDULER_ENABLED = "true"
-
-[[mounts]]
- source = "executive_data"
- destination = "/data"
-
-[http_service]
- internal_port = 8000
- force_https = true
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
- max_machines_running = 1
- processes = ["app"]
-
-[[http_service.checks]]
- # extensible-mcp builds a tool-discovery vector index at startup. Its
- # embedding model (sentence-transformers/all-MiniLM-L6-v2) is now baked into
- # the image (see docker/Dockerfile: HF_HOME + offline flags), so the boot no
- # longer fetches it from Hugging Face — but index build plus the main app's
- # Chroma load still take time on a cold machine. 5 minutes gives headroom
- # without masking a genuinely stuck process.
- grace_period = "5m"
- interval = "30s"
- method = "GET"
- timeout = "10s"
- path = "/health"
-
-[[vm]]
- cpu_kind = "shared"
- cpus = 1
- # 1 GB OOMs the ingest pipeline (ONNX embedder + Chroma writes).
- # 2 GB has comfortably handled ingest + MCP startup in testing.
- memory_mb = 2048
diff --git a/fly.api.toml b/fly.api.toml
deleted file mode 100644
index 69d17727..00000000
--- a/fly.api.toml
+++ /dev/null
@@ -1,70 +0,0 @@
-# Fly app config — Open Executive API (FastAPI + scheduler)
-#
-# Single-instance only: the scheduler claims rows with UPDATE…RETURNING and
-# would duplicate work if two machines were running. Do not scale `count`
-# above 1 without disabling the scheduler on the extra instances.
-#
-# Provision once:
-# flyctl apps create openexec-api-dev
-# flyctl volumes create executive_data --region iad --size 1 -a openexec-api-dev
-# flyctl secrets set -a openexec-api-dev ANTHROPIC_API_KEY=... (etc.)
-
-app = "openexec-api-dev"
-primary_region = "iad"
-
-[build]
- dockerfile = "docker/Dockerfile"
-
-# "immediate" replaces in place rather than spinning up a second machine
-# during the rollout. Combined with min/max=1 below this guarantees the
-# scheduler is never running on two machines at once.
-[deploy]
- strategy = "immediate"
-
-[env]
- VECTOR_STORE_PATH = "/data/chroma_db"
- COMPANY_PROFILE_PATH = "/data/company/profile.yaml"
- EPISODIC_DB_PATH = "/data/episodic_memory.db"
- MCP_SERVERS_CONFIG_PATH = "/data/company/mcp_servers.json"
- ENABLE_CACHING = "true"
- SCHEDULER_ENABLED = "true"
- # Co-located Google Workspace MCP child (docker/workspace-mcp-launch.sh).
- # Credentials persist on the /data volume; tier is the full tool surface.
- # Per-install auth: set GWORKSPACE_AUTH_MODE (default oauth) + the Google
- # secrets via `flyctl secrets set` — see docs/deployment.md.
- WORKSPACE_MCP_CREDENTIALS_DIR = "/data/google_credentials"
- WORKSPACE_MCP_TOOL_TIER = "complete"
- GWORKSPACE_AUTH_MODE = "oauth"
-
-[[mounts]]
- source = "executive_data"
- destination = "/data"
-
-[http_service]
- internal_port = 8000
- force_https = true
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
- max_machines_running = 1
- processes = ["app"]
-
-[[http_service.checks]]
- # extensible-mcp builds a tool-discovery vector index at startup. Its
- # embedding model (sentence-transformers/all-MiniLM-L6-v2) is now baked into
- # the image (see docker/Dockerfile: HF_HOME + offline flags), so the boot no
- # longer fetches it from Hugging Face — but index build plus the main app's
- # Chroma load still take time on a cold machine. 5 minutes gives headroom
- # without masking a genuinely stuck process.
- grace_period = "5m"
- interval = "30s"
- method = "GET"
- timeout = "10s"
- path = "/health"
-
-[[vm]]
- cpu_kind = "shared"
- cpus = 1
- # 1 GB OOMs the ingest pipeline (ONNX embedder + Chroma writes).
- # 2 GB has comfortably handled ingest + MCP startup in testing.
- memory_mb = 2048
diff --git a/fly.honcho.toml b/fly.honcho.toml
deleted file mode 100644
index 5dd8651c..00000000
--- a/fly.honcho.toml
+++ /dev/null
@@ -1,160 +0,0 @@
-# Fly app config — Open Executive's self-hosted Honcho memory service.
-#
-# Internal-only: no [http_service] block, no public IP. Reachable from
-# other Fly apps in the same org via:
-# openexec-honcho-dev.flycast (load-balanced internal IPv6 — api process)
-# embed.process.openexec-honcho-dev.internal (per-process group DNS — embed process)
-# <id>.vm.openexec-honcho-dev.internal (per-machine 6PN DNS)
-# Set HONCHO_BASE_URL=http://openexec-honcho-dev.flycast:8000 in the
-# openexec-api-dev secrets to point OE's wrapper at this service.
-#
-# Three process groups:
-# api — FastAPI on :8000. Handles all client traffic.
-# deriver — Background worker that runs Honcho's extraction + dreaming
-# passes (`src.deriver`). Two workers in dev.
-# embed — Local OpenAI-compatible embeddings sidecar on :8001
-# (docker/honcho/embed_server.py, fastembed +
-# BAAI/bge-small-en-v1.5). The deriver hits it for
-# embeddings, keeping that data path inside Fly's network.
-#
-# Provision once (see docs/honcho-hosting.md for the full sequence,
-# including the DATABASE_URL → DB_CONNECTION_URI scheme rewrite):
-# flyctl apps create openexec-honcho-dev
-# flyctl postgres create --name openexec-honcho-pg --region iad
-# flyctl postgres attach openexec-honcho-pg -a openexec-honcho-dev
-# flyctl secrets set -a openexec-honcho-dev \
-# LLM_OPENAI_API_KEY="$OPENROUTER_API_KEY" \
-# AUTH_JWT_SECRET="$(openssl rand -hex 32)" \
-# EMBEDDING_MODEL_CONFIG__OVERRIDES__BASE_URL="http://embed.process.openexec-honcho-dev.internal:8001/v1" \
-# EMBEDDING_MODEL_CONFIG__OVERRIDES__API_KEY="local-no-auth-needed" \
-# EMBEDDING_VECTOR_DIMENSIONS=384 \
-# DERIVER_WORKERS=2 \
-# SENTRY_ENABLED=false
-# flyctl deploy -c fly.honcho.toml
-# NOTE: Honcho's pydantic-settings convention is `env_prefix="EMBEDDING_"`
-# with `env_nested_delimiter="__"`. Plain `EMBEDDING_BASE_URL` is
-# silently IGNORED — the nested form above is the load-bearing name.
-
-app = "openexec-honcho-dev"
-primary_region = "iad"
-
-[build]
- dockerfile = "docker/honcho/Dockerfile"
-
-# Fly's release_command runs once per deploy in a one-shot machine
-# BEFORE the new app machines become active. We use it for Honcho's DB
-# bootstrap so:
-# - migrations land before any api/deriver request can hit a stale
-# schema (no race; no SSH from CI; no chicken-and-egg if the
-# previous api was crash-looping)
-# - `configure_embeddings.py --yes` ALTERs the pgvector column dim
-# to match the configured embedding model (384 for bge-small).
-# Idempotent: no-ops when current dim matches.
-# Both scripts ship in the Honcho repo and are stable across minor
-# version bumps; if either is renamed in a future Honcho release,
-# update this line in the same PR as the HONCHO_VERSION bump.
-[deploy]
- release_command = "sh -c 'python scripts/provision_db.py && python scripts/configure_embeddings.py --yes'"
-
-# Three process groups share the same image; Fly's [processes] block
-# picks which CMD each machine runs. The .venv is on PATH so commands
-# don't need an `uv run` prefix.
-#
-# embed binds `::` (IPv6 all-interfaces) — NOT `0.0.0.0`. Fly's
-# `<process>.process.<app>.internal` DNS resolves to 6PN AAAA records
-# only; an IPv4-only listen accepts no connections from the deriver and
-# every embed call times out. `::` on Linux dual-stacks v4+v6 so this
-# also still works from `flyctl proxy 8001:8001 -a ...` for ad-hoc
-# debugging.
-[processes]
- api = "fastapi run --host 0.0.0.0 src/main.py"
- deriver = "python -m src.deriver"
- embed = "uvicorn embed_server:app --host :: --port 8001 --workers 1"
-
-# Deliberately NO [http_service] block — that would allocate a public
-# IP and expose the API. Internal callers reach the api process on
-# port 8000 over Fly's 6PN. If you ever run `flyctl ips allocate-v4`
-# or `allocate-v6` for debugging, RELEASE IT before you walk away —
-# the [[services]] blocks below have no TLS handler, so any public IP
-# would expose plaintext :8000 / :8001 to the internet. If you need
-# public access for real, add an `[http_service]` with
-# `force_https = true` AND confirm AUTH_USE_AUTH is still on (config.toml
-# enforces it, but double-check after the change).
-
-# api process — 1.5GB to leave headroom alongside Honcho's tokenisers
-# and dialectic-chat scratch space.
-[[vm]]
- memory = "1.5gb"
- cpu_kind = "shared"
- cpus = 1
- processes = ["api"]
-
-# deriver process — 2GB matches upstream Honcho recommendation; the
-# dreaming pass holds more working state than the simple deriver in
-# our previous MVP config. DERIVER_WORKERS=2 set via Fly secret keeps
-# the background queue moving without burning a third deriver machine.
-[[vm]]
- memory = "2gb"
- cpu_kind = "shared"
- cpus = 1
- processes = ["deriver"]
-
-# embed process — fastembed loads the BGE-small ONNX model (~130MB) +
-# inference scratch. 1GB is generous; bumps if/when we move up the
-# embedding quality ladder (bge-base ~700MB, bge-large ~1.5GB).
-[[vm]]
- memory = "1gb"
- cpu_kind = "shared"
- cpus = 1
- processes = ["embed"]
-
-# api healthcheck — Honcho's /health is unauthenticated and returns
-# {"status":"ok"} (src/main.py).
-[[services]]
- internal_port = 8000
- protocol = "tcp"
- processes = ["api"]
-
- # Fly validation requires every [[services]] to declare at least one
- # port. We declare port 8000 with NO handlers — no TLS termination,
- # no public HTTP entrypoint. Combined with no public IP allocation,
- # this stays a private TCP service reachable only on flycast / 6PN.
- [[services.ports]]
- port = 8000
- handlers = []
-
- [[services.http_checks]]
- interval = "30s"
- timeout = "5s"
- grace_period = "20s"
- method = "get"
- path = "/health"
- protocol = "http"
-
-# embed healthcheck — embed_server.py's /health returns
-# {"status":"ok", "model": EMBED_MODEL}.
-[[services]]
- internal_port = 8001
- protocol = "tcp"
- processes = ["embed"]
-
- [[services.ports]]
- port = 8001
- handlers = []
-
- [[services.http_checks]]
- interval = "30s"
- timeout = "5s"
- grace_period = "30s" # fastembed model-load can take a moment on cold start
- method = "get"
- path = "/health"
- protocol = "http"
-
-# Honcho exposes Prometheus metrics on the API at /metrics. Keep on
-# the same internal port — no scraping configured yet, but the
-# operator can `flyctl proxy 9091:8000 -a openexec-honcho-dev` for ad-hoc
-# inspection.
-[[metrics]]
- port = 8000
- path = "/metrics"
- processes = ["api"]
diff --git a/fly.ui.qa.toml b/fly.ui.qa.toml
deleted file mode 100644
index ff11b3f8..00000000
--- a/fly.ui.qa.toml
+++ /dev/null
@@ -1,41 +0,0 @@
-# Fly app config — Open Executive UI, QA environment (Next.js, standalone output)
-#
-# Stable twin of fly.ui.toml. Only the app name and the backend URL differ:
-# this UI points at the QA API, not dev. Promoted via the `qa` branch.
-#
-# Stateless; safe to auto-stop and scale horizontally if ever needed.
-# Provision once:
-# flyctl apps create openexec-ui-qa
-# flyctl secrets set -a openexec-ui-qa AUTH_SECRET=... AUTH_GOOGLE_ID=... \
-# AUTH_GOOGLE_SECRET=... ALLOWED_EMAILS=... AUTH_TRUST_HOST=true \
-# AUTH_URL=https://openexec-ui-qa.fly.dev BACKEND_SHARED_SECRET=<same as API>
-
-app = "openexec-ui-qa"
-primary_region = "iad"
-
-[build]
- dockerfile = "docker/Dockerfile.ui"
-
-[env]
- # The UI proxies all backend traffic through its server-side route at
- # /api/backend/[...path], which reads BACKEND_BASE_URL at request time.
- # We use the public Fly URL rather than `.flycast` (private IPv6 anycast)
- # because Node's fetch on alpine has flaky AAAA-record resolution that
- # surfaces as opaque 500s from the proxy. The public route adds a small
- # latency hop but is reliable. Switch to flycast if you confirm IPv6
- # resolution works in your build.
- BACKEND_BASE_URL = "https://openexec-api-qa.fly.dev"
- NODE_ENV = "production"
-
-[http_service]
- internal_port = 3000
- force_https = true
- auto_stop_machines = true
- auto_start_machines = true
- min_machines_running = 0
- processes = ["app"]
-
-[[vm]]
- cpu_kind = "shared"
- cpus = 1
- memory_mb = 512
diff --git a/fly.ui.toml b/fly.ui.toml
deleted file mode 100644
index 8737c2a0..00000000
--- a/fly.ui.toml
+++ /dev/null
@@ -1,36 +0,0 @@
-# Fly app config — Open Executive UI (Next.js, standalone output)
-#
-# Stateless; safe to auto-stop and scale horizontally if ever needed.
-# Provision once:
-# flyctl apps create openexec-ui-dev
-# (no volume; no secrets needed unless we add a server-only one later)
-
-app = "openexec-ui-dev"
-primary_region = "iad"
-
-[build]
- dockerfile = "docker/Dockerfile.ui"
-
-[env]
- # The UI proxies all backend traffic through its server-side route at
- # /api/backend/[...path], which reads BACKEND_BASE_URL at request time.
- # We use the public Fly URL rather than `.flycast` (private IPv6 anycast)
- # because Node's fetch on alpine has flaky AAAA-record resolution that
- # surfaces as opaque 500s from the proxy. The public route adds a small
- # latency hop but is reliable. Switch to flycast if you confirm IPv6
- # resolution works in your build.
- BACKEND_BASE_URL = "https://openexec-api-dev.fly.dev"
- NODE_ENV = "production"
-
-[http_service]
- internal_port = 3000
- force_https = true
- auto_stop_machines = true
- auto_start_machines = true
- min_machines_running = 0
- processes = ["app"]
-
-[[vm]]
- cpu_kind = "shared"
- cpus = 1
- memory_mb = 512
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 070e7546..07efbcdc 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -137,7 +137,8 @@ def _configure_logging() -> None:
_configure_logging()
-# Paths that bypass the shared-secret gate. /health is hit by Fly's checker;
+# Paths that bypass the shared-secret gate. /health is hit by the platform's
+# health checker;
# the /webhook/* routes are called by external services (Google, Telegram) and
# carry their own verification.
_UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
@@ -177,7 +178,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
initialize_db()
initialize_alerts_db()
- # User-generated company fixtures (DB-backed; persists on the Fly volume).
+ # User-generated company fixtures (DB-backed; persists on the data volume).
from openexecutive.fixtures.store import initialize_db as initialize_fixtures_db
initialize_fixtures_db()
@@ -347,9 +348,9 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
from openexecutive.workflows.resumer import run_resumer
resumer_task = asyncio.create_task(run_resumer())
- # Discord gateway bot. Embedded in the lifespan (rather than a sibling Fly
- # app) because the bot needs direct access to the same SQLite + ChromaDB
- # under /data, and Fly volumes attach to a single machine. Same pattern as
+ # Discord gateway bot. Embedded in the lifespan (rather than a sibling
+ # service) because the bot needs direct access to the same SQLite + ChromaDB
+ # under /data, and that volume attaches to a single instance. Same pattern as
# email_poller above. Skipped when no token is configured.
if settings.discord_bot_token:
_discord_log = logging.getLogger("openexecutive")
@@ -397,7 +398,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# Shut Discord down FIRST so the gateway stops accepting new events before
# we tear down email_poller/scheduler/resumer that handlers might call into.
# Bounded timeout: discord.py's close handshake can stall during a reconnect,
- # and a hung shutdown blocks the FastAPI lifespan and risks SIGKILL on Fly.
+ # and a hung shutdown blocks the FastAPI lifespan and risks SIGKILL.
if discord_bot is not None or discord_bot_task is not None:
async def _shutdown_discord() -> None:
if discord_bot is not None:
@@ -450,6 +451,22 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# Cleanup if needed (ChromaDB handles persistence)
+# Values that explicitly mean "not a public deployment". Anything else
+# non-empty arms the guard: for a fail-closed check, an unrecognised value
+# must err toward requiring the secret, never toward skipping it.
+_FALSEY_ENV = frozenset({"", "0", "false", "no", "off"})
+
+
+def _is_public_deployment() -> bool:
+ """Whether this process is serving an internet-reachable deployment.
+
+ Driven by the explicit ``OE_PUBLIC_DEPLOYMENT`` env var rather than any
+ hosting provider's injected variables, so the check works identically on
+ every platform (and in plain Docker). See docs/deployment.md.
+ """
+ return os.environ.get("OE_PUBLIC_DEPLOYMENT", "").strip().lower() in _FALSEY_ENV
+
+
def create_app() -> FastAPI:
app = FastAPI(
title="Open Executive API",
@@ -460,7 +477,7 @@ def create_app() -> FastAPI:
# Allowed UI origins: localhost for `make dev`, plus any production
# origins listed in BACKEND_ALLOWED_ORIGINS (comma-separated, e.g.
- # "https://openexec-ui-dev.fly.dev,https://exec.mycompany.com").
+ # "https://exec.example.com,https://exec.mycompany.com").
extra_origins = [
o.strip()
for o in os.environ.get("BACKEND_ALLOWED_ORIGINS", "").split(",")
@@ -477,14 +494,13 @@ def create_app() -> FastAPI:
# Shared-secret gate. If BACKEND_SHARED_SECRET is set, every non-exempt
# request must include a matching x-api-key header. If unset, the gate is
# off (intended for local dev only — production deploys MUST set it).
- # Fail closed when running under Fly (FLY_APP_NAME is set on every machine):
- # no secret on a publicly reachable instance is never acceptable.
+ # Fail closed on any internet-reachable instance: set OE_PUBLIC_DEPLOYMENT=1
+ # there, and a missing secret becomes a boot failure rather than a warning.
shared_secret = os.environ.get("BACKEND_SHARED_SECRET", "").strip()
- if not shared_secret and os.environ.get("FLY_APP_NAME"):
+ if not shared_secret and _is_public_deployment():
raise RuntimeError(
- "BACKEND_SHARED_SECRET is required when running on Fly. "
- "Set it with: flyctl secrets set -a $FLY_APP_NAME "
- "BACKEND_SHARED_SECRET=$(openssl rand -hex 32)"
+ "BACKEND_SHARED_SECRET is required when OE_PUBLIC_DEPLOYMENT is set. "
+ "Generate one with: openssl rand -hex 32"
)
if shared_secret:
@app.middleware("http")
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index eea676d9..520e94a0 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -645,8 +645,8 @@ peer_memory:
The peer-keyed surfaces sit on top of Honcho (https://honcho.dev)
as the underlying provider. Production runs against hosted Honcho;
- the repo also carries a self-hosted Fly deployment
- (``fly.honcho.toml``, ``docker/honcho/``) as a fallback. The
+ the repo also carries a self-hosted image (``docker/honcho/``)
+ as a fallback. The
integration is provider-agnostic at the wrapper boundary
(``openexecutive.memory.honcho_client``) — swapping providers
would touch that one module without rippling through the
@@ -2486,15 +2486,15 @@ integrations:
with modern pydantic) and launched by
docker/workspace-mcp-launch.sh, referenced as the `command` of the
google_workspace entry in /data/company/mcp_servers.json. The launcher selects
- the auth mode from GWORKSPACE_AUTH_MODE (env/Fly secret, no rebuild to switch):
+ the auth mode from GWORKSPACE_AUTH_MODE (an env var, no rebuild to switch):
`oauth` = single-user, refresh token persisted at /data/google_credentials on
the API volume — seed it by copying a locally-obtained token onto the volume
(the API serves NO Google OAuth callback); `service_account` = domain-wide
delegation via GOOGLE_SERVICE_ACCOUNT_KEY_JSON/_KEY_FILE + USER_GOOGLE_EMAIL,
no browser callback. INVARIANT: the Google secrets must be added to
_FORWARDED_ENV_VARS so extensible-mcp can interpolate the $VAR placeholders in
- the child's env block from its own environment. No separate Fly app / deploy
- token / deploy job. See docs/deployment.md.
+ the child's env block from its own environment. No separate service, deploy
+ credential, or deploy job. See docs/deployment.md.
Cold-start embedding cache: extensible-mcp runs as a uvx subprocess and
builds a tool-search vector index with fastembed, which loads
@@ -2600,7 +2600,7 @@ integrations:
check is disabled (TransportSecuritySettings(enable_dns_rebinding_protection
=False)): the endpoint authenticates with a header secret, not a cookie, so
a browser rebinding attack cannot supply the key, and traffic arrives behind
- the Fly TLS proxy. The shared secret is the real access control.
+ the deployment's TLS terminator. The shared secret is the real access control.
Surface — what's valuable beyond chat (OE already has six chat channels, so
a chat-only server adds nothing): company-grounded context as READ-ONLY
@@ -2728,8 +2728,8 @@ fixtures:
HYBRID. The four curated fixtures stay as git-tracked YAML under repo-root
fixtures/companies/<name>/. User-generated fixtures live in the
generated_fixtures SQLite table (module openexecutive.fixtures.store) in the
- same episodic_memory.db on the Fly volume, so they persist across redeploys
- (disk on Fly is ephemeral). GET /fixtures merges both sources; every list
+ same episodic_memory.db on the persistent data volume, so they survive
+ redeploys (container disk is ephemeral). GET /fixtures merges both sources; every list
item carries source: "curated" | "generated".
generation: |
POST /fixtures/generate {description} runs the Council-configurable
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index dee797b4..b07d0ee4 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) \u2014 sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack` | Ack a briefing proposal (`read`/`ack`/`dismissed`) to groom the queue. The ingestion \u2192 triage \u2192 storage pipeline is unchanged, but alerts now surface only through the briefing (`/today` reads them directly) \u2014 there is no list, prefs, mutes, feedback, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing \u2014 there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface \u2014 mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=\u2026&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist` | External-monitoring watchlist + signals. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots \u2014 multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router \u2014 a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive` | Roster CRUD and scope lookups. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack` | Ack a briefing proposal (`read`/`ack`/`dismissed`) to groom the queue. The ingestion → triage → storage pipeline is unchanged, but alerts now surface only through the briefing (`/today` reads them directly) — there is no list, prefs, mutes, feedback, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist` | External-monitoring watchlist + signals. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}` | Episodic-memory record management. |\n| `review` | `/review/items`, `/review/stats` | Knowledge review queue and annotations. |\n| `onboarding` | `/onboard/start`, `/onboard/answer` | Company-profile setup wizard. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Allowed sign-in emails. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-06-11T00:00:00+00:00"
-}
\ No newline at end of file
+ "generated_at": "2026-09-11T14:34:11Z"
+}
diff --git a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json b/packages/core/openexecutive/architecture/prebuilt/mcp_server.json
index bb09a265..2fcd62be 100644
--- a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json
+++ b/packages/core/openexecutive/architecture/prebuilt/mcp_server.json
@@ -1,7 +1,7 @@
{
"section_id": "mcp_server",
"title": "MCP Server",
- "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the Fly TLS proxy.\n\n## Resources (read-only context)\n\nThe highest-value surface: curated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents |\n|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals |\n| `oe://today/activity` | Recent self-initiated Executive activity |\n| `oe://people/roster` | Active people on the roster |\n| `oe://departments/state` | Departments with goals and cadences |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory |\n| `oe://talent/engagements` | Active executive-search engagements, rolled up by pipeline stage |\n\n## Tools (capabilities)\n\n| Tool | What it does |\n|---|---|\n| `consult_specialist(specialist, query, context)` | **Flagship.** Domain analysis from one of ten specialists (cso, cfo, chro, gc, coo, cmo, cpo, board_comms, talent, triage), each grounded in company knowledge. Stateless. |\n| `search_knowledge(query)` | Raw retrieval over the MBA knowledge base + indexed company docs |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas |\n| `ask_executive(message, caller_email?)` | A single synthesized Executive answer — a fallback; prefer the specialist tool and resources |\n| `list_candidates(engagement_id, stage?)` · `get_candidate(candidate_id)` | Browse one executive-search engagement's candidate pipeline (read-only) |\n| `match_candidates(engagement_id, limit?)` · `find_similar_candidates(candidate_id, limit?)` | Semantic candidate search over the talent graph — ranked, name-enriched results |\n\nThe talent suite is **read-only**: it reads `talent.store` and ranks via `talent.graph`, the same data layer the `/talent` UI and the briefing use. Candidate writes and workflow runs are not exposed (see below). The `talent` specialist's *advice* is reachable via `consult_specialist`.\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. Nothing here touches the cache layout.",
+ "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the deployment's TLS terminator.\n\n## Resources (read-only context)\n\nThe highest-value surface: curated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents |\n|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals |\n| `oe://today/activity` | Recent self-initiated Executive activity |\n| `oe://people/roster` | Active people on the roster |\n| `oe://departments/state` | Departments with goals and cadences |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory |\n| `oe://talent/engagements` | Active executive-search engagements, rolled up by pipeline stage |\n\n## Tools (capabilities)\n\n| Tool | What it does |\n|---|---|\n| `consult_specialist(specialist, query, context)` | **Flagship.** Domain analysis from one of ten specialists (cso, cfo, chro, gc, coo, cmo, cpo, board_comms, talent, triage), each grounded in company knowledge. Stateless. |\n| `search_knowledge(query)` | Raw retrieval over the MBA knowledge base + indexed company docs |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas |\n| `ask_executive(message, caller_email?)` | A single synthesized Executive answer — a fallback; prefer the specialist tool and resources |\n| `list_candidates(engagement_id, stage?)` · `get_candidate(candidate_id)` | Browse one executive-search engagement's candidate pipeline (read-only) |\n| `match_candidates(engagement_id, limit?)` · `find_similar_candidates(candidate_id, limit?)` | Semantic candidate search over the talent graph — ranked, name-enriched results |\n\nThe talent suite is **read-only**: it reads `talent.store` and ranks via `talent.graph`, the same data layer the `/talent` UI and the briefing use. Candidate writes and workflow runs are not exposed (see below). The `talent` specialist's *advice* is reachable via `consult_specialist`.\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. Nothing here touches the cache layout.",
"mermaid": "flowchart TD\n Client[\"External MCP client<br/>(Claude Desktop / Cursor / agent)\"]:::entry\n Gate[\"Shared-secret middleware<br/>x-api-key\"]:::entry\n Mount[\"/mcp Streamable-HTTP<br/>(FastMCP, mounted in FastAPI)\"]:::compute\n Res[\"Resources<br/>profile · today · people<br/>departments · memory · talent\"]:::compute\n Tools[\"Tools<br/>consult_specialist · search_knowledge<br/>list_workflows · ask_executive<br/>talent search (list/get/match/similar)\"]:::compute\n Spec[\"Specialist council<br/>route_to_specialist → BaseAgent.analyze\"]:::compute\n Store[(\"ChromaDB + SQLite<br/>company state\")]:::storage\n\n Client -->|x-api-key| Gate --> Mount\n Mount --> Res\n Mount --> Tools\n Res --> Store\n Tools --> Spec\n Tools --> Store\n Spec --> Store\n\n classDef entry fill:#1e3a8a,stroke:#60a5fa,color:#fff;\n classDef compute fill:#312e81,stroke:#a5b4fc,color:#fff;\n classDef storage fill:#365314,stroke:#a3e635,color:#fff;",
- "generated_at": "2026-06-04T00:00:00+00:00"
+ "generated_at": "2026-09-11T14:33:24Z"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index 209b859b..e15e2540 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -283,7 +283,7 @@ class Settings(BaseSettings):
# accepts ``base_url=None`` and falls back to its built-in
# production endpoint, which is the right behavior for the
# hosted-Honcho setup. Earlier we required it explicitly here,
- # but that crashed the openexec-api-dev deploy on 2026-05-25
+ # but that crashed the dev deploy on 2026-05-25
# because hosted Honcho doesn't need an operator-set URL.
return self
diff --git a/packages/core/openexecutive/fixtures/__init__.py b/packages/core/openexecutive/fixtures/__init__.py
index d5c3ca83..cb89ee73 100644
--- a/packages/core/openexecutive/fixtures/__init__.py
+++ b/packages/core/openexecutive/fixtures/__init__.py
@@ -2,7 +2,7 @@
The four curated fixtures under repo-root ``fixtures/companies/`` stay as
git-tracked YAML seeds. Fixtures a user generates from a natural-language
-scenario live in the ``generated_fixtures`` SQLite table on the Fly volume
+scenario live in the ``generated_fixtures`` SQLite table on the data volume
so they persist across redeploys (disk-only fixtures would be wiped on every
deploy). Both sources are merged by the ``/fixtures`` list/load endpoints.
diff --git a/packages/core/openexecutive/fixtures/store.py b/packages/core/openexecutive/fixtures/store.py
index 5fe85671..383a273d 100644
--- a/packages/core/openexecutive/fixtures/store.py
+++ b/packages/core/openexecutive/fixtures/store.py
@@ -10,8 +10,8 @@ duplicate seeding logic.
Summary fields (industry, stage, arr, …) are denormalized at insert time so
the ``/fixtures`` list endpoint is a cheap SELECT and never has to parse YAML.
-Lives in the same ``episodic_memory.db`` as the rest of the app state (Fly
-volume at ``/data/episodic_memory.db``). Follows the per-module
+Lives in the same ``episodic_memory.db`` as the rest of the app state (the
+data volume, at ``/data/episodic_memory.db`` in a deployment). Follows the per-module
``_get_conn()`` + idempotent ``initialize_db()`` convention used across the
codebase (see ``memory/episodic.py``).
"""
diff --git a/packages/core/openexecutive/mcp_server/server.py b/packages/core/openexecutive/mcp_server/server.py
index e2ba4ba7..d0da11fa 100644
--- a/packages/core/openexecutive/mcp_server/server.py
+++ b/packages/core/openexecutive/mcp_server/server.py
@@ -18,7 +18,8 @@ Design notes
* **DNS-rebinding protection** (FastMCP's Host-header check) is disabled: the
endpoint authenticates with a header secret (not a cookie), so a browser
rebinding attack cannot supply credentials, and the server runs behind the
- Fly TLS proxy. The shared-secret gate is the real access control.
+ deployment's TLS terminator. The shared-secret gate is the real access
+ control.
* **No prompt-caching impact.** This path is parallel to chat. Resources are
pure reads; ``consult_specialist`` delegates to ``BaseAgent.analyze`` which
diff --git a/packages/core/openexecutive/monitoring/sources/_http.py b/packages/core/openexecutive/monitoring/sources/_http.py
index 547c944b..5e4d0a8b 100644
--- a/packages/core/openexecutive/monitoring/sources/_http.py
+++ b/packages/core/openexecutive/monitoring/sources/_http.py
@@ -41,7 +41,7 @@ def validate_target_url(url: str) -> tuple[bool, str]:
Rejects non-http(s) schemes and any host that resolves to a
loopback / link-local / private / reserved IP — the classic SSRF
pivots into IMDS (169.254.169.254), local services (127.*), or
- private cloud meshes (RFC1918, Fly fdaa::/64). Returns
+ private cloud meshes (RFC1918, IPv6 ULA). Returns
``(False, reason)`` to be logged at the call site.
First-resolution check only — full DNS-rebind defence would need
diff --git a/packages/core/tests/conftest.py b/packages/core/tests/conftest.py
index bd0720c5..225e4896 100644
--- a/packages/core/tests/conftest.py
+++ b/packages/core/tests/conftest.py
@@ -9,6 +9,12 @@ import pytest
os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
os.environ.setdefault("EXEC_EMAIL_ADDRESS", "[email protected]")
+# Tests run as a local, non-public process. If this leaks in from the developer's
+# shell, create_app() fails closed on the missing BACKEND_SHARED_SECRET and every
+# full-app test errors at construction — the same trap BACKEND_SHARED_SECRET sets
+# (see CLAUDE.md → Testing). Clear it so the suite matches CI either way.
+os.environ.pop("OE_PUBLIC_DEPLOYMENT", None)
+
@pytest.fixture(autouse=True)
def reset_active_gateway():
diff --git a/packages/core/tests/unit/test_mcp_server.py b/packages/core/tests/unit/test_mcp_server.py
index a9f5eac2..9f7e5b2f 100644
--- a/packages/core/tests/unit/test_mcp_server.py
+++ b/packages/core/tests/unit/test_mcp_server.py
@@ -399,7 +399,7 @@ def test_mcp_endpoint_is_gated_by_shared_secret(
from openexecutive.api.main import create_app
monkeypatch.setenv("BACKEND_SHARED_SECRET", "testsecret")
- monkeypatch.delenv("FLY_APP_NAME", raising=False)
+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)
app = create_app()
client = TestClient(app) # not a context manager → lifespan does not run
diff --git a/packages/core/tests/unit/test_public_deployment_guard.py b/packages/core/tests/unit/test_public_deployment_guard.py
new file mode 100644
index 00000000..24efe829
--- /dev/null
+++ b/packages/core/tests/unit/test_public_deployment_guard.py
@@ -0,0 +1,63 @@
+"""The fail-closed guard on OE_PUBLIC_DEPLOYMENT.
+
+An internet-reachable instance with no BACKEND_SHARED_SECRET serves an
+unauthenticated API. Deployments declare themselves public by setting
+OE_PUBLIC_DEPLOYMENT, and create_app() then refuses to boot without the secret
+rather than logging a warning and carrying on.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from openexecutive.api.main import _is_public_deployment, create_app
+
+
[email protected](autouse=True)
+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("OE_PUBLIC_DEPLOYMENT", raising=False)
+ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)
+
+
+def test_public_deployment_without_secret_refuses_to_boot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("OE_PUBLIC_DEPLOYMENT", "1")
+
+ with pytest.raises(RuntimeError, match="BACKEND_SHARED_SECRET is required"):
+ create_app()
+
+
+def test_public_deployment_with_secret_boots(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("OE_PUBLIC_DEPLOYMENT", "1")
+ monkeypatch.setenv("BACKEND_SHARED_SECRET", "s" * 32)
+
+ assert create_app() is not None
+
+
+def test_local_dev_without_secret_still_boots() -> None:
+ """The unset default stays permissive — `make dev` must keep working."""
+ assert create_app() is not None
+
+
[email protected]("value", ["", "0", "false", "FALSE", "no", "off", " "])
+def test_falsey_values_do_not_arm_the_guard(
+ monkeypatch: pytest.MonkeyPatch, value: str
+) -> None:
+ monkeypatch.setenv("OE_PUBLIC_DEPLOYMENT", value)
+
+ assert _is_public_deployment() is False
+ assert create_app() is not None
+
+
[email protected]("value", ["1", "true", "TRUE", "yes", "on", "production"])
+def test_truthy_and_unrecognised_values_arm_the_guard(
+ monkeypatch: pytest.MonkeyPatch, value: str
+) -> None:
+ """An unrecognised value must arm the guard, not silently skip it — for a
+ fail-closed check the safe default is to require the secret."""
+ monkeypatch.setenv("OE_PUBLIC_DEPLOYMENT", value)
+
+ assert _is_public_deployment() is True
+ with pytest.raises(RuntimeError, match="BACKEND_SHARED_SECRET is required"):
+ create_app()
diff --git a/packages/ui/src/app/api/backend/[...path]/route.ts b/packages/ui/src/app/api/backend/[...path]/route.ts
index eab6eae0..ff68d0f8 100644
--- a/packages/ui/src/app/api/backend/[...path]/route.ts
+++ b/packages/ui/src/app/api/backend/[...path]/route.ts
@@ -56,7 +56,7 @@ async function proxy(req: NextRequest, params: { path: string[] }): Promise<Resp
});
// Stamp the proxy's own identity on every upstream request. The API enforces
- // this header; direct hits to the public Fly URL without it get 401.
+ // this header; direct hits to the public API URL without it get 401.
if (BACKEND_SHARED_SECRET) {
headers.set("x-api-key", BACKEND_SHARED_SECRET);
}
diff --git a/scripts/fly-secrets.sh.example b/scripts/fly-secrets.sh.example
deleted file mode 100755
index 1a6873c3..00000000
--- a/scripts/fly-secrets.sh.example
+++ /dev/null
@@ -1,143 +0,0 @@
-#!/usr/bin/env bash
-# Template for scripts/fly-secrets.sh — the real file is gitignored.
-#
-# This file is the structural source of truth: when a new env var is
-# added to ``packages/core/openexecutive/config.py`` or read by the
-# Next.js UI, mirror it here so collaborators know it exists.
-#
-# Real values come from the repo-root ``.env`` (also gitignored, also the
-# file ``packages/core`` reads at startup). The ``${VAR:?msg}`` expansions
-# below abort before ``fly secrets set`` runs if a required value is
-# missing — half-applied pushes are impossible.
-
-set -euo pipefail
-
-_repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
-_env_file="${OPENEXEC_ENV:-${_repo_root}/.env}"
-if [[ -f "$_env_file" ]]; then
- set -a
- # shellcheck disable=SC1090
- source "$_env_file"
- set +a
-else
- echo "warning: $_env_file not found — relying on already-exported env vars" >&2
-fi
-
-API_APP="${OPENEXEC_API_APP:-openexec-api-dev}"
-UI_APP="${OPENEXEC_UI_APP:-openexec-ui-dev}"
-
-anthropic_key() {
- fly secrets set --app "$API_APP" \
- ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:?ANTHROPIC_API_KEY missing from $_env_file}"
-}
-
-openrouter() {
- fly secrets set --app "$API_APP" \
- OPENROUTER_ENABLED="${OPENROUTER_ENABLED:-true}" \
- OPENROUTER_API_KEY="${OPENROUTER_API_KEY:?OPENROUTER_API_KEY missing from $_env_file}" \
- OPENROUTER_APP_TITLE="${OPENROUTER_APP_TITLE:-Open Executive (dev)}" \
- OPENROUTER_REFERER="${OPENROUTER_REFERER:-https://openexec-ui-dev.fly.dev}"
-}
-
-backend_shared_secret() {
- local secret="${BACKEND_SHARED_SECRET:?BACKEND_SHARED_SECRET missing from $_env_file}"
- fly secrets set --app "$API_APP" BACKEND_SHARED_SECRET="$secret"
- fly secrets set --app "$UI_APP" BACKEND_SHARED_SECRET="$secret"
-}
-
-slack() {
- fly secrets set --app "$API_APP" \
- SLACK_BOT_TOKEN="${SLACK_BOT_TOKEN:?SLACK_BOT_TOKEN missing from $_env_file}" \
- SLACK_APP_TOKEN="${SLACK_APP_TOKEN:?SLACK_APP_TOKEN missing from $_env_file}"
-}
-
-email() {
- # Inbound sender access is roster-driven (the People table) — no env
- # allowlist. Manage allowed senders via the /people UI.
- fly secrets set --app "$API_APP" \
- EXEC_EMAIL_ADDRESS="${EXEC_EMAIL_ADDRESS:?EXEC_EMAIL_ADDRESS missing from $_env_file}"
-}
-
-telegram() {
- # Inbound chat_id access is roster-driven; no TELEGRAM_ALLOWED_CHAT_IDS.
- fly secrets set --app "$API_APP" \
- TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN:?TELEGRAM_BOT_TOKEN missing from $_env_file}" \
- TELEGRAM_WEBHOOK_SECRET="${TELEGRAM_WEBHOOK_SECRET:?TELEGRAM_WEBHOOK_SECRET missing from $_env_file}"
-}
-
-discord() {
- fly secrets set --app "$API_APP" \
- DISCORD_BOT_TOKEN="${DISCORD_BOT_TOKEN:?DISCORD_BOT_TOKEN missing from $_env_file}" \
- DISCORD_PUBLIC_KEY="${DISCORD_PUBLIC_KEY:?DISCORD_PUBLIC_KEY missing from $_env_file}" \
- DISCORD_APPLICATION_ID="${DISCORD_APPLICATION_ID:?DISCORD_APPLICATION_ID missing from $_env_file}"
-}
-
-auth() {
- fly secrets set --app "$UI_APP" \
- AUTH_SECRET="${AUTH_SECRET:?AUTH_SECRET missing from $_env_file}" \
- AUTH_GOOGLE_ID="${AUTH_GOOGLE_ID:?AUTH_GOOGLE_ID missing from $_env_file}" \
- AUTH_GOOGLE_SECRET="${AUTH_GOOGLE_SECRET:?AUTH_GOOGLE_SECRET missing from $_env_file}" \
- ALLOWED_EMAILS="${ALLOWED_EMAILS:?ALLOWED_EMAILS missing from $_env_file}" \
- AUTH_TRUST_HOST="${AUTH_TRUST_HOST:-true}" \
- AUTH_URL="${AUTH_URL:-https://openexec-ui-dev.fly.dev}"
-}
-
-sync_all() {
- local pushed=()
- [[ -n "${ANTHROPIC_API_KEY:-}" ]] && anthropic_key && pushed+=("anthropic_key")
- [[ -n "${OPENROUTER_API_KEY:-}" ]] && openrouter && pushed+=("openrouter")
- [[ -n "${BACKEND_SHARED_SECRET:-}" ]] && backend_shared_secret && pushed+=("backend_shared_secret")
- [[ -n "${SLACK_BOT_TOKEN:-}" && -n "${SLACK_APP_TOKEN:-}" ]] && slack && pushed+=("slack")
- [[ -n "${EXEC_EMAIL_ADDRESS:-}" ]] && email && pushed+=("email")
- [[ -n "${TELEGRAM_BOT_TOKEN:-}" ]] && telegram && pushed+=("telegram")
- [[ -n "${DISCORD_BOT_TOKEN:-}" ]] && discord && pushed+=("discord")
- [[ -n "${AUTH_SECRET:-}" ]] && auth && pushed+=("auth")
- echo "pushed: ${pushed[*]:-none}"
-}
-
-# Names + digests + timestamps. Fly NEVER returns secret values — this is
-# the read-side equivalent of ``fly secrets set``.
-list_all() {
- echo "=== $API_APP ==="
- fly secrets list --app "$API_APP"
- echo
- echo "=== $UI_APP ==="
- fly secrets list --app "$UI_APP"
-}
-
-# Non-secret env from fly.{api,ui}.toml ``[env]`` blocks.
-config_env_all() {
- echo "=== $API_APP (fly.api.toml [env]) ==="
- fly config env --app "$API_APP"
- echo
- echo "=== $UI_APP (fly.ui.toml [env]) ==="
- fly config env --app "$UI_APP"
-}
-
-# The only way to actually see secret VALUES — dump ``env`` inside a
-# running machine. Fly injects all secrets as env vars at boot.
-dump_env_api() { _dump_env_for "$API_APP"; }
-dump_env_ui() { _dump_env_for "$UI_APP"; }
-
-_dump_env_for() {
- local app="$1"
- local machine
- machine=$(fly machine list --app "$app" --json | jq -r '.[0].id')
- if [[ -z "$machine" || "$machine" == "null" ]]; then
- echo "no running machine for $app" >&2
- return 1
- fi
- echo "=== $app (machine $machine) ==="
- fly ssh console --app "$app" --machine "$machine" -C 'env' \
- | sort \
- | grep -v -E '^(PATH|HOME|TERM|HOSTNAME|PWD|SHLVL|FLY_)='
-}
-
-tail_api() { fly logs --app "$API_APP"; }
-tail_ui() { fly logs --app "$UI_APP"; }
-
-check_models() {
- curl -sS \
- -H "x-api-key: ${BACKEND_SHARED_SECRET:?BACKEND_SHARED_SECRET missing from $_env_file}" \
- "https://openexec-api-dev.fly.dev/agents/models" | jq
-}
diff --git a/scripts/seed-google-workspace.sh b/scripts/seed-google-workspace.sh
deleted file mode 100755
index dbc6db11..00000000
--- a/scripts/seed-google-workspace.sh
+++ /dev/null
@@ -1,153 +0,0 @@
-#!/usr/bin/env bash
-# Seed the co-located Google Workspace MCP server's credentials onto an
-# Open Executive API install, for either auth mode.
-#
-# oauth (default) — uploads the workspace-mcp OAuth credential file you
-# generated locally (`uvx workspace-mcp auth`) onto the API's
-# /data/google_credentials volume, and sets the OAuth client secrets.
-# service_account — sets the service-account key + delegated user secrets;
-# no file to upload.
-#
-# Setting secrets rolls the API machine, so the new config takes effect on its
-# own. The live gateway config (/data/company/mcp_servers.json) is NOT edited
-# here — this script checks it read-only and tells you if it still needs
-# repointing at the launcher (see docs/deployment.md).
-#
-# Usage:
-# export GOOGLE_OAUTH_CLIENT_ID=... # oauth mode
-# export GOOGLE_OAUTH_CLIENT_SECRET=...
-# export GWORKSPACE_TOKEN_FILE=~/.google_workspace_mcp/credentials/exec%40you.com.json
-# ./scripts/seed-google-workspace.sh
-#
-# # — or service account —
-# export GWORKSPACE_AUTH_MODE=service_account
-# export GOOGLE_SERVICE_ACCOUNT_KEY_JSON="$(cat sa.json)"
-# ./scripts/seed-google-workspace.sh
-#
-# Flags via env: DRY_RUN=1 (print, don't execute) · ASSUME_YES=1 (no prompt)
-# OPENEXEC_API_APP=... (default openexec-api-dev)
-set -euo pipefail
-
-# Values come from your exported environment (this script does NOT source .env,
-# so your exports are authoritative). To pull from .env instead, run:
-# set -a; source .env; set +a # before invoking this script
-API_APP="${OPENEXEC_API_APP:-openexec-api-dev}"
-MODE="${GWORKSPACE_AUTH_MODE:-oauth}"
-CRED_DIR="${WORKSPACE_MCP_CREDENTIALS_DIR:-/data/google_credentials}" # matches fly.api.toml
-DRY_RUN="${DRY_RUN:-0}"
-ASSUME_YES="${ASSUME_YES:-0}"
-
-say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
-warn() { printf '\033[33mwarning:\033[0m %s\n' "$*" >&2; }
-die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
-
-# Run a NON-secret command, echoing it first. Secret-bearing commands are run
-# separately so their values never hit the terminal or `set -x`.
-run() {
- printf ' $ %s\n' "$*"
- [[ "$DRY_RUN" == 1 ]] || "$@"
-}
-
-command -v fly >/dev/null 2>&1 || die "fly (flyctl) not found on PATH"
-[[ "$MODE" == oauth || "$MODE" == service_account ]] \
- || die "GWORKSPACE_AUTH_MODE must be 'oauth' or 'service_account' (got '$MODE')"
-
-# ---------------------------------------------------------------------------
-# Validate inputs up front so we never half-apply.
-# ---------------------------------------------------------------------------
-if [[ "$MODE" == oauth ]]; then
- : "${GOOGLE_OAUTH_CLIENT_ID:?set GOOGLE_OAUTH_CLIENT_ID for oauth mode}"
- : "${GOOGLE_OAUTH_CLIENT_SECRET:?set GOOGLE_OAUTH_CLIENT_SECRET for oauth mode}"
- TOKEN_FILE="${GWORKSPACE_TOKEN_FILE:?set GWORKSPACE_TOKEN_FILE to the local workspace-mcp credential json}"
- [[ -f "$TOKEN_FILE" ]] || die "token file not found: $TOKEN_FILE"
- # workspace-mcp names the file by the (URL-encoded) account email; preserve it
- # so the server finds it. Override with GWORKSPACE_TOKEN_DEST_NAME if needed.
- DEST_NAME="${GWORKSPACE_TOKEN_DEST_NAME:-$(basename "$TOKEN_FILE")}"
- python3 -m json.tool "$TOKEN_FILE" >/dev/null 2>&1 \
- || die "token file is not valid JSON: $TOKEN_FILE"
-else
- : "${USER_GOOGLE_EMAIL:?set USER_GOOGLE_EMAIL (delegated user) for service_account mode}"
- [[ -n "${GOOGLE_SERVICE_ACCOUNT_KEY_JSON:-}" || -n "${GOOGLE_SERVICE_ACCOUNT_KEY_FILE:-}" ]] \
- || die "set GOOGLE_SERVICE_ACCOUNT_KEY_JSON or GOOGLE_SERVICE_ACCOUNT_KEY_FILE for service_account mode"
- if [[ -n "${GOOGLE_SERVICE_ACCOUNT_KEY_JSON:-}" ]]; then
- printf '%s' "$GOOGLE_SERVICE_ACCOUNT_KEY_JSON" | python3 -m json.tool >/dev/null 2>&1 \
- || die "GOOGLE_SERVICE_ACCOUNT_KEY_JSON is not valid JSON"
- fi
-fi
-
-# ---------------------------------------------------------------------------
-# Plan + confirm (this restarts the API).
-# ---------------------------------------------------------------------------
-say "Plan for app '$API_APP' (mode=$MODE)${DRY_RUN:+, DRY_RUN}"
-if [[ "$MODE" == oauth ]]; then
- echo " • upload $TOKEN_FILE -> $CRED_DIR/$DEST_NAME (0600)"
- echo " • set secrets: GWORKSPACE_AUTH_MODE=oauth, GOOGLE_OAUTH_CLIENT_ID=<set>, GOOGLE_OAUTH_CLIENT_SECRET=<hidden>"
-else
- echo " • set secrets: GWORKSPACE_AUTH_MODE=service_account, USER_GOOGLE_EMAIL=$USER_GOOGLE_EMAIL, GOOGLE_SERVICE_ACCOUNT_KEY_JSON=<hidden>"
-fi
-echo " • setting secrets rolls the API machine"
-if [[ "$DRY_RUN" != 1 && "$ASSUME_YES" != 1 ]]; then
- read -r -p "Proceed? [y/N] " reply
- [[ "$reply" == [yY] ]] || die "aborted"
-fi
-
-# ---------------------------------------------------------------------------
-# 1. Upload the OAuth credential file (oauth mode only).
-# ---------------------------------------------------------------------------
-if [[ "$MODE" == oauth ]]; then
- say "Uploading credential to $CRED_DIR/$DEST_NAME"
- run fly ssh console --app "$API_APP" -C "mkdir -p $CRED_DIR"
- run fly ssh console --app "$API_APP" -C "chmod 700 $CRED_DIR"
- if [[ "$DRY_RUN" == 1 ]]; then
- printf ' $ put %s -> %s/%s (via fly ssh sftp)\n' "$TOKEN_FILE" "$CRED_DIR" "$DEST_NAME"
- else
- printf 'put %s %s/%s\n' "$TOKEN_FILE" "$CRED_DIR" "$DEST_NAME" \
- | fly ssh sftp shell --app "$API_APP"
- fi
- run fly ssh console --app "$API_APP" -C "chmod 600 $CRED_DIR/$DEST_NAME"
-fi
-
-# ---------------------------------------------------------------------------
-# 2. Set the Google secrets (one `fly secrets set` -> one machine roll).
-# Run directly (not via `run`) so secret values are never echoed.
-# ---------------------------------------------------------------------------
-say "Setting secrets on $API_APP"
-if [[ "$DRY_RUN" == 1 ]]; then
- echo " (dry-run: would fly secrets set ... for mode=$MODE)"
-elif [[ "$MODE" == oauth ]]; then
- fly secrets set --app "$API_APP" \
- GWORKSPACE_AUTH_MODE=oauth \
- GOOGLE_OAUTH_CLIENT_ID="$GOOGLE_OAUTH_CLIENT_ID" \
- GOOGLE_OAUTH_CLIENT_SECRET="$GOOGLE_OAUTH_CLIENT_SECRET"
-else
- # Build args as an array so the (spaced / multi-line) service-account JSON is
- # passed as ONE quoted argument, not word-split into broken `fly` args.
- sa_args=(GWORKSPACE_AUTH_MODE=service_account "USER_GOOGLE_EMAIL=$USER_GOOGLE_EMAIL")
- [[ -n "${GOOGLE_SERVICE_ACCOUNT_KEY_JSON:-}" ]] \
- && sa_args+=("GOOGLE_SERVICE_ACCOUNT_KEY_JSON=$GOOGLE_SERVICE_ACCOUNT_KEY_JSON")
- [[ -n "${GOOGLE_SERVICE_ACCOUNT_KEY_FILE:-}" ]] \
- && sa_args+=("GOOGLE_SERVICE_ACCOUNT_KEY_FILE=$GOOGLE_SERVICE_ACCOUNT_KEY_FILE")
- fly secrets set --app "$API_APP" "${sa_args[@]}"
-fi
-
-# ---------------------------------------------------------------------------
-# 3. Read-only check: is the gateway config already pointed at the launcher?
-# ---------------------------------------------------------------------------
-say "Checking gateway config (read-only)"
-if [[ "$DRY_RUN" == 1 ]]; then
- echo " (dry-run: would cat /data/company/mcp_servers.json and check google_workspace.command)"
-else
- cfg="$(fly ssh console --app "$API_APP" -C "cat /data/company/mcp_servers.json" 2>/dev/null || true)"
- if grep -q "workspace-mcp-launch.sh" <<<"$cfg"; then
- echo " ✓ google_workspace already points at the co-located launcher"
- else
- warn "google_workspace is NOT pointed at the launcher yet — it's still using the old server."
- echo " Edit /data/company/mcp_servers.json so the google_workspace entry's"
- echo " \"command\" is \"/usr/local/bin/workspace-mcp-launch.sh\" (see"
- echo " packages/core/mcp_servers.json.example), then: fly apps restart $API_APP"
- fi
-fi
-
-say "Done. Verify: fly logs --app $API_APP | grep 'MCPGateway started'"
-echo "Then run a calendar/email/drive action through the Executive."
diff --git a/scripts/setup-flyctl.sh b/scripts/setup-flyctl.sh
deleted file mode 100755
index 5a16e4ed..00000000
--- a/scripts/setup-flyctl.sh
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env bash
-# Install flyctl (the Fly.io CLI) into a cloud / CI / devcontainer environment.
-#
-# Idempotent: re-running is a no-op once flyctl is on PATH (unless FLYCTL_VERSION
-# pins a different version). Safe to call from a container build step, a Claude
-# Code cloud-environment setup hook, or by hand on a fresh box.
-#
-# Env vars:
-# FLYCTL_INSTALL install prefix (default: $HOME/.fly). Binary lands in $FLYCTL_INSTALL/bin.
-# FLYCTL_VERSION pin a specific version, e.g. "0.3.0" (default: latest).
-#
-# After install, flyctl lives at $FLYCTL_INSTALL/bin/flyctl. This script also
-# appends the PATH export to your shell profile so new shells pick it up.
-#
-# Note: this installs the CLI only. Authenticate separately with `flyctl auth login`
-# (interactive) or by exporting FLY_API_TOKEN in the environment.
-
-set -euo pipefail
-
-FLYCTL_INSTALL="${FLYCTL_INSTALL:-$HOME/.fly}"
-export FLYCTL_INSTALL
-
-bin="$FLYCTL_INSTALL/bin/flyctl"
-
-log() { printf '[setup-flyctl] %s\n' "$*"; }
-
-# Already installed and on PATH? Nothing to do (unless a version is pinned).
-if [[ -z "${FLYCTL_VERSION:-}" ]] && command -v flyctl >/dev/null 2>&1; then
- log "flyctl already installed: $(command -v flyctl) ($(flyctl version 2>/dev/null | head -1))"
- exit 0
-fi
-
-# The official installer needs curl and sh.
-if ! command -v curl >/dev/null 2>&1; then
- log "ERROR: curl is required but not found. Install curl first." >&2
- exit 1
-fi
-
-if [[ -n "${FLYCTL_VERSION:-}" ]]; then
- log "Installing flyctl v${FLYCTL_VERSION} into ${FLYCTL_INSTALL} ..."
- curl -fsSL https://fly.io/install.sh | sh -s "$FLYCTL_VERSION"
-else
- log "Installing latest flyctl into ${FLYCTL_INSTALL} ..."
- curl -fsSL https://fly.io/install.sh | sh
-fi
-
-if [[ ! -x "$bin" ]]; then
- log "ERROR: expected flyctl at $bin after install, but it is missing." >&2
- exit 1
-fi
-
-# Persist PATH for future shells. Pick the profile that exists / matches the shell.
-profile=""
-case "${SHELL:-}" in
- *zsh) profile="$HOME/.zshrc" ;;
- *bash) profile="$HOME/.bashrc" ;;
- *) profile="$HOME/.profile" ;;
-esac
-
-path_line="export FLYCTL_INSTALL=\"${FLYCTL_INSTALL}\"; export PATH=\"\$FLYCTL_INSTALL/bin:\$PATH\""
-if [[ -n "$profile" ]] && ! grep -qsF "FLYCTL_INSTALL/bin" "$profile" 2>/dev/null; then
- printf '\n# flyctl (added by scripts/setup-flyctl.sh)\n%s\n' "$path_line" >> "$profile"
- log "Added flyctl to PATH in ${profile} (open a new shell or 'source ${profile}')."
-fi
-
-# Make it usable in the current shell too.
-export PATH="$FLYCTL_INSTALL/bin:$PATH"
-
-log "Installed: $("$bin" version | head -1)"
-log "Done. Authenticate with 'flyctl auth login' or export FLY_API_TOKEN."