@tangle-network/agent-app 0.45.34 → 0.45.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/spend/types.ts","../src/spend/ownership.ts","../src/spend/ceiling.ts","../src/spend/reference.ts","../src/spend/reconcile.ts","../src/spend/report.ts"],"sourcesContent":["/**\n * The vocabulary of consumer-side spend verification.\n *\n * Kept in its own module with ZERO imports so a product can type its storage\n * rows and its reconciliation config without pulling in `node:fs` through the\n * CLI half.\n *\n * The model in one paragraph: the platform's ledger is authoritative about what\n * was CHARGED. A product knows something the ledger does not — what it ASKED\n * for. Recording that second view, and diffing it against the first, is what\n * turns a platform billing defect from silent money into an alert. Nothing here\n * lets a product self-certify a charge away; the output is a discrepancy a human\n * disputes.\n */\n\n// ── the product's own view of a box's life ────────────────────────────────────\n\n/**\n * One box, as the PRODUCT understands it. Folded, not an append-only log: a\n * product runs one row per sandbox, and every field below is derived by a\n * monotonic fold (see `foldSpendBoxRecord`) so two concurrent writers cannot\n * produce a wrong answer, only a stale one.\n *\n * Timestamps are epoch ms throughout, matching the platform's own\n * `sandbox_meta.last_started_at`.\n */\nexport interface SpendBoxRecord {\n /** The platform's sandbox id — the join key to every settlement row. */\n readonly sandboxId: string\n /** The product's own tenancy unit, which the platform does not model. */\n readonly workspaceId: string\n /** First moment the product knew this box existed. */\n readonly createdAt: number\n /**\n * The idle timeout the product ASKED the platform for, seconds. This is the\n * width of the grace window between the last thing the product saw and the\n * moment the platform should have stopped billing.\n */\n readonly idleTimeoutSeconds: number\n /**\n * The maximum lifetime the product asked for, seconds, when it asked for one.\n * This is the strongest bound a product holds: the platform destroys the box\n * at `createdAt + maxLifetimeSeconds` regardless of what the product observed,\n * so it caps the ceiling even when nothing else can (see `computeExpectedCeiling`).\n */\n readonly maxLifetimeSeconds: number | null\n /** Latest moment the product OBSERVED the box doing work. */\n readonly lastActivityAt: number\n /**\n * Detached runs dispatched but never observed to finish, by run id.\n *\n * Non-empty means the product genuinely cannot bound this box from its own\n * observations: it handed the platform work and disconnected. The ceiling\n * degrades accordingly rather than pretending to a tightness it did not earn.\n */\n readonly openDetachedRunIds: readonly string[]\n /** When the product knows the box stopped. Cleared by later activity. */\n readonly stoppedAt: number | null\n /** When the product knows the box was deleted. Set once — a deleted id never returns. */\n readonly deletedAt: number | null\n /** Opaque product-column values, written verbatim and never read here. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * A fold step. Every field states its own merge rule, so a SQL implementation\n * can apply it in one statement and reach the same record an in-memory\n * read-modify-write reaches.\n */\nexport interface SpendBoxPatch {\n /** Advance `lastActivityAt` to the max of stored and this. Never moves backward. */\n readonly observedActivityAt?: number\n /** Add a run id to `openDetachedRunIds` (set semantics — re-adding is a no-op). */\n readonly openDetachedRunAdd?: string\n /** Remove a run id from `openDetachedRunIds`. Removing an absent id is a no-op. */\n readonly openDetachedRunRemove?: string\n /**\n * Latest-wins. Activity observed AFTER a recorded stop clears it: a box that\n * worked after we thought it stopped is running again, and a stale stop would\n * make the ceiling too tight.\n */\n readonly stoppedAt?: number\n /** Set-once. A later delete observation does not move the first one. */\n readonly deletedAt?: number\n}\n\n// ── what bounds a box's billable time ─────────────────────────────────────────\n\n/** Which fact bounds a box's billable time, weakest last. */\nexport type CeilingBasis =\n /** The product observed deletion. Billing cannot run past a box that is gone. */\n | 'deleted'\n /** The product observed a stop. Billing should have closed there. */\n | 'stopped'\n /** No stop seen, but the platform destroys the box at its max lifetime. */\n | 'max-lifetime'\n /** No stop seen; the platform's idle timer is what should have closed billing. */\n | 'idle-timeout'\n /**\n * An unfinished detached run and no max lifetime — the product cannot bound\n * this box at all, so the ceiling degrades to the reconciliation instant.\n * A finding on this basis is weak evidence and says so.\n */\n | 'open-detached-run'\n\n/** The upper bound on one box's billable duration, and what earned it. */\nexport interface ExpectedCeiling {\n readonly sandboxId: string\n readonly basis: CeilingBasis\n /** The latest instant this box could still have been billable, epoch ms. */\n readonly horizonAt: number\n /** `horizonAt - createdAt + toleranceMs`. The upper bound on billable ms. */\n readonly ceilingMs: number\n readonly toleranceMs: number\n /**\n * False when the basis is `open-detached-run` — the ceiling then rests on the\n * reconciliation instant rather than on anything the product observed, so an\n * overage means the platform billed outside the box's own lifetime, not merely\n * longer than expected.\n */\n readonly bounded: boolean\n}\n\n// ── what the platform actually emitted ────────────────────────────────────────\n\n/**\n * One settled ledger row, in the shape the platform's `credit_transactions`\n * table stores it. The product supplies these through its own fetch (the\n * platform's credit-history API, an export, a mirror) — this package never\n * reaches for them, because the ledger is the counterparty's record and reading\n * it is the product's authenticated business.\n *\n * The rows a product can fetch are scoped to the BILLING OWNER, not to the\n * product: `product: 'sandbox'` is the platform's service taxonomy and every\n * consumer app's compute wears it. So a wallet running two of our products\n * returns both products' settlements, and telling them apart is\n * {@link SpendOwnershipRule}'s job.\n */\nexport interface SettlementRow {\n /** The ledger row id, for the dispute. */\n readonly id: string\n /**\n * `sandbox:<kind>:<sandboxId>:<intervalStartMs>` — the platform's idempotency\n * key, and the only place the billed interval's START is recorded.\n */\n readonly referenceId: string | null\n /**\n * Signed nanodollars, exactly as the ledger stores it: negative is a charge,\n * positive is a credit or refund.\n */\n readonly amountNanoUsd: number\n /** `compute` | `refund` | `inference` | … */\n readonly type: string\n /** `sandbox` | `router` | … */\n readonly product: string | null\n /** `sandbox:<sandboxId>` — the platform's aggregation unit. */\n readonly groupKey: string | null\n /** Settlement instant, epoch ms. The product normalizes the stored text. */\n readonly createdAt: number\n readonly description: string | null\n /** Provider at-cost basis, unsigned nanodollars. Null when unattributed. */\n readonly costBasisNanoUsd: number | null\n /**\n * The billed duration, when the product's ledger view exposes it directly.\n * Null is the common case: the platform does not store duration on the row.\n */\n readonly billedMs: number | null\n /**\n * The platform API key the charge was triggered by — `credit_transactions.key_id`,\n * stamped from the box's own creation metadata at settlement time and exposed\n * by `/v1/billing/transactions` (which also filters on it).\n *\n * This is the ONLY field on a settlement row that can be attributed back to a\n * PRODUCT rather than to a wallet or to the platform's service taxonomy, which\n * is why {@link SpendOwnershipRule}'s shipped constructor is built on it. The\n * sandbox id cannot do the job: the platform mints it as `sandbox-<12 hex>`\n * from a hash of (owner, idempotency key), so a product's own box naming never\n * reaches the ledger row.\n *\n * Optional, and `null` is a real answer: the platform leaves it null on legacy\n * rows and an export may not carry the column at all. A missing key is\n * `undecidable`, never `foreign` — see {@link SpendOwnershipVerdict}.\n */\n readonly keyId?: string | null\n}\n\n// ── whose box is this? ────────────────────────────────────────────────────────\n\n/**\n * What one settlement is attributable to, from inside ONE product.\n *\n * The distinction this type exists for: a sibling product's box and a charge\n * that is not ours at all look identical from inside a single product, because\n * both arrive as a settlement naming a sandbox this product's expectation ledger\n * has never heard of. Dropping both loses the check's whole purpose; reporting\n * both makes it noise. Only a platform-stamped attribution field separates them.\n */\nexport type SpendOwnershipVerdict =\n /** Attributable to THIS product. An unrecorded one is a phantom-charge candidate. */\n | 'mine'\n /** Attributable to a DIFFERENT product on the same wallet. Reported, never a finding. */\n | 'foreign'\n /**\n * The row carries nothing that decides it. Counted as `mine` — FAIL CLOSED.\n * An unattributable charge on a shared wallet is precisely the shape of the\n * thing this module exists to catch, so the ambiguous case costs a human five\n * minutes rather than costing the product the detection.\n */\n | 'undecidable'\n\n/** One settlement, presented to an ownership rule. */\nexport interface SpendOwnershipCandidate {\n readonly row: SettlementRow\n /** The sandbox the row is attributable to, or null for a row naming none. */\n readonly sandboxId: string | null\n}\n\n/**\n * The product's declaration of which settlements are its own.\n *\n * The one hard constraint on `decide`: it must answer from PROPERTIES OF THE\n * ROW. A rule that answers by looking the sandbox up in the product's own\n * expectation ledger deletes `unknown-box` entirely — every unrecorded box would\n * be `foreign` by construction, and \"we were billed for a box we never asked\n * for\" would become unrepresentable. The ledger already decides recorded-ness;\n * this decides ATTRIBUTION, and the two must stay independent.\n *\n * `decide` must not throw. If it does, the throw propagates and the whole pass\n * fails — a reconciliation whose ownership rule is broken has no verdict worth\n * printing, and swallowing it would turn a broken rule into a clean bill.\n */\nexport interface SpendOwnershipRule {\n /** Named in the report and on every finding, so a reader knows what was excluded. */\n readonly label: string\n decide(candidate: SpendOwnershipCandidate): SpendOwnershipVerdict\n}\n\n/**\n * What this pass scoped itself to — present on every report, including a clean\n * one, because \"nothing fired\" and \"nothing was looked at\" are different\n * answers and a report that cannot tell them apart is the failure this closes.\n */\nexport interface SpendOwnershipSummary {\n /**\n * False when the caller declared no rule. The pass then treats every box as\n * its own — today's behaviour, which over-reports rather than under-reports —\n * and every `unknown-box` finding says on its face that a sibling product's\n * box is indistinguishable from a charge that is not ours.\n */\n readonly declared: boolean\n /** The rule's label, or null when none was declared. */\n readonly label: string | null\n /** Boxes this pass treated as this product's, and what they were charged. */\n readonly ownedBoxes: number\n readonly ownedNanoUsd: number\n /**\n * Of those, the boxes no rule could decide. Counted as owned (fail-closed) and\n * reported separately so a product can see how much of its own verdict rests\n * on rows that carried no attribution.\n */\n readonly undecidableBoxes: number\n /** Boxes attributed to another product on the same wallet. Never findings. */\n readonly foreignBoxes: number\n readonly foreignNanoUsd: number\n /**\n * Their ids, in full — an exclusion a reader cannot audit is an exclusion\n * they have to trust, and this module's whole posture is that nothing about\n * money is taken on trust.\n */\n readonly foreignSandboxIds: readonly string[]\n}\n\n/** The parts of a settlement reference id, once parsed. */\nexport interface SettlementReference {\n /** `stop` | `compute` | `egress` | `gpu-lease` | anything the platform adds. */\n readonly kind: string\n /** For compute kinds, the sandbox id. For `gpu-lease`, the lease id. */\n readonly resourceId: string\n /** The interval's start, epoch ms. Null for kinds that carry no interval. */\n readonly intervalStartMs: number | null\n}\n\n/** How a settled duration was arrived at — every duration finding carries one. */\nexport type BilledDurationBasis =\n /** The ledger row carried the duration. Exact. */\n | 'reported'\n /** `amount ÷ the product's stated hourly rate`. Exact when the rate is right. */\n | 'rate'\n /**\n * `settledAt - intervalStart`. An UPPER bound, not the billed duration: a\n * correct settlement posted late by the platform's durable settlement queue\n * reads longer here than it billed. Findings on this basis say so.\n */\n | 'reference-span'\n /** No basis available — duration rules are skipped for this row. */\n | 'unknown'\n\n// ── findings ──────────────────────────────────────────────────────────────────\n\n/** The checks this reconciler runs. Each is individually skippable, by name. */\nexport type SpendCheckId =\n /** A settlement against a box the product has no record of ever asking for. */\n | 'unknown-box'\n /** A settled duration longer than the product's own upper bound allows. */\n | 'over-ceiling'\n /** A spend window far above the trailing median — the burst shape of a defect. */\n | 'velocity'\n /** The balance the product observes has gone below its floor. */\n | 'negative-balance'\n\nexport const SPEND_CHECKS: readonly SpendCheckId[] = [\n 'unknown-box',\n 'over-ceiling',\n 'velocity',\n 'negative-balance',\n]\n\n/**\n * One discrepancy, with every number the rule compared.\n *\n * Nullable fields are per-check and deliberately present-but-null rather than\n * absent: a reader scanning a JSON dump can tell \"this rule does not measure\n * that\" from \"that measurement is missing\".\n */\nexport interface SpendFinding {\n readonly check: SpendCheckId\n /** What is wrong, in one sentence, with the numbers in it. */\n readonly message: string\n /** What to do about it. A finding without a remedy is a complaint. */\n readonly remedy: string\n readonly sandboxId: string | null\n readonly workspaceId: string | null\n /** The ledger rows that evidence this finding — the dispute's exhibit list. */\n readonly referenceIds: readonly string[]\n /** Nanodollars this finding puts in question, unsigned. */\n readonly settledNanoUsd: number\n /** `over-ceiling` — the duration actually settled, and how that was derived. */\n readonly settledMs: number | null\n readonly durationBasis: BilledDurationBasis | null\n /** `over-ceiling` — the bound it broke, and what earned that bound. */\n readonly ceilingMs: number | null\n readonly overageMs: number | null\n readonly ceilingBasis: CeilingBasis | null\n /** `velocity` — the window, its trailing median, and the ratio between them. */\n readonly windowNanoUsd: number | null\n readonly trailingMedianNanoUsd: number | null\n readonly velocityRatio: number | null\n readonly windowStartAt: number | null\n /** `negative-balance` — the observed balance and the floor it broke. */\n readonly balanceNanoUsd: number | null\n readonly balanceFloorNanoUsd: number | null\n}\n\n/** What one reconciliation pass concluded. */\nexport interface SpendReport {\n /** True when nothing fired. `ok === findings.length === 0`. */\n readonly ok: boolean\n readonly findings: readonly SpendFinding[]\n readonly checksRun: readonly SpendCheckId[]\n /** Rows the pass read, including the ones no rule looked at. */\n readonly rowsExamined: number\n /** Distinct boxes those rows settled against. */\n readonly boxesExamined: number\n /** Total charged across every examined row, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** Total credited back across every examined row, unsigned nanodollars. */\n readonly creditedNanoUsd: number\n /** What this pass claimed as its own, and what it excluded as another product's. */\n readonly ownership: SpendOwnershipSummary\n /** The instant the pass treated as \"now\". */\n readonly asOf: number\n}\n","import type {\n SettlementRow,\n SpendOwnershipRule,\n SpendOwnershipVerdict,\n} from './types'\n\n/**\n * Which settlements belong to the product running the reconciliation.\n *\n * ## The problem this module is the answer to\n *\n * A product fetches its settled rows from `/v1/billing/transactions`, scoped to\n * the BILLING OWNER — the wallet whose key paid. `product: 'sandbox'` narrows\n * that to compute, but `sandbox` is the PLATFORM's service taxonomy: every\n * consumer app's box compute wears it. So a Tangle account running two of our\n * products hands each product's reconciliation the other product's boxes, and\n * `unknown-box` — correctly, by its own rule — reports one finding per sibling\n * box. Two products on one wallet make each other's spend check useless.\n *\n * ## Why the obvious fix is the wrong fix\n *\n * The obvious fix is to reconcile only the boxes already in the product's\n * expectation ledger. That removes the false findings and removes the check:\n * `unknown-box` exists to catch \"we were billed for a box we never asked for\",\n * which is the 2026-08-05 incident's day-one signature and the ONLY thing a\n * product with no lifecycle bookkeeping can catch at all. Filtering to the\n * ledger makes a phantom charge unrepresentable — the ledger's own contents\n * would define the answer.\n *\n * So the residue — settlements against boxes with no ledger record — has to be\n * SPLIT, not dropped. A sibling's box and a phantom charge are indistinguishable\n * unless something outside the product's own bookkeeping tells them apart.\n *\n * ## What can tell them apart\n *\n * Exactly one field on a settlement row, and it is not the sandbox id. The\n * platform mints that id as `sandbox-<12 hex>` — a hash of (owner, idempotency\n * key) — so a product's own box naming never reaches the ledger row, and the\n * charge's `description` carries only the resource spec. What does survive is\n * `credit_transactions.key_id`: the platform API key the box was created under,\n * stamped from the box's own creation metadata at settlement and filterable on\n * the transactions endpoint. Each product deploys with its own key, so the key\n * is the product's billing identity as the PLATFORM recorded it — not as the\n * product asserts it after the fact.\n *\n * That asymmetry is what makes the split safe. A product cannot widen its own\n * claim by claiming; it can only recognise a stamp the platform already wrote.\n *\n * ## The three rules that keep the detection intact\n *\n * 1. **A recorded box is never excluded.** Ownership is consulted only for\n * boxes with no ledger record. A rule that is wrong or over-narrow therefore\n * cannot hide an `over-ceiling` finding on a box the product recorded — the\n * incident's own 23 findings survive any rule at all.\n * 2. **Undecidable fails closed.** A row with no key attribution is `mine`, so\n * an unattributable charge on a shared wallet is reported. Silence is never\n * the answer to \"I don't know.\"\n * 3. **A box is claimed if ANY of its rows claims it.** The fold is\n * `mine > undecidable > foreign`, which is the module's standing asymmetry:\n * every derivation error pushes toward a false alarm, never toward a missed\n * charge.\n */\n\n/**\n * Claim every settlement the platform stamped with one of these API keys.\n *\n * The shipped rule, because it is the only one built on a field the PLATFORM\n * writes. Give each product its own platform key and this separates them\n * exactly; give two products the same key and no consumer-side rule can tell\n * them apart, because after settlement there is nothing left that differs — the\n * fix then is a second key, not a cleverer predicate.\n *\n * A row with no `keyId` (a legacy row, or an export that drops the column) is\n * `undecidable`, never `foreign`: the absence of an attribution is not evidence\n * that the charge is someone else's.\n *\n * @param keyIds The product's own platform API key ids. Must be non-empty — a\n * rule that owns nothing would classify every settlement as another product's\n * and report a clean bill for an account nobody is checking.\n */\nexport function ownedByBillingKeys(keyIds: readonly string[]): SpendOwnershipRule {\n const owned = new Set(keyIds.map((id) => id.trim()).filter(Boolean))\n if (owned.size === 0) {\n throw new Error(\n 'ownedByBillingKeys needs at least one key id: a rule that owns no key classifies every ' +\n 'settlement as another product\\'s and reports a clean bill for an unchecked account.',\n )\n }\n const label = `billing key ${[...owned].join(', ')}`\n return {\n label,\n decide({ row }) {\n const keyId = row.keyId?.trim()\n if (!keyId) return 'undecidable'\n return owned.has(keyId) ? 'mine' : 'foreign'\n },\n }\n}\n\n/**\n * One box's verdict, folded over every row that settled against it.\n *\n * `mine` wins over `undecidable`, which wins over `foreign`: it takes one row\n * attributable to this product to make the box this product's problem, and one\n * unattributable row to stop the box being excluded. Both directions push\n * toward reporting, which is the only direction that cannot lose money.\n *\n * Exported because a product auditing its own scoping wants the same answer the\n * reconciler reached, not a re-derivation of it.\n */\nexport function decideBoxOwnership(\n rule: SpendOwnershipRule,\n sandboxId: string,\n rows: readonly SettlementRow[],\n): SpendOwnershipVerdict {\n let verdict: SpendOwnershipVerdict = 'foreign'\n for (const row of rows) {\n const rowVerdict = rule.decide({ row, sandboxId })\n if (rowVerdict === 'mine') return 'mine'\n if (rowVerdict === 'undecidable') verdict = 'undecidable'\n }\n return verdict\n}\n","import type { CeilingBasis, ExpectedCeiling, SpendBoxRecord } from './types'\n\n/**\n * Slack allowed between the product's bound and what the platform settled,\n * before an overage is called a discrepancy. 15 minutes.\n *\n * Not a guess: it is the platform's OWN staleness threshold for compute\n * settlement. Its runbook clears an incident when\n * `/health computeSettlement.oldestAgeSeconds` is \"back under 900\" — so 900 s is\n * the age the platform itself treats as normal settlement lag, and anything\n * inside it is drift the platform has already declared acceptable. Below that a\n * product would alert on the platform's ordinary queue behaviour; far above it\n * the tolerance starts eating the signal, because the idle window it must stay\n * well under is 3600 s in every shipped product.\n *\n * It is a caller parameter because a product that asks for a shorter idle\n * timeout must shrink this with it.\n */\nexport const DEFAULT_CEILING_TOLERANCE_MS = 900_000\n\nexport interface ComputeExpectedCeilingOptions {\n /** The instant the reconciliation treats as \"now\", epoch ms. */\n readonly asOf: number\n /** Slack before an overage counts. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n}\n\n/**\n * The upper bound on how long one box could honestly have been billable.\n *\n * The whole design constraint is that this must stay an UPPER bound under\n * everything the product cannot see. Three such blind spots exist, and they\n * pull in different directions:\n *\n * - **Platform-side suspends.** The platform can park a box the product never\n * hears about. That only ever REDUCES real billable time, so an upper bound\n * is unaffected and nothing here widens for it.\n * - **Detached runs.** The product dispatches work and disconnects. The box\n * keeps working — and billing — after the last activity the product saw, so\n * `lastActivityAt` understates the truth. An unfinished detached run\n * therefore abandons the activity-based bound entirely rather than reporting\n * a bound it cannot support.\n * - **Reconnects.** A browser or worker re-attaches and work resumes. This\n * needs no special case: a reconnect is recorded as activity, the fold takes\n * the max, and the horizon moves out on its own.\n *\n * The bound that rescues the detached case is `maxLifetimeSeconds`. The platform\n * destroys the box at `createdAt + maxLifetimeSeconds` no matter what anyone\n * observed, so a product that asks for one holds a hard bound that survives\n * every blind spot above. Both shipped products ask for 86 400 s, which is why\n * the incident — 124 to 268 hours settled against boxes with a 24-hour\n * lifetime — is detectable with no lifecycle bookkeeping at all.\n */\nexport function computeExpectedCeiling(\n record: SpendBoxRecord,\n options: ComputeExpectedCeilingOptions,\n): ExpectedCeiling {\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const { asOf } = options\n\n let basis: CeilingBasis\n let horizonAt: number\n\n if (record.deletedAt !== null) {\n basis = 'deleted'\n horizonAt = record.deletedAt\n } else if (record.stoppedAt !== null) {\n basis = 'stopped'\n horizonAt = record.stoppedAt\n } else if (record.openDetachedRunIds.length > 0) {\n // Nothing the product observed bounds this box. Fall back to the\n // reconciliation instant, and say so through `bounded: false`.\n basis = 'open-detached-run'\n horizonAt = asOf\n } else {\n basis = 'idle-timeout'\n horizonAt = record.lastActivityAt + record.idleTimeoutSeconds * 1000\n }\n\n // The hard platform bound wins whenever it is tighter — including over an\n // unfinished detached run, which is what turns an unbounded box back into a\n // bounded one.\n if (record.maxLifetimeSeconds !== null) {\n const lifetimeHorizon = record.createdAt + record.maxLifetimeSeconds * 1000\n if (lifetimeHorizon < horizonAt) {\n basis = 'max-lifetime'\n horizonAt = lifetimeHorizon\n }\n }\n\n // Time that has not elapsed cannot have been billed, so an idle window\n // reaching into the future does not widen the bound. This only ever tightens\n // the ceiling, so it cannot mask a charge.\n if (horizonAt > asOf) horizonAt = asOf\n // A horizon before creation would produce a negative ceiling; a box is at\n // minimum billable for the instant it existed.\n if (horizonAt < record.createdAt) horizonAt = record.createdAt\n\n return {\n sandboxId: record.sandboxId,\n basis,\n horizonAt,\n ceilingMs: horizonAt - record.createdAt + toleranceMs,\n toleranceMs,\n bounded: basis !== 'open-detached-run',\n }\n}\n","import type { SettlementReference, SettlementRow } from './types'\n\n/**\n * Parse the platform's settlement idempotency key.\n *\n * The platform mints it as `sandbox:<kind>:<resourceId>:<intervalStart>`\n * (`d1-usage-service.ts`), where `intervalStart` is the interval cursor in epoch\n * ms — the SAME `last_started_at` the settlement subtracts from to get its\n * billed duration. That makes this string the only place a consumer can read the\n * billed interval's start, because the ledger row itself stores no duration.\n *\n * Kinds seen in production: `stop` (an interval closing), `compute` (a heartbeat\n * claim), `egress`, `gpu-lease`. `stop` deliberately covers both a settle and a\n * late stop racing over the same claim, so the two derive one reference id and\n * the ledger's uniqueness constraint makes the overlap safe.\n *\n * Returns null for anything that is not a sandbox reference — a router\n * inference row, a grant, a refund — rather than guessing.\n */\nexport function parseSettlementReference(referenceId: string | null | undefined): SettlementReference | null {\n if (!referenceId) return null\n const parts = referenceId.split(':')\n if (parts.length < 3 || parts[0] !== 'sandbox') return null\n const kind = parts[1]\n if (!kind) return null\n\n // The trailing segment is the interval cursor ONLY when it reads as an epoch\n // instant. `sandbox:gpu-lease:<leaseId>` has no cursor, and a resource id that\n // happened to contain a colon must not have its tail eaten as one.\n const tail = parts[parts.length - 1] as string\n const tailMs = /^\\d+$/.test(tail) ? Number(tail) : Number.NaN\n const hasCursor = parts.length >= 4 && Number.isSafeInteger(tailMs) && tailMs > 0\n\n const resourceId = hasCursor ? parts.slice(2, -1).join(':') : parts.slice(2).join(':')\n if (!resourceId) return null\n\n return { kind, resourceId, intervalStartMs: hasCursor ? tailMs : null }\n}\n\n/**\n * Read the sandbox id out of the platform's aggregation key, `sandbox:<id>`.\n *\n * Distinct from the reference id: `groupKey` is the unit a billing statement\n * groups by and is deliberately NOT unique per row, while `referenceId` is\n * unique per interval. A null group key means \"do not aggregate\" (grants,\n * top-ups, refunds, transfers) and is not an error.\n */\nexport function parseSandboxGroupKey(groupKey: string | null | undefined): string | null {\n if (!groupKey) return null\n const parts = groupKey.split(':')\n if (parts.length < 2 || parts[0] !== 'sandbox') return null\n const id = parts.slice(1).join(':')\n return id || null\n}\n\n/**\n * The sandbox a settlement row is attributable to.\n *\n * The reference id wins over the group key because it is the field the platform\n * dedups on, so it is the one guaranteed present and correct on a compute\n * settlement; the group key is the fallback for rows written before a producer\n * stamped a reference, and for kinds whose reference names something else (a GPU\n * lease id, not a box).\n */\nexport function settlementSandboxId(row: SettlementRow): string | null {\n const reference = parseSettlementReference(row.referenceId)\n if (reference && reference.intervalStartMs !== null) return reference.resourceId\n return parseSandboxGroupKey(row.groupKey) ?? (reference ? reference.resourceId : null)\n}\n\n/** True when a row is a charge (the ledger stores charges as negative amounts). */\nexport function isCharge(row: SettlementRow): boolean {\n return row.amountNanoUsd < 0\n}\n\n/** A charge's magnitude in unsigned nanodollars; 0 for credits. */\nexport function chargeNanoUsd(row: SettlementRow): number {\n return row.amountNanoUsd < 0 ? -row.amountNanoUsd : 0\n}\n","import { DEFAULT_CEILING_TOLERANCE_MS, computeExpectedCeiling } from './ceiling'\nimport { decideBoxOwnership } from './ownership'\nimport { chargeNanoUsd, parseSettlementReference, settlementSandboxId } from './reference'\nimport type { SpendLedgerStorePort } from './store'\nimport {\n SPEND_CHECKS,\n type BilledDurationBasis,\n type CeilingBasis,\n type SettlementRow,\n type SpendBoxRecord,\n type SpendCheckId,\n type SpendFinding,\n type SpendOwnershipRule,\n type SpendOwnershipSummary,\n type SpendOwnershipVerdict,\n type SpendReport,\n} from './types'\n\n/** How many nanodollars in one US dollar. The ledger's unit. */\nconst NANO_PER_USD = 1_000_000_000\nconst MS_PER_HOUR = 3_600_000\n\nexport interface VelocityOptions {\n /** Bucket width for a spend window, ms. Default 24 h. */\n readonly windowMs?: number\n /** Fire when a window exceeds this multiple of the trailing median. Default 5. */\n readonly multiple?: number\n /**\n * Windows of history required before a median means anything. Default 3.\n * Below this the rule stays silent, so a product's genuine first days of\n * usage are not reported as an anomaly.\n */\n readonly minTrailingWindows?: number\n /**\n * A window under this never fires, whatever the ratio. Default $1.00.\n *\n * Without a floor the rule is useless: a trailing median of a tenth of a cent\n * makes every ordinary day a 5x outlier. $1.00 is set from the incident's own\n * distribution — the smallest of the eight affected wallets took $1.98, and\n * the two rows in the same window that were GENUINE were sub-cent. So the\n * floor sits above the noise and below every real finding.\n */\n readonly minAbsoluteNanoUsd?: number\n}\n\nconst DEFAULT_VELOCITY: Required<VelocityOptions> = {\n windowMs: 86_400_000,\n multiple: 5,\n minTrailingWindows: 3,\n minAbsoluteNanoUsd: NANO_PER_USD,\n}\n\n/** The balance the product observes, and the floor it must not cross. */\nexport interface ObservedBalance {\n /** Signed nanodollars, as the platform reports it. */\n readonly nanoUsd: number\n /** Below this is a finding. Default 0. */\n readonly floorNanoUsd?: number\n}\n\n/**\n * A box's price, nanodollars per hour, used to derive an EXACT billed duration\n * from a charge. Return null when the product does not know the box's rate; the\n * reconciler then falls back to the reference span.\n */\nexport type BoxRateResolver = (record: SpendBoxRecord | null, sandboxId: string) => number | null | undefined\n\nexport interface ReconcileSpendOptions {\n /**\n * Settled ledger rows, supplied by the product's own authenticated fetch.\n *\n * The fetch can only scope to a WALLET — `product: 'sandbox'` is the\n * platform's service taxonomy, not this product's — so on an account running\n * more than one of our products these rows carry the siblings' boxes too.\n * {@link ReconcileSpendOptions.ownership} is what separates them.\n */\n readonly rows: readonly SettlementRow[]\n /** The product's expectation ledger. */\n readonly store: SpendLedgerStorePort\n /**\n * Which of those rows are THIS product's — see {@link SpendOwnershipRule} and\n * the shipped `ownedByBillingKeys`.\n *\n * Omitting it is safe and changes nothing: the pass claims every box, which is\n * the behaviour that shipped, and the direction that over-reports rather than\n * under-reports. It is not silent about it — `report.ownership.declared` is\n * `false`, `formatSpendReport` says so above the findings, and every\n * `unknown-box` finding states on its face that a sibling product's box is\n * indistinguishable from a charge that is not ours.\n *\n * Declaring it never weakens the ledger-backed checks: ownership is consulted\n * ONLY for boxes with no expectation record, so `over-ceiling` on a recorded\n * box fires whatever the rule says.\n */\n readonly ownership?: SpendOwnershipRule\n /** Treated as \"now\". Default `Date.now()`. */\n readonly asOf?: number\n /** Ceiling slack. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */\n readonly toleranceMs?: number\n /** Box price, for the exact duration basis. A number applies to every box. */\n readonly nanoUsdPerHour?: number | BoxRateResolver\n /** Velocity tuning, or `false` to skip the rule. */\n readonly velocity?: VelocityOptions | false\n /** The workspace balance, when the product can see one. Omitted skips the rule. */\n readonly balance?: ObservedBalance\n /** Stamped onto findings so an alert names the tenant. */\n readonly workspaceId?: string\n /** Checks to leave out of this pass. */\n readonly skip?: readonly SpendCheckId[]\n}\n\nfunction usd(nano: number): string {\n return `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\nfunction hours(ms: number): string {\n return `${(ms / MS_PER_HOUR).toFixed(1)}h`\n}\n\n/** Trust order, least trustworthy first — a mixed aggregate reports the weakest. */\nconst BASIS_TRUST: readonly BilledDurationBasis[] = ['unknown', 'reference-span', 'rate', 'reported']\n\nfunction weakestBasis(a: BilledDurationBasis, b: BilledDurationBasis): BilledDurationBasis {\n return BASIS_TRUST.indexOf(a) <= BASIS_TRUST.indexOf(b) ? a : b\n}\n\n/**\n * How long one settlement billed for, and how confidently we know it.\n *\n * The ledger row does not store a duration — this is the whole reason the check\n * is subtle. Three ways to recover it, best first:\n *\n * 1. `reported` — the product's ledger view exposed it. Exact.\n * 2. `rate` — `charge / pricePerHour`. Exact, because the platform computes the\n * charge as `(durationMs / 3_600_000) * costPerHour` and nothing else enters\n * it. Requires the product to know its box's price.\n * 3. `reference-span` — `settledAt - intervalStart`, both read off the row. An\n * UPPER bound, not the duration: a correct settlement delayed by the\n * platform's durable settlement queue reads longer here than it billed. It is\n * exact for the failure this module exists to catch, because billing \"up to\n * now\" makes the settlement instant and the interval end the same moment.\n */\nfunction resolveBilledMs(\n row: SettlementRow,\n ratePerHourNano: number | null,\n): { ms: number; basis: BilledDurationBasis } {\n if (row.billedMs !== null) return { ms: row.billedMs, basis: 'reported' }\n\n const charge = chargeNanoUsd(row)\n if (ratePerHourNano !== null && ratePerHourNano > 0 && charge > 0) {\n return { ms: (charge / ratePerHourNano) * MS_PER_HOUR, basis: 'rate' }\n }\n\n const reference = parseSettlementReference(row.referenceId)\n if (reference?.intervalStartMs != null && row.createdAt > reference.intervalStartMs) {\n return { ms: row.createdAt - reference.intervalStartMs, basis: 'reference-span' }\n }\n\n return { ms: 0, basis: 'unknown' }\n}\n\nfunction median(values: readonly number[]): number {\n if (values.length === 0) return 0\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n if (sorted.length % 2 === 1) return sorted[mid] as number\n return (((sorted[mid - 1] as number) + (sorted[mid] as number)) / 2)\n}\n\n/**\n * What an `unknown-box` finding can honestly claim about WHOSE box it is.\n *\n * Three different statements, because the reader's next action differs: chase a\n * charge inside our own billing identity, chase a charge nothing attributes,\n * or first go and declare an ownership rule so the question can be answered at\n * all. A single message covering all three would be the vaguest of the three.\n */\nfunction unknownBoxAttribution(\n ownership: SpendOwnershipRule | null,\n verdict: SpendOwnershipVerdict,\n): string {\n if (!ownership) {\n return (\n ' No ownership rule was declared for this pass, so a sibling product\\'s box on the same ' +\n 'wallet reads exactly like a charge that is not ours — this finding could be either.'\n )\n }\n if (verdict === 'undecidable') {\n return (\n ` The ownership rule (${ownership.label}) could not decide it: the settlement carries no ` +\n 'billing-key attribution to exclude it by, so it is reported rather than dropped.'\n )\n }\n return ` The ownership rule (${ownership.label}) attributes it to THIS product.`\n}\n\nfunction unknownBoxRemedy(\n ownership: SpendOwnershipRule | null,\n verdict: SpendOwnershipVerdict,\n sandboxId: string,\n): string {\n const lookup = `Look up ${sandboxId} on the platform before disputing.`\n if (!ownership) {\n return (\n 'Declare `ownership` (see `ownedByBillingKeys`) so a sibling product\\'s box stops reading as ' +\n 'a discrepancy — without it this check cannot tell one from a charge that is not ours. ' +\n 'Until then, treat this as one of three things: a sibling product on the same wallet, a box ' +\n `provisioned outside the recorded seam, or a box that is not ours at all. ${lookup}`\n )\n }\n if (verdict === 'undecidable') {\n return (\n 'An unattributable charge on a shared wallet is exactly what a phantom charge looks like, so ' +\n 'it is reported by design rather than excluded. Confirm the row genuinely predates key ' +\n `attribution before dismissing it. ${lookup}`\n )\n }\n return (\n 'This box is inside this product\\'s own billing attribution and the product never recorded it, ' +\n 'so it is either a provision that bypassed the recorded seam or a charge that is not ours. ' +\n `${lookup}`\n )\n}\n\nfunction emptyFinding(check: SpendCheckId): Omit<SpendFinding, 'message' | 'remedy'> {\n return {\n check,\n sandboxId: null,\n workspaceId: null,\n referenceIds: [],\n settledNanoUsd: 0,\n settledMs: null,\n durationBasis: null,\n ceilingMs: null,\n overageMs: null,\n ceilingBasis: null,\n windowNanoUsd: null,\n trailingMedianNanoUsd: null,\n velocityRatio: null,\n windowStartAt: null,\n balanceNanoUsd: null,\n balanceFloorNanoUsd: null,\n }\n}\n\n/**\n * Diff what the platform charged against what the product believes it asked for.\n *\n * Never disputes anything and never writes: the output is a report a human acts\n * on. The platform's ledger stays authoritative — this only ever produces the\n * evidence for a conversation with it.\n */\nexport async function reconcileSpend(options: ReconcileSpendOptions): Promise<SpendReport> {\n const asOf = options.asOf ?? Date.now()\n const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS\n const workspaceId = options.workspaceId ?? null\n const skip = new Set(options.skip ?? [])\n const checksRun = SPEND_CHECKS.filter((check) => !skip.has(check))\n const runs = (check: SpendCheckId): boolean => !skip.has(check)\n\n const ownership = options.ownership ?? null\n\n const findings: SpendFinding[] = []\n let settledNanoUsd = 0\n let creditedNanoUsd = 0\n let ownedBoxes = 0\n let ownedNanoUsd = 0\n let undecidableBoxes = 0\n let foreignNanoUsd = 0\n const foreignSandboxIds: string[] = []\n\n // ── group charges by the box they are attributable to ──────────────────────\n const byBox = new Map<string, SettlementRow[]>()\n for (const row of options.rows) {\n if (row.amountNanoUsd < 0) settledNanoUsd += -row.amountNanoUsd\n else creditedNanoUsd += row.amountNanoUsd\n if (row.amountNanoUsd >= 0) continue\n const sandboxId = settlementSandboxId(row)\n if (!sandboxId) continue\n const bucket = byBox.get(sandboxId)\n if (bucket) bucket.push(row)\n else byBox.set(sandboxId, [row])\n }\n\n const rateOf = (record: SpendBoxRecord | null, sandboxId: string): number | null => {\n const rate = options.nanoUsdPerHour\n if (rate === undefined) return null\n if (typeof rate === 'number') return rate\n return rate(record, sandboxId) ?? null\n }\n\n for (const [sandboxId, rows] of byBox) {\n const record = await options.store.load(sandboxId)\n const referenceIds = rows.map((row) => row.referenceId ?? row.id)\n const charged = rows.reduce((sum, row) => sum + chargeNanoUsd(row), 0)\n\n // A box the product RECORDED is this product's by construction, and no\n // ownership rule may un-own it. That is what stops a wrong or over-narrow\n // rule from hiding an over-ceiling finding: the ledger decides recorded-ness,\n // the rule decides attribution, and the rule only ever gets a say about the\n // residue neither of them has claimed.\n const verdict: SpendOwnershipVerdict = record\n ? 'mine'\n : ownership\n ? decideBoxOwnership(ownership, sandboxId, rows)\n : 'mine'\n\n if (verdict === 'foreign') {\n foreignSandboxIds.push(sandboxId)\n foreignNanoUsd += charged\n continue\n }\n ownedBoxes += 1\n ownedNanoUsd += charged\n if (verdict === 'undecidable') undecidableBoxes += 1\n\n // ── unknown-box ──────────────────────────────────────────────────────────\n if (!record) {\n if (runs('unknown-box')) {\n findings.push({\n ...emptyFinding('unknown-box'),\n sandboxId,\n workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n message:\n `${usd(charged)} settled across ${rows.length} row(s) against sandbox ${sandboxId}, ` +\n 'which this product has no record of ever asking for.' +\n unknownBoxAttribution(ownership, verdict),\n remedy: unknownBoxRemedy(ownership, verdict, sandboxId),\n })\n }\n continue\n }\n\n // ── over-ceiling ─────────────────────────────────────────────────────────\n if (!runs('over-ceiling')) continue\n\n const ceiling = computeExpectedCeiling(record, { asOf, toleranceMs })\n const ratePerHourNano = rateOf(record, sandboxId)\n\n let settledMs = 0\n let basis: BilledDurationBasis = 'reported'\n let anyMeasured = false\n for (const row of rows) {\n const resolved = resolveBilledMs(row, ratePerHourNano)\n if (resolved.basis === 'unknown') {\n basis = weakestBasis(basis, 'unknown')\n continue\n }\n anyMeasured = true\n settledMs += resolved.ms\n basis = weakestBasis(basis, resolved.basis)\n }\n if (!anyMeasured) continue\n if (settledMs <= ceiling.ceilingMs) continue\n\n const overageMs = settledMs - ceiling.ceilingMs\n const confidence = ceiling.bounded\n ? ''\n : ' The product could not bound this box from its own observations (an unfinished detached ' +\n 'run, and no max lifetime), so the ceiling rests on the reconciliation instant: this ' +\n 'settlement bills time outside the box\\'s own life, not merely more than expected.'\n const spanCaveat =\n basis === 'reference-span'\n ? ' Duration is derived from the settlement instant minus the interval start, which ' +\n 'overstates a settlement the platform merely posted late — confirm before disputing.'\n : ''\n\n findings.push({\n ...emptyFinding('over-ceiling'),\n sandboxId,\n workspaceId: record.workspaceId || workspaceId,\n referenceIds,\n settledNanoUsd: charged,\n settledMs,\n durationBasis: basis,\n ceilingMs: ceiling.ceilingMs,\n overageMs,\n ceilingBasis: ceiling.basis,\n message:\n `Sandbox ${sandboxId} settled ${hours(settledMs)} (${usd(charged)}) across ${rows.length} ` +\n `row(s), against an expected ceiling of ${hours(ceiling.ceilingMs)} — over by ` +\n `${hours(overageMs)}. Ceiling basis: ${ceiling.basis}; duration basis: ${basis}.` +\n confidence +\n spanCaveat,\n remedy:\n `Dispute ${referenceIds.join(', ')} against the platform ledger with both numbers. ` +\n (ceiling.basis === 'stopped' || ceiling.basis === 'deleted'\n ? 'The product recorded this box as no longer running before the billed time ended, so ' +\n 'either the stop did not take or the interval was settled at the wrong boundary.'\n : 'Freeze the open interval before anything deletes this box — deleting a box with an ' +\n 'open compute interval settles the whole gap at once.'),\n })\n }\n\n // ── velocity ───────────────────────────────────────────────────────────────\n if (runs('velocity') && options.velocity !== false) {\n const cfg = { ...DEFAULT_VELOCITY, ...(options.velocity ?? {}) }\n const buckets = new Map<number, { nano: number; references: string[] }>()\n for (const row of options.rows) {\n const charge = chargeNanoUsd(row)\n if (charge === 0) continue\n // Velocity is decided per ROW, not per box, because a row naming no\n // sandbox at all still counts toward what this product spent. A sibling's\n // burst is excluded rather than paged on: a product cannot dispute a\n // charge it did not incur, and leaving them in makes one product's\n // incident wake every product on the wallet.\n if (ownership && ownership.decide({ row, sandboxId: settlementSandboxId(row) }) === 'foreign') {\n continue\n }\n const bucketStart = Math.floor(row.createdAt / cfg.windowMs) * cfg.windowMs\n const bucket = buckets.get(bucketStart)\n if (bucket) {\n bucket.nano += charge\n bucket.references.push(row.referenceId ?? row.id)\n } else {\n buckets.set(bucketStart, { nano: charge, references: [row.referenceId ?? row.id] })\n }\n }\n\n const ordered = [...buckets.entries()].sort((a, b) => a[0] - b[0])\n for (let i = 0; i < ordered.length; i++) {\n const entry = ordered[i]\n if (!entry) continue\n const [windowStartAt, bucket] = entry\n if (i < cfg.minTrailingWindows) continue\n const trailing = ordered.slice(0, i).map(([, prior]) => prior.nano)\n const trailingMedian = median(trailing)\n const threshold = Math.max(trailingMedian * cfg.multiple, cfg.minAbsoluteNanoUsd)\n if (bucket.nano <= threshold) continue\n const ratio = trailingMedian > 0 ? bucket.nano / trailingMedian : Number.POSITIVE_INFINITY\n\n findings.push({\n ...emptyFinding('velocity'),\n workspaceId,\n referenceIds: bucket.references,\n settledNanoUsd: bucket.nano,\n windowNanoUsd: bucket.nano,\n trailingMedianNanoUsd: trailingMedian,\n velocityRatio: ratio,\n windowStartAt,\n message:\n `${usd(bucket.nano)} settled in the window starting ${new Date(windowStartAt).toISOString()} ` +\n `across ${bucket.references.length} row(s), against a trailing median of ` +\n `${usd(trailingMedian)} over ${trailing.length} prior window(s) — ` +\n `${Number.isFinite(ratio) ? `${ratio.toFixed(1)}x` : 'no prior spend to compare against'}, ` +\n `over the ${cfg.multiple}x threshold.` +\n (ownership\n ? ` Counted over this product's own rows only (${ownership.label}); the wallet total ` +\n 'for the window is higher when a sibling product settled into it.'\n : ' Counted over every row on the wallet, which on a shared account includes any ' +\n 'sibling product\\'s spend.'),\n remedy:\n 'A burst of this shape is what a settlement defect looks like from the consumer side: ' +\n 'long-dormant intervals cashed out at once. Check whether these rows carry interval ' +\n 'starts far older than the settlement instant before treating it as real usage.',\n })\n }\n }\n\n // ── negative-balance ───────────────────────────────────────────────────────\n if (runs('negative-balance') && options.balance) {\n const floor = options.balance.floorNanoUsd ?? 0\n if (options.balance.nanoUsd < floor) {\n findings.push({\n ...emptyFinding('negative-balance'),\n workspaceId,\n settledNanoUsd: Math.max(0, floor - options.balance.nanoUsd),\n balanceNanoUsd: options.balance.nanoUsd,\n balanceFloorNanoUsd: floor,\n message:\n `Observed balance ${usd(options.balance.nanoUsd)} is below the floor ${usd(floor)}.`,\n remedy:\n 'Stop provisioning new compute for this owner until the balance is explained. A negative ' +\n 'balance that nobody is watching is how a billing defect becomes settled money.',\n })\n }\n }\n\n const ownershipSummary: SpendOwnershipSummary = {\n declared: ownership !== null,\n label: ownership?.label ?? null,\n ownedBoxes,\n ownedNanoUsd,\n undecidableBoxes,\n foreignBoxes: foreignSandboxIds.length,\n foreignNanoUsd,\n foreignSandboxIds,\n }\n\n return {\n ok: findings.length === 0,\n findings,\n checksRun,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n settledNanoUsd,\n creditedNanoUsd,\n ownership: ownershipSummary,\n asOf,\n }\n}\n","import type { SpendFinding, SpendOwnershipSummary, SpendReport } from './types'\n\nconst NANO_PER_USD = 1_000_000_000\n\nfunction usd(nano: number | null): string {\n return nano === null ? '—' : `$${(nano / NANO_PER_USD).toFixed(2)}`\n}\n\n/**\n * Render a reconciliation for a human deciding whether to open a dispute.\n *\n * Every finding prints its numbers, not a summary of them: the reader's next\n * action is a conversation with the platform about specific reference ids, and a\n * report that made them re-derive the durations would just be re-read alongside\n * the raw rows anyway.\n */\nexport function formatSpendReport(report: SpendReport): string {\n const lines: string[] = []\n lines.push(\n `spend reconciliation — ${report.rowsExamined} row(s), ${report.boxesExamined} box(es), ` +\n `${usd(report.settledNanoUsd)} charged, ${usd(report.creditedNanoUsd)} credited, ` +\n `as of ${new Date(report.asOf).toISOString()}`,\n )\n lines.push(`checks: ${report.checksRun.join(', ') || '(none)'}`)\n for (const line of ownershipLines(report.ownership)) lines.push(line)\n\n if (report.ok) {\n lines.push('')\n lines.push('OK — no discrepancy between the product\\'s expectations and the settled ledger.')\n return lines.join('\\n')\n }\n\n lines.push('')\n lines.push(`${report.findings.length} finding(s):`)\n for (const finding of report.findings) {\n lines.push('')\n lines.push(` [${finding.check}] ${finding.message}`)\n for (const [label, value] of measuredFields(finding)) lines.push(` ${label}: ${value}`)\n if (finding.referenceIds.length > 0) {\n lines.push(` rows: ${finding.referenceIds.join(', ')}`)\n }\n lines.push(` → ${finding.remedy}`)\n }\n return lines.join('\\n')\n}\n\n/**\n * What the pass claimed and what it set aside — printed on EVERY report,\n * clean ones included.\n *\n * A clean report that does not say what it looked at is the failure this\n * closes: an over-narrow ownership rule and a genuinely quiet account produce\n * the same \"OK\" line, and only the excluded numbers tell them apart. The\n * excluded box ids are printed in full for the same reason — an exclusion a\n * reader cannot audit is one they have to take on trust.\n */\nfunction ownershipLines(ownership: SpendOwnershipSummary): string[] {\n if (!ownership.declared) {\n return [\n `scope: NOT DECLARED — all ${ownership.ownedBoxes} settled box(es) claimed as this ` +\n 'product\\'s. A sibling product\\'s box on this wallet is reported as unknown-box; pass ' +\n '`ownership` (see `ownedByBillingKeys`) to tell the two apart.',\n ]\n }\n const lines = [\n `scope: ${ownership.label} — ${ownership.ownedBoxes} box(es) ${usd(ownership.ownedNanoUsd)} ` +\n `owned, ${ownership.foreignBoxes} box(es) ${usd(ownership.foreignNanoUsd)} excluded as ` +\n 'another product\\'s',\n ]\n if (ownership.undecidableBoxes > 0) {\n lines.push(\n ` ${ownership.undecidableBoxes} of the owned box(es) carried no billing-key ` +\n 'attribution and were claimed fail-closed',\n )\n }\n if (ownership.foreignSandboxIds.length > 0) {\n lines.push(` excluded: ${ownership.foreignSandboxIds.join(', ')}`)\n }\n return lines\n}\n\n/** Every measured field a finding carries, including the ones it left null. */\nfunction measuredFields(finding: SpendFinding): Array<[string, string]> {\n const ms = (value: number | null): string =>\n value === null ? '—' : `${(value / 3_600_000).toFixed(2)}h`\n return [\n ['sandbox', finding.sandboxId ?? '—'],\n ['workspace', finding.workspaceId ?? '—'],\n ['amount', usd(finding.settledNanoUsd)],\n ['settled', ms(finding.settledMs)],\n ['ceiling', ms(finding.ceilingMs)],\n ['overage', ms(finding.overageMs)],\n ['ceiling basis', finding.ceilingBasis ?? '—'],\n ['duration basis', finding.durationBasis ?? '—'],\n ['window', finding.windowStartAt === null ? '—' : new Date(finding.windowStartAt).toISOString()],\n ['window spend', usd(finding.windowNanoUsd)],\n ['trailing median', usd(finding.trailingMedianNanoUsd)],\n ['ratio', finding.velocityRatio === null ? '—' : `${finding.velocityRatio.toFixed(1)}x`],\n ['balance', usd(finding.balanceNanoUsd)],\n ['balance floor', usd(finding.balanceFloorNanoUsd)],\n ]\n}\n\n/** The report as a plain JSON value, for an alerting pipeline. */\nexport function spendReportToJson(report: SpendReport): string {\n return JSON.stringify(report, null, 2)\n}\n"],"mappings":";AAsTO,IAAM,eAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC3OO,SAAS,mBAAmB,QAA+C;AAChF,QAAM,QAAQ,IAAI,IAAI,OAAO,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE,OAAO,OAAO,CAAC;AACnE,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,QAAM,QAAQ,eAAe,CAAC,GAAG,KAAK,EAAE,KAAK,IAAI,CAAC;AAClD,SA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