cloud

package module
v1.801.245 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 81 Imported by: 0

README

Hanzo Cloud

Hanzo Cloud

The Open AI Cloud as one Go binary. Identity, secrets, data, AI, gateway, observability, and the console — every Hanzo-native subsystem mounted into a single multi-org process. Per HIP-0106.

Status License

The same artifact serves api.hanzo.ai, api.lux.cloud, api.zoo.cloud, api.osage.cloud, and every white-label reseller. Brand, enabled subsystems, and org scope are deployment configuration — one binary, one origin, no sidecars.

Quick start

# Run the unified binary (pin a released version)
docker run -p 8080:8080 ghcr.io/hanzoai/cloud:v1.801.206

# Or install the CLI + server
go install github.com/hanzoai/cloud/cmd/hanzo@latest
brew install hanzoai/tap/hanzo

Open http://localhost:8080 for the embedded console; the API is served under /v1 on the same origin.

What this is

hanzoai/cloud is one Go binary that mounts every Hanzo subsystem (iam, kms, base, gateway, ai, commerce, vfs, mq, dns, amqp, mcp, o11y, tasks, …) into a single multi-org process. The same artifact serves api.hanzo.ai, api.osage.cloud, api.lux.cloud, api.zoo.cloud, and every white-label reseller. Brand, enabled subsystems, and org scope are deployment configuration.

hanzo — cloud control CLI

The same binary is also a gcloud/doctl-class CLI. The first token selects the mode:

  • hanzo <subsystem>server mode: serve a subsystem (hanzo iam, hanzo cloud, …).
  • hanzo <verb>client mode: control the live estate. A thin client over Hanzo IAM (hanzo.id), the platform control plane (platform.hanzo.ai/v1), and the cloud /v1 API — it invents no parallel API.
hanzo login                       # IAM password grant against hanzo.id → token in ~/.hanzo (0600)
hanzo whoami                      # identity from the stored token (--verify hits IAM userinfo)
hanzo apps list                   # platform apps board: declared/running/latest tag + drift + health
hanzo apps get <org>/<app>/<env>  # one app row
hanzo deploy <container> --project <p> --env <e>   # rolling, zero-downtime redeploy
hanzo clusters list|get|create|select|target       # dedicated DOKS cluster lifecycle
hanzo build <repo> --sha <sha> --image <img>       # platform-native (arcd/Kaniko) build, no GitHub builders
hanzo k8s target                  # the org's resolved deploy target (kubeconfig never returned)
hanzo config set <k> <v>          # ~/.hanzo/config preferences

Global flags: --org, -o/--output table|json, --platform-url, --iam-issuer, --platform-token. Tokens resolve from flag → env → ~/.hanzo (never hardcoded): the IAM user token is the identity; the platform control plane is service-token authed (it cannot validate user tokens), so apps/deploy/clusters use --platform-token / HANZO_PLATFORM_TOKEN / PLATFORM_SERVICE_TOKEN, and build uses HANZO_BUILD_TOKEN / PLATFORM_BUILD_CALLBACK_TOKEN.

Install: go install github.com/hanzoai/cloud/cmd/hanzo@latest, or brew install hanzoai/tap/hanzo.

Subsystems mounted

