@tangle-network/agent-app 0.45.30 → 0.45.32

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.
@@ -3,14 +3,16 @@ import {
3
3
  SPEND_CHECKS,
4
4
  chargeNanoUsd,
5
5
  computeExpectedCeiling,
6
+ decideBoxOwnership,
6
7
  formatSpendReport,
7
8
  isCharge,
9
+ ownedByBillingKeys,
8
10
  parseSandboxGroupKey,
9
11
  parseSettlementReference,
10
12
  reconcileSpend,
11
13
  settlementSandboxId,
12
14
  spendReportToJson
13
- } from "../chunk-NEJ7OMQS.js";
15
+ } from "../chunk-5LC2VXH5.js";
14
16
 
15
17
  // src/spend/store.ts
16
18
  function foldSpendBoxRecord(record, patch) {
@@ -184,9 +186,11 @@ export {
184
186
  createInMemorySpendLedgerStore,
185
187
  createSandboxSpendHooks,
186
188
  createSpendLedger,
189
+ decideBoxOwnership,
187
190
  foldSpendBoxRecord,
188
191
  formatSpendReport,
189
192
  isCharge,
193
+ ownedByBillingKeys,
190
194
  parseSandboxGroupKey,
191
195
  parseSettlementReference,
192
196
  reconcileSpend,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/spend/store.ts","../../src/spend/budget.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","import type { SpendLedger } from './store'\n\n/** Why provisioning was refused, with every number the decision used. */\nexport interface ComputeBudgetRefusal {\n readonly workspaceId: string\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for this workspace, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** How far past the cap it already is. */\n readonly overageNanoUsd: number\n readonly at: number\n}\n\n/**\n * Provisioning refused because the workspace is already past its compute cap.\n *\n * Correctable by design: every number the decision used is on the error, so a\n * product can render \"this workspace has spent $X of its $Y compute budget\" and\n * an operator can raise the cap or investigate without reading logs.\n *\n * This is the failure mode the module exists to produce. A platform billing\n * defect that used to end in a silent negative balance now ends in provisioning\n * stopping and something loud happening instead.\n */\nexport class ComputeBudgetExceededError extends Error {\n readonly workspaceId: string\n readonly limitNanoUsd: number\n readonly settledNanoUsd: number\n readonly overageNanoUsd: number\n\n constructor(refusal: ComputeBudgetRefusal) {\n super(\n `Compute budget exceeded for workspace ${refusal.workspaceId}: ` +\n `$${(refusal.settledNanoUsd / 1_000_000_000).toFixed(2)} settled against a cap of ` +\n `$${(refusal.limitNanoUsd / 1_000_000_000).toFixed(2)} ` +\n `(over by $${(refusal.overageNanoUsd / 1_000_000_000).toFixed(2)}). ` +\n 'No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.',\n )\n this.name = 'ComputeBudgetExceededError'\n this.workspaceId = refusal.workspaceId\n this.limitNanoUsd = refusal.limitNanoUsd\n this.settledNanoUsd = refusal.settledNanoUsd\n this.overageNanoUsd = refusal.overageNanoUsd\n }\n}\n\n/**\n * A per-workspace cap on sandbox compute.\n *\n * `/billing`'s budget primitive caps MODEL keys, and it works because the\n * platform enforces the cap at the key it minted. Sandbox compute has no such\n * key: a box bills the shared company wallet, so nothing upstream refuses. This\n * carries the same shape to the one place a consumer can still act — the moment\n * before it asks for another box.\n *\n * `settledNanoUsd` is a callback rather than a number because the authority is\n * the platform ledger, not this package: the product reads the same rows it\n * hands the reconciler. Cache it if the read is expensive; a cap is a\n * coarse-grained control and a slightly stale total still refuses.\n */\nexport interface ComputeBudget {\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for the workspace, unsigned nanodollars. */\n readonly settledNanoUsd: (workspaceId: string) => Promise<number> | number\n /**\n * Called on every refusal, before the error is thrown. This is the alert\n * seam: a refusal nobody hears is a product that silently stopped working.\n */\n readonly onRefusal?: (refusal: ComputeBudgetRefusal) => void\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n}\n\n/**\n * Throw {@link ComputeBudgetExceededError} when the workspace is already past\n * its cap. Returns normally — and reads nothing — when no budget is configured.\n *\n * Deliberately a pre-check against spend ALREADY SETTLED, not a reservation\n * against spend about to happen: settlement lags provisioning by design (the\n * platform's durable settlement queue), so there is no instant at which a\n * consumer could hold an accurate running total. The cap therefore overshoots by\n * at most the unsettled tail, which is bounded by the box's own idle timeout.\n * A cap that refuses one box late is worth far more than one that cannot be\n * implemented honestly.\n */\nexport async function assertComputeBudget(\n budget: ComputeBudget | undefined,\n workspaceId: string,\n): Promise<void> {\n if (!budget) return\n const settledNanoUsd = await budget.settledNanoUsd(workspaceId)\n if (settledNanoUsd < budget.limitNanoUsd) return\n\n const refusal: ComputeBudgetRefusal = {\n workspaceId,\n limitNanoUsd: budget.limitNanoUsd,\n settledNanoUsd,\n overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,\n at: (budget.now ?? Date.now)(),\n }\n budget.onRefusal?.(refusal)\n throw new ComputeBudgetExceededError(refusal)\n}\n\n// ── the /sandbox seam ─────────────────────────────────────────────────────────\n\n/**\n * What `/sandbox` reports once a box is provisioned, reused or resumed.\n *\n * Structurally identical to `SandboxProvisionedObservation` in `/sandbox`, and\n * deliberately re-declared rather than imported: `/spend` composes `/sandbox`,\n * so a type import in the other direction would invert the dependency. The two\n * are pinned together by a compile-time assignment in this module's tests.\n */\nexport interface SpendProvisionObservation {\n readonly workspaceId: string\n readonly userId?: string\n readonly sandboxId: string\n readonly boxKey?: string | undefined\n readonly idleTimeoutSeconds: number\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * The optional seam `EnsureWorkspaceSandboxOptions.spend` and the turn\n * primitives' `spend` option both accept. One object, wired in both places.\n */\nexport interface SandboxSpendSeam {\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n onProvisioned?(observation: SpendProvisionObservation): Promise<void> | void\n /** Synchronous by contract — it sits on the turn path. See `createSandboxSpendHooks`. */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n\nexport interface SandboxSpendHooksOptions {\n /** Records box lifecycle. Omit to run the budget guard alone. */\n readonly ledger?: SpendLedger\n /** Refuses provisioning past a cap. Omit to record alone. */\n readonly budget?: ComputeBudget\n /**\n * Called when RECORDING fails. Recording is best-effort — a bookkeeping\n * failure must never take down the provisioning it is bookkeeping — so this\n * is the only place such a failure is visible. A refusal is NOT routed here;\n * refusals throw, by design.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Build the object to hand `ensureWorkspaceSandbox`'s `spend` option.\n *\n * Wiring it is the entire adoption cost: one field, and the product's boxes are\n * both budget-capped and recorded.\n */\nexport function createSandboxSpendHooks(options: SandboxSpendHooksOptions): SandboxSpendSeam {\n const { ledger, budget, onError } = options\n return {\n async beforeProvision(input) {\n await assertComputeBudget(budget, input.workspaceId)\n },\n async onProvisioned(observation) {\n if (!ledger) return\n try {\n await ledger.observeSandbox({\n sandboxId: observation.sandboxId,\n workspaceId: observation.workspaceId,\n idleTimeoutSeconds: observation.idleTimeoutSeconds,\n maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,\n at: observation.at,\n })\n } catch (err) {\n onError?.(err)\n }\n },\n onActivity(input) {\n if (!ledger) return\n // The turn path calls this synchronously and does not await it, so the\n // promise is settled here rather than escaping as an unhandled rejection.\n // Recording activity is a monotonic max, so a write that lands late — or\n // out of order against another turn's — still converges.\n void ledger.recordActivity(input.sandboxId, input.at).catch((err: unknown) => onError?.(err))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuCO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,OAAO;AAEhC,MAAI,MAAM,uBAAuB,QAAW;AAC1C,qBAAiB,KAAK,IAAI,gBAAgB,MAAM,kBAAkB;AAClE,QAAI,cAAc,QAAQ,MAAM,qBAAqB,UAAW,aAAY;AAAA,EAC9E;AACA,MAAI,MAAM,uBAAuB,UAAa,CAAC,mBAAmB,SAAS,MAAM,kBAAkB,GAAG;AACpG,yBAAqB,CAAC,GAAG,oBAAoB,MAAM,kBAAkB;AAAA,EACvE;AACA,MAAI,MAAM,0BAA0B,QAAW;AAC7C,yBAAqB,mBAAmB,OAAO,CAAC,OAAO,OAAO,MAAM,qBAAqB;AAAA,EAC3F;AACA,MAAI,MAAM,cAAc,QAAW;AAGjC,gBAAY,MAAM,aAAa,iBAAiB,MAAM,YAAY;AAAA,EACpE;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,WAAW,OAAO,aAAa,MAAM,aAAa;AAAA,EACpD;AACF;AAWO,SAAS,iCAA2D;AACzE,QAAM,OAAO,oBAAI,IAA4B;AAC7C,SAAO;AAAA,IACL,MAAM,KAAK,WAAW;AACpB,YAAM,MAAM,KAAK,IAAI,SAAS;AAC9B,aAAO,MAAM,gBAAgB,GAAG,IAAI;AAAA,IACtC;AAAA,IACA,MAAM,OAAO,QAAQ;AACnB,YAAM,SAAS,gBAAgB,MAAM;AACrC,WAAK,IAAI,OAAO,WAAW,MAAM;AACjC,aAAO,gBAAgB,MAAM;AAAA,IAC/B;AAAA,IACA,MAAM,OAAO,WAAW,OAA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C/B;AACA,SAAO,YAAY,OAAO;AAC1B,QAAM,IAAI,2BAA2B,OAAO;AAC9C;AAqDO,SAAS,wBAAwB,SAAqD;AAC3F,QAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,SAAO;AAAA,IACL,MAAM,gBAAgB,OAAO;AAC3B,YAAM,oBAAoB,QAAQ,MAAM,WAAW;AAAA,IACrD;AAAA,IACA,MAAM,cAAc,aAAa;AAC/B,UAAI,CAAC,OAAQ;AACb,UAAI;AACF,cAAM,OAAO,eAAe;AAAA,UAC1B,WAAW,YAAY;AAAA,UACvB,aAAa,YAAY;AAAA,UACzB,oBAAoB,YAAY;AAAA,UAChC,oBAAoB,YAAY,sBAAsB;AAAA,UACtD,IAAI,YAAY;AAAA,QAClB,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,kBAAU,GAAG;AAAA,MACf;AAAA,IACF;AAAA,IACA,WAAW,OAAO;AAChB,UAAI,CAAC,OAAQ;AAKb,WAAK,OAAO,eAAe,MAAM,WAAW,MAAM,EAAE,EAAE,MAAM,CAAC,QAAiB,UAAU,GAAG,CAAC;AAAA,IAC9F;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/spend/store.ts","../../src/spend/budget.ts"],"sourcesContent":["import type { SpendBoxPatch, SpendBoxRecord } from './types'\n\n/**\n * Persistence seam for the expectation ledger — the product implements it over\n * its own tables.\n *\n * Deliberately NOT compare-and-set, unlike `MissionStorePort`. A mission has one\n * serialized owner and a lost write corrupts a state machine; a box record is a\n * MONOTONIC FOLD (activity takes a max, a detached-run id joins or leaves a set,\n * delete is set-once) so concurrent writers converge no matter what order they\n * land in. The worst a lost race can do here is leave `lastActivityAt` behind\n * the truth — which makes the derived ceiling TIGHTER, so the failure mode is a\n * false alarm a human dismisses, never a missed charge. That asymmetry is the\n * whole reason the fold is shaped this way.\n *\n * `update` returns null when the row does not exist, never a throw.\n */\nexport interface SpendLedgerStorePort {\n load(sandboxId: string): Promise<SpendBoxRecord | null>\n /** `extras` are the opaque product-column values — write them in the SAME\n * statement as the record, or ignore them if the table has no extra columns. */\n insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord>\n update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null>\n}\n\n/**\n * Apply one fold step. Exported so a SQL implementation and an in-memory one\n * reach the same record, and so a product can unit-test its own store against\n * the canonical answer.\n *\n * The two rules worth stating out loud:\n *\n * - `observedActivityAt` only ever moves `lastActivityAt` FORWARD. A replayed\n * or out-of-order event cannot rewind the ceiling.\n * - activity later than a recorded `stoppedAt` CLEARS the stop. A box that\n * worked after the product thought it stopped is running again, and keeping\n * the stale stop would make the ceiling too tight — inventing an over-ceiling\n * finding out of the product's own bookkeeping rather than the platform's.\n */\nexport function foldSpendBoxRecord(record: SpendBoxRecord, patch: SpendBoxPatch): SpendBoxRecord {\n let lastActivityAt = record.lastActivityAt\n let stoppedAt = record.stoppedAt\n let openDetachedRunIds = record.openDetachedRunIds\n\n if (patch.observedActivityAt !== undefined) {\n lastActivityAt = Math.max(lastActivityAt, patch.observedActivityAt)\n if (stoppedAt !== null && patch.observedActivityAt > stoppedAt) stoppedAt = null\n }\n if (patch.openDetachedRunAdd !== undefined && !openDetachedRunIds.includes(patch.openDetachedRunAdd)) {\n openDetachedRunIds = [...openDetachedRunIds, patch.openDetachedRunAdd]\n }\n if (patch.openDetachedRunRemove !== undefined) {\n openDetachedRunIds = openDetachedRunIds.filter((id) => id !== patch.openDetachedRunRemove)\n }\n if (patch.stoppedAt !== undefined) {\n // Latest-wins, but never behind observed activity: a stop we are told about\n // that predates work we watched is not the stop that closed this box.\n stoppedAt = patch.stoppedAt >= lastActivityAt ? patch.stoppedAt : stoppedAt\n }\n\n return {\n ...record,\n lastActivityAt,\n stoppedAt,\n openDetachedRunIds,\n // Set-once: a deleted sandbox id never comes back, so a second observation\n // is a duplicate delivery, not a second deletion.\n deletedAt: record.deletedAt ?? patch.deletedAt ?? null,\n }\n}\n\n/** An in-memory store that also lets a test inspect and force state. */\nexport interface InMemorySpendLedgerStore extends SpendLedgerStorePort {\n /** Every record, insertion order. */\n records(): SpendBoxRecord[]\n /** Unguarded direct write — simulates a crash-shaped or platform-seeded row. */\n put(record: SpendBoxRecord): void\n}\n\n/** Create an in-memory expectation ledger. Production writers use the same port. */\nexport function createInMemorySpendLedgerStore(): InMemorySpendLedgerStore {\n const rows = new Map<string, SpendBoxRecord>()\n return {\n async load(sandboxId) {\n const row = rows.get(sandboxId)\n return row ? structuredClone(row) : null\n },\n async insert(record) {\n const stored = structuredClone(record)\n rows.set(record.sandboxId, stored)\n return structuredClone(stored)\n },\n async update(sandboxId, patch) {\n const current = rows.get(sandboxId)\n if (!current) return null\n const next = foldSpendBoxRecord(current, patch)\n rows.set(sandboxId, next)\n return structuredClone(next)\n },\n records() {\n return [...rows.values()].map((row) => structuredClone(row))\n },\n put(record) {\n rows.set(record.sandboxId, structuredClone(record))\n },\n }\n}\n\n/** What the product tells the ledger when it first sees a box. */\nexport interface ObserveSandboxInput {\n readonly sandboxId: string\n readonly workspaceId: string\n /** The idle timeout the product asked the platform for, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime the product asked for, seconds, when it asked for one. */\n readonly maxLifetimeSeconds?: number | null\n /** Defaults to the ledger's clock. */\n readonly at?: number\n}\n\nexport interface SpendLedgerOptions {\n readonly store: SpendLedgerStorePort\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n /** Product columns written verbatim on every insert. */\n readonly extras?: Record<string, unknown>\n}\n\n/**\n * The recording half of spend verification: the product's own account of what\n * it asked the platform for.\n *\n * Every method is best-effort from the caller's point of view — a product wires\n * these into paths that must not fail because bookkeeping failed. They still\n * reject on a store error rather than swallowing it, so a caller that wants\n * fire-and-forget says so at the call site (`/sandbox`'s hook does).\n */\nexport interface SpendLedger {\n /**\n * Record that a box exists and is billable from now. Inserts on first sight,\n * and otherwise records activity — reuse and resume are both \"the platform is\n * charging for this box again\", and the record's own existence is what\n * distinguishes them, so no caller has to know which happened.\n */\n observeSandbox(input: ObserveSandboxInput): Promise<SpendBoxRecord>\n /** Record that the product saw this box do work. */\n recordActivity(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /**\n * Record that the product handed the platform work it will NOT watch finish.\n * Until the matching end is recorded, this box's ceiling cannot rest on\n * observed activity — see `computeExpectedCeiling`.\n */\n recordDetachedRunStarted(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that a detached run was confirmed finished. */\n recordDetachedRunEnded(sandboxId: string, runId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box stopped. */\n recordStopped(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n /** Record that the product knows this box was deleted. */\n recordDeleted(sandboxId: string, at?: number): Promise<SpendBoxRecord | null>\n}\n\n/** Create the recording half over a product-supplied store. */\nexport function createSpendLedger(options: SpendLedgerOptions): SpendLedger {\n const { store } = options\n const clock = options.now ?? Date.now\n\n return {\n async observeSandbox(input) {\n const at = input.at ?? clock()\n const existing = await store.load(input.sandboxId)\n if (existing) {\n const updated = await store.update(input.sandboxId, { observedActivityAt: at })\n return updated ?? existing\n }\n return await store.insert(\n {\n sandboxId: input.sandboxId,\n workspaceId: input.workspaceId,\n createdAt: at,\n idleTimeoutSeconds: input.idleTimeoutSeconds,\n maxLifetimeSeconds: input.maxLifetimeSeconds ?? null,\n lastActivityAt: at,\n openDetachedRunIds: [],\n stoppedAt: null,\n deletedAt: null,\n },\n options.extras,\n )\n },\n async recordActivity(sandboxId, at) {\n return await store.update(sandboxId, { observedActivityAt: at ?? clock() })\n },\n async recordDetachedRunStarted(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunAdd: runId,\n })\n },\n async recordDetachedRunEnded(sandboxId, runId, at) {\n return await store.update(sandboxId, {\n observedActivityAt: at ?? clock(),\n openDetachedRunRemove: runId,\n })\n },\n async recordStopped(sandboxId, at) {\n return await store.update(sandboxId, { stoppedAt: at ?? clock() })\n },\n async recordDeleted(sandboxId, at) {\n return await store.update(sandboxId, { deletedAt: at ?? clock() })\n },\n }\n}\n","import type { SpendLedger } from './store'\n\n/** Why provisioning was refused, with every number the decision used. */\nexport interface ComputeBudgetRefusal {\n readonly workspaceId: string\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for this workspace, unsigned nanodollars. */\n readonly settledNanoUsd: number\n /** How far past the cap it already is. */\n readonly overageNanoUsd: number\n readonly at: number\n}\n\n/**\n * Provisioning refused because the workspace is already past its compute cap.\n *\n * Correctable by design: every number the decision used is on the error, so a\n * product can render \"this workspace has spent $X of its $Y compute budget\" and\n * an operator can raise the cap or investigate without reading logs.\n *\n * This is the failure mode the module exists to produce. A platform billing\n * defect that used to end in a silent negative balance now ends in provisioning\n * stopping and something loud happening instead.\n */\nexport class ComputeBudgetExceededError extends Error {\n readonly workspaceId: string\n readonly limitNanoUsd: number\n readonly settledNanoUsd: number\n readonly overageNanoUsd: number\n\n constructor(refusal: ComputeBudgetRefusal) {\n super(\n `Compute budget exceeded for workspace ${refusal.workspaceId}: ` +\n `$${(refusal.settledNanoUsd / 1_000_000_000).toFixed(2)} settled against a cap of ` +\n `$${(refusal.limitNanoUsd / 1_000_000_000).toFixed(2)} ` +\n `(over by $${(refusal.overageNanoUsd / 1_000_000_000).toFixed(2)}). ` +\n 'No sandbox was provisioned. Raise the cap or reconcile the spend before retrying.',\n )\n this.name = 'ComputeBudgetExceededError'\n this.workspaceId = refusal.workspaceId\n this.limitNanoUsd = refusal.limitNanoUsd\n this.settledNanoUsd = refusal.settledNanoUsd\n this.overageNanoUsd = refusal.overageNanoUsd\n }\n}\n\n/**\n * A per-workspace cap on sandbox compute.\n *\n * `/billing`'s budget primitive caps MODEL keys, and it works because the\n * platform enforces the cap at the key it minted. Sandbox compute has no such\n * key: a box bills the shared company wallet, so nothing upstream refuses. This\n * carries the same shape to the one place a consumer can still act — the moment\n * before it asks for another box.\n *\n * `settledNanoUsd` is a callback rather than a number because the authority is\n * the platform ledger, not this package: the product reads the same rows it\n * hands the reconciler. Cache it if the read is expensive; a cap is a\n * coarse-grained control and a slightly stale total still refuses.\n */\nexport interface ComputeBudget {\n /** The cap, unsigned nanodollars. */\n readonly limitNanoUsd: number\n /** Cumulative settled compute spend for the workspace, unsigned nanodollars. */\n readonly settledNanoUsd: (workspaceId: string) => Promise<number> | number\n /**\n * Called on every refusal, before the error is thrown. This is the alert\n * seam: a refusal nobody hears is a product that silently stopped working.\n */\n readonly onRefusal?: (refusal: ComputeBudgetRefusal) => void\n /** Injectable clock (epoch ms). Default `Date.now`. */\n readonly now?: () => number\n}\n\n/**\n * Throw {@link ComputeBudgetExceededError} when the workspace is already past\n * its cap. Returns normally — and reads nothing — when no budget is configured.\n *\n * Deliberately a pre-check against spend ALREADY SETTLED, not a reservation\n * against spend about to happen: settlement lags provisioning by design (the\n * platform's durable settlement queue), so there is no instant at which a\n * consumer could hold an accurate running total. The cap therefore overshoots by\n * at most the unsettled tail, which is bounded by the box's own idle timeout.\n * A cap that refuses one box late is worth far more than one that cannot be\n * implemented honestly.\n */\nexport async function assertComputeBudget(\n budget: ComputeBudget | undefined,\n workspaceId: string,\n): Promise<void> {\n if (!budget) return\n const settledNanoUsd = await budget.settledNanoUsd(workspaceId)\n if (settledNanoUsd < budget.limitNanoUsd) return\n\n const refusal: ComputeBudgetRefusal = {\n workspaceId,\n limitNanoUsd: budget.limitNanoUsd,\n settledNanoUsd,\n overageNanoUsd: settledNanoUsd - budget.limitNanoUsd,\n at: (budget.now ?? Date.now)(),\n }\n budget.onRefusal?.(refusal)\n throw new ComputeBudgetExceededError(refusal)\n}\n\n// ── the /sandbox seam ─────────────────────────────────────────────────────────\n\n/**\n * What `/sandbox` reports once a box is provisioned, reused or resumed.\n *\n * Structurally identical to `SandboxProvisionedObservation` in `/sandbox`, and\n * deliberately re-declared rather than imported: `/spend` composes `/sandbox`,\n * so a type import in the other direction would invert the dependency. The two\n * are pinned together by a compile-time assignment in this module's tests.\n */\nexport interface SpendProvisionObservation {\n readonly workspaceId: string\n readonly userId?: string\n readonly sandboxId: string\n readonly boxKey?: string | undefined\n readonly idleTimeoutSeconds: number\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * The optional seam `EnsureWorkspaceSandboxOptions.spend` and the turn\n * primitives' `spend` option both accept. One object, wired in both places.\n */\nexport interface SandboxSpendSeam {\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n onProvisioned?(observation: SpendProvisionObservation): Promise<void> | void\n /** Synchronous by contract — it sits on the turn path. See `createSandboxSpendHooks`. */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n\nexport interface SandboxSpendHooksOptions {\n /** Records box lifecycle. Omit to run the budget guard alone. */\n readonly ledger?: SpendLedger\n /** Refuses provisioning past a cap. Omit to record alone. */\n readonly budget?: ComputeBudget\n /**\n * Called when RECORDING fails. Recording is best-effort — a bookkeeping\n * failure must never take down the provisioning it is bookkeeping — so this\n * is the only place such a failure is visible. A refusal is NOT routed here;\n * refusals throw, by design.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Build the object to hand `ensureWorkspaceSandbox`'s `spend` option.\n *\n * Wiring it is the entire adoption cost: one field, and the product's boxes are\n * both budget-capped and recorded.\n */\nexport function createSandboxSpendHooks(options: SandboxSpendHooksOptions): SandboxSpendSeam {\n const { ledger, budget, onError } = options\n return {\n async beforeProvision(input) {\n await assertComputeBudget(budget, input.workspaceId)\n },\n async onProvisioned(observation) {\n if (!ledger) return\n try {\n await ledger.observeSandbox({\n sandboxId: observation.sandboxId,\n workspaceId: observation.workspaceId,\n idleTimeoutSeconds: observation.idleTimeoutSeconds,\n maxLifetimeSeconds: observation.maxLifetimeSeconds ?? null,\n at: observation.at,\n })\n } catch (err) {\n onError?.(err)\n }\n },\n onActivity(input) {\n if (!ledger) return\n // The turn path calls this synchronously and does not await it, so the\n // promise is settled here rather than escaping as an unhandled rejection.\n // Recording activity is a monotonic max, so a write that lands late — or\n // out of order against another turn's — still converges.\n void ledger.recordActivity(input.sandboxId, input.at).catch((err: unknown) => onError?.(err))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuCO,SAAS,mBAAmB,QAAwB,OAAsC;AAC/F,MAAI,iBAAiB,OAAO;AAC5B,MAAI,YAAY,OAAO;AACvB,MAAI,qBAAqB,OAAO;AAEhC,MAAI,MAAM,uBAAuB,QAAW;AAC1C,qBAAiB,KAAK,IAAI,gBAAgB,MAAM,kBAAkB;AAClE,QAAI,cAAc,QAAQ,MAAM,qBAAqB,UAAW,aAAY;AAAA,EAC9E;AACA,MAAI,MAAM,uBAAuB,UAAa,CAAC,mBAAmB,SAAS,MAAM,kBAAkB,GAAG;AACpG,yBAAqB,CAAC,GAAG,oBAAoB,MAAM,kBAAkB;AAAA,EACvE;AACA,MAAI,MAAM,0BAA0B,QAAW;AAC7C,yBAAqB,mBAAmB,OAAO,CAAC,OAAO,OAAO,MAAM,qBAAqB;AAAA,EAC3F;AACA,MAAI,MAAM,cAAc,QAAW;AAGjC,gBAAY,MAAM,aAAa,iBAAiB,MAAM,YAAY;AAAA,EACpE;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,WAAW,OAAO,aAAa,MAAM,aAAa;AAAA,EACpD;AACF;AAWO,SAAS,iCAA2D;AACzE,QAAM,OAAO,oBAAI,IAA4B;AAC7C,SAAO;AAAA,IACL,MAAM,KAAK,WAAW;AACpB,YAAM,MAAM,KAAK,IAAI,SAAS;AAC9B,aAAO,MAAM,gBAAgB,GAAG,IAAI;AAAA,IACtC;AAAA,IACA,MAAM,OAAO,QAAQ;AACnB,YAAM,SAAS,gBAAgB,MAAM;AACrC,WAAK,IAAI,OAAO,WAAW,MAAM;AACjC,aAAO,gBAAgB,MAAM;AAAA,IAC/B;AAAA,IACA,MAAM,OAAO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K;AAAA,EAC/B;AACA,SAAO,YAAY,OAAO;AAC1B,QAAM,IAAI,2BAA2B,OAAO;AAC9C;AAqDO,SAAS,wBAAwB,SAAqD;AAC3F,QAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,SAAO;AAAA,IACL,MAAM,gBAAgB,OAAO;AAC3B,YAAM,oBAAoB,QAAQ,MAAM,WAAW;AAAA,IACrD;AAAA,IACA,MAAM,cAAc,aAAa;AAC/B,UAAI,CAAC,OAAQ;AACb,UAAI;AACF,cAAM,OAAO,eAAe;AAAA,UAC1B,WAAW,YAAY;AAAA,UACvB,aAAa,YAAY;AAAA,UACzB,oBAAoB,YAAY;AAAA,UAChC,oBAAoB,YAAY,sBAAsB;AAAA,UACtD,IAAI,YAAY;AAAA,QAClB,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,kBAAU,GAAG;AAAA,MACf;AAAA,IACF;AAAA,IACA,WAAW,OAAO;AAChB,UAAI,CAAC,OAAQ;AAKb,WAAK,OAAO,eAAe,MAAM,WAAW,MAAM,EAAE,EAAE,MAAM,CAAC,QAAiB,UAAU,GAAG,CAAC;AAAA,IAC9F;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.45.30",
3
+ "version": "0.45.32",
4
4
  "packageManager": "pnpm@11.17.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/spend/types.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 product's fetch MUST scope rows to boxes it owns. Products bill to a\n * shared company key, so an unscoped fetch returns every sibling product's\n * settlements and every one of them is a correct `unknown-box` finding.\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\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 /** The instant the pass treated as \"now\". */\n readonly asOf: number\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 { 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 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 * MUST be scoped to boxes this product owns. Products bill to a shared company\n * key, so an unscoped fetch returns every sibling product's settlements and\n * every one is a correct — and useless — `unknown-box` finding.\n */\n readonly rows: readonly SettlementRow[]\n /** The product's expectation ledger. */\n readonly store: SpendLedgerStorePort\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\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 findings: SpendFinding[] = []\n let settledNanoUsd = 0\n let creditedNanoUsd = 0\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 // ── 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 remedy:\n 'Either the fetch is not scoped to this product\\'s own boxes (fix the scope — a shared ' +\n 'billing key returns every sibling product\\'s settlements), or a box was provisioned ' +\n 'outside the recorded seam, or the platform billed a box that is not ours. Identify ' +\n `which by looking up ${sandboxId} on the platform before disputing.`,\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 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 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 return {\n ok: findings.length === 0,\n findings,\n checksRun,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n settledNanoUsd,\n creditedNanoUsd,\n asOf,\n }\n}\n","import type { SpendFinding, 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\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/** 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":";AA6MO,IAAM,eAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AChMO,IAAM,+BAA+B;AAmCrC,SAAS,uBACd,QACA,SACiB;AACjB,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,EAAE,KAAK,IAAI;AAEjB,MAAI;AACJ,MAAI;AAEJ,MAAI,OAAO,cAAc,MAAM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