Multiplayer agent harness for work.
Attribute spend to the cron that ran it (#2420)
Eric Bakan3592c2a9190e
diff --git a/SECURITY.md b/SECURITY.mdindex 4ce8a28b3..b121e6463 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -183,8 +183,9 @@ these, not through them.changes do not revoke individual link holders.- **The spend export token is bearer authorization for org-wide spend.** When`SPEND_EXPORT_TOKEN` is set, anyone holding it can read every scope's daily model-call- spend: per-person totals, channel and group names, and the model mix. It reads no- conversation content and changes nothing, and each export is audited, but the token is+ spend: per-person totals, channel and group names, the model mix, and each billed+ cron's title, owner, scope, schedule and state. It reads no conversation content or+ cron task and changes nothing, and each export is audited, but the token isnot bound to a caller. Rotating it means replacing the secret in core and in everyconsumer; core accepts only the current value after it restarts with the new one.- **Portal sessions have residual risk.** A signed portal session defaults to eightdiff --git a/docs/deploy-directory.md b/docs/deploy-directory.mdindex dbda08631..0fb6885bf 100644--- a/docs/deploy-directory.md+++ b/docs/deploy-directory.md@@ -70,7 +70,7 @@ A chunk whose score is at or above its threshold resolves to Strict, and any Str## Spend export-`secretEnv.core.SPEND_EXPORT_TOKEN` (at least 32 characters, without surrounding whitespace, and distinct from every other environment value) turns on `GET /v1/spend/export?from=YYYY-MM-DD&to=YYYY-MM-DD` for an external spend or chargeback system. Requests send `Authorization: Bearer <token>`; the window is whole UTC days, half-open, and at most 93 days long. The response carries `scopeId`, the `window`, `asOf` when the report is served from saved daily totals, and `rows` at the Spend page's ledger grain — one per UTC day, scope, origin (`live`, `cron`, `background`) and model — each with `scopeId`, `kind`, `principalId` (people only, after identity links), `displayName`, `calls`, `costUsd` and the four token counts. `costUsd` is the same estimate the admin Spend page shows, not a provider bill. Without the secret the route answers 404, and every export is audited as `spend.export`. Portal does not forward the route, so callers use the origin that reaches core directly.+`secretEnv.core.SPEND_EXPORT_TOKEN` (at least 32 characters, without surrounding whitespace, and distinct from every other environment value) turns on `GET /v1/spend/export?from=YYYY-MM-DD&to=YYYY-MM-DD` for an external spend or chargeback system. Requests send `Authorization: Bearer <token>`; the window is whole UTC days, half-open, and at most 93 days long. The response carries `scopeId`, the `window`, `asOf` when the report is served from saved daily totals, `rows` at the Spend page's ledger grain — one per UTC day, scope, source, cron and model — each with `scopeId`, `kind`, `principalId` (people only, after identity links), `displayName`, `source` (`live`, or the background kind: `cron`, `loop`, `swarm`, `webhook` or `monitor`), `cronId` (the cron that ran it, including its subagents' calls, else `null`), `calls`, `costUsd` and the four token counts, and `crons`: each billed cron's `id`, `title`, `owner`, `ownerScopeId`, `schedule`, `enabled` and `archived`, without its task. A deleted cron keeps its `cronId` on rows but has no `crons` entry. `costUsd` is the same estimate the admin Spend page shows, not a provider bill. Without the secret the route answers 404, and every export is audited as `spend.export`. Portal does not forward the route, so callers use the origin that reaches core directly.## Secretsdiff --git a/docs/upgrading-runtime.md b/docs/upgrading-runtime.mdindex d6aa3233d..b7dde0261 100644--- a/docs/upgrading-runtime.md+++ b/docs/upgrading-runtime.md@@ -54,6 +54,13 @@ second, so a few thousand sessions take a couple of minutes; above that, runservers so readiness checks do not time out. Instances that start meanwhile wait for the copy onthe migration lock.+Sessions created before QM recorded each session's origin get `origin` and `origin_id`+from their thread reference during startup migrations. The backfill commits 5,000+sessions at a time, resumes after an interrupted startup, and fills roughly 10,000+sessions per second; with more than a few hundred thousand such sessions, run+`node src/migrate-main.ts` with the release's configuration before starting the servers+so readiness checks do not time out.+Rolling back the runtime restores code and configuration, not database contents.Older binaries do not display cron history written only to the new journal; thoserecords remain stored in `cron_fires`. Validate both old and new readers against thediff --git a/knip.json b/knip.jsonindex f6781a772..3c357c161 100644--- a/knip.json+++ b/knip.json@@ -14,7 +14,7 @@"scripts/aws-deploy-smoke.ts","scripts/aws-litestream-smoke.ts","scripts/backfill-search-index.ts",- "scripts/backfill-session-origin.ts",+ "scripts/backfill-delivery-source-cron-id.ts","scripts/e2b-live-smoke.mjs","scripts/modal-live-smoke.mjs","scripts/dev/cli.ts",diff --git a/plugins/admin/public/admin-components.css b/plugins/admin/public/admin-components.cssindex fe19b3dfb..472768c8c 100644--- a/plugins/admin/public/admin-components.css+++ b/plugins/admin/public/admin-components.css@@ -1910,7 +1910,10 @@ dialog.credential-dialog {.spend-chart {--spend-live: var(--text);--spend-cron: var(--trigger);- --spend-background: var(--muted);+ --spend-loop: color-mix(in srgb, var(--trigger) 65%, var(--bg));+ --spend-swarm: color-mix(in srgb, var(--trigger) 35%, var(--bg));+ --spend-webhook: var(--muted);+ --spend-monitor: color-mix(in srgb, var(--muted) 55%, var(--bg));padding-top: 4px;}.spend-chart-summary {@@ -1956,8 +1959,17 @@ dialog.credential-dialog {.spend-cron {background: var(--spend-cron);}-.spend-background {- background: var(--spend-background);+.spend-loop {+ background: var(--spend-loop);+}+.spend-swarm {+ background: var(--spend-swarm);+}+.spend-webhook {+ background: var(--spend-webhook);+}+.spend-monitor {+ background: var(--spend-monitor);}.spend-chart-plot {display: grid;diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 32b0dde7d..a85083413 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -9389,9 +9389,13 @@fmtPct,fmtTokens,shortName,+ shortSchedule,+ cronName,plural,window: governanceUI.spend.spendWindow(urlToState()),openUser: (principal) => go({ view: "user", scope, session: null, principal }),+ openCronRuns: (cron, cronScope) =>+ go({ view: "history", scope: cronScope, session: null, historyKind: "cron", cron }),setRange: (range) => go({ ...urlToState(), view: "spend", range, from: null, to: null }),setCustomRange: (from, to) => go({ ...urlToState(), view: "spend", range: null, from, to }),downloadCsv: (breakdown = "entity") => {diff --git a/plugins/admin/test/spend-download.test.ts b/plugins/admin/test/spend-download.test.tsindex a7f395357..fddbda7fb 100644--- a/plugins/admin/test/spend-download.test.ts+++ b/plugins/admin/test/spend-download.test.ts@@ -4,7 +4,7 @@ import { createServer, type IncomingMessage } from "node:http";import type { AddressInfo } from "node:net";const CSV_HEADER =- "principal_id,scope_id,kind,display_name,live_usd,cron_usd,background_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio";+ "principal_id,scope_id,kind,display_name,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio";const CSV_BODY =CSV_HEADER +"\r\n" +diff --git a/plugins/admin/test/spend-lit.test.ts b/plugins/admin/test/spend-lit.test.tsindex 9041adfb2..cf0dcaa56 100644--- a/plugins/admin/test/spend-lit.test.ts+++ b/plugins/admin/test/spend-lit.test.ts@@ -2,6 +2,17 @@ import assert from "node:assert/strict";import test from "node:test";import { litFixture } from "./lit-fixture.ts";+const zero = { costUsd: 0, calls: 0, tokens: 0 };+const background = (sources: Record<string, number> = {}) => {+ const all = Object.fromEntries(+ ["cron", "loop", "swarm", "webhook", "monitor"].map((source) => [+ source,+ { ...zero, costUsd: sources[source] ?? 0 },+ ]),+ );+ return { ...zero, costUsd: Object.values(sources).reduce((a, b) => a + b, 0), sources: all };+};+const person = (principalId: string, costUsd: number, over: Record<string, any> = {}) => ({principalId,scopeId: `personal:${principalId}`,@@ -16,8 +27,7 @@ const person = (principalId: string, costUsd: number, over: Record<string, any>cacheWrite: 100,cacheHitRatio: 0.7,live: { costUsd, calls: 2, tokens: 1000 },- cron: { costUsd: 0, calls: 0, tokens: 0 },- background: { costUsd: 0, calls: 0, tokens: 0 },+ background: background(),...over,});@@ -33,18 +43,16 @@ const DATA = {cacheWrite: 400,cacheHitRatio: 0.7,live: { costUsd: 16, calls: 8, tokens: 4000 },- cron: { costUsd: 0, calls: 0, tokens: 0 },- background: { costUsd: 0, calls: 0, tokens: 0 },+ background: background(),},series: [- { day: "2026-09-23", costUsd: 6, calls: 4, live: { costUsd: 6 }, cron: { costUsd: 0 }, background: { costUsd: 0 } },+ { day: "2026-09-23", costUsd: 6, calls: 4, live: { costUsd: 6 }, background: background() },{day: "2026-09-24",costUsd: 10,calls: 4,live: { costUsd: 10 },- cron: { costUsd: 0 },- background: { costUsd: 0 },+ background: background(),},],people: [person("alice", 5), person("bob", 10), person("carol", 1)],@@ -63,8 +71,7 @@ const EMPTY = {cacheWrite: 0,cacheHitRatio: null,live: { costUsd: 0, calls: 0, tokens: 0 },- cron: { costUsd: 0, calls: 0, tokens: 0 },- background: { costUsd: 0, calls: 0, tokens: 0 },+ background: background(),},series: [],people: [],@@ -114,7 +121,7 @@ test("spend view: KPI stats, stacked chart and range tabs describe the whole orgassert.deepEqual(JSON.parse(JSON.stringify(calls.shell.stats)), [["$16.00", "Total spend"],["$16.00", "Live"],- ["$0.00", "Crons"],+ ["$0.00", "Background"],["70.0%", "Cache hit rate"],]);assert.deepEqual(JSON.parse(JSON.stringify(calls.shell.tabs.map((t: any) => [t.label, t.active]))), [@@ -200,15 +207,15 @@ test("spend view: a null per-row cache ratio reads n/a", () => {test("spend chart: category stacks and keyboard details use exact amounts", () => {const { f } = render({...DATA,- series: [{ day: "2026-09-24", live: { costUsd: 3 }, cron: { costUsd: 2 }, background: { costUsd: 1 } }],+ series: [{ day: "2026-09-24", live: { costUsd: 3 }, background: background({ cron: 2, loop: 1, swarm: 0.5 }) }],});const bar = f.root.querySelectorAll<HTMLElement>(".spend-column")[29]!;bar.dispatchEvent(new f.window.Event("focus"));assert.match(f.root.querySelector(".spend-chart-detail")!.textContent!,- /Live \$3.00.*Crons \$2.00.*Background \$1.00/,+ /Live \$3.00.*Crons \$2.00.*Loops \$1.00.*Swarms \$0.50.*Webhooks \$0.00.*Monitors \$0.00/,);- assert.equal(bar.querySelectorAll(".spend-segment").length, 3);+ assert.equal(bar.querySelectorAll(".spend-segment").length, 6);assert.ok(!f.root.innerHTML.includes("NaN"));f.window.close();});@@ -228,19 +235,19 @@ test("spend models: category breakdown, sorting, filtering and export", () => {const { f, calls } = render({...DATA,models: [- { ...person("", 10), model: "model-a", live: { costUsd: 3 }, cron: { costUsd: 6 }, background: { costUsd: 1 } },- { ...person("", 6), model: null, live: { costUsd: 5 }, cron: { costUsd: 0 }, background: { costUsd: 1 } },+ { ...person("", 10), model: "model-a", live: { costUsd: 3 }, background: background({ cron: 6, swarm: 1 }) },+ { ...person("", 6), model: null, live: { costUsd: 5 }, background: background({ webhook: 1 }) },],});const names = () =>[...f.root.querySelectorAll(".spend-models tbody tr")].map((row) => row.querySelector("td")!.textContent!.trim());assert.deepEqual(names(), ["model-a", "Unknown model"]);const cells = [...f.root.querySelectorAll(".spend-models tbody tr:first-child td")].map((c) => c.textContent!.trim());- assert.deepEqual(cells.slice(0, 5), ["model-a", "$10.00", "$3.00", "$6.00", "$1.00"]);- const cron = [...f.root.querySelectorAll<HTMLElement>(".spend-models thead button")].find((b) =>- b.textContent!.includes("Crons"),+ assert.deepEqual(cells.slice(0, 4), ["model-a", "$10.00", "$3.00", "$7.00Crons $6.00 · Swarms $1.00"]);+ const backgroundHeader = [...f.root.querySelectorAll<HTMLElement>(".spend-models thead button")].find((b) =>+ b.textContent!.includes("Background"),)!;- cron.click();+ backgroundHeader.click();assert.deepEqual(names(), ["Unknown model", "model-a"]);calls.shell.search.onInput("model-a");assert.deepEqual(names(), ["model-a"]);@@ -419,3 +426,78 @@ test("spend view: Custom turns the current window into two editable UTC days, apassert.equal(calls.api, 0);f.window.close();});++test("spend view: crons show each cron's spend under its title, scope and schedule, filter, and open the cron's runs", () => {+ const opened: string[][] = [];+ const downloads: string[] = [];+ const cron = (cronId: string, costUsd: number, scopeId: string, scopeName: string, info: unknown) => ({+ ...person("", costUsd, { principalId: null, scopeId, kind: "person" }),+ cronId,+ scopeName,+ info,+ });+ const digest = {+ id: "abc123",+ title: "Morning digest",+ owner: "alice",+ ownerScopeId: "channel:C1",+ schedule: { cron: "0 9 * * 1-5" },+ enabled: true,+ };+ const { f, calls } = render(+ {+ ...DATA,+ crons: [+ cron("gone1234567890", 1, "personal:alice", "Alice", null),+ cron("abc123", 7, "channel:C1", "#general", digest),+ ],+ },+ {+ cronName: (c: { id: string; title?: string }) => c.title || `Cron ${c.id.slice(0, 6)}`,+ shortSchedule: (schedule: { cron: string }) => schedule.cron,+ openCronRuns: (cronId: string, scope: string) => opened.push([cronId, scope]),+ downloadCsv: (breakdown?: string) => downloads.push(breakdown ?? "entity"),+ },+ );+ const rows = () => [...f.root.querySelectorAll<HTMLTableRowElement>(".spend-crons tbody tr")];+ const labels = () =>+ rows().map((row) => {+ const cell = row.querySelector("td")!;+ const where = cell.querySelector(".subline")!.textContent!;+ return [cell.textContent!.replace(where, "").trim(), where.trim()];+ });+ assert.deepEqual(labels(), [+ ["Morning digest", "#general · 0 9 * * 1-5"],+ ["Cron gone12", "Alice · deleted"],+ ]);+ rows()[1]!.click();+ rows()[0]!.click();+ assert.deepEqual(opened, [+ ["gone1234567890", "personal:alice"],+ ["abc123", "channel:C1"],+ ]);+ [...f.root.querySelectorAll<HTMLButtonElement>("button")].find((b) => b.textContent === "Export cron CSV")!.click();+ assert.deepEqual(downloads, ["cron"]);+ for (const query of ["digest", "abc123", "general", "channel:C1"]) {+ calls.shell.search.onInput(query);+ assert.deepEqual(labels(), [["Morning digest", "#general · 0 9 * * 1-5"]], query);+ }+ f.window.close();+});++test("spend view: background by source names where background spend came from, largest first", () => {+ const { f } = render({+ ...DATA,+ org: { ...DATA.org, background: background({ cron: 6, loop: 3, swarm: 1 }) },+ });+ const card = [...f.root.querySelectorAll(".tablewrap")].find((t) => t.textContent!.includes("Share of background"))!;+ const rows = [...card.querySelectorAll("tbody tr")].map((r) =>+ [...r.querySelectorAll("td")].slice(0, 3).map((c) => c.textContent!.trim()),+ );+ assert.deepEqual(rows, [+ ["Crons", "$6.00", "60.0%"],+ ["Loops", "$3.00", "30.0%"],+ ["Swarms", "$1.00", "10.0%"],+ ]);+ f.window.close();+});diff --git a/plugins/admin/ui/spend-chart.ts b/plugins/admin/ui/spend-chart.tsindex f9841f854..ec35b4df7 100644--- a/plugins/admin/ui/spend-chart.ts+++ b/plugins/admin/ui/spend-chart.ts@@ -1,11 +1,15 @@import { html } from "lit";const DAY = 86400000;-const PARTS = [- ["live", "Live"],+export const BACKGROUND_SOURCES = [["cron", "Crons"],- ["background", "Background"],+ ["loop", "Loops"],+ ["swarm", "Swarms"],+ ["webhook", "Webhooks"],+ ["monitor", "Monitors"],] as const;+const PARTS = [["live", "Live"], ...BACKGROUND_SOURCES] as const;+const categoryCost = (p: any, key: string) => (key === "live" ? p?.live : p?.background?.sources?.[key])?.costUsd;const usd = (n: number) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });const date = (ms: number) =>new Date(ms).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });@@ -51,7 +55,7 @@ export function spendChart(data: any, breakdown: "category" | "model" | "person"points.push({t,values: parts.map(({ key }) =>- Math.max(0, Number(breakdown !== "category" ? costs.get(key) : p?.[key!]?.costUsd) || 0),+ Math.max(0, Number(breakdown !== "category" ? costs.get(key) : categoryCost(p, key!)) || 0),),});}diff --git a/plugins/admin/ui/spend.ts b/plugins/admin/ui/spend.tsindex e46af9ae1..aef7e77d1 100644--- a/plugins/admin/ui/spend.ts+++ b/plugins/admin/ui/spend.ts@@ -1,6 +1,6 @@import { html } from "lit";import { keyed } from "lit/directives/keyed.js";-import { spendChart } from "./spend-chart.ts";+import { BACKGROUND_SOURCES, spendChart } from "./spend-chart.ts";import { table, card, renderer } from "./shared.ts";type Services = Record<string, any>;@@ -16,11 +16,25 @@ const COLUMNS: Array<[string, string]> = [["person", "Person"],["costUsd", "Total"],["live", "Live"],- ["cron", "Crons"],["background", "Background"],["tokens", "Tokens"],["cacheHitRatio", "Cache hit"],];+const SCOPE_COLUMNS: Array<[string, string]> = [["person", "Scope"], ...COLUMNS.slice(1)];+const MODEL_COLUMNS: Array<[string, string]> = [["person", "Model"], ...COLUMNS.slice(1)];+const SOURCE_COLUMNS: Array<[string, string]> = [+ ["person", "Source"],+ ["costUsd", "Total"],+ ["share", "Share of background"],+ ["calls", "Calls"],+ ["tokens", "Tokens"],+];+const CRON_COLUMNS: Array<[string, string]> = [+ ["person", "Cron"],+ ["costUsd", "Total"],+ ["tokens", "Tokens"],+ ["cacheHitRatio", "Cache hit"],+];const rowName = (row: any) =>"model" in row ? row.model || "Unknown model" : row.displayName || row.principalId || row.scopeId || "";@@ -61,7 +75,7 @@ export function spendWindow(function sortValue(row: any, key: string): number | string {if (key === "person") return String(rowName(row)).toLowerCase();- if (key === "live" || key === "cron" || key === "background") return Number(row[key]?.costUsd || 0);+ if (key === "live" || key === "background") return Number(row[key]?.costUsd || 0);if (key === "cacheHitRatio") return row.cacheHitRatio === null ? -1 : Number(row.cacheHitRatio);return Number(row[key] || 0);}@@ -102,7 +116,7 @@ export class SpendView {stats: [[fmtUsd(org.costUsd), "Total spend"],[fmtUsd(org.live?.costUsd), "Live"],- [fmtUsd(org.cron?.costUsd), "Crons"],+ [fmtUsd(org.background?.costUsd), "Background"],[org.cacheHitRatio == null ? "n/a" : s.fmtPct(org.cacheHitRatio), "Cache hit rate"],],tabs: [@@ -119,7 +133,7 @@ export class SpendView {],search: {value: this.filter,- placeholder: "person, scope or model",+ placeholder: "person, scope, cron or model",onInput: (value: string) => {this.filter = value;this.draw();@@ -165,12 +179,10 @@ export class SpendView {if (this.sortKey !== key) return "";return this.sortDir === "asc" ? " ↑" : " ↓";}- header(models = false) {- return COLUMNS.map(+ header(columns = COLUMNS) {+ return columns.map(([key, label]) =>- html`<button type="button" class="rowbtn" @click=${() => this.sortBy(key)}>- ${models && key === "person" ? "Model" : label}${this.arrow(key)}- </button>`,+ html`<button type="button" class="rowbtn" @click=${() => this.sortBy(key)}>${label}${this.arrow(key)}</button>`,);}rowCells(row: any) {@@ -180,8 +192,40 @@ export class SpendView {{ text: name, cls: "mono" },{ text: fmtUsd(row.costUsd), cls: "num" },{ text: fmtUsd(row.live?.costUsd), cls: "num" },- { text: fmtUsd(row.cron?.costUsd), cls: "num" },- { text: fmtUsd(row.background?.costUsd), cls: "num" },+ { node: this.backgroundCell(row.background), cls: "num" },+ { text: s.fmtTokens(row.tokens || 0), cls: "num" },+ { text: row.cacheHitRatio == null ? "n/a" : s.fmtPct(row.cacheHitRatio), cls: "num" },+ ];+ }+ backgroundCell(background: any) {+ const parts = BACKGROUND_SOURCES.filter(([key]) => Number(background?.sources?.[key]?.costUsd) > 0).map(+ ([key, label]) => `${label} ${fmtUsd(background.sources[key].costUsd)}`,+ );+ return html`${fmtUsd(background?.costUsd)}${parts.length ? html`<div class="subline">${parts.join(" · ")}</div>` : null}`;+ }+ sourceCells(row: any) {+ const s = this.services;+ return [+ { text: row.displayName },+ { text: fmtUsd(row.costUsd), cls: "num" },+ { text: row.share == null ? "n/a" : s.fmtPct(row.share), cls: "num" },+ { text: Number(row.calls || 0).toLocaleString(), cls: "num" },+ { text: s.fmtTokens(row.tokens || 0), cls: "num" },+ ];+ }+ cronCells(row: any) {+ const s = this.services;+ const where = [+ row.scopeName || s.shortName(row.scopeId),+ row.info ? s.shortSchedule(row.info.schedule) : "deleted",+ ];+ return [+ {+ node: html`${row.displayName}+ <div class="subline">${where.join(" · ")}</div>`,+ cls: "mono",+ },+ { text: fmtUsd(row.costUsd), cls: "num" },{ text: s.fmtTokens(row.tokens || 0), cls: "num" },{ text: row.cacheHitRatio == null ? "n/a" : s.fmtPct(row.cacheHitRatio), cls: "num" },];@@ -201,6 +245,30 @@ export class SpendView {});const people = sorted((this.data.people || []).filter(matches));const scopes = sorted((this.data.scopes || []).filter(matches));+ const crons = sorted(+ (this.data.crons || [])+ .map((row: any) => ({ ...row, displayName: s.cronName({ ...row.info, id: row.cronId }, true) }))+ .filter((row: any) =>+ [row.cronId, row.scopeId, row.scopeName, row.info?.ownerScopeId, row.displayName]+ .join(" ")+ .toLowerCase()+ .includes(needle),+ ),+ );+ const backgroundTotal = Number(this.data.org?.background?.costUsd) || 0;+ const sources = sorted(+ BACKGROUND_SOURCES.map(([source, label]) => {+ const totals = this.data.org?.background?.sources?.[source] || {};+ return {+ source,+ displayName: label,+ costUsd: Number(totals.costUsd) || 0,+ calls: Number(totals.calls) || 0,+ tokens: Number(totals.tokens) || 0,+ share: backgroundTotal > 0 ? (Number(totals.costUsd) || 0) / backgroundTotal : null,+ };+ }).filter((row) => row.costUsd > 0 && row.displayName.toLowerCase().includes(needle)),+ );const models = sorted((this.data.models || []).filter((row: any) => rowName(row).toLowerCase().includes(needle)));const series = this.data.series || [];const org = this.data.org || {};@@ -239,7 +307,7 @@ export class SpendView {: null,)}${card("Spend per person",- "Live is interactive conversation; Crons are scheduled runs; Background covers webhook and monitor runs.",+ "Live is interactive conversation. Background is work nobody is typing into: crons, loops, swarms, webhooks and monitors, split out under each amount.",table(this.header(),people.map((row: any) => this.rowCells(row)),@@ -253,16 +321,39 @@ export class SpendView {"Shared scopes","Channels, groups and teams are billed to the scope, not to a speaker. These rows plus the people above make up the org total.",table(- this.header(),+ this.header(SCOPE_COLUMNS),scopes.map((row: any) => this.rowCells(row)),this.data.scopes?.length ? "No scopes match." : "No shared-scope spend in this window.",),+ )}${card(+ "Background by source",+ "Where background spend comes from. Subagents count toward the run that started them.",+ table(+ this.header(SOURCE_COLUMNS),+ sources.map((row: any) => this.sourceCells(row)),+ backgroundTotal > 0 ? "No sources match." : "No background spend in this window.",+ ),+ )}${card(+ "Spend per cron",+ "Each cron's scheduled runs, including the subagents they start. A deleted cron keeps its spend under its id.",+ html`<div class="spend-crons">+ ${table(+ this.header(CRON_COLUMNS),+ crons.map((row: any) => this.cronCells(row)),+ this.data.crons?.length ? "No crons match." : "No cron spend in this window.",+ (i) => {+ const row = crons[i];+ if (row) s.openCronRuns(row.cronId, row.info?.ownerScopeId ?? row.scopeId);+ },+ )}+ </div>`,+ html`<button type="button" @click=${() => s.downloadCsv("cron")}>Export cron CSV</button>`,)}${card("Spend by model","Same org spend, split by the model recorded on each call. Unknown model covers calls without a model ID.",html`<div class="spend-models">${table(- this.header(true),+ this.header(MODEL_COLUMNS),models.map((row: any) => this.rowCells(row)),this.data.models?.length ? "No models match." : "No model breakdown available in this window.",)}diff --git a/scripts/backfill-delivery-source-cron-id.ts b/scripts/backfill-delivery-source-cron-id.tsnew file mode 100644index 000000000..5e6905ae3--- /dev/null+++ b/scripts/backfill-delivery-source-cron-id.ts@@ -0,0 +1,19 @@+import { createPgPool } from "../src/persistence/pg-pool.ts";+import { backfillDeliverySourceCronIdBatch } from "../src/delivery/postgres-delivery-store.ts";+import { sleep } from "../src/util/async.ts";+import { databaseUrl } from "./lib/backfill-runner.ts";++const BATCH = 5000;+const PAUSE_MS = 250;++const db = createPgPool(databaseUrl());+let total = 0;+for (;;) {+ const updated = await backfillDeliverySourceCronIdBatch(db.q, BATCH);+ if (updated === 0) break;+ total += updated;+ console.log(`backfilled ${total} deliveries`);+ await sleep(PAUSE_MS);+}+console.log(`done: ${total} deliveries backfilled, none left to derive`);+await db.close();diff --git a/scripts/backfill-session-origin.ts b/scripts/backfill-session-origin.tsdeleted file mode 100644index c00f87bfb..000000000--- a/scripts/backfill-session-origin.ts+++ /dev/null@@ -1,25 +0,0 @@-import { createPgPool } from "../src/persistence/pg-pool.ts";-import { backfillDeliverySourceCronIdBatch } from "../src/delivery/postgres-delivery-store.ts";-import { backfillSessionOriginBatch } from "../src/sessions/postgres-session-store.ts";-import { sleep } from "../src/util/async.ts";-import { databaseUrl } from "./lib/backfill-runner.ts";--const BATCH = 5000;-const PAUSE_MS = 250;--const db = createPgPool(databaseUrl());-for (const [table, backfillBatch] of [- ["sessions", backfillSessionOriginBatch],- ["deliveries", backfillDeliverySourceCronIdBatch],-] as const) {- let total = 0;- for (;;) {- const updated = await backfillBatch(db.q, BATCH);- if (updated === 0) break;- total += updated;- console.log(`backfilled ${total} ${table}`);- await sleep(PAUSE_MS);- }- console.log(`done: ${total} ${table} backfilled, none left to derive`);-}-await db.close();diff --git a/src/api/routes/admin/spend.ts b/src/api/routes/admin/spend.tsindex 6ccc23a6e..0387a6376 100644--- a/src/api/routes/admin/spend.ts+++ b/src/api/routes/admin/spend.ts@@ -1,6 +1,6 @@import { cacheHitRatio } from "../../../admin/metrics-sink.ts";import { canonicalPerson } from "../../../directory/person.ts";-import { parseScopeId, personalScope, type ScopeId } from "../../../types.ts";+import { parseScopeId, personalScope, type Cron, type ScopeId } from "../../../types.ts";import type { SessionOrigin, SessionStore, SpendRow } from "../../../sessions/session-store.ts";import { constantTimeEqual } from "../../../util/crypto.ts";import { contentDispositionAttachment, contentTypeWithUtf8Charset, sendJson } from "../../http.ts";@@ -11,15 +11,23 @@ import { type ApiCtx, type BaseCtx } from "../route.ts";const DAY_MS = 86_400_000;const DEFAULT_WINDOW_DAYS = 30;const EXPORT_MAX_DAYS = 93;+const CRON_LOOKUP_CONCURRENCY = 8;const SPEND_EXPORT_PRINCIPAL = "spend-export";const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;const EPOCH_MS = /^\d+$/;const CSV_FORMULA_LEAD = /^[=+\-@\t\r]/;const CSV_NEEDS_QUOTES = /["\r\n,]/;+const BACKGROUND_SOURCES = ["cron", "loop", "swarm", "webhook", "monitor"] as const satisfies readonly Exclude<+ SessionOrigin,+ "conversation"+>[];+type BackgroundSource = (typeof BACKGROUND_SOURCES)[number];+type SpendSource = "live" | BackgroundSource;+const SPEND_SOURCES: readonly SpendSource[] = ["live", ...BACKGROUND_SOURCES];const CSV_TOTALS_HEADER = ["live_usd",- "cron_usd","background_usd",+ ...BACKGROUND_SOURCES.map((source) => `${source}_usd`),"total_usd","calls","input_tokens",@@ -29,10 +37,9 @@ const CSV_TOTALS_HEADER = ["cache_hit_ratio",];-type SpendBreakdown = "entity" | "model";+const SPEND_BREAKDOWNS = ["entity", "model", "cron"] as const;+type SpendBreakdown = (typeof SPEND_BREAKDOWNS)[number];type SpendBucket = "day" | "week";-type OriginBucket = "live" | "cron" | "background";-const ORIGIN_BUCKETS: readonly OriginBucket[] = ["live", "cron", "background"];interface SpendBucketTotals {costUsd: number;@@ -50,8 +57,7 @@ interface SpendTotals {cacheWrite: number;cacheHitRatio: number | null;live: SpendBucketTotals;- cron: SpendBucketTotals;- background: SpendBucketTotals;+ background: SpendBucketTotals & { sources: Record<BackgroundSource, SpendBucketTotals> };}interface SpendEntity extends SpendTotals {@@ -61,6 +67,16 @@ interface SpendEntity extends SpendTotals {displayName: string;}+type SpendExportCron = Pick<Cron, "id" | "title" | "owner" | "ownerScopeId" | "schedule" | "enabled" | "archived">;+type SpendCronInfo = SpendExportCron & Pick<Cron, "action" | "message">;++interface SpendCron extends SpendTotals {+ cronId: string;+ scopeId: ScopeId;+ scopeName: string;+ info: SpendCronInfo | null;+}+interface SpendSeriesPoint {day: string;costUsd: number;@@ -68,8 +84,7 @@ interface SpendSeriesPoint {models: { model: string | null; costUsd: number }[];people: { principalId: string | null; costUsd: number }[];live: { costUsd: number };- cron: { costUsd: number };- background: { costUsd: number };+ background: { costUsd: number; sources: Record<BackgroundSource, { costUsd: number }> };}export interface SpendReport {@@ -78,6 +93,7 @@ export interface SpendReport {series: SpendSeriesPoint[];people: SpendEntity[];scopes: SpendEntity[];+ crons: SpendCron[];models: ({ model: string | null } & SpendTotals)[];}@@ -87,7 +103,8 @@ export interface SpendExportRow extends Tally {kind: string;principalId: string | null;displayName: string;- origin: OriginBucket;+ source: SpendSource;+ cronId: string | null;model: string | null;}@@ -96,6 +113,7 @@ export interface SpendSummaryOptions {to: number;bucket: SpendBucket;label: (scopeId: ScopeId) => string;+ cron: (cronId: string) => SpendCronInfo | null;}interface Tally {@@ -112,15 +130,25 @@ interface EntityAccumulator {scopeId: ScopeId;kind: string;sources: ScopeId[];- byOrigin: Record<OriginBucket, Tally>;+ bySource: Record<SpendSource, Tally>;}function emptyTally(): Tally {return { costUsd: 0, calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };}-function emptyOrigins(): Record<OriginBucket, Tally> {- return { live: emptyTally(), cron: emptyTally(), background: emptyTally() };+function emptySources(): Record<SpendSource, Tally> {+ return Object.fromEntries(SPEND_SOURCES.map((source) => [source, emptyTally()])) as Record<SpendSource, Tally>;+}++function backgroundSources<T>(value: (source: BackgroundSource) => T): Record<BackgroundSource, T> {+ return Object.fromEntries(BACKGROUND_SOURCES.map((source) => [source, value(source)])) as Record<BackgroundSource, T>;+}++function backgroundTally(bySource: Record<SpendSource, Tally>): Tally {+ const total = emptyTally();+ for (const source of BACKGROUND_SOURCES) addTally(total, bySource[source]);+ return total;}function addRow(t: Tally, r: SpendRow): void {@@ -149,10 +177,8 @@ function bucketTotals(t: Tally): SpendBucketTotals {return { costUsd: t.costUsd, calls: t.calls, tokens: tokensOf(t) };}-function originBucket(origin: SessionOrigin): OriginBucket {- if (origin === "conversation") return "live";- if (origin === "cron") return "cron";- return "background";+function spendSource(origin: SessionOrigin): SpendSource {+ return origin === "conversation" ? "live" : origin;}function isoDay(day: number): string {@@ -163,9 +189,11 @@ function weekStart(day: number): number {return day - ((day + 3) % 7);}-function totalsOf(byOrigin: Record<OriginBucket, Tally>): SpendTotals {+function totalsOf(bySource: Record<SpendSource, Tally>): SpendTotals {+ const background = backgroundTally(bySource);const total = emptyTally();- for (const bucket of ORIGIN_BUCKETS) addTally(total, byOrigin[bucket]);+ addTally(total, bySource.live);+ addTally(total, background);return {costUsd: total.costUsd,calls: total.calls,@@ -179,9 +207,11 @@ function totalsOf(byOrigin: Record<OriginBucket, Tally>): SpendTotals {cacheWrite: total.cacheWrite,uncachedInput: total.input,}),- live: bucketTotals(byOrigin.live),- cron: bucketTotals(byOrigin.cron),- background: bucketTotals(byOrigin.background),+ live: bucketTotals(bySource.live),+ background: {+ ...bucketTotals(background),+ sources: backgroundSources((source) => bucketTotals(bySource[source])),+ },};}@@ -205,7 +235,7 @@ function entityOf(acc: EntityAccumulator, label: (scopeId: ScopeId) => string):scopeId: acc.scopeId,kind: acc.kind,displayName: displayNameOf(acc.sources, label),- ...totalsOf(acc.byOrigin),+ ...totalsOf(acc.bySource),};}@@ -216,52 +246,56 @@ function byCodePoint(a: string | null, b: string | null): number {return a < b ? -1 : 1;}-function byCostThenId(a: SpendEntity, b: SpendEntity): number {- if (a.costUsd !== b.costUsd) return b.costUsd - a.costUsd;- return byCodePoint(a.scopeId, b.scopeId);+function byCostThen<T extends { costUsd: number }>(id: (row: T) => string | null): (a: T, b: T) => number {+ return (a, b) => (a.costUsd !== b.costUsd ? b.costUsd - a.costUsd : byCodePoint(id(a), id(b)));}-function byCostThenModel(- a: { model: string | null; costUsd: number },- b: { model: string | null; costUsd: number },-): number {- if (a.costUsd !== b.costUsd) return b.costUsd - a.costUsd;- return byCodePoint(a.model, b.model);-}+const byCostThenId = byCostThen<SpendEntity>((entity) => entity.scopeId);+const byCostThenModel = byCostThen<{ model: string | null; costUsd: number }>((row) => row.model);+const byCostThenCron = byCostThen<SpendCron>((row) => row.cronId);export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOptions): SpendReport {const accumulators = new Map<string, EntityAccumulator>();const buckets = new Map<number,- { byOrigin: Record<OriginBucket, Tally>; models: Map<string | null, number>; people: Map<string | null, number> }+ { bySource: Record<SpendSource, Tally>; models: Map<string | null, number>; people: Map<string | null, number> }>();- const modelBuckets = new Map<string | null, Record<OriginBucket, Tally>>();- const orgOrigins = emptyOrigins();+ const modelBuckets = new Map<string | null, Record<SpendSource, Tally>>();+ const cronBuckets = new Map<string, { scopeId: ScopeId; bySource: Record<SpendSource, Tally> }>();+ const orgSources = emptySources();for (const row of rows) {const { key, person, kind } = resolveScope(row.scopeId);let acc = accumulators.get(key);if (!acc) {- acc = { principalId: person, scopeId: key, kind, sources: [], byOrigin: emptyOrigins() };+ acc = { principalId: person, scopeId: key, kind, sources: [], bySource: emptySources() };accumulators.set(key, acc);}if (!acc.sources.includes(row.scopeId)) acc.sources.push(row.scopeId);- const origin = originBucket(row.origin);- addRow(acc.byOrigin[origin], row);- addRow(orgOrigins[origin], row);+ const source = spendSource(row.origin);+ addRow(acc.bySource[source], row);+ addRow(orgSources[source], row);+ if (row.cronId !== null) {+ let cron = cronBuckets.get(row.cronId);+ if (!cron) {+ cron = { scopeId: row.scopeId, bySource: emptySources() };+ cronBuckets.set(row.cronId, cron);+ }+ addRow(cron.bySource[source], row);+ }let model = modelBuckets.get(row.model);if (!model) {- model = emptyOrigins();+ model = emptySources();modelBuckets.set(row.model, model);}- addRow(model[origin], row);+ addRow(model[source], row);const bucketKey = opts.bucket === "week" ? weekStart(row.day) : row.day;let bucket = buckets.get(bucketKey);if (!bucket) {- bucket = { byOrigin: emptyOrigins(), models: new Map(), people: new Map() };+ bucket = { bySource: emptySources(), models: new Map(), people: new Map() };buckets.set(bucketKey, bucket);}- addRow(bucket.byOrigin[origin], row);+ addRow(bucket.bySource[source], row);bucket.models.set(row.model, (bucket.models.get(row.model) ?? 0) + row.costUsd);bucket.people.set(person, (bucket.people.get(person) ?? 0) + row.costUsd);}@@ -270,15 +304,27 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOpticonst people = entities.filter((e) => e.principalId !== null).sort(byCostThenId);const scopes = entities.filter((e) => e.principalId === null).sort(byCostThenId);+ const crons = [...cronBuckets.entries()]+ .map(([cronId, { scopeId, bySource }]) => ({+ cronId,+ scopeId,+ scopeName: opts.label(scopeId),+ info: opts.cron(cronId),+ ...totalsOf(bySource),+ }))+ .sort(byCostThenCron);+const models = [...modelBuckets.entries()]- .map(([model, byOrigin]) => ({ model, ...totalsOf(byOrigin) }))+ .map(([model, bySource]) => ({ model, ...totalsOf(bySource) })).sort(byCostThenModel);const series = [...buckets.entries()].sort(([a], [b]) => a - b)- .map(([day, { byOrigin, models, people }]) => {+ .map(([day, { bySource, models, people }]) => {+ const background = backgroundTally(bySource);const total = emptyTally();- for (const bucket of ORIGIN_BUCKETS) addTally(total, byOrigin[bucket]);+ addTally(total, bySource.live);+ addTally(total, background);return {day: isoDay(day),costUsd: total.costUsd,@@ -287,9 +333,11 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOptipeople: [...people].sort(([a], [b]) => byCodePoint(a, b)).map(([principalId, costUsd]) => ({ principalId, costUsd })),- live: { costUsd: byOrigin.live.costUsd },- cron: { costUsd: byOrigin.cron.costUsd },- background: { costUsd: byOrigin.background.costUsd },+ live: { costUsd: bySource.live.costUsd },+ background: {+ costUsd: background.costUsd,+ sources: backgroundSources((source) => ({ costUsd: bySource[source].costUsd })),+ },};});@@ -299,10 +347,11 @@ export function summarizeSpend(rows: readonly SpendRow[], opts: SpendSummaryOptito: isoDay(Math.floor(opts.to / DAY_MS)),bucket: opts.bucket,},- org: totalsOf(orgOrigins),+ org: totalsOf(orgSources),series,people,scopes,+ crons,models,};}@@ -315,8 +364,8 @@ export function spendExportRows(rows: readonly SpendRow[], label: (scopeId: Scopconst seen = sources.get(scopeId);if (!seen) sources.set(scopeId, [row.scopeId]);else if (!seen.includes(row.scopeId)) seen.push(row.scopeId);- const origin = originBucket(row.origin);- const key = JSON.stringify([row.day, scopeId, origin, row.model]);+ const source = spendSource(row.origin);+ const key = JSON.stringify([row.day, scopeId, source, row.cronId, row.model]);let out = merged.get(key);if (!out) {out = {@@ -325,7 +374,8 @@ export function spendExportRows(rows: readonly SpendRow[], label: (scopeId: Scopkind,principalId: person,displayName: "",- origin,+ source,+ cronId: row.cronId,model: row.model,...emptyTally(),};@@ -339,7 +389,8 @@ export function spendExportRows(rows: readonly SpendRow[], label: (scopeId: Scop(a, b) =>byCodePoint(a.day, b.day) ||byCodePoint(a.scopeId, b.scopeId) ||- ORIGIN_BUCKETS.indexOf(a.origin) - ORIGIN_BUCKETS.indexOf(b.origin) ||+ SPEND_SOURCES.indexOf(a.source) - SPEND_SOURCES.indexOf(b.source) ||+ byCodePoint(a.cronId ?? "", b.cronId ?? "") ||byCodePoint(a.model ?? "", b.model ?? ""),);}@@ -351,23 +402,42 @@ function csvCell(value: string | number | null): string {return CSV_NEEDS_QUOTES.test(defanged) ? `"${defanged.replaceAll('"', '""')}"` : defanged;}-export function spendCsv(report: SpendReport, breakdown: SpendBreakdown = "entity"): string {- const modelBreakdown = breakdown === "model";- const header = modelBreakdown ? ["model"] : ["principal_id", "scope_id", "kind", "display_name"];- const rows = modelBreakdown- ? report.models.map((row) => ({ labels: [row.model ?? "Unknown model"], totals: row }))- : [...report.people, ...report.scopes].map((row) => ({- labels: [row.principalId, row.scopeId, row.kind, row.displayName],+function csvBreakdown(+ report: SpendReport,+ breakdown: SpendBreakdown,+): { header: string[]; rows: { labels: (string | null)[]; totals: SpendTotals }[] } {+ if (breakdown === "model")+ return {+ header: ["model"],+ rows: report.models.map((row) => ({ labels: [row.model ?? "Unknown model"], totals: row })),+ };+ if (breakdown === "cron")+ return {+ header: ["cron_id", "title", "owner", "scope_id"],+ rows: report.crons.map((row) => ({+ labels: [row.cronId, row.info?.title ?? null, row.info?.owner ?? null, row.scopeId],totals: row,- }));+ })),+ };+ return {+ header: ["principal_id", "scope_id", "kind", "display_name"],+ rows: [...report.people, ...report.scopes].map((row) => ({+ labels: [row.principalId, row.scopeId, row.kind, row.displayName],+ totals: row,+ })),+ };+}++export function spendCsv(report: SpendReport, breakdown: SpendBreakdown = "entity"): string {+ const { header, rows } = csvBreakdown(report, breakdown);const lines = [[...header, ...CSV_TOTALS_HEADER].join(",")];for (const { labels, totals: row } of rows) {lines.push([...labels,row.live.costUsd,- row.cron.costUsd,row.background.costUsd,+ ...BACKGROUND_SOURCES.map((source) => row.background.sources[source].costUsd),row.costUsd,row.calls,row.input,@@ -404,6 +474,23 @@ async function loadSpendRows(return sessions.spendReport ? sessions.spendReport(range) : { rows: await sessions.spendRollup(range) };}+async function cronInfoLookup(+ app: BaseCtx["app"],+ rows: readonly { cronId: string | null }[],+): Promise<Map<string, SpendCronInfo>> {+ const ids = [...new Set(rows.flatMap((row) => (row.cronId === null ? [] : [row.cronId])))];+ const crons = new Map<string, SpendCronInfo>();+ for (let start = 0; start < ids.length; start += CRON_LOOKUP_CONCURRENCY) {+ const batch = await Promise.all(ids.slice(start, start + CRON_LOOKUP_CONCURRENCY).map((id) => app.getCron(id)));+ for (const cron of batch) {+ if (!cron) continue;+ const { id, title, message, action, owner, ownerScopeId, schedule, enabled, archived } = cron;+ crons.set(id, { id, title, message, action, owner, ownerScopeId, schedule, enabled, archived });+ }+ }+ return crons;+}+export async function spendExport(ctx: BaseCtx): Promise<void> {const { req, res, app, deps, url } = ctx;const token = deps.spendExportToken;@@ -430,6 +517,17 @@ export async function spendExport(ctx: BaseCtx): Promise<void> {const scope = orgScope(deps);const window = { from: isoDay(from / DAY_MS), to: isoDay(to / DAY_MS) };const exported = spendExportRows(rows, (id) => labels.get(id) ?? "");+ const crons: SpendExportCron[] = [...(await cronInfoLookup(app, exported)).values()]+ .sort((a, b) => byCodePoint(a.id, b.id))+ .map(({ id, title, owner, ownerScopeId, schedule, enabled, archived }) => ({+ id,+ title,+ owner,+ ownerScopeId,+ schedule,+ enabled,+ archived,+ }));audit(deps, {principalId: SPEND_EXPORT_PRINCIPAL,action: "spend.export",@@ -437,7 +535,7 @@ export async function spendExport(ctx: BaseCtx): Promise<void> {scopeLabel: scope,detail: `${window.from}..${window.to} rows=${exported.length}`,});- sendJson(res, 200, { scopeId: scope, window, ...(asOf === undefined ? {} : { asOf }), rows: exported });+ sendJson(res, 200, { scopeId: scope, window, ...(asOf === undefined ? {} : { asOf }), rows: exported, crons });}export async function spend(ctx: ApiCtx): Promise<void> {@@ -453,8 +551,8 @@ export async function spend(ctx: ApiCtx): Promise<void> {const format = url.searchParams.get("format") ?? "json";if (format !== "json" && format !== "csv") return bad('format must be "json" or "csv"');- const breakdown = url.searchParams.get("breakdown") ?? "entity";- if (breakdown !== "entity" && breakdown !== "model") return bad('breakdown must be "entity" or "model"');+ const breakdown = SPEND_BREAKDOWNS.find((value) => value === (url.searchParams.get("breakdown") ?? "entity"));+ if (!breakdown) return bad('breakdown must be "entity", "model" or "cron"');const toRaw = url.searchParams.get("to");const to = toRaw === null ? Math.floor(Date.now() / DAY_MS) * DAY_MS + DAY_MS : parseBound(toRaw);@@ -472,7 +570,15 @@ export async function spend(ctx: ApiCtx): Promise<void> {deps,rows.map((r) => r.scopeId),);- const report = summarizeSpend(rows, { from, to, bucket, label: (id) => labels.get(id) ?? "" });+ const crons =+ format === "csv" && breakdown !== "cron" ? new Map<string, SpendCronInfo>() : await cronInfoLookup(app, rows);+ const report = summarizeSpend(rows, {+ from,+ to,+ bucket,+ label: (id) => labels.get(id) ?? "",+ cron: (cronId) => crons.get(cronId) ?? null,+ });if (format === "json")return sendJson(res, 200, { scopeId: scope, ...report, ...(asOf === undefined ? {} : { asOf }) });@@ -481,7 +587,7 @@ export async function spend(ctx: ApiCtx): Promise<void> {"content-type": contentTypeWithUtf8Charset("text/csv"),"content-length": String(Buffer.byteLength(body)),"content-disposition": contentDispositionAttachment(- `qm-spend-${breakdown === "model" ? "models-" : ""}${report.window.from}-${report.window.to}.csv`,+ `qm-spend-${breakdown === "entity" ? "" : `${breakdown}s-`}${report.window.from}-${report.window.to}.csv`,),"x-content-type-options": "nosniff",});diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex 8781ecc72..d11a47e9f 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -871,12 +871,13 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoreancestor = parent;origin = sessionOrigin(parent.threadRef);}+ const cronId = cronIdOf(ancestor.threadRef);for (const r of records) {if (!r.usage) continue;if (r.createdAt < range.from || r.createdAt >= range.to) continue;const day = Math.floor(r.createdAt / DAY);const model = r.model ?? null;- const key = JSON.stringify([day, session.scopeId, origin, model]);+ const key = JSON.stringify([day, session.scopeId, origin, cronId, model]);let row = buckets.get(key);if (!row) {row = {@@ -884,6 +885,7 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoremodel,scopeId: session.scopeId,origin,+ cronId,calls: 0,costUsd: 0,input: 0,diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 62b59a14d..5af156c52 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -3,7 +3,6 @@ import { randomUUID } from "node:crypto";import { jsonbStringify } from "../persistence/durable-map.ts";import {createPgPool,- type PgPool,type PoolClient,type PgQueryOptions,type Rows,@@ -78,16 +77,30 @@ import { SECURITY_SCREEN_STEP, screenPayloadFromEnvelope } from "../security/secconst threadRefOriginExpr = (threadRef: string): string =>`COALESCE(substring(${threadRef} FROM '${stableOriginPattern(ORIGIN_ALTERNATION)}'), substring(${threadRef} FROM '${legacyOriginPattern(ORIGIN_ALTERNATION)}'), 'conversation')`;-export async function backfillSessionOriginBatch(q: PgPool["q"], limit: number): Promise<number> {- const updated = await q(- `UPDATE sessions- SET origin = ${threadRefOriginExpr("thread_ref")}, origin_id = ${threadRefCronIdExpr("thread_ref")}- WHERE id IN (SELECT id FROM sessions WHERE origin IS NULL LIMIT $1)- RETURNING 1`,- [limit],- );- return updated.length;-}+const LOOP_OR_SWARM_REF = legacyOriginPattern("(loop|swarm)");++const sessionOriginBackfillLoop = (candidates: string, keepSpendMarkers: boolean): string => `+ after := '';+ LOOP+ SELECT array_agg(id ORDER BY id) INTO batch+ FROM (SELECT id FROM sessions WHERE id > after AND ${candidates} ORDER BY id LIMIT 5000) candidates;+ EXIT WHEN batch IS NULL;+ UPDATE sessions SET origin = ${threadRefOriginExpr("thread_ref")}, origin_id = ${threadRefCronIdExpr("thread_ref")}+ WHERE id = ANY(batch);${keepSpendMarkers ? "" : "\n DELETE FROM session_spend_dirty WHERE writer = pg_current_xact_id();"}+ after := batch[cardinality(batch)];+ COMMIT;+ PERFORM pg_sleep(0.25);+ END LOOP;`;++const SESSION_ORIGIN_BACKFILL_SQL = `DO $session_origin_backfill$+DECLARE+ batch text[];+ after text;+BEGIN${sessionOriginBackfillLoop(`origin IS NULL AND thread_ref !~ '${LOOP_OR_SWARM_REF}'`, false)}${sessionOriginBackfillLoop(+ `(origin IS NULL OR origin = 'conversation') AND thread_ref ~ '${LOOP_OR_SWARM_REF}'`,+ true,+)}+END $session_origin_backfill$`;function rowToGoal(r: Record<string, unknown>): GoalRecord {return {@@ -207,6 +220,7 @@ function rowToSpendRow(r: Record<string, unknown>): SpendRow {model: (r.model as string | null) ?? null,scopeId: r.scope_id as ScopeId,origin: r.origin as SessionOrigin,+ cronId: (r.cron_id as string | null) ?? null,calls: Number(r.calls),costUsd: Number(r.cost_usd),input: Number(r.input),@@ -300,31 +314,29 @@ export function createPostgresSessionStore(const rows = await q(participantSessionsSql(" AND s.id = $2"), [principalId, sessionId]);return rows[0] ? rowToParticipantSession(rows[0]) : null;};- const originExpr = (alias: string): string =>- `COALESCE(${alias}.origin, ${threadRefOriginExpr(`${alias}.thread_ref`)})`;- const cronIdExpr = (alias: string): string =>- `COALESCE(${alias}.origin_id, ${threadRefCronIdExpr(`${alias}.thread_ref`)})`;- const isBackground = (alias: string): string => `${originExpr(alias)} <> 'conversation'`;- const hasOrigin = (alias: string, origin: SessionOrigin): string => `${originExpr(alias)} = '${origin}'`;+ const isBackground = (alias: string): string => `${alias}.origin <> 'conversation'`;+ const hasOrigin = (alias: string, origin: SessionOrigin): string => `${alias}.origin = '${origin}'`;const originFilterClause = (alias: string, origin: SessionOriginFilter): string =>- origin === "other_background" ? `${originExpr(alias)} NOT IN ('conversation', 'cron')` : hasOrigin(alias, origin);+ origin === "other_background" ? `${alias}.origin NOT IN ('conversation', 'cron')` : hasOrigin(alias, origin);const spendSql = `WITH RECURSIVE ancestry AS (- SELECT s.id AS session_id, s.parent_session_id, ${originExpr("s")} AS origin, ARRAY[s.id] AS path+ SELECT s.id AS session_id, s.parent_session_id, s.origin AS origin, s.origin_id AS cron_id,+ ARRAY[s.id] AS pathFROM sessions s- WHERE s.parent_session_id IS NOT NULL AND ${originExpr("s")} = 'conversation'+ WHERE s.parent_session_id IS NOT NULL AND s.origin = 'conversation'AND EXISTS (SELECT 1 FROM session_llm_requests rWHERE r.session_id = s.id AND r.created_at >= $1 AND r.created_at < $2AND r.usage_json IS NOT NULL)UNION ALL- SELECT a.session_id, p.parent_session_id, ${originExpr("p")}, a.path || p.id+ SELECT a.session_id, p.parent_session_id, p.origin, p.origin_id, a.path || p.idFROM ancestry a JOIN sessions p ON p.id = a.parent_session_idWHERE a.origin = 'conversation' AND NOT p.id = ANY(a.path) AND cardinality(a.path) < 64), origins AS (- SELECT DISTINCT ON (session_id) session_id, origin+ SELECT DISTINCT ON (session_id) session_id, origin, cron_idFROM ancestry ORDER BY session_id, cardinality(path) DESC), rollup AS MATERIALIZED (SELECT (r.created_at / 86400000)::bigint AS day, s.scope_id,- COALESCE(o.origin, ${originExpr("s")}) AS origin, r.model,+ COALESCE(o.origin, s.origin) AS origin,+ COALESCE(o.cron_id, s.origin_id) AS cron_id, r.model,COUNT(*) AS calls,COALESCE(SUM(cost_usd), 0)::text AS cost_usd,COALESCE(SUM(input), 0) AS input,@@ -354,9 +366,9 @@ export function createPostgresSessionStore(OFFSET 0) rJOIN sessions s ON s.id = r.session_idLEFT JOIN origins o ON o.session_id = s.id- GROUP BY day, s.scope_id, COALESCE(o.origin, ${originExpr("s")}), r.model+ GROUP BY day, s.scope_id, COALESCE(o.origin, s.origin), COALESCE(o.cron_id, s.origin_id), r.model)- SELECT * FROM rollup ORDER BY day, scope_id, origin, model`;+ SELECT * FROM rollup ORDER BY day, scope_id, origin, cron_id, model`;const { pool, q } = createPgPool(connectionString,@@ -897,6 +909,11 @@ export function createPostgresSessionStore(id: "sessions/store/0033-client-tools",statements: [`ALTER TABLE sessions ADD COLUMN IF NOT EXISTS client_tools JSONB`],},+ {+ id: "sessions/store/0034-session-origin-backfill",+ prepare: [SESSION_ORIGIN_BACKFILL_SQL],+ statements: [],+ },...(opts.stageItemsCutover? []: [@@ -1788,7 +1805,7 @@ export function createPostgresSessionStore(let cronClause = "";if (page.cronId) {params.push(page.cronId);- cronClause = ` AND ${cronIdExpr("s")} = $${params.length}`;+ cronClause = ` AND s.origin_id = $${params.length}`;}let keysetClause = "";if (page.before) {@@ -1797,7 +1814,7 @@ export function createPostgresSessionStore(}params.push(page.limit);const rows = await q(- `SELECT s.id, s.type, s.scope_id, s.thread_ref, s.created_at, s.messages, s.turns,+ `SELECT s.id, s.type, s.scope_id, s.thread_ref, s.origin, s.created_at, s.messages, s.turns,${lastActivityExpr("s")} AS last_activity, s.first_user_preview, s.last_user_previewFROM sessions sWHERE ($1::boolean OR s.scope_id = $2)${categoryClause}${originClause}${cronClause}${keysetClause}@@ -1810,7 +1827,7 @@ export function createPostgresSessionStore(return rows.map((r) => ({id: r.id as string,type: r.type as Session["type"],- origin: sessionOrigin(r.thread_ref as string | null),+ origin: r.origin as SessionOrigin,scopeId: r.scope_id as Session["scopeId"],threadRef: r.thread_ref as Session["threadRef"],turns: Number(r.turns ?? 0),@@ -1845,7 +1862,7 @@ export function createPostgresSessionStore(COALESCE(SUM(t.turns), 0) AS turns,MAX(t.activity) AS last_activity,MIN(t.created_at) AS created_at- FROM (SELECT ${cronIdExpr("s")} AS cron_id, s.scope_id, s.messages, s.turns, s.created_at,+ FROM (SELECT s.origin_id AS cron_id, s.scope_id, s.messages, s.turns, s.created_at,${lastActivityExpr("s")} AS activityFROM sessions sWHERE ($1::boolean OR s.scope_id = $2)) t@@ -1906,14 +1923,14 @@ export function createPostgresSessionStore(if (originFilter) matchedClauses.push(originFilterClause("s", originFilter));if (cronId) {params.push(cronId);- matchedClauses.push(`${cronIdExpr("s")} = $${params.length}`);+ matchedClauses.push(`s.origin_id = $${params.length}`);}const rows = await q(`SELECT origin, CASE WHEN origin = 'conversation' THEN type ELSE origin END AS bucket,matched, COUNT(*) AS sessions, COALESCE(SUM(turns), 0) AS turns,COUNT(DISTINCT cron_id) AS crons- FROM (SELECT s.type, ${originExpr("s")} AS origin,- ${cronIdExpr("s")} AS cron_id,+ FROM (SELECT s.type, s.origin AS origin,+ s.origin_id AS cron_id,(${matchedClauses.join(" AND ") || "TRUE"}) AS matched,COALESCE(s.turns, 0) AS turnsFROM sessions s@@ -2014,9 +2031,10 @@ export function createPostgresSessionStore(});const days = await q(`SELECT d.day FROM (SELECT DISTINCT day FROM session_spend_dirty WHERE day IS NOT NULL) d- LEFT JOIN session_spend_days c ON c.day = d.day ORDER BY c.updated_at NULLS FIRST, d.day DESC`,+ LEFT JOIN session_spend_days c ON c.day = d.day+ ORDER BY d.day = max(d.day) OVER () DESC, c.updated_at NULLS FIRST, d.day DESC`,);- for (const { day } of days) {+ for (const [index, { day }] of days.entries()) {try {await withPgTransaction(await pool(), async (client) => {const pending = await client.query("DELETE FROM session_spend_dirty WHERE day = $1 RETURNING day", [day]);@@ -2033,7 +2051,7 @@ export function createPostgresSessionStore(reportFailure("spend: refresh daily totals", error);continue;}- if (Date.now() - started >= 5_000) break;+ if (index > 0 && Date.now() - started >= 5_000) break;}},diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex 347eff9ab..babb44bdb 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -201,6 +201,7 @@ export interface SpendRow {model: string | null;scopeId: ScopeId;origin: SessionOrigin;+ cronId: string | null;calls: number;costUsd: number;input: number;@@ -337,11 +338,11 @@ export interface AttributedTurn {lastAt: number;}-export type SessionOrigin = "conversation" | "cron" | "webhook" | "monitor";+export type SessionOrigin = "conversation" | "cron" | "webhook" | "monitor" | "loop" | "swarm";export const stableOriginPattern = (origin: string): string => `^agent:main:${origin}:[^:]+$`;export const legacyOriginPattern = (origin: string): string => `^${origin}:[^:]+(:.+)?$`;-export const ORIGIN_ALTERNATION = "(cron|webhook|monitor)";+export const ORIGIN_ALTERNATION = "(cron|webhook|monitor|loop|swarm)";const STABLE_CRON_ID_PATTERN = "^agent:main:cron:([^:]+)$";const LEGACY_CRON_ID_PATTERN = "^cron:([^:]+)(:.+)?$";export const threadRefCronIdExpr = (threadRef: string): string =>diff --git a/test/admin-spend.test.ts b/test/admin-spend.test.tsindex 0a5be0b02..570bd38e2 100644--- a/test/admin-spend.test.ts+++ b/test/admin-spend.test.ts@@ -91,9 +91,13 @@ test("spend: live and cron dollars land on the owning person, shared scopes on tconst alice = body.people.find((p: any) => p.principalId === "alice");const bob = body.people.find((p: any) => p.principalId === "bob");assert.ok(alice && bob, "both principals appear with the ids the Users page shows");- assert.ok(alice.live.costUsd > 0 && alice.cron.costUsd > 0, "alice carries both live and cron dollars");- assert.equal(bob.cron.costUsd, 0, "bob never ran a cron");- assert.equal(alice.cron.costUsd, 0.5, "the cron is billed to its scope owner, not to a speaker");+ assert.ok(+ alice.live.costUsd > 0 && alice.background.sources.cron.costUsd > 0,+ "alice carries both live and cron dollars",+ );+ assert.equal(bob.background.sources.cron.costUsd, 0, "bob never ran a cron");+ assert.equal(alice.background.sources.cron.costUsd, 0.5, "the cron is billed to its scope owner, not to a speaker");+ assert.equal(alice.background.costUsd, 0.5, "crons count toward background");assert.deepEqual(body.scopes.map((e: any) => [e.principalId, e.scopeId, e.kind, e.costUsd]),@@ -229,11 +233,11 @@ test("spend: ?format=csv exports the same numbers for the same window", async ()const lines = body.trimEnd().split("\r\n");assert.equal(lines[0],- "principal_id,scope_id,kind,display_name,live_usd,cron_usd,background_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio",+ "principal_id,scope_id,kind,display_name,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio",);assert.equal(lines.length, json.people.length + json.scopes.length + 1);const alice = lines.find((l) => l.startsWith("alice,"))!.split(",");- assert.equal(Number(alice[7]), json.people.find((p: any) => p.principalId === "alice").costUsd);+ assert.equal(Number(alice[11]), json.people.find((p: any) => p.principalId === "alice").costUsd);} finally {await s.close();}@@ -313,6 +317,57 @@ test("spend: an empty deployment answers 200 with zeroed totals", async () => {}});+test("spend: cron JSON and CSV name each billed cron, giving admins the task an untitled cron is known by", async () => {+ const clock = { at: Date.UTC(2026, 0, 5, 12) };+ const store = createMemorySessionStore({ now: () => clock.at });+ const s = start(store);+ try {+ const cron = await s.built.app.createCron({+ ownerScopeId: "personal:alice",+ owner: "alice",+ createdBy: "alice",+ schedule: { everyMs: 3_600_000 },+ action: "check the build",+ });+ await bill(store, `cron:${cron.id}:fire:1`, "dm", scopeId("personal", "alice"), { costUsd: 3 });+ await bill(store, "dm:alice:priced", "dm", scopeId("personal", "alice"), { costUsd: 2 });+ const query = "from=2026-01-05&to=2026-01-06";+ const json = await getJson(s.base, `/v1/admin/spend?${query}`);+ assert.deepEqual(+ json.crons.map((c: any) => [c.cronId, c.scopeId, c.costUsd, c.info.action]),+ [[cron.id, "personal:alice", 3, "check the build"]],+ );+ const r = await get(s.base, `/v1/admin/spend?${query}&breakdown=cron&format=csv`);+ assert.equal(r.status, 200);+ assert.match(+ r.headers.get("content-disposition")!,+ /^attachment; filename="qm-spend-crons-2026-01-05-2026-01-06\.csv"/,+ );+ const [header, line, ...rest] = (await r.text()).trimEnd().split("\r\n");+ assert.match(+ header!,+ /^cron_id,title,owner,scope_id,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,/,+ );+ assert.deepEqual(line!.split(",").slice(0, 12), [+ cron.id,+ "",+ "alice",+ "personal:alice",+ "0",+ "3",+ "3",+ "0",+ "0",+ "0",+ "0",+ "3",+ ]);+ assert.deepEqual(rest, []);+ } finally {+ await s.close();+ }+});+test("spend: model CSV selects the model breakdown with its own filename", async () => {const clock = { at: Date.UTC(2026, 0, 5, 12) };const store = createMemorySessionStore({ now: () => clock.at });@@ -342,8 +397,8 @@ test("spend: model CSV selects the model breakdown with its own filename", asyncfor (const [i, model] of json.models.entries()) {const cells = lines[i + 1]!.split(",");assert.equal(cells[0], model.model);- assert.equal(Number(cells[4]), model.costUsd);- assert.equal(Number(cells[5]), model.calls);+ assert.equal(Number(cells[8]), model.costUsd);+ assert.equal(Number(cells[9]), model.calls);}assert.equal(json.models.reduce((sum: number, m: any) => sum + m.costUsd, 0),diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex 480955d2c..d4a993a3a 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -4,11 +4,7 @@ import { randomUUID } from "node:crypto";import assert from "node:assert/strict";import { applyPgMigrations, migrateRegisteredPgSchemas, registeredPgMigrations } from "../src/persistence/pg-pool.ts";import { PARALLEL_EXCEPTION_QUERY } from "../src/deployment/postdeploy-smoke.ts";-import {- backfillSessionOriginBatch,- createPostgresSessionStore,- rowToSession,-} from "../src/sessions/postgres-session-store.ts";+import { createPostgresSessionStore, rowToSession } from "../src/sessions/postgres-session-store.ts";import { SECURITY_SCREEN_STEP } from "../src/security/security-posture.ts";import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";import { createPostgresRunSignalStore } from "../src/runs/postgres-run-signal-store.ts";@@ -328,6 +324,81 @@ test("pg spend refresh keeps concurrent writes pending and failures preserve the}});+test(+ "pg spend refresh takes the newest dirty day, then the stalest days, at least two per pass",+ { skip },+ async (t) => {+ const pg = (await import("pg")).default;+ const admin = new pg.Pool({ connectionString: URL });+ const schema = `spend_order_${randomUUID().replaceAll("-", "")}`;+ await admin.query(`CREATE SCHEMA ${schema}`);+ const url = new globalThis.URL(URL!);+ url.searchParams.set("options", `-c search_path=${schema}`);+ const day = 86_400_000;+ const base = Date.UTC(2025, 5, 1);+ let clock = base + 3 * day;+ let at = base;+ let elapsed = 0;+ let slow = false;+ const store = createPostgresSessionStore(url.toString(), {+ now: () => {+ if (slow) elapsed += 10_000;+ return at;+ },+ });+ const raw = new pg.Pool({ connectionString: url.toString() });+ const scope = scopeId("personal", "spend-order");+ const session = await store.getOrCreateByThread("spend-order", "dm", scope);+ const bill = async (offset: number) => {+ at = base + offset * day;+ await store.recordLlmRequest(session.id, {+ turnSeq: null,+ step: 0,+ model: "order",+ scopeLabel: scope,+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, costUsd: 1 },+ });+ at = clock;+ };+ const slowPass = async () => {+ clock += 60_000;+ at = clock;+ slow = true;+ await store.refreshSpendRollup!();+ slow = false;+ };+ const pending = async () =>+ (await raw.query("SELECT DISTINCT day FROM session_spend_dirty WHERE day IS NOT NULL ORDER BY day")).rows.map(+ (r) => Number(r.day) - base / day,+ );+ try {+ for (const offset of [0, 1, 2, 3]) {+ await bill(offset);+ at = base + offset * day;+ await store.refreshSpendRollup!();+ }+ for (const offset of [0, 1, 2, 3]) await bill(offset);+ t.mock.method(Date, "now", () => elapsed);+ await slowPass();+ assert.deepEqual(await pending(), [1, 2]);+ await bill(2);+ await bill(3);+ await slowPass();+ assert.deepEqual(await pending(), [2]);+ await slowPass();+ assert.deepEqual(await pending(), []);+ clock = base + 10 * day;+ for (const offset of [0, 1, 2]) await bill(offset);+ await slowPass();+ assert.deepEqual(await pending(), [1]);+ } finally {+ await raw.end();+ await admin.query(`DROP SCHEMA ${schema} CASCADE`);+ await admin.end();+ }+ },+);+test("pg saved spend resolves session changes after commit and preserves non-finite legacy costs",{ skip },@@ -1111,7 +1182,7 @@ test();test(- "pg session origin columns: written at insert, regex fallback while NULL, backfill restores them",+ "pg session origin columns: written at insert, and the store migration fills rows that predate them",{ skip },async () => {const s = createPostgresSessionStore(URL!);@@ -1121,6 +1192,8 @@ test("cron:oc2:slot": { origin: "cron", cronId: "oc2" },"agent:main:webhook:ocw": { origin: "webhook", cronId: null },"monitor:ocm:extra": { origin: "monitor", cronId: null },+ "loop:ocl:fire:aaa": { origin: "loop", cronId: null },+ "swarm:ocs:member": { origin: "swarm", cronId: null },"ch:C1:oc-thread": { origin: "conversation", cronId: null },};const ids: string[] = [];@@ -1160,7 +1233,12 @@ test(assert.deepEqual(await columns(), shapes, "insert derives origin and origin_id from the thread ref");const stored = await classify();assert.deepEqual(stored.groups, ["oc1", "oc2"]);- assert.deepEqual(stored.other, ["agent:main:webhook:ocw", "monitor:ocm:extra"]);+ assert.deepEqual(stored.other, [+ "agent:main:webhook:ocw",+ "loop:ocl:fire:aaa",+ "monitor:ocm:extra",+ "swarm:ocs:member",+ ]);assert.deepEqual(stored.conversation, ["ch:C1:oc-thread"]);assert.deepEqual(stored.cron, ["agent:main:cron:oc1", "cron:oc2:slot"]);assert.deepEqual(stored.oc2, ["cron:oc2:slot"]);@@ -1168,22 +1246,42 @@ test(assert.equal(stored.cronStats.total, 1);await q("UPDATE sessions SET origin = NULL, origin_id = NULL WHERE id = ANY($1)", [ids]);+ await q("UPDATE sessions SET origin = 'conversation' WHERE id = ANY($1) AND thread_ref ~ '^(loop|swarm):'", [+ ids,+ ]);+ await q("DELETE FROM session_spend_dirty WHERE session_id = ANY($1)", [ids]);+ const unrelated = randomUUID();+ await q("INSERT INTO session_spend_dirty(session_id) VALUES ($1)", [unrelated]);+ await q("DELETE FROM qm_schema_migrations WHERE id = 'sessions/store/0034-session-origin-backfill'");+ await applyPgMigrations(raw, registeredPgMigrations(URL!));+ assert.deepEqual(await columns(), shapes, "the migration derives the same values the insert path wrote");+ assert.deepEqual(await classify(), stored, "migrated rows classify identically");assert.deepEqual(- await classify(),- stored,- "NULL columns fall back to the thread-ref regex and classify identically",+ (+ await q(+ "SELECT s.thread_ref FROM session_spend_dirty d JOIN sessions s ON s.id = d.session_id WHERE d.session_id = ANY($1)",+ [ids],+ )+ )+ .map((r) => r.thread_ref)+ .sort(),+ ["loop:ocl:fire:aaa", "swarm:ocs:member"],+ "filling in the columns leaves no spend to recompute, but reclassified loops and swarms recompute theirs",+ );+ await q("DELETE FROM session_spend_dirty WHERE session_id = ANY($1)", [ids]);+ assert.deepEqual(+ await q("DELETE FROM session_spend_dirty WHERE session_id = $1 RETURNING session_id", [unrelated]),+ [{ session_id: unrelated }],+ "another transaction's pending spend survives the backfill",+ );+ await q("UPDATE sessions SET origin = 'cron' WHERE id = ANY($1) AND thread_ref = 'ch:C1:oc-thread'", [ids]);+ assert.deepEqual(+ (await s.scopeSessionSummaries(team, false, { limit: 10, origin: "cron" }))+ .filter((r) => r.threadRef === "ch:C1:oc-thread")+ .map((r) => r.origin),+ ["cron"],+ "a listed session reports the stored origin its filter matched",);-- let batches = 0;- let updated = 0;- for (let n = await backfillSessionOriginBatch(q, 2); n > 0; n = await backfillSessionOriginBatch(q, 2)) {- batches++;- updated += n;- }- assert.ok(updated >= ids.length, "the backfill reaches every NULL row");- assert.ok(batches >= 3, "the backfill works in bounded batches until nothing is left");- assert.deepEqual(await columns(), shapes, "the backfill derives the same values the insert path wrote");- assert.deepEqual(await classify(), stored, "backfilled rows classify identically");} finally {await raw.end();}diff --git a/test/spend-export.test.ts b/test/spend-export.test.tsindex d7760a29d..d1dc9bd5c 100644--- a/test/spend-export.test.ts+++ b/test/spend-export.test.ts@@ -95,7 +95,7 @@ test("spend export: the token authorizes the export and nothing else", async ()}});-test("spend export: rows keep the ledger grain with canonical people, origin buckets and the org scope, in code-point order", async () => {+test("spend export: rows keep the ledger grain with canonical people, sources and the org scope, in code-point order", async () => {const s = fixture();try {const sessions = s.sessions!;@@ -111,13 +111,23 @@ test("spend export: rows keep the ledger grain with canonical people, origin bucassert.equal(body.scopeId, "org:default-org");assert.deepEqual(body.window, { from: iso(today - DAY), to: iso(today + DAY) });assert.deepEqual(- body.rows.map((r: any) => [r.day, r.scopeId, r.kind, r.principalId, r.origin, r.model, r.calls, r.costUsd]),+ body.rows.map((r: any) => [+ r.day,+ r.scopeId,+ r.kind,+ r.principalId,+ r.source,+ r.cronId,+ r.model,+ r.calls,+ r.costUsd,+ ]),[- [iso(today), "channel:C1", "channel", null, "live", "claude-opus-5", 1, 3],- [iso(today), "channel:C1", "channel", null, "background", "claude-opus-5", 1, 4],- [iso(today), "personal:U1", "person", "U1", "live", "claude-opus-5", 1, 1],- [iso(today), "personal:alice", "person", "alice", "live", "claude-opus-5", 2, 3],- [iso(today), "personal:alice", "person", "alice", "cron", "gpt-6-astra", 1, 0.5],+ [iso(today), "channel:C1", "channel", null, "live", null, "claude-opus-5", 1, 3],+ [iso(today), "channel:C1", "channel", null, "webhook", null, "claude-opus-5", 1, 4],+ [iso(today), "personal:U1", "person", "U1", "live", null, "claude-opus-5", 1, 1],+ [iso(today), "personal:alice", "person", "alice", "live", null, "claude-opus-5", 2, 3],+ [iso(today), "personal:alice", "person", "alice", "cron", "nightly", "gpt-6-astra", 1, 0.5],],);assert.deepEqual(@@ -133,6 +143,50 @@ test("spend export: rows keep the ledger grain with canonical people, origin buc}});+test("spend export: lists each billed cron's title, owner and schedule without its task", async () => {+ const s = fixture();+ try {+ const cron = await s.built.app.createCron({+ ownerScopeId: "personal:alice",+ owner: "alice",+ createdBy: "alice",+ title: "Morning digest",+ schedule: { cron: "0 9 * * 1-5", timezone: "America/New_York" },+ action: "summarize my unread mail",+ });+ await s.built.app.createCron({+ ownerScopeId: "personal:alice",+ owner: "alice",+ createdBy: "alice",+ title: "Never billed",+ schedule: { everyMs: 60_000 },+ action: "idle",+ });+ await bill(s.sessions!, `cron:${cron.id}:fire:1`, "dm", scopeId("personal", "alice"), { costUsd: 2 }, "m1");+ await bill(s.sessions!, "cron:deleted:fire:1", "dm", scopeId("personal", "alice"), { costUsd: 1 }, "m1");+ const body: any = await (await s.get(`/v1/spend/export?${window}`)).json();+ assert.deepEqual(+ body.rows.map((r: any) => [r.cronId, r.costUsd]),+ [+ [cron.id, 2],+ ["deleted", 1],+ ].sort((a, b) => (String(a[0]) < String(b[0]) ? -1 : 1)),+ );+ assert.deepEqual(body.crons, [+ {+ id: cron.id,+ title: "Morning digest",+ owner: "alice",+ ownerScopeId: "personal:alice",+ schedule: { cron: "0 9 * * 1-5", timezone: "America/New_York" },+ enabled: true,+ },+ ]);+ } finally {+ await s.close();+ }+});+test("spend export: passes through the saved report's freshness", async () => {const store = createMemorySessionStore();const asOf = Date.UTC(2026, 0, 1);diff --git a/test/spend-summary.test.ts b/test/spend-summary.test.tsindex 502fe69a9..705002219 100644--- a/test/spend-summary.test.ts+++ b/test/spend-summary.test.ts@@ -12,6 +12,7 @@ const WED = 20355;const row = (over: Partial<SpendRow> & Pick<SpendRow, "day" | "scopeId" | "origin">): SpendRow => ({model: null,+ cronId: null,calls: 1,costUsd: 0,input: 0,@@ -92,6 +93,7 @@ const summarize = (rows: SpendRow[], over: Partial<Parameters<typeof summarizeSpto: (WED + 1) * DAY,bucket: "day",label: () => "",+ cron: () => null,...over,});@@ -123,15 +125,42 @@ test("summarizeSpend: people plus non-person scopes conserve the org totals", ()}const alice = report.people.find((p) => p.principalId === "alice")!;assert.equal(alice.live.costUsd, 1.75);- assert.equal(alice.cron.costUsd, 0.75);- assert.equal(alice.cron.calls, 3);- assert.equal(alice.background.costUsd, 0);+ assert.equal(alice.background.sources.cron.costUsd, 0.75);+ assert.equal(alice.background.sources.cron.calls, 3);+ assert.equal(alice.background.costUsd, 0.75, "crons are background");const bob = report.people.find((p) => p.principalId === "bob")!;- assert.equal(bob.cron.costUsd, 0, "no cron rows means a zero cron bucket, not a missing one");+ assert.equal(bob.background.sources.cron.costUsd, 0, "no cron rows means a zero cron source, not a missing one");+ assert.equal(bob.background.sources.monitor.costUsd, 4);assert.equal(bob.background.costUsd, 4, "monitor origin rolls up as background");+ assert.equal(report.scopes[0]!.background.sources.webhook.costUsd, 2);assert.equal(report.scopes[0]!.background.costUsd, 2, "webhook origin rolls up as background");});+test("summarizeSpend: background holds every non-live source, split by where it came from", () => {+ const report = summarize([+ row({ day: MON, scopeId: "personal:alice", origin: "conversation", costUsd: 1 }),+ row({ day: MON, scopeId: "personal:alice", origin: "cron", costUsd: 2 }),+ row({ day: MON, scopeId: "personal:alice", origin: "loop", costUsd: 4 }),+ row({ day: MON, scopeId: "personal:alice", origin: "swarm", costUsd: 8 }),+ row({ day: MON, scopeId: "personal:alice", origin: "webhook", costUsd: 16 }),+ row({ day: MON, scopeId: "personal:alice", origin: "monitor", costUsd: 32 }),+ ]);+ const alice = report.people[0]!;+ assert.equal(alice.live.costUsd, 1);+ assert.equal(alice.background.costUsd, 62);+ assert.deepEqual(+ Object.fromEntries(Object.entries(alice.background.sources).map(([source, t]) => [source, t.costUsd])),+ { cron: 2, loop: 4, swarm: 8, webhook: 16, monitor: 32 },+ );+ assert.equal(alice.costUsd, alice.live.costUsd + alice.background.costUsd);+ const day = report.series[0]!;+ assert.equal(day.background.costUsd, 62);+ assert.deepEqual(+ Object.fromEntries(Object.entries(day.background.sources).map(([source, t]) => [source, t.costUsd])),+ { cron: 2, loop: 4, swarm: 8, webhook: 16, monitor: 32 },+ );+});+test("summarizeSpend: cache hit ratio comes from the shared helper and is null without cache data", () => {const report = summarize(ROWS);assert.equal(@@ -180,7 +209,7 @@ test("summarizeSpend: the series is sparse, UTC-keyed, and restricted to [from,const narrowed = summarizeSpend(ROWS.filter((r) => r.day >= TUE && r.day < WED),- { from: TUE * DAY, to: WED * DAY, bucket: "day", label: () => "" },+ { from: TUE * DAY, to: WED * DAY, bucket: "day", label: () => "", cron: () => null },);assert.deepEqual(narrowed.window, { from: "2025-09-23", to: "2025-09-24", bucket: "day" });assert.deepEqual(@@ -208,14 +237,15 @@ test("spendCsv: one row per entity, people first, matching the report's numbers"const lines = spendCsv(report).trimEnd().split("\r\n");assert.equal(lines[0],- "principal_id,scope_id,kind,display_name,live_usd,cron_usd,background_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio",+ "principal_id,scope_id,kind,display_name,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio",);assert.equal(lines.length, report.people.length + report.scopes.length + 1);const bob = lines.find((l) => l.startsWith("bob,"))!.split(",");const bobRow = report.people.find((p) => p.principalId === "bob")!;- assert.equal(Number(bob[7]), bobRow.costUsd);+ assert.equal(Number(bob[11]), bobRow.costUsd);assert.equal(Number(bob[4]), bobRow.live.costUsd);- assert.equal(Number(bob[6]), bobRow.background.costUsd);+ assert.equal(Number(bob[5]), bobRow.background.costUsd);+ assert.equal(Number(bob[10]), bobRow.background.sources.monitor.costUsd);assert.equal(lines.at(-1)!.split(",")[1], "channel:C1", "non-person rows come last");});@@ -245,7 +275,7 @@ test("summarizeSpend: models conserve org totals and category totals across scopcolumn,);}- for (const origin of ["live", "cron", "background"] as const) {+ for (const origin of ["live", "background"] as const) {for (const column of ["costUsd", "calls", "tokens"] as const) {assert.equal(report.models.reduce((sum, m) => sum + m[origin][column], 0),@@ -263,7 +293,7 @@ test("summarizeSpend: models conserve org totals and category totals across scop}),);}- assert.equal(report.models.find((m) => m.model === null)!.cron.costUsd, 0.75);+ assert.equal(report.models.find((m) => m.model === null)!.background.sources.cron.costUsd, 0.75);assert.deepEqual(summarize([]).models, []);});@@ -303,13 +333,13 @@ test("spendCsv: model export retains totals, unknown models, and safe escaping",const csv = spendCsv(report, "model");assert.ok(csv.startsWith(- "model,live_usd,cron_usd,background_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio\r\n",+ "model,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio\r\n",),);- assert.ok(csv.includes('"Model ""quoted"", name",0,1,0,1,1,100,0,100,0,0.5\r\n'));+ assert.ok(csv.includes('"Model ""quoted"", name",0,1,1,0,0,0,0,1,1,100,0,100,0,0.5\r\n'));assert.ok(csv.includes('"line one\r\nline two"'));for (const model of ["=formula", "+formula", "-formula", "@formula"]) assert.ok(csv.includes(`'${model},`));- assert.ok(csv.includes("Unknown model,0,1,0,1,1,100,0,100,0,0.5\r\n"));+ assert.ok(csv.includes("Unknown model,0,1,1,0,0,0,0,1,1,100,0,100,0,0.5\r\n"));assert.equal(spendCsv(report), spendCsv(report, "entity"));});@@ -410,7 +440,7 @@ for (const bucket of ["day", "week"] as const) {});}-test("spendExportRows keeps the ledger grain, merging principal aliases into one person per day, origin and model", (t) => {+test("spendExportRows keeps the ledger grain, merging principal aliases into one person per day, source and model", (t) => {installPrincipalLinks({ canonical: (id) => (id === "slack-alice" ? "alice" : undefined), aliases: () => [] });t.after(() => installPrincipalLinks(null));const labels = new Map([@@ -425,16 +455,22 @@ test("spendExportRows keeps the ledger grain, merging principal aliases into onerow({ day: MON, scopeId: "personal:alice", origin: "monitor", model: "m1", costUsd: 4 }),row({ day: MON, scopeId: "personal:alice", origin: "webhook", model: "m1", costUsd: 16 }),row({ day: MON, scopeId: "personal:alice", origin: "conversation", model: null, costUsd: 32 }),+ row({ day: MON, scopeId: "personal:alice", origin: "loop", model: "m1", costUsd: 64 }),+ row({ day: MON, scopeId: "personal:alice", origin: "swarm", model: "m1", costUsd: 128 }),];const rows = spendExportRows(ledger, (id) => labels.get(id) ?? "");assert.deepEqual(- rows.map((r) => [r.day, r.scopeId, r.kind, r.principalId, r.displayName, r.origin, r.model, r.costUsd, r.calls]),+ rows.map((r) => [r.day, r.scopeId, r.kind, r.principalId, r.displayName, r.source, r.model, r.costUsd, r.calls]),[["2025-09-22", "personal:alice", "person", "alice", "Alice", "live", null, 32, 1],["2025-09-22", "personal:alice", "person", "alice", "Alice", "live", "m1", 3, 2],- ["2025-09-22", "personal:alice", "person", "alice", "Alice", "background", "m1", 20, 2],+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "loop", "m1", 64, 1],+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "swarm", "m1", 128, 1],+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "webhook", "m1", 16, 1],+ ["2025-09-22", "personal:alice", "person", "alice", "Alice", "monitor", "m1", 4, 1],["2025-09-23", "channel:C1", "channel", null, "#general", "cron", "m1", 8, 2],],+ "each row names its exact source, live first, then background kinds in report order",);assert.equal(rows[1]!.input, 8);const report = summarize(ledger, { bucket: "day", to: (TUE + 1) * DAY, label: (id) => labels.get(id) ?? "" });@@ -453,3 +489,95 @@ test("spendExportRows keeps the ledger grain, merging principal aliases into one"the export names each scope exactly as the Spend page does",);});++test("summarizeSpend: crons group each cron's spend under the scope it ran in, and deleted crons keep theirs", (t) => {+ installPrincipalLinks({ canonical: (id) => (id === "slack-bob" ? "bob" : undefined), aliases: () => [] });+ t.after(() => installPrincipalLinks(null));+ const nightly = {+ id: "nightly",+ title: "Nightly report",+ owner: "alice",+ ownerScopeId: "personal:alice",+ schedule: { cron: "0 9 * * *", timezone: "UTC" },+ enabled: true,+ };+ const rows = [+ row({ day: MON, scopeId: "personal:alice", origin: "cron", cronId: "nightly", model: "m1", costUsd: 2 }),+ row({ day: TUE, scopeId: "personal:alice", origin: "cron", cronId: "nightly", model: "m2", costUsd: 3, calls: 2 }),+ row({ day: TUE, scopeId: "channel:C1", origin: "cron", cronId: "digest", costUsd: 4 }),+ row({ day: WED, scopeId: "personal:slack-bob", origin: "cron", cronId: "gone", costUsd: 1 }),+ row({ day: MON, scopeId: "personal:alice", origin: "cron", cronId: "moved", costUsd: 1 }),+ row({ day: TUE, scopeId: "channel:C1", origin: "cron", cronId: "moved", costUsd: 1 }),+ row({ day: WED, scopeId: "personal:bob", origin: "conversation", costUsd: 10 }),+ ];+ const infos = new Map([+ ["nightly", nightly],+ ["digest", { ...nightly, id: "digest", title: "Digest" }],+ ]);+ const report = summarize(rows, {+ cron: (id) => infos.get(id) ?? null,+ label: (id) => (id === "channel:C1" ? "#general" : ""),+ });+ assert.deepEqual(+ report.crons.map((c) => [c.cronId, c.scopeId, c.scopeName, c.info?.title ?? null, c.costUsd, c.calls]),+ [+ ["nightly", "personal:alice", "", "Nightly report", 5, 3],+ ["digest", "channel:C1", "#general", "Digest", 4, 1],+ ["moved", "personal:alice", "", null, 2, 2],+ ["gone", "personal:slack-bob", "", null, 1, 1],+ ],+ );+ assert.deepEqual(+ report.people.map((p) => [p.scopeId, p.costUsd]),+ [+ ["personal:bob", 11],+ ["personal:alice", 6],+ ],+ );+ assert.deepEqual(report.crons[0]!.info, nightly);+ assert.equal(+ report.crons.reduce((sum, c) => sum + c.costUsd, 0),+ report.org.background.sources.cron.costUsd,+ );+});++test("spendCsv: cron export names each cron by id, title, owner and spend scope, and de-fangs titles", () => {+ const rows = [+ row({ day: MON, scopeId: "personal:alice", origin: "cron", cronId: "c1", costUsd: 2, calls: 1 }),+ row({ day: MON, scopeId: "channel:C1", origin: "cron", cronId: "gone", costUsd: 1, calls: 1 }),+ ];+ const report = summarize(rows, {+ cron: (id) =>+ id === "c1"+ ? { id, title: "=HYPERLINK()", owner: "alice", ownerScopeId: "personal:alice", schedule: {}, enabled: true }+ : null,+ });+ const lines = spendCsv(report, "cron").trimEnd().split("\r\n");+ assert.equal(+ lines[0],+ "cron_id,title,owner,scope_id,live_usd,background_usd,cron_usd,loop_usd,swarm_usd,webhook_usd,monitor_usd,total_usd,calls,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,cache_hit_ratio",+ );+ assert.deepEqual(lines.slice(1), [+ "c1,'=HYPERLINK(),alice,personal:alice,0,2,2,0,0,0,0,2,1,0,0,0,0,",+ "gone,,,channel:C1,0,1,1,0,0,0,0,1,1,0,0,0,0,",+ ]);+});++test("spendExportRows keeps two crons in the same scope, day and model apart", () => {+ const rows = spendExportRows(+ [+ row({ day: MON, scopeId: "personal:alice", origin: "cron", cronId: "a", model: "m1", costUsd: 1 }),+ row({ day: MON, scopeId: "personal:alice", origin: "cron", cronId: "b", model: "m1", costUsd: 2 }),+ row({ day: MON, scopeId: "personal:alice", origin: "conversation", model: "m1", costUsd: 4 }),+ ],+ () => "",+ );+ assert.deepEqual(+ rows.map((r) => [r.source, r.cronId, r.costUsd]),+ [+ ["live", null, 4],+ ["cron", "a", 1],+ ["cron", "b", 2],+ ],+ );+});diff --git a/test/support/scope-rollup-oracle.ts b/test/support/scope-rollup-oracle.tsindex 9cc88c1d9..9b27c15aa 100644--- a/test/support/scope-rollup-oracle.ts+++ b/test/support/scope-rollup-oracle.ts@@ -1,5 +1,4 @@-import type { ScopeSessionRollup, SessionSummary } from "../../src/sessions/session-store.ts";-import { parseSessionWakeRef } from "../../src/api/routes/admin/origins.ts";+import { sessionCategory, type ScopeSessionRollup, type SessionSummary } from "../../src/sessions/session-store.ts";export function rollupsFromSummaries(summaries: SessionSummary[]): ScopeSessionRollup[] {const out = new Map<string, ScopeSessionRollup>();@@ -15,7 +14,7 @@ export function rollupsFromSummaries(summaries: SessionSummary[]): ScopeSessionR};out.set(s.scopeId, r);r.lastActivity = Math.max(r.lastActivity, s.lastActivity);- if (parseSessionWakeRef(s.threadRef)) {+ if (sessionCategory(s.origin) === "background") {r.backgroundSessions += 1;continue;}diff --git a/test/support/spend-rollup-parity.ts b/test/support/spend-rollup-parity.tsindex 35c308b0a..874a902ba 100644--- a/test/support/spend-rollup-parity.ts+++ b/test/support/spend-rollup-parity.ts@@ -57,7 +57,7 @@ export async function assertSpendRollupParity(const day = Math.floor(BASE / DAY);const rollup = (await store.spendRollup({ from: BASE, to: BASE + 2 * DAY })).filter((r) => mine.has(r.scopeId));- const key = (r: SpendRow) => JSON.stringify([r.day, r.scopeId, r.origin, r.model]);+ const key = (r: SpendRow) => JSON.stringify([r.day, r.scopeId, r.origin, r.cronId, r.model]);const byKey = (a: SpendRow, b: SpendRow) => {if (key(a) === key(b)) return 0;return key(a) < key(b) ? -1 : 1;@@ -71,6 +71,7 @@ export async function assertSpendRollupParity(scopeId: alice,model: "other-model",origin: "conversation",+ cronId: null,calls: 1,costUsd: 0.75,input: 100,@@ -83,6 +84,7 @@ export async function assertSpendRollupParity(scopeId: alice,model: "mock",origin: "conversation",+ cronId: null,calls: 2,costUsd: 1.75,input: 200,@@ -95,6 +97,7 @@ export async function assertSpendRollupParity(scopeId: alice,model: "mock",origin: "cron",+ cronId: `${prefix}-nightly`,calls: 1,costUsd: 0.5,input: 100,@@ -107,6 +110,7 @@ export async function assertSpendRollupParity(scopeId: channel,model: "mock",origin: "conversation",+ cronId: null,calls: 1,costUsd: 2,input: 100,@@ -119,6 +123,7 @@ export async function assertSpendRollupParity(scopeId: alice,model: "mock",origin: "conversation",+ cronId: null,calls: 1,costUsd: 0.125,input: 100,@@ -131,6 +136,7 @@ export async function assertSpendRollupParity(scopeId: bob,model: "mock",origin: "conversation",+ cronId: null,calls: 1,costUsd: 4,input: 100,@@ -149,8 +155,16 @@ export async function assertSpendRollupParity(await store.setParentSession(session.id, parentId);return session;};- for (const origin of ["cron", "webhook", "monitor", "conversation"] as const) {- const parent = await store.getOrCreateByThread(`agent:main:${origin}:${prefix}-parent`, "dm", bob);+ const parents = {+ cron: `agent:main:cron:${prefix}-parent`,+ webhook: `agent:main:webhook:${prefix}-parent`,+ monitor: `agent:main:monitor:${prefix}-parent`,+ loop: `loop:${prefix}-parent:fire:aaa`,+ swarm: `swarm:${prefix}-parent:member`,+ conversation: `agent:main:conversation:${prefix}-parent`,+ };+ for (const [origin, threadRef] of Object.entries(parents)) {+ const parent = await store.getOrCreateByThread(threadRef, "dm", bob);const first = await child(`${origin}-child`, parent.id);await child(`${origin}-grandchild`, first.id);}@@ -168,7 +182,7 @@ export async function assertSpendRollupParity(r.model?.startsWith(`${prefix}-`),);const origins = new Map<string, string>([- ...["cron", "webhook", "monitor", "conversation"].flatMap((origin) =>+ ...Object.keys(parents).flatMap((origin) =>["child", "grandchild"].map((kind) => [`${prefix}-${origin}-${kind}`, origin] as const),),...["missing-parent", "deleted-parent", "cycle-a", "cycle-b", "self-cycle"].map(@@ -178,6 +192,7 @@ export async function assertSpendRollupParity(assert.equal(inherited.length, origins.size);for (const row of inherited) {assert.equal(row.origin, origins.get(row.model!), row.model!);+ assert.equal(row.cronId, row.origin === "cron" ? `${prefix}-parent` : null, row.model!);assert.equal(row.scopeId, alice, "inherit origin, not the parent's scope");assert.equal(row.calls, 1);assert.equal(row.costUsd, 0.01);@@ -199,8 +214,10 @@ export async function assertSpendRollupParity(const cronParent = await store.getOrCreateByThread(`cron:${prefix}-changing:fire:aaa`, "dm", bob);await store.setParentSession(changing.id, cronParent.id);assert.equal((await readChanging())[0]!.origin, "cron");+ assert.equal((await readChanging())[0]!.cronId, `${prefix}-changing`);await store.deleteSession(cronParent.id);assert.equal((await readChanging())[0]!.origin, "conversation");+ assert.equal((await readChanging())[0]!.cronId, null);await store.deleteSession(changing.id);assert.deepEqual(await readChanging(), []);}