Each subsystem exposes func Mount(app *zip.App, deps cloud.Deps) error and wires its own /v1/<name>/* routes onto the shared app.

  • iam — identity & access (users, orgs, roles, OIDC/JWKS per HIP-0026)
  • base — per-org SQLite + in-process extension runtimes (HIP-0105)
  • kms — secret custody (sealed secrets, HIP-0027)
  • commerce — checkout, billing, pricing, invoicing (light router; NOT in PCI-DSS scope)
  • ai — AI control plane: inference, RAG, model hub, agents, MCP management
  • gateway — HTTP routing + policy
  • o11y — metrics / traces / logs
  • vfs — virtual filesystem / object-store abstraction
  • mq — message queue
  • dns, amqp, mcp, auto, tasks, … — full list per HIP-0106

Deployment modes

Same binary; different startup configuration:

cloud --enable=iam,base,kms,commerce,ai,gateway,o11y --brand=hanzo  --domain=hanzo.ai
cloud --enable=iam,base,kms,commerce,ai,gateway,o11y --brand=osage  --domain=osage.cloud
cloud --enable=iam,base,kms,commerce,ai,gateway,o11y --brand=lux    --domain=lux.cloud
cloud --enable=iam,base,kms,commerce,ai,gateway,o11y --brand=zoo    --domain=zoo.cloud

Architecture

                 api.{org}.{brand}
                          |
                   hanzoai/cloud (one Go binary)
                          |
   +----------+----------+----------+----------+----------+
   |    iam   |   base   |   kms    |    ai    | gateway  | ...
   |  Mount() |  Mount() |  Mount() |  Mount() |  Mount() |
   +----------+----------+----------+----------+----------+
   per-org SQLite (HIP-0302)   |   Hanzo IAM JWKS (HIP-0026)
   replicate -> S3 (HIP-0107)  |   ZAP inter-subsystem RPC

Every subsystem mounts through the same Mount(app, deps) seam. Cross-subsystem calls ride a narrow in-process interface; no subsystem reaches into another's store.

White-label fork pattern

Customers fork hanzoai/cloud to launch their own ecosystem in one binary. Brand detection, enabled subsystems, and ZAP endpoints (payments / vault backends) are all deployment configuration.

Web framework

hanzoai/zip — Sinatra-style Go web framework built on Fiber v3. The ONE Go web framework. No .Fast escape hatch.

Console UI — embedded in the ONE binary

The same hanzoai/cloud binary serves the console (@hanzo/gui) UI at the web root AND the /v1 API from one process — one artifact, one origin, no separate console Service. The UI is compiled in via //go:embed (see webui.go).

Pipeline (in the Dockerfile, before go build):

console stage  →  build console static bundle  →  /out
      COPY --from=console /out/ → src/webui/dist/     (overlays the fallback shell)
build stage    →  go build   →  //go:embed all:webui/dist bakes it into /cloud

Serving (webui.go, registered LAST in Serve so it never shadows the API):

  • GET / and any client-side route (/orgs, /models, …) → the SPA shell (index.html) with Cache-Control: no-cache; fingerprinted assets under assets//_next/ are served immutable for a year, with brotli/gzip precompressed negotiation when the build emits .br/.gz siblings.
  • GET /v1/* (and /zap, /healthz, …) → the API. Real subsystem routes are registered before the console catch-all, so they always win; an unmatched path under an API prefix returns a real 404 (JSON namespace), never HTML.
  • Same-origin: the embedded console calls /v1 on its own host, so the session cookie is first-party — no second origin, no CORS.

webui/dist/index.html is a committed fallback shell (a real same-origin /v1 bootstrap) so go build always compiles and the binary always serves a UI even without the Node toolchain. The image build overwrites webui/dist with the real console bundle. See webui_test.go for the boot-and-assert tests (/ → shell, deep link → shell 200, /v1/* → API, unmatched /v1 → 404).

The hanzoai/console build:embed script (scripts/build-embed.mjs) stashes its Next server route handlers (BFF proxies that collapse to the cloud /v1/* the SPA calls same-origin), wraps the client catch-all pages for output: 'export', neutralizes the root layout's request-time headers() read, and emits a real static export at out/ (a ~360 KB index.html + _next/ chunks). The image build (and make webui) run it and overlay webui/dist, so //go:embed bakes the FULL @hanzo/gui console into the ONE binary. The Dockerfile console stage FAILS HARD if that bundle is missing or degenerate — the placeholder shell can never silently ship to prod (escape hatch: --build-arg ALLOW_PLACEHOLDER=1 for a pure-Go dev image).

Specs

Implements:

  • HIP-0014 Application Deployment
  • HIP-0026 IAM
  • HIP-0027 KMS
  • HIP-0037 AI Cloud Platform
  • HIP-0105 In-Process Extension Runtime
  • HIP-0106 Unified Cloud Binary
  • HIP-0129 Open Cloud Planes
  • HIP-0302 Encrypted SQLite + ZapDB Durability

Status

In production. The unified binary serves api.hanzo.ai and the white-label cloud surfaces today, with per-org SQLite (HIP-0302) and the embedded console. Subsystems continue to land per HIP-0106's migration phases; apps/apps.go:Wire() is the one ordered list of everything mounted. For repo-level engineering doctrine (module graph, route-table projections, cross-subsystem seams), see LLM.md.

Hanzo — the Open AI Cloud

Open source · every language · on-chain settlement. hanzo.ai · docs.hanzo.ai

SDKs in every languagePython (flagship) · TypeScript · Go · Rust · C++ · Swift · Kotlin · umbrella

Documentation

Overview

Package cloud is the unified Hanzo Cloud binary per HIP-0106.

One Go binary mounts every Hanzo-native subsystem (iam, base, kms, commerce, ai, gateway, o11y, vfs, mq, dns, amqp, mcp, ...) via the canonical Mount(app cloud.Router, deps cloud.Deps) error contract. Brand, enabled subsystems, and org scope are deployment configuration; the binary is the same artifact across every white-label deployment.

Per HIP-0106 — github.com/hanzoai/HIPs/blob/main/HIPs/hip-0106-unified-hanzo-cloud-binary.md.

Index

Constants

View Source
const (
	ReasonUnpaid     = "unpaid"
	ReasonUnresolved = "unresolved"
)

The two reasons a 402 can carry, spelled once for every gate. They are DISTINCT codes because the caller's cure is different: an unpaid caller must buy something, an unresolved one must retry.

View Source
const AIMeterProvider = "ai"

AIMeterProvider is the commerce provider/service label every inference debit carries, so LLM spend is attributable and the per-scope + account caps sum over (project, "ai"). It is exported so any OTHER inference path that does not run through this wrapper — a BYO model invoked with the org's own provider token (e.g. Cloudflare Workers AI) — debits the SAME product axis and shares the same per-scope caps, rather than inventing a parallel usage label.

View Source
const DefaultBrand = "hanzo"

DefaultBrand is the fallback brand when CLOUD_BRAND is unknown.

View Source
const DefaultModel = "enso-flash"

DefaultModel is the model a Hanzo agent runs on when the caller names none.

It is the FLASH tier on purpose, and pinned rather than left to the router.

The bare `enso` alias does not mean "resolve to the cheapest adequate tier" — its route opens on an Opus-class arm (zen catalog-enso.yaml, route[0]) and bills $4/$20 per Mtok, against enso-flash at $2/$4 and the upstream base at $0.14/$0.28. Defaulting every agent to the bare alias was a 28.6x input / 71.4x output increase on work that mostly wants a fast first response, so the default names the tier it actually wants. A caller who needs more pins enso-pro or enso-ultra; a caller who wants the router's judgement pins `enso`.

This constant is the only literal. The deployment knob (CLOUD_AI_DEFAULT_MODEL, read into Config.AIDefaultModel) defaults to it, every subsystem reads that, and nothing hardcodes a model name of its own. Changing the tier is this line plus the same value in the deployment's env — never a third place.

View Source
const DefaultResourceFeeCents int64 = 100

DefaultResourceFeeCents is the fallback flat provision/create fee (in cents) when no operator override is set — $1.00, so "every service costs money" holds out of the box. It is a configurable POLICY default, not a fabricated market price: ops sets the real number per deployment/kind via ResourceFeeCents's env knobs. Set a kind to 0 to make it free (and therefore un-gated, mirroring the edge gate's price==0 pass-through).

View Source
const PublishablePrefix = "pk-"

PublishablePrefix is the ONE publishable spelling: pk- is the key you may ship in a browser bundle, sk- is the one you may not. Stripe's split, same reason.

View Source
const SwitchPaywallEnforced = "paywall_enforced"

SwitchPaywallEnforced gates the subscription paywall. The key lives here so the registry entry (clients/entitlements), the evaluator (clients/flags) and the edge (serve.go) all name the same string — a switch whose readers disagree about its key is worse than no switch.

View Source
const SwitchPaywallStrict = "paywall_strict"

SwitchPaywallStrict is the posture on an UNRESOLVABLE standing. OFF (the default) = availability: an authority we cannot reach never refuses a customer. ON = revenue: an unresolvable standing refuses. It lives beside its sibling for the same reason — SpendGate (this package) and RequireProduct (clients/ entitlements, which also REGISTERS it) must name one string.

View Source
const TracerName = "hanzo-cloud"

TracerName is the instrumentation scope for cloud's HTTP request spans. It is resolved off the GLOBAL tracer provider — the ZAP provider installed once by the composition root (cmd/cloud initTelemetry) — so a request span ships over the SAME ZAP wire to hanzoai/datastore as every log and GenAI span. One transport, one provider.

Variables

View Source
var APIKeyPrefixes = []string{"pk-", "sk-", "hk-"}

APIKeyPrefixes are the Hanzo API key families. A published key (pk-) is write-only and scoped, so it is safe in a public bundle; a secret key (sk-) authenticates a server. Everything else is OAuth2, which is a JWT and not a key.

hk- is sk- under an older name and is on its way out. It stays accepted here because IAM mints it — cloud only validates (see account.go mintKey, which delegates to iam.mintUserKey) — so dropping it here before IAM renames the family would reject every key IAM hands out. Retire it in that order: IAM mints sk-, holders re-key, then delete the entry below.

fw_ and hz_ were listed here and never minted by anything: dead entries that widened what counts as a credential for no reason. Gone.

This is the ONE authority. Admission mirrors it rather than importing it (it stays free of cloud-internal imports); if this list changes, that copy must too.

View Source
var ErrGitImporterUnavailable = errors.New("cloud: git importer not registered")

ErrGitImporterUnavailable is returned when the git object plane is not mounted (no importer registered) — a fail-closed sentinel, never a silent success.

View Source
var ErrGitMirrorControllerUnavailable = errors.New("cloud: git mirror controller not registered")

ErrGitMirrorControllerUnavailable is returned when the git object plane is not mounted — fail-closed, never a silent success.

View Source
var ErrIssueSinkUnavailable = errors.New("cloud: tracker issue sink not registered")

ErrIssueSinkUnavailable is returned when the tracker is not mounted — fail-closed, never a silent success, so a feeder logs precisely rather than dropping the item.

View Source
var ErrSyncUnavailable = errors.New("cloud: sync engine not registered")

ErrSyncUnavailable is returned when the engine is not mounted — a fail-closed sentinel, never a silent success, so a trigger logs precisely rather than pretending it synced.

View Source
var Version = "dev"

Version is the API contract/build version emitted as the X-Api-Version response header — the support-correlation build signal (the brand-neutral analog of the image tag). Stamped at link time by the release build:

-ldflags "-X github.com/hanzoai/cloud.Version=<image tag>"

and overridable at runtime by CLOUD_VERSION, which the operator sets from the deployed image tag without a rebuild (the same channel as CLOUD_BRAND). Defaults to "dev" for an untagged go build / go test.

Functions

func AccountFromPrincipal added in v1.801.186

func AccountFromPrincipal() zip.Handler

func AuditTrail added in v1.786.1

func AuditTrail(rec *audit.Recorder) zip.Handler

AuditTrail returns the audit middleware bound to rec. A nil rec makes it a no-op passthrough so callers always Use() it unconditionally.

func BYOFeeBps added in v1.801.186

func BYOFeeBps() int64

BYOFeeBps resolves the BYO inference platform fee (basis points) from CLOUD_AI_BYO_FEE_BPS, else the policy default. A negative/invalid value falls through to the default so a typo cannot silently zero out the fee; 0 is honored (free BYO). This is the ONE BYO fee knob for the whole binary.

func BYOFloorMicros added in v1.801.186

func BYOFloorMicros() int64

BYOFloorMicros resolves the per-call BYO floor (micro-USD) from CLOUD_AI_BYO_FLOOR_UUSD, else the policy default. A negative/invalid value falls through to the default.

func BYOInferenceFeeMicros added in v1.801.186

func BYOInferenceFeeMicros(tokens int) int64

BYOInferenceFeeMicros is the per-CALL platform routing fee (micro-USD) for a BYO inference of `tokens` tokens: BYOFeeBps of the EQUIVALENT metered price (aiPriceUUSDPer1kTokens), FLOORED at BYOFloorMicros. A BYO model invoked with the org's own provider token (Cloudflare Workers AI) debits the SAME usage spine and the SAME per-scope caps as a Hanzo-served call, at the thin BYO fee — but never below the floor, so a call the token estimate CANNOT price (a non-text modality: 0 tokens) is still gated and billed rather than slipping through free and unchecked. This is the ONE BYO fee model — no per-provider variant.

func Billable added in v1.801.242

func Billable(method, path string) bool

Billable reports whether a request CONSUMES resource somebody has to pay a provider for, and therefore requires standing before it runs.

THIS IS THE BUG THE SPLIT EXISTS TO KILL. Authorization and pricing were one int64: DefaultPrice returned the edge charge, and BillingGate read `cents <= 0` as "do not gate". Every LLM path prices at 0 there — deliberately, because the ai and zen subsystems meter their own token costs and an edge charge would double-bill — so "we charge nothing HERE" silently meant "we authorize NOTHING here", and the same fusion made every resource kind an operator prices at 0 un-gated as well (ResourceMeter.Gate: `costCents <= 0 -> nil`). One int64 answering two questions is why the LLM leak and the non-LLM gap are a single bug. They are two questions now: Billable says WHETHER standing is required, DefaultPrice says WHAT the edge charges. Pricing something at zero can no longer un-authorize it.

READS ARE NEVER BILLABLE. GET/HEAD/OPTIONS pass unconditionally — gating reads already caused one outage, a balance view that 402s is unusable, and no read this binary serves calls a paid provider.

The path sets are MEASURED, not invented:

  • inference — the exact paths zen's Claim owns (zen@v1.4.2 proxy.go) plus ai's own tree. These are the free-inference hole.
  • meteredTrees — the subsystems that construct a ResourceMeter (the non-LLM auth-not-balance gap). /v1/commerce/ and /v1/o11y/ are in BillingGate's selfMeteredPrefixes but are deliberately NOT here: one is the pay path itself and the other is telemetry ingest, and neither spends a provider's money.

func BillingGate added in v1.786.1

func BillingGate(m *metering.Client, price func(c *zip.Ctx) int64) zip.Handler

BillingGate returns a zip middleware that gates every request on the caller's commerce balance and records usage for priced paths.

Order of operations:

  1. price(c) == 0 AND not gated → pass straight through (free path).
  2. Authorize(ctx, identity) BEFORE c.Next(): nil → allow. ErrInsufficientBalance → 402 insufficient_balance, c.Next() NOT called. other error → 503 balance_unavailable, c.Next() NOT called (fail-closed; the client returns nil here when built FailOpen, so this branch never fires in fail-open mode).
  3. c.Next() runs the handler chain.
  4. After a successful chain, if price(c) > 0, fire `go m.Record(...)` so the debit never blocks or corrupts the response the user already received.

When m is nil or not configured (no commerce URL) the gate is a no-op: it returns c.Next() directly so an unconfigured deployment is never blocked. price must not be nil; pass DefaultPrice.

func BrandForHost added in v1.786.165

func BrandForHost(host string) string

BrandForHost is BrandForHostOK with the Hanzo default for an unmatched Host.

func BrandForHostOK added in v1.786.165

func BrandForHostOK(host string) (string, bool)

BrandForHostOK resolves a request Host to a brand id from the same `brands` registry, mirroring the hostname→brand semantics of platform.ts's getWhiteLabelBrand: a Host at or under a brand's Domain (api.lux.network, lux.network) is that brand. The port is stripped and the compare is case-insensitive; the longest matching Domain wins so a nested brand domain is never shadowed by a shorter one. ok is false when NO brand domain matches, so the caller can choose its own fallback (the deployment brand) rather than silently emitting Hanzo branding on, say, a Zoo pod hit with an odd Host.

func BrandIssuers added in v1.786.50

func BrandIssuers() []string

BrandIssuers returns the OIDC issuer of every configured white-label brand. The in-binary identity validator (auth_identity.go) trusts a token whose `iss` is any of these, so ONE cloud binary validates hanzo AND lux/zoo/pars tokens. One source of truth: derived from the same `brands` registry above.

func CallerBearer added in v1.801.89

func CallerBearer(c *zip.Ctx) string

CallerBearer returns the caller's validated JWT bearer for RELAY to a downstream org-scoped service (e.g. the DNS control plane) that authorizes on the caller's OWN identity and derives the org from the token's `owner` claim. It returns the SAME token SanitizeIdentity validated the principal with (callerToken), UNCHANGED -- cloud substitutes NO service credential of its own, so tenant isolation carries across the hop: a caller in org A relays an org-A token and can reach only org A.

An opaque API key (hk-/sk-/...) is NOT a relayable bearer -- an OIDC target cannot validate it and forwarding it would leak the key -- so it returns "". Empty when the request carries no validatable bearer; the relay then sends no Authorization and the downstream fails closed on its own gate.

func ClientIP added in v1.786.1

func ClientIP(c *zip.Ctx) string

ClientIP extracts the originating client IP from X-Forwarded-For (the gateway sets it); the left-most entry is the real client. Shared by the edge gate and the resource meter so usage records carry a consistent client_ip.

func DefaultPrice added in v1.786.1

func DefaultPrice(c *zip.Ctx) int64

DefaultPrice is cloud's per-request price (in cents) for the edge gate.

It returns 0 — meaning "do not gate, do not charge" — for:

  • health/liveness probes (every /v1/<svc>/health and bare /health),

  • /v1/ai/* : the ai subsystem self-meters its own LLM token costs to commerce; charging again here would DOUBLE-BILL,

  • /v1/agents/* : the canonical agents subsystem now gates + meters its OWN per-run fee to commerce (clients/agents runAgent); the edge must stay 0 or every agent run is billed twice,

  • other subsystems that already self-meter their units (commerce billing itself, o11y telemetry, mcp tool dispatch),

  • /v1/agent* : the agent orchestrator self-meters, billing through the completion it runs in-process, so an edge charge would double-bill.

Every billable surface meters its own units downstream, so the edge charges nothing on its own; it stays wired as a uniform passthrough. Keep self-metering subsystems at 0 to preserve single-charge accounting.

func DenyResource added in v1.786.1

func DenyResource(c *zip.Ctx, err error) error

DenyResource renders the Gate denial outcomes as the SAME JSON the edge gate returns (denyBilling), so every Hanzo surface emits one error contract: 402 insufficient_balance / 503 balance_unavailable.

func Draining added in v1.801.231

func Draining() bool

Draining reports whether a graceful shutdown is in progress.

func EdgeCORS added in v1.786.165

func EdgeCORS(pol *edge.Store) zip.Handler

EdgeCORS returns the browser-CORS middleware for the public /v1 edge. The origin allowlist is the PLATFORM policy's CORSOrigins, read live (recompiled only when it changes) so a SuperAdmin can add/remove origins via PUT /v1/gateway/config.

DEFAULT OFF (empty allowlist ⇒ no-op passthrough). On the RECOMMENDED rollout — the shared Traefik ingress keeps fronting api.hanzo.ai and its `cors-allow-all` middleware already answers CORS there — enabling cloud CORS too would emit a SECOND Access-Control-Allow-Origin header and break every browser preflight. So CORS stays owned by exactly ONE layer: the ingress until/unless the edge moves to a direct DO-LB→cloud path (cloud terminates TLS for api.hanzo.ai), at which point the operator sets CLOUD_CORS_ORIGINS (or PUTs it) and cloud becomes the sole CORS authority. One policy, one place — never both.

When enabled it handles the OPTIONS preflight itself (204, short-circuit) and reflects the allowlisted Origin on the actual response, then continues the chain.

func EdgeRateLimit added in v1.786.165

func EdgeRateLimit(pol *edge.Store) zip.Handler

EdgeRateLimit returns the per-client-IP flood cap that runs BEFORE identity — the gateway's `qos/ratelimit/router` (strategy:"ip") role. The limit + window are read LIVE from the PLATFORM policy (per_ip_rpm / window_sec), so a SuperAdmin can retune the cap via PUT /v1/gateway/config with no redeploy. It is a fixed-window counter keyed on the client IP (leftmost X-Forwarded-For, via ClientIP) with opportunistic eviction of expired windows so the map stays bounded even at the edge's high IP cardinality (why this is not the zip token-bucket primitive that ScopeRateLimit reuses: that primitive never evicts, which is fine for a bounded per-org keyspace but would grow without bound keyed on raw IPs).

SCOPE = public edge only. A request with NO X-Forwarded-For is an IN-CLUSTER direct caller (console BFF, sibling service hitting cloud.svc:8000) — it never transited the ingress/LB, exactly the traffic the standalone gateway never saw, so it is not IP-limited here (parity: the gateway only ever rate-limited public traffic). Only proxied edge traffic, which carries the real client IP in XFF, is throttled. A per_ip_rpm of 0 (env CLOUD_EDGE_RATELIMIT=false at boot) is a live no-op.

func EmbeddedTasks added in v1.786.72

func EmbeddedTasks() *tasksengine.Embedded

EmbeddedTasks returns the ONE in-process tasks engine, or nil until wireDurableIngest has run (or if it failed to start). The Tasks HTTP/UI surface (clients/tasks, mounted at /v1/tasks/*) serves on THIS shared engine — there is exactly one engine per process, shared by ai's durable ingest AND the Tasks product surface, never a second Embed. The surface resolves it lazily (per request) because subsystem Mount runs during MountAll, before wireDurableIngest.

func EmitLifecycle added in v1.800.1

func EmitLifecycle(ctx context.Context, ev LifecycleEvent)

EmitLifecycle fans one event out to every registered subscriber, best-effort and NON-BLOCKING: each subscriber runs in its own goroutine on a cancel-immune context (the fact already happened — a request cancel must not abort the notify/mirror), so a slow reactor (a mirror push) can never delay the git/deploy path or another reactor. A panicking subscriber is contained so one bad reactor can neither crash the shared multi-tenant process nor starve the others; each subscriber logs its own errors.

func EnsureGitMirror added in v1.801.59

func EnsureGitMirror(ctx context.Context, org, project, repo, url string, enabled bool) error

EnsureGitMirror registers (enabled) or removes (disabled) the outbound mirror target url on the native repo. Idempotent.

func EnsureStarterCredit added in v1.801.242

func EnsureStarterCredit(ctx context.Context, w principal.Wallet) (int64, error)

EnsureStarterCredit grants the one-time starter credit to wallet and reports the balance it left behind, or (0,nil) when the wallet was not eligible.

THE ADDRESS IS THE CALLER'S, NOT A GUESS. It credits (Ledger, Account) exactly as principal.WalletOf resolved it, passing Account through as CreditInput.Subject. For a real org Payer yields the org pool and Subject is the bare slug; the day IAM mints per-member `billing_account` claims it yields a person account and the same field carries it. Either way the credit lands where the gate looks, because both come from one call to account.Payer.

ELIGIBILITY IS "NEW", NOT "UNSEEN". A first-contact trigger sees every EXISTING account too — on the first request after a deploy, every org in the fleet is unseen. Granting on unseen alone would hand a retroactive $5 to the entire customer base. So a wallet qualifies only if it has no money and no history: a zero balance AND zero lifetime usage. A funded org is skipped, an org that has ever spent is skipped, and a genuinely new account passes. (Known edge, stated: an old account that was refunded to exactly zero and never metered reads as new and is granted once. It cannot recur — the Ref below is permanent.)

AMOUNT IS SERVER-AUTHORITATIVE. credit.StarterCreditCents, the shared constant, read from the server's own dependency. This function takes no amount and no request body, so there is no client field that could reach it.

func EstTokens added in v1.801.186

func EstTokens(texts ...string) int

EstTokens is a deterministic, provider-agnostic token estimate (~4 chars/token) used to price embeddings (no usage returned) and to pre-gate chat before the completion tokens are known.

func Fail added in v1.801.231

func Fail(c *zip.Ctx, msg string) error

Fail writes a { status:"error", msg } envelope. The operator's transport maps a non-ok envelope to a surfaced error (never a fabricated value).

func GitRepoStatuses added in v1.801.23

func GitRepoStatuses(ctx context.Context, org, project string, names []string) (map[string]GitRepoStatus, error)

GitRepoStatuses returns the per-repo import + sync status for names (org-scoped).

func Handle added in v1.786.216

func Handle[S any](s *Service[S], h func(*Service[S], *zip.Ctx) error) func(*zip.Ctx) error

Handle binds a Service-scoped handler to a route: it adapts a `func(*Service[S], *zip.Ctx) error` to the plain `func(*zip.Ctx) error` the router takes, capturing s. One adapter, so packages write free-function handlers and register them with `app.Get("/path", cloud.Handle(s, myHandler))`.

func IdentityMiddleware added in v1.786.72

func IdentityMiddleware(cfg *Config) zip.Handler

IdentityMiddleware builds the identity trust-boundary middleware from cfg: it constructs the IAM JWT validator (trusted-issuer set, JWKS, audience allowlist) and returns SanitizeIdentity bound to the admin org. This is the ONE constructor for the boundary, so Serve and integration tests wire it identically — no second copy of the validator-construction glue to drift.

func ImportGitRepo added in v1.801.23

func ImportGitRepo(ctx context.Context, req GitImportReq) error

ImportGitRepo creates + mirrors an external repo into the native git server.

func IsPublishableKey added in v1.801.231

func IsPublishableKey(tok string) bool

IsPublishableKey reports whether tok is a publishable key.

A publishable key is NOT a credential: it identifies a tenant so a public surface can WRITE (ingest events), and it must never mint a principal that can READ. Cloud resolved any isAPIKey token — pk- included — into "the same principal a JWT yields", which made a key documented as "safe to show" into a full bearer for the org that owns it. IdentityFromRequest now refuses it, so publishable means publishable.

It stays in APIKeyPrefixes on purpose: OrgForKey must still resolve a pk- to its owning org, because that is exactly how the ingest door learns which tenant a browser beacon belongs to. Resolvable, not authenticating.

func IssuerForBrand added in v1.786.1

func IssuerForBrand(id string) string

IssuerForBrand returns the canonical OIDC issuer for a brand id.

func MarkdownNegotiation added in v1.786.165

func MarkdownNegotiation(defaultPrefixes []string) zip.Handler

MarkdownNegotiation returns the response-path middleware. Register it ONCE at the compose root and every /v1 endpoint negotiates markdown uniformly.

func MetricsHandler added in v1.786.131

func MetricsHandler() http.Handler

MetricsHandler serves the private registry in Prometheus exposition format for the ops /metrics listener (healthMux). Self-contained: it reads only this registry, never the API stack.

func MicrosToGateCents added in v1.801.186

func MicrosToGateCents(micros int64) int64

MicrosToGateCents converts a micro-USD amount to the whole cents a pre-call balance gate must RESERVE: round UP (a gate must never under-reserve), with a 1-cent floor for any positive amount. 1 cent = 10_000 micro-USD. Shared by the LLM meter and every other inference path (Workers AI) so one rule prices the gate everywhere.

func Mount added in v1.786.216

func Mount[S any](app Router, deps Deps, name string, build func(Base) (S, error), routes func(Router, *Service[S])) error

Mount is the one generic subsystem entrypoint. `build` constructs the typed State from Base (open stores, dial clients — returns an error to fail the mount closed); `routes` registers the handlers. A package's exported Mount is then one line: `return cloud.Mount(app, deps, "name", build, routes)`.

func MountAll

func MountAll(app *zip.App, specs []MountSpec, cfg *Config, deps Deps) error

MountAll mounts every ENABLED subsystem in specs, in slice order — the order is the composition root's (apps.Wire()); MountAll does NOT sort.

app is the concrete *zip.App from Serve. A Global spec receives it. Everyone else receives a scope bound to their declared Prefixes, so a subsystem's middleware reaches its own subtrees and nothing else, whatever its slice position. A subsystem that installs middleware outside them fails the mount — the binary refuses to boot half-gated rather than serving with a stranger's gate on.

Teardown is wired HERE, at mount time: right after a subsystem mounts, its ShutdownFunc (if any) is registered via app.OnShutdown. zip drains those hooks LIFO — AFTER the listeners stop accepting and in-flight requests drain — so registration-at-mount yields reverse-mount teardown (a dependency mounted before its dependents is torn down after them) with no subsystem torn down while a request still uses it. Only ENABLED specs mount, so only they register a hook; teardown needs no separate enablement gate.

func OK added in v1.801.231

func OK(c *zip.Ctx, data any) error

OK writes a { status:"ok", data } envelope (the get<T> shape).

func OKList added in v1.801.231

func OKList(c *zip.Ctx, rows any, total int) error

OKList writes a { status:"ok", data:[...], data2:total } envelope (getList<T>).

func OKRaw added in v1.801.231

func OKRaw(c *zip.Ctx, rows json.RawMessage, total int) error

OKRaw writes a { status:"ok", data:<raw>, data2:total } envelope, forwarding a pre-encoded payload verbatim so its exact wire shape reaches the operator field-for-field. An empty payload is normalized to an empty array.

func OnGitPush added in v1.786.216

func OnGitPush(ctx context.Context, ev GitPushEvent) error

OnGitPush fires the registered push-to-deploy trigger for a landed push. It is a no-op when no builder is registered (git server running without the platform subsystem co-resident). Best-effort by contract: the caller must never fail the push the client already committed just because a build could not be triggered.

func OnServiceRelease added in v1.801.7

func OnServiceRelease(ctx context.Context, ev ServiceReleaseEvent) error

OnServiceRelease rolls a proven image live by patching the matching hanzo.ai/v1 Service CR's spec.image (the operator then reconciles the Deployment). It is a no-op when no releaser is registered (a binary without the paas control plane co-resident). The releaser enforces the clean-semver gate and CR-name resolution; this is only the dispatch seam.

func OrgDB added in v1.786.216

func OrgDB(dataDir, org, project, subsystem string) (*sql.DB, error)

OrgDB is the ONE way any cloud subsystem opens a per-org SQLite file (HIP-0302 physical org isolation). It resolves the path, creates the parent directory 0700, opens via the sole "sqlite" driver, and applies the single-writer + WAL pragmas every org store shares. The caller owns migration (its schema is its own) and Close.

Path convention — scope is chosen by project:

project != ""  →  {DataDir}/orgs/{orgSlug}/projects/{projectSlug}/{subsystem}.db
project == ""  →  {DataDir}/orgs/{orgSlug}/{subsystem}.db

org and project MUST be the VALIDATED principal values (principal.Org and, when project-scoped, principal.Project) — never a raw request body/header. OrgDB folds each through SanitizeOrg, the ONE injective org slugger, so two distinct orgs can never share a file (case-fold on a case-insensitive filesystem, or a "-"/"." fold, would otherwise collapse them) and no segment can traverse out of DataDir. An org (or, when project-scoped, a project) that SanitizeOrg refuses is an error — never a silent fall-through to another org's file.

func OrgForKey added in v1.801.91

func OrgForKey(ctx context.Context, key string) (string, bool)

OrgForKey resolves an opaque Hanzo API key (hk-/sk-/pk-/fw_/hz_) to the org it belongs to — the SAME owner org SanitizeIdentity mints when that key arrives as a bearer — through the ONE IAM key seam (get-user?accessKey). It is the exported door a keyed, bearer-less SDK path uses to attribute a project key to a tenant.

FAILS CLOSED: ("", false) for a non-key-shaped string, an unknown/unresolvable key, an unconfigured resolver, or an out-of-bounds org — never a fabricated or default tenant, so a bad key can never be written into another org's partition. The isAPIKey prefix gate keeps garbage strings off the IAM network path.

func OrgHasUnsafeRune added in v1.786.32

func OrgHasUnsafeRune(s string) bool

OrgHasUnsafeRune reports whether s carries any whitespace, control, or zero-width/format rune — the class that defeats the injectivity of the org→org map. strings.TrimSpace (and fasthttp's own header-value OWS trimming) silently drop such runes at the edges, so two DISTINCT IAM org names ("acme" vs "acme ", or an NBSP/ZWSP variant) would collapse onto ONE org-<slug> namespace / image ref — a cross-org fold. The identity trust boundary REFUSES to grant org-scoping from an org bearing one of these (fail secure) instead of folding it, so distinct raw names never collide and no namespace is ever derived from an invisible-character identifier.

Case / '-' / '.' / other visible punctuation are deliberately NOT unsafe: those fold INJECTIVELY through the org-slug hash (provisioning.SanitizeOrg). Only the invisible / edge-trimmable class — which no injective fold can survive once transport strips it — is rejected here. A legitimate IAM org slug never contains such a rune, so no real caller is affected.

func PlatformDB added in v1.801.59

func PlatformDB(dataDir, subsystem string) (*sql.DB, error)

PlatformDB opens the deployment's reserved, NON-tenant partition of an otherwise per-org subsystem at {DataDir}/orgs/_platform/{subsystem}.db, through the SAME cek + single-writer + WAL path as OrgDB. It is the home for records a per-org subsystem holds that belong to no single tenant (e.g. a platform-wide HMAC key): everything tenant-scoped stays in its own {DataDir}/orgs/{slug}/… file. Because the slug carries a '_' that SanitizeOrg never produces, this file is guaranteed disjoint from every tenant's. The caller owns migration + Close.

func Reachable added in v1.801.242

func Reachable(path string) bool

Reachable reports whether a path must be served REGARDLESS of standing.

This is not a scope selector — which routes a gate guards is decided by where it is applied. It is a SAFETY PROPERTY: a customer who has not yet paid must still be able to reach the paths that let them pay, and a lapsed one must be able to cure their own lapse. Gate those and you deadlock every prospect and every lapsed customer at once — a self-inflicted total revenue stop that looks like success in a naive test, because everything returns 402. So the list lives INSIDE the predicate: no future wiring mistake can gate the pay path, whatever it wraps.

Gating too little is a revenue leak we fix next week. Gating too much is an outage. The list is therefore deliberately generous, and anything ambiguous belongs on it.

Traced from the console subscribe flow (console src/components/products/ PlansModule.tsx -> src/lib/api/plans.ts): PlansApi.plans() reads /v1/billing/plans through the per-tenant billing proxy, and checkout drives the /v1/billing/* money surface — which also carries the INBOUND PROVIDER WEBHOOKS at /v1/billing/webhooks/:provider. Gating an inbound payment webhook loses payments outright, so that prefix is load-bearing twice over.

func Refuse added in v1.801.242

func Refuse(c *zip.Ctx, product, reason string) error

Refuse renders the ONE 402 shape every spend gate uses. product is empty for the edge gate (which gates spend itself, not a product) and set by a product-scoped gate; `for <product>` is the only difference it makes to the sentence.

func RegisterCommerceClientFactory added in v1.786.216

func RegisterCommerceClientFactory(f func(cfg *Config, log luxlog.Logger) CommerceClient)

RegisterCommerceClientFactory installs the embedded-Commerce client constructor. apps/commerce.go calls this from its init(); exactly one registration.

func RegisterGitImporter added in v1.801.23

func RegisterGitImporter(g GitImporter)

RegisterGitImporter installs the git object-plane importer. nil-safe.

func RegisterGitMirrorController added in v1.801.59

func RegisterGitMirrorController(c GitMirrorController)

RegisterGitMirrorController installs the git-plane mirror controller. nil-safe.

func RegisterIssueSink added in v1.801.218

func RegisterIssueSink(fn IssueSink)

RegisterIssueSink installs the tracker upsert sink. nil-safe.

func RegisterKMSClientFactory added in v1.786.165

func RegisterKMSClientFactory(f func(cfg *Config, log luxlog.Logger) (KMSClient, error))

RegisterKMSClientFactory installs the embedded-KMS constructor. clients/kms calls this from its init(); it is the ONE inversion point that lets the KMS library and its /v1/kms subsystem share one package with no cloud⇄kms cycle.

func RegisterLifecycleSubscriber added in v1.800.1

func RegisterLifecycleSubscriber(fn func(ctx context.Context, ev LifecycleEvent))

RegisterLifecycleSubscriber adds a git-lifecycle reactor. Every subsystem that reacts to a push/deploy (mirror-out, Slack-notify) registers ONE here at Mount; git/platform EMIT via EmitLifecycle. The inversion keeps the emitters from importing the subscribers — the same pattern as RegisterPushBuilder, but many-registrant.

func RegisterOrgScopeResolver added in v1.786.216

func RegisterOrgScopeResolver(r OrgScopeResolver)

RegisterOrgScopeResolver adds a project-ownership registry consulted by the identity trust boundary. Called once per registry at its Mount (mirrors sites.SetResolver). Registries COMPOSE: a project is "mine" if ANY registry owns it for the org, and "foreign" only if some registry owns it for another org while NONE owns it for this org. A nil resolver is ignored.

func RegisterPushBuilder added in v1.786.216

func RegisterPushBuilder(f func(ctx context.Context, ev GitPushEvent) error)

RegisterPushBuilder installs the git-push-to-deploy trigger. clients/platform calls this from its Mount when co-resident; it is the ONE inversion point that lets the embedded git server launch a platform build with no git⇄platform cycle.

func RegisterServiceReleaser added in v1.801.7

func RegisterServiceReleaser(f func(ctx context.Context, ev ServiceReleaseEvent) error)

RegisterServiceReleaser installs the first-party CR-rollout hook. clients/paas calls this from its Mount when co-resident; it is the ONE inversion point that lets a build-completion path roll a proven image onto its operator Service CR with no cloud⇄paas import cycle.

func RegisterSync added in v1.801.59

func RegisterSync(fn SyncFunc)

RegisterSync installs the sync reconcile func. nil-safe.

func RegisterTelemetryInstaller added in v1.786.216

func RegisterTelemetryInstaller(f func(ctx context.Context, serviceName string) func(context.Context))

RegisterTelemetryInstaller installs the tracer-provider bootstrap that wires this process's OTel global provider to the o11y in-process trace sink AND adopts it into the embedded ai module (so ai emits gen_ai spans). clients/o11y calls this from its init(); it is the ONE inversion point that lets cloud.Serve bootstrap telemetry with no cloud⇄clients/o11y import cycle. Exactly one registration.

func RepoFromCloneURL added in v1.800.1

func RepoFromCloneURL(u string) string

RepoFromCloneURL extracts the repo name from a git clone URL (last path segment, ".git" stripped) — the repo component of the (org,project,repo) routing key that a deploy emitter derives from an app/project's linked RepoURL. The ONE place this derivation lives, shared by the platform + projects deploy paths (no per-package copy).

func ResetLifecycleSubscribers added in v1.800.1

func ResetLifecycleSubscribers()

ResetLifecycleSubscribers clears the registry. TEST-ONLY seam (a test mounts and unmounts repeatedly); production registers once at Mount and never resets.

func ResourceFeeCents added in v1.786.1

func ResourceFeeCents(envPrefix, kind string) int64

ResourceFeeCents resolves the flat create fee (in cents) for kind from operator config, most specific first:

<envPrefix>_<KIND>   e.g. CLOUD_PROVISION_FEE_CENTS_SQL=500
<envPrefix>          e.g. CLOUD_PROVISION_FEE_CENTS=100  (all kinds)
DefaultResourceFeeCents                                   ($1.00)

A clearly-named, configurable policy knob — never a fabricated price. A value of 0 makes the kind free (and un-gated). Negative/invalid values are ignored (fall through), so a typo can never make a paid resource free by accident.

func SanitizeIdentity added in v1.786.1

func SanitizeIdentity(v *identityValidator, adminOrg string) zip.Handler

SanitizeIdentity returns the identity-trust-boundary middleware.

Per request:

  • ALWAYS delete every header in authorityHeaders (a client copy never survives — this alone kills X-User-IsAdmin forgery).
  • Validate a Bearer / Basic / session-cookie JWT, if present: SuperAdmin (homeOrg == adminOrg, human) — membership of the reserved admin org IS the predicate; the isAdmin bit is deliberately not a second term. This line previously read "claims.isAdmin && owner == adminOrg", which was wrong twice over: the code has never consulted isAdmin here (see TestSuperAdminGate_IsAdminOrgMembership), and `owner` named the APP's org, not the user's. → X-User-IsAdmin=true; X-Org-Id = the requested org when present (admin org-switch), else the home org. any other principal (incl. org admins, normal users) → X-Org-Id pinned to owner; NO admin. A client org cannot widen scope.
  • No / invalid / opaque-API-key credential: → NO admin (forgery dead), and the client's X-Org-Id is restored for the Phase-1 data path (residual below).

PHASE-1 RESIDUAL (documented; not a regression vs. today): with no validatable bearer, the client X-Org-Id is passed through for DATA scoping. cloud's data plane has no session of its own yet ("Auth stays gateway-owned in Phase 1") and the console browser data path depends on this header. So a direct-to-pod caller can still SELECT an org for DATA reads. Closing that needs the data path to carry a bearer universally OR the NetworkPolicy locked to gateway-only (which would break console's legitimate direct in-cluster BFF) — Phase-2. The ADMIN boundary (this fix's P0) is closed on every path regardless, because X-User-IsAdmin is NEVER restored from client input.

FAIL MODE. If the validator can't verify a token (JWKS unreachable on a cold cache, issuer/audience misconfigured), the request resolves anonymous and BOTH planes fail SECURE. Admin fails closed (X-User-IsAdmin is never restored from client input), and — since F1 — the DATA plane fails closed too: it gates on a validated principal (clients/principal.Validated) and the anonymous request carries no X-User-Id, so the restored X-Org-Id is refused, not served. Never fails OPEN. The availability cost is bounded to COLD caches: the jwksCache is stale-on-error (a warm cache keeps validating through a transient JWKS outage), so only a from-cold JWKS failure degrades to anonymous-403.

func SanitizeOrg added in v1.786.173

func SanitizeOrg(s string) string

SanitizeOrg reduces a gateway org id to a lowercase [a-z0-9-] slug that is INJECTIVE in the raw owner: an org bearing any whitespace/control/format rune is REFUSED (→ "") at the boundary — folding it would not survive TrimSpace / transport OWS-trim and would collapse "acme " onto "acme" — and every accepted owner then maps to the identity on a DNS-1123 label, else a folded slug disambiguated with "-" + the first 16 hex of SHA-256(raw owner). Without the suffix the fold was lossy — ToLower + every non-[a-z0-9-]→"-" + a 32-char truncation collapse distinct owners (`Acme`/`acme`, `team.a`/`team-a`) onto one slug, and since the whole org→bucket/DB/namespace hashes THIS slug, that was a cross-org collision.

This is the ONE org-slug normalizer for the cloud org layer; it lives in the root package beside OrgHasUnsafeRune (the identity-middleware twin) and OrgDB (which folds every org DB path through it). provisioning.SanitizeOrg (shared with S3/KMS/knowledge) delegates here, so the slug is byte-identical across every physical namespace an org touches.

The identity fast-path is withheld from a clean slug that ITSELF looks like a suffixed output (`<label>-<16 lowercase hex>`): such a slug is ambiguous with a folded owner's disambiguation, so it too is re-suffixed — otherwise a squatted org literally named "foo-<sha256(Foo)[:8]>" would alias non-slug owner "Foo".

func ScopeRateLimit added in v1.786.112

func ScopeRateLimit(m *metering.Client, gp *edge.Store) zip.Handler

ScopeRateLimit returns the per-scope rate-limit middleware. It caps an authenticated org from TWO config sources, most-restrictive-wins:

  • commerce spend-alert RateLimitRpm (the plan-configured ceiling), and
  • the /v1/gateway per-org OrgRPM (gp), the runtime-mutable operator override.

It is a no-op passthrough only when BOTH are absent (no commerce AND no policy store), so an unwired deployment is never blocked — mirroring BillingGate.

func Serve

func Serve(specs []MountSpec, enable []string) error

Serve boots the canonical compose root and mounts the selected subsystems.

This is the ONE place the cloud-server body lives. cmd/cloud (the full fused surface) and every `hanzo <svc>` subcommand share it; no boot logic is duplicated per entrypoint.

specs is the composition root's subsystem list (apps.Wire()), threaded in by the caller so cloud never imports subsystems (which would cycle). Serve mounts it in slice order and tears it down in reverse.

enable==nil ⇒ honor cfg.Enable from flags/env (cloud mode; empty = all). enable!=nil ⇒ force exactly that set (single-service mode), overriding --enable so `hanzo kms` is unambiguous.

Serve registers the HIP-0106 liveness contract (GET /v1/<name>/health for every enabled subsystem) before MountAll, runs the canonical middleware pipeline (Recover → RequestID → Logger), and shuts down gracefully on SIGINT/SIGTERM.

func ServiceReleaserRegistered added in v1.801.7

func ServiceReleaserRegistered() bool

ServiceReleaserRegistered reports whether a first-party CR-rollout hook is installed (the paas control plane is co-resident). A caller uses it to know whether OnServiceRelease actually patches a CR or is a no-op, so it can be honest about which rollout path took effect.

func SetDraining added in v1.801.231

func SetDraining()

SetDraining marks the process draining (readiness → NotReady). Idempotent.

func SetSwitchReader added in v1.801.218

func SetSwitchReader(f func(string) bool)

SetSwitchReader installs the platform-switch evaluator. clients/flags calls it once on mount; passing nil detaches it (used by tests).

func SpendGate added in v1.801.242

func SpendGate(commerce CommerceClient) zip.Handler

SpendGate returns the balance-and-subscription gate serve.go mounts app-wide.

DEFAULT OFF, AND THAT IS A SEQUENCING DECISION, NOT TIMIDITY. There is no reachable starter-credit path in this binary today: the grant-starter route was deleted from commerce (last present in commerce v1.48.2), its replacement POST /v1/billing/credit is not registered in the co-resident build, and no ensureStarterCredit runs anywhere. So a brand-new signup's wallet is $0 with no self-service way to fund it. Enforcing on that state 402s every new signup on day one — trading a revenue leak for a total signup outage. The gate therefore ships behind the kill switch, proven by tests, and is flipped only after a funding path exists. Turning it on before then is the one way to make this worse.

Enforcement is read PER REQUEST from the platform switch an owner flips at admin.hanzo.ai, so it turns on and off within one flag-cache TTL — no redeploy, no CR edit. Switch reports false before the flag engine mounts, so an unmounted switch never enforces.

DECISION ORDER — a request is ADMITTED unless the one proven refusal fires:

  1. enforcement OFF ........................ admit. Read FIRST, so a dark gate costs one atomic load and touches no authority.
  2. not Billable ........................... admit. Reads, the pay path, and every non-metered route are never gated (see Billable / Reachable).
  3. unvalidated principal .................. admit. An anonymous caller is the route's own 401 to make; a 402 is meaningless to someone not signed in, and the org on such a request is a forge anyway.
  4. platform super-admin ................... admit. Platform sudo, including masquerade, is strictly tighter than any purchasable tier and never 402s.
  5. subscribed OR funded ................... admit.
  6. UNRESOLVABLE standing .................. posture (paywall_strict), logged WARN.
  7. proven unpaid .......................... 402 with the actionable refusal.

FAIL POSTURE — argued, not inherited. The refusal in (7) requires PROOF: both authorities answered and both said no. An authority we could not reach yields Unknown, and by default an Unknown ADMITS. That is not "unpaid users get everything free whenever commerce hiccups" — it is "we never call a customer delinquent on evidence we do not have". The asymmetry decides it: refusing on an outage 402s every PAYING customer at once (a total product outage, irreversible), while admitting on an outage leaks access for the duration (bounded, recoverable, and separately capped — the subsystem meters still run their own fail-closed debit). Every fail-open admit logs at WARN with the reason, so a sustained leak pages rather than hides. When an owner wants the other trade, paywall_strict flips it live.

An unresolvable WALLET is an Unknown, not an admit: principal.WalletOf refuses an unresolvable org, and "we could not work out who pays" must refuse AS UNKNOWN and take the strict posture, never be silently waved through as if it were free.

func StarterGrant added in v1.801.242

func StarterGrant() zip.Handler

StarterGrant returns the middleware serve.go mounts ahead of the billing gates, so a brand-new account is funded BEFORE the gate on that same request evaluates it — otherwise the very first request of every new signup would 402 the moment enforcement is switched on, which is the failure this whole path exists to prevent.

It never blocks, never fails a request, and never rejects: funding is not an authorization decision. Every outcome falls through to c.Next(). If the grant fails the account simply holds no credit, and the gate — which reads the ledger, not a grant flag — refuses it. There is no path where a failed grant is mistaken for funding.

func Switch added in v1.801.218

func Switch(key string) bool

Switch reports a platform switch's live value. It returns false before the flag engine mounts and when no engine is present (!cgo), which is the same dark default the engine itself falls back to — so an unmounted switch never enforces.

func Terminal added in v1.801.59

func Terminal(h func(*zip.Ctx) error) func(*zip.Ctx) error

Terminal wraps a handler so a returned *zip.HTTPError is written in-band (its status + the {status,code,error} JSON zip's default errorHandler would emit) and nil is returned, instead of propagating the error up the middleware chain.

It exists for routes mounted UNDER an outer error-flattening filter. The commerce embed installs one: mountCommerce (apps) registers ErrorHandlerJSON on an app.Group("/v1") whose middleware rewrites ANY error a downstream /v1 handler PROPAGATES into a hardcoded HTTP 500 — so a reject that returns zip.ErrUnauthorized (401) or zip.ErrBadRequest (400) up the chain surfaces to the client as 500. A subsystem mounted after commerce (git, sync, integrations, …) whose reject path must keep its real 4xx wraps its handler here: the status is written before the filter runs, so the filter's c.Next() sees nil and has nothing to flatten. A non-HTTPError (a genuine unexpected failure) passes through unchanged — those are 500s regardless. Compose with Handle: cloud.Terminal(cloud.Handle(s, fn)).

func TracingMiddleware added in v1.786.82

func TracingMiddleware() zip.Handler

TracingMiddleware emits ONE OpenTelemetry SERVER span per /v1/* request through the global (ZAP) tracer provider, so every api.hanzo.ai request lands in hanzoai/datastore over the ZAP wire alongside the log pipeline. It records the OTel HTTP semantic-convention attributes (method, route, status), sets the span status on error/5xx, and — critically — PROPAGATES the span context onto the request via SetContext so nested spans (agent.run, agent.step, the LLM chat client span in clients/aihttp.go) parent correctly under the request span. That makes a full agent trace a single tree: request → run → step → chat.

It is a plain zip.Handler wrapping c.Continue(), the framework's idiomatic middleware form (the same shape as middleware.Logger); no otelfiber shim is needed because zip already exposes method/path/status/context.

func UpstreamModel added in v1.801.231

func UpstreamModel(name string) bool

UpstreamModel reports whether name carries an upstream family name.

It matches the family as a WORD, not as a substring: a model id is split on its separators (vendor prefixes, tiers, sizes) and each word has its trailing version digits stripped, so "qwen3.5-397b", "fireworks/deepseek-v3" and "kimi-k2.6" all match while "zen5-coder" and "enso-flash" do not.

func ZenModel added in v1.801.231

func ZenModel(name string) string

ZenModel returns the Hanzo name for a model: an upstream family name becomes DefaultModel, and a name that is already ours is returned unchanged (trimmed).

Mapping to the default rather than to a guessed tier is the honest answer. We are not claiming which enso tier a given upstream base corresponds to; we are saying the work runs on whatever this deployment runs unnamed work on, which is the same thing we would have told the caller had they named no model.

Types

type AIClient

type AIClient = types.AIClient

type Base added in v1.786.216

type Base struct {
	Log     luxlog.Logger
	KMS     KMSClient
	Bill    *ResourceMeter
	Brand   string
	Env     string
	Domain  string
	DataDir string
	// Durable is the deployment's HA-durability factory (nil ⇒ local-only). A
	// subsystem opening per-org SQLite passes it to NewOrgStore(WithDurable) to make
	// its stores survive rolling deploys/replicas.
	Durable *Durability
}

Base is the shared dependency set every subsystem needs, derived ONCE from Deps at mount. It is embedded in Service, so a handler reaches Log/KMS/Bill/ Brand directly (s.Log, s.Bill, …) with no package re-plumbing them.

func NewBase added in v1.786.216

func NewBase(deps Deps, name string) Base

NewBase derives the shared deps for a named subsystem: a scoped child logger, the embedded KMS client, and the per-org resource meter (provider = name).

Most packages never call this — cloud.Mount does. It is exported for the few subsystems whose Mount is more than build+routes (a background reconciler, a package-global for cross-package hooks, a shutdown cancel): they construct the value directly — `s := &cloud.Service[state]{Base: cloud.NewBase(deps, "x"), State: st}` — then wire routes with Handle, still on the ONE generic type.

type BaseClient

type BaseClient = types.BaseClient

type BrandInfo added in v1.786.1

type BrandInfo struct {
	// ID is the canonical brand key.
	ID string
	// IAMIssuer is the OIDC issuer (JWKS source) for this brand — the value the
	// JWT `iss` claim must equal and whose /v1/iam/.well-known/jwks signs tokens.
	IAMIssuer string
	// Domain is the brand's primary marketing/site domain (for response scoping
	// and base-URL derivation, e.g. api.<Domain>).
	Domain string
	// AltDomains are additional registrable domains that ALSO belong to this
	// brand, used ONLY for hostname→brand white-label detection (BrandForHostOK).
	// A brand's real serving surfaces span more than its marketing domain — the
	// cloud console runs on <brand>.cloud hosts (console.lux.cloud,
	// console.zoo.cloud), and a request Host there must brand as Lux/Zoo, never
	// fall through to Hanzo. Base-URL/issuer scoping still uses the primary Domain.
	AltDomains []string
}

BrandInfo is the PUBLIC per-brand identity used for token validation + URL scoping. No secrets.

func BrandFor added in v1.786.1

func BrandFor(id string) BrandInfo

BrandFor returns the BrandInfo for id, falling back to the Hanzo brand for an unknown id. Lookup is case-insensitive.

type ChatRequest

type ChatRequest = types.ChatRequest

type ChatResponse

type ChatResponse = types.ChatResponse

type Claims

type Claims = types.Claims

type CommerceClient

type CommerceClient = types.CommerceClient

type Config

type Config struct {
	// Enable lists subsystems to mount this run. Empty = all enabled.
	// Example: --enable=iam,base,kms,commerce,ai,gateway,o11y
	Enable []string

	// EnableStaged ADDITIVELY activates staged subsystems (stagedSubsystems) on top
	// of the default set, orthogonally to the Enable allowlist. It exists so a
	// deployment can run "every default subsystem PLUS iam" — the faithful prod +
	// staged-fold shape — WITHOUT collapsing Enable into a hand-enumerated allowlist
	// that silently drops a subsystem the day one is added. CLOUD_ENABLE_STAGED=iam
	// with an empty CLOUD_ENABLE = all-non-staged (the production default) + iam.
	// A staged name may equally be activated by naming it directly in Enable; this
	// is the additive path that does not disturb the non-staged default. One lever
	// per intent: Enable = "exactly this set", EnableStaged = "also turn these
	// staged ones on".
	EnableStaged []string

	// Replicas is the app-tier replica count the operator injects (CLOUD_REPLICAS,
	// mirroring the Deployment's spec.replicas). 0 = unset/unmanaged. It exists to
	// enforce ONE contract: embedded IAM (clients/iam) keeps its identity store as a
	// per-pod embedded SQLite file, so an iam-enabled cloud MUST run at a single
	// replica or each replica gets its OWN divergent identity store. Validate refuses
	// to boot iam-enabled above 1; the helm chart pins replicas=1 whenever "iam" is in
	// --enable. Pointing IAM at a shared external store lifts this.
	Replicas int

	// Brand is the white-label brand identifier.
	Brand string

	// Version is the API contract/build version emitted as the X-Api-Version
	// response header. Sourced from CLOUD_VERSION, else HANZO_VERSION — which the
	// operator sets on every container from the image tag it rendered, so a pod
	// can name its own build without a rebuild — else the link-time cloud.Version
	// default (see version.go).
	Version string

	// Env is the deployment environment (mainnet|testnet|devnet) per the 3-env
	// split. Billing fires in EVERY env — test/dev meter against their own
	// sandbox commerce/Square, never free — so Env is an attribution label, not
	// a gate. Empty when the operator has not set CLOUD_ENV.
	Env string

	// Domain is the deployment's primary public domain.
	Domain string

	// IAMIssuer is the JWKS issuer for JWT validation (usually iam.hanzo.ai).
	IAMIssuer string

	// AdminOrg is the IAM org slug whose members are SuperAdmins (IAM's
	// IsSuperAdmin: owner == AdminOrg). The in-binary identity sanitizer grants
	// admin authority — the c.IsAdmin() that gates /v1/admin/* writes, the
	// /v1/pricing/sync trigger, and the literal "admin" org bucket — ONLY to a
	// validated principal from this org, never to a raw header. Env IAM_ADMIN_ORG
	// (default "admin"), matching the gateway's admin-guard.
	AdminOrg string

	// JWKSURL is the JSON Web Key Set endpoint the identity sanitizer fetches IAM
	// signing keys from. Defaults to {IAMIssuer}/v1/iam/.well-known/jwks
	// (HIP-0111); override with CLOUD_JWKS_URL.
	JWKSURL string

	// KMSMasterKeyRef is the base64-encoded 32-byte KMS master key (KEK) the
	// embedded luxfi/kms store seals every secret's DEK under. The operator
	// injects it from a K8s Secret as CLOUD_KMS_MASTER_KEY_REF; cloud reads it
	// ONLY from env (never from the store it hosts — the bootstrap chicken-and-egg)
	// and never logs it. Empty ⇒ the KMS subsystem runs fail-closed (health-only).
	KMSMasterKeyRef string

	// KMSMPCAddr / KMSMPCVaultID configure the MPC threshold-signing backend for
	// KMS Sign. Both empty (the default) ⇒ Sign fails closed with a clear error;
	// signing is never fabricated. Set via CLOUD_KMS_MPC_ADDR / CLOUD_KMS_MPC_VAULT_ID.
	KMSMPCAddr    string
	KMSMPCVaultID string

	// DataDir is the on-disk data root.
	DataDir string

	// Role is the HA role of this process (CLOUD_ROLE): the single Writer that
	// owns the RWO stores (default) or a read-only Reader replica. Resolved and
	// validated in Serve; defaults to Writer so an unset variable is byte-identical
	// to today's single-pod deployment.
	Role role.Role

	// WriterURL is the base URL of the single writer (CLOUD_WRITER_URL, e.g.
	// http://cloud-writer.hanzo.svc:8000). A Reader forwards EVERY request here —
	// it opens no stores and is a transparent, always-ready edge that absorbs the
	// writer's rollout gap (see reader_proxy.go). Required when Role==Reader;
	// ignored by a Writer.
	WriterURL string

	// ReaderRetryBudget bounds how long a Reader retries a request the writer
	// could not yet accept (connection refused / no ready endpoint) during a
	// writer roll, before returning 502. Dial-only retry (the request never
	// reached the writer) keeps a non-idempotent POST safe. CLOUD_READER_RETRY_BUDGET
	// (Go duration, default 25s).
	ReaderRetryBudget time.Duration

	// WriterLease, when true (CLOUD_WRITER_LEASE), makes a Writer take an
	// exclusive fcntl lease on {DataDir}/.writer.lock BEFORE opening the RWO
	// stores and release it LAST at shutdown (after every store is closed). This
	// serializes a surge/overlap roll (RollingUpdate maxUnavailable:1 +
	// same-node podAffinity) so the new writer opens the exclusive-lock ZapDB/
	// audit stores only after the old one released them — never a double-open.
	// Default OFF, so an unset variable is byte-identical to today's Recreate
	// single-writer (which never overlaps and needs no lease). With per-pod RWO
	// PVCs (the sharded StatefulSet below) the lease is pod-local and never
	// contends across peers, so it stays OFF there — the shard router, not the
	// lease, is the cross-pod single-writer guarantee.
	WriterLease bool

	// ShardPeers is the CLOUD_PEERS membership list ("id@addr,id2@addr2") of the
	// horizontal-scale StatefulSet: the full, STABLE set of writer pods (each a
	// cloud-N ordinal at its headless per-pod DNS cloud-N.<svc>:8000). Every org is
	// pinned to exactly one owner pod by rendezvous hashing (ha.Owner over this set),
	// so each org's per-org SQLite files are written by ONE pod only; a request whose
	// org this pod does not own is forwarded to the owner (shardrouter.go). Empty or a
	// single entry ⇒ sharding OFF, byte-identical to the single-pod deployment. The
	// set is identical on every pod (static env), so all pods agree on every org's
	// owner — no split-brain dual-writer, no routing loop.
	ShardPeers string

	// ShardSelf is THIS pod's stable id — the StatefulSet ordinal name cloud-N, from
	// CLOUD_POD_NAME (or the downward-API POD_NAME). When sharding is on it MUST be one
	// of ShardPeers' ids (Validate refuses otherwise, so a misconfigured ordinal cannot
	// black-hole every request by forwarding it away with no shard of its own).
	ShardSelf string

	// PeerSelector is the Kubernetes label selector that names this deployment's writer
	// pods (CLOUD_PEER_SELECTOR, e.g. "app.kubernetes.io/name=cloud,app.kubernetes.io/
	// instance=<release>"). When set AND running in-cluster, membership is LIVE — the
	// binary lists Ready, non-terminating pods matching it via the K8s API, so a rolling
	// upgrade's changing pod set is tracked and a draining/dead pod is never elected an
	// org's owner. Empty (dev / native-Go / not in a cluster) falls back to the STATIC
	// ShardPeers/self set — capability-detected, no on/off flag. Deployment wiring the
	// chart sets, not a feature toggle.
	PeerSelector string

	// ListenAddr is the public HTTP listener (default :8080).
	ListenAddr string

	// ZAPListenAddr is the ZAP-RPC listener (default :9653).
	ZAPListenAddr string

	// ZAPWebOrigins is the WebSocket Origin allowlist for the browser-facing
	// /zap ZAP plane (the SPA hosts that may open a ZAP-over-WS connection).
	// Empty == same-origin only. Set via CLOUD_ZAP_WEB_ORIGINS (comma-sep).
	ZAPWebOrigins []string

	// MarkdownDefaultPrefixes lists path prefixes whose successful JSON
	// responses default to markdown (zap-proto/md) when the caller expresses no
	// format preference — the agent-facing endpoints (e.g. /v1/code/, /v1/agents/).
	// A caller always keeps the override: ?format=json or Accept: application/json
	// forces JSON even here, and JSON stays the default everywhere else. Empty ==
	// JSON everywhere unless explicitly negotiated. Env CLOUD_MARKDOWN_DEFAULT_PREFIXES
	// (comma-separated). See middleware_markdown.go.
	MarkdownDefaultPrefixes []string

	// Edge policy (middleware_edge.go) — the "gateway role" cloud absorbs when it
	// serves the public api.hanzo.ai edge directly, no KrakenD hop.
	//
	// CORSOrigins is the browser-CORS allowlist for the /v1 edge. Each entry is an
	// exact origin ("https://hanzo.ai"), a bare host ("hanzo.ai"), or a host
	// wildcard ("*.hanzo.ai" = apex + any subdomain). EMPTY ⇒ CORS is OWNED
	// ELSEWHERE (the shared Traefik ingress `cors-allow-all` fronting api.hanzo.ai)
	// and cloud emits NO CORS headers — set CLOUD_CORS_ORIGINS only on a direct
	// DO-LB→cloud edge, so exactly one layer answers CORS (never both → duplicate
	// ACAO breaks the browser). Reads CLOUD_CORS_ORIGINS, then GATEWAY_CORS_ORIGINS
	// (shared with the gateway so both trust boundaries agree on one list).
	CORSOrigins []string

	// EdgeRateEnabled turns on the per-client-IP edge flood cap that runs BEFORE
	// identity (CLOUD_EDGE_RATELIMIT, default true — the gateway enforced this, so
	// dropping it silently would drop a protection). EdgeRatePerIP requests per
	// EdgeRateWindowSec seconds are allowed per public client IP (leftmost
	// X-Forwarded-For); in-cluster direct callers carry no XFF and are exempt.
	// Defaults 100/1s mirror the gateway service-tier client_max_rate (strategy:ip).
	EdgeRateEnabled   bool
	EdgeRatePerIP     int
	EdgeRateWindowSec int

	// HealthListenAddr is the health/metrics listener (default :9090).
	HealthListenAddr string

	// AdminListenAddr is the admin endpoint (default :8081, gated by IAM admin).
	AdminListenAddr string

	// ReadBufferSize is the fasthttp per-conn request-read buffer for the public
	// HTTP edge (zip/fiber), in bytes. fasthttp caps total request-header size at
	// this value and returns 431 (Request Header Fields Too Large) above it. The
	// framework default is 4 KiB — too small once a multi-domain SSO session (an
	// admin-guard Domain=.hanzo.ai cookie set on EVERY subdomain) pushes a
	// browser's request headers past ~4 KiB, 431-ing legitimate requests. This
	// raises the edge ceiling to a sane 32 KiB (nginx large_client_header_buffers
	// parity). Env GATEWAY_READ_BUFFER_SIZE (shared with the gateway edge so both
	// trust boundaries agree on ONE value); tunable down if the per-conn memory
	// budget (SCALE_STANDARD §8) demands it. Internal zip services keep the 4 KiB
	// framework default — only the browser-facing edge opts up.
	ReadBufferSize int

	// BodyLimit is the maximum request body the public HTTP edge (zip/fiber)
	// accepts, in bytes. The framework default is 4 MiB — which silently caps the
	// CONTEXT WINDOW: a chat request carries its whole prompt in the body, and at
	// ~4.3 bytes/token a 1M-token prompt is ~4.3 MB. So the 1M-context models we
	// route to (deepseek-v4-pro; anything glm-5.2 overflows into past its 262,144
	// cap) could not actually be reached — fasthttp refused the body before any
	// handler ran, with the opaque 400 "Error when parsing request" that reads
	// like a malformed payload rather than a size cap. 16 MiB gives 1M tokens
	// real headroom (~3.7x) without inviting a memory-exhaustion vector: the edge
	// is authenticated + rate-limited, and fasthttp streams rather than buffering
	// per-conn. Env GATEWAY_BODY_LIMIT.
	BodyLimit int

	// SitesApex is the zone whose subdomains are PUBLIC published-site hosts
	// (`<slug>.<apex>`, default hanzo.app). The site host-router (clients/sites)
	// serves the root path space for these hosts from OUR S3, ahead of the API
	// pipeline, so a published site is a public artifact — never an org API call.
	// Env CLOUD_SITES_APEX.
	SitesApex string

	// SitesReserved lists subdomain labels under SitesApex that are NOT sites and
	// must fall through to the normal pipeline (real app/api hosts on the apex).
	// This is the reserved-host exclusion that stops a published site from
	// shadowing a real hanzo.app app. The empty label (apex) and "www" are always
	// reserved; these add to them. Env CLOUD_SITES_RESERVED (comma-separated).
	SitesReserved []string

	// SitesSelfDomains are OUR OWN registrable domains (hanzo.ai, hanzo.app, …).
	// The site edge serves a BOUND CUSTOM domain (a customer's own apex pointed at
	// this edge) from that project's S3 prefix — but only for hosts NOT at/under a
	// self domain, so the api/console path never does a per-request binding lookup
	// and a customer binding can never shadow a real Hanzo host. Defaults to the
	// apex plus the registrable domain of the deployment's own Domain (api.hanzo.ai
	// → hanzo.ai). Env CLOUD_SITES_SELF_DOMAINS (comma-separated) overrides.
	SitesSelfDomains []string

	// SitesFirstPartyApex is an internal SelfDomain (hanzo.ai) on which we serve a
	// small OPT-IN set of OUR OWN first-party sites (SitesFirstPartySites). Unlike
	// SitesApex — multi-tenant, sites-by-default with a reserved denylist — the brand
	// apex carries api/console/iam/kms/…, so it serves a site ONLY for an explicitly
	// allow-listed label; every other host falls through protected by default (no
	// denylist to keep complete). Env CLOUD_SITES_FIRSTPARTY_APEX (default hanzo.ai).
	SitesFirstPartyApex string
	// SitesFirstPartySites is the explicit allowlist of first-party site labels on
	// SitesFirstPartyApex (our internal pages: cd, flow, gallery). A user site never
	// lands here — users get <slug>.hanzo.app. Env CLOUD_SITES_FIRSTPARTY (comma-sep).
	SitesFirstPartySites []string
	// SitesFirstPartyOrg owns the first-party sites (hanzo). First-party host
	// resolution is PINNED to this org so a customer project can never shadow an
	// internal host (cd.hanzo.ai serves ONLY org hanzo's "cd"). Empty ⇒ first-party
	// sites are disabled (fail-closed). Env CLOUD_SITES_FIRSTPARTY_ORG (default hanzo).
	SitesFirstPartyOrg string

	// Endpoints for out-of-process subsystems (payments, vault). Empty
	// means the subsystem is disabled OR the deployment expects a default
	// service-discovery resolution.
	PaymentsZAPAddr string
	VaultZAPAddr    string

	// Billing gate (commerce metering) — the request-edge balance gate.
	//
	// CommerceHTTPURL is the commerce service base over HTTP (the metering
	// client speaks net/http, not ZAP). Empty disables the gate entirely.
	//
	// CommerceServiceToken is the admin-scoped commerce S2S token. It is a
	// SECRET sourced from a KMS-backed secret the operator injects as
	// COMMERCE_SERVICE_TOKEN — never hard-coded or read from disk here.
	//
	// BillingFailOpen flips the gate to allow-on-error. Default is
	// fail-closed (deny when balance can't be determined), matching the
	// gateway. Set only where availability outranks billing.
	CommerceHTTPURL      string
	CommerceServiceToken string
	BillingFailOpen      bool

	// AI inference gateway. Two DISTINCT endpoints, two DISTINCT credentials by
	// concern (see build.go pickCompletionsClient / pickEmbedClient):
	//   - CHAT COMPLETIONS (deps.AI, a WRITE endpoint) — agents/guide/crm/content/
	//     sitegen/code-ask. Authenticated by the IAM M2M identity below, NEVER by a
	//     read-only publishable (pk-) key.
	//   - EMBEDDINGS (deps.Embed, a READ-ONLY endpoint) — code-index + KB. This is
	//     the ONLY consumer of AIAPIKey (the pk- key); read-only is exactly what a
	//     publishable key may do.
	//
	// AIBaseURL is the gateway /v1 root (CLOUD_AI_BASE_URL, default
	// https://api.hanzo.ai/v1); the client appends /chat/completions or /embeddings.
	//
	// AIAPIKey is the KMS-injected static gateway key (CLOUD_AI_API_KEY ←
	// cloud-ai-embed-key). It is a SECRET — never logged, printed, or read from disk
	// here. On the Hanzo deployment it is a read-only PUBLISHABLE (pk-) key: it feeds
	// deps.Embed (read-only, valid) and is REFUSED for deps.AI completions, which the
	// gateway would 403 ("Publishable keys can only access read-only endpoints"). A
	// completions-capable secret key (sk-/hk-) set here would instead drive both.
	//
	// AIDefaultModel is the served model an agent with no explicit model falls
	// back to (CLOUD_AI_DEFAULT_MODEL, default DefaultModel — the bare "enso"
	// alias the gateway resolves to a tier per call). Model routing is the
	// gateway's job; this is the ONLY cloud-side model default, and its literal
	// lives in exactly one place (model.go).
	//
	// AIFallbackModel is the reliable model the agent runner fails over to when
	// the agent's own model stays throttled (429/overloaded) after bounded retries
	// (CLOUD_AI_FALLBACK_MODEL, default "best" — the gateway's route-to-best
	// meta-model). It keeps an autonomous bot reply landing when the default flash
	// model is overloaded; the interactive chat path never uses it. Empty disables
	// failover (retry-only).
	AIBaseURL       string
	AIAPIKey        string
	AIDefaultModel  string
	AIFallbackModel string

	// AIAuthClientID / AIAuthClientSecret are the binary's OWN IAM service
	// identity (IAM_CLIENT_ID / IAM_CLIENT_SECRET). The completions client (deps.AI)
	// authenticates to the gateway with a client-credentials (M2M) token minted from
	// this identity and auto-refreshed — the durable no-static-key path, and the ONLY
	// completions credential when AIAPIKey is the read-only pk- embed key. On the
	// Hanzo deployment the identity resolves to admin/hanzo-cloud (gateway-balance-
	// exempt), so cloud's per-org ResourceMeter remains the single debit. The token
	// endpoint is derived from IAMIssuer ({issuer}/v1/iam/oauth/token). The secret is
	// KMS-injected and never logged.
	AIAuthClientID     string
	AIAuthClientSecret string

	// ZAP RPC endpoints for subsystems that are NOT enabled in this
	// process but are still needed by an enabled subsystem. Empty
	// means "no remote endpoint" — the client falls back to the
	// disabled stub which fails closed with a clear error.
	//
	// Convention: <subsystem>.<env>.<deployment>.svc:9653 — the same
	// inter-subsystem listener port the unified binary exposes. The
	// transport is hanzoai/zap, never JSON.
	IAMZAPAddr      string
	KMSZAPAddr      string
	BaseZAPAddr     string
	CommerceZAPAddr string
	AIZAPAddr       string
	O11yZAPAddr     string
	VFSZAPAddr      string
	MQZAPAddr       string

	// NodeID is this instance's stable identity within the control-plane quorum.
	// Env NODE_ID. Empty ⇒ unset.
	NodeID string

	// Peers is the control-plane peer set (the other nodes this instance would
	// form consensus with). Env PEERS (comma-separated). Empty ⇒ unset.
	Peers []string

	// ControlPlaneRole is this instance's control-plane role: "voter"
	// (participates in consensus) or "data" (data-plane only). Env ROLE.
	// Empty ⇒ unset. NAMED ControlPlaneRole (not Role) to avoid colliding with
	// the HA Role field above (role.Role, CLOUD_ROLE): #160 (writer/reader HA
	// split) and #163 (Stage-0 control plane) each added a `Role` to this struct
	// on separate branches, which broke the build on merge. This one is the inert
	// Stage-0 string — read but consumed by nothing until the engine is wired.
	ControlPlaneRole string

	// ControlPlaneQuorum is the number of voter nodes required to form a
	// control-plane quorum. Env CONTROL_PLANE_QUORUM. 0 ⇒ unset.
	ControlPlaneQuorum int
}

Config is the cloud binary's startup configuration. Drives which subsystems mount, what brand surface to serve, and where data lives.

func LoadConfig

func LoadConfig() *Config

LoadConfig reads flags + env into a Config. Flags override env.

func (*Config) Enabled

func (c *Config) Enabled(name string) bool

Enabled reports whether subsystem `name` is enabled in this config. Empty Enable list = all subsystems enabled, EXCEPT staged subsystems (stagedSubsystems). A staged subsystem mounts only when named explicitly — in Enable, or (the additive, allowlist-preserving path) in EnableStaged.

func (*Config) Validate

func (c *Config) Validate() error

Validate returns an error if the config is missing required values.

type Counter

type Counter = types.Counter

type Cure added in v1.801.242

type Cure struct {
	Kind string `json:"kind"`
	URL  string `json:"url"`
}

Cure is one way out of a 402: Kind names the admit leg it satisfies ("subscribe" | "credit"), URL where to do it.

type DBHandle

type DBHandle = types.DBHandle

type Deps

type Deps struct {
	// Logger is the canonical Hanzo logger (luxfi/log). Subsystems derive
	// scoped child loggers from this.
	Logger luxlog.Logger

	// Brand is the white-label brand identifier for this deployment.
	// Values: "hanzo", "lux", "zoo", "osage", "pars", or any customer brand.
	Brand string

	// Version is the API contract/build version emitted as the X-Api-Version
	// response header (see middleware.ProductionHeaders wiring in serve.go).
	Version string

	// Env is the deployment environment (mainnet|testnet|devnet). Subsystems
	// that meter usage stamp it for per-env attribution; it never gates or
	// bypasses billing (every env bills against its own commerce ledger).
	Env string

	// Domain is the deployment's primary domain (e.g. "api.hanzo.ai",
	// "api.osage.cloud"). Subsystems use this to scope URLs in responses.
	Domain string

	// IAMIssuer is the canonical OIDC issuer (JWKS source) for this brand,
	// resolved from Brand via the white-label registry unless pinned by the
	// operator. Subsystems validate JWT `iss` + signatures against
	// {IAMIssuer}/v1/iam/.well-known/jwks (HIP-0111). One issuer per deployment.
	IAMIssuer string

	// DataDir is the per-deployment data root. Per-org SQLite files
	// land at {DataDir}/orgs/{orgSlug}/{service}.db per HIP-0302.
	DataDir string

	// Durable is the per-deployment HA-durability factory an OrgStore wires
	// WithDurable: the shared ha election + vfs FencedStore over the SeaweedFS S3
	// gateway + per-org envelope Cipher. nil ⇒ local-only (no object store creds,
	// dev/single-node), and every OrgStore is exactly the pre-durability cache.
	Durable *Durability

	// LiveMembers reads the CURRENT live writer set (the SAME ha.Membership snapshot the
	// durability fencer elects over). Non-nil ONLY when the durable plane is active — the
	// shard router then routes on the live set, so a draining/dead pod's orgs go to the
	// ready successor that hydrates them (M3), not to the gone pod. nil ⇒ the router falls
	// back to the static CLOUD_PEERS set: without the durable plane a peer cannot serve
	// another pod's local-only files, so ownership must stay pinned to the ordinal (which
	// reattaches its PVC across a restart). One field gates the whole live-routing path.
	LiveMembers func() []ha.Member

	// AIDefaultModel is the served model a subsystem uses when a caller supplies
	// none (CLOUD_AI_DEFAULT_MODEL, default DefaultModel = "enso"). It is the ONE
	// cloud-side model default, sourced from config so no subsystem hardcodes a
	// model id. The agents subsystem stores it on an agent created without an
	// explicit model, so a bot launched without a model still runs on a valid
	// catalog model. Model routing itself stays the gateway's job.
	AIDefaultModel string

	// AIFallbackModel is the reliable model the agent runner fails over to when an
	// agent's own model stays throttled after retries (CLOUD_AI_FALLBACK_MODEL,
	// default "best"). Only the autonomous agent/bot run path uses it; interactive
	// chat is untouched. Empty disables failover.
	AIFallbackModel string

	// Subsystem clients — populated by BuildDeps based on enabled subsystems.
	// Each is an interface with both in-process and ZAP-RPC implementations.
	IAM      IAMClient
	KMS      KMSClient
	Base     BaseClient
	Commerce CommerceClient
	// AI runs CHAT COMPLETIONS (a WRITE endpoint): agents, guide, crm, content,
	// sitegen, code /ask. It authenticates with the binary's IAM M2M identity — a
	// completions-capable credential — NEVER the read-only publishable (pk-) embed
	// key, which the gateway 403s on any write endpoint.
	AI AIClient
	// Embed runs EMBEDDINGS (a READ-ONLY endpoint): code-index + KB knowledge. This
	// is the ONLY consumer of the read-only publishable (pk-) key (CLOUD_AI_API_KEY),
	// the correct least-privilege credential for a read-only call. Split from AI so a
	// pk- embed key can never leak onto the completions path (the intermittent-403
	// bug). Falls back to the AI (M2M) resolution when no static embed key is set.
	Embed AIClient
	O11y  O11yClient
	VFS   VFSClient
	MQ    MQClient

	// Payments + Vault stay out-of-process (PCI scope isolation per
	// HIP-0106). These clients always resolve to ZAP-RPC implementations,
	// never in-process.
	Payments PaymentsClient
	Vault    VaultClient

	// Metering is the canonical commerce billing client used by the
	// request-edge BillingGate. It speaks net/http to commerce's billing API
	// (separate from the ZAP Commerce client above, which is for typed
	// inter-subsystem calls). Nil or not-Enabled() makes the gate a no-op.
	Metering *metering.Client

	// Audit is the tamper-evident, append-only audit trail Recorder (FedRAMP AU-*
	// / SOC 2 CC-*). Serve constructs it once, wires the AuditTrail middleware to
	// it, and hands it here so the /v1/admin/audit query + /v1/admin/audit/verify
	// endpoints read the SAME store the middleware writes. Nil makes the audit
	// middleware a no-op and the query endpoint fall back to the IAM proxy (an
	// unconfigured deployment is never blocked). See audit/ and audit_middleware.go.
	Audit *audit.Recorder

	// GatewayPolicy is the runtime-mutable edge-policy store (the /v1/gateway
	// config plane): CORS allowlist + pre-auth per-IP flood cap (platform scope)
	// and the authenticated per-org rate ceiling. BuildDeps constructs it once,
	// layered over the static env/flag defaults; the EdgeCORS/EdgeRateLimit
	// middleware read its PLATFORM policy live and ScopeRateLimit reads its
	// per-org OrgRPM, and the clients/gateway subsystem serves GET/PUT over the
	// SAME store. Never nil — New always returns a working (static-only on store
	// error) *Store, so the edge is never blocked. See clients/edge.
	GatewayPolicy *edge.Store
}

Deps is the shared dependency surface passed to every subsystem's Mount(app, deps) function. Subsystems consume only what they need.

In-process: each Client below resolves to a direct Go method-call implementation. Out-of-process (legacy split deploys): the same Client resolves to a ZAP-RPC implementation. Subsystem code does not branch on which mode; the interface is the contract.

func BuildDeps

func BuildDeps(cfg *Config) Deps

BuildDeps constructs the Deps used by every subsystem's Mount(app, deps).

Wiring rules per HIP-0106 inter-subsystem contract:

  1. If the subsystem is enabled in this process, the Client field is left nil here. The subsystem's own Mount() will install a typed in-process Client into Deps via the SetClient helpers exposed by this package. (Subsystem Mounts run after BuildDeps; they have full access to construct their concrete implementation, and the resulting object goes back into Deps for everyone else to call.)

  2. If the subsystem is disabled but cfg has a non-empty ZAP RPC endpoint for it, the Client field gets a ZAP-RPC stub targeting that endpoint. Subsystem code calls deps.X.Foo(...) without knowing the call goes over the wire.

  3. If the subsystem is disabled AND there is no endpoint, the Client field gets a "disabled" stub that fails closed with a clear error. Mount-time consumers detect this with clients.IsDisabled(err) and log a friendly "dep X needed by Y not configured" message.

JSON does not appear in any of these paths. Inter-subsystem calls are ZAP-typed Go values either via direct method dispatch (mode 1) or via ZAP RPC over the wire (mode 2). JSON happens only at the gateway/ingress edge, through the zip jsonenc helper.

Payments and Vault are special: they are NEVER in-process per HIP-0106 solo-vault CDE. Their clients always resolve via clients.PaymentsRPCAt / clients.VaultRPCAt; the disabled stub fires when no endpoint is configured.

type Durability added in v1.801.191

type Durability = org.Durability

Durability wires an OrgStore's per-org files through the HA-durable path (github.com/hanzoai/cloud/internal/org): each store is owned by the ha-elected single writer for its org, hydrated from the object store on open, and its writes shipped back fenced by the lease round. It is the per-deployment factory (one election+fence over one object store); a possibly-nil value means local-only (dev/single-node), the open path unchanged.

type EmbedRequest added in v1.786.216

type EmbedRequest = types.EmbedRequest

type GitImportReq added in v1.801.23

type GitImportReq struct {
	Org, Project, Repo string
	CloneURL           string // https://github.com/<owner>/<repo>.git (we construct it)
	Token              string // installation access token; env-only downstream, never argv/logs
	MirrorURL          string // outbound target to register; "" ⇒ don't register
}

GitImportReq imports one external repo into the native git server: create the (Org, Project, Repo) repo if absent, then force-fetch every ref from CloneURL using the short-lived installation Token (mirror-in). Idempotent — a re-import is a re-fetch. When MirrorURL is non-empty an outbound mirror target is registered so a later native push force-safe-mirrors back to the same remote.

type GitImporter added in v1.801.23

type GitImporter interface {
	ImportRepo(ctx context.Context, req GitImportReq) error
	InboundSync(ctx context.Context, req GitInboundReq) (GitSyncResult, error)
	RepoStatus(ctx context.Context, org, project string, names []string) (map[string]GitRepoStatus, error)
}

GitImporter is the git object-plane seam clients/git registers at Mount.

type GitInboundReq added in v1.801.23

type GitInboundReq struct {
	Org, Project, Repo string
	Branch             string // short branch name (refs/heads/<Branch>)
	CloneURL           string
	Token              string
	Origin             string // source host, e.g. "github.com"
}

GitInboundReq fast-forward-only advances ONE branch from an upstream push (a signature-verified webhook). Native is CANONICAL: the fetch NEVER force- overwrites a native ref — a divergence is reported as a Conflict and native is left unchanged (the split-brain guard). Origin stamps the source host so the outbound mirror suppresses the echo (loop prevention).

type GitMirrorController added in v1.801.59

type GitMirrorController interface {
	EnsureMirror(ctx context.Context, org, project, repo, url string, enabled bool) error
}

GitMirrorController lets the sync engine's git provider ENSURE or REMOVE a native repo's outbound mirror target without importing clients/git (which owns the per-org repo store + the mirror_out reactor that does the actual pushing). enabled=true registers the target (idempotent); enabled=false removes it. The push itself stays with mirror_out on the native push lifecycle — the engine only declares the target, exactly the "cloud ensures the mirror exists; the git plane does the pushing" split.

type GitPushEvent added in v1.786.216

type GitPushEvent struct {
	Org      string
	Project  string
	Repo     string
	Branch   string
	Commit   string
	CloneURL string
}

GitPushEvent describes a push that just landed on the embedded git server: the org, the repo, the branch that moved, and its new tip commit. CloneURL is the canonical clone URL of that repo (https://<host>/v1/git/<org>/<repo>.git) — the exact value an Application's RepoURL carries — so the builder can resolve which app (if any) tracks this branch and needs a rebuild.

type GitRepoStatus added in v1.801.23

type GitRepoStatus struct {
	Imported     bool  // a native repo exists for this name
	Conflict     bool  // a branch diverged on a prior inbound sync (native preserved)
	LastSyncedAt int64 // unix seconds of the last import/sync (0 = never)
}

GitRepoStatus is the per-repo import + sync status for the console repo list.

type GitSyncResult added in v1.801.23

type GitSyncResult struct {
	Applied  bool   // native advanced (fast-forward); a push.landed was emitted
	NoOp     bool   // already up to date (tip equal — the loop echo) or not imported
	Conflict bool   // native diverged; native was NOT overwritten (split-brain guard)
	Detail   string // human reason (conflict / skip)
	Before   string // native tip before (set on Applied)
	After    string // native tip after (set on Applied)
}

GitSyncResult is the outcome of an inbound fast-forward.

func InboundGitSync added in v1.801.23

func InboundGitSync(ctx context.Context, req GitInboundReq) (GitSyncResult, error)

InboundGitSync fast-forward-only advances one native branch from an upstream push. Never force-overwrites native; a divergence returns Conflict.

type IAMClient

type IAMClient = types.IAMClient

type IntentRequest

type IntentRequest = types.IntentRequest

type IntentResponse

type IntentResponse = types.IntentResponse

type IntentStatus

type IntentStatus = types.IntentStatus

type IssueSink added in v1.801.218

type IssueSink func(ctx context.Context, in IssueUpsert) (IssueUpsertResult, error)

IssueSink is the tracker's upsert entry the sink registers at Mount; feeders reach it via UpsertIssue. A function, not a tracker noun — the one implementation (clients/tracker) registers it, and the feeders never see the store.

type IssueUpsert added in v1.801.218

type IssueUpsert struct {
	Org         string
	Project     string
	ProjectKey  string
	ProjectName string
	Repo        string
	ExtRef      string
	Kind        string
	Source      string
	Title       string
	Description string
	State       string // "open" | "closed"
	Assignee    string
	Labels      []string
}

IssueUpsert is a provider-agnostic external work item mirrored into the native tracker, keyed idempotently by ExtRef so a webhook redelivery or a backfill re-run UPDATES the same row instead of duplicating it. Flat + string-typed so it crosses the feeder→tracker seam without importing the tracker's domain types.

  • Org the tenant (resolved from the signed installation, never a header).
  • Project the IAM project scope; "" ⇒ the org's default project store.
  • ProjectKey the tracker team the item files under (e.g. "GH"); ensured on first use.
  • ProjectName the display name for that team when it is first created (e.g. "GitHub").
  • Repo the git repo the item belongs to — the per-repo filter discriminator.
  • ExtRef the external anchor + idempotency key (e.g. "github:owner/repo#123").
  • Kind/Source what it IS / which surface opened it ("issue"|"pr" / "git").
  • State the upstream open/closed state; the tracker maps it to a board column.
  • Labels upstream label names (the tracker joins them for storage).

type IssueUpsertResult added in v1.801.218

type IssueUpsertResult struct {
	Created    bool
	Number     int
	Identifier string // KEY-<number>
}

IssueUpsertResult reports what the upsert did — Created (a new row) vs updated, plus the tracker identity, so a feeder can log/count precisely (the backfill count).

func UpsertIssue added in v1.801.218

func UpsertIssue(ctx context.Context, in IssueUpsert) (IssueUpsertResult, error)

UpsertIssue mirrors one external work item into the native tracker via the registered sink. Fails closed when the tracker is unmounted.

type KMSClient

type KMSClient = types.KMSClient

type Licence added in v1.801.242

type Licence uint8

Licence is a subscription authority's ANSWER about one caller, already resolved. The zero value is LicenceUnknown, which is the honest default: a question that could not be asked has no answer, and "no answer" is never "not licensed".

const (
	// LicenceUnknown — the authority could not answer (commerce absent, query
	// failed, nil result). NOT a statement about the caller.
	LicenceUnknown Licence = iota
	// LicenceNone — the authority answered: no live subscription.
	LicenceNone
	// LicenceActive — the authority answered: a live subscription.
	LicenceActive
)

type LicenseEntitlement

type LicenseEntitlement = types.LicenseEntitlement

type LifecycleEvent added in v1.800.1

type LifecycleEvent struct {
	Kind     LifecycleKind
	Org      string
	Project  string
	Repo     string
	Branch   string
	Before   string
	After    string
	Pusher   string
	DeployID string
	Detail   string
	Origin   string
}

LifecycleEvent is one git lifecycle fact fanned out to every registered subscriber. A plain data value — values, not places:

  • Org/Project/Repo the tenant + repo the fact happened in (the routing key).
  • Branch/Before/After the ref that moved and its old→new tip (a push).
  • Pusher who pushed (best-effort; "" for a client-less push).
  • DeployID/Detail the deployment id + a human one-liner (a deploy transition).
  • Origin "" for a native push; the source host when the refs arrived via an inbound mirror sync — the loop-prevention seam that lets the outbound mirror subscriber suppress a re-mirror of refs it just pulled in.

type LifecycleKind added in v1.800.1

type LifecycleKind string

LifecycleKind classifies a git lifecycle event. The value IS the wire name a subscription filters on.

const (
	LifecyclePushLanded   LifecycleKind = "push.landed"
	LifecycleBuildStarted LifecycleKind = "build.started"
	LifecycleDeployLive   LifecycleKind = "deploy.live"
	LifecycleDeployFailed LifecycleKind = "deploy.failed"
)

type MQClient

type MQClient = types.MQClient

type MountFunc

type MountFunc func(app Router, deps Deps) error

MountFunc is a subsystem's mount contract: register your routes on app, using deps for everything shared. Every subsystem in the fleet exports exactly this signature, so Wire references each one directly and the compiler checks it.

app is a Router, not the concrete *zip.App, and that is the whole safety property: middleware a subsystem installs lands on the subtrees its MountSpec declares, never over the binary. Routes register exactly as before — absolute paths, same precedence. See scope.go. A subsystem that genuinely gates everything says so with Global: true and gets the bare app.

func Global added in v1.801.242

func Global(fn func(*zip.App, Deps) error) MountFunc

Global adapts a subsystem whose Mount still takes the concrete *zip.App into a MountFunc. It exists for the linked modules cloud does not own — they cannot take cloud.Router until their own module takes it — and it only works on a spec that also declares Global: true, because the bare app is the only Router that IS a *zip.App. Anything else fails the mount at boot rather than silently.

type MountSpec

type MountSpec struct {
	Name     string
	Mount    MountFunc
	Shutdown ShutdownFunc // optional; nil means the subsystem has nothing to tear down.

	// OwnsHealth marks a subsystem that serves its OWN GET /v1/<name>/health
	// (a real, fail-closed probe). Serve's generic liveness loop skips these so
	// its always-ok route never shadows the subsystem's real probe.
	OwnsHealth bool

	// Prefixes are the route subtrees whose middleware this subsystem may install.
	// Empty means the convention it already follows — /v1/<Name>, the same subtree
	// Serve's generic liveness route assumes — so only a subsystem that gates
	// something else has to name it. It bounds MIDDLEWARE, not route registration:
	// routes still register at absolute paths anywhere, as they always have.
	Prefixes []string

	// Global says this subsystem gates the whole binary and receives the bare
	// *zip.App. It is the one way to reach app-wide middleware, so every grant is a
	// decision someone made in writing, and apps.TestWireFrozen fails on a new one.
	// Today it is held only by linked modules whose own Mount still takes *zip.App
	// (see cloud.Global) — none of which installs middleware.
	Global bool
}

MountSpec describes one subsystem to mount. There is NO Order field: the slice position in apps.Wire() IS the mount order — the composition root lists subsystems in the exact sequence they mount (and, reversed, tear down), so order is data read top-to-bottom in one file, not ints scattered across the tree.

type O11yClient

type O11yClient = types.O11yClient

type Org

type Org = types.Org

type OrgConfig added in v1.801.59

type OrgConfig = types.OrgConfig

OrgConfig and LicenseEntitlement are the two values CommerceClient's methods name. Both are aliased here for the same reason the interface is: a subsystem that implements CommerceClient (or fakes it in a test) must be able to spell its signature using only this package. LicenseEntitlement was aliased and OrgConfig was not, which made the exported interface unimplementable from outside without reaching into cloud/types — an omission, not a boundary.

type OrgScopeResolver added in v1.786.216

type OrgScopeResolver interface {
	// ProjectOwnership reports, for the project addressed by idOrSlug:
	//   mine  — org itself owns a project with this id/slug,
	//   other — some org OTHER than org owns a project with this id/slug.
	// A store failure is returned as err; the boundary then fails CLOSED (refuses
	// the claim) so a transient registry error can never let a cross-org claim
	// through.
	ProjectOwnership(ctx context.Context, org, idOrSlug string) (mine, other bool, err error)
}

OrgScopeResolver reports the ownership of a project identifier relative to an org, WITHOUT this package importing the registry that holds it. The identifier may be a slug or an opaque id — the implementation matches whichever.

type OrgStore added in v1.786.216

type OrgStore[T io.Closer] struct {
	// contains filtered or unexported fields
}

OrgStore is the lazily-opened, cached set of per-org stores of type T for one subsystem, each keyed by its resolved DB path so an org's SQLite file is opened (and migrated) exactly once. It is the caching layer over OrgDB: every open routes through the same path resolver and pragmas, so there is ONE way a subsystem opens its org DBs and ONE hand-rolled map is replaced by this shared value. T is the subsystem's own store handle (it owns its schema via the open func's migration); T must Close its DB.

func NewOrgStore added in v1.786.216

func NewOrgStore[T io.Closer](dataDir, subsystem string, open func(*sql.DB) (T, error), opts ...OrgStoreOption) *OrgStore[T]

NewOrgStore builds a per-org store cache for subsystem under dataDir. open wraps a freshly-opened *sql.DB (already pragma'd by OrgDB) into the subsystem's store handle, running its migration; it is called once per org file. Pass WithDurable to route every file through the HA-durable path; with no options the cache is exactly the local-only one it has always been.

func (*OrgStore[T]) CloseAll added in v1.786.216

func (c *OrgStore[T]) CloseAll() error

CloseAll closes every open per-org store. Idempotent; returns the first close error, if any.

func (*OrgStore[T]) Each added in v1.801.186

func (c *OrgStore[T]) Each(fn func(slug string, st T, err error)) error

Each folds fn over every org that has a {subsystem} store on disk under {dataDir}/orgs, handing it the org's SLUG (the on-disk directory name) and the SAME cached store handle For returns (opened through forPath, keyed by path — no second open). It is the cross-org sweep primitive a reconciler folds over: the filesystem is the source of truth for "which orgs have this store", so no derived registry can drift. The reserved platform partitions ({dataDir}/orgs/_*) are skipped (their '_' is a rune SanitizeOrg never emits, so no real org is dropped). A per-org OPEN failure is passed to fn as its err (fn decides skip vs. record); a missing orgs root (a writer with no stores yet) is not an error. Under horizontal sharding each writer's PVC holds only the orgs routed to it, so Each on a given writer enumerates exactly that writer's orgs.

func (*OrgStore[T]) For added in v1.786.216

func (c *OrgStore[T]) For(orgID, project string) (T, error)

For returns the store for (org, project), opening and migrating it on first use and caching it thereafter. Pass project=="" for an org-scoped subsystem; pass principal.Project(c) for a project-scoped one. Isolation is PHYSICAL: a distinct (org[, project]) resolves to a distinct file, so a query in one can never reach another's rows.

func (*OrgStore[T]) Sync added in v1.801.191

func (c *OrgStore[T]) Sync(orgID, project string) (acked bool, err error)

Sync ships the org's local file to its durable object, fenced at the lease round (the ship-before-ack step a durable subsystem calls after a write commits). It returns acked=false when this replica is not the owner or was deposed mid-request (the caller retries on the new owner). On a local-only store (no Durability) it is a successful no-op — the write is already as durable as configured. project is "" for an org-scoped subsystem.

type OrgStoreOption added in v1.801.191

type OrgStoreOption func(*orgStoreOpts)

OrgStoreOption configures optional OrgStore behavior. With no options an OrgStore is exactly the local-only cache it has always been (cek open, no ship).

func WithDurable added in v1.801.191

func WithDurable(dur *Durability) OrgStoreOption

WithDurable routes every per-org file through the HA-durable path. A nil dur is a no-op (local-only), so a caller passes its deployment's possibly-nil Durability directly and the store degrades to local on a deployment without an object store.

func WithStoreLogger added in v1.801.191

func WithStoreLogger(log luxlog.Logger) OrgStoreOption

WithStoreLogger sets the logger used to report a degraded hydrate (the store still opens; the message is the operator's signal that a durable open ran read-only).

type PaymentsClient

type PaymentsClient = types.PaymentsClient

type PlanChecker added in v1.801.242

type PlanChecker interface {
	ActivePaidPlan(ctx context.Context, org string) (tier string, paid bool, err error)
}

PlanChecker is the ONE commerce read this gate needs: does org X hold a LIVE (active or trialing) PAID plan? It is a consumer-defined interface satisfied structurally by the co-resident commerce client (clients/commerce.ActivePaidPlan) — an OPTIONAL capability resolved from Deps.Commerce by type-assertion, so the narrow types.CommerceClient interface is untouched and a commerce build that cannot answer (split deploy / disabled stub) simply yields LicenceUnknown.

  • (tier, true, nil) -> LicenceActive.
  • ("", false, nil) -> LicenceNone: resolved, no live paid plan.
  • (_, _, err) -> LicenceUnknown: machinery failure, never a "no".

type Refusal added in v1.801.242

type Refusal struct {
	Error   string `json:"error"`             // stable machine code: always "payment_required"
	Product string `json:"product,omitempty"` // the gated product id, when the gate is product-scoped
	Reason  string `json:"reason"`            // "unpaid" | "unresolved"
	Message string `json:"message"`           // one human sentence
	Cure    []Cure `json:"cure"`              // the ways to fix it, in the order to offer them
}

Refusal is the 402 body. A bare 402 is useless to the console shell, so this names WHAT is gated, WHY, and every way to cure it — one Cure per admit leg, so the body is the structural mirror of the predicate and can never drift from it.

The cure paths are RELATIVE and same-origin, deliberately: a hard-coded cloud.hanzo.ai would brand a Lux / Zoo / Pars deployment as Hanzo, and this binary white-labels by host. They point at the two API surfaces the shell already reads and that Reachable guarantees are never gated — /v1/plans (what to buy, with prices) and /v1/billing (where to pay, subscribe or top up).

type ResourceMeter added in v1.786.1

type ResourceMeter struct {
	// contains filtered or unexported fields
}

ResourceMeter gates and meters per-org spend for non-LLM resource creation, reusing Deps.Metering (the single commerce billing client). Build it with NewResourceMeter. A nil meter, or one whose commerce URL is unset, makes Gate allow and Meter a no-op — so an unconfigured deployment is never blocked, exactly like BillingGate.

func NewResourceMeter added in v1.786.1

func NewResourceMeter(deps Deps, provider string) *ResourceMeter

NewResourceMeter builds a ResourceMeter from the shared deps. provider labels the recorded usage so spend is attributable to the surface that metered it.

func (*ResourceMeter) Enabled added in v1.786.1

func (rm *ResourceMeter) Enabled() bool

Enabled reports whether billing will actually enforce (a commerce URL is configured). When false, Gate allows and Meter is a no-op.

func (*ResourceMeter) Gate added in v1.786.1

func (rm *ResourceMeter) Gate(ctx context.Context, org, project string, projectValidated bool, kind string, costCents int64) error

Gate is the pre-create balance gate. It returns:

nil                              -> allow (balance positive, OR not priced,
                                    OR billing not configured).
metering.ErrInsufficientBalance  -> deny, out of funds (render 402).
other error                      -> balance unknown; fail-closed denies
                                    (render 503). Fail-open returns nil.

costCents<=0 means the kind is free → no gate (mirrors BillingGate's price==0 short-circuit). org MUST be the caller's resolved slug; it is sent as the commerce user AND X-Org-Id so the CALLER's ledger is checked, overriding the client default org — the anti-cross-org property. The balance check honors ctx (a client disconnect/timeout cancels it).

costCents is forwarded as AuthInput.AmountCents so the gate enforces available >= costCents, not merely available > 0 — otherwise a 1-cent balance would authorize an arbitrarily expensive charge (the debit still lands, taking the ledger negative). This mirrors what a prepaid gate must do: refuse a request the balance cannot cover BEFORE the work runs. project + projectValidated are the caller's org SUB-SCOPE and whether it is bound to a VALIDATED identity claim — principal.ValidatedProject(c), the SAME signal the edge BillingGate threads. When validated, a project-scoped spend cap (issue #70) on (project, provider) HARD-enforces (402) on resource creation exactly as on the request edge; when not, it DEGRADES to soft (org- and service-scoped caps stay hard), so a forgeable X-Project-Id can neither hard-stop nor be evaded. service is intrinsically this meter's provider. Pass ("", false) on a background/no-principal path (org- and service-scoped caps only).

func (*ResourceMeter) Meter added in v1.786.1

func (rm *ResourceMeter) Meter(org, project, kind string, amountCents int64, requestID, clientIP string)

Meter records a successful charge to the caller's org ledger. It is the ONE metering entry point for BOTH the one-time create fee AND any recurring footprint charge (storage GB-month, GPU-hour): the caller supplies the amount, so a future recurring meter reuses this same method with a usage-derived amount. No-op when billing is not configured or amountCents<=0.

The debit is fire-and-forget on a background context: the resource already exists, so the charge must never block or corrupt the response the caller received, and a request-context cancellation must not cancel the debit (mirror of BillingGate). A debit failure is logged for reconciliation, not swallowed.

func (*ResourceMeter) MeterUsage added in v1.786.32

func (rm *ResourceMeter) MeterUsage(org, kind string, u metering.Usage)

MeterUsage is the general-purpose per-org debit: it records the caller-built usage event after forcing the per-org billing invariants that make the debit land on the CALLER's ledger and never another org's:

  • u.User and u.Org are OVERWRITTEN to the caller's org slug (the per-org prepaid billing key + the X-Org-Id namespace) — a caller can never bill someone else, and a surface can't accidentally leave them unset (which would debit the client-default org).
  • Provider defaults to the meter's provider; Status defaults to "success"; Currency defaults to "usd".

Everything else the caller supplies (AmountCents, Model, Actor, RequestID, token counts, ClientIP) flows through so a metered surface can attribute spend richly. Like Meter it is fire-and-forget on a background context and a no-op when billing is unconfigured or AmountCents<=0. kind is for the failure log.

type Router added in v1.801.242

type Router interface {
	Use(handlers ...zip.Handler) zip.Router

	Get(path string, handlers ...zip.Handler) zip.Router
	Post(path string, handlers ...zip.Handler) zip.Router
	Put(path string, handlers ...zip.Handler) zip.Router
	Patch(path string, handlers ...zip.Handler) zip.Router
	Delete(path string, handlers ...zip.Handler) zip.Router
	Head(path string, handlers ...zip.Handler) zip.Router
	Options(path string, handlers ...zip.Handler) zip.Router
	All(path string, handlers ...zip.Handler) zip.Router

	Group(prefix string, handlers ...zip.Handler) zip.Router

	Fiber() *fiber.App
}

Router is the surface a subsystem mounts on: zip's routing methods, plus the *fiber.App escape the in-process dispatchers need (fiber.Test, GetRoutes, adaptor.FiberApp). *zip.App satisfies it as-is, so Serve can hand the bare app to a Global subsystem and tests can pass a raw app.

Fiber() is a deliberate, named hole: it is the concrete engine, and middleware installed through it is app-wide. It is promoted onto the scoped Router rather than granting those subsystems Global — the alternative was four more Globals for four read-only uses. Its callers are greppable and none of them registers middleware.

type Service added in v1.786.216

type Service[S any] struct {
	Base
	State S
}

Service is THE subsystem value: the shared Base plus the subsystem's own typed State. One generic type across the whole binary; S is plain data (the package's fields). A handler is a free function `func(*Service[S], *zip.Ctx) error` bound with Handle — a package declares no service type, only its State.

type ServiceReleaseEvent added in v1.801.7

type ServiceReleaseEvent struct {
	Service string
	Image   string
	SHA     string
}

ServiceReleaseEvent describes a proven, clean-semver image ready to roll live on an operator-managed first-party service. It is the payload of the release seam that closes push→build→image→CR: after a build produces the image, the CR for this service is patched to it and the operator reconciles the Deployment.

  • Service is the target CR metadata.name (the repo/service name ⇒ CR name, mirroring universe's image-update.yml convention).
  • Image is the full registry ref (repository:tag); the tag MUST be clean semver (vX.Y.Z) — the releaser refuses every mutable/sha/suffixed form.
  • SHA is the source commit for provenance (optional; logged, never gated on).

type ShutdownFunc added in v1.786.32

type ShutdownFunc func(ctx context.Context) error

ShutdownFunc releases a subsystem's process-lifetime resources (background goroutines, open DB handles) on graceful shutdown. It must be idempotent and bounded — Serve calls it within the shutdown deadline. ctx carries that deadline so a slow teardown is cut off rather than hanging SIGTERM.

type Span

type Span = types.Span

type Standing added in v1.801.242

type Standing uint8

Standing is a caller's resolved commercial standing. The zero value is Unknown, which is the honest default: a question not yet asked has no answer, and "no answer" is never "has not paid".

const (
	// Unknown — at least one authority could not answer (commerce unreachable,
	// ledger unreadable, org unresolvable). NOT a statement about the caller.
	Unknown Standing = iota
	// Unpaid — BOTH authorities answered and both said no: no subscription and no
	// credit. The only proven refusal.
	Unpaid
	// Subscribed — a live subscription admits the caller.
	Subscribed
	// Funded — the wallet holds a positive prepaid balance to burn down.
	Funded
)

func Stand added in v1.801.242

func Stand(ctx context.Context, lic Licence, w principal.Wallet) Standing

Stand composes the two independent legs into the one answer.

lic — the subscription authority's already-resolved answer.
w   — the money address the credit leg reads (principal.WalletOf).

The legs are evaluated cheapest-decisive-first: a licensed caller never touches the ledger. A caller with no subscription always does — that is the pay-as-you-go path, and it is the common case for a prepaid customer.

func (Standing) Admits added in v1.801.242

func (s Standing) Admits() bool

Admits reports whether this standing lets a request through on its own merits. Unknown does NOT admit here — it is not an admit, it is an absence, and the posture that resolves it is enforcement's, deliberately not hidden inside this predicate.

func (Standing) String added in v1.801.242

func (s Standing) String() string

String renders the standing for logs.

type SyncEvent added in v1.801.59

type SyncEvent struct {
	Kind     string // sync kind, e.g. "git"
	Provider string // endpoint the event came from: "github" | "gitlab" | "hanzo-git"
	Org      string // tenant (from the signed installation / gateway identity)
	Locator  string // source repo locator (a clone URL, or "<org>/<repo>")
	Repo     string // short repo name (git)
	Branch   string
	Before   string
	After    string
	Actor    string // who made the upstream push — the loop guard compares it to the sync's own Actor
	Token    string // OPTIONAL short-lived credential the trigger already minted (git: installation token); never logged
	Manual   bool   // a manual /run or an initial sync reconcile (no specific push)
	Hop      int    // chained-propagation depth (bounded by the engine's hop limit)
}

SyncEvent is a provider-agnostic sync trigger. A webhook (GitHub push, Gitea push) or a manual run builds one and hands it to the registered engine via Sync; the engine resolves the Syncs whose SOURCE matches (Provider, Locator/Repo) for the org and applies each. Flat + string-typed so it crosses the trigger→ engine seam without importing the engine.

type SyncFunc added in v1.801.59

type SyncFunc func(ctx context.Context, ev SyncEvent) (SyncResult, error)

SyncFunc is the reconcile entry the universal sync engine registers — a function, not an engine noun. The one implementation (clients/sync) registers it at Mount; triggers reach it via Sync.

type SyncResult added in v1.801.59

type SyncResult struct {
	Ran     int // syncs that reconciled a change
	Skipped int // syncs resolved but skipped (loop guard / idempotent / direction off)
}

SyncResult is the outcome of dispatching one SyncEvent across the resolved syncs.

func Sync added in v1.801.59

func Sync(ctx context.Context, ev SyncEvent) (SyncResult, error)

Sync dispatches one event to the registered reconcile func. Fails closed when unmounted.

type Timing

type Timing = types.Timing

type TokenValidator added in v1.801.108

type TokenValidator struct {
	// contains filtered or unexported fields
}

TokenValidator verifies IAM access tokens exactly as the identity boundary does. Safe for concurrent use; the underlying JWKS cache is shared and stale-on-error.

func NewTokenValidator added in v1.801.108

func NewTokenValidator(issuer string) *TokenValidator

NewTokenValidator builds a validator bound to issuer, with the SAME JWKS endpoint SanitizeIdentity uses — jwksURLFor is the single source for both, so a token this accepts is a token the boundary accepts, and the two can never drift apart into a mint-then-refuse loop.

func (*TokenValidator) Validate added in v1.801.108

func (t *TokenValidator) Validate(raw string) (VerifiedIdentity, error)

Validate verifies raw and returns what it proved. The error is the real reason (untrusted issuer, audience, expired, no matching key) so an operator reading a failed sign-in learns which knob is wrong instead of seeing a bare refusal.

Fails closed on every path: a nil validator, an unparseable token, a token whose claims do not check out. It NEVER returns a partially-trusted identity.

type User

type User = types.User

type VFSClient

type VFSClient = types.VFSClient

type VaultChargeRequest

type VaultChargeRequest = types.VaultChargeRequest

type VaultChargeResponse

type VaultChargeResponse = types.VaultChargeResponse

type VaultClient

type VaultClient = types.VaultClient

type VerifiedIdentity added in v1.801.108

type VerifiedIdentity struct {
	// Owner is the validated `owner` claim — the IAM org. This is the value the
	// SuperAdmin predicate compares against the reserved admin org.
	Owner string
	// User is the canonical user id (sub, then preferred_username, then name).
	User string
	// Username is the IAM username — the `name` half of `<owner>/<name>`.
	Username string
	// Email is the validated `email` claim, when present.
	Email string
	// IsAdmin is IAM's `isAdmin` bit: admin OF ONE'S OWN ORG. It is NOT the
	// SuperAdmin predicate — that is Owner == the reserved admin org, and
	// conflating the two is a privilege escalation. Reported so a caller can tell
	// an org admin from a plain member, never as the platform gate.
	IsAdmin bool
	// Orgs is the validated `orgs` membership-set claim — every org the subject
	// may act in (the HOME org first, then explicit team memberships), each with
	// its coarse role (owner | admin | member). It is the Slack-model tenancy set
	// a caller enumerates cross-org surfaces against (hanzo.team unions a user's
	// workspaces across it) with NO IAM round-trip. Empty on a token minted before
	// the claim shipped (iam < 1.31.34); a reader then falls back to the single
	// Owner org. Verified off the SAME signed token as Owner — never trusted raw.
	Orgs []model.OrgRef
	// Expiry is the token's own `exp`. A session built on this token must not
	// outlive it.
	Expiry time.Time
}

VerifiedIdentity is what a token PROVED, after signature, issuer and expiry all checked out. It is deliberately the small subset a caller can act on; the authorization decision still belongs to the caller (deploy compares Owner to the admin org) and, independently, to SanitizeIdentity on every later request.

Directories

Path Synopsis
Package apps is the composition root: the single, explicit list of which Hanzo cloud subsystems are linked into the binary AND the order they mount in.
Package apps is the composition root: the single, explicit list of which Hanzo cloud subsystems are linked into the binary AND the order they mount in.
Package audit is the unified cloud binary's compliance-grade audit trail — tamper-evident, append-only, and complete over the security-relevant request surface (FedRAMP AU-* / SOC 2 CC-* controls).
Package audit is the unified cloud binary's compliance-grade audit trail — tamper-evident, append-only, and complete over the security-relevant request surface (FedRAMP AU-* / SOC 2 CC-* controls).
Package cek is cloud's ONE encryption-at-rest gate for its per-subsystem SQLite stores.
Package cek is cloud's ONE encryption-at-rest gate for its per-subsystem SQLite stores.
Package cli is the Hanzo cloud-control CLI — the gcloud/doctl-class client half of the `hanzo` binary.
Package cli is the Hanzo cloud-control CLI — the gcloud/doctl-class client half of the `hanzo` binary.
Package clients holds the canonical ZAP-typed inter-subsystem clients used by cloud.Deps.
Package clients holds the canonical ZAP-typed inter-subsystem clients used by cloud.Deps.
account
Package account mounts the signed-in caller's OWN account self-service surface natively in the unified cloud binary — the Go port of the console's two NON-proxy Next server routes (app/keys + app/onboard) plus the money/store data bridges the statically-exported console needs (task #41, "True 1-binary FE").
Package account mounts the signed-in caller's OWN account self-service surface natively in the unified cloud binary — the Go port of the console's two NON-proxy Next server routes (app/keys + app/onboard) plus the money/store data bridges the statically-exported console needs (task #41, "True 1-binary FE").
admin
Package admin mounts the god-mode admin surface (/v1/admin/*) the Hanzo Admin Console (admin.hanzo.ai, apps/operator) calls, per the api.ts contract.
Package admin mounts the god-mode admin surface (/v1/admin/*) the Hanzo Admin Console (admin.hanzo.ai, apps/operator) calls, per the api.ts contract.
admin/audit
Package audit is the /v1/admin/audit query surface, wired to cloud's REAL tamper-evident audit store (the audit.Recorder Serve builds and hands over via deps.Audit).
Package audit is the /v1/admin/audit query surface, wired to cloud's REAL tamper-evident audit store (the audit.Recorder Serve builds and hands over via deps.Audit).
admin/commerce
Package commerce is the admin cockpit's typed reader for the commerce billing plane.
Package commerce is the admin cockpit's typed reader for the commerce billing plane.
admin/core
Package core is the shared kernel of the admin subsystem: the resolved upstream clients (State) plus the one-copy business primitives every admin domain composes — the two-tier gate, the /v1 envelope writers, the tenant-scope predicate, the IAM fan-in, the single credit-grant path, the tamper-evident audit emit, and the fleet activity/time-series model.
Package core is the shared kernel of the admin subsystem: the resolved upstream clients (State) plus the one-copy business primitives every admin domain composes — the two-tier gate, the /v1 envelope writers, the tenant-scope predicate, the IAM fan-in, the single credit-grant path, the tamper-evident audit emit, and the fleet activity/time-series model.
admin/customer
Package customer is the CUSTOMER management surface (/v1/admin/customers*) — the operator cockpit's core: the live fleet customer list (incl.
Package customer is the CUSTOMER management surface (/v1/admin/customers*) — the operator cockpit's core: the live fleet customer list (incl.
admin/digitalocean
Package digitalocean reads DigitalOcean's billing and infrastructure APIs.
Package digitalocean reads DigitalOcean's billing and infrastructure APIs.
admin/finance
Package finance is the SaaS business/finance dashboard (/v1/admin/finance) — the profitability panel: what we pay every vendor (COGS), what we earn, the gross margin, how fast we're burning the DigitalOcean promo credit, and the runway that credit + burn imply.
Package finance is the SaaS business/finance dashboard (/v1/admin/finance) — the profitability panel: what we pay every vendor (COGS), what we earn, the gross margin, how fast we're burning the DigitalOcean promo credit, and the runway that credit + burn imply.
admin/health
Package health probes an upstream's health endpoint (e.g.
Package health probes an upstream's health endpoint (e.g.
admin/iam
Package iam is the admin cockpit's typed reader for the Hanzo IAM management surface (/v1/iam/get-*).
Package iam is the admin cockpit's typed reader for the Hanzo IAM management surface (/v1/iam/get-*).
admin/infra
Package infra is the platform's DigitalOcean fleet board: the physical inventory (DOKS clusters, droplets, block-storage volumes, load balancers) cross-referenced against what every cluster's Kubernetes actually claims, with the cost of each and an orphan analysis that is safe BY CONSTRUCTION.
Package infra is the platform's DigitalOcean fleet board: the physical inventory (DOKS clusters, droplets, block-storage volumes, load balancers) cross-referenced against what every cluster's Kubernetes actually claims, with the cost of each and an orphan analysis that is safe BY CONSTRUCTION.
admin/invoices
Package invoices is the fleet INVOICE view (/v1/admin/invoices) — every issued invoice across every tenant: number, org, amount, status, issue + due date, plus the id a future detail view fetches /v1/billing/invoices/:id with.
Package invoices is the fleet INVOICE view (/v1/admin/invoices) — every issued invoice across every tenant: number, org, amount, status, issue + due date, plus the id a future detail view fetches /v1/billing/invoices/:id with.
admin/metrics
Package metrics is the fleet SaaS-operations god-view (/v1/admin/metrics) — the operator's business dashboard: MRR/ARR, net-new vs churned MRR, the plan/category mix, the top customers, and the recent subscription movements.
Package metrics is the fleet SaaS-operations god-view (/v1/admin/metrics) — the operator's business dashboard: MRR/ARR, net-new vs churned MRR, the plan/category mix, the top customers, and the recent subscription movements.
admin/money
Package money is the admin cockpit's one billing unit: USD cents as a typed value, so no field or method anywhere has to spell "Cents" again and a dollar amount can never be silently passed where cents are meant.
Package money is the admin cockpit's one billing unit: USD cents as a typed value, so no field or method anywhere has to spell "Cents" again and a dollar amount can never be silently passed where cents are meant.
admin/revenue
Package revenue is the fleet REVENUE aggregate (/v1/admin/revenue) — the operator's money board: total prepaid balances held, total realized spend, MRR, a per-customer revenue table, ARPU, and a real spend trend.
Package revenue is the fleet REVENUE aggregate (/v1/admin/revenue) — the operator's money board: total prepaid balances held, total realized spend, MRR, a per-customer revenue table, ARPU, and a real spend trend.
admin/subscriptions
Package subscriptions is the fleet SUBSCRIPTION view (/v1/admin/subscriptions) — every tenant's plan subscription: customer/org, plan, status, monthly-normalized MRR, and the current-period start/renews.
Package subscriptions is the fleet SUBSCRIPTION view (/v1/admin/subscriptions) — every tenant's plan subscription: customer/org, plan, status, monthly-normalized MRR, and the current-period start/renews.
admission
Package admission is the launch-control GATE for Hanzo's hosted services — the COMPLETE waitlist feature, COMPOSING the ONE flag engine (clients/flags) one-way.
Package admission is the launch-control GATE for Hanzo's hosted services — the COMPLETE waitlist feature, COMPOSING the ONE flag engine (clients/flags) one-way.
ads
Package ads mounts the Hanzo Cloud /v1/ads/* surface: a native-Go, per-org ad-campaign store on Base/SQLite.
Package ads mounts the Hanzo Cloud /v1/ads/* surface: a native-Go, per-org ad-campaign store on Base/SQLite.
affiliates
Package affiliates mounts the Hanzo Cloud /v1/affiliates/* partner-commission surface: a native-Go, per-org affiliate program on Base/SQLite that pays partners an ONGOING COMMISSION on the metered spend of the customers they refer.
Package affiliates mounts the Hanzo Cloud /v1/affiliates/* partner-commission surface: a native-Go, per-org affiliate program on Base/SQLite that pays partners an ONGOING COMMISSION on the metered spend of the customers they refer.
agent
Package agent mounts the hanzoai/agent orchestrator into cloud: POST /v1/agent (+ /v1/agent/presets, /v1/agent/conversations).
Package agent mounts the hanzoai/agent orchestrator into cloud: POST /v1/agent (+ /v1/agent/presets, /v1/agent/conversations).
agents
Package agents mounts the Hanzo Cloud /v1/agents surface: per-org autonomous agent definitions and their runs.
Package agents mounts the Hanzo Cloud /v1/agents surface: per-org autonomous agent definitions and their runs.
agentskills
Package agentskills serves the Agent Skills Discovery surface (/.well-known/agent-skills/) from a catalogue embedded into the ONE cloud binary.
Package agentskills serves the Agent Skills Discovery surface (/.well-known/agent-skills/) from a catalogue embedded into the ONE cloud binary.
analytics
Package analytics mounts the Hanzo Cloud /v1/analytics/* surface: a native-Go, per-org analytics read API over the `hanzo` datastore warehouse (the `datastore` cluster).
Package analytics mounts the Hanzo Cloud /v1/analytics/* surface: a native-Go, per-org analytics read API over the `hanzo` datastore warehouse (the `datastore` cluster).
ask
Package ask is the UNIFIED GROUNDED ADVISOR: POST /v1/ask.
Package ask is the UNIFIED GROUNDED ADVISOR: POST /v1/ask.
auditlog
Package auditlog mounts the ORG-SCOPED audit trail surface (GET /v1/audit): an org admin's read of THEIR OWN organization's security-relevant events off the same tamper-evident, hash-chained store the AuditTrail middleware writes and the admin god-view (/v1/admin/audit) reads.
Package auditlog mounts the ORG-SCOPED audit trail surface (GET /v1/audit): an org admin's read of THEIR OWN organization's security-relevant events off the same tamper-evident, hash-chained store the AuditTrail middleware writes and the admin god-view (/v1/admin/audit) reads.
authors
Package authors mounts the Hanzo Cloud /v1/authors/* OSS-author surface: a native-Go, per-org program on Base/SQLite that pays open-source AUTHORS a royalty on the metered platform spend of the orgs who DEPLOY their projects on Hanzo.
Package authors mounts the Hanzo Cloud /v1/authors/* OSS-author surface: a native-Go, per-org program on Base/SQLite that pays open-source AUTHORS a royalty on the metered platform spend of the orgs who DEPLOY their projects on Hanzo.
automations
Package automations mounts the Hanzo Cloud /v1/automations/* surface: the Connectors+Automations engine (HIP-0106, task #51).
Package automations mounts the Hanzo Cloud /v1/automations/* surface: the Connectors+Automations engine (HIP-0106, task #51).
base
Package base embeds the Hanzo Base app engine in-process in the unified cloud binary (the HIP-0106 base fold) — the in-binary replacement for the standalone `ghcr.io/hanzoai/superbase` pod, whose whole job was `base.New()` + serve.
Package base embeds the Hanzo Base app engine in-process in the unified cloud binary (the HIP-0106 base fold) — the in-binary replacement for the standalone `ghcr.io/hanzoai/superbase` pod, whose whole job was `base.New()` + serve.
benchmark
Package benchmark mounts the Hanzo Cloud /v1/benchmark/* surface: the native benchmark ARENA — run the top-N canonical public benchmarks against any model or endpoint, under ONE standardized harness, measure Hanzo's own models (enso, zen), and reconcile any external provider-reported claim against that measurement.
Package benchmark mounts the Hanzo Cloud /v1/benchmark/* surface: the native benchmark ARENA — run the top-N canonical public benchmarks against any model or endpoint, under ONE standardized harness, measure Hanzo's own models (enso, zen), and reconcile any external provider-reported claim against that measurement.
billing
Package billing mounts the CUSTOMER-facing, org-scoped billing surface (/v1/billing/{usage,balance,gpu-eligibility,gpu-charge,payment-methods}) on the unified cloud binary.
Package billing mounts the CUSTOMER-facing, org-scoped billing surface (/v1/billing/{usage,balance,gpu-eligibility,gpu-charge,payment-methods}) on the unified cloud binary.
blueprint
Package blueprint mounts the Hanzo Cloud /v1/blueprint/* surface: the compute-cost basis for the OSS-template economy.
Package blueprint mounts the Hanzo Cloud /v1/blueprint/* surface: the compute-cost basis for the OSS-template economy.
books
Package books is the revenue BOOKS spine: a native double-entry ledger that records hanzo.ai's real prepaid-credit revenue on per-org Base/SQLite, exposed at /v1/books.
Package books is the revenue BOOKS spine: a native double-entry ledger that records hanzo.ai's real prepaid-credit revenue on per-org Base/SQLite, exposed at /v1/books.
bots
Package bots is the CONTROL PLANE for a bot run: a task the bot runtime executes on a surface — a desktop or terminal sandbox it drives — with a LIVE session (the URL the hanzo.app /vnc panel embeds to watch/attach).
Package bots is the CONTROL PLANE for a bot run: a task the bot runtime executes on a surface — a desktop or terminal sandbox it drives — with a LIVE session (the URL the hanzo.app /vnc panel embeds to watch/attach).
campaign
Package campaign mounts the Hanzo Cloud /v1/campaign/* surface: the top-level go-to-market orchestration plane.
Package campaign mounts the Hanzo Cloud /v1/campaign/* surface: the top-level go-to-market orchestration plane.
captable
Package captable folds hanzoai/captable into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106) — the PILOT of epic #96 (fold the Captable,Inc app into cloud, drop Next.js/Prisma/Postgres).
Package captable folds hanzoai/captable into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106) — the PILOT of epic #96 (fold the Captable,Inc app into cloud, drop Next.js/Prisma/Postgres).
catalogsync
Package catalogsync is the REVERSE half of the storefront loop: it consumes the commerce COMMERCE stream and turns each `commerce.product.created` into ONE content.EnsureCatalogAsset call, so a newly-created catalog product gets its ecom asset rendered (design == slug) — the mirror of the forward edge (clients/content storefront.go) that publishes a rendered asset back onto the product image.
Package catalogsync is the REVERSE half of the storefront loop: it consumes the commerce COMMERCE stream and turns each `commerce.product.created` into ONE content.EnsureCatalogAsset call, so a newly-created catalog product gets its ecom asset rendered (design == slug) — the mirror of the forward edge (clients/content storefront.go) that publishes a rendered asset back onto the product image.
channels
Package channels is the /v1/channels transport plane: the portable chat envelope, per-org access policy (pairing / allowlist / open), a durable inbox, and outbound send across the connected chat transports (Discord, Slack, Teams, Telegram).
Package channels is the /v1/channels transport plane: the portable chat envelope, per-org access policy (pairing / allowlist / open), a durable inbox, and outbound send across the connected chat transports (Discord, Slack, Teams, Telegram).
cloudflare
Package cloudflare is the per-org Cloudflare asset plane for the unified Hanzo Cloud binary — the first-class /v1/cloudflare/* surface (sibling of /v1/dns and /v1/domain) that manages an org's Cloudflare Zones/Analytics, Pages, Workers, Workers AI, R2, KV, and D1 through the SAME per-org, KMS-sealed API token the org connected via clients/integrations.
Package cloudflare is the per-org Cloudflare asset plane for the unified Hanzo Cloud binary — the first-class /v1/cloudflare/* surface (sibling of /v1/dns and /v1/domain) that manages an org's Cloudflare Zones/Analytics, Pages, Workers, Workers AI, R2, KV, and D1 through the SAME per-org, KMS-sealed API token the org connected via clients/integrations.
cms
Package cms declares the Hanzo CMS content model as DocType fixtures on the framework engine (clients/framework).
Package cms declares the Hanzo CMS content model as DocType fixtures on the framework engine (clients/framework).
code
Package code mounts the Hanzo Cloud /v1/code/* surface: a native, per-org code-intelligence engine for AI coding agents and the hanzo.app UI.
Package code mounts the Hanzo Cloud /v1/code/* surface: a native, per-org code-intelligence engine for AI coding agents and the hanzo.app UI.
coding
Package coding is the keystone that turns @hanzo from a chatbot into an engineer: it orchestrates ONE autonomous coding run — register a live agent session, dispatch the job to the bot-gateway sandbox runtime, mirror the sandbox's progress into the session live, verify the pushed branch landed in native git, and open a native "PR" work item — then returns a Result the trigger surface (Slack today, console/API tomorrow) renders.
Package coding is the keystone that turns @hanzo from a chatbot into an engineer: it orchestrates ONE autonomous coding run — register a live agent session, dispatch the job to the bot-gateway sandbox runtime, mirror the sandbox's progress into the session live, verify the pushed branch landed in native git, and open a native "PR" work item — then returns a Result the trigger surface (Slack today, console/API tomorrow) renders.
commerce
activeplan.go answers the subscription paywall's ONE question: does org X hold a LIVE PAID plan? It is the commerce "active-subscription check" — the tier sibling of CheckEntitlement (per-product license).
activeplan.go answers the subscription paywall's ONE question: does org X hold a LIVE PAID plan? It is the commerce "active-subscription check" — the tier sibling of CheckEntitlement (per-product license).
commerce/transport
Package transport is the ONE seam that lets every cloud subsystem that speaks the commerce billing S2S surface (clients/{billing,account,admin, referrals,authors,affiliates,usage} + the request-edge metering gate in build.go) reach the co-resident, in-process commerce handler with a DIRECT Go call instead of an HTTP hop to the standalone commerce pod (CLOUD_COMMERCE_HTTP_URL, commerce.hanzo.svc:8001).
Package transport is the ONE seam that lets every cloud subsystem that speaks the commerce billing S2S surface (clients/{billing,account,admin, referrals,authors,affiliates,usage} + the request-edge metering gate in build.go) reach the co-resident, in-process commerce handler with a DIRECT Go call instead of an HTTP hop to the standalone commerce pod (CLOUD_COMMERCE_HTTP_URL, commerce.hanzo.svc:8001).
company
Package company mounts /v1/company — Hanzo Company, the Stripe-Atlas-class incorporation + fundraising product.
Package company mounts /v1/company — Hanzo Company, the Stripe-Atlas-class incorporation + fundraising product.
compliance
Package compliance mounts the ORG-SCOPED compliance operations surface (/v1/compliance): the company's own KYC/KYB onboarding verification, accreditation STATE TRACKING, and a compliance-scoped read of the tamper-evident audit trail (the SOC 2 posture surface).
Package compliance mounts the ORG-SCOPED compliance operations surface (/v1/compliance): the company's own KYC/KYB onboarding verification, accreditation STATE TRACKING, and a compliance-scoped read of the tamper-evident audit trail (the SOC 2 posture surface).
connectorruntime
Package connectorruntime executes an automation connector's action NATIVELY in-process — no Node.
Package connectorruntime executes an automation connector's action NATIVELY in-process — no Node.
connectorruntime/internal/bundlecmd command
Command bundlecmd is the offline connector-ingest step: it esbuild-bundles ONE ActivePieces connector source tree (its index.ts) into a single CommonJS program with the framework packages left external, and writes the blob.
Command bundlecmd is the offline connector-ingest step: it esbuild-bundles ONE ActivePieces connector source tree (its index.ts) into a single CommonJS program with the framework packages left external, and writes the blob.
content
Package content is the Hanzo agentic-marketing lane: the marketing content loop (generate → CMS → review → approve → publish → distribute) built natively on the framework DocType engine, the ONE Go-native replacement for the bespoke karma Python scripts, multi-tenant for ANY brand (org = tenant, project = brand/site sub-scope).
Package content is the Hanzo agentic-marketing lane: the marketing content loop (generate → CMS → review → approve → publish → distribute) built natively on the framework DocType engine, the ONE Go-native replacement for the bespoke karma Python scripts, multi-tenant for ANY brand (org = tenant, project = brand/site sub-scope).
crm
Package crm mounts the Hanzo Cloud /v1/crm/* surface: a native-Go, per-org CRM (companies, contacts, opportunities) on Base/SQLite.
Package crm mounts the Hanzo Cloud /v1/crm/* surface: a native-Go, per-org CRM (companies, contacts, opportunities) on Base/SQLite.
cron
Package cron is the platform's ONE cron system: durable schedules on the embedded hanzoai/tasks engine (cloud.EmbeddedTasks) replacing every k8s CronJob.
Package cron is the platform's ONE cron system: durable schedules on the embedded hanzoai/tasks engine (cloud.EmbeddedTasks) replacing every k8s CronJob.
dataroom
Package dataroom folds hanzoai/dataroom (a Papermark fork: Next.js + Prisma + Postgres, "open-source DocSend/dataroom") FULLY into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106, task #101 / epic #96).
Package dataroom folds hanzoai/dataroom (a Papermark fork: Next.js + Prisma + Postgres, "open-source DocSend/dataroom") FULLY into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106, task #101 / epic #96).
datastore
Package datastore holds cloud's one connection to the analytics warehouse — the shared columnar store behind the usage, observability and billing ledgers.
Package datastore holds cloud's one connection to the analytics warehouse — the shared columnar store behind the usage, observability and billing ledgers.
deploy
actions.go — the two GitOps write actions.
actions.go — the two GitOps write actions.
destinations
Package destinations is the native fan-out plane: it TRANSLATES the canonical /v1/event stream (clients/analytics) into each connected ad/analytics platform's own conversion schema and forwards it server-side — Google Analytics 4 (Measurement Protocol) + Meta (Conversions API) end-to-end, with X/LinkedIn/ TikTok/Reddit against the same interface.
Package destinations is the native fan-out plane: it TRANSLATES the canonical /v1/event stream (clients/analytics) into each connected ad/analytics platform's own conversion schema and forwards it server-side — Google Analytics 4 (Measurement Protocol) + Meta (Conversions API) end-to-end, with X/LinkedIn/ TikTok/Reddit against the same interface.
dns
Package dns forwards the console's DNS dashboard traffic (/v1/dns/*) to the Hanzo DNS control plane (dns/plugin/hanzodns), which owns the authoritative zone/record store.
Package dns forwards the console's DNS dashboard traffic (/v1/dns/*) to the Hanzo DNS control plane (dns/plugin/hanzodns), which owns the authoritative zone/record store.
do
Package do mounts the Hanzo Cloud DigitalOcean-native infra surface — /v1/vpcs and /v1/load-balancers — on the unified cloud binary (HIP-0106).
Package do mounts the Hanzo Cloud DigitalOcean-native infra surface — /v1/vpcs and /v1/load-balancers — on the unified cloud binary (HIP-0106).
domain
Package domain is Hanzo Domains — the DOMAIN-REGISTRATION product: search a name, see its price (with Hanzo's markup), buy it billed through the customer's prepaid wallet, and have it born pointing at Hanzo's own authoritative nameservers.
Package domain is Hanzo Domains — the DOMAIN-REGISTRATION product: search a name, see its price (with Hanzo's markup), buy it billed through the customer's prepaid wallet, and have it born pointing at Hanzo's own authoritative nameservers.
domain/namecom
Package namecom is a minimal client for the name.com Core API v4 — the wholesale registrar surface Hanzo Domains resells: check availability, price, register, renew, transfer, and set nameservers/contacts on a domain.
Package namecom is a minimal client for the name.com Core API v4 — the wholesale registrar surface Hanzo Domains resells: check availability, price, register, renew, transfer, and set nameservers/contacts on a domain.
entitlements
Package entitlements is the per-org product-enablement plane for the unified Hanzo Cloud binary: the /v1/orgs/:org/entitlements surface the console's paid- product sidebar reads to decide which products to SHOW, and org owners / super admins write to TURN a product on or off.
Package entitlements is the per-org product-enablement plane for the unified Hanzo Cloud binary: the /v1/orgs/:org/entitlements surface the console's paid- product sidebar reads to decide which products to SHOW, and org owners / super admins write to TURN a product on or off.
erp
Package erp declares the ERPNext-core business model as DocType fixtures on the framework engine (clients/framework).
Package erp declares the ERPNext-core business model as DocType fixtures on the framework engine (clients/framework).
eval
Package eval mounts the Hanzo Cloud /v1/evals/* surface: a NATIVE, org-scoped evaluation system that replaces the retired 3.x observability-console fork (the crash-looping console proxy this file used to be).
Package eval mounts the Hanzo Cloud /v1/evals/* surface: a NATIVE, org-scoped evaluation system that replaces the retired 3.x observability-console fork (the crash-looping console proxy this file used to be).
exec
Package exec exposes the Code Interpreter ("Run Code") surface on the unified cloud-api /v1 plane, per HIP-0106.
Package exec exposes the Code Interpreter ("Run Code") surface on the unified cloud-api /v1 plane, per HIP-0106.
experiments
Package experiments is cloud's unified EXPERIMENT primitive: A/B testing as ONE value whatever the variant KIND is — a feature flag, an ad creative, an email subject, a model id.
Package experiments is cloud's unified EXPERIMENT primitive: A/B testing as ONE value whatever the variant KIND is — a feature flag, an ad creative, an email subject, a model id.
finance
Package finance is the ZAP-native money subsystem: a per-CUSTOMER, double-entry PREPAID WALLET on the native ledger core.
Package finance is the ZAP-native money subsystem: a per-CUSTOMER, double-entry PREPAID WALLET on the native ledger core.
flags
Package flags is cloud's NATIVE feature-flag engine: definitions live in per-(org, project) SQLite (cloud.OrgDB — {DataDir}/orgs/{org}/projects/{project}/ flags.db, encrypted at rest via cek) and evaluation runs in-process through the embedded hanzo-flags Rust evaluator (native/flags, FFI) with PostHog-compatible semantics: rollout hash, full property-operator set, variants, payloads.
Package flags is cloud's NATIVE feature-flag engine: definitions live in per-(org, project) SQLite (cloud.OrgDB — {DataDir}/orgs/{org}/projects/{project}/ flags.db, encrypted at rest via cek) and evaluation runs in-process through the embedded hanzo-flags Rust evaluator (native/flags, FFI) with PostHog-compatible semantics: rollout hash, full property-operator set, variants, payloads.
fleet
Package fleet is the ONE per-org registry of attached compute (BYO k8s clusters / BYO GPU / bare metal).
Package fleet is the ONE per-org registry of attached compute (BYO k8s clusters / BYO GPU / bare metal).
framework
Package framework is the Hanzo Framework: a metadata-driven DocType engine, native Go on Base/SQLite, mounted in the unified cloud binary at /v1/framework/*.
Package framework is the Hanzo Framework: a metadata-driven DocType engine, native Go on Base/SQLite, mounted in the unified cloud binary at /v1/framework/*.
functions
Package functions mounts the Hanzo Cloud /v1/functions surface: a per-org serverless function registry.
Package functions mounts the Hanzo Cloud /v1/functions surface: a per-org serverless function registry.
gateway
Package gateway is the /v1/gateway subsystem: the RUNTIME config plane for the cloud edge ("gateway role").
Package gateway is the /v1/gateway subsystem: the RUNTIME config plane for the cloud edge ("gateway role").
gateway/edge
Package edge is the runtime-mutable store for the cloud edge ("gateway role") policy: the CORS allowlist, the pre-auth per-client-IP flood cap, and the authenticated per-org rate ceiling.
Package edge is the runtime-mutable store for the cloud edge ("gateway role") policy: the CORS allowlist, the pre-auth per-client-IP flood cap, and the authenticated per-org rate ceiling.
git
browse.go — Hanzo Git's JSON read/browse surface: the machine-readable twin of the server-rendered UI (ui.go).
browse.go — Hanzo Git's JSON read/browse surface: the machine-readable twin of the server-rendered UI (ui.go).
goja
Package gojahost runs a Hanzo Node service's goja bundle (a self-contained, ESM-free JS file exposing globalThis.handle(req)) inside the unified cloud binary, per HIP-0106.
Package gojahost runs a Hanzo Node service's goja bundle (a self-contained, ESM-free JS file exposing globalThis.handle(req)) inside the unified cloud binary, per HIP-0106.
graph
client.go is the ONE HTTP path from this subsystem to the Lux chain-data plane.
client.go is the ONE HTTP path from this subsystem to the Lux chain-data plane.
guide
Package guide mounts the Hanzo Cloud /v1/guide/* surface: the Business AI Guide, an interactive launch checklist every org completes on-site.
Package guide mounts the Hanzo Cloud /v1/guide/* surface: the Business AI Guide, an interactive launch checklist every org completes on-site.
help
Package help is the Hanzo Support product: the Frappe-Helpdesk model rebuilt as DocType fixtures on the native framework engine (clients/framework), plus a thin /v1/help subsystem (subsystem.go) for the one plane the generic, secure-by-default framework surface deliberately cannot serve — the PUBLIC help center.
Package help is the Hanzo Support product: the Frappe-Helpdesk model rebuilt as DocType fixtures on the native framework engine (clients/framework), plus a thin /v1/help subsystem (subsystem.go) for the one plane the generic, secure-by-default framework surface deliberately cannot serve — the PUBLIC help center.
iam
Package iam folds Hanzo IAM into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106) — the LAST binary-consolidation piece: "one Go binary (hanzoai/cloud) embeds IAM + KMS + o11y".
Package iam folds Hanzo IAM into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106) — the LAST binary-consolidation piece: "one Go binary (hanzoai/cloud) embeds IAM + KMS + o11y".
idv
Package idv is the ONE identity/business verification seam the Hanzo cloud binary uses to orchestrate a KYC (individual) or KYB (business) check through an external provider.
Package idv is the ONE identity/business verification seam the Hanzo cloud binary uses to orchestrate a KYC (individual) or KYB (business) check through an external provider.
ingress
Package ingress is cloud's embedded, runtime-configurable edge — the /v1/ingress subsystem.
Package ingress is cloud's embedded, runtime-configurable edge — the /v1/ingress subsystem.
integrations
connectors.go is the per-USER connector plane — /v1/connectors, the sibling of the org-scoped /v1/integrations surface.
connectors.go is the per-USER connector plane — /v1/connectors, the sibling of the org-scoped /v1/integrations surface.
k8s
Package k8s holds the Kubernetes coordinates the cloud binary addresses — the GroupVersionResources that identify our own CRs and the upstream objects we read.
Package k8s holds the Kubernetes coordinates the cloud binary addresses — the GroupVersionResources that identify our own CRs and the upstream objects we read.
kafka
Package kafka embeds the Hanzo Stream Kafka-wire adaptor (github.com/hanzoai/ stream) as an in-process cloud subsystem (HIP-0106), translating the Kafka protocol to/from the embedded JetStream (clients/pubsub).
Package kafka embeds the Hanzo Stream Kafka-wire adaptor (github.com/hanzoai/ stream) as an in-process cloud subsystem (HIP-0106), translating the Kafka protocol to/from the embedded JetStream (clients/pubsub).
kms
Package kms embeds luxfi/kms in-process inside the unified Hanzo Cloud binary per HIP-0106 ("all Go embeds in cloud"), replacing the legacy Infisical fork.
Package kms embeds luxfi/kms in-process inside the unified Hanzo Cloud binary per HIP-0106 ("all Go embeds in cloud"), replacing the legacy Infisical fork.
knowledge
connectors.go is the per-org app-connector control plane: OAuth into Slack / GitHub / Google, store the token in KMS (never plaintext, never logged), and sync external documents INTO the same per-org knowledge store + vector index as manual pages.
connectors.go is the per-org app-connector control plane: OAuth into Slack / GitHub / Google, store the token in KMS (never plaintext, never logged), and sync external documents INTO the same per-org knowledge store + vector index as manual pages.
knowledge/evernote
Package evernote normalizes an Evernote .enex export into vault.Page documents.
Package evernote normalizes an Evernote .enex export into vault.Page documents.
knowledge/lexical
Package lexical builds a Lexical EditorState JSON string from block-structured content.
Package lexical builds a Lexical EditorState JSON string from block-structured content.
knowledge/notion
export.go normalizes a Notion workspace EXPORT (the "Markdown & CSV" or "HTML" zip a user downloads) into vault.Page documents — distinct from notion.go, which shapes records from the live Notion API connector.
export.go normalizes a Notion workspace EXPORT (the "Markdown & CSV" or "HTML" zip a user downloads) into vault.Page documents — distinct from notion.go, which shapes records from the live Notion API connector.
knowledge/obsidian
Package obsidian normalizes an Obsidian vault (a tree of markdown files) into vault.Page documents.
Package obsidian normalizes an Obsidian vault (a tree of markdown files) into vault.Page documents.
knowledge/roam
Package roam normalizes a Roam Research JSON export into vault.Page documents.
Package roam normalizes a Roam Research JSON export into vault.Page documents.
knowledge/vault
Package vault is the normalized model an importer produces: a set of pages with a parent tree and wikilinks preserved inline in the body.
Package vault is the normalized model an importer produces: a set of pages with a parent tree and wikilinks preserved inline in the body.
leaderboard
GET /v1/usage/activity — the per-day contribution series (GitHub-style heatmap + timeline) for ONE authorized subject.
GET /v1/usage/activity — the per-day contribution series (GitHub-style heatmap + timeline) for ONE authorized subject.
legal
Package legal mounts the ORG-SCOPED legal-document surface (/v1/legal): a versioned, org-overridable library of standardized templates, a PURE merge-field generation engine that renders those templates from the org's own company/cap-table data, a KMS-sealed store for the generated documents, and the e-signature + filing seams that carry a document to execution — all on the shared audit plane.
Package legal mounts the ORG-SCOPED legal-document surface (/v1/legal): a versioned, org-overridable library of standardized templates, a PURE merge-field generation engine that renders those templates from the org's own company/cap-table data, a KMS-sealed store for the generated documents, and the e-signature + filing seams that carry a document to execution — all on the shared audit plane.
link
Package link is the unified AI login manager's registry: the org+user-scoped record of WHICH provider accounts (Claude Max, ChatGPT Plus, a Hanzo API key, a raw provider key) a developer has signed into, ON WHICH MACHINES, with each account's latest usage snapshot.
Package link is the unified AI login manager's registry: the org+user-scoped record of WHICH provider accounts (Claude Max, ChatGPT Plus, a Hanzo API key, a raw provider key) a developer has signed into, ON WHICH MACHINES, with each account's latest usage snapshot.
marketing
Package marketing mounts the Hanzo Cloud /v1/marketing/* surface: the native-Go GTM engine folded from github.com/hanzoai/marketing onto the ONE cloud framework (zip/Fiber + cloud.Deps + per-org SQLite), the twin of clients/crm — NOT a proxy to a standalone pod, and nothing Python in the mount path.
Package marketing mounts the Hanzo Cloud /v1/marketing/* surface: the native-Go GTM engine folded from github.com/hanzoai/marketing onto the ONE cloud framework (zip/Fiber + cloud.Deps + per-org SQLite), the twin of clients/crm — NOT a proxy to a standalone pod, and nothing Python in the mount path.
marketplace
Package marketplace is the /v1/marketplace surface: listing, discovery, and install of tools + agents per org/project, plus monetized listings that declare a price + recipient wallet and enforce through the x402 seam.
Package marketplace is the /v1/marketplace surface: listing, discovery, and install of tools + agents per org/project, plus monetized listings that declare a price + recipient wallet and enforce through the x402 seam.
metering
Package metering is the ONE way every Hanzo product meters usage to commerce — the single billing source of truth — so that every product (not only the LLM/cloud path) can be paid for.
Package metering is the ONE way every Hanzo product meters usage to commerce — the single billing source of truth — so that every product (not only the LLM/cloud path) can be paid for.
ml
Package ml mounts the Hanzo Cloud /v1/ml/* and /v1/train/* surfaces: a thin, tenant-scoped bridge that turns three Kubeflow-family CustomResources into a small REST API.
Package ml mounts the Hanzo Cloud /v1/ml/* and /v1/train/* surfaces: a thin, tenant-scoped bridge that turns three Kubeflow-family CustomResources into a small REST API.
money
Package money is the ONE exact money value for the Hanzo cloud finance stack: a USD balance carried at 18-decimal (EVM/ERC-20) precision, so an off-chain ledger amount and an on-chain uint256 credit balance are THE SAME INTEGER — no conversion or rounding at the boundary.
Package money is the ONE exact money value for the Hanzo cloud finance stack: a USD balance carried at 18-decimal (EVM/ERC-20) precision, so an off-chain ledger amount and an on-chain uint256 credit balance are THE SAME INTEGER — no conversion or rounding at the boundary.
mpc
Package mpcseal is cloud's client-side-CEK sealing client for the SEPARATE MPC node ring (ghcr.io/luxfi/mpc).
Package mpcseal is cloud's client-side-CEK sealing client for the SEPARATE MPC node ring (ghcr.io/luxfi/mpc).
notify
Package notify folds the Hanzo Notify SEND surface into the unified cloud binary (HIP-0106), mounting /v1/notify/* natively in-process — the native replacement for the standalone notifyd (github.com/hanzoai/notify) Deployment.
Package notify folds the Hanzo Notify SEND surface into the unified cloud binary (HIP-0106), mounting /v1/notify/* natively in-process — the native replacement for the standalone notifyd (github.com/hanzoai/notify) Deployment.
o11y
O11Y LLM-OBSERVABILITY EVENT INGEST — the native-Go write path for LLM-observability events (traces / observations / scores), folding the RETIRED console-worker (a Node BullMQ→Valkey→Datastore worker) into the one cloud binary.
O11Y LLM-OBSERVABILITY EVENT INGEST — the native-Go write path for LLM-observability events (traces / observations / scores), folding the RETIRED console-worker (a Node BullMQ→Valkey→Datastore worker) into the one cloud binary.
paas
Package paas mounts the native, in-process Hanzo PaaS control plane at /v1/paas/*: the "one and only one way to deploy" made native to the cloud binary.
Package paas mounts the native, in-process Hanzo PaaS control plane at /v1/paas/*: the "one and only one way to deploy" made native to the cloud binary.
payout
Package payout is the ONE attributed-credit money seam shared by the credit programs — referrals, affiliates, authors: read an org's metered spend (the qualify / accrual base) and grant a promo credit to its wallet (a payout made in credits, landing in commerce's Credit/trial bucket).
Package payout is the ONE attributed-credit money seam shared by the credit programs — referrals, affiliates, authors: read an org's metered spend (the qualify / accrual base) and grant a promo credit to its wallet (a payout made in credits, landing in commerce's Credit/trial bucket).
plan
Package plan mounts the @hanzo/plans catalog into the unified cloud binary under /v1/plans/*, per HIP-0106.
Package plan mounts the @hanzo/plans catalog into the unified cloud binary under /v1/plans/*, per HIP-0106.
platform
applylive.go — the ONE version-monotonic deploy mechanic shared by the image-source path (deployImage) and the git build reconciler.
applylive.go — the ONE version-monotonic deploy mechanic shared by the image-source path (deployImage) and the git build reconciler.
plugin
Package plugin is the runtime plugin loader for the unified cloud binary.
Package plugin is the runtime plugin loader for the unified cloud binary.
prefs
Package prefs is the per-USER preference plane for the unified Hanzo Cloud binary: the /v1/prefs surface behind the user menu on every Hanzo surface (console, insights, and anything else that renders "signed in as").
Package prefs is the per-USER preference plane for the unified Hanzo Cloud binary: the /v1/prefs surface behind the user menu on every Hanzo surface (console, insights, and anything else that renders "signed in as").
pricing
Admin surface for the catalog enablement overlay (SuperAdmin only).
Admin surface for the catalog enablement overlay (SuperAdmin only).
principal
Package principal is the ONE place the cloud data plane turns a request into a org.
Package principal is the ONE place the cloud data plane turns a request into a org.
product
Package product exposes the read-only Search and Vector product surfaces the Hanzo console panels call at api.cloud.hanzo.ai, per HIP-0106.
Package product exposes the read-only Search and Vector product surfaces the Hanzo console panels call at api.cloud.hanzo.ai, per HIP-0106.
projects
Package projects is the Hanzo Cloud projects control plane: the ONE org-scoped store of buildable/deployable sites, shared by every surface that shows a user's projects.
Package projects is the Hanzo Cloud projects control plane: the ONE org-scoped store of buildable/deployable sites, shared by every surface that shows a user's projects.
prompts
Package prompts mounts the Hanzo Cloud /v1/prompts surface: a per-org, versioned prompt library.
Package prompts mounts the Hanzo Cloud /v1/prompts surface: a per-org, versioned prompt library.
provisioning
Package provisioning is the Hanzo Cloud provisioning control plane.
Package provisioning is the Hanzo Cloud provisioning control plane.
pubsub
Package pubsub embeds the Hanzo PubSub core data plane (NATS + JetStream) as an in-process cloud subsystem (HIP-0106) — the same fold pattern as iam/kms/tasks.
Package pubsub embeds the Hanzo PubSub core data plane (NATS + JetStream) as an in-process cloud subsystem (HIP-0106) — the same fold pattern as iam/kms/tasks.
referrals
Package referrals mounts the Hanzo Cloud /v1/referrals/* viral-loop surface: a native-Go, per-org referral program on Base/SQLite that grants promo cloud credit through the SAME commerce ledger path as clients/admin.grantCredit (the trial/Credit bucket, tag grant:referral).
Package referrals mounts the Hanzo Cloud /v1/referrals/* viral-loop surface: a native-Go, per-org referral program on Base/SQLite that grants promo cloud credit through the SAME commerce ledger path as clients/admin.grantCredit (the trial/Credit bucket, tag grant:referral).
research
Package research mounts the Hanzo Cloud /v1/research/* surface: the R&D EVIDENCE plane (HIP-0512 §"Hanzo Research").
Package research mounts the Hanzo Cloud /v1/research/* surface: the R&D EVIDENCE plane (HIP-0512 §"Hanzo Research").
research/ui
Package ui embeds the Hanzo Research R&D Ops Board — the dashboard over the /v1/research evidence plane (HIP-0512) — directly into the cloud binary and serves it at /research (cloud.hanzo.ai/research + console.hanzo.ai/research).
Package ui embeds the Hanzo Research R&D Ops Board — the dashboard over the /v1/research evidence plane (HIP-0512) — directly into the cloud binary and serves it at /research (cloud.hanzo.ai/research + console.hanzo.ai/research).
rollingcap
Package rollingcap installs the ai gate's rolling-window AI-spend cap — the Anthropic-style burst limit that resets continuously (usage older than the window drops out of the trailing sum, so there is no fixed reset boundary).
Package rollingcap installs the ai gate's rolling-window AI-spend cap — the Anthropic-style burst limit that resets continuously (usage older than the window drops out of the trailing sum, so there is no fixed reset boundary).
runtime
ops.go mounts /v1/bot/* — the runtime's OWN operational paths (health, and the surfaces the console Bot module links out to), relayed verbatim.
ops.go mounts /v1/bot/* — the runtime's OWN operational paths (health, and the surfaces the console Bot module links out to), relayed verbatim.
s3admin
Package s3admin is the ONE shared S3 access path for the unified cloud binary.
Package s3admin is the ONE shared S3 access path for the unified cloud binary.
samples
Package samples is the fleet's compute-utilization time series: ONE table, ONE writer seam, ONE read face that every compute source feeds.
Package samples is the fleet's compute-utilization time series: ONE table, ONE writer seam, ONE read face that every compute source feeds.
sbom
Pure core of the SBOM lens: the wire types, the CycloneDX parser, the row builder, and the datastore value coercers.
Pure core of the SBOM lens: the wire types, the CycloneDX parser, the row builder, and the datastore value coercers.
security/detect
Package detect is the pure, dependency-free secret-detection engine behind Hanzo's native code-security surface.
Package detect is the pure, dependency-free secret-detection engine behind Hanzo's native code-security surface.
session
Package session mounts the Hanzo Cloud /v1/code/sessions/* surface: the registry of live coding-agent runs launched by `hanzo code <agent>`.
Package session mounts the Hanzo Cloud /v1/code/sessions/* surface: the registry of live coding-agent runs launched by `hanzo code <agent>`.
settings
Package settings is the per-org, per-product configuration plane for the unified Hanzo Cloud binary: the /v1/settings/:product surface behind every product's detail view in console.hanzo.ai (#59).
Package settings is the per-org, per-product configuration plane for the unified Hanzo Cloud binary: the /v1/settings/:product surface behind every product's detail view in console.hanzo.ai (#59).
share
Package share fronts the zrok controller so a Hanzo org can publish a local service to a public https://<token>.share.hanzo.ai URL — "ngrok on our own stack" — folded into the ONE cloud binary.
Package share fronts the zrok controller so a Hanzo org can publish a local service to a public https://<token>.share.hanzo.ai URL — "ngrok on our own stack" — folded into the ONE cloud binary.
sign
Package sign folds hanzoai/sign (the Documenso fork — "open-source DocuSign") into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106, task #100, epic #96).
Package sign folds hanzoai/sign (the Documenso fork — "open-source DocuSign") into the unified hanzoai/cloud binary as an in-process subsystem (HIP-0106, task #100, epic #96).
sites
Package sites is the public site-server for published projects: the host-routed edge that turns `<slug>.hanzo.app` into the static site a user deployed to OUR S3.
Package sites is the public site-server for published projects: the host-routed edge that turns `<slug>.hanzo.app` into the static site a user deployed to OUR S3.
social
Package social mounts the Hanzo Cloud /v1/social/* surface: a native-Go, per-org social-media store on Base/SQLite.
Package social mounts the Hanzo Cloud /v1/social/* surface: a native-Go, per-org social-media store on Base/SQLite.
storage
Package s3 is the Fiber-facing subsystem that exposes an org-scoped S3 object-storage file manager as /v1/s3/* on the unified Hanzo Cloud binary (HIP-0106).
Package s3 is the Fiber-facing subsystem that exposes an org-scoped S3 object-storage file manager as /v1/s3/* on the unified Hanzo Cloud binary (HIP-0106).
sync
Package sync is the universal sync service (/v1/sync): cloud↔cloud data sync between connected platforms, expressed as Syncs the engine runs.
Package sync is the universal sync service (/v1/sync): cloud↔cloud data sync between connected platforms, expressed as Syncs the engine runs.
tasks
Package tasks mounts the Hanzo Tasks HTTP + UI surface natively onto the unified cloud binary per HIP-0106 — the follow-up named in cloud's durable.go ("consolidating that surface into cloud").
Package tasks mounts the Hanzo Tasks HTTP + UI surface natively onto the unified cloud binary per HIP-0106 — the follow-up named in cloud's durable.go ("consolidating that surface into cloud").
tasks/ui
Package ui embeds the built Hanzo Tasks SPA (@hanzo/tasks, the admin-tasks app in hanzoai/admin, Vite + hanzogui) directly into the cloud binary and serves it at /tasks/* (console.hanzo.ai/tasks + tasks.hanzo.ai/tasks).
Package ui embeds the built Hanzo Tasks SPA (@hanzo/tasks, the admin-tasks app in hanzoai/admin, Vite + hanzogui) directly into the cloud binary and serves it at /tasks/* (console.hanzo.ai/tasks + tasks.hanzo.ai/tasks).
team
Package team mounts the Hanzo Cloud /v1/team/* surface: the native-Go port of hanzo team-go (HIP-0106, task #45) into the unified cloud binary.
Package team mounts the Hanzo Cloud /v1/team/* surface: the native-Go port of hanzo team-go (HIP-0106, task #45) into the unified cloud binary.
team/token
Package token mints and verifies the HS256 JWTs that the team SPA, the /v1/team/account API and the /v1/team/transactor data plane all share.
Package token mints and verifies the HS256 JWTs that the team SPA, the /v1/team/account API and the /v1/team/transactor data plane all share.
team/wallet
Package wallet embeds the built hanzo.team usage/wallet page — a SMALL @hanzo/ui@8 React static export (app/, Vite) — into the cloud binary, the same one-binary/one-origin precedent as the console (webui.go) and the tasks SPA (clients/tasks/ui).
Package wallet embeds the built hanzo.team usage/wallet page — a SMALL @hanzo/ui@8 React static export (app/, Vite) — into the cloud binary, the same one-binary/one-origin precedent as the console (webui.go) and the tasks SPA (clients/tasks/ui).
templates
Package templates mounts /v1/templates — the read-only Hanzo starter-kit gallery: deployable app/site scaffolds (source of truth: hanzoai/gallery), vendored so the unified `cloud` binary ships the catalog with no external dependency.
Package templates mounts /v1/templates — the read-only Hanzo starter-kit gallery: deployable app/site scaffolds (source of truth: hanzoai/gallery), vendored so the unified `cloud` binary ships the catalog with no external dependency.
tools
Package tools is the ONE tool plane for Hanzo Cloud: a single registry where every callable capability — a connector action, a user function, a zap service route, a cloud /v1 control ("full-cloud-control"), an agent, a skill, or a tool on an org's own external MCP server — is a Tool with a Source, a JSON-Schema, a per-(org,project) activation state, and an optional price.
Package tools is the ONE tool plane for Hanzo Cloud: a single registry where every callable capability — a connector action, a user function, a zap service route, a cloud /v1 control ("full-cloud-control"), an agent, a skill, or a tool on an org's own external MCP server — is a Tool with a Source, a JSON-Schema, a per-(org,project) activation state, and an optional price.
tracker
Package tracker mounts the Hanzo Cloud /v1/tracker/* surface: a native-Go, per-org issue tracker (projects + issues) on SQLite.
Package tracker mounts the Hanzo Cloud /v1/tracker/* surface: a native-Go, per-org issue tracker (projects + issues) on SQLite.
translate
Package translate serves POST /v1/translate — the ONE translation surface, two tiers behind one endpoint, one auth path, one meter (HIP-0516).
Package translate serves POST /v1/translate — the ONE translation surface, two tiers behind one endpoint, one auth path, one meter (HIP-0516).
treasury
Package treasury mounts the Hanzo Cloud /v1/finance/* surface: the platform's OWN fund/reserve accounting, one layer ABOVE the per-org commerce credit ledger.
Package treasury mounts the Hanzo Cloud /v1/finance/* surface: the platform's OWN fund/reserve accounting, one layer ABOVE the per-org commerce credit ledger.
treasury/cmd/anchorctl command
Command anchorctl bootstraps the Hanzo L1 (chain 36963) treasury anchor: it provisions the KMS-held signer key, funds it, and deploys contracts/TreasuryAnchor.sol — the on-chain witness that clients/treasury/anchor_evm.go later writes ledger roots to.
Command anchorctl bootstraps the Hanzo L1 (chain 36963) treasury anchor: it provisions the KMS-held signer key, funds it, and deploys contracts/TreasuryAnchor.sol — the on-chain witness that clients/treasury/anchor_evm.go later writes ledger roots to.
treasury/formance
Package formance is the Formance Ledger adapter for the treasury: it satisfies ledger.Backend by posting the reserve fund's double-entry through a live Formance Ledger service (Postgres-backed, the production ledger of record) over its v2 HTTP API.
Package formance is the Formance Ledger adapter for the treasury: it satisfies ledger.Backend by posting the reserve fund's double-entry through a live Formance Ledger service (Postgres-backed, the production ledger of record) over its v2 HTTP API.
treasury/ledger
Package ledger is the native, double-entry accounting core of the Hanzo finance stack — the store-agnostic engine that owns EVERY accounting rule (balanced postings, a non-negative reserve fund, idempotent journal entries, revenue-share math) and NOTHING about how those facts are persisted or served.
Package ledger is the native, double-entry accounting core of the Hanzo finance stack — the store-agnostic engine that owns EVERY accounting rule (balanced postings, a non-negative reserve fund, idempotent journal entries, revenue-share math) and NOTHING about how those facts are persisted or served.
treasury/ledger/sqlstore
manager.go is the PER-TENANT selector over the treasury Store: it resolves each request to its OWN Hanzo Base (SQLite) file instead of a process-wide singleton, so one tenant's finance/ledger writes can NEVER appear in another tenant's reads.
manager.go is the PER-TENANT selector over the treasury Store: it resolves each request to its OWN Hanzo Base (SQLite) file instead of a process-wide singleton, so one tenant's finance/ledger writes can NEVER appear in another tenant's reads.
usage
Analytics entitlement contract.
Analytics entitlement contract.
validators
Package validators mounts the Hanzo Cloud /v1/validators/* surface: the "click → provision node + queue registration" pipeline behind GDA/SDM validator onboarding on lux.cloud.
Package validators mounts the Hanzo Cloud /v1/validators/* surface: the "click → provision node + queue registration" pipeline behind GDA/SDM validator onboarding on lux.cloud.
venue
Package venue is the org-scoped "connect a cloud account" plane: an org links its native cloud-provider accounts (DigitalOcean / AWS / GCP), and Hanzo DISCOVERS the Kubernetes clusters in each account and FOLDS them into the ONE fleet (clients/fleet) — the same registry clients/visor surfaces at /v1/clusters and clients/ml federates workloads onto.
Package venue is the org-scoped "connect a cloud account" plane: an org links its native cloud-provider accounts (DigitalOcean / AWS / GCP), and Hanzo DISCOVERS the Kubernetes clusters in each account and FOLDS them into the ONE fleet (clients/fleet) — the same registry clients/visor surfaces at /v1/clusters and clients/ml federates workloads onto.
visor
board.go — GET /v1/fleet: the org's compute, from every source, on ONE board, each unit carrying its latest utilization.
board.go — GET /v1/fleet: the org's compute, from every source, on ONE board, each unit carrying its latest utilization.
wallets
Package wallets is the Hanzo Cloud accounts/wallets/custody/keys/sign surface (/v1/wallets/*): one configurable custody seam over three orthogonal signing backends, selected PER WALLET by its Kind.
Package wallets is the Hanzo Cloud accounts/wallets/custody/keys/sign surface (/v1/wallets/*): one configurable custody seam over three orthogonal signing backends, selected PER WALLET by its Kind.
webhooks
Package webhooks is the platform-global webhook layer (HIP-0106): ONE registry plus ONE dispatcher that delivers ANY event on the platform bus to org-registered HTTP subscribers.
Package webhooks is the platform-global webhook layer (HIP-0106): ONE registry plus ONE dispatcher that delivers ANY event on the platform bus to org-registered HTTP subscribers.
websearch
Native Go meta-search — the SEARCH half of /v1/websearch, replacing the reverse proxy to the (retired) SearXNG pod.
Native Go meta-search — the SEARCH half of /v1/websearch, replacing the reverse proxy to the (retired) SearXNG pod.
world
World plan enforcement contract.
World plan enforcement contract.
x402
Package x402 is the Hanzo Cloud native x402 pay-per-use subsystem (HTTP 402): challenge → the client pays → proof submitted → verify → serve → settle.
Package x402 is the Hanzo Cloud native x402 pay-per-use subsystem (HTTP 402): challenge → the client pays → proof submitted → verify → serve → settle.
zt
client.go is the ONE HTTP path from this subsystem to Hanzo Zero Trust — the OpenZiti-based fabric controller (hanzoai/zt) at zt-controller.hanzo.svc.
client.go is the ONE HTTP path from this subsystem to Hanzo Zero Trust — the OpenZiti-based fabric controller (hanzoai/zt) at zt-controller.hanzo.svc.
cmd
account command
account-bridge command
admin command
ads command
affiliates command
agents command
agentskills command
ai command
analytics command
audit command
authors command
authz command
automations command
base command
billing command
bots command
captable command
catalogsync command
channels command
cloud command
cloud is the unified Hanzo Cloud binary per HIP-0106.
cloud is the unified Hanzo Cloud binary per HIP-0106.
code command
commerce command
company command
content command
crm command
cron command
dataroom command
do command
entitlements command
evals command
exec command
flags command
framework command
functions command
gateway command
gen-app-cmds command
Command gen-app-cmds generates one cmd/<app>/main.go stub per app in apps.Wire so each app builds as its own standalone binary AND still mounts into the unified cloud binary.
Command gen-app-cmds generates one cmd/<app>/main.go stub per app in apps.Wire so each app builds as its own standalone binary AND still mounts into the unified cloud binary.
git command
gitops command
graph command
guide command
hanzo command
Command hanzo is the unified Hanzo Go binary, dispatched by subcommand.
Command hanzo is the unified Hanzo Go binary, dispatched by subcommand.
iam command
ingress command
integrations command
kafka command
kms command
kmsreseal command
Command kmsreseal is the CR-driven re-seal migration tool for embedding the fleet KMS into cloud (#79).
Command kmsreseal is the CR-driven re-seal migration tool for embedding the fleet KMS into cloud (#79).
knowledge command
licensing command
link command
marketing command
marketplace command
metrics command
migrate-pg-to-sqlite command
Command migrate-pg-to-sqlite copies a legacy `hanzo_cloud` PostgreSQL database into per-(org, user) SQLite files served by the Hanzo cloud orchestrator (HIP-0106).
Command migrate-pg-to-sqlite copies a legacy `hanzo_cloud` PostgreSQL database into per-(org, user) SQLite files served by the Hanzo cloud orchestrator (HIP-0106).
ml command
notify command
o11y command
paas command
plan command
platform command
plugins command
pricing command
product command
projects command
prompts command
provisioning command
pubsub command
referrals command
runtime command
sbom command
security command
settings command
sign command
smoke command
Command smoke is the durable, authenticated functional smoke for the unified cloud API (api.hanzo.ai).
Command smoke is the durable, authenticated functional smoke for the unified cloud API (api.hanzo.ai).
social command
storage command
tasks command
team command
templates command
tools command
tracker command
treasury command
usage command
venue command
visor command
wallets command
websearch command
world command
x402 command
zen command
zero-trust command
internal
idem
Package idem is exactly-once request execution over a per-org SQLite database: a request named by a caller-supplied idempotency key runs AT MOST ONCE, and any retry — including one re-routed to a different replica after a rolling upgrade — returns the first run's recorded result instead of executing the effect again.
Package idem is exactly-once request execution over a per-org SQLite database: a request named by a caller-supplied idempotency key runs AT MOST ONCE, and any retry — including one re-routed to a different replica after a rolling upgrade — returns the first run's recorded result instead of executing the effect again.
migratetest
Package migratetest is the shared regression harness for one production bug class: a store's migrate() creates an index over a column that a pre-existing (legacy) table lacks — because the column is ALTER-added later — so CREATE INDEX fails "no such column", migrate() fails, mount fails, and the pod crashloops on deploy.
Package migratetest is the shared regression harness for one production bug class: a store's migrate() creates an index over a column that a pre-existing (legacy) table lacks — because the column is ALTER-added later — so CREATE INDEX fails "no such column", migrate() fails, mount fails, and the pod crashloops on deploy.
org
storagelock
Package storagelock refuses to boot the canonical Hanzo cloud orchestrator against Postgres.
Package storagelock refuses to boot the canonical Hanzo cloud orchestrator against Postgres.
Package migration ports a legacy `hanzo_cloud` PostgreSQL database into per-(org, user) SQLite files served by the Hanzo cloud orchestrator (HIP-0106).
Package migration ports a legacy `hanzo_cloud` PostgreSQL database into per-(org, user) SQLite files served by the Hanzo cloud orchestrator (HIP-0106).
Package openapi projects the LIVE zip/fiber router into an OpenAPI 3.1 document.
Package openapi projects the LIVE zip/fiber router into an OpenAPI 3.1 document.
Package role resolves the HA role of a Hanzo Cloud process: the single authoritative WRITER (owns the RWO data dir — the ZapDB KMS store, the SQLite audit chain, the durable task store, and per-tenant SQLite) or a stateless READER (no RWO PVC, no exclusive store lock; hydrates read-only replicas from the S3/vfs replication stream and serves read paths).
Package role resolves the HA role of a Hanzo Cloud process: the single authoritative WRITER (owns the RWO data dir — the ZapDB KMS store, the SQLite audit chain, the durable task store, and per-tenant SQLite) or a stateless READER (no RWO PVC, no exclusive store lock; hydrates read-only replicas from the S3/vfs replication stream and serves read paths).
ars_types.go — minimal AutoscalingRunnerSet CRD.
ars_types.go — minimal AutoscalingRunnerSet CRD.
Package types holds the placeholder transport types AND the inter-subsystem client interfaces shared between cloud (the orchestrator) and cloud/clients (the in-process and RPC client implementations).
Package types holds the placeholder transport types AND the inter-subsystem client interfaces shared between cloud (the orchestrator) and cloud/clients (the in-process and RPC client implementations).
Package writerpin abstracts WHO holds the single-writer pin — the exclusive right to open the RWO stores for write.
Package writerpin abstracts WHO holds the single-writer pin — the exclusive right to open the RWO stores for write.
Package zapface serves the browser-facing ZAP RPC plane over WebSocket.
Package zapface serves the browser-facing ZAP RPC plane over WebSocket.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL