# Project export: Forge

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2026
- Tagline: 30 million underserved patients. No engineers. Forge lets safety-net clinics build permanent, verified operational tools from plain language and gets smarter with every tool built.
- Devpost: https://devpost.com/software/forge-z8v4qm
- GitHub: https://github.com/arjvnv/forge
- Video: https://www.youtube.com/embed/4K3G6_XONPU?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Using Redis Beyond Caching, Best Creativity and Originality, Best Technical Implementation)
- Team: 3 GitHub contributor(s) — arjvnv (28 commits), Claude Sonnet 4.6 (1 commits), Steven Kuzhipala (1 commits)

## Devpost submission (written by the team)

### Overview

Systemic inequity shows up in software as much as it does anywhere else. The very communities with the greatest healthcare needs, that is low-income, uninsured, and immigrant populations served by safety-net clinics. They are the ones whose providers have the least access to the tools that make care delivery efficient, trackable, and accountable. Forge is a direct response to that structural gap. It empowers clinic staff to build their own tools using plain language without engineers or enterprise contracts, and without anything other than a description of what they need. More than 30 million patients in the United States receive their primary care from Federally Qualified Health Centers and safety-net clinics. These organizations operate on federal grant margins, carry high staff turnover, and run constant streams of operational software needs like quality measure reporting, care gap tracking, billing anomaly detection, scheduling tools. These are operational needs that require custom logic no one on their team can build. The tools that exist today do not reach this population. EHR built-in dashboards (eClinicalWorks, NextGen, Athena health) ship with 15–20 fixed quality reports. A quality coordinator with a question outside those reports has no path forward from within the system. Population health platforms like Arcadia, Innovaccer, and Health Catalyst solve this problem for large integrated health systems but requires six-month long implementations, IT-heavy onboarding, enterprise pricing that a safety-net clinic cannot approach. Microsoft's natural language patient cohort builder in Microsoft Fabric was discontinued in November 2025. Epic's NL query layer exists only for Epic customers, which is a minority of FQHCs. What remains is manual Excel exports, brittle volunteer-built spreadsheets, or outside consultants charging $5,000–$50,000 per engagement for tools the clinic needs every reporting cycle. The tools that would fix this never get built because each one is individually too small to justify engineering the clinic doesn't have. Consider a quality coordinator at a community health center. Her federal Uniform Data System (UDS) report is due in six weeks, and she has no data analyst or IT team on call. She types into Forge: "Show me diabetic patients who haven't had an A1c in the last six months." Forge synthesizes one from scratch. Once she approves the verified logic, 47 patient records appear in under a minute, and the tool installs permanently into the clinic's infrastructure. Three weeks later, a care manager types a slightly different phrasing of that same exact need. Forge recognizes the intent of the request and finds the original tool at a 91% similarity match, skips the synthesis phase entirely, and returns the live, updated patient list in two seconds. By skipping the synthesis phase, Forge is able to save the clinic on thousands of tokens that would otherwise go toward creating a redundant tool whose capability has already been implemented in another tool. The clinic's software library grows automatically with every question asked, improving the performance of the brain that creates these tools, with Forge wrapping around the clinic's/health department's infrastructure. What Forge Builds Forge is a self-building operational tooling system. A clinic coordinator describes what they need in plain language. Forge synthesizes a verified, executable capability, installs it as a permanent reusable tool in the clinic's library, runs it against the clinic's patient data, and returns the result, all in under a minute without an engineer. The mechanism is a six-stage pipeline: Route. Every incoming intent is embedded using OpenAI's text-embedding-3-small model and compared against the clinic's existing capability library via HNSW vector similarity search in Redis. If a semantically equivalent tool already exists (cosine similarity ≥ 0.85), the system routes directly to it and executes without synthesis — near-zero token cost, sub-second latency. Retrieve adjacent context. When routing misses, the same embedding — computed once and carried forward — queries the adjacent band of the vector space (similarity 0.5–0.84). Capabilities in that band are retrieved and injected into the synthesis prompt as proven patterns. A new capability asking about hypertensive patients benefits from context pulled from an already-proven diabetes denominator construction that shares the same structural shape. Synthesize. Claude Opus 4 generates executable Python logic against the clinic's typed data layer, primed with any retrieved adjacent patterns and constrained by a system prompt that explicitly marks user input as untrusted data. Verify. Two-stage verification before any logic runs on patient data. An AST walker structurally proves the generated code: zero imports, zero dunder attribute accesses, all data layer calls on a named allowlist, all name references either locally defined or explicitly permitted. Sandbox execution against mock data then confirms the function compiles, executes cleanly, and returns the declared output shape. Approve. An async gate pauses the build loop. The verified logic is presented for human review. No AI-generated code touches real patient data until a human releases the gate. Install and execute. The capability is stored in Redis as a permanent bundle with its embedding indexed in the vector store, then executed immediately. Every future request that semantically matches this tool routes to it directly. The Compounding Intelligence Layer The core architectural property of Forge is that the system gets more capable and more efficient as it is used. This is a direct consequence of how the vector index, embedding model, and synthesis pipeline interact. When the clinic builds its first capability, the vector index has one entry. By the tenth capability, a new request arrives with a rich context band of adjacent patterns that the synthesizer uses to produce more accurate, more structurally sound logic, faster. The built_from field on each installed manifest records exactly which prior capabilities were retrieved and used as synthesis context as a permanent provenance chain stored in RedisJSON. Token economics follow the same compounding logic. A fresh synthesis costs roughly 2,400–3,000 tokens of Claude Opus inference. A reuse costs an OpenAI embedding call and a Redis vector search. Across six monthly reporting cycles, re-synthesizing from scratch every time scales linearly in cost. Forge's build-reuse model flattens after the first build and stays flat. The efficiency ratio grows with every reuse event. Intelligence Metrics Dashboard The Intelligence Dashboard runs as a standalone application alongside the main demo, making Forge's Redis and Anthropic infrastructure directly observable in real time. Every query Forge receives triggers a live vector search across the capability library using RedisVL's HNSW index. The Routing Log captures each decision: the cosine similarity score returned, the intent text that triggered it, and the outcome. When similarity clears the threshold, Redis routes directly to the existing capability, the query executes instantly, and no Claude inference happens at all. When it misses, the adjacent similarity band is queried to retrieve related capabilities as synthesis context, Claude Opus 4 builds a new one, and the token cost is recorded from the live SSE payload. This is Redis acting as agent memory: the vector index holds the clinic's accumulated operational knowledge, and every incoming query is matched against it before any model is called. The Session Stats panel surfaces the token economics this produces in running totals: tokens spent on synthesis, tokens saved through dynamic capability reuse, and a live reuse rate that climbs as the library grows. These numbers are not projected. They are counted from real payloads across real queries in the session. The Capability Provenance section shows what Redis stores beyond the routing layer. Each installed capability carries its full build trace, AST verification facts, and a built_from lineage recording which prior capabilities the HNSW adjacent retrieval pulled in as synthesis context during the build. That lineage is what makes Forge compound: Claude synthesizes each new capability with awareness of proven patterns already in the Redis registry, so the system builds on what it knows rather than re-deriving from scratch. Taken together, the dashboard shows Redis doing three distinct jobs simultaneously: vector search for semantic routing, persistent JSON storage as the capability registry and agent memory, and Streams as the live event bus powering every stage of the build. The dashboard makes that structural dependency visible, and shows in live numbers how it translates directly into reduced token usage, real-time dynamic capability selection, and a system that gets more efficient the more it is used. Anthropic Track: Building with Claude for Social Impact Claude Code as the Development Environment The entire Forge system was built in about a 24-hour window using Claude Code as the primary development tool between the two of us (Steven and Arjun). Claude Code held the full system architecture in context across files by maintaining schema consistency between the Python backend and TypeScript frontend, catching cross-module contract violations, and reference implementations directly from the PRD specification. Claude Opus 4 and Sonnet 4.6 in the Synthesis Loop Claude Opus 4 (claude-opus-4-8) handles capability synthesis, which is the step requiring genuine clinical reasoning about what LOINC codes map to A1c observations, what SNOMED codes identify hypertension, and what the correct denominator construction logic looks like for a given care gap query. Claude Sonnet 4.6 (claude-sonnet-4-6) handles routing decisions making them lighter and faster, whcih is appropriate for the embedding-based similarity matching task. Ethical Architecture for Clinical AI Privacy is enforced at the AST level where the generated logic can only access the data sources declared in its manifest, verified structurally before any execution against patient data. The human approval gate means no AI-generated code runs on real patient records without explicit human release. Forge does not make care decisions. It generates operational tooling for the staff who support care decisions like a quality coordinator, a care manager, a billing lead. Every output is a patient list for human action, not a clinical recommendation. Environmental impact is reduced structurally by the reuse mechanism. Every routing hit to an existing capability is an avoided Claude Opus inference call. As the capability library grows, the system does more work with less compute per question answered. The evaluation pipeline uses Synthea synthetic patients exclusively. No PHI was used anywhere in the build, test, or validation process. Redis Track: Three Pillars, One Backbone Redis is not an add-on to Forge. The product cannot function without it. Three Redis capabilities are deployed simultaneously, each handling a distinct and load-bearing role. Pillar 1: Vector Search — Semantic Routing and Compounding Retrieval Every installed capability's description is embedded with text-embedding-3-small (1,536 dimensions) and indexed in a RedisVL HNSW vector index under cosine similarity. Incoming intents are embedded with the same model and searched against this index in milliseconds. The HNSW algorithm provides approximate nearest-neighbor search in O(log n) time. Cosine similarity measures semantic alignment between query and capability embeddings. For example a "show me diabetic patients with poor A1c" maps within 0.09 cosine distance of "which diabetes patients have A1c above 9%", routing both to the same installed tool without re-synthesis. The query embedding is computed once at routing time and carried forward for the adjacent band retrieval which is one embedding API call per intent regardless of downstream uses. Pillar 2: RedisJSON — Capability Registry and Provenance Each capability's complete bundle which includes the manifest, generated logic, ui_spec, and verification status is stored as a JSON document in Redis, co-located with its embedding under the same key prefix. Redis is the registry, not a cache in front of a database. Reuse counting is an atomic JSON numeric increment. Provenance chains recording which prior capabilities informed each synthesis are stored on the manifest and queryable at any time. Pillar 3: Redis Streams — Live Event Bus Every build loop stage transition emits a BuildEvent to a Redis Stream. The FastAPI SSE endpoint polls this stream and forwards matching events to the browser as Server-Sent Events. This is the mechanism behind the live build choreography — every stage (routing, gap, synthesizing, verified, approved, installed, executing, done) is a real Redis Stream entry consumed in real time by the frontend. The intelligence dashboard's live stream panel shows these entries arriving as the demo runs. The Three Roles Together These three use cases map to the three Redis patterns foundational to production AI infrastructure: vector search for grounding responses in real data, semantic routing as a form of semantic caching that skips expensive inference when the answer already exists, and persistent searchable agent memory across all sessions. Technical Stack The Broader Purpose Forge is infrastructure for the long tail of communities that have always been told their needs are too small to justify engineering. Tens of millions of patients rely on safety-net clinics as their primary access to healthcare. Those clinics deserve the same operational software capabilities that well-funded hospital systems take for granted, like tools built from their own needs, verified before they touch patient data, permanent so knowledge doesn't walk out the door when staff turns over, and cheap enough to run every month without a second thought. That is what Forge builds toward. Every capability installed is a piece of infrastructure the clinic permanently owns. Every reuse is a tool running correctly without anyone having to rebuild it. Every month the library grows, the system gets smarter about that clinic's specific data, and the cost of the next question gets lower. The infrastructure compounds because the communities it serves needs it to.

