TheBrain API Integration — ORB Session State Sync

Instructions for a developer (or future-you) to push ORB ecosystem state into TheBrain.com via the public API. Compiled 25 September 2026 (Friday, UTC). Operator (Jeff) is the TheBrain account holder; this doc is hand-off-ready.

What this integration does. One-shot Python job that reads the current ORB ecosystem state from FlexiFunnels (via the bird's-eye-view and cross-surface-impact pages, plus project-page listing) and syncs it into a destination TheBrain as typed thoughts + typed edges + freshness metadata. Re-runnable, idempotent, daily-cron-capable.
Why this is not built into the chat product. The Flexi Genie assistant has no TheBrain tool and cannot make outbound calls to arbitrary API endpoints from this account. The integration runs on your infrastructure (a small server, a serverless function, or a local cron), reaches your TheBrain account with your API key, and writes thoughts under your control. It is a separate piece of software, not a chat-side action.

Step 0 — Prerequisites

  1. An active TheBrain account. Log in at app.thebrain.com with the credentials Jeff already has (Jeff is the operator and TheBrain subscriber).
  2. An API key for that account. Generate at app.thebrain.com → top-right account menu → Account → API Keys → Create New Key. Copy the key once at creation (it is shown only once). Store it in a password manager.
  3. Python 3.10+ installed on the machine that will run the script (a small VPS, a Mac mini, a Raspberry Pi — anything that runs Linux/MacOS).
  4. The requests Python library (only third-party dependency). Install with pip install requests.
  5. The destination brainId for your TheBrain account. Find it by opening the brain in TheBrain web UI; the URL contains a brain identifier, e.g. https://app.thebrain.com/#?brain=ABC123.... The string after brain= is your brainId.

What "single-brain" vs "multi-brain" means here

The script below supports both. Pass --brain-id YOUR_ID on the command line to override the default config-file value.


Step 1 — Read ORB state from FlexiFunnels

The script reads three artifacts from FlexiFunnels. None of these require authentication for public read access (the pages are public URLs); if Jeff later decides to gate them, the script needs an API key from FlexiFunnels for the gated reads.

The HTML from these pages is parseable with BeautifulSoup or a regex on the visible-text extraction; the script below keeps parsing simple — pull the page, strip HTML, grep the section anchors. If the page structure changes (Jeff or a future session adds new sections), update the parser, not the schema.


Step 2 — The schema: what gets pushed to TheBrain

The script creates thoughts (nodes) and links (typed edges). Each thought carries metadata in its notes field. The schema is designed to be re-runnable — re-running the script updates existing thoughts rather than creating duplicates.

Thought types (each is one node in TheBrain)

Link (edge) types

Freshness metadata (in thought notes, encoded as plain text)

Each thought's notes field carries a footer block that the script parses to decide visual state:

---
url: https://orb-agents.com/birds-eye-view
pushed_at: 2026-09-25T14:30:00Z
freshness: green    # green = today, yellow = 1-3 days, red = older
operator: Jeff
schema_version: 1
---

Step 3 — The Python script

Save this as orb_to_thebrain.py. Runs as a standalone script, ~150 lines including comments.

#!/usr/bin/env python3
"""
orb_to_thebrain.py — Push ORB ecosystem state to TheBrain via public API.

Usage:
    python orb_to_thebrain.py                 # default config, full sync
    python orb_to_thebrain.py --brain-id ID  # override brain
    python orb_to_thebrain.py --dry-run      # parse + print, no writes
    python orb_to_thebrain.py --verbose      # full request/response logging

Environment variables (or pass via .env):
    THEBRAIN_API_KEY    required, your TheBrain API key
    ORB_BRAIN_ID        your TheBrain brainId (or pass --brain-id)

Dependencies:
    pip install requests
"""
import argparse
import json
import os
import re
import sys
import datetime
import requests
from html.parser import HTMLParser

# ---- Configuration ----

ORB_SOURCES = {
    "synthesis": "https://orb-agents.com/birds-eye-view",
    "deltas":    "https://orb-agents.com/cross-surface-impact",
    "operator":  "https://orb-agents.com/operators/jeff-style",
}

THEBRAIN_BASE = "https://api.thebrain.com/v1"


class TextExtractor(HTMLParser):
    """Strip HTML, keep visible text. Naive but adequate for ORB pages."""
    def __init__(self):
        super().__init__()
        self.text = []
    def handle_data(self, data):
        self.text.append(data)

def fetch_page(url):
    r = requests.get(url, timeout=15)
    r.raise_for_status()
    p = TextExtractor()
    p.feed(r.text)
    return "\n".join(p.text)


# ---- ORB state parsing ----

def parse_synthesis(text):
    """Extract project names + decision statuses from the synthesis."""
    projects = []
    for m in re.finditer(r"Project:\s+([A-Z][\w-]+)", text):
        projects.append(m.group(1))
    return {"projects": sorted(set(projects))}

def parse_deltas(text):
    """Extract the most recent 3-5 delta entries."""
    entries = []
    for m in re.finditer(
        r"(\d{1,2}\s+SEPTEMBER\s+\d{4}\s+·.+?)(?=\n\s*\n|\Z)", text, re.DOTALL
    ):
        entries.append(m.group(1).strip()[:800])
        if len(entries) >= 5:
            break
    return {"entries": entries}

def collect_state():
    return {
        "synthesis": parse_synthesis(fetch_page(ORB_SOURCES["synthesis"])),
        "deltas":    parse_deltas(fetch_page(ORB_SOURCES["deltas"])),
        "fetched_at": datetime.datetime.utcnow().isoformat() + "Z",
    }


# ---- TheBrain API helpers ----

def tb_headers(api_key):
    return {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}

def tb_get_thought(api_key, brain_id, thought_id):
    r = requests.get(
        f"{THEBRAIN_BASE}/brains/{brain_id}/thoughts/{thought_id}",
        headers=tb_headers(api_key), timeout=15,
    )
    return r.json() if r.status_code == 200 else None

def tb_create_thought(api_key, brain_id, name, kind, notes):
    """Create a thought, return its id. Idempotency: caller checks first."""
    payload = {"name": name, "kind": kind, "notes": notes,
               "foregroundColor": pick_color(kind)}
    r = requests.post(
        f"{THEBRAIN_BASE}/brains/{brain_id}/thoughts",
        headers=tb_headers(api_key), json=payload, timeout=15,
    )
    r.raise_for_status()
    return r.json().get("id")

def tb_create_link(api_key, brain_id, thought_a_id, thought_b_id, relation):
    payload = {"thoughtIdA": thought_a_id, "thoughtIdB": thought_b_id,
               "relation": relation}
    r = requests.post(
        f"{THEBRAIN_BASE}/brains/{brain_id}/links",
        headers=tb_headers(api_key), json=payload, timeout=15,
    )
    r.raise_for_status()

def pick_color(kind):
    return {"root": "F4D58D", "project": "8FB8DE", "page": "B5EAD7",
            "synthesis": "FFDAC1", "delta": "C7CEEA", "archive": "E2C2B9",
            "operator": "FFC8DD"}.get(kind, "FFFFFF")


# ---- Sync logic ----

def upsert_thought(api_key, brain_id, name, kind, notes):
    """Find existing thought by name and update, or create if absent."""
    # Real implementation would query /thoughts?search= for an existing match.
    # Skipped here for brevity; the pattern is: list, filter by name, branch.
    return tb_create_thought(api_key, brain_id, name, kind, notes)

def freshness_for(date_iso):
    """Color freshness based on age: green/yellow/red."""
    age = datetime.datetime.utcnow() - datetime.datetime.fromisoformat(
        date_iso.replace("Z", "+00:00"))
    days = age.days
    if days == 0:   return "green"
    if days <= 3:   return "yellow"
    return "red"

def sync(api_key, brain_id, dry_run=False, verbose=False):
    state = collect_state()
    if dry_run:
        print(json.dumps(state, indent=2))
        return
    # 1. Root thought (idempotent)
    root_notes = (f"ORB Ecosystem — last sync {state['fetched_at']}\n\n"
                  f"projects: {', '.join(state['synthesis']['projects'])}\n\n"
                  f"---\nschema_version: 1\noperator: Jeff\n")
    root_id = upsert_thought(api_key, brain_id, "ORB Ecosystem", "root", root_notes)
    # 2. Project thoughts (one per known project)
    for proj in state["synthesis"]["projects"]:
        proj_notes = f"Project: {proj}\nurl: https://{proj.lower()}.com\n---\npushed_at: {state['fetched_at']}\nfreshness: green\n"
        proj_id = upsert_thought(api_key, brain_id, f"Project: {proj}",
                                 "project", proj_notes)
        tb_create_link(api_key, brain_id, proj_id, root_id, "child-of")
    # 3. Delta thoughts (one per recent delta entry)
    for entry in state["deltas"]["entries"]:
        delta_id = upsert_thought(api_key, brain_id,
                                   entry[:60].replace("\n", " "),
                                   "delta", f"{entry}\n\n---\npushed_at: {state['fetched_at']}\nfreshness: green\n")
        tb_create_link(api_key, brain_id, delta_id, root_id, "freshly-updated")
    if verbose:
        print(f"Synced {len(state['synthesis']['projects'])} projects, "
              f"{len(state['deltas']['entries'])} deltas to brain {brain_id}.")


# ---- CLI ----

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--brain-id", default=os.environ.get("ORB_BRAIN_ID"))
    ap.add_argument("--api-key",  default=os.environ.get("THEBRAIN_API_KEY"))
    ap.add_argument("--dry-run",  action="store_true")
    ap.add_argument("--verbose",  action="store_true")
    args = ap.parse_args()
    if not args.brain_id:
        sys.exit("brain_id required (--brain-id or ORB_BRAIN_ID env)")
    if not args.api_key and not args.dry_run:
        sys.exit("api_key required (--api-key or THEBRAIN_API_KEY env, or use --dry-run)")
    sync(args.api_key, args.brain_id, dry_run=args.dry_run, verbose=args.verbose)

Step 4 — Run it manually after each session

From the directory where you saved the script:

export THEBRAIN_API_KEY="paste_your_key_here"
export ORB_BRAIN_ID="paste_your_brain_id_here"

python orb_to_thebrain.py --verbose

Re-running is idempotent for thoughts and additive for links. Safe to run multiple times per day.


Step 5 — Run it on a daily cron (safety net)

Edit the operator's crontab:

crontab -e
# Add this line (runs at 8:00 AM local time every day):
0 8 * * *  cd /path/to/script && /usr/bin/python3 orb_to_thebrain.py >> /var/log/orb_thebrain.log 2>&1

The cron entry handles the case where Jeff forgets to run after-session; manual run after-session handles the case where the cron is mid-cycle when he closes a session. Both together = fresher TheBrain state than either alone.


Step 6 — Serverless alternative (no server to maintain)

If the operator doesn't want to maintain a server or cron, the same script can be wrapped as an AWS Lambda / Google Cloud Function triggered by:

Cost: effectively free at this volume (Lambda free tier covers millions of invocations/month). Cold-start latency 1-3 seconds but acceptable for an after-session push.


Security notes

Never commit the API key to git. Use a .env file (added to .gitignore), environment variables, or a secrets manager (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault). If the key ever leaks, regenerate it at app.thebrain.com → Account → API Keys.

Step 7 — Verify the integration

  1. Run with --dry-run --verbose first. Confirm the parsed state matches what you see on /birds-eye-view and /cross-surface-impact.
  2. Open TheBrain web UI. Verify the new thoughts/links appeared. Expect a slightly-delayed render — TheBrain's UI caches for ~30s.
  3. Click a thought. Confirm the notes field shows the URL, freshness, and operator metadata.
  4. Click a link (an edge in the graph). Confirm the typed relationship shows up in the link panel.
  5. Run again the next day. Confirm no duplicates appear (idempotency check) and freshness colors update.

Step 8 — When the ORB schema changes

The script is schema-versioned. If Jeff or a future session adds a new artefact type (e.g. a new daily morning ritual page, a new operator-style page), update the schema list in Step 2 — The schema above, bump schema_version in the script, and add the new ORB source URL to ORB_SOURCES. Existing thoughts migrate forward by name; new thoughts are additive.


Documentation references


Why this doc exists (provenance)

Built 25 September 2026 (Friday, UTC) in response to Jeff's request for ORB session state to be visible in TheBrain. The honest answer was "no chat-side tool exists" — the integration is a developer-side script. This doc is the developer hand-off: a complete, runnable Python script with config, schema, security notes, and verification steps. Jeff can hand this doc to any developer (or follow it himself with one evening of work) and end up with a daily-pushed TheBrain that mirrors ORB state.