Cubiczan stack — Profile · software-factory · You are here:
Metabocommand
Metabolic Commerce Multi-Agent Platform — an AI-agent orchestration dashboard for eCommerce finance and operations teams. Twelve specialized agents across five metabolic systems (Capital Reflex, Revenue Velocity, Inventory Intelligence, Customer Lifetime, Operational Health) surface anomalies, propose actions, and route decisions through role-scoped approval queues with realtime collaboration.
Built on Next.js 16, Supabase (Auth + Postgres + Realtime + Presence), React 19, TypeScript, Tailwind 4, and Recharts.
Four KPIs at the top (Total Capital Deployed, Net Capital Velocity Score, Active Anomalies, Pending Approvals) render against live database counts. The Pulse Agent view below is the always-on capital health monitor.
Thirty days of inflow / outflow / net capital with a hover tooltip for any date, plus a color-graded heatmap of contribution margin by vendor × week (Vendor Delta's red cells show a real-world margin-erosion problem).
Each anomaly surfaces velocity impact, correlated patterns, and three proposed intervention scenarios. "Queue for Approval" creates a live approval item with a Slack notification.
The top bar uses Supabase Realtime Presence to show who is viewing the queue, with color-coded activity badges (Idle / Reviewing approval / Approving item / Rejecting item) that broadcast in real time. New items and status changes stream in via postgres_changes subscription — no polling, no refresh.
Chronological audit trail of every agent action (proposals, auto-executions, and human decisions). Multi-select filters for Agent, Action Type, and Outcome combine with a date-range picker. Clicking any row reveals the full reasoning summary. The log also subscribes to Realtime — new log rows appear automatically with a row highlight and toast.
Every user-initiated action (logins, approvals, threshold updates, agent pauses, settings changes) is recorded with UTC timestamp, user identity, and contextual reference. Filters update the timeline instantly; "Export Report" downloads the current filtered set as CSV for offline review.
Probability-weighted demand forecasting with a 15% confidence band across a 13-week rolling window. Forecast accuracy, active scenario count, and capital deployment lead time are surfaced as KPIs, while the scenarios table below (not shown) ranks five scenarios by probability with inline "Submit for Approval" actions.
Two visual layers: the scatter plot maps every expense line item by Capital Deployed (x) vs LTV Contribution (y), with a shaded red "waste zone" on the low-spend / low-LTV quadrant. Below it, the velocity bar chart color-codes categories (green ≥1.5, indigo ≥1.0, amber ≥0.5, rose <0.5). Items under $500/month auto-execute; larger items queue for CFO approval.
Liquidity gauge with critical / watch / healthy thresholds, alongside proposed capital reallocation flows. Each flow shows velocity deltas between source and destination channels and can be one-click submitted for CFO approval.
Five-card KPI bar (Conversion Rate, Stockout Rate, Customer LTV, Support Resolution, Pending Approvals) plus section-grouped agent panels. James (Operational Lead) lands here on login; RLS ensures he sees only Operations-scoped approval items, log records, and activity history.
LTV:CAC ratio heatmap by customer segment × acquisition channel (green = healthy, amber = watch, red = losing money), with auto-generated spend reallocation recommendations below. Each recommendation quantifies the CAC reduction and monthly dollar amount, submittable for approval with one click.
Inline funnel visualization with step-to-step conversion percentages, color-coded conversion rate by device, and A/B test results with split routing: tests under a 10% lift threshold auto-roll out to 100% traffic; larger lifts require approval.
Six-month LTV trend plus churn risk segmentation with intervention recommendations and dollar revenue at risk. Clicking through to win-back campaign proposals (not shown) submits real approval items for the Operational Lead to approve.
60-day SKU-level demand forecast with an 18% confidence band, paired with a stockout risk heatmap across distribution centers and weeks. Warehouses flagged amber or red trigger auto-generated POs (auto-execute under $10,000, approval-required above).
Carrier cost bars color-coded by on-time rate (green ≥95%, rose <85%), on-time trend line, and active delay alerts with proposed proactive actions. Route optimization proposals quantify annual savings and on-time improvement percentages.
Inquiry volume bars color-coded by severity (rose ≥1000, amber 500-999, indigo 300-499, green <300), 8-week resolution time trend, and recurring issue patterns with auto-generated process improvements submittable for approval.
Six-month review volume trend, inline referral funnel with step-to-step conversion percentages, and a high-advocacy segment table ranking customer cohorts by advocacy score with recommended actions (Review request / Referral incentive / Loyalty program invite).
The system-wide coordinator. Two KPI cards plus a Growth / Efficiency operating mode toggle (confirmed via modal, broadcast via Realtime so all tabs sync). The Active agent conflicts feed shows cross-agent disagreements with Harmony's resolution recommendation; the System bottlenecks feed surfaces capacity issues with Submit-for-Approval actions.
After Phase 2b, the app is feature-complete against the requirements spec except for live data integrations and agent pause persistence (both explicitly deferred):
- Auth + role routing — Supabase email/password; CFO lands on Finance Dashboard, Operational Lead lands on Operations Dashboard.
- Finance Dashboard with four fully-built Capital Reflex agents:
- Pulse Agent — KPI cards, capital flows line chart, vendor margin heatmap, alert feed with "Queue for Approval"
- Oracle Agent — demand forecast with 15% confidence band, probability-weighted scenario stack, 5-scenario decision table
- Sniper Agent — expense scatter plot with waste zone overlay, velocity bar chart, waste proposals with Auto-Execute / Submit-for-Approval split
- Conductor Agent — liquidity gauge, reallocation flows, priority matrix for 7 active initiatives
- Operations Dashboard with all eight agents across four panels:
- Acquisition Agent — CAC trend, LTV:CAC heatmap, spend pie, reallocation recommendations
- Conversion Agent — inline funnel, device breakdown, A/B test table with Auto-Rollout vs Submit routing
- Retention Agent — LTV trend, churn risk segments, win-back campaign proposals
- Demand Prophet Agent — SKU forecast with confidence band, stockout heatmap, auto-PO table with threshold
- Logistics Conductor Agent — carrier bars color-coded by on-time rate, on-time trend, delay alerts, route optimizations
- Support Reflex Agent — inquiry volume bars, resolution time trend, recurring issue patterns with process improvements
- Advocacy Agent — review volume trend, referral funnel, high-advocacy segment table
- Harmony Agent — agent conflict feed, Growth/Efficiency operating mode toggle (confirmation modal + Realtime broadcast), system bottleneck feed
- Approval Queue — Realtime subscription + Presence + four activity status badges (Idle / Reviewing / Approving / Rejecting) + 60s idle timeout + Slack webhook notifications + RLS-enforced role scoping
- Governance Watchdog — seniority-based agent permissions, default approval gates for high-impact actions, evidence packets, policy flags, and role-scoped evidence export
- Agent Action Log — Realtime + Presence (Idle / Reviewing log / Filtering logs) + three-filter combination + expandable reasoning rows
- Activity History Log — multi-select filters + date range + paginated load-more + CSV export + role scoping
- Settings — Data Source cards, editable Agent Threshold table, Slack Integration with Test Connection
- Profile — read-only account info, password change, notification preferences toggles (persisted to JSONB)
- Seed data — 12 agents, 14 approval items, 22 agent log records, 14 activity records, all matching the requirements spec exactly
The Support Reflex workflow has been strengthened with evidence-gated escalation lanes inspired by open-source human-in-the-loop support and agent-control projects. The app now separates autonomous support actions from approval-required and human-handoff lanes, and each lane names the evidence package required before it can be queued.
See docs/OPEN_SOURCE_RESEARCH.md for attribution to Tiledesk, the
InterSystems customer-support agent demo, and EpicStaff. No upstream source code
is vendored.
MetaboCommand formalizes the approval boundary as a Governance Watchdog:
each new approval proposal receives a seniority classification, policy flags,
and an exportable evidence packet. See docs/GOVERNANCE_WATCHDOG.md.
Attribution: runtime enforcement, evidence-packet, and seniority-based decision-rights patterns are adapted from Georgios Fradelos, PhD, Verifiable Governance Architecture (VGA) for Organisations and Teams with Human and AI Employees, Geneva, January 9, 2026. Finance-grade assurance direction is adapted from Georgios Fradelos, PhD, Finance-Grade Assurance for Agentic AI, Geneva, January 11, 2026.
Browser (Next.js client)
│
┌───────────────────────────┴───────────────────────────┐
│ │
Server Components Client Components
(RSC + Tailwind) - Recharts
│ - Realtime subscriptions
│ - Presence channels
│ - Activity-status broadcasts
▼ │
Route handlers ▼
/api/approvals/submit Supabase JS (anon key + RLS)
/api/approvals/decide - postgres_changes on approval_items
/api/approvals/evidence - evidence packet export
- Zod validation - postgres_changes on agent_action_log
- Role check - presence channel per page per role
- Watchdog evidence packet
- Insert + Slack webhook
- Activity log write
│
▼
Supabase Postgres
- profiles (role) ──> enforced by RLS policies
- agents scoped via current_user_role()
- approval_items function in security definer context
- agent_action_log
- activity_history
- slack_settings
MetaboCommand coordinates ~12 agents (Pulse, Oracle, Sniper, Conductor,
Acquisition, Conversion, Retention, Demand Prophet, Logistics Conductor,
Support Reflex, Advocacy, Harmony). Historically these agents coordinated by
talking to each other through the LLM chat loop — the Harmony Agent detected
cross-agent conflicts by having agents converse. That cost grows quadratically
with the number of agents: with m agents and h̄ messages per pair,
coordination costs h̄·m(m+1)/2 LLM calls that produce no customer value.
The StigmergyBoard (src/lib/stigmergy/) replaces those conversations with
stigmergy: agents don't message each other, they leave short-lived "scent"
signals on a shared board, and coordinate by reading the aggregated state of a
region. This is the same zero-token pattern proven in the Cubiczan swarm packs
(TEMM1E-derived scent field), where it measured 5.86× faster, 3.4× cheaper,
and turned 78 coordination LLM calls into 0 at identical quality — because
coordination becomes pure arithmetic instead of model round-trips.
import { StigmergyBoard } from "@/lib/stigmergy";
const board = new StigmergyBoard(); // immutable in-memory store by default
// Agents deposit scent instead of chatting:
board.deposit_signal({ region: "meta-ads", agent: "Acquisition Agent", kind: "claim", strength: 1 });
board.deposit_signal({ region: "meta-ads", agent: "Sniper Agent", kind: "veto", strength: 1 });
// Any agent reads the aggregated, time-decayed state — zero LLM calls:
board.read_signals("meta-ads"); // [{ kind: "claim", strength, agents }, { kind: "veto", ... }]
// Spent signals evaporate so stale intent can't cause phantom conflicts:
board.evaporate();deposit_signal(region, kind, strength)— writes one scent deposit (id + timestamp filled in). Kinds:completion,failure,difficulty,urgency,progress,help_wanted,claim,veto.read_signals(region)— aggregated, time-decayed reading per kind. Each kind decays on an exponential curve (strength × e^(−λt),λ = ln2 / half_life);urgencygrows with age (capped) so starved work rises on its own.evaporate()— purges signals whose decayed strength fell below the GC threshold, keeping the board self-cleaning.
The board is store-agnostic. The default InMemorySignalStore is pure and
immutable (every write returns a fresh snapshot), matching the repo's
immutability convention and staying safe in the client bundle. A durable
SqliteSignalStore (src/lib/stigmergy/sqlite-store.ts) backs the board with
Node's built-in node:sqlite — zero new npm dependencies, server-only, and
never re-exported from the barrel so it can't leak into the browser. This proves
the coordination surface needs nothing heavier than one table and two indexes —
no external coordination service.
The coordination path is feature-flagged and additive. The Harmony Agent
view calls resolveHarmonyConflicts() (src/lib/stigmergy/coordination.ts):
- flag off (default) → returns the existing static conflict list unchanged;
- flag on → conflicts are derived from the board via
detectConflicts()(aclaimand an opposingveto/failure/difficultyfrom a different agent on the same region), with zero LLM calls.
Enable it by setting NEXT_PUBLIC_STIGMERGY_COORDINATION=1 (client/view) or
STIGMERGY_COORDINATION=1 (server helpers).
npm run test:stigmergyRuns tests/stigmergy.test.ts on Node's built-in test runner (no new deps),
covering deposit/decay/read, evaporation, the SQLite-backed store, and
board-derived conflict detection with an injectable clock for deterministic
decay.
| Layer | Choice | Why |
|---|---|---|
| Framework | Next.js 16 (App Router, Turbopack) | Server Components, strong Supabase SSR integration, fast dev builds |
| Language | TypeScript (strict) | Type safety across the DB contract |
| Database / Auth | Supabase (Postgres + Auth + Realtime + Presence) | Required by the spec for realtime + presence |
| Styling | Tailwind CSS 4 | Consistent design system, zero CSS files |
| UI primitives | Radix UI + small local components | Accessible dropdowns, switches, checkboxes |
| Charts | Recharts | Covers every chart type in spec (line, area, scatter, bar, radial, heatmap table) |
| Validation | Zod | API payload validation |
| Icons | Lucide React | Consistent icon set |
metabocommand/
├── src/
│ ├── app/
│ │ ├── (dashboard)/ # auth-gated layout
│ │ │ ├── finance/ # Capital Reflex dashboard
│ │ │ │ ├── page.tsx
│ │ │ │ ├── pulse-agent-view.tsx
│ │ │ │ ├── oracle-agent-view.tsx
│ │ │ │ ├── sniper-agent-view.tsx
│ │ │ │ └── conductor-agent-view.tsx
│ │ │ ├── operations/ # placeholder
│ │ │ ├── approvals/ # Realtime + Presence + activity status
│ │ │ │ ├── page.tsx
│ │ │ │ ├── approval-queue.tsx
│ │ │ │ └── presence-bar.tsx
│ │ │ ├── agent-log/ # Realtime + Presence + filters
│ │ │ │ ├── page.tsx
│ │ │ │ ├── agent-log-view.tsx
│ │ │ │ └── log-presence-bar.tsx
│ │ │ ├── activity/ # Filters + CSV export
│ │ │ │ ├── page.tsx
│ │ │ │ └── activity-view.tsx
│ │ │ ├── settings/ # placeholder
│ │ │ ├── profile/ # read-only
│ │ │ └── layout.tsx # sidebar + auth guard
│ │ ├── api/approvals/
│ │ │ ├── submit/route.ts # create approval + Slack + log
│ │ │ └── decide/route.ts # approve/reject + Slack + activity + log
│ │ ├── login/ # email/password sign-in
│ │ ├── role-not-assigned/
│ │ ├── layout.tsx
│ │ └── page.tsx # role-based redirect
│ ├── components/
│ │ ├── ui/ # Button, Card, Badge, Switch, Input, CheckboxList
│ │ ├── sidebar.tsx
│ │ ├── kpi-card.tsx
│ │ └── placeholder-page.tsx
│ ├── lib/
│ │ ├── supabase/ # client / server / middleware / types
│ │ ├── slack.ts # webhook payload builder
│ │ ├── csv.ts # RFC-4180 CSV export
│ │ ├── dummy-data.ts # deterministic seeded chart data
│ │ └── utils.ts # cn, formatters, avatar helpers
│ └── middleware.ts # session refresh + auth redirect
├── supabase/migrations/
│ ├── 0001_schema.sql # tables, types, RLS, realtime
│ └── 0002_seed.sql # all seed records
├── docs/screenshots/ # README imagery
├── .env.example
└── README.md
- Node.js 20+ (tested on 24.14)
- A Supabase project (free tier is fine)
git clone https://github.com/icohangar-ops/metabocommand.git
cd metabocommand
npm installCopy .env.example to .env.local and fill in your Supabase credentials:
cp .env.example .env.localNEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
# Optional; can be configured later via SQL
SLACK_FINANCE_WEBHOOK_URL=
SLACK_OPERATIONS_WEBHOOK_URL=Open your Supabase Dashboard → SQL Editor → New query, paste the full contents of supabase/migrations/0001_schema.sql, and click Run.
This creates all tables, enum types, RLS policies, the handle_new_user trigger, and adds approval_items + agent_action_log to the supabase_realtime publication.
In Supabase → Authentication → Users → Add user, with Auto Confirm User checked:
| Role | |
|---|---|
| sarah.chen@metabo.io | finance |
| james.okafor@metabo.io | operations |
Then run this in the SQL Editor to set roles:
update public.profiles set role = 'finance', display_name = 'Sarah Chen' where email = 'sarah.chen@metabo.io';
update public.profiles set role = 'operations', display_name = 'James Okafor' where email = 'james.okafor@metabo.io';Paste and run supabase/migrations/0002_seed.sql in the SQL Editor. Expected counts after:
| Table | Row count |
|---|---|
agents |
12 |
approval_items |
14 (6 Finance + 8 Operations) |
agent_action_log |
22 (10 Finance + 12 Operations) |
activity_history |
14 (7 Finance + 7 Operations) |
update public.slack_settings set webhook_url = 'https://hooks.slack.com/services/...' where queue = 'finance';
update public.slack_settings set webhook_url = 'https://hooks.slack.com/services/...' where queue = 'operations';Without webhooks, approvals still work — Slack notifications are just skipped with slack_notified = false.
npm run devOpen http://localhost:3000 and sign in as Sarah or James.
- Sign in as Sarah in two browser tabs (or one regular + one incognito).
- Navigate both to
/approvals. - Hover an approval item in tab 1 — watch Sarah's badge turn blue ("Reviewing approval") in tab 2 within a second.
- Click Approve in tab 1 — the row updates in tab 2 instantly, badge turns green → grey as the action completes, and a toast appears.
- Close tab 1 — Sarah's presence entry disappears from tab 2 within a few seconds.
The same pattern works on /agent-log with its own activity statuses (Idle / Reviewing log / Filtering logs).
- RLS is enforced on every table. Finance-role users can only read and write Finance-scoped rows; Operations users only Operations.
profilesis readable by all authenticated users so Presence can display names and avatars. - Service role key is server-only, used for admin operations via
createServiceClient(). Never sent to the browser. - Anon key is safe to expose in the client — RLS does the gatekeeping.
- Approval actions validate the user's role matches the approval item's queue before allowing the state transition. Already-decided items cannot be re-decided (409 Conflict).
- Slack webhooks are stored in the database (not env) so they can be rotated without redeploy.
- Live Shopify / QuickBooks integrations — dummy data only per spec section 7
- Agent pause/resume persistence — the Active/Paused toggle is local-state only; a trivial follow-up to write to
agents.is_active - Automated test suite — Vitest for utilities + Playwright for the two-tab Realtime/Presence demo
- Sniper auto-execute logging to the server — currently UI-only; a follow-up endpoint would write to
agent_action_logas "Auto-Executed"
Full spec in MetaboCommand.md (maintained outside this repository). Sections implemented:
- §3.2 Authentication — login + role redirect
- §3.3 Global Navigation — role-aware sidebar
- §3.4.1 Dashboard Header + KPI bar
- §3.4.2 Pulse Agent
- §3.4.3 Oracle Agent
- §3.4.4 Sniper Agent
- §3.4.5 Conductor Agent
- §3.4.6 Finance Approval Queue (Realtime, Presence, activity status)
- §3.5.1 Operations Dashboard Header + KPI bar
- §3.5.2 Revenue Velocity panel (Acquisition, Conversion, Retention)
- §3.5.3 Inventory Intelligence panel (Demand Prophet, Logistics Conductor)
- §3.5.4 Customer Lifetime panel (Support Reflex, Advocacy)
- §3.5.5 Operational Health panel (Harmony)
- §3.5.6 Operations Approval Queue (shares Approval Queue component, RLS-scoped)
- §3.6 Agent Action Log (Realtime, Presence, filters, expandable rows)
- §3.7 Activity History Log (filters, CSV export, pagination)
- §3.8 Settings UI (Data Source cards, Threshold table, Slack config with Test Connection)
- §3.9 User Profile (read-only account, password change, notification preferences)
- §4.1 RBAC (enforced via RLS)
- §4.2 Approval workflow (auto-execute threshold + Slack)
- §4.3 Capital Velocity Score formula (displayed throughout)
- §4.4 Operating Mode (Growth / Efficiency toggle with confirmation + Realtime)
- §4.7 Seed data for queues + logs
- §4.8 Realtime subscription rules
- §4.9 Presence rules
- §4.10 Activity status rules
- §4.11 Activity History tracked types + seed
- §4.6 Agent pause persistence — UI-only currently; trivial follow-up
Start here: software-factory · Profile
| Finance | Strata · Metabocommand · meshcfo · working-capital-optimizer · cash-flow-optimizer · finance-cockpit | | Governance | consensus-hardening-protocol · agent-conductor · compliance-as-code-agent · cleanmandate |
Metabocommand routes agent proposals through role-scoped approval queues — the same human-in-the-loop pattern CHP locks and CleanMandate mandates enforce at the protocol layer.
MIT. See LICENSE.
This repository is hardened with the Consensus Hardening Protocol (CHP), Cubiczan's decision-governance layer for multi-agent AI systems.
- R0 Gate: All decisions must pass Solvable, Scoped, Valid, Worth_it checks
- Foundation Disclosure: 1-3 weakest assumptions, 1-2 invalidation conditions, 1 key vulnerability
- Adversarial Layer: Mandatory devil's advocate at Phase 0 and Round 3
- State Machine: EXPLORING → PROVISIONAL → PROVISIONAL_LOCK → LOCKED
- Third-Party Validation: Independent CONFIRM/REJECT before lock
- Category: Blockchain / DeFi
- Foundation Threshold: 85
- CFO Accuracy Guard: Disabled
| File | Purpose |
|---|---|
.chp/STATE_MACHINE.md |
Decision state transitions |
.chp/R0_CONFIG.yaml |
Domain-calibrated thresholds |
.chp/ADVERSARIAL_PROMPTS.md |
Standardized challenge templates |
.chp/CHP_COMPLIANCE.md |
Compliance tracking & audit trail |
cognitive-mesh-orchestrator 0.1.0 | Protocol Docs

















