@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.
- package/dist/{agent-session-controls-1q1XR3j8.d.ts → agent-session-controls-CCeu5QLS.d.ts} +59 -5
- package/dist/assistant/index.d.ts +1 -1
- package/dist/assistant/index.js +2 -2
- package/dist/chat-react/index.d.ts +1 -1
- package/dist/chat-react/index.js +1 -1
- package/dist/{chunk-MIZMWCKW.js → chunk-3AXSERRK.js} +258 -110
- package/dist/chunk-3AXSERRK.js.map +1 -0
- package/dist/{chunk-AIHKKLKY.js → chunk-H3LYJIAQ.js} +2 -2
- package/dist/chunk-H3LYJIAQ.js.map +1 -0
- package/dist/{chunk-5LC2VXH5.js → chunk-TRWJ5CRT.js} +205 -5
- package/dist/chunk-TRWJ5CRT.js.map +1 -0
- package/dist/spend/cli.js +1 -1
- package/dist/spend/index.d.ts +303 -3
- package/dist/spend/index.js +18 -3
- package/dist/spend/index.js.map +1 -1
- package/dist/web-react/index.d.ts +1 -1
- package/dist/web-react/index.js +6 -2
- package/package.json +6 -2
- package/dist/chunk-5LC2VXH5.js.map +0 -1
- package/dist/chunk-AIHKKLKY.js.map +0 -1
- package/dist/chunk-MIZMWCKW.js.map +0 -1
|
@@ -3,7 +3,8 @@ var SPEND_CHECKS = [
|
|
|
3
3
|
"unknown-box",
|
|
4
4
|
"over-ceiling",
|
|
5
5
|
"velocity",
|
|
6
|
-
"negative-balance"
|
|
6
|
+
"negative-balance",
|
|
7
|
+
"silent-ledger"
|
|
7
8
|
];
|
|
8
9
|
|
|
9
10
|
// src/spend/ownership.ts
|
|
@@ -73,6 +74,79 @@ function computeExpectedCeiling(record, options) {
|
|
|
73
74
|
};
|
|
74
75
|
}
|
|
75
76
|
|
|
77
|
+
// src/spend/liveness.ts
|
|
78
|
+
var DEFAULT_EXPECTATION_GRACE_MS = 9e5;
|
|
79
|
+
function assertSpendWindow(window) {
|
|
80
|
+
if (!Number.isFinite(window.startAt) || !Number.isFinite(window.endAt)) {
|
|
81
|
+
throw new Error("spend window needs finite `startAt` and `endAt` epoch-ms instants");
|
|
82
|
+
}
|
|
83
|
+
if (window.endAt <= window.startAt) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`spend window ends at or before it starts (${new Date(window.startAt).toISOString()} \u2192 ${new Date(window.endAt).toISOString()}): a zero-width window expects nothing and would certify an unchecked account.`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function boxLivenessInWindow(record, window, options = {}) {
|
|
90
|
+
const graceMs = options.graceMs ?? DEFAULT_EXPECTATION_GRACE_MS;
|
|
91
|
+
const ceiling = computeExpectedCeiling(record, { asOf: window.endAt, toleranceMs: 0 });
|
|
92
|
+
const liveFrom = record.createdAt;
|
|
93
|
+
const liveUntil = ceiling.horizonAt;
|
|
94
|
+
const overlaps = liveFrom <= window.endAt && liveUntil >= window.startAt;
|
|
95
|
+
const overlapStart = Math.max(liveFrom, window.startAt);
|
|
96
|
+
const overlapEnd = Math.min(liveUntil, window.endAt);
|
|
97
|
+
const liveMsInWindow = overlaps ? Math.max(0, overlapEnd - overlapStart) : 0;
|
|
98
|
+
return {
|
|
99
|
+
sandboxId: record.sandboxId,
|
|
100
|
+
workspaceId: record.workspaceId,
|
|
101
|
+
liveFrom,
|
|
102
|
+
liveUntil,
|
|
103
|
+
basis: ceiling.basis,
|
|
104
|
+
overlaps,
|
|
105
|
+
liveMsInWindow,
|
|
106
|
+
expectSettlement: overlaps && liveMsInWindow >= graceMs
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function assessAllExcluded(report) {
|
|
110
|
+
const { ownership, expectation } = report;
|
|
111
|
+
if (report.boxesExamined === 0 || ownership.ownedBoxes > 0) {
|
|
112
|
+
return {
|
|
113
|
+
pathological: false,
|
|
114
|
+
basis: "not-all-excluded",
|
|
115
|
+
reason: `${report.boxesExamined} box(es) examined, ${ownership.ownedBoxes} claimed as this product's \u2014 this pass looked at its own settlements.`
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (!expectation.declared) {
|
|
119
|
+
return {
|
|
120
|
+
pathological: true,
|
|
121
|
+
basis: "not-declared",
|
|
122
|
+
reason: `every one of the ${report.boxesExamined} settled box(es) was excluded as another product's, and no expectation was declared \u2014 so an over-narrow ownership rule and a genuinely idle product are indistinguishable here. Raised fail-closed; declare \`window\` and implement \`listLiveBetween\` on the expectation store to make this answerable.`
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
if (expectation.expectedBoxes === 0) {
|
|
126
|
+
return {
|
|
127
|
+
pathological: false,
|
|
128
|
+
basis: "nothing-expected",
|
|
129
|
+
reason: `every one of the ${report.boxesExamined} settled box(es) was excluded as another product's, and this product had no box live in the window (${expectation.liveBoxes} overlapping, 0 live long enough to expect a bill) \u2014 an idle product beside a busy sibling, not a broken rule.`
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
pathological: true,
|
|
134
|
+
basis: "expected-boxes-live",
|
|
135
|
+
reason: `every one of the ${report.boxesExamined} settled box(es) was excluded as another product's (${ownership.label ?? "no rule"}) while this product had ${expectation.expectedBoxes} box(es) live in the window \u2014 its own settlements should have been in there.`
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function undeclaredExpectation(graceMs) {
|
|
139
|
+
return {
|
|
140
|
+
declared: false,
|
|
141
|
+
window: null,
|
|
142
|
+
graceMs,
|
|
143
|
+
liveBoxes: 0,
|
|
144
|
+
expectedBoxes: 0,
|
|
145
|
+
settledBoxes: 0,
|
|
146
|
+
unsettledSandboxIds: []
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
76
150
|
// src/spend/reference.ts
|
|
77
151
|
function parseSettlementReference(referenceId) {
|
|
78
152
|
if (!referenceId) return null;
|
|
@@ -179,10 +253,60 @@ function emptyFinding(check) {
|
|
|
179
253
|
trailingMedianNanoUsd: null,
|
|
180
254
|
velocityRatio: null,
|
|
181
255
|
windowStartAt: null,
|
|
256
|
+
windowEndAt: null,
|
|
182
257
|
balanceNanoUsd: null,
|
|
183
|
-
balanceFloorNanoUsd: null
|
|
258
|
+
balanceFloorNanoUsd: null,
|
|
259
|
+
expectedBoxes: null,
|
|
260
|
+
settledBoxes: null,
|
|
261
|
+
liveMsInWindow: null
|
|
184
262
|
};
|
|
185
263
|
}
|
|
264
|
+
function iso(at) {
|
|
265
|
+
return new Date(at).toISOString();
|
|
266
|
+
}
|
|
267
|
+
function silentLedgerFindings(input) {
|
|
268
|
+
const { expectation, unsettled, ownership, workspaceId } = input;
|
|
269
|
+
const scope = ownership ? `the ownership rule (${ownership.label})` : "no ownership rule (none declared)";
|
|
270
|
+
if (input.coverage === "unverified") {
|
|
271
|
+
return [
|
|
272
|
+
{
|
|
273
|
+
...emptyFinding("silent-ledger"),
|
|
274
|
+
workspaceId,
|
|
275
|
+
expectedBoxes: 0,
|
|
276
|
+
settledBoxes: 0,
|
|
277
|
+
message: `This pass examined none of this product's settlements \u2014 ${input.rowsExamined} row(s) read, ${input.boxesExamined} box(es), ${input.foreignBoxes} excluded by ${scope}, 0 claimed as this product's \u2014 and no expectation was declared, so it cannot tell a genuinely idle window from a check that stopped checking. A clean bill is not one of the answers available here.`,
|
|
278
|
+
remedy: "Declare `window` and implement `listLiveBetween` on the expectation store, so this pass can state what it EXPECTED to be billed for and an empty result becomes an answer instead of a silence. Until then, verify the ledger fetch by hand for this window before treating the account as checked."
|
|
279
|
+
}
|
|
280
|
+
];
|
|
281
|
+
}
|
|
282
|
+
if (unsettled.length === 0) return [];
|
|
283
|
+
const window = expectation.window;
|
|
284
|
+
const span = window ? ` in the window ${iso(window.startAt)} \u2192 ${iso(window.endAt)}` : "";
|
|
285
|
+
if (unsettled.length === expectation.expectedBoxes) {
|
|
286
|
+
return [
|
|
287
|
+
{
|
|
288
|
+
...emptyFinding("silent-ledger"),
|
|
289
|
+
workspaceId,
|
|
290
|
+
expectedBoxes: expectation.expectedBoxes,
|
|
291
|
+
settledBoxes: 0,
|
|
292
|
+
...window ? { windowStartAt: window.startAt, windowEndAt: window.endAt } : {},
|
|
293
|
+
message: `Nothing settled against ANY of the ${expectation.expectedBoxes} box(es) this product had live${span}, out of ${expectation.liveBoxes} that overlapped it. ${input.rowsExamined} row(s) were read and ${input.foreignBoxes} box(es) excluded by ${scope}. A window in which this product ran boxes and was billed for none of them is far more likely to be a broken check than a free week \u2014 an empty or mis-scoped ledger fetch, a rotated key the ownership rule does not name, or a feed that quietly stopped returning rows all produce exactly this shape. Treat this report as unverified, not as clean.`,
|
|
294
|
+
remedy: `Check the fetch before the bill: re-run the transactions query for this exact window by hand and compare the row count with \`rowsExamined\` above. If the rows are there, the ownership rule is excluding them \u2014 compare its key ids against the key the boxes were created under. Boxes expected: ${expectation.unsettledSandboxIds.join(", ")}.`
|
|
295
|
+
}
|
|
296
|
+
];
|
|
297
|
+
}
|
|
298
|
+
return unsettled.map((box) => ({
|
|
299
|
+
...emptyFinding("silent-ledger"),
|
|
300
|
+
sandboxId: box.sandboxId,
|
|
301
|
+
workspaceId: box.workspaceId || workspaceId,
|
|
302
|
+
expectedBoxes: expectation.expectedBoxes,
|
|
303
|
+
settledBoxes: expectation.settledBoxes,
|
|
304
|
+
liveMsInWindow: box.liveMsInWindow,
|
|
305
|
+
...window ? { windowStartAt: window.startAt, windowEndAt: window.endAt } : {},
|
|
306
|
+
message: `Sandbox ${box.sandboxId} was live for ${hours(box.liveMsInWindow)}${span} and nothing settled against it, while ${expectation.settledBoxes} of this product's other expected box(es) settled normally. Its life ended on basis ${box.basis} at ${iso(box.liveUntil)}.`,
|
|
307
|
+
remedy: `One silent box beside working siblings is not a discount. Check, in order: whether its settlement is merely late (the platform treats up to 900 s of compute-settlement lag as normal, and \`expectationGraceMs\` is the dial for it); whether this box was created under a key the ownership rule does not claim, so its charges are landing on another product's report; and whether the expectation ledger's own record for ${box.sandboxId} is stale.`
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
186
310
|
async function reconcileSpend(options) {
|
|
187
311
|
const asOf = options.asOf ?? Date.now();
|
|
188
312
|
const toleranceMs = options.toleranceMs ?? DEFAULT_CEILING_TOLERANCE_MS;
|
|
@@ -191,6 +315,8 @@ async function reconcileSpend(options) {
|
|
|
191
315
|
const checksRun = SPEND_CHECKS.filter((check) => !skip.has(check));
|
|
192
316
|
const runs = (check) => !skip.has(check);
|
|
193
317
|
const ownership = options.ownership ?? null;
|
|
318
|
+
const graceMs = options.expectationGraceMs ?? DEFAULT_EXPECTATION_GRACE_MS;
|
|
319
|
+
if (options.window) assertSpendWindow(options.window);
|
|
194
320
|
const findings = [];
|
|
195
321
|
let settledNanoUsd = 0;
|
|
196
322
|
let creditedNanoUsd = 0;
|
|
@@ -199,6 +325,7 @@ async function reconcileSpend(options) {
|
|
|
199
325
|
let undecidableBoxes = 0;
|
|
200
326
|
let foreignNanoUsd = 0;
|
|
201
327
|
const foreignSandboxIds = [];
|
|
328
|
+
const ownedSandboxIds = /* @__PURE__ */ new Set();
|
|
202
329
|
const byBox = /* @__PURE__ */ new Map();
|
|
203
330
|
for (const row of options.rows) {
|
|
204
331
|
if (row.amountNanoUsd < 0) settledNanoUsd += -row.amountNanoUsd;
|
|
@@ -228,6 +355,7 @@ async function reconcileSpend(options) {
|
|
|
228
355
|
}
|
|
229
356
|
ownedBoxes += 1;
|
|
230
357
|
ownedNanoUsd += charged;
|
|
358
|
+
ownedSandboxIds.add(sandboxId);
|
|
231
359
|
if (verdict === "undecidable") undecidableBoxes += 1;
|
|
232
360
|
if (!record) {
|
|
233
361
|
if (runs("unknown-box")) {
|
|
@@ -346,8 +474,47 @@ async function reconcileSpend(options) {
|
|
|
346
474
|
foreignNanoUsd,
|
|
347
475
|
foreignSandboxIds
|
|
348
476
|
};
|
|
477
|
+
const window = options.window ?? null;
|
|
478
|
+
const canList = typeof options.store.listLiveBetween === "function";
|
|
479
|
+
let expectation = undeclaredExpectation(graceMs);
|
|
480
|
+
let unsettled = [];
|
|
481
|
+
if (window && canList) {
|
|
482
|
+
const candidates = await options.store.listLiveBetween(window);
|
|
483
|
+
const live = candidates.map((record) => boxLivenessInWindow(record, window, { graceMs })).filter((box) => box.overlaps);
|
|
484
|
+
const expected = live.filter((box) => box.expectSettlement);
|
|
485
|
+
unsettled = expected.filter((box) => !ownedSandboxIds.has(box.sandboxId));
|
|
486
|
+
expectation = {
|
|
487
|
+
declared: true,
|
|
488
|
+
window,
|
|
489
|
+
graceMs,
|
|
490
|
+
liveBoxes: live.length,
|
|
491
|
+
expectedBoxes: expected.length,
|
|
492
|
+
settledBoxes: expected.length - unsettled.length,
|
|
493
|
+
unsettledSandboxIds: unsettled.map((box) => box.sandboxId)
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
const coverage = ownedBoxes > 0 ? "verified" : expectation.declared ? expectation.expectedBoxes > 0 ? "verified" : "nothing-expected" : "unverified";
|
|
497
|
+
if (runs("silent-ledger")) {
|
|
498
|
+
findings.push(
|
|
499
|
+
...silentLedgerFindings({
|
|
500
|
+
expectation,
|
|
501
|
+
unsettled,
|
|
502
|
+
coverage,
|
|
503
|
+
ownership,
|
|
504
|
+
workspaceId,
|
|
505
|
+
rowsExamined: options.rows.length,
|
|
506
|
+
boxesExamined: byBox.size,
|
|
507
|
+
ownedBoxes,
|
|
508
|
+
foreignBoxes: foreignSandboxIds.length
|
|
509
|
+
})
|
|
510
|
+
);
|
|
511
|
+
}
|
|
349
512
|
return {
|
|
350
|
-
|
|
513
|
+
// `coverage` is the second half of the gate deliberately: skipping the
|
|
514
|
+
// `silent-ledger` check removes its findings, never the verdict, so no
|
|
515
|
+
// combination of options can make an examined-nobody pass report clean.
|
|
516
|
+
ok: findings.length === 0 && coverage !== "unverified",
|
|
517
|
+
coverage,
|
|
351
518
|
findings,
|
|
352
519
|
checksRun,
|
|
353
520
|
rowsExamined: options.rows.length,
|
|
@@ -355,6 +522,7 @@ async function reconcileSpend(options) {
|
|
|
355
522
|
settledNanoUsd,
|
|
356
523
|
creditedNanoUsd,
|
|
357
524
|
ownership: ownershipSummary,
|
|
525
|
+
expectation,
|
|
358
526
|
asOf
|
|
359
527
|
};
|
|
360
528
|
}
|
|
@@ -371,11 +539,18 @@ function formatSpendReport(report) {
|
|
|
371
539
|
);
|
|
372
540
|
lines.push(`checks: ${report.checksRun.join(", ") || "(none)"}`);
|
|
373
541
|
for (const line of ownershipLines(report.ownership)) lines.push(line);
|
|
542
|
+
for (const line of expectationLines(report.expectation)) lines.push(line);
|
|
374
543
|
if (report.ok) {
|
|
375
544
|
lines.push("");
|
|
376
545
|
lines.push("OK \u2014 no discrepancy between the product's expectations and the settled ledger.");
|
|
377
546
|
return lines.join("\n");
|
|
378
547
|
}
|
|
548
|
+
if (report.coverage === "unverified") {
|
|
549
|
+
lines.push("");
|
|
550
|
+
lines.push(
|
|
551
|
+
`UNVERIFIED \u2014 this pass examined none of this product's settlements and could not say what it expected, so it cannot certify the bill either way. Read the finding below as "do not trust this report", not as "dispute this charge".`
|
|
552
|
+
);
|
|
553
|
+
}
|
|
379
554
|
lines.push("");
|
|
380
555
|
lines.push(`${report.findings.length} finding(s):`);
|
|
381
556
|
for (const finding of report.findings) {
|
|
@@ -408,6 +583,22 @@ function ownershipLines(ownership) {
|
|
|
408
583
|
}
|
|
409
584
|
return lines;
|
|
410
585
|
}
|
|
586
|
+
function expectationLines(expectation) {
|
|
587
|
+
if (!expectation.declared) {
|
|
588
|
+
return [
|
|
589
|
+
"expectation: NOT DECLARED \u2014 this pass is driven entirely by the settlement rows it was handed, so it can say nothing about a box it asked for and was never billed for. Pass `window` and implement `listLiveBetween` on the expectation store to close that direction."
|
|
590
|
+
];
|
|
591
|
+
}
|
|
592
|
+
const window = expectation.window;
|
|
593
|
+
const span = window ? `${new Date(window.startAt).toISOString()} \u2192 ${new Date(window.endAt).toISOString()}` : "\u2014";
|
|
594
|
+
const lines = [
|
|
595
|
+
`expectation: ${span} \u2014 ${expectation.liveBoxes} box(es) live, ${expectation.expectedBoxes} expected to settle (\u2265 ${(expectation.graceMs / 6e4).toFixed(0)} min live), ${expectation.settledBoxes} did`
|
|
596
|
+
];
|
|
597
|
+
if (expectation.unsettledSandboxIds.length > 0) {
|
|
598
|
+
lines.push(` nothing settled against: ${expectation.unsettledSandboxIds.join(", ")}`);
|
|
599
|
+
}
|
|
600
|
+
return lines;
|
|
601
|
+
}
|
|
411
602
|
function measuredFields(finding) {
|
|
412
603
|
const ms = (value) => value === null ? "\u2014" : `${(value / 36e5).toFixed(2)}h`;
|
|
413
604
|
return [
|
|
@@ -420,11 +611,15 @@ function measuredFields(finding) {
|
|
|
420
611
|
["ceiling basis", finding.ceilingBasis ?? "\u2014"],
|
|
421
612
|
["duration basis", finding.durationBasis ?? "\u2014"],
|
|
422
613
|
["window", finding.windowStartAt === null ? "\u2014" : new Date(finding.windowStartAt).toISOString()],
|
|
614
|
+
["window end", finding.windowEndAt === null ? "\u2014" : new Date(finding.windowEndAt).toISOString()],
|
|
423
615
|
["window spend", usd2(finding.windowNanoUsd)],
|
|
424
616
|
["trailing median", usd2(finding.trailingMedianNanoUsd)],
|
|
425
617
|
["ratio", finding.velocityRatio === null ? "\u2014" : `${finding.velocityRatio.toFixed(1)}x`],
|
|
426
618
|
["balance", usd2(finding.balanceNanoUsd)],
|
|
427
|
-
["balance floor", usd2(finding.balanceFloorNanoUsd)]
|
|
619
|
+
["balance floor", usd2(finding.balanceFloorNanoUsd)],
|
|
620
|
+
["expected boxes", finding.expectedBoxes === null ? "\u2014" : String(finding.expectedBoxes)],
|
|
621
|
+
["settled boxes", finding.settledBoxes === null ? "\u2014" : String(finding.settledBoxes)],
|
|
622
|
+
["live in window", ms(finding.liveMsInWindow)]
|
|
428
623
|
];
|
|
429
624
|
}
|
|
430
625
|
function spendReportToJson(report) {
|
|
@@ -437,6 +632,11 @@ export {
|
|
|
437
632
|
decideBoxOwnership,
|
|
438
633
|
DEFAULT_CEILING_TOLERANCE_MS,
|
|
439
634
|
computeExpectedCeiling,
|
|
635
|
+
DEFAULT_EXPECTATION_GRACE_MS,
|
|
636
|
+
assertSpendWindow,
|
|
637
|
+
boxLivenessInWindow,
|
|
638
|
+
assessAllExcluded,
|
|
639
|
+
undeclaredExpectation,
|
|
440
640
|
parseSettlementReference,
|
|
441
641
|
parseSandboxGroupKey,
|
|
442
642
|
settlementSandboxId,
|
|
@@ -446,4 +646,4 @@ export {
|
|
|
446
646
|
formatSpendReport,
|
|
447
647
|
spendReportToJson
|
|
448
648
|
};
|
|
449
|
-
//# sourceMappingURL=chunk-
|
|
649
|
+
//# sourceMappingURL=chunk-TRWJ5CRT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/spend/types.ts","../src/spend/ownership.ts","../src/spend/ceiling.ts","../src/spend/liveness.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// ── what the product EXPECTED to be billed for ────────────────────────────────\n\n/**\n * The stretch of time a reconciliation pass covers — the same window the\n * product's own ledger fetch was scoped to.\n *\n * Declared by the caller rather than derived from the rows, because deriving it\n * from the rows is circular: a feed that returns nothing would produce a\n * zero-width window that expects nothing and certifies itself.\n */\nexport interface SpendWindow {\n /** Inclusive start, epoch ms. */\n readonly startAt: number\n /** Inclusive end, epoch ms. */\n readonly endAt: number\n}\n\n/**\n * One box's life, measured against a reconciliation window.\n *\n * The live interval is `[createdAt, horizon]`, where the horizon is the SAME one\n * `computeExpectedCeiling` derives — so a box cannot count as live for the\n * expectation check and dead for the ceiling check.\n */\nexport interface SpendBoxLiveness {\n readonly sandboxId: string\n readonly workspaceId: string\n /** First instant the box could have been billable. */\n readonly liveFrom: number\n /** Last instant it could have been, evaluated at the window's end. */\n readonly liveUntil: number\n /** Which fact closed the interval — the ceiling's own vocabulary. */\n readonly basis: CeilingBasis\n /** True when any of that life fell inside the window. */\n readonly overlaps: boolean\n /** How much of it did, in ms. Zero for a box that did not overlap. */\n readonly liveMsInWindow: number\n /**\n * True when the overlap is long enough that a settlement should have landed.\n * A box that came up moments before the window closed is live but not yet\n * expected — settlement lags provisioning, and demanding a row inside that lag\n * would report the platform's ordinary queue as a defect.\n */\n readonly expectSettlement: boolean\n}\n\n/**\n * What this pass EXPECTED to be billed for — present on every report, including\n * a clean one, for the same reason {@link SpendOwnershipSummary} is: \"nothing\n * fired\" and \"nothing was expected\" and \"nothing could be expected\" are three\n * different answers and a report that cannot tell them apart is the failure this\n * closes.\n */\nexport interface SpendExpectationSummary {\n /**\n * False when the caller declared no window, or the store cannot list its\n * boxes. The pass then cannot say what it expected — which is reported, never\n * rounded down to a clean bill.\n */\n readonly declared: boolean\n readonly window: SpendWindow | null\n /** Live ms inside the window before a settlement is expected of a box. */\n readonly graceMs: number\n /** Boxes whose life overlapped the window at all. */\n readonly liveBoxes: number\n /** Of those, the ones live long enough that a settlement should have landed. */\n readonly expectedBoxes: number\n /** Of those, the ones at least one settlement this pass claimed did land against. */\n readonly settledBoxes: number\n /**\n * The expected boxes nothing settled against, in full — the exhibit list for\n * \"the check stopped checking\", and an expectation a reader cannot audit is\n * one they have to take on trust.\n */\n readonly unsettledSandboxIds: readonly string[]\n}\n\n/**\n * How much this pass is entitled to claim about the bill.\n *\n * `ok` is gated on this, which is what makes an examined-nobody pass\n * structurally incapable of rendering as a clean bill.\n */\nexport type SpendCoverage =\n /** The pass examined this product's settlements, or knows what it expected. */\n | 'verified'\n /**\n * Expectation was declared and no box was live long enough to expect a bill.\n * Zero settlements is the RIGHT answer — an idle product, not a defect, and\n * the one case in which a pass that examined nobody is still clean.\n */\n | 'nothing-expected'\n /**\n * The pass examined none of this product's settlements and cannot say what it\n * expected. The CHECK is suspect, not the bill.\n */\n | 'unverified'\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 /**\n * The product expected settlements and saw none — the only check whose\n * subject is the CHECK rather than the bill.\n *\n * Every other rule is driven by a settlement row, so all of them go quiet\n * together when the rows stop arriving: an empty ledger fetch, a stale\n * ownership rule that excludes every box, an expectation ledger naming\n * nobody. This is the rule that fires when the others cannot, and it reads as\n * \"do not trust this report\" rather than \"dispute this charge\".\n */\n | 'silent-ledger'\n\nexport const SPEND_CHECKS: readonly SpendCheckId[] = [\n 'unknown-box',\n 'over-ceiling',\n 'velocity',\n 'negative-balance',\n 'silent-ledger',\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 /** `velocity` and `silent-ledger` — the window the finding is about. */\n readonly windowStartAt: number | null\n readonly windowEndAt: number | null\n /** `negative-balance` — the observed balance and the floor it broke. */\n readonly balanceNanoUsd: number | null\n readonly balanceFloorNanoUsd: number | null\n /** `silent-ledger` — how many boxes were expected to settle, and how many did. */\n readonly expectedBoxes: number | null\n readonly settledBoxes: number | null\n /** `silent-ledger`, per-box form — how long that box was live inside the window. */\n readonly liveMsInWindow: number | null\n}\n\n/** What one reconciliation pass concluded. */\nexport interface SpendReport {\n /**\n * True when nothing fired AND the pass earned the right to say so:\n * `findings.length === 0 && coverage !== 'unverified'`.\n *\n * The second half is not decoration. Every rule but `silent-ledger` is driven\n * by a settlement row, so a pass that read no rows — an empty ledger fetch, a\n * stale ownership rule excluding every box, an expectation ledger naming\n * nobody — fires nothing and used to report a clean bill. `coverage` is what\n * makes that shape unrepresentable, and it holds even when a caller skips the\n * `silent-ledger` check: the skip removes the finding, never the verdict.\n */\n readonly ok: boolean\n /** How much this pass is entitled to claim. See {@link SpendCoverage}. */\n readonly coverage: SpendCoverage\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 /** What this pass expected to be billed for, and what did not arrive. */\n readonly expectation: SpendExpectationSummary\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 { computeExpectedCeiling } from './ceiling'\nimport type {\n SpendBoxLiveness,\n SpendBoxRecord,\n SpendExpectationSummary,\n SpendReport,\n SpendWindow,\n} from './types'\n\n/**\n * Expectation liveness: what the product BELIEVES it should have been billed for.\n *\n * ## The hole this closes\n *\n * `reconcileSpend` compares settlements against expectations, and every one of\n * its rules is driven by a settlement row. That makes it able to answer exactly\n * one direction of the question:\n *\n * > were we billed for something we did not ask for, or for more than allowed?\n *\n * It cannot answer the other direction — *were we NOT billed for something we\n * DID ask for* — because with no row there is nothing to iterate. Three real\n * shapes fall straight through that hole and every one of them renders as a\n * clean bill:\n *\n * - the expectation ledger names no box, so the pass examines nobody → `ok:true`;\n * - the billing endpoint quietly starts returning zero rows → `ok:true`,\n * `rowsExamined:0`;\n * - a stale or rotated key list excludes every box → `ok:true` with everything\n * `foreign`.\n *\n * In all three the check stopped checking while looking green. That is the exact\n * failure class the module exists to prevent, reproduced inside the module.\n *\n * ## The discriminator, and why it is not a new store\n *\n * The expectation ledger already records the only fact needed: when the product\n * first saw a box (`createdAt`), the last work it observed (`lastActivityAt`),\n * and any stop or delete it knows about. Those are precisely the inputs\n * {@link computeExpectedCeiling} already folds into a horizon — the latest\n * instant a box could still have been billable. So a box's LIVE INTERVAL is\n * `[createdAt, horizon]`, derived from the same fold the ceiling uses rather\n * than from a second, drift-prone definition of \"running\".\n *\n * A box whose live interval overlaps the reconciliation window is a box the\n * product expected to be billed for. The absence of a settlement against it is\n * then a first-class outcome, not silence.\n *\n * ## Why the grace period is load-bearing\n *\n * Settlement lags provisioning. A box that came up ninety seconds before the\n * window closed has no settlement yet and never should have — expecting one\n * would manufacture a finding out of the platform's ordinary queue behaviour.\n * So expectation is asserted only for boxes with at least\n * {@link DEFAULT_EXPECTATION_GRACE_MS} of live time INSIDE the window, which is\n * the platform's own declared-normal settlement lag (see the constant).\n *\n * The asymmetry the rest of the module runs on holds here too, but it points the\n * other way and that is deliberate: an over-tight liveness derivation produces a\n * false ALARM about the check, never a false clean bill. Nothing in this file\n * can make a report cleaner than it would otherwise be.\n */\n\n/**\n * How much live time a box needs inside the window before a settlement is\n * EXPECTED for it. 15 minutes.\n *\n * Same number and same justification as {@link DEFAULT_CEILING_TOLERANCE_MS},\n * arrived at from the other side: the platform's runbook clears a compute\n * settlement incident when `/health computeSettlement.oldestAgeSeconds` is \"back\n * under 900\", so 900 s is lag the platform has already declared normal. A box\n * live for less than that inside the window may legitimately have settled\n * nothing yet, and demanding a row for it would report the platform's own queue\n * as a defect.\n *\n * A caller parameter, because a product reconciling a very short window must\n * shrink it or the window expects nothing at all.\n */\nexport const DEFAULT_EXPECTATION_GRACE_MS = 900_000\n\n/** Options for {@link boxLivenessInWindow}. */\nexport interface BoxLivenessOptions {\n /** Live ms inside the window before a settlement is expected. Default {@link DEFAULT_EXPECTATION_GRACE_MS}. */\n readonly graceMs?: number\n}\n\n/** Reject a window that cannot be reconciled, rather than examining nobody inside it. */\nexport function assertSpendWindow(window: SpendWindow): void {\n if (!Number.isFinite(window.startAt) || !Number.isFinite(window.endAt)) {\n throw new Error('spend window needs finite `startAt` and `endAt` epoch-ms instants')\n }\n if (window.endAt <= window.startAt) {\n throw new Error(\n `spend window ends at or before it starts (${new Date(window.startAt).toISOString()} → ` +\n `${new Date(window.endAt).toISOString()}): a zero-width window expects nothing and would ` +\n 'certify an unchecked account.',\n )\n }\n}\n\n/**\n * One box's live interval, and whether the product should have been billed for\n * it inside this window.\n *\n * The live interval's end is {@link computeExpectedCeiling}'s horizon evaluated\n * at the window's end — the SAME derivation the ceiling check uses, so a box\n * cannot be considered live here and dead there. `toleranceMs` is zero because\n * tolerance is slack allowed to the PLATFORM's clock, and widening a box's life\n * by it would expect settlements for boxes that were already gone.\n */\nexport function boxLivenessInWindow(\n record: SpendBoxRecord,\n window: SpendWindow,\n options: BoxLivenessOptions = {},\n): SpendBoxLiveness {\n const graceMs = options.graceMs ?? DEFAULT_EXPECTATION_GRACE_MS\n const ceiling = computeExpectedCeiling(record, { asOf: window.endAt, toleranceMs: 0 })\n\n const liveFrom = record.createdAt\n const liveUntil = ceiling.horizonAt\n const overlaps = liveFrom <= window.endAt && liveUntil >= window.startAt\n const overlapStart = Math.max(liveFrom, window.startAt)\n const overlapEnd = Math.min(liveUntil, window.endAt)\n const liveMsInWindow = overlaps ? Math.max(0, overlapEnd - overlapStart) : 0\n\n return {\n sandboxId: record.sandboxId,\n workspaceId: record.workspaceId,\n liveFrom,\n liveUntil,\n basis: ceiling.basis,\n overlaps,\n liveMsInWindow,\n expectSettlement: overlaps && liveMsInWindow >= graceMs,\n }\n}\n\n/** Why {@link assessAllExcluded} answered the way it did. */\nexport type AllExcludedBasis =\n /** Not every box was excluded — the pass examined some of this product's own. */\n | 'not-all-excluded'\n /** Boxes of this product's were live in the window, so an all-foreign pass is wrong. */\n | 'expected-boxes-live'\n /** Expectation was declared and nothing was live: an idle product, not a defect. */\n | 'nothing-expected'\n /** No expectation was declared, so the question cannot be answered. Fails closed. */\n | 'not-declared'\n\n/** {@link assessAllExcluded}'s verdict, with the reason a pager message needs. */\nexport interface AllExcludedAssessment {\n /** True when the caller should raise. */\n readonly pathological: boolean\n readonly basis: AllExcludedBasis\n /** One sentence naming the numbers behind the verdict. */\n readonly reason: string\n}\n\n/**\n * Should \"we saw settlements but none of them were ours\" page a human?\n *\n * Consumers raise this pathology on `boxesExamined > 0 && ownedBoxes === 0`.\n * That shape has two completely different causes and the naive test cannot tell\n * them apart:\n *\n * - an ownership rule that has gone stale — a rotated key, a new deployment key\n * nobody added — so every one of the product's OWN boxes now reads as a\n * sibling's. The check has stopped checking.\n * - a product that was legitimately idle while a sibling settled on the same\n * wallet. Nothing is wrong, and paging on it pages EVERY day the product is\n * quiet, which is how a real alert gets muted.\n *\n * The discriminator is expectation liveness: did this product have a box alive\n * during the window? Only then is an all-excluded pass pathological.\n *\n * Fails closed when no expectation was declared — that is today's behaviour, and\n * a pass that cannot answer the question must not answer it optimistically. The\n * `reason` says so, and the fix (declare `window`, implement `listLiveBetween`)\n * is in the string a human reads.\n */\nexport function assessAllExcluded(report: SpendReport): AllExcludedAssessment {\n const { ownership, expectation } = report\n if (report.boxesExamined === 0 || ownership.ownedBoxes > 0) {\n return {\n pathological: false,\n basis: 'not-all-excluded',\n reason:\n `${report.boxesExamined} box(es) examined, ${ownership.ownedBoxes} claimed as this ` +\n 'product\\'s — this pass looked at its own settlements.',\n }\n }\n if (!expectation.declared) {\n return {\n pathological: true,\n basis: 'not-declared',\n reason:\n `every one of the ${report.boxesExamined} settled box(es) was excluded as another ` +\n 'product\\'s, and no expectation was declared — so an over-narrow ownership rule and a ' +\n 'genuinely idle product are indistinguishable here. Raised fail-closed; declare `window` ' +\n 'and implement `listLiveBetween` on the expectation store to make this answerable.',\n }\n }\n if (expectation.expectedBoxes === 0) {\n return {\n pathological: false,\n basis: 'nothing-expected',\n reason:\n `every one of the ${report.boxesExamined} settled box(es) was excluded as another ` +\n `product's, and this product had no box live in the window (${expectation.liveBoxes} ` +\n 'overlapping, 0 live long enough to expect a bill) — an idle product beside a busy ' +\n 'sibling, not a broken rule.',\n }\n }\n return {\n pathological: true,\n basis: 'expected-boxes-live',\n reason:\n `every one of the ${report.boxesExamined} settled box(es) was excluded as another ` +\n `product's (${ownership.label ?? 'no rule'}) while this product had ${expectation.expectedBoxes} ` +\n 'box(es) live in the window — its own settlements should have been in there.',\n }\n}\n\n/** The expectation summary a pass that declared none reports. Loud, never absent. */\nexport function undeclaredExpectation(graceMs: number): SpendExpectationSummary {\n return {\n declared: false,\n window: null,\n graceMs,\n liveBoxes: 0,\n expectedBoxes: 0,\n settledBoxes: 0,\n unsettledSandboxIds: [],\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 {\n DEFAULT_EXPECTATION_GRACE_MS,\n assertSpendWindow,\n boxLivenessInWindow,\n undeclaredExpectation,\n} from './liveness'\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 SpendBoxLiveness,\n type SpendBoxRecord,\n type SpendCheckId,\n type SpendCoverage,\n type SpendExpectationSummary,\n type SpendFinding,\n type SpendOwnershipRule,\n type SpendOwnershipSummary,\n type SpendOwnershipVerdict,\n type SpendReport,\n type SpendWindow,\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 * The stretch of time these `rows` were fetched for.\n *\n * Declaring it — together with a store that implements `listLiveBetween` — is\n * what lets the pass answer the direction every settlement-driven rule is\n * blind to: *were we NOT billed for something we DID ask for*. The expectation\n * ledger already holds the answer; nothing new is stored for it.\n *\n * Omitting it is additive and changes no existing finding. It is not silent:\n * `report.expectation.declared` is `false`, `formatSpendReport` prints\n * `expectation: NOT DECLARED` above the findings, and a pass that also\n * examined none of this product's settlements reports `coverage: 'unverified'`\n * and cannot render as a clean bill.\n */\n readonly window?: SpendWindow\n /**\n * Live ms a box needs inside the window before a settlement is EXPECTED of it.\n * Default {@link DEFAULT_EXPECTATION_GRACE_MS} (15 min — the platform's own\n * declared-normal settlement lag). Shrink it for a short window.\n */\n readonly expectationGraceMs?: number\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 windowEndAt: null,\n balanceNanoUsd: null,\n balanceFloorNanoUsd: null,\n expectedBoxes: null,\n settledBoxes: null,\n liveMsInWindow: null,\n }\n}\n\nfunction iso(at: number): string {\n return new Date(at).toISOString()\n}\n\n/**\n * The `silent-ledger` findings — the only ones whose subject is the CHECK.\n *\n * Three distinct shapes, because the reader's next action differs in each:\n *\n * - **the whole expectation is silent** — every box this product had live in the\n * window settled nothing. One aggregate finding, because there is one cause\n * and N per-box findings would spread it across N pages.\n * - **one box is silent** while its siblings settled normally. Per-box, because\n * the cause is specific to that box and the rest of the pass is working.\n * - **the pass examined nobody and expected nothing** — no window declared, no\n * settlement claimed. It cannot tell an idle window from a check that stopped\n * checking, and says so instead of answering optimistically.\n */\nfunction silentLedgerFindings(input: {\n readonly expectation: SpendExpectationSummary\n readonly unsettled: readonly SpendBoxLiveness[]\n readonly coverage: SpendCoverage\n readonly ownership: SpendOwnershipRule | null\n readonly workspaceId: string | null\n readonly rowsExamined: number\n readonly boxesExamined: number\n readonly ownedBoxes: number\n readonly foreignBoxes: number\n}): SpendFinding[] {\n const { expectation, unsettled, ownership, workspaceId } = input\n const scope = ownership ? `the ownership rule (${ownership.label})` : 'no ownership rule (none declared)'\n\n if (input.coverage === 'unverified') {\n return [\n {\n ...emptyFinding('silent-ledger'),\n workspaceId,\n expectedBoxes: 0,\n settledBoxes: 0,\n message:\n `This pass examined none of this product's settlements — ${input.rowsExamined} row(s) read, ` +\n `${input.boxesExamined} box(es), ${input.foreignBoxes} excluded by ${scope}, 0 claimed as ` +\n 'this product\\'s — and no expectation was declared, so it cannot tell a genuinely idle ' +\n 'window from a check that stopped checking. A clean bill is not one of the answers ' +\n 'available here.',\n remedy:\n 'Declare `window` and implement `listLiveBetween` on the expectation store, so this pass ' +\n 'can state what it EXPECTED to be billed for and an empty result becomes an answer ' +\n 'instead of a silence. Until then, verify the ledger fetch by hand for this window ' +\n 'before treating the account as checked.',\n },\n ]\n }\n\n if (unsettled.length === 0) return []\n const window = expectation.window\n const span = window ? ` in the window ${iso(window.startAt)} → ${iso(window.endAt)}` : ''\n\n // Every expected box silent: one cause, one finding.\n if (unsettled.length === expectation.expectedBoxes) {\n return [\n {\n ...emptyFinding('silent-ledger'),\n workspaceId,\n expectedBoxes: expectation.expectedBoxes,\n settledBoxes: 0,\n ...(window ? { windowStartAt: window.startAt, windowEndAt: window.endAt } : {}),\n message:\n `Nothing settled against ANY of the ${expectation.expectedBoxes} box(es) this product had ` +\n `live${span}, out of ${expectation.liveBoxes} that overlapped it. ` +\n `${input.rowsExamined} row(s) were read and ${input.foreignBoxes} box(es) excluded by ${scope}. ` +\n 'A window in which this product ran boxes and was billed for none of them is far more ' +\n 'likely to be a broken check than a free week — an empty or mis-scoped ledger fetch, a ' +\n 'rotated key the ownership rule does not name, or a feed that quietly stopped returning ' +\n 'rows all produce exactly this shape. Treat this report as unverified, not as clean.',\n remedy:\n 'Check the fetch before the bill: re-run the transactions query for this exact window by ' +\n 'hand and compare the row count with `rowsExamined` above. If the rows are there, the ' +\n 'ownership rule is excluding them — compare its key ids against the key the boxes were ' +\n `created under. Boxes expected: ${expectation.unsettledSandboxIds.join(', ')}.`,\n },\n ]\n }\n\n // A subset: the pass is working, these boxes are the anomaly.\n return unsettled.map((box) => ({\n ...emptyFinding('silent-ledger'),\n sandboxId: box.sandboxId,\n workspaceId: box.workspaceId || workspaceId,\n expectedBoxes: expectation.expectedBoxes,\n settledBoxes: expectation.settledBoxes,\n liveMsInWindow: box.liveMsInWindow,\n ...(window ? { windowStartAt: window.startAt, windowEndAt: window.endAt } : {}),\n message:\n `Sandbox ${box.sandboxId} was live for ${hours(box.liveMsInWindow)}${span} and nothing settled ` +\n `against it, while ${expectation.settledBoxes} of this product's other expected box(es) settled ` +\n `normally. Its life ended on basis ${box.basis} at ${iso(box.liveUntil)}.`,\n remedy:\n 'One silent box beside working siblings is not a discount. Check, in order: whether its ' +\n 'settlement is merely late (the platform treats up to 900 s of compute-settlement lag as ' +\n 'normal, and `expectationGraceMs` is the dial for it); whether this box was created under a ' +\n 'key the ownership rule does not claim, so its charges are landing on another product\\'s ' +\n `report; and whether the expectation ledger's own record for ${box.sandboxId} is stale.`,\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 const graceMs = options.expectationGraceMs ?? DEFAULT_EXPECTATION_GRACE_MS\n // A malformed window would expect nothing and certify an unchecked account,\n // which is the failure this whole addition exists to close — so it throws\n // rather than degrading to a pass that examines nobody.\n if (options.window) assertSpendWindow(options.window)\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 /** Boxes this pass claimed — the join key the expectation check settles against. */\n const ownedSandboxIds = new Set<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 ownedSandboxIds.add(sandboxId)\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 // ── silent-ledger: what did we EXPECT to be billed for? ────────────────────\n //\n // Every rule above is driven by a settlement row, so all of them go quiet\n // together when the rows stop arriving. This is the one that reads the other\n // direction — off the expectation ledger the pass already has — and it needs\n // both halves: a window the caller declares (deriving it from the rows would\n // be circular) and a store that can list its own boxes.\n const window = options.window ?? null\n const canList = typeof options.store.listLiveBetween === 'function'\n let expectation: SpendExpectationSummary = undeclaredExpectation(graceMs)\n let unsettled: SpendBoxLiveness[] = []\n\n if (window && canList) {\n const candidates = await options.store.listLiveBetween!(window)\n // The store may over-return; liveness is re-derived here so the definition\n // of \"live\" lives in one place rather than once per product's SQL.\n const live = candidates\n .map((record) => boxLivenessInWindow(record, window, { graceMs }))\n .filter((box) => box.overlaps)\n const expected = live.filter((box) => box.expectSettlement)\n unsettled = expected.filter((box) => !ownedSandboxIds.has(box.sandboxId))\n expectation = {\n declared: true,\n window,\n graceMs,\n liveBoxes: live.length,\n expectedBoxes: expected.length,\n settledBoxes: expected.length - unsettled.length,\n unsettledSandboxIds: unsettled.map((box) => box.sandboxId),\n }\n }\n\n // A pass that claimed one of its own settlements HAS examined something. Past\n // that, only a declared expectation can tell \"nothing was billed because\n // nothing ran\" from \"nothing was billed because the check broke\".\n const coverage: SpendCoverage =\n ownedBoxes > 0\n ? 'verified'\n : expectation.declared\n ? expectation.expectedBoxes > 0\n ? 'verified'\n : 'nothing-expected'\n : 'unverified'\n\n if (runs('silent-ledger')) {\n findings.push(\n ...silentLedgerFindings({\n expectation,\n unsettled,\n coverage,\n ownership,\n workspaceId,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n ownedBoxes,\n foreignBoxes: foreignSandboxIds.length,\n }),\n )\n }\n\n return {\n // `coverage` is the second half of the gate deliberately: skipping the\n // `silent-ledger` check removes its findings, never the verdict, so no\n // combination of options can make an examined-nobody pass report clean.\n ok: findings.length === 0 && coverage !== 'unverified',\n coverage,\n findings,\n checksRun,\n rowsExamined: options.rows.length,\n boxesExamined: byBox.size,\n settledNanoUsd,\n creditedNanoUsd,\n ownership: ownershipSummary,\n expectation,\n asOf,\n }\n}\n","import type {\n SpendExpectationSummary,\n SpendFinding,\n SpendOwnershipSummary,\n SpendReport,\n} 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 for (const line of expectationLines(report.expectation)) 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 // A pass that examined nobody is not clean and is not a dispute either. Say\n // which of the two this is before the reader starts reading findings as\n // charges to argue about.\n if (report.coverage === 'unverified') {\n lines.push('')\n lines.push(\n 'UNVERIFIED — this pass examined none of this product\\'s settlements and could not say what ' +\n 'it expected, so it cannot certify the bill either way. Read the finding below as \"do not ' +\n 'trust this report\", not as \"dispute this charge\".',\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/**\n * What this pass expected to be billed for — printed on EVERY report, clean ones\n * included, for the same reason the scope line is.\n *\n * An undeclared expectation is the difference between \"we were billed for\n * everything we asked for\" and \"we found nothing to complain about in whatever\n * rows arrived\", and only this line tells a reader which report they are\n * holding.\n */\nfunction expectationLines(expectation: SpendExpectationSummary): string[] {\n if (!expectation.declared) {\n return [\n 'expectation: NOT DECLARED — this pass is driven entirely by the settlement rows it was ' +\n 'handed, so it can say nothing about a box it asked for and was never billed for. Pass ' +\n '`window` and implement `listLiveBetween` on the expectation store to close that direction.',\n ]\n }\n const window = expectation.window\n const span = window ? `${new Date(window.startAt).toISOString()} → ${new Date(window.endAt).toISOString()}` : '—'\n const lines = [\n `expectation: ${span} — ${expectation.liveBoxes} box(es) live, ${expectation.expectedBoxes} ` +\n `expected to settle (≥ ${(expectation.graceMs / 60_000).toFixed(0)} min live), ` +\n `${expectation.settledBoxes} did`,\n ]\n if (expectation.unsettledSandboxIds.length > 0) {\n lines.push(` nothing settled against: ${expectation.unsettledSandboxIds.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 end', finding.windowEndAt === null ? '—' : new Date(finding.windowEndAt).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 ['expected boxes', finding.expectedBoxes === null ? '—' : String(finding.expectedBoxes)],\n ['settled boxes', finding.settledBoxes === null ? '—' : String(finding.settledBoxes)],\n ['live in window', ms(finding.liveMsInWindow)],\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":";AAmaO,IAAM,eAAwC;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACzVO,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,SAAO;AAAA,IACL;AAAA,IACA,OAAO,EAAE,IAAI,GAAG;AACd,YAAM,QAAQ,IAAI,OAAO,KAAK;AAC9B,UAAI,CAAC,MAAO,QAAO;AACnB,aAAO,MAAM,IAAI,KAAK,IAAI,SAAS;AAAA,IACrC;AAAA,EACF;AACF;AAaO,SAAS,mBACd,MACA,WACA,MACuB;AACvB,MAAI,UAAiC;AACrC,aAAW,OAAO,MAAM;AACtB,UAAM,aAAa,KAAK,OAAO,EAAE,KAAK,UAAU,CAAC;A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