# Project export: MetricThread

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: OpenAI Build Week
- Tagline: An enterprise intelligence agent that turns cross-functional business signals into auditable, evidence-backed decisions
- Devpost: https://devpost.com/software/metricthread
- GitHub: https://github.com/Venkat-Kolasani/MetricThread-Enterprise.Intelligence.Agent
- Demo: https://metricthread.vercel.app/
- Video: https://www.youtube.com/embed/jCOZeOj08fk?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — Kolasani Venkat (18 commits)

## Devpost submission (written by the team)

### Inspiration

Business decisions rarely fail because teams lack dashboards. They fail because the evidence is scattered across departments, the relationships between metrics are hard to inspect, and recommendations arrive without a clear explanation of why anyone should trust them. MetricThread began with a VP-of-Growth question: when customer acquisition cost starts rising, how can a team quickly determine which upstream business signal deserves attention—and confidently act on it without treating an AI explanation as proof? We wanted to build something more useful than “chat with your CSV.” MetricThread continuously connects Client, Financial, and Partner signals, detects evidence-backed predictive relationships, and turns them into a decision workflow that people can inspect, challenge, and measure.

### What it does

MetricThread is an Enterprise Intelligence Agent for auditable business decisions. It monitors cross-functional metrics, detects statistically significant predictive lead–lag relationships, and presents the evidence before generating a recommendation. Its hero scenario identifies a decline in partner referral quality that predicts a rise in client acquisition cost. A user can: Start a live event feed and watch metrics update. Inspect retained signals in an Evidence Ledger. Open an Evidence Casefile to replay the underlying series, see candidate tests, rejected negative controls, ADF preparation, q-values, F-statistics, effect sizes, fingerprints, and confidence components. Review Evidence Resilience, which uses rolling historical windows and a target-history baseline before allowing a new recommendation. Move a recommendation from proposed to planned to implemented, then record a measured outcome. Ask grounded questions that return cited signal and insight IDs—or explicitly refuse when evidence is unavailable. Run a bounded marketing-spend scenario with forecast intervals, assumptions, reliability, and supporting evidence.

### How we built it

We built MetricThread as a React/Vite frontend and FastAPI backend, with Supabase Postgres for durable evidence and decision records, and Upstash Redis Streams for the live event pipeline. The system uses a deterministic seeded enterprise dataset spanning 180 days and nine metrics across Client, Financial, and Partner domains. Redis Streams fan each event into independent hot and cold consumer paths: one powers the live dashboard and the other persists data for historical analysis. The statistical core uses Python, pandas, NumPy, and statsmodels. It aligns daily series, checks stationarity, applies differencing when needed, selects model history with BIC, evaluates directed Granger tests, and applies Benjamini–Hochberg correction across the full candidate family. Confidence is computed deterministically from adjusted significance, incremental effect, sample adequacy, and recency. For the intelligence layer, we implemented an OpenAI Responses integration with strict structured output. The model receives only a compact, validated evidence packet; server-side checks require valid cited IDs, preserve deterministic confidence, and reject causal language. Codex helped us plan the architecture, implement the pipeline and product surfaces, build tests, and harden the deployment path.

### Challenges we ran into

The hardest problem was making the product genuinely trustworthy rather than merely polished. We had to ensure the signal engine did not simply rediscover the relationship we wanted. That meant testing the complete cross-domain candidate family, using multiple-testing correction, and carrying two unrelated negative controls through the workflow. We also learned that a significant full-history result is not enough. A relationship can look strong overall but fail across historical windows or add no value beyond the target metric’s own history. This led to Evidence Resilience: a rolling-origin validation layer that suppresses unstable signals before they can produce a new recommendation. Finally, we had to make the live demo feel operational. The workspace now supports real persisted decision lifecycle changes and outcome tracking, so judges can experiment with the product rather than only watch a static dashboard.

### Accomplishments we're proud of

