# AiSO Food Corp — AI Operations Center
## Full Rebuild Guide (for a Claude / self-hosted engineering environment)

This package contains **everything needed to rebuild and run the AI Operations
Center** — the multi-agent "AI Finance Services" platform built for Rich's
Products / AiSO Food Corp — inside your own company environment (Claude Code,
an internal dev box, or any standard cloud host).

> **What this application is.** A web application that runs five agentic
> "swarms" over finance & supply-chain workflows: Trade Deduction Triage
> (MVP1), Collections Prioritization (MVP2), Invoice Exception Handling
> (MVP3), Buyer Assistance / Source-to-Pay (MVP4), and Continuous Demand
> Sensing (MVP5), plus an executive dashboard and an Agreement-with-Human
> quality monitor. Each swarm is a small state machine of specialized agents
> (Classifier → Validity → independent Validator → Orchestrator) that reason
> over real database records and make evidence-backed, policy-gated decisions.

---

## 1. What's in this package

```
├── REBUILD_IN_CLAUDE.md        ← you are here (start here)
├── source/                     ← complete application source code
│   ├── app/                    ← pages + API routes (App Router)
│   ├── components/             ← React UI components
│   ├── lib/                    ← agent swarms, orchestrators, prisma client, utils
│   ├── hooks/                  ← React hooks
│   ├── prisma/                 ← schema.prisma (68 models) + seed helpers
│   ├── types/                  ← shared TypeScript types
│   ├── package.json            ← dependencies + scripts
│   ├── tailwind.config.ts / postcss.config.js / components.json
│   ├── tsconfig.json / next.config.js
│   ├── STYLE_GUIDE.md          ← design system reference
│   └── .env.example            ← copy to .env and fill in
├── database/
│   └── schema.prisma           ← standalone copy of the data model (68 tables)
└── manuals/                    ← full documentation set (Markdown + PDF)
    ├── MIGRATION_MANUAL.(md|pdf)          ← how the app was built / how to move it
    ├── ARCHITECTURE_DECISIONS.(md|pdf)    ← key design decisions & rationale
    ├── API_REFERENCE.(md|pdf)             ← every API route documented
    ├── DEPLOYMENT_GUIDE.(md|pdf)          ← production deployment steps
    ├── SECURITY_POSTURE.(md|pdf)          ← security model & controls
    ├── INTEGRATION_GAP_REGISTER.(md|pdf)  ← what's real vs. simulated (READ THIS)
    ├── GLOSSARY.(md|pdf)                  ← domain terms
    ├── BUILD_LOG.(md|pdf)                 ← chronological build history
    ├── COMPLETE_ROADMAP.(md|pdf)          ← full product roadmap
    ├── DEMO_SCRIPT.(md|pdf)               ← how to demo the platform
    ├── COMPLETE_80_SLIDE_OUTLINE / SLIDE_WEAVE  ← presentation material
    └── AI_Agent_MVP_Technical_Manual.docx ← original technical manual
```

---

## 2. Technology stack

| Layer            | Technology                                             |
|------------------|--------------------------------------------------------|
| Framework        | Next.js 14 (App Router) + React 18 + TypeScript        |
| Styling          | Tailwind CSS + shadcn/ui (Radix primitives)            |
| Charts           | Recharts                                               |
| ORM / Database   | Prisma → PostgreSQL (14+)                              |
| LLM calls        | Server-side `fetch` to an OpenAI-compatible endpoint   |
| Icons            | lucide-react                                           |

> **Important:** This is a **Next.js 14** codebase. Do not upgrade to Next.js
> 15 / React 19 without testing — several patterns here assume Next 14.

---

## 3. Prerequisites

- **Node.js 18.18+ or 20+**
- **Yarn** (the project is yarn-based; a `yarn.lock` will be generated on install)
- **A PostgreSQL 14+ database** you can reach with a connection string
- **An LLM API key** for an OpenAI-compatible chat/completions endpoint

---

## 4. Quick start (local rebuild)

```bash
# 1. Move into the source directory
cd source

# 2. Install dependencies (yarn is the supported package manager)
yarn install

# 3. Configure environment
cp .env.example .env
#    then edit .env → set DATABASE_URL and your LLM API key

# 4. Generate the Prisma client
yarn prisma generate

# 5. Create the database schema (first-time setup on an empty database)
yarn prisma db push

# 6. Start the dev server
yarn dev
#    → open http://localhost:3000
```

The app **self-seeds** most demo data on first request: many API routes call an
`ensureSeeded()` / auto-seed helper that populates their tables if empty
(deductions, collection accounts, invoices, boundary conditions, value ledger,
HITL queue, agreement metrics, governance, etc.). So after `yarn dev`, simply
visit each module page and data will appear.

To force a full seed up front, you can also POST to the seed endpoints, e.g.:

```bash
curl -X POST http://localhost:3000/api/seed-data
curl -X POST http://localhost:3000/api/seed-governance
curl -X POST http://localhost:3000/api/agreement-metrics
```

---

## 5. Seeing an agent swarm run end-to-end (recommended first step)

A standalone demonstration script runs the **real** MVP1 deduction pipeline
against a real database record and narrates every stage in the terminal:

```bash
cd source
npx tsx scripts/demo-deduction-agent.ts            # auto-pick a deduction
npx tsx scripts/demo-deduction-agent.ts 4          # a specific db id
npx tsx scripts/demo-deduction-agent.ts DED-2026-00003   # by case code
```

