Infrastructure for the Big 5 Agent Matrix (Hope, Dream, Vision, KNOLL, APEX) — a 14.3-quadrillion-parameter hierarchy over ephemeral 20,480-node matrices. Security-first, Colab-ready, strict modular governance with automated billing ledgers.
▶ Start here:
docs/MASTER_PLAN.md— the one document (vision, phases 1–8, founder actions, market-this-week). Founder quick-list (driving-friendly):docs/FOUNDER_ACTIONS.md·npm run plan.Live site: https://joeholloway445-maker.github.io/HDV_Foundation/ (auto-deployed to GitHub Pages on every push to
main).Prototype & marketing:
docs/PROTOTYPE.md· landing pagemarketing/index.html(npm run marketing) · waitlistmarketing/waitlist.html(npm run waitlist) ·docs/GTM.md·docs/LAUNCH_CHECKLIST.md·docs/MESSAGING.md· headline mathmarketing/math.md. Launch helpers:bash scripts/gh_launch.sh --status(un-private repo · protectmain).
Formerly titled Big 5 Matrix; this repository is the HDV Foundation.
A strict-separation-of-concerns agent hierarchy. Five "Big AI" agents cooperate, but
never talk to each other directly — every exchange is routed by APEX and audited
by KNOLL using a single, tamper-evident RoutingPacket contract.
Constitution: see
.cursorrules— the System Manifest. Its core rule: "Strictly enforce the RoutingPacket interface. If any data is passed between agents that does not strictly adhere to this interface, the system is considered compromised."Game plan & architecture: see
docs/GAME_PLAN.md(the authoritative full plan) anddocs/ARCHITECTURE.md(mermaid diagrams for packet flow, always-on vs ephemeral, the node matrix, and the HOPE voice loop).
The Primary Triad — HOPE, VISION, DREAM — holds absolute separation of duty: each owns exactly one duty at 100% and is forbidden the other two. Authority flows downward Hope → Vision → Dream; memory returns upward to Hope. KNOLL is the independent foundational enforcer and APEX is the orchestration layer (both outside the triad).
| Agent | Full name | Duty / Layer | Job | Hard constraint | Lifecycle |
|---|---|---|---|---|---|
| HOPE | Holloway's Own Providential Enterprise | 100% Governance | Rule-making, policy, direction; interpret intent (a governance function) | CANNOT execute or create | Always-on |
| VISION | Vectorized Infrastructure and Systems Ionic Operational Node | 100% Execution | Pipelines, processing, delivery (sandboxed) | CANNOT govern or create | Ephemeral |
| DREAM | Dynamic Renderer of Ephemeral Art Model | 100% Creation | Generative / UI / content | CANNOT govern or execute | Ephemeral |
| KNOLL | Kinetic Node of Operational Locks and Limiters | Foundation (Security) | Active health routing + virtual laws; 34% freeze | Independent entity; freeze + quarantine | Always-on |
| APEX | Automated Processor of Ephemeral eXchanges | Orchestration | Route tasks between agents (master router) | Every route MUST pass through KNOLL first | Always-on |
Operational rule: APEX is master router · KNOLL is master auditor + foundational enforcer ·
HOPE is the governance voice (interpreting intent is governance). DREAM and VISION cannot
communicate directly. Full audited constitution: docs/CONSTITUTION.md.
SOURCE agent ──▶ APEX.dispatch() ──▶ KNOLL.intercept() ──▶ (allowed?) ──▶ DESTINATION agent
│
└── (blocked) ──▶ SecurityAudit + ledger BLOCKED
No peer agent module imports another peer agent module. Agents only receive an APEX
transport (the router, or a sendViaApex callback) via dependency injection.
- Under each of the 5 Big AI: 4,096 nodes = 64 sub-AI managers × 64 nodes each.
- Total across the Big 5: 20,480 nodes.
- Each node hosts 100 ephemeral personas (spawn → execute → terminate).
- Each persona is tied to a conceptual 7B model → ~14.3 quadrillion parameters.
- Always-on standby: HOPE, KNOLL, APEX. Ephemeral: DREAM, VISION (+ their matrices).
20,480 nodes × 100 personas × 7,000,000,000 params ≈ 1.4336 × 10^16 ≈ 14.3 quadrillion
big5-matrix/
├── apex/ Orchestrator & routing (router, ledger, packet, orchestrator, dispatchAsync)
├── hope/ Intent interpreter + documenter (IntentArchive) + voice
├── dream/ Multi-branch simulation engine (outcome trees, ranking) + scheduler
├── vision/ Sandboxed tool library (tools registry + sandbox sessions + reports)
├── knoll/ Security guardrails: 6 virtual laws + behavioral scoring (scoring/features)
├── nodes/ 20,480-node topology + lifecycle + persona pipeline + parameter accounting
├── gateway/ Phase 4 HOPE HTTP API (node:http): server + CLI (no framework)
├── mcp/ MCP tool provider (stdio): HDV as tools for external agents/IDEs (see docs/MCP.md)
├── persistence/ Repository interfaces + in-memory impls + Prisma impls + factory + Redis stub + Kafka-like queue
├── colab/ Notebooks for GPU processing & persona spawning (ML lab only) + worker protocol
├── config/ routing_schema.ts, matrix.json, filters.json, schema.prisma
├── personamatrix/ Python: persona loop + billing ledger + scoring twin + parameter twin
├── demo/ TypeScript end-to-end demos (Phase 1 + Phase 2/3 + Phase 4)
├── docs/ GAME_PLAN.md + ARCHITECTURE.md (mermaid diagrams)
├── tests/ Automated tests (backbone + phase2 + phase3 + phase4)
├── package.json
├── tsconfig.json
├── README.md
├── .cursorrules System Manifest / Constitution
└── .gitignore
Current release: v0.9.0 — Phases 5–8 foundations are implemented in-repo and offline-tested
(routing, security, metering, gateway, SDK, learned scorer, marketplace, hash-chain), with live
GPU/Kafka/K8s remaining an ops task. Every release is additive: the Phase 1 backbone and the
Phase 2/3 capabilities are unchanged and still enforced. See CHANGELOG.md
for the full v0.1 → v0.9 history, docs/PHASES_5_8_STATUS.md for
the honest real-vs-stub ledger, and docs/GAME_PLAN.md for the
authoritative plan. The Phase-by-phase table below documents the Phase 1 → Phase 4 backbone.
| Area | Phase 1 | Phase 2/3 | Phase 4 (v0.3.0) |
|---|---|---|---|
| RoutingPacket contract | ✅ Enforced | ✅ Unchanged (SHA-256 hash + knoll_token) | ✅ Unchanged (only inter-agent contract) |
| APEX router | ✅ dispatch |
✅ dispatchAsync + ApexOrchestrator composition root |
✅ + optional async queue intake (same KNOLL gate) |
| APEX billing ledger | ✅ In-memory | ✅ Optional repository mirror (RequestLog) | ✅ Unchanged; surfaced read-only via gateway /v1/ledger |
| KNOLL laws + behavioral scoring | ✅ / — | ✅ Additive anomaly gate (BEHAVIORAL_SCORE) |
✅ Unchanged (gates sync + async + gateway paths) |
| HOPE interpreter/document/voice | ✅ Basic | ✅ Entities/goals/urgency, clarify, voice | ✅ + HTTP gateway (gateway/) forward-facing |
| DREAM simulation + scheduler | ✅ Flat | ✅ Multi-branch trees + Pareto + scheduler | ✅ Unchanged; also backs ephemeral Colab workers |
| VISION execution | ✅ Stub | ✅ Tool registry + sandbox + billable report | ✅ + Phase 4.2: http_fetch/json_transform tools, per-session resource monitor + tool audit, concurrent-session limit, timeout kill |
| Node matrix | ✅ Definitions | ✅ SubManager + fleet lifecycle + pipeline | ✅ + parameter accounting (nodes/parameters.ts) |
| personamatrix (Python) | ✅ Persona loop | ✅ + behavioral scoring twin | ✅ + parameter twin (personamatrix/parameters.py) |
| Colab lab | ✅ 01/02 | ✅ + 03 (scoring) + 04 (ipywidgets) | ✅ + 05 horizontal worker + worker_protocol.py |
| Real-time queue | — | ✅ Kafka-like partitioned queue + consumer groups | |
| Docker/gVisor sandbox internals | |||
| Prisma runtime persistence | ✅ Prisma/Postgres backend via createRepositories('prisma') (in-memory still default) |
||
| Real 7B inference / real GPU |
Phase 4.2 — VISION sandbox expansion. The VISION tool library gains a hermetic
http_fetch(allowlisted domains only, returns deterministic mocks — no real network) and a safejson_transform(pure path extract/map, nevereval, prototype-pollution safe). The sandbox is hardened with a per-session resource monitor (CPU-seconds, peak memory, timeout accounting) plus a tool-invocation audit trail, a concurrent-session limit (SandboxManager), and timeout kill (a run over its wall-clock limit is force-killed with exit 124 and the session is stopped). None of this weakens the constitution: VISION still cannot create or govern, and results return to HOPE via APEX only. Seenpm run demo:vision.
- Node.js ≥ 20 (developed on Node 22)
- Python ≥ 3.10 (standard library only;
ipywidgetsoptional forcolab/04)
git clone https://github.com/joeholloway445-maker/HDV_Foundation.git
cd HDV_Foundation
npm install
npm run prototype # boots + live-verifies the whole stack over HTTP, then prints every URL/file to opennpm run prototype installs deps if needed, typechecks, runs a fast smoke, starts the HOPE
gateway on :8787, curls the marquee endpoints (health · intent · pricing · waitlist · metrics),
and prints the marketing page, waitlist, showcase, and MCP paths you can open next. Ctrl+C
stops the gateway; add --ci (./scripts/prototype.sh --ci) to boot-verify-and-exit. Full
honest timeline: docs/PROTOTYPE.md. Version history:
CHANGELOG.md.
Then open the marketing funnel (static, no build step):
npm run marketing # prints how to open marketing/index.html (landing page)
npm run waitlist # prints how to open marketing/waitlist.html (waitlist form)
npm run showcase # prints how to open showcase/index.html (architecture/product showcase)npm install # from the repository rootnpm run prototype # ONE command: boot + live-verify the whole prototype over HTTP (Ctrl+C to stop)
npm run smoke # fast programmatic smoke of every gateway handler (no port bound)
npm run eval:board # public eval board — 5 headline metrics vs the real APEX→KNOLL gate (GATE must PASS)
npm run marketing # print how to open the static marketing landing page
npm run waitlist # print how to open the static waitlist page
npm run showcase # print how to open the static architecture/product showcase
npm run typecheck # tsc --noEmit — MUST be zero errors
npm run demo # Phase 1: routing + KNOLL block + tampered-hash demo
npm run demo:phase2 # Phase 2/3: HOPE docs, DREAM trees, VISION tools, KNOLL scoring
npm run demo:phase4 # Phase 4: queue intake · worker re-ingestion · params · health
npm run demo:vision # Phase 4.2: VISION tools · http_fetch stub · timeout kill · session limits · audit
npm run demo:hope-ui # HOPE console: interpret + document + voice, renders standalone HTML
npm run demo:dream-energy # Phase 4.2: energy-driven DREAM scheduling (accumulate/decay)
npm run demo:metrics # Phase 5: observability metrics · trace ring buffer · Prometheus text
npm run demo:billing # PRODUCT metering: pricing · estimate · live meter · hard-cap · BYOK $0
npm run gateway # start HOPE HTTP gateway on PORT (default 8787)
npm run mcp # start the MCP tool provider on stdio (for Cursor/other MCP clients)
npm run test:mcp # MCP tool-provider tests
npm test # all tests (backbone + phase2 + phase3 + phase4)
npm run python:demo # persona loop + billing ledger (python3)
npm run python:scoring # behavioral scoring twin validation (python3)
npm run python:worker # ephemeral DREAM/VISION Colab worker simulation (python3)
npm run python:gpu-hook # detect GPU + run stub, attempt real 7B if installed (python3)
npm run python:test-backend# model backend seam tests (stub always; transformers if present)
npm run db:generate # prisma generate (client from config/schema.prisma)
npm run db:push # create/sync Postgres tables from config/schema.prismaEvery push to main / feature branches (cursor/**, feature/**, feat/**) and every PR
to main runs /.github/workflows/ci.yml. Any failure fails
the workflow.
| Job | Runtime | Steps |
|---|---|---|
| node | Node 22 (matrix) | npm ci → npm run db:generate (Prisma client) → npm run typecheck → npm test → npm run eval:board (quality gate — must PASS) → npm run smoke |
| python | Python 3.12 (matrix) | personamatrix/demo.py → personamatrix/test_model_backend.py → colab/03_behavioral_scoring.py |
Reproduce the CI gates locally:
npm run ci # db:generate + typecheck + test + eval:board + smoke (Node backbone)
npm run ci:python # personamatrix demo + backend tests + behavioral scoring (Python)An optional /.github/workflows/release.yml fires only on a
pushed v* tag: it re-runs npm run ci on the tagged commit, then creates a GitHub Release
only if one does not already exist for that tag (idempotent — re-pushing a tag never clobbers
an existing release). See CHANGELOG.md for release notes.
A lightweight /.github/workflows/security.yml adds a
PR-only dependency review (blocks new high-severity vulnerabilities) plus a non-blocking
npm audit (advisory, continue-on-error).
/.github/workflows/pages.yml publishes the static
marketing site on every push to main (also runnable via workflow_dispatch). It builds a
bundle with actions/upload-pages-artifact
and deploys with actions/deploy-pages:
| Source | Served at |
|---|---|
marketing/ (incl. index.html, waitlist.html, 404.html) |
site root /HDV_Foundation/ |
showcase/ |
/HDV_Foundation/showcase/ |
hope/app/ |
/HDV_Foundation/hope/app/ |
The published URL follows the project-pages pattern
https://joeholloway445-maker.github.io/HDV_Foundation/. This workflow is independent of
the CI gates above — it only builds and uploads static HTML, so it never blocks (or is blocked
by) typecheck/test jobs. Enable Pages once under Settings → Pages → Source: GitHub Actions.
The backbone runs fully in-memory by default (createRepositories('memory')), so no
database is required for npm test, the demos, or the gateway. A durable Prisma/Postgres
backend is available behind the same repository interfaces via createRepositories('prisma')
(write-through cache: synchronous reads from an in-memory projection, async persistence to
Postgres — call hydrate()/flush()/close() to control the lifecycle).
To use it locally:
cp .env.example .env # sets DATABASE_URL + REDIS_URL
docker compose up -d # starts postgres:16 (+ redis:7) with healthchecks
npm run db:generate # generate the Prisma client
npm run db:push # create tables from config/schema.prisma
npm test # persistence_prisma tests now run against PostgresWithout DATABASE_URL, the Prisma-backed tests in tests/persistence_prisma.test.ts
skip gracefully while the in-memory tests still run. Prisma files live only in the
persistence layer: persistence/prisma_repos.ts (implementations), persistence/factory.ts
(createRepositories), and config/schema.prisma (source of truth).
Phase 4 gives HOPE a forward-facing HTTP presence and lays the fleet-scaling foundations:
npm run gateway # binds PORT env or 8787
PORT=9090 npm run gateway # custom portEndpoints (all JSON; every routed packet is still gated by KNOLL — the gateway never bypasses APEX):
| Method | Path | Purpose |
|---|---|---|
| POST | /v1/intent |
{ "utterance" } → HOPE interpret + document + submit via APEX |
| GET | /v1/health |
Always-on (HOPE/KNOLL/APEX) + ephemeral Dream/Vision idle flags |
| GET | /v1/ledger |
Recent APEX billing entries (read-only) |
| GET | /v1/audit |
Recent KNOLL verdicts (read-only) |
| GET | /v1/matrix/stats |
Node/persona topology + 14.3Q parameter accounting |
| GET | /v1/metrics |
Observability snapshot (JSON; ?format=prometheus for text) |
Example:
curl -s localhost:8787/v1/intent -H 'content-type: application/json' \
-d '{"utterance":"simulate three outcomes for launching the product early"}'
curl -s localhost:8787/v1/healthThe gateway front door adds optional auth, per-IP rate limiting, CORS, and request logging without touching HOPE/APEX/KNOLL — every routed packet is still KNOLL-gated. All of it is env-configurable:
| Env var | Default | Effect |
|---|---|---|
HDV_API_KEY |
unset | Require X-HDV-Key: <key> or Authorization: Bearer <key>. Unset ⇒ dev mode (auth off). |
HDV_RATE_LIMIT |
60 |
Max requests per minute per client IP before 429. |
HDV_CORS_ORIGIN |
* |
Value for Access-Control-Allow-Origin (preflight OPTIONS → 204). |
/v1/health is always public (auth- and rate-limit-exempt) so liveness/readiness probes
keep working regardless of key config or traffic bursts. Rate-limited responses include
Retry-After and X-RateLimit-* headers; the request logger records method/path/status/
duration/IP and never logs the key.
# Enabled auth + tighter limit; health still open, protected routes need the key:
HDV_API_KEY=s3cret HDV_RATE_LIMIT=120 npm run gateway
curl -s localhost:8787/v1/health # 200 (public)
curl -s localhost:8787/v1/matrix/stats # 401 (no key)
curl -s localhost:8787/v1/matrix/stats -H 'X-HDV-Key: s3cret' # 200
npm run demo:gateway-auth # scripted 401 → 200 → 429 + public-health walkthrough
npm run test:gateway-auth # gateway hardening testsA strictly out-of-band metering layer. It plugs into a new read-only dispatch-observer
seam on the APEX router (ApexRouterOptions.observer / ApexOrchestratorOptions.observer) and
only meters what already happened — it never routes, gates, mutates a packet, or influences
a KNOLL verdict, so the constitution's separation of concerns is preserved. The observer is
optional: unset, APEX behaves byte-for-byte as before; a throwing observer can never break
routing.
MetricsCollector— counters (packets routed / blocked / failed), a simple latency histogram, KNOLL deny reasons (keyed by enforced-constraint for bounded cardinality), per-destination counts, an active-personas estimate, and total billed cost. Emits a JSONsnapshot()or a Prometheus-ishtoPrometheus()exposition.PacketTracer— a bounded in-memory ring buffer of trace spans (packetId · source · dest · durationMs · verdict); oldest spans roll off. No payload contents are retained.- The gateway wires both into the orchestrator it builds and serves them at
GET /v1/metrics(JSON by default,?format=prometheusfor text). It covers APEX's internal DREAM/VISION forwards too, since metering happens at the router.
npm run demo:metrics # legal + blocked traffic → JSON snapshot · Prometheus · trace spans
npm run test:observability # observability unit + gateway integration tests
curl -s localhost:8787/v1/metrics # JSON snapshot
curl -s 'localhost:8787/v1/metrics?format=prometheus' # Prometheus-ish textOther Phase 4 pieces: a Kafka-like partitioned task queue (persistence/kafka_stub.ts,
optional async intake in ApexOrchestrator), parameter accounting (nodes/parameters.ts
personamatrix/parameters.py), and the horizontal Colab worker protocol (colab/worker_protocol.py+colab/05_horizontal_worker.py). Only HOPE/KNOLL/APEX need standby; DREAM/VISION workers are ephemeral and self-terminating.
A small forward-facing console that presents HOPE as the system's voice. It wraps HOPE's
existing stack — IntentInterpreter (parse), HopeDocumenter (record), HopeVoice (speak) —
and keeps a turn-by-turn transcript.
HopeConsole.say(utterance)interprets, documents, and replies in HOPE's voice.- Interpretation-only by default. With no transport injected the console routes nothing.
Pass a
sendViaApexcallback to let confident intents be submitted HOPE → APEX (APEX, after KNOLL, still decides). HOPE never executes or creates, and never addresses a peer. renderTranscriptToHtml(transcript)emits one self-contained, brand-forward HTML page (inline CSS, Google-Fonts typography, atmospheric gradient, subtle brand-breathe + fade-in motions). User content is HTML-escaped.
npm run demo:hope-ui # writes /tmp/hope-console.html
HOPE_CONSOLE_OUT=demo/out/hope-console.html npm run demo:hope-ui # custom output pathThen open the written HTML file in a browser. Tests: node --import tsx --test tests/hope_ui.test.ts.
The persona loop is backend-agnostic via a pluggable inference seam
(personamatrix/model_backend.py). By default every persona runs the deterministic,
dependency-free StubBackend (unchanged historical behavior). On a GPU Colab runtime you
can flip one env var and the same loop drives a real 7B-class model through
transformers — routing, security, ledger, and topology are untouched.
python3 colab/06_gpu_model_hooks.py # or: npm run python:gpu-hook
python3 personamatrix/test_model_backend.py # or: npm run python:test-backendBackend selection (factory reads these, defaults shown):
| Env var | Values | Default |
|---|---|---|
PERSONAMATRIX_BACKEND |
stub | transformers |
stub |
PERSONAMATRIX_MODEL_ID |
any Hugging Face id | mistralai/Mistral-7B-Instruct-v0.2 |
Enable the real path in a Colab GPU runtime (Runtime → Change runtime type → GPU):
!pip install transformers accelerate torch
import os
os.environ["PERSONAMATRIX_BACKEND"] = "transformers"
os.environ["PERSONAMATRIX_MODEL_ID"] = "mistralai/Mistral-7B-Instruct-v0.2"Off-GPU (or without the deps installed) the transformers path skips gracefully with
install instructions and only the StubBackend runs, so all Python demos and tests still
pass with the standard library alone. colab/06_gpu_model_hooks.py detects CUDA, prints
device info, always runs the stub, and attempts the real 7B model only when both the deps
and a GPU are present.
- HOPE parses a natural-language request into a structured intent.
- APEX wraps it in a
RoutingPacket, calls KNOLL, and (if allowed) routes to DREAM. - DREAM simulates outcomes; results return via APEX (never directly).
- The APEX ledger records
cost_usdfor the ephemeral execution. - KNOLL blocks an illegal direct
DREAM → VISIONpacket. - KNOLL blocks a packet with a tampered SHA-256 hash.
- HOPE interprets + documents an intent (entities/goals/constraints/urgency) and speaks.
- APEX orchestrates it to DREAM; a ranked outcome tree returns via APEX.
- APEX orchestrates a task to VISION's sandboxed tool registry; a billable report returns.
- A low-confidence utterance triggers a clarification (no dispatch).
- The DREAM scheduler schedules a speculative sim on a stream
ENERGY_SPIKE(via APEX). - KNOLL blocks an illegal direct
DREAM → VISIONpacket. - KNOLL blocks a high behavioral-anomaly packet (
BEHAVIORAL_SCORE, additive to the laws). - Persistence repositories mirror the ledger + audit + intent-archive rows.
- Parameter accounting — the ~14.3 quadrillion figure computed (not asserted), with a per-agent breakdown and an ACTIVE snapshot (idle personas draw ~zero compute).
- Async intake — an intent is published to a partitioned, consumer-group task queue and drained by a consumer that dispatches it through the same KNOLL gate.
- Worker re-ingestion — a simulated ephemeral DREAM worker's result is re-ingested via
APEX (
DREAM → HOPE, legal), and an illegalDREAM → VISIONroute is BLOCKED. - Health snapshot — always-on (HOPE/KNOLL/APEX) vs ephemeral (DREAM/VISION) status.
dream/energy.ts adds a StreamEnergyMeter that folds a stream of events
(USER_REQUEST, ENERGY_SPIKE, CHAT_BURST, ANOMALY_NEAR_MISS, IDLE_TICK) into a
single decaying "attention energy" scalar — busy streams heat up, quiet streams cool off
(exponential half-life decay). The DreamScheduler now reads that accumulated energy to
decide when to simulate and how wide/deep (breadth / depth / priority): a single spike
still triggers immediately, while sustained chatter or repeated near-misses can accumulate
past a threshold and schedule on their own — and idle speculation is deferred while the
stream is still warm. dream/scenario_bank.ts provides optional seeded scenario
templates DREAM can specialize into concrete intents (simulation only — no governance,
no execution). Scheduling still goes APEX → DREAM only; DREAM is never reached directly.
Run npm run demo:dream-energy; tests live in tests/dream_energy.test.ts
(npm run test:dream-energy).
The PRODUCT metering layer turns raw APEX usage into a customer-facing allowance: a
parameter-usage budget with clear cost + occurrence metrics, per tenant, per plan tier.
Where the APEX ledger records what the system spent, billing/ prices it for a customer.
It only prices and accounts — it never routes, gates, executes, or interprets, so the
constitution holds. The meter plugs into the same read-only dispatch-observer seam as
observability, so it can never influence a KNOLL verdict or a route.
- Metering unit: active-parameter-seconds. Idle personas draw ~zero compute, so you pay
only for the parameters you light up, for as long as they run:
cost = pricePerRequest + (activeParams × durationSec / 1e6) × rate. One persona = 7B params. - Plan tiers (
FREE · STARTER · PRO · ENTERPRISE · BYOK), rates, included allowance, hard caps, and overage rates live inconfig/pricing.json— edit the table, no code change. Usage within your included allowance bills at the standard rate; beyond it, at the overage rate. - Allowances (
billing/allowance.ts) are per-tenant, in-memory (offlinedemotenant seeded).consume()rejects work that would breach the hard cap (logged, never billed); BYOK is unlimited with a $0 platform fee (pass-through — you pay only your provider). - MeterService (
billing/meter.ts) attributes live APEX dispatch to a tenant using the active-persona estimate × model params when available, else the ledgercost_usd.
Gateway routes (auth-aware; tenant via the X-HDV-Tenant header, default demo):
GET /v1/billing/pricing # public marketing pricing table (no key required)
GET /v1/billing/usage # balance · spend · recent occurrences (X-HDV-Tenant)
GET /v1/billing/estimate # { activeParams, durationSec, model? } (body or query) → cost + per-tier
POST /v1/billing/allowance # set/adjust allowance { tier?, includedAllowanceUsd?, hardCapUsd? }Run npm run demo:billing (pricing → estimate → live metering → hard-cap block → BYOK $0);
tests live in tests/billing.test.ts (npm run test:billing).
MIT — see LICENSE.