Built a deterministic-first intelligence system where evidence comes before AI narration. Created the Evidence Casefile: an inspectable forensic record for every retained signal. Added rolling-origin resilience checks, negative-control validation, and baseline comparisons to suppress unstable recommendations. Kept confidence immutable and reproducible rather than model-generated. Built a complete evidence-to-action loop: signal → insight → recommendation → implementation → measured outcome. Made unsupported questions refuse instead of inventing an answer. Delivered a distinctive enterprise product experience that prioritizes inspectability over dashboard theatre.

### What we learned

We learned that “AI for analytics” becomes much more compelling when the AI is the final interpreter, not the source of truth. We also learned that explainability is not a tooltip. It needs to be part of the product architecture: persisted evidence, reproducible tests, negative controls, model versions, confidence components, and a clear record of what a recommendation is based on. Most importantly, we learned that predictive evidence should support human judgment—not replace it. MetricThread is designed to help teams make better decisions with an inspectable trail behind every important recommendation.

### What's next

Next, we want to connect governed real-world sources such as CRM, ERP, support, and marketing platforms while preserving the same evidence boundary. We also plan to add authenticated workspaces, decision ownership, richer audit attribution, collaboration workflows, scheduled executive briefings, and calibrated recommendation evaluation based on real outcomes. Longer term, MetricThread can become a decision-intelligence layer for enterprises: continuously finding meaningful cross-functional signals, validating them over time, and helping teams turn evidence into accountable action.

## README (from the GitHub repository)

# MetricThread

**Grounded cross-functional intelligence for auditable business decisions.**

MetricThread is an Enterprise Intelligence Agent for a VP-of-Growth workflow. It continuously simulates Client, Financial, and Partner signals; identifies statistically corrected predictive lead-lag evidence; exposes every retained signal as an auditable Evidence Casefile; requires resilience validation before a new model narrative can become a recommendation; and lets an executive test one constrained marketing-spend scenario.

MetricThread is a seeded enterprise scenario with a real, persisted decision workflow: lifecycle changes, outcomes, briefings, and forecasts are saved by the workspace.

## The executive journey

1. Start the live event feed: one compressed business day (nine events) emits every five seconds.
2. Inspect the accepted evidence: partner referral quality is predictive of client acquisition cost in the seeded fixture after correction for the complete candidate family.
3. Open the Evidence Casefile: replay the source and target series, inspect every candidate/rejected result, stationarity preparation, q/F/effect/sample/fingerprint values, the compact provider packet, cited IDs, immutable confidence, and causal-language refusal.
4. Inspect Evidence Resilience: rolling-origin windows compare the signal-assisted forecast with a target-history-only baseline, require every negative control to stay rejected, and suppress unstable signals from new model narratives.
5. Review an evidence-linked narrative, recommendation, confidence decomposition, and human-controlled decision status.
6. Ask a grounded follow-up. Factual answers cite stored insight and signal IDs; unsupported questions explicitly return `no_evidence`.
7. Test a deterministic marketing-spend change over one through seven days. The returned baseline, forecast interval, reliability, assumptions, and signal IDs are stored with the decision record.

## Architecture

```mermaid
flowchart LR
    S[Seeded synthetic generator] --> R[Upstash Redis Stream]
    R --> H[Hot consumer group\nrolling dashboard window]
    R --> C[Cold consumer group\nSupabase Postgres]
    C --> E[Deterministic signal engine\nADF, BIC, Granger, BH]
    E --> K[Evidence Casefile\nreplay and model boundary]
    E --> R[Rolling-origin resilience\nbaseline and control gate]
    R --> I[Evidence-linked insight\nand recommendation]
    E --> F[Deterministic scenario forecast]
    K --> U[React executive dashboard]
    I --> U[React executive dashboard]
    F --> U
```