## README (from the GitHub repository)

# forge
Clinics serve millions on tight budgets but lack engineers to build tools for tracking overdue patients or running reports. Standard AI fails here because it improvises, causing errors and high costs. Forge lets staff type needs in plain English to build, verify, and permanently save secure tools in seconds.


## Detected evidence (automated analysis)

Indexed codebase: 80 recognized source files, 373 KB.
- Anthropic (technology) — detected in the code
- CrewAI (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Redis (technology) — detected in the code
- SQL (language) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code
- AI coding agent: Claude Code — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (94 of 94)

```
.env.example
.gitignore
backend/__init__.py
backend/config.py
backend/data/__init__.py
backend/data/clinic_data.py
backend/kernel/__init__.py
backend/kernel/build_loop.py
backend/kernel/executor.py
backend/kernel/installer.py
backend/kernel/router.py
backend/kernel/synthesizer.py
backend/kernel/verifier.py
backend/main.py
backend/registry/__init__.py
backend/registry/capability_store.py
backend/schemas.py
backend/seed_capabilities.py
data/load_synthea.py
data/schema.sql
docker-compose.yml
eval/__init__.py
eval/harness.py
eval/metrics.py
eval/reference/__init__.py
eval/reference/cms122_diabetes.py
eval/reference/cms165_hypertension.py
eval/swarm/__init__.py
eval/swarm/swarm_agent.py
intelligence/.env.example
intelligence/.gitignore
intelligence/index.html
intelligence/package.json
intelligence/src/api/client.ts
intelligence/src/api/types.ts
intelligence/src/App.tsx
intelligence/src/components/ConnectionBanner.tsx
intelligence/src/components/Header.tsx
intelligence/src/components/Provenance.tsx
intelligence/src/components/RedisPanel.tsx
intelligence/src/components/RoutingLog.tsx
intelligence/src/components/SessionStats.tsx
intelligence/src/main.tsx
intelligence/src/state/derive.test.ts
intelligence/src/state/derive.ts
intelligence/src/state/useIntelligence.ts
intelligence/src/styles.ts
intelligence/src/vite-env.d.ts
intelligence/tsconfig.json
intelligence/tsconfig.node.json
intelligence/vite.config.ts
pytest.ini
README.md
requirements.txt
shell/.gitignore
shell/index.html
shell/package.json
shell/postcss.config.js
shell/src/api.ts
shell/src/App.tsx
shell/src/chart/palette.ts
shell/src/chart/select.test.ts
shell/src/chart/select.ts
shell/src/chart/transform.test.ts
shell/src/chart/transform.ts
shell/src/chart/types.ts
shell/src/components/AskBar.tsx
shell/src/components/BuildPanel.tsx
shell/src/components/CodeBlock.tsx
shell/src/components/DetailModal.tsx
shell/src/components/Header.tsx
shell/src/components/Hero.tsx
shell/src/components/LibraryAside.tsx
shell/src/components/ResultChart.tsx
shell/src/components/ResultsTable.tsx
shell/src/index.css
shell/src/main.tsx
shell/src/theme.ts
shell/src/types.ts
shell/src/useForge.ts
shell/tailwind.config.js
shell/tsconfig.app.json
shell/tsconfig.json
shell/tsconfig.node.json
shell/vite.config.ts
tests/__init__.py
tests/conftest.py
tests/test_build_loop.py
tests/test_executor.py
tests/test_harness_parse.py
tests/test_installer.py
tests/test_main.py
tests/test_provenance.py
tests/test_swarm_agent.py
```

### Dependencies

- intelligence/package.json: @types/react@^18.3.12, @types/react-dom@^18.3.1, @vitejs/plugin-react@^4.3.4, react@^18.3.1, react-dom@^18.3.1, typescript@^5.6.3, vite@^5.4.11, vitest@^2.1.8
- requirements.txt: anthropic@==0.111.0, arize-otel@>=0.1.0, astroid@==3.3.5, asyncpg@==0.29.0, crewai@==1.14.7, fastapi@==0.115.0, httpx@==0.28.1, numpy@==1.26.4, openinference-instrumentation-anthropic@>=0.1.15, opentelemetry-exporter-otlp@>=1.28.0, opentelemetry-sdk@>=1.28.0, pandas@==2.2.3, psycopg2-binary@==2.9.9, pydantic@>=2.11.9,<2.13, pydantic-settings@>=2.5.2,<2.13, pytest@==8.3.3, pytest-asyncio@==0.24.0, python-dotenv@>=1.0.1,<2, redis@==5.1.0, redisvl@==0.3.6, RestrictedPython@==7.4, scikit-learn@==1.5.2, sqlalchemy@==2.0.35, sse-starlette@==2.1.3, uvicorn[standard]@>=0.31.1
- shell/package.json: @types/react@^18.3.12, @types/react-dom@^18.3.1, @vitejs/plugin-react@^4.3.4, autoprefixer@^10.4.20, postcss@^8.4.49, react@^18.3.1, react-dom@^18.3.1, recharts@^2.13.3, tailwindcss@^3.4.17, typescript@^5.6.3, vite@^5.4.11, vitest@^2.1.8

### Recent commits (newest first)

- Merge pull request #9 from arjvnv/feature/visualize-charts
- shell: Visualize — purpose-backed result charts (Table | Chart toggle)
- backend: emit optional ui_spec.chart from synthesizer + seeds
- Merge pull request #8 from arjvnv/fix/seed-provenance
- Give pre-loaded seeds grounded provenance so they fully drive the metrics
- Merge pull request #7 from arjvnv/feature/intelligence-dashboard
- Fix empty Routing Log / Session Stats: drop fragile session-anchor gate
- Add standalone Forge Intelligence Dashboard (Vite+React+TS, port 5174)
- Add read-only provenance persistence + /intelligence/stream endpoint
- Update example chips to data-returning queries
- Allow exception handling in generated logic; block mro() half-gadget
- Load all observations (not just A1c/BP); harden routing against timeouts
- Persist built_from provenance; relax manifest metadata types
- Rebuild frontend: light-theme design fully wired to live backend
- Add retrieval-augmented (compounding) synthesis
- Fix build loop end-to-end: reuse routing, sandbox allowlist, seed capabilities
- Phase 5: Forge/blacksmithing visual identity — dark steel + ember accent
- Fix synthesizer: tell Claude date/datetime are pre-injected, no imports needed
- Fix config extra fields validation and redisvl 0.20 schema format
- Merge pull request #5 from arjvnv/phase/4-eval-pipeline

## Key source files (fetched from GitHub, selected and truncated for size)

### docker-compose.yml

```yaml
version: "3.9"

services:
  redis:
    image: redis/redis-stack:latest
    ports:
      - "6379:6379"
      - "8001:8001"  # RedisInsight UI
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-forge}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-forge}
      POSTGRES_DB: ${POSTGRES_DB:-forge}
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./data/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U forge"]
      interval: 5s
      timeout: 3s
      retries: 10

volumes:
  redis_data:
  postgres_data:

```

### requirements.txt

```
fastapi==0.115.0
uvicorn[standard]>=0.31.1
python-dotenv>=1.0.1,<2
# Ranges (not hard pins): crewai-core needs pydantic>=2.11.9,<2.13; the backend
# already runs newer pydantic happily, so this overlap installs in both venvs.
pydantic>=2.11.9,<2.13
pydantic-settings>=2.5.2,<2.13

# Redis
redis==5.1.0
redisvl==0.3.6

# Postgres
asyncpg==0.29.0
psycopg2-binary==2.9.9
sqlalchemy==2.0.35

# Anthropic
anthropic==0.111.0

# CrewAI multi-agent baseline (eval only; requires Python <3.14 — install into .venv-eval)
crewai==1.14.7

# Eval / data science
pandas==2.2.3
numpy==1.26.4
scikit-learn==1.5.2

# Arize tracing (not yet imported in code; floors avoid pinning conflicts with
# crewai's opentelemetry-sdk~=1.34 in the eval venv while keeping the backend installable)
arize-otel>=0.1.0
opentelemetry-sdk>=1.28.0
opentelemetry-exporter-otlp>=1.28.0
openinference-instrumentation-anthropic>=0.1.15

# AST / sandbox
astroid==3.3.5
RestrictedPython==7.4

# HTTP client
httpx==0.28.1
sse-starlette==2.1.3

# Test
pytest==8.3.3
pytest-asyncio==0.24.0

```

### intelligence/package.json

```
{
  "name": "forge-intelligence",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "preview": "vite preview",
    "test": "vitest run"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  },
  "devDependencies": {
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "@vitejs/plugin-react": "^4.3.4",
    "typescript": "^5.6.3",
    "vite": "^5.4.11",
    "vitest": "^2.1.8"
  }
}

```

### shell/package.json

```
{
  "name": "forge-shell",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "preview": "vite preview",
    "test": "vitest run"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "recharts": "^2.13.3"
  },
  "devDependencies": {
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "@vitejs/plugin-react": "^4.3.4",
    "autoprefixer": "^10.4.20",
    "postcss": "^8.4.49",
    "tailwindcss": "^3.4.17",
    "typescript": "^5.6.3",
    "vite": "^5.4.11",
    "vitest": "^2.1.8"
  }
}

```

### backend/main.py

```python
"""
Forge FastAPI app — wires the kernel together and exposes the build loop over
HTTP + SSE.

Flow for the demo:
    POST /intent           -> kicks off the build loop as a background task,
                              returns a pre-generated capability_id + stream URL
    GET  /events/{id}      -> SSE stream of BuildEvents for that build
    POST /approve/{id}     -> releases the human-approval gate
    ... capability installs, executes, and the stream ends with `done`.
"""
from __future__ import annotations

import asyncio
import json
import uuid
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse

from backend.config import settings
from backend.data.clinic_data import ClinicDataLayer
from backend.kernel.build_loop import BuildLoop
from backend.kernel.executor import Executor, ExecutionError
from backend.registry.capability_store import CapabilityStore
from backend.schemas import BuildEvent, IntentRequest

SSE_POLL_INTERVAL_S = 0.3
SSE_TIMEOUT_S = 60.0
# read_events blocks ~500ms server-side; the outer wait_for must exceed that so
# it only fires as a backstop, never on the normal blocking-read path.
SSE_READ_BLOCK_TIMEOUT_S = 1.0
TERMINAL_STAGES = {"done", "error", "verify_failed"}


@asynccontextmanager
async def lifespan(app: FastAPI):
    store = CapabilityStore(settings.redis_url)
    await store.connect()

    clinic_data = ClinicDataLayer(settings.database_url)
    await clinic_data.connect()

    app.state.store = store
    app.state.clinic_data = clinic_data
    app.state.build_loop = BuildLoop(store, clinic_data)
    # Keep references to background build tasks so they aren't GC'd mid-flight.
    app.state.build_tasks = set()

    try:
        yield
    finally:
        await clinic_data.close()
        await store.close()


app = FastAPI(title="Forge", version="0.1.0", lifespan=lifespan)

# Hackathon: the shell runs on a different port, so origins are open.
# allow_credentials is False: "*" + credentials is spec-invalid (browsers reject
# it) and would otherwise broaden CSRF surface on /intent and /approve. If real
# auth/cookies are added later, replace "*" with an explicit origin allowlist.
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


class RunRequest(BaseModel):
    measurement_year: int = Field(default=2023, ge=1900, le=2100)


# ── health ──────────────────────────────────────────────────────────────────


@app.get("/health")
async def health():
    redis_ok = False
    postgres_ok = False
    try:
        await app.state.store._redis.ping()
        redis_ok = True
    except Exception:
        redis_ok = False
    try:
        async with app.state.clinic_data._pool.acquire() as conn:
            await conn.fetchval("SELECT 1")
        postgres_ok = True
    except Exception:
        postgres_ok = False
    return {"status": "ok", "redis": redis_ok, "postgres": postgres_ok}


# ── build loop ────────────────────────────────────────────────────────────────


async def _drain_build(build_loop: BuildLoop, request: IntentRequest, cap_id: str):
    """Run the async generator to completion; events go to the Redis stream."""
    try:
        async for _event in build_loop.run(request, cap_id):
            pass
    except Exception as e:
        # Never let a background build die silently — surface it on the stream.
        await build_loop.store.emit(
            BuildEvent(
                capability_id=cap_id, stage="error", message=f"Build crashed: {e}"
            )
        )


@app.post("/intent")
async def intent(request: IntentRequest):
    cap_id = str(uuid.uuid4())
    build_loop: BuildLoop = app.state.build_loop

    task = asyncio.create_task(_drain_build(build_loop, request, cap_id))
    app.state.build_tasks.add(task)
    task.add_done_callback(app.state.build_tasks.discard)

    return {"capability_id": cap_id, "stream_url": f"/events/{cap_id}"}


@app.get("/events/{capability_id}")
async def events(capability_id: str):
    store: CapabilityStore = app.state.store

    async def event_generator():
        last_id = "0"
        loop = asyncio.get_running_loop()
        deadline = loop.time() + SSE_TIMEOUT_S

        while True:
            if loop.time() >= deadline:
                yield {
                    "data": json.dumps(
                        {"stage": "timeout", "message": "Stream timed out", "payload": {}}
                    )
                }
                return

            try:
                # read_events blocks server-side for a finite window (its own
                # default); the outer wait_for is just a backstop so a cancelled
                # read can't hang the SSE generator.
                entries = await asyncio.wait_for(
                    store.read_events(last_id, count=10),
                    timeout=SSE_READ_BLOCK_TIMEOUT_S,
                )
            except asyncio.TimeoutError:
                entries = []
            except Exception:
                entries = []

            for entry in entries:
                last_id = entry.get("id", last_id)
                if entry.get("capability_id") != capability_id:
                    continue

                try:
                    payload = json.loads(entry.get("payload", "{}"))
                except (json.JSONDecodeError, TypeError):
                    payload = {}

                stage = entry.get("stage", "")
                yield {
                    "data": json.dumps(
                        {
                            "stage": stage,
                            "message": entry.get("message", ""),
                            "payload": payload,
                        }
                    )
                }
                if stage in TERMINAL_STAGES:
                    return

 
[truncated — 2531 more characters]
```

### intelligence/src/main.tsx

```typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
);

```

### shell/src/main.tsx

```typescript
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';

const rootEl = document.getElementById('root');
if (!rootEl) throw new Error('Root element #root not found');

createRoot(rootEl).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

```

### intelligence/src/App.tsx

```typescript
import { useMemo } from 'react';
import { KEYFRAMES, SANS, C } from './styles';
import { useIntelligence } from './state/useIntelligence';
import {
  deriveRoutingDecisions,
  deriveStats,
  deriveStreamRows,
} from './state/derive';
import { Header } from './components/Header';
import { ConnectionBanner } from './components/ConnectionBanner';
import { RoutingLog } from './components/RoutingLog';
import { SessionStats } from './components/SessionStats';
import { RedisPanel } from './components/RedisPanel';
import { Provenance } from './components/Provenance';

export default function App() {
  const {
    capabilities,
    capDetail,
    health,
    events,
    loaded,
    requestDetail,
  } = useIntelligence();

  const decisions = useMemo(
    () => deriveRoutingDecisions(events, capabilities),
    [events, capabilities],
  );
  const stats = useMemo(() => deriveStats(decisions), [decisions]);
  const streamRows = useMemo(() => deriveStreamRows(events, capabilities), [events, capabilities]);

  const connectionLost =
    !health.reachable || !health.redis || !health.postgres;

  return (
    <div
      style={{
        minHeight: '100vh',
        background: C.pageBg,
        color: C.text,
        fontFamily: SANS,
        fontSize: 14,
        lineHeight: 1.5,
        WebkitFontSmoothing: 'antialiased',
      }}
    >
      <style>{KEYFRAMES}</style>
      <Header health={health} />
      <ConnectionBanner visible={connectionLost} />
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 32px 56px' }}>
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: '1.4fr 1fr',
            gap: 28,
            alignItems: 'start',
          }}
        >
          <RoutingLog decisions={decisions} stats={stats} loaded={loaded} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
            <SessionStats stats={stats} />
            <RedisPanel
              indexedCount={capabilities.length}
              streamRows={streamRows}
              loaded={loaded}
            />
          </div>
        </div>
        <Provenance
          capabilities={capabilities}
          capDetail={capDetail}
          events={events}
          requestDetail={requestDetail}
          loaded={loaded}
        />
      </div>
    </div>
  );
}

```

### shell/src/App.tsx

```typescript
import { C } from './theme';
import { useForge } from './useForge';
import Header from './components/Header';
import AskBar from './components/AskBar';
import Hero from './components/Hero';
import BuildPanel from './components/BuildPanel';
import ResultsTable from './components/ResultsTable';
import LibraryAside from './components/LibraryAside';
import DetailModal from './components/DetailModal';

export default function App() {
  const f = useForge();

  const toolsForged = f.library.length;
  const totalReuses = f.library.reduce((a, c) => a + (c.reuse_count || 0), 0);
  const showHero = !f.build && !f.results;
  const detailCap = f.detailId
    ? f.library.find((c) => c.id === f.detailId)
    : undefined;

  return (
    <div
      style={{ minHeight: '100vh', padding: '22px 26px 60px', background: C.bg }}
    >
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <Header
          toolsForged={toolsForged}
          totalReuses={totalReuses}
          health={f.health}
          judge={f.judge}
          onToggleJudge={() => f.setJudge(!f.judge)}
        />

        <div
          className="frg-main"
          style={{
            display: 'grid',
            gridTemplateColumns: 'minmax(0,1fr) 368px',
            gap: 22,
            alignItems: 'start',
          }}
        >
          <main
            style={{
              display: 'flex',
              flexDirection: 'column',
              gap: 18,
              minWidth: 0,
            }}
          >
            <AskBar
              askText={f.askText}
              year={f.year}
              submitting={f.submitting}
              onAskText={f.setAskText}
              onYear={f.setYear}
              onSubmit={f.startBuild}
            />

            {f.build ? (
              <BuildPanel
                build={f.build}
                judge={f.judge}
                onToggleJudge={() => f.setJudge(!f.judge)}
                onApprove={f.approve}
              />
            ) : null}

            {f.results ? (
              <ResultsTable r={f.results} onOpen={f.openDetail} />
            ) : null}

            {showHero ? <Hero /> : null}
          </main>

          <LibraryAside
            library={f.library}
            runningId={f.runningId}
            onOpen={f.openDetail}
            onRun={f.runSaved}
          />
        </div>
      </div>

      {f.detailId ? (
        <DetailModal
          id={f.detailId}
          fallback={detailCap}
          running={f.runningId === f.detailId}
          onClose={f.closeDetail}
          onRun={f.runSaved}
        />
      ) : null}
    </div>
  );
}

```

### shell/postcss.config.js

```javascript
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

```

[64 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]