It prints: intake → context enrichment → ClassifierAgent → ValidityAgent →
ValidatorAgent (challenger) → Orchestrator decision → autonomous vs.
Human-in-the-Loop routing → Value Ledger booking. This is the fastest way to
confirm your LLM key and database are wired correctly.

---

## 6. How the code is organized

### Agent swarms (the core IP) — `source/lib/`
- `agent-swarm.ts` — MVP1 (Trade Deduction) and MVP2 (Collections) state machines
- `agent-swarm-mvp3.ts` — MVP3 Invoice Exception triage
- `agent-swarm-mvp4.ts` / `mvp4-orchestrator.ts` — MVP4 Source-to-Pay / Buyer policy
- `agent-swarm-mvp5.ts` — MVP5 Demand Sensing
- `mvp1-orchestrator.ts` — the deduction workflow orchestration stages
- `trade-deal-validator.ts` — deterministic (non-LLM) validity checks
- `invoice-validity-engine.ts` — MVP3 three-way-match logic
- `schemas.ts` — shared types, MVP labels/paths, boundary-condition defaults, `ulid()`
- `prisma.ts` — the singleton Prisma client (import `prisma` from here everywhere)

Each "cognitive" agent step calls an LLM with a strict-JSON system prompt; each
"tool" step is a real Prisma query. Every run persists an `AgentRun`,
`ActionProposal`, and (when relevant) `HITLQueueItem` + `ValueLedgerEntry`, plus
a full reasoning trace that the UI replays in the "Live Agent Trace" panel.

### Pages — `source/app/`
- `/` MVP1 (Deductions) · `/collection` MVP2 · `/invoices` MVP3 ·
  `/buyer` MVP4 · `/demand` MVP5
- `/executive` executive dashboard · `/agreement` Agreement-with-Human monitor
- `/methodology`, `/reference`, `/integration`, `/escalations`, `/workbench`, etc.
- `app/api/**` — all backend routes (documented in manuals/API_REFERENCE.md)

### Data model — `source/prisma/schema.prisma`
68 models covering deductions, trade deals, customers, SKUs, invoices,
collection accounts, agent runs, action proposals, HITL queue, value ledger,
audit log, governance, boundary conditions, agreement metrics, and more.

---

## 7. Swapping the LLM provider (Abacus.AI → your own / Claude)

The reference build calls an OpenAI-compatible endpoint. To point it at your
own gateway, edit the LLM constants near the top of each swarm file:

```ts
// source/lib/agent-swarm.ts  (and agent-swarm-mvp3/4/5.ts)
const LLM_URL   = 'https://YOUR-OPENAI-COMPATIBLE-ENDPOINT/v1/chat/completions';
const LLM_MODEL = 'your-model-name';
// Authorization header uses:  Bearer ${process.env.ABACUSAI_API_KEY}
```

The request body uses standard `messages`, `max_tokens`, and
`response_format: { type: 'json_object' }` (or a `json_schema`). Any endpoint
that honors OpenAI-style chat completions with JSON responses will work.

- **To use Anthropic Claude directly:** put an OpenAI-compatible shim/proxy in
  front of the Anthropic API (several exist), or adapt `llmJson()` in each swarm
  file to call the Anthropic Messages API and map the JSON response. The rest of
  the pipeline is provider-agnostic — it only consumes parsed JSON.
- Keep the API key in `.env` (`ABACUSAI_API_KEY`), or rename the variable and
  update the references if you prefer a different name.

---

## 8. What is real vs. simulated (read before your demo)

The platform deliberately separates **real platform data** (live Prisma reads,
real LLM reasoning, persisted runs) from **deterministic simulation** used to
make dashboards look full without external ERP connectivity (e.g. simulated
S/4HANA throughput, some synthetic financials seeded deterministically).

👉 **`manuals/INTEGRATION_GAP_REGISTER.md`** is the authoritative list of what is
live vs. simulated and exactly which integrations you'd wire up for a true
production deployment (S/4HANA, TPM, OCR, email, SSO). Read it first so you can
speak accurately to stakeholders.

---

## 9. Production build & deploy

```bash
cd source
yarn build      # produces an optimized production build
yarn start      # serves the production build on :3000
```

The app runs on any host that supports Node.js + a reachable PostgreSQL
database (a VM, a container, or a Node-friendly PaaS). See
`manuals/DEPLOYMENT_GUIDE.md` for the full production checklist, and
`manuals/ARCHITECTURE_DECISIONS.md` for the reasoning behind the structure.

---

## 10. Suggested reading order for a new engineer

1. **REBUILD_IN_CLAUDE.md** (this file) — get it running
2. **manuals/ARCHITECTURE_DECISIONS.md** — understand the shape
3. **manuals/API_REFERENCE.md** — the backend surface
4. **manuals/INTEGRATION_GAP_REGISTER.md** — real vs. simulated
5. **manuals/MIGRATION_MANUAL.md** — deep build/migration detail
6. **manuals/SECURITY_POSTURE.md** + **DEPLOYMENT_GUIDE.md** — before going live
7. **manuals/GLOSSARY.md** — domain vocabulary as needed

---

_Built for the Rich's Products AI Finance Services program. This package is a
full, self-contained snapshot of the application source and documentation._