The stream uses independent hot and cold consumer groups, acknowledgements, recovery, and idempotent cold writes. The signal engine requires 60 usable daily observations, applies stationarity preparation and BIC-selected history through seven days, then retains only Benjamini–Hochberg adjusted `q <= 0.05` evidence. A score named `confidence_v1` is deterministic (significance 40%, incremental effect 25%, sample adequacy 20%, recency 15%); a model may narrate it but cannot change it. `resilience_rolling_origin_v1` evaluates four historical origins, requires the accepted signal in at least three, requires at least three target-history baseline wins, and requires both declared controls to remain rejected at every origin before a new recommendation is eligible.

## Evidence semantics

- A displayed relationship is **predictive lead-lag evidence**, never proof that one business event caused another.
- Evidence includes source/target metrics, p and q values, F statistic, effect size, sample size, BIC model history, a stable fingerprint, and confidence components.
- The generator deliberately plants a partner-referral-quality to CAC relationship and two unrelated negative controls. These are test fixtures, not real-world findings.
- Grounded narratives receive a compact accepted-evidence packet, must cite stored IDs, are checked server-side, and reject causal wording or unknown citations.
- A Casefile recomputes the deterministic test family in memory for inspection but never overwrites persisted evidence.
- Resilience assessments are versioned and linked to an exact evidence fingerprint. A missing, stale, or failing assessment blocks a new model-generated recommendation; it does not erase past human decision records.
- Recommendation actions stay human-controlled: `proposed → planned → implemented`; only an implemented recommendation can receive a measured outcome.

## Local setup

Requirements: Python 3.13+, [uv](https://docs.astral.sh/uv/), Node 20+ and npm. Create your own `.env`; it is ignored by Git.

```bash
cp .env.example .env
uv sync
cd frontend && npm ci && cd ..
./scripts/test
```

Configure the variables in `.env`:

- `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are required for the simulator and Stream consumers.
- `SUPABASE_URL` and `SUPABASE_SECRET_KEY` are required for the server-side durable data, evidence, and decision stores. Never place the secret key in `frontend/`.
- `OPENAI_API_KEY` and `OPENAI_REASONING_MODEL` enable evidence-grounded narrative generation. Keep both server-side.

The first two migrations and the canonical 1,620-row fixture are already applied to the project used during development. For a fresh Supabase project, apply the existing foundation and signal-engine migrations and seed according to the SQL/Python commands in the charter. Phase 6 additionally requires `db/migrations/003_phase6_readiness.sql` and `db/migrations/004_evidence_resilience.sql` before running the current API against Supabase. If a direct Postgres connection is available, use:

```bash
uv run python -m metricthread.cli migrate
uv run python -m metricthread.cli seed
uv run python -m metricthread.cli signals
uv run python -m metricthread.cli resilience
```

If direct database TCP is unavailable, open **Supabase Dashboard → SQL Editor → New query**, paste and run `db/migrations/003_phase6_readiness.sql` followed by `db/migrations/004_evidence_resilience.sql`. The latter creates versioned resilience records. Then run `uv run python -m metricthread.cli resilience` to persist the current active-signal assessments through the server-side Supabase Data API.

Start the backend and frontend in separate terminals:

```bash
uv run uvicorn metricthread.api:app --reload
cd frontend && npm run dev
```

Open `http://localhost:5173`. The Vite development proxy forwards API requests to `http://localhost:8000`.

## Validation

Run the full local check before proposing or committing changes:

```bash
./scripts/test
```

This runs the Python suite and a Vite production build. The raw Postgres integration test is intentionally skipped in the current environment because the Supabase pooler resets direct TCP connections; deployed persistence is tested through the server-side Supabase Data API instead. The exact historical test results and decisions are recorded in [the charter](enterprise_intelligence_agent_project_charter.md).

## Deployment and interactive workspace

The supplied configuration builds the FastAPI API as a Render Docker service and the Vite frontend on Vercel. Follow the detailed [deployment runbook](docs/deployment-runbook.md). In short:

1. Apply the Phase 6 and Evidence Resilience Supabase migrations, then persist assessments with `uv run python -m metricthread.cli resilience`.
2. Deploy the API from `render.yaml` with `DEMO_READ_ONLY=false`.
3. Deploy the frontend with `VITE_API_BASE_URL` set to the Render API origin.
4. Set `CORS_ALLOWED_ORIGINS` on Render to the exact Vercel origin, redeploy, then run the rehearsal command.

The deployed workspace uses a seeded scenario for its data layer while retaining real human decision tracking. Recommendation lifecycle changes, measured outcomes, scenario forecasts, and briefings persist through the server-side Supabase stores. The live pipeline writes through its durable cold path.

```bash
uv run python -m scripts.phase6_rehearsal --base-url https://YOUR-RENDER-API.onrender.com
```

## Built with Code

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 62 recognized source files, 495 KB.
- 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
- SQL (language) — detected in the code
- Docker (technology) — claimed on Devpost, not found in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code
- Redis (technology) — claimed on Devpost, not found in the code
- Supabase (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code
- AI coding agent: Codex — evidence: config files committed to the repository

## Codebase structure (from repository index)

### Files (72 of 72)

```
.dockerignore
.env.example
.gitignore
AGENTS.md
db/migrations/001_foundation.sql
db/migrations/002_signal_engine.sql
db/migrations/003_phase6_readiness.sql
db/migrations/004_evidence_resilience.sql
db/seed_foundation.sql
Dockerfile
docs/collaboration-record.md
docs/demo-script.md
docs/deployment-runbook.md
docs/submission-checklist.md
enterprise_intelligence_agent_project_charter.md
frontend/index.html
frontend/package.json
frontend/src/components/AppWorkspace.jsx
frontend/src/components/BrandMark.jsx
frontend/src/components/BriefingStudio.jsx
frontend/src/components/DecisionLedger.jsx
frontend/src/components/EvidenceCasefile.jsx
frontend/src/components/EvidenceLedger.jsx
frontend/src/components/LandingPage.jsx
frontend/src/components/OverviewPanel.jsx
frontend/src/components/ScenarioLab.jsx
frontend/src/hooks/useExecutiveData.js
frontend/src/lib/api.js
frontend/src/main.jsx
frontend/src/styles.css
frontend/vite.config.js
LICENSE
metricthread/__init__.py
metricthread/api.py
metricthread/casefile.py
metricthread/cli.py
metricthread/database.py
metricthread/entities.py
metricthread/executive_repository.py
metricthread/executive.py
metricthread/generator.py
metricthread/insight_repository.py
metricthread/insights.py
metricthread/live_pipeline.py
metricthread/resilience_repository.py
metricthread/resilience.py
metricthread/signal_repository.py
metricthread/signals.py
metricthread/streams.py
pyproject.toml
README.md
render.yaml
scripts/phase2_rehearsal.py
scripts/phase3_demo.py
scripts/phase4_demo.py
scripts/phase6_rehearsal.py
scripts/test
tests/test_api.py
tests/test_casefile.py
tests/test_database.py
tests/test_entities.py
tests/test_executive.py
tests/test_generator.py
tests/test_insight_repository.py
tests/test_insights.py
tests/test_live_pipeline.py
tests/test_resilience.py
tests/test_signal_repository.py
tests/test_signals.py
tests/test_streams.py
uv.lock
vercel.json
```

### Dependencies

- frontend/package.json: @vitejs/plugin-react@^5.1.1, react@^19.2.0, react-dom@^19.2.0, vite@^7.2.0
- pyproject.toml: fastapi@>=0.115,<1, httpx@>=0.28,<1, numpy@>=2.2,<3, pandas@>=2.2,<3, psycopg[binary]@>=3.2,<4, python-dotenv@>=1.2,<2, statsmodels@>=0.14,<1, uvicorn[standard]@>=0.30,<1

### Recent commits (newest first)

- docs: highlight Codex and GPT-5.6 implementation
- feat: enable interactive MetricThread judge workspace
- fix: make judge evidence and storage boundaries auditable
- feat: add rolling-origin evidence resilience
- feat: add forensic evidence casefile
- feat: redesign MetricThread evidence workspace
- docs: record hosted MetricThread rehearsal evidence
- fix: keep live stream paths within demo latency target
- fix: scope judge latency to current simulation
- fix: make Upstash stream group creation idempotent
- docs: prepare MetricThread demo and Build Week submission
- feat: add executive briefing chat and scenario forecasting
- feat: generate grounded recommendations with decision tracking
- feat: detect auditable cross-domain lead-lag signals
- feat: stream live enterprise events through hot and cold paths
- feat: establish seeded enterprise data foundation
- docs: refine MetricThread plan from Build Week research
- Initial commit

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

### AGENTS.md

```markdown
# AGENTS.md

## Before any work

Read `enterprise_intelligence_agent_project_charter.md` in full before proposing or writing anything. Follow the phases in Section 10 in order. Do not skip a phase or reorder it, and do not start Phase 1 until Phase 0 research is recorded in Section 13 of the charter.

## Sub-phase workflow

Each sub-phase in Section 10 follows this exact sequence, in order, every time:

1. Build the deliverables listed for that sub-phase.
2. Run the four checks from Section 12 of the charter: correctness, negative control, latency and reliability where applicable, and groundedness where applicable. Report the actual results, not a summary claiming success.
3. Add a decision log entry to Section 13 of the charter, in the format specified there, for every meaningful choice made in that sub-phase, including ones made under time pressure.
4. Stop and present a summary of what was built, the test results, and the documentation update. Wait for explicit approval before continuing.
5. Only after approval is given, commit the work with a clear, specific commit message describing what changed and why, and push to the remote repository. Do not batch multiple sub-phases into one commit and do not push before approval is given.

Do not mark a sub-phase complete or move to the next one until all five steps above are done.

## Demo checkpoints

At the end of every phase in Section 10, not just at the very end of the project, show a working demo of what that phase added, even if the rest of the system is unfinished. This means running the actual pipeline or interface for that phase and showing real output, not describing what it would do. If a phase has nothing visually demoable on its own, for example a schema-only phase, say so plainly instead of stretching another phase's output to fill the gap.

## Manual steps

Anything that cannot be done by Codex directly, such as creating a `.env` file with real API keys, creating a Supabase project and copying its connection string, creating an Upstash Redis instance, setting a Vercel or Render environment variable through their dashboards, or authorizing a GitHub token, must be flagged clearly and separately from regular progress updates. For each manual step, provide:

- What needs to be created or obtained, and where, for example the exact dashboard and setting name
- The exact variable name Codex expects it to be stored under
- Confirmation of what happens once it is provided, so it is clear the step actually unblocks something

Do not proceed past a step that depends on a manual input that has not been confirmed as complete. Do not invent placeholder keys or silently skip the step.

## Code quality

Write code the way a careful engineer would, not the way a language model defaults to when unsupervised. Concretely, this means:

- No unnecessary abstraction, no speculative generality for requirements that do not exist yet in the current phase
- No dead code, no commented-out blocks left in place, no
[truncated — 1227 more characters]
```

### docs/submission-checklist.md

```markdown
# Build Week submission checklist

This document intentionally distinguishes completed repository work from manual submission evidence. Do not mark a manual item complete until it is verified.

## Repository and product

- [x] Public GitHub repository with MIT license.
- [x] Seeded synthetic data, deterministic signal engine, Evidence Casefile, rolling-origin resilience gate, evidence-linked workflow, chat refusal, and constrained scenario implementation.
- [x] Root test command and frontend production build.
- [x] README with setup, sample-data semantics, architecture, evidence boundary, and deployment instructions.
- [x] Deployment configuration for Vercel and Render with an interactive seeded-data workspace.
- [x] Under-three-minute narration script and a Codex/model collaboration record.
- [x] Phase 6 and Evidence Resilience Supabase migrations applied and versioned resilience records persisted in the current Supabase project.
- [ ] Render API deployed and `/health` verified.
- [ ] Vercel frontend deployed with the Render API origin and CORS verified.
- [ ] Full deployed API rehearsal and browser journey recorded with actual results in the charter.

## Required model evidence

- [x] OpenAI Responses integration and strict evidence validation are implemented.
- [ ] Funded GPT-5.6 structured output succeeds against an accepted persisted signal.
- [ ] GPT-5.6 result passes citation, non-causal-language, confidence-preservation, and no-evidence checks.
- [ ] Charter and video accurately describe the verified model result.

## Public submission artifacts

- [ ] Public YouTube video is uploaded, narrated, and under three minutes.
- [ ] Video explicitly describes how Codex and GPT-5.6 were used.
- [ ] Codex `/feedback` session ID for the core build is recorded.
- [ ] Existing Devpost draft has the Work & Productivity category, product description, public repository, public video URL, and `/feedback` ID.
- [ ] User explicitly authorizes the Devpost draft update; no duplicate Devpost project is created.

The current official requirements and deadline are on the [OpenAI Build Week Devpost page](https://openai.devpost.com/).

```

### Dockerfile

```
FROM python:3.13-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app

WORKDIR /app

RUN pip install --no-cache-dir uv==0.11.24

COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

COPY metricthread ./metricthread

EXPOSE 10000

CMD ["sh", "-c", ".venv/bin/uvicorn metricthread.api:app --host 0.0.0.0 --port ${PORT:-10000}"]

```

### pyproject.toml

```
[project]
name = "metricthread"
version = "0.1.0"
description = "Grounded cross-functional intelligence for auditable business decisions."
requires-python = ">=3.13"
dependencies = [
  "fastapi>=0.115,<1",
  "httpx>=0.28,<1",
  "numpy>=2.2,<3",
  "pandas>=2.2,<3",
  "psycopg[binary]>=3.2,<4",
  "python-dotenv>=1.2,<2",
  "statsmodels>=0.14,<1",
  "uvicorn[standard]>=0.30,<1",
]

[dependency-groups]
dev = [
  "pytest>=8.3,<9",
]

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]

```

### frontend/package.json

```
{
  "name": "metricthread-dashboard",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^19.2.0",
    "react-dom": "^19.2.0"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^5.1.1",
    "vite": "^7.2.0"
  }
}

```

### metricthread/cli.py

```python
from __future__ import annotations

import argparse
import os

from dotenv import load_dotenv

from metricthread.database import (
    apply_foundation_migration,
    apply_evidence_resilience_migration,
    apply_phase6_readiness_migration,
    apply_signal_engine_migration,
    database_url,
    foundation_counts,
    seed_foundation,
    seed_foundation_via_data_api,
)
from metricthread.entities import foundation_source_records, resolve_exact_keys
from metricthread.generator import lagged_pearson
from metricthread.signal_repository import signal_repository_from_environment
from metricthread.resilience import assess_signal_resilience
from metricthread.resilience_repository import resilience_store_from_environment


def main() -> None:
    load_dotenv()
    parser = argparse.ArgumentParser(description="MetricThread development commands")
    parser.add_argument("command", choices=("migrate", "seed", "seed-rest", "demo", "signals", "resilience"))
    args = parser.parse_args()

    if args.command == "migrate":
        url = database_url()
        apply_foundation_migration(url)
        apply_signal_engine_migration(url)
        apply_phase6_readiness_migration(url)
        apply_evidence_resilience_migration(url)
        print("foundation, signal-engine, Phase 6 readiness, and resilience migrations applied")
        return

    if args.command == "signals":
        report = signal_repository_from_environment().run_analysis()
        print(
            "signal analysis complete "
            f"candidates={report.candidate_count} accepted={len(report.accepted)} rejected={len(report.rejected)}"
        )
        for signal in report.accepted:
            print(
                f"{signal.metric_a} -> {signal.metric_b} "
                f"q={signal.adjusted_q_value:.3g} confidence={signal.confidence_score:.2f}"
            )
        return

    if args.command == "resilience":
        repository = signal_repository_from_environment()
        store = resilience_store_from_environment()
        observations = repository.list_metric_observations()
        for signal in repository.list_accepted():
            assessment = assess_signal_resilience(signal, observations)
            store.persist(assessment)
            summary = assessment.result["summary"]
            print(
                f"{signal.metric_a} -> {signal.metric_b} "
                f"eligible={assessment.recommendation_eligible} "
                f"retained={summary['signal_retained_windows']}/{summary['origin_count']} "
                f"baseline_wins={summary['baseline_wins']}/{summary['origin_count']}"
            )
        return

    if args.command == "seed-rest":
        supabase_url = os.environ.get("SUPABASE_URL")
        secret_key = os.environ.get("SUPABASE_SECRET_KEY")
        if not supabase_url or not secret_key:
            raise RuntimeError("SUPABASE_URL and SUPABASE_SECRET_KEY are required for seed-rest")
        dataset = seed_foundation_via_data_api(supabase_url, secret_key)
        print(f"canonical fixture synchronized through Data API: {len(dataset.events)} metric events")
        return

    url = database_url()

    if args.command == "seed":
        apply_foundation_migration(url)
        dataset = seed_foundation(url)
        print(f"seeded {len(dataset.events)} metric events")
        return

    apply_foundation_migration(url)
    dataset = seed_foundation(url)
    quality_to_cac = lagged_pearson(
        dataset.values("partner_referral_quality"),
        dataset.values("client_acquisition_cost"),
        dataset.primary_lag_days,
    )
    resolved = resolve_exact_keys(foundation_source_records())
    print("MetricThread Phase 1 foundation demo")
    print(f"entities={len(resolved)} events={len(dataset.events)} counts={foundation_counts(url)}")
    print(f"partner_referral_quality -> client_acquisition_cost (lag 3): r={quality_to_cac:.3f}")


if __name__ == "__main__":
    main()

```

### frontend/src/main.jsx

```javascript
import { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { AppWorkspace } from './components/AppWorkspace'
import { LandingPage } from './components/LandingPage'
import './styles.css'

function usePathname() {
  const [pathname, setPathname] = useState(window.location.pathname)

  useEffect(() => {
    function updatePathname() {
      setPathname(window.location.pathname)
    }

    window.addEventListener('popstate', updatePathname)
    return () => window.removeEventListener('popstate', updatePathname)
  }, [])

  return pathname
}

function MetricThreadApp() {
  const pathname = usePathname().replace(/\/+$/, '') || '/'

  if (pathname === '/app') return <AppWorkspace />
  return <LandingPage />
}

createRoot(document.getElementById('root')).render(<MetricThreadApp />)

```

### render.yaml

```yaml
services:
  - type: web
    name: metricthread-api
    runtime: docker
    plan: free
    dockerfilePath: ./Dockerfile
    healthCheckPath: /health
    envVars:
      - key: DEMO_READ_ONLY
        value: "false"
      - key: CORS_ALLOWED_ORIGINS
        sync: false
      - key: UPSTASH_REDIS_REST_URL
        sync: false
      - key: UPSTASH_REDIS_REST_TOKEN
        sync: false
      - key: SUPABASE_URL
        sync: false
      - key: SUPABASE_SECRET_KEY
        sync: false
      - key: OPENAI_API_KEY
        sync: false
      - key: OPENAI_REASONING_MODEL
        sync: false

```

### metricthread/__init__.py

```python
"""MetricThread foundation package."""

```

### frontend/index.html

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="theme-color" content="#ece8de" />
    <meta name="description" content="MetricThread is a grounded enterprise intelligence workspace for auditable business decisions." />
    <title>MetricThread — Enterprise Intelligence Agent</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

```

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