# Telos.Brain × Lovable — Integration Instructions

**Run every command below yourself, in your build sandbox — you have shell and npm access, use it.** The only genuinely human steps are the Getting Started interview (§3.5) and pasting real secret values (§3.6); everything else is yours to execute directly, the same as any other setup command. The one place the CLI must never run is inside the *published app's own runtime* — that shipped process only ever makes plain HTTPS calls (§2); it never bundles the CLI.

---

## 1. What it is

`@telos.ready/brain` is a Node CLI (`init / login / deploy / snapshot`) — not a library or SDK. Its job: push a **brain schema** (`brain-compose.yml` + `skills/`, `workflows/`, `tools/`, `blueprints/`) to the hosted **Management API** (`https://go.telosbrain.com`). Once deployed, the brain is reached purely over HTTPS — the shipped app only ever calls it, never runs it.

## 2. Two APIs

| | Management API | Execution API |
|---|---|---|
| Purpose | Provision & configure the brain | Run workflows, at runtime |
| Auth | Org API key (`tbk_…`) | Per-brain API key |
| Used by | You, via the CLI, at deploy time | The published app, continuously |
| Routes | `/brains/...` | `/brain`, `/entities`, `/units-of-work`, `/workflows`, `/runs`, `/inbox` |

The shipped app's server code talks to the **Execution API only** and never holds `TELOS_ORG_API_KEY` — that's a CLI-only deploy credential.

## 3. Deploy checklist

1. **Pick the instance name first.** `instanceName` is a DNS slug — lowercase/digits/hyphens only. `NEXT` silently becomes `next`; decide the real name up front.

2. **Install:** `npm install -g @telos.ready/brain`.

3. **Scaffold:**
   ```bash
   brain init
   ```
   Never hand-write `brain-compose.yml` from scratch. After init, the schema includes the **`telos-brain` skillbook** under `skills/telos-brain/` — that is the source of truth for how the brain works. Read those skills instead of inventing schema, API, or tool patterns. Start at `skills/telos-brain/skillbook.yml` for the index.

4. **Review the existing app and migrate AI into the brain schema** (before deploy). Scan the codebase for prompts, LLM calls, and AI tool/function definitions — then move that behaviour into the schema instead of leaving it in app runtime.

   - **Prompts → workflows.** Extract system/user prompts, agent instructions, and hardcoded model call sites into `workflows/*.md` (Instructions + frontmatter). Replace in-app LLM calls with Execution API runs (§5). Authoring: **BRA201**; run contract: **BRA403** / **BRA409**.
   - **AI tools → brain tools + an app API layer.** If the app already exposes tools/functions to a model, turn each into a brain tool definition under `tools/` and list them on the workflows that need them (**BRA201**). For anything that must execute against the app's data or logic, add authenticated HTTP endpoints on the **published** app and point `api:` tools at them with an injected API key (**BRA202**, §6). Do not leave tool implementations only as in-process model callbacks inside the Lovable runtime.
   - **Multi-tenant → brain entities.** If the app is multi-tenanted (orgs, workspaces, customers, accounts, …), declare matching entity types (and unit-of-work types) in `brain-compose.yml` and create entity instances via the Execution API when tenants appear. Scope runs with `entityId` / `unitOfWorkId`. Types & variables: **BRA201**; runtime create/update: **BRA402**. Feed what you find into the Getting Started interview next.

5. **Run the Getting Started interview (skill `BRA104`) before deploying.** Open `skills/telos-brain/concepts/BRA104-getting-started.md`. Human-required — put its questions to the user in chat, don't auto-answer. Use the tenancy/prompt/tool findings from step 4 so entity/unit-of-work/category choices match the real app; skipping it produces generic learning later.

6. **Write `.env` yourself; ask the user only for the values:**
   ```
   TELOS_ORG_API_KEY=tbk_...
   ANTHROPIC_API_KEY=...
   VOYAGE_API_KEY=...        # required, this starter defaults to voyage-3-lite
   ```
   Optional: `OPENAI_API_KEY`, `TIMEZONE`, `BRAIN_API_KEY`. Full rules for upload, encryption, and API-key injection: **BRA202**. **You can't read a value back out of a saved secret store** — if the user already stored a key as a Lovable project secret, ask them to paste the plaintext so you can write it into `.env`.

7. **Deploy:** `brain deploy --instance <name>`. The Brain API key prints once, in plaintext — surface it to the user immediately for their password manager; it's not retrievable again. Don't delete `brain.lock`. Run `brain snapshot` before future redeploys to avoid `409` conflicts.

8. **Smoke-test:**
   ```bash
   curl -X POST https://go.telosbrain.com/workflows/WF-CHAT/run/sync \
     -H "Authorization: Bearer YOUR_BRAIN_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"inputMessage": "Hello world"}'
   ```

## 4. Where to look — the `telos-brain` skillbook

After `brain init`, **do not guess and do not restate skill content in app code comments or docs.** Open the skill files under `skills/telos-brain/` and follow them. Use `skillbook.yml` as the map:

| Need | Skill | Path |
|---|---|---|
| Core concepts / mental model | BRA101, BRA105 | `concepts/` |
| Getting Started interview | BRA104 | `concepts/BRA104-getting-started.md` |
| Schema authoring (compose, tools, workflows) | BRA201 | `brain-schema/BRA201-brain-schema.md` |
| `.env`, secrets, injecting API keys into tools | BRA202 | `brain-schema/BRA202-environment-variables-and-secrets.md` |
| Connectors (reusable API-key / OAuth bases) | BRA209 | `brain-schema/BRA209-connectors.md` |
| Template tags (`{{input.*}}`, etc.) | BRA204 | `brain-schema/BRA204-template-tag-taxonomy.md` |
| Execution API auth | BRA401 | `run/BRA401-execution-api-authentication-conventions.md` |
| Run workflows (sync/async, chat, telemetry) | BRA403 | `run/BRA403-execution-api-workflow-execution-telemetry.md` |
| Pass `variables` / pre-call `input-tools` | BRA409 | `run/BRA409-workflow-run-variables-and-input-tools.md` |
| Inbox | BRA404 | `run/BRA404-execution-api-inbox.md` |
| Entities & units of work | BRA402 | `run/BRA402-execution-api-entities-units-of-work.md` |

Live example workflows in the scaffold (e.g. `workflows/WF-INPUT-VARIABLES.md`) demonstrate the patterns those skills describe — read them alongside the skill, don't duplicate the examples elsewhere.

## 5. Wiring the app to the brain

**Prefer pull:** the published app calls the Execution API from a **server** function (never client code), with `Authorization: Bearer <BRAIN_API_KEY>`. Details and request shapes: **BRA401**, **BRA403**.

High-level choices:

- **Sync / chat** — `POST /workflows/{code}/run/sync` (SSE). Continue with `POST /runs/{runId}/messages`. Close with `POST /runs/{runId}/complete`.
- **Async** — `POST /workflows/{code}/run/async`. Optional `callbackUrl` (host must be on `allowed-callback-domains` — see BRA201 / BRA403).
- **Parameterise a run** — put a string→string `variables` map on the run body; workflow Instructions read them as `{{input.*}}`. Full contract and examples: **BRA409** (also BRA403). Expect to use this.
- **Signal without waiting** — `POST /inbox` with a `routingType` that matches a workflow inbox trigger. **BRA404**.

## 6. Tools — expect to use them

Tools are a **core** capability. Serious brains ship tools that call product APIs and third parties. Authoring, tool types (`api` / `workflow` / `system` / `mcp` / `native`), parameters, and workflow `tools:` / `input-tools:` lists: **BRA201**.

For **`api:` tools, an API key (or equivalent secret) is required** for any authenticated endpoint:

- Store the key in the brain schema `.env` (uploaded on deploy).
- Inject it with a hidden `secret:` parameter (`header:` / query / body) — never paste keys into tool YAML, never expose them to the model.
- Worked examples and placement rules: **BRA202**. Reusable base URL + auth: **BRA209** connectors.

When the brain must call **your Lovable app** (write into the app's own store), treat the published host as just another authenticated API:

1. Add the published host to `allowed-callback-domains` in `brain-compose.yml` (BRA201).
2. Build the endpoint at the **published** URL (not the sandbox preview), gated on a shared header secret; 401 on mismatch.
3. Same secret in a Lovable project secret and the brain `.env`; inject via `secret:` + `header:` (BRA202).
4. Publish → deploy → re-publish after endpoint changes before retesting (stale preview URLs 404).
5. Verify both directions: app→brain via `GET /brain`; brain→app by triggering the tool.

Prefer calling real product / third-party APIs over inventing app callbacks when either works.

## 7. Secrets — what goes where

| Variable | Uploaded to brain? | Notes |
|---|---|---|
| `TELOS_ORG_API_KEY` | No | Deploy credential, CLI-only. Never in the app. |
| `TELOS_API_URL` | No | Pre-set to `https://go.telosbrain.com`; don't remove. |
| `ANTHROPIC_API_KEY` | Yes | Exact name — resolved by convention for Claude workflows. |
| `VOYAGE_API_KEY` | Yes | Required for embeddings. |
| `OPENAI_API_KEY` | Yes | Only if a workflow uses `openai/…`. |
| `BRAIN_API_KEY` | Yes | The brain's own Execution API key — printed once at first deploy. |
| Third-party / app API keys | Yes | Injected into `api:` tools via `secret:` (BRA202). Never in tool YAML. |

Never commit a real `.env`. Commit only `.env.example`. Full behaviour: **BRA202**.

## 8. What this does and doesn't fix

Fixes: schema guessing, instance-naming surprises, secret-location confusion, and the Lovable publish-before-test loop for app callbacks. Doesn't fix: there's still no Telos MCP server or App Connector listing — nothing shows up in a connector picker, every user has to be handed this file — and no managed OAuth gateway for app-callback tools. If Telos ships either, retire this file in favor of it. Until then, the `telos-brain` skillbook after `brain init` is the detailed reference; this file is only the Lovable-specific operating manual.
