@tangle-network/agent-app 0.60.65 → 0.60.66
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/VaultPane-JUSNGOV7.js +7 -0
- package/dist/{chunk-RYUTKTOR.js → chunk-PPPX26BF.js} +33 -14
- package/dist/chunk-PPPX26BF.js.map +1 -0
- package/dist/{chunk-ST3ARHJH.js → chunk-RQSNTJTW.js} +5 -5
- package/dist/chunk-RQSNTJTW.js.map +1 -0
- package/dist/{chunk-7UB4K2R2.js → chunk-YGUSZDMW.js} +1 -1
- package/dist/chunk-YGUSZDMW.js.map +1 -0
- package/dist/launch-invariants/catalog.d.ts +5 -0
- package/dist/launch-invariants/cli.js +2 -2
- package/dist/launch-invariants/conformance.d.ts +3 -1
- package/dist/launch-invariants/index.js +1 -1
- package/dist/launch-invariants/testing.d.ts +12 -2
- package/dist/launch-invariants/testing.js +2 -2
- package/dist/vault/index.js +1 -1
- package/dist/vault/lazy.js +1 -1
- package/package.json +1 -1
- package/dist/VaultPane-XUAGL5SP.js +0 -7
- package/dist/chunk-7UB4K2R2.js.map +0 -1
- package/dist/chunk-RYUTKTOR.js.map +0 -1
- package/dist/chunk-ST3ARHJH.js.map +0 -1
- /package/dist/{VaultPane-XUAGL5SP.js.map → VaultPane-JUSNGOV7.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/launch-invariants/catalog.ts","../src/launch-invariants/schedule.ts","../src/launch-invariants/limit-alarms.ts"],"sourcesContent":["/**\n * The launch invariants every agent app holds, and the budgets they are held to.\n *\n * Each one is a failure GTM shipped to production on 2026-10-10 and fixed by\n * hand. They are listed here once so every app checks the same rule with the\n * same numbers, and `agent-app-invariants` reports each by its id.\n */\n\n/** Budgets the invariants are measured against. */\nexport const LAUNCH_BUDGETS = {\n /** Most bytes one query may return in a scheduled job or report route: one sized batch with room for its listing. */\n queryBytes: 8 * 1024 * 1024,\n /** Most the live heap may grow while one scheduled job runs on a day-sized fixture. */\n heapGrowthBytes: 40 * 1024 * 1024,\n /** Most bytes of a large column one sized read returns; a single larger row is read alone. */\n sizedReadBytes: 4 * 1024 * 1024,\n /** Most stored events one long turn may write. */\n turnEvents: 5_000,\n /** A turn whose owner stopped reaches its terminal state within this long. */\n settleWithinMs: 15 * 60_000,\n /** Turn recovery and orphan settlement run at least this often. */\n recoveryEveryMs: 15 * 60_000,\n /** Longest a cached auth lookup may be served while the store cannot answer. */\n authCacheTtlMs: 60_000,\n /** A platform-limit alarm fires at this share of the limit. */\n alarmRatio: 0.8,\n} as const\n\nexport type LaunchInvariantId =\n | 'bounded-reads'\n | 'memory-budget'\n | 'isolated-jobs'\n | 'honest-settlement'\n | 'coalesced-events'\n | 'auth-survives-d1-stall'\n | 'authorize-before-stream'\n | 'limit-alarms'\n\nexport interface LaunchInvariant {\n id: LaunchInvariantId\n title: string\n /** The rule, as the conformance report states it. */\n rule: string\n /** The production failure the rule answers. */\n incident: string\n}\n\nexport const LAUNCH_INVARIANTS: readonly LaunchInvariant[] = [\n {\n id: 'bounded-reads',\n title: 'Bounded reads',\n rule: 'No query in a scheduled job or report route returns more than 8 MB; large columns are read in sized batches of at most 4 MB.',\n incident: 'GTM turn health read 500 replies with their parts (122 MB of a 128 MB Worker); the reliability report scanned 1.63 M events and overloaded D1.',\n },\n {\n id: 'memory-budget',\n title: 'Memory budget',\n rule: 'Every scheduled job runs on a day-sized fixture with live-heap growth of at most 40 MB, and every scheduled job is covered.',\n incident: 'GTM sweeps exceeded the Worker\\'s 128 MB six times; a regex slice kept in a Map pinned whole tool outputs.',\n },\n {\n id: 'isolated-jobs',\n title: 'Isolated scheduled jobs',\n rule: 'Each scheduled invocation runs exactly one job, and turn recovery and orphan settlement run at least every 15 minutes.',\n incident: 'At 21:00Z turn health ran out of memory while the hourly sweeps shared one run, and none of the eight queued after it ran.',\n },\n {\n id: 'honest-settlement',\n title: 'Honest turn settlement',\n rule: 'Every turn reaches exactly one terminal state (an answer, a typed failure with Retry, or a Stop counted on its own) within 15 minutes of its owner stopping; failures are attributed to the request time, and a completed run with an aborted tool is a failure.',\n incident: 'Stale running rows (51 settled by hand), failure notices 8–11 h late, and completions with aborted tools counted as answers.',\n },\n {\n id: 'coalesced-events',\n title: 'Coalesced turn events',\n rule: 'A recorded long turn stores at most 5,000 events: text and reasoning deltas are merged before storage.',\n incident: 'A reasoning model wrote 59,659 events in one turn and 1.63 M in a day.',\n },\n {\n id: 'auth-survives-d1-stall',\n title: 'Auth survives a D1 stall',\n rule: 'A key or session verified within 60 s keeps working while D1 errors or stalls; the cache is used only then, never past revoke or expiry, and is keyed by SHA-256.',\n incident: 'An overloaded D1 failed sign-in and API-key checks for credentials that were valid moments before.',\n },\n {\n id: 'authorize-before-stream',\n title: 'Authorization before any stream',\n rule: 'A refused request gets a plain response; no stream opens and no product state is touched before authorization resolves.',\n incident: 'agent-app 0.60.48–0.60.49 opened a progress-first stream before authorize ran.',\n },\n {\n id: 'limit-alarms',\n title: 'Platform-limit alarms at 80%',\n rule: 'Worker memory, D1 rows per query, sandbox disk, snapshot count and key rate each have a declared limit and an alarm that fires at 80%.',\n incident: '19 platform-limit events on 2026-10-10, each found after it failed a customer.',\n },\n]\n\n/** The invariant ids in report order. */\nexport const LAUNCH_INVARIANT_IDS: readonly LaunchInvariantId[] = LAUNCH_INVARIANTS.map((invariant) => invariant.id)\n\n/** One checked outcome of one invariant, for one subject (a job, a route, a scenario). */\nexport interface InvariantVerdict {\n invariant: LaunchInvariantId\n /** What was checked: a job name, a route, a scenario. */\n subject: string\n pass: boolean\n /** Findings, one line each. On a pass, what was proven. */\n details: string[]\n /** Measurements behind the verdict, for the report. */\n data?: Record<string, unknown>\n /**\n * Set when the app recorded this failure as known, with why and who owns the\n * fix. The report counts it as not holding; it does not fail the suite.\n */\n knownFailing?: string\n}\n\n/** A verdict whose message names every finding, for a test runner's failure output. */\nexport function describeVerdict(verdict: InvariantVerdict): string {\n const head = `${verdict.pass ? 'PASS' : 'FAIL'} ${verdict.invariant} — ${verdict.subject}`\n return verdict.details.length ? `${head}\\n ${verdict.details.join('\\n ')}` : head\n}\n","/**\n * Scheduled jobs that cannot take each other down.\n *\n * On 2026-10-10 at 21:00Z GTM's turn health ran out of memory while the hourly\n * sweeps shared one scheduled run, and none of the eight queued after it ran.\n * Here each scheduled invocation runs exactly one job. A cron can carry a\n * minute list (`0,1,2 * * * *`) with one job per minute, so a Worker keeps a\n * few trigger expressions while every job gets its own invocation, its own\n * memory and its own failure.\n *\n * Cloudflare hands the handler the configured string verbatim as `event.cron`,\n * so dispatch is exact-string; a tick no entry handles is reported as\n * unhandled instead of silently running nothing. {@link checkIsolatedJobs}\n * holds the table against the deployment's configured crons.\n */\nimport { LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\n\n/** One cron expression and the job it runs, or one job per listed minute. */\nexport type ScheduleEntry =\n | { cron: string; job: string }\n | { cron: string; minutes: Readonly<Record<number, string>> }\n\n/** One scheduled invocation: the cron, the minute for a minute-list entry, and the job it runs. */\nexport interface ScheduleSlot {\n cron: string\n minute?: number\n job: string\n}\n\nexport interface ScheduledJobInput<Ctx> {\n cron: string\n scheduledTime: Date\n context: Ctx\n /** 1 for the first try. */\n attempt: number\n}\n\nexport type ScheduledJob<Ctx> = (input: ScheduledJobInput<Ctx>) => Promise<unknown>\n\nexport interface ScheduledDispatchOptions<Ctx> {\n entries: readonly ScheduleEntry[]\n jobs: Readonly<Record<string, ScheduledJob<Ctx>>>\n /** Waits before each retry of a failed job; empty (the default) runs a job once. Jobs that retry must be idempotent. */\n retryDelaysMs?: readonly number[]\n log?: {\n info(message: string, detail?: Record<string, unknown>): void\n error(message: string, detail?: Record<string, unknown>): void\n }\n /** Tests pass a no-op. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport interface ScheduledJobOutcome {\n job: string\n ok: boolean\n attempts: number\n durationMs: number\n error?: string\n}\n\nexport interface ScheduledDispatchResult {\n handled: boolean\n job: string | null\n /** Settles when the job's last attempt ends; never rejects. */\n done: Promise<ScheduledJobOutcome | null>\n}\n\nexport interface ScheduledDispatch<Ctx> {\n readonly entries: readonly ScheduleEntry[]\n /** Every invocation the table can make. */\n slots(): ScheduleSlot[]\n /** The job a tick runs, or null when no entry handles it. */\n jobFor(cron: string, scheduledTime: number | Date): string | null\n /**\n * Run the tick's one job. With `waitUntil` the job runs in the background and\n * this returns at once; without it, this waits for the job.\n */\n dispatch(\n event: { cron: string; scheduledTime: number | Date },\n context: Ctx,\n waitUntil?: (promise: Promise<unknown>) => void,\n ): Promise<ScheduledDispatchResult>\n}\n\nexport function createScheduledDispatch<Ctx>(options: ScheduledDispatchOptions<Ctx>): ScheduledDispatch<Ctx> {\n const problems = validateEntries(options.entries, Object.keys(options.jobs))\n if (problems.length) throw new Error(`scheduled dispatch: ${problems.join('; ')}`)\n const byCron = new Map(options.entries.map((entry) => [entry.cron, entry]))\n const retryDelaysMs = options.retryDelaysMs ?? []\n const log = options.log ?? {\n info: (message: string, detail?: Record<string, unknown>) => console.log(message, detail ?? ''),\n error: (message: string, detail?: Record<string, unknown>) => console.error(message, detail ?? ''),\n }\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n\n function jobFor(cron: string, scheduledTime: number | Date): string | null {\n const entry = byCron.get(cron)\n if (!entry) return null\n if ('job' in entry) return entry.job\n const minute = new Date(scheduledTime).getUTCMinutes()\n return entry.minutes[minute] ?? null\n }\n\n async function runJob(job: string, cron: string, scheduledTime: Date, context: Ctx): Promise<ScheduledJobOutcome> {\n const run = options.jobs[job]!\n const started = Date.now()\n let lastError = ''\n for (let attempt = 1; attempt <= retryDelaysMs.length + 1; attempt += 1) {\n try {\n await run({ cron, scheduledTime, context, attempt })\n return { job, ok: true, attempts: attempt, durationMs: Date.now() - started }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error)\n const delay = retryDelaysMs[attempt - 1]\n if (delay === undefined) break\n log.error(`[scheduled] ${job} failed; retrying`, { attempt, error: lastError })\n await sleep(delay)\n }\n }\n log.error(`[scheduled] ${job} failed`, { attempts: retryDelaysMs.length + 1, error: lastError })\n return { job, ok: false, attempts: retryDelaysMs.length + 1, durationMs: Date.now() - started, error: lastError }\n }\n\n return {\n entries: options.entries,\n slots: () => slotsOf(options.entries),\n jobFor,\n async dispatch(event, context, waitUntil) {\n const scheduledTime = new Date(event.scheduledTime)\n const job = jobFor(event.cron, scheduledTime)\n if (!job) {\n log.error(`[scheduled] no job handles cron \"${event.cron}\" at minute ${scheduledTime.getUTCMinutes()}; the configured crons and the schedule disagree`)\n return { handled: false, job: null, done: Promise.resolve(null) }\n }\n const done = runJob(job, event.cron, scheduledTime, context)\n if (waitUntil) waitUntil(done)\n else await done\n return { handled: true, job, done }\n },\n }\n}\n\n/** Every invocation a schedule table can make. */\nexport function slotsOf(entries: readonly ScheduleEntry[]): ScheduleSlot[] {\n return entries.flatMap((entry) => 'job' in entry\n ? [{ cron: entry.cron, job: entry.job }]\n : Object.entries(entry.minutes).map(([minute, job]) => ({ cron: entry.cron, minute: Number(minute), job })))\n}\n\nfunction validateEntries(entries: readonly ScheduleEntry[], jobNames: readonly string[]): string[] {\n const problems: string[] = []\n const known = new Set(jobNames)\n const seen = new Set<string>()\n for (const entry of entries) {\n if (seen.has(entry.cron)) problems.push(`cron \"${entry.cron}\" is listed twice`)\n seen.add(entry.cron)\n const fields = entry.cron.trim().split(/\\s+/)\n if (fields.length !== 5) problems.push(`cron \"${entry.cron}\" does not have five fields`)\n for (const slot of slotsOf([entry])) {\n if (!known.has(slot.job)) problems.push(`cron \"${entry.cron}\" names job \"${slot.job}\", which is not defined`)\n }\n if ('minutes' in entry) {\n const listed = minuteList(fields[0] ?? '')\n const mapped = Object.keys(entry.minutes).map(Number).sort((a, b) => a - b)\n if (!listed) problems.push(`cron \"${entry.cron}\" maps jobs by minute, so its minute field must be a list of minutes`)\n else if (listed.join(',') !== mapped.join(',')) {\n problems.push(`cron \"${entry.cron}\" lists minutes ${listed.join(',')} but maps jobs to ${mapped.join(',')}`)\n }\n }\n }\n return problems\n}\n\n/** The minutes of a plain minute list (`5` or `0,15,30`), or null for any other form. */\nfunction minuteList(field: string): number[] | null {\n if (!/^\\d{1,2}(,\\d{1,2})*$/.test(field)) return null\n const minutes = field.split(',').map(Number)\n if (minutes.some((minute) => minute > 59)) return null\n return [...new Set(minutes)].sort((a, b) => a - b)\n}\n\n// ── cron analysis ────────────────────────────────────────────────────────────\n\nfunction expandField(field: string, min: number, max: number): Set<number> | null {\n const values = new Set<number>()\n for (const part of field.split(',')) {\n const match = /^(\\*|\\d+(?:-\\d+)?)(?:\\/(\\d+))?$/.exec(part)\n if (!match) return null\n const [, range, stepText] = match\n const step = stepText ? Number(stepText) : 1\n if (!(step >= 1)) return null\n let lo = min\n let hi = max\n if (range !== '*') {\n const [a, b] = range!.split('-').map(Number)\n lo = a!\n hi = b ?? (stepText ? max : a!)\n }\n if (lo < min || hi > max || lo > hi) return null\n for (let value = lo; value <= hi; value += step) values.add(value)\n }\n return values\n}\n\n/**\n * The minutes of the day (0–1439, UTC) a cron fires, or null when it does not\n * fire every day (a day-of-month, month or weekday restriction) or cannot be read.\n */\nexport function cronDailyFirings(cron: string): Set<number> | null {\n const fields = cron.trim().split(/\\s+/)\n if (fields.length !== 5) return null\n const [minuteField, hourField, dayField, monthField, weekdayField] = fields as [string, string, string, string, string]\n if (dayField !== '*' || monthField !== '*' || (weekdayField !== '*' && weekdayField !== '?')) return null\n const minutes = expandField(minuteField, 0, 59)\n const hours = expandField(hourField, 0, 23)\n if (!minutes || !hours) return null\n const firings = new Set<number>()\n for (const hour of hours) for (const minute of minutes) firings.add(hour * 60 + minute)\n return firings\n}\n\n/** The longest wait, in minutes, between consecutive firings over a day, or null when they do not fire daily. */\nexport function longestGapMinutes(firings: Iterable<number>): number | null {\n const sorted = [...new Set(firings)].sort((a, b) => a - b)\n if (sorted.length === 0) return null\n let gap = sorted[0]! + 1440 - sorted[sorted.length - 1]!\n for (let index = 1; index < sorted.length; index += 1) gap = Math.max(gap, sorted[index]! - sorted[index - 1]!)\n return gap\n}\n\n/** The cron expressions a wrangler config declares, top level and per environment. */\nexport interface WranglerCrons {\n top: string[]\n envs: Record<string, string[]>\n}\n\n/** Read `[triggers] crons` (and `[env.<name>.triggers]`) from wrangler.toml, or `triggers.crons` from wrangler.json(c). */\nexport function parseWranglerCrons(source: string, format: 'toml' | 'json'): WranglerCrons {\n return format === 'json' ? parseJsonCrons(source) : parseTomlCrons(source)\n}\n\nfunction parseTomlCrons(source: string): WranglerCrons {\n const result: WranglerCrons = { top: [], envs: {} }\n let table = ''\n let collecting: string[] | null = null\n let buffer = ''\n for (const raw of source.split('\\n')) {\n const line = stripTomlComment(raw)\n if (collecting) {\n buffer += ` ${line}`\n if (line.includes(']')) {\n collecting.push(...quoted(buffer))\n collecting = null\n buffer = ''\n }\n continue\n }\n const header = /^\\s*\\[([^\\[\\]]+)\\]\\s*$/.exec(line)\n if (header) {\n table = header[1]!.trim()\n continue\n }\n const assignment = /^\\s*crons\\s*=\\s*(.*)$/.exec(line)\n if (!assignment) continue\n const envName = /^env\\.([^.]+)\\.triggers$/.exec(table)?.[1]\n const target = table === 'triggers' ? result.top : envName ? (result.envs[envName] ??= []) : null\n if (!target) continue\n const rest = assignment[1]!\n if (rest.includes(']')) target.push(...quoted(rest))\n else {\n collecting = target\n buffer = rest\n }\n }\n return result\n}\n\nfunction stripTomlComment(line: string): string {\n let quote: string | null = null\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index]!\n if (quote) {\n if (char === quote) quote = null\n } else if (char === '\"' || char === \"'\") quote = char\n else if (char === '#') return line.slice(0, index)\n }\n return line\n}\n\nfunction quoted(text: string): string[] {\n return [...text.matchAll(/\"([^\"]*)\"|'([^']*)'/g)].map((match) => match[1] ?? match[2] ?? '')\n}\n\nfunction parseJsonCrons(source: string): WranglerCrons {\n const config = JSON.parse(stripJsonComments(source)) as {\n triggers?: { crons?: string[] }\n env?: Record<string, { triggers?: { crons?: string[] } }>\n }\n return {\n top: [...(config.triggers?.crons ?? [])],\n envs: Object.fromEntries(Object.entries(config.env ?? {})\n .filter(([, env]) => Array.isArray(env.triggers?.crons))\n .map(([name, env]) => [name, [...env.triggers!.crons!]])),\n }\n}\n\nfunction stripJsonComments(source: string): string {\n let out = ''\n let inString = false\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index]!\n const next = source[index + 1]\n if (inString) {\n out += char\n if (char === '\\\\') out += source[++index] ?? ''\n else if (char === '\"') inString = false\n continue\n }\n if (char === '\"') {\n inString = true\n out += char\n } else if (char === '/' && next === '/') {\n while (index < source.length && source[index] !== '\\n') index += 1\n out += '\\n'\n } else if (char === '/' && next === '*') {\n index += 2\n while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) index += 1\n index += 1\n } else out += char\n }\n return out.replace(/,(\\s*[}\\]])/g, '$1')\n}\n\n// ── the invariant ────────────────────────────────────────────────────────────\n\n/** What one scheduled invocation was observed to run. */\nexport interface ObservedSlot {\n cron: string\n minute?: number\n /** The jobs the invocation ran; exactly one passes. */\n jobs: readonly string[]\n}\n\nexport interface IsolatedJobsInput {\n /** Every cron the deployment configures, from each wrangler environment. */\n configuredCrons: readonly string[]\n /** What each invocation runs: from {@link slotsOf} for a {@link createScheduledDispatch} table, or observed by driving the app's own handler. */\n slots: readonly ObservedSlot[]\n /** Jobs that recover and settle turns; each must run at least every 15 minutes. */\n recoveryJobs: readonly string[]\n /** Default {@link LAUNCH_BUDGETS.recoveryEveryMs}. */\n everyMs?: number\n}\n\n/** One job per invocation, the table and the deployment agree, and recovery runs at least every 15 minutes. */\nexport function checkIsolatedJobs(input: IsolatedJobsInput): InvariantVerdict {\n const everyMinutes = (input.everyMs ?? LAUNCH_BUDGETS.recoveryEveryMs) / 60_000\n const findings: string[] = []\n const configured = new Set(input.configuredCrons)\n const dispatched = new Set(input.slots.map((slot) => slot.cron))\n for (const cron of configured) if (!dispatched.has(cron)) findings.push(`configured cron \"${cron}\" runs no job: no schedule entry matches it`)\n for (const cron of dispatched) if (!configured.has(cron)) findings.push(`schedule cron \"${cron}\" is not configured, so it never runs`)\n for (const slot of input.slots) {\n const where = `cron \"${slot.cron}\"${slot.minute !== undefined ? ` at minute ${slot.minute}` : ''}`\n if (slot.jobs.length !== 1) findings.push(`${where} runs ${slot.jobs.length} jobs in one invocation (${slot.jobs.join(', ') || 'none'}); one failure ends the rest`)\n }\n const byCron = new Map<string, ObservedSlot[]>()\n for (const slot of input.slots) byCron.set(slot.cron, [...(byCron.get(slot.cron) ?? []), slot])\n for (const [cron, slots] of byCron) {\n const minuteSlots = slots.filter((slot) => slot.minute !== undefined)\n if (minuteSlots.length === 0) continue\n const listed = minuteList(cron.trim().split(/\\s+/)[0] ?? '')\n const mapped = [...new Set(minuteSlots.map((slot) => slot.minute!))].sort((a, b) => a - b)\n if (!listed || listed.join(',') !== mapped.join(',')) {\n findings.push(`cron \"${cron}\" fires at minutes ${listed?.join(',') ?? '(not a minute list)'} but jobs are mapped to ${mapped.join(',')}`)\n }\n }\n if (input.recoveryJobs.length === 0) findings.push('no turn recovery or orphan settlement job is declared')\n const gaps: Record<string, number | null> = {}\n for (const job of input.recoveryJobs) {\n const firings = new Set<number>()\n let daily = false\n for (const slot of input.slots) {\n if (slot.jobs.length !== 1 || slot.jobs[0] !== job) continue\n const fires = cronDailyFirings(slot.cron)\n if (!fires) continue\n daily = true\n for (const minuteOfDay of fires) if (slot.minute === undefined || minuteOfDay % 60 === slot.minute) firings.add(minuteOfDay)\n }\n const gap = daily ? longestGapMinutes(firings) : null\n gaps[job] = gap\n if (gap === null) findings.push(`recovery job \"${job}\" is not scheduled to run every day on its own`)\n else if (gap > everyMinutes) findings.push(`recovery job \"${job}\" can wait ${gap} minutes between runs; the most is ${everyMinutes}`)\n }\n return {\n invariant: 'isolated-jobs',\n subject: 'schedule',\n pass: findings.length === 0,\n details: findings.length ? findings : [\n `${input.slots.length} scheduled invocations, one job each, across ${configured.size} configured crons`,\n ...input.recoveryJobs.map((job) => `${job} runs at least every ${gaps[job]} minutes`),\n ],\n data: { configuredCrons: [...configured], slots: input.slots.length, recoveryGapsMinutes: gaps },\n }\n}\n","/**\n * Alarms that fire at 80% of a platform limit, before the limit fails a customer.\n *\n * On 2026-10-10 GTM recorded 19 platform-limit events (Worker memory, D1,\n * sandbox disk, snapshot count, key rate) and learned of each one after it had\n * failed someone. Each resource here has a declared limit; an observation at\n * or above 80% of it delivers a warning, and at or above the limit a critical\n * alert, through the same {@link AlertSink} the turn-health sweep uses (wrap it\n * in `createThrottledAlertSink` so a hot loop pages once).\n *\n * Where each observation comes from:\n * - `d1-rows-per-query`: {@link withD1LimitAlarms} reads `meta.rows_read` on every query.\n * - `worker-memory`: workerd exposes no heap reading, so the D1 wrapper observes\n * the bytes each response returns (the reads that overran memory today), and a\n * tail consumer reports an `exceededMemory` outcome at the full limit.\n * - `sandbox-disk` and `snapshot-count`: the Sandbox SDK's box usage and snapshot list, read on a schedule.\n * - `key-rate`: the per-key request counter the operator API keeps.\n */\nimport type { AlertSink, TurnHealthAlert } from '../turn-health/sink.js'\nimport { LAUNCH_BUDGETS } from './catalog.js'\n\nexport type LimitResource = 'worker-memory' | 'd1-rows-per-query' | 'sandbox-disk' | 'snapshot-count' | 'key-rate'\n\nexport const LIMIT_RESOURCES: readonly LimitResource[] = [\n 'worker-memory',\n 'd1-rows-per-query',\n 'sandbox-disk',\n 'snapshot-count',\n 'key-rate',\n]\n\n/** The limit of each resource, in its own unit: bytes, rows, bytes, snapshots, requests per minute. */\nexport type LimitBudgets = Readonly<Record<LimitResource, number>>\n\nconst UNITS: Readonly<Record<LimitResource, string>> = {\n 'worker-memory': 'bytes',\n 'd1-rows-per-query': 'rows',\n 'sandbox-disk': 'bytes',\n 'snapshot-count': 'snapshots',\n 'key-rate': 'requests/min',\n}\n\nexport type LimitLevel = 'ok' | 'warning' | 'critical'\n\nexport interface LimitObservation {\n resource: LimitResource\n used: number\n limit: number\n /** used / limit. */\n share: number\n level: LimitLevel\n}\n\nexport interface LimitAlarms {\n readonly budgets: LimitBudgets\n /** Record one reading; a warning or critical reading is delivered before this resolves. */\n observe(resource: LimitResource, used: number, context?: { subject?: string; detail?: string }): Promise<LimitObservation>\n}\n\nexport interface LimitAlarmOptions {\n product: string\n budgets: LimitBudgets\n sink: AlertSink\n /** Default {@link LAUNCH_BUDGETS.alarmRatio}; a product cannot raise it past the limit itself. */\n ratio?: number\n now?: () => number\n}\n\nexport function createLimitAlarms(options: LimitAlarmOptions): LimitAlarms {\n const ratio = Math.min(options.ratio ?? LAUNCH_BUDGETS.alarmRatio, 1)\n const now = options.now ?? (() => Date.now())\n for (const resource of LIMIT_RESOURCES) {\n const limit = options.budgets[resource]\n if (!(typeof limit === 'number' && limit > 0 && Number.isFinite(limit))) {\n throw new Error(`limit alarms: ${resource} needs a positive limit`)\n }\n }\n return {\n budgets: options.budgets,\n async observe(resource, used, context) {\n const limit = options.budgets[resource]\n const share = used / limit\n const level: LimitLevel = share >= 1 ? 'critical' : share >= ratio ? 'warning' : 'ok'\n const observation = { resource, used, limit, share, level }\n if (level === 'ok') return observation\n const alert: TurnHealthAlert = {\n product: options.product,\n severity: level,\n // Keyed by product and resource only, so a throttled sink pages once per resource.\n key: `limit:${options.product}:${resource}`,\n title: `${options.product}: ${resource} at ${Math.round(share * 100)}% of its limit`,\n details: [\n `${formatAmount(used, resource)} of ${formatAmount(limit, resource)} ${UNITS[resource]}`,\n ...(context?.subject ? [`in ${context.subject}`] : []),\n ...(context?.detail ? [context.detail] : []),\n ],\n data: { resource, used, limit, share, ...(context?.subject ? { subject: context.subject } : {}) },\n at: now(),\n }\n await options.sink.deliver(alert)\n return observation\n },\n }\n}\n\nfunction formatAmount(value: number, resource: LimitResource): string {\n if (UNITS[resource] === 'bytes') return `${(value / (1024 * 1024)).toFixed(1)} MB`\n return Math.round(value).toLocaleString('en-US')\n}\n\n/** The D1 surface the wrapper measures; Cloudflare `D1Database` satisfies it. */\ninterface D1Measurable {\n prepare(sql: string): unknown\n}\n\n/**\n * The D1 binding with each query's rows read and response size observed.\n * Rows read come from `meta.rows_read` (the rows D1 scanned, not only those\n * returned). The response size is estimated from three sampled rows, so the\n * wrapper never serializes a whole response: that copy would double the memory\n * of the very read it watches.\n */\nexport function withD1LimitAlarms<D extends D1Measurable>(d1: D, alarms: LimitAlarms, options: { subject?: string } = {}): D {\n const observe = (sql: string, result: unknown) => {\n const meta = (result as { meta?: { rows_read?: unknown } } | null)?.meta\n const rowsRead = typeof meta?.rows_read === 'number' ? meta.rows_read : rowsOf(result)\n const pending: Promise<unknown>[] = []\n if (rowsRead !== null) pending.push(alarms.observe('d1-rows-per-query', rowsRead, { subject: options.subject, detail: sql }))\n const results = (result as { results?: unknown[] } | null)?.results ?? (Array.isArray(result) ? result : null)\n if (results && results.length > 0) {\n pending.push(alarms.observe('worker-memory', estimatedBytes(results), { subject: options.subject, detail: `one response: ${sql}` }))\n }\n // An alarm delivery failure must not fail the query that triggered it.\n return Promise.all(pending).catch(() => undefined)\n }\n // D1's batch() takes only its own statements, so a batch is given the unwrapped ones.\n const unwrapped = new WeakMap<object, object>()\n const statement = (target: object, sql: string): object => {\n const wrapped = new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object, sql)\n if (key === 'all' || key === 'raw' || key === 'run' || key === 'first') {\n return async (...args: unknown[]) => {\n const result: unknown = await value.apply(stmt, args)\n if (key !== 'first') await observe(sql, result)\n return result\n }\n }\n return value.bind(stmt)\n },\n })\n unwrapped.set(wrapped, target)\n return wrapped\n }\n return new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') {\n return (sql: string) => statement((value as (sql: string) => object).call(binding, sql), sql.replace(/\\s+/g, ' ').slice(0, 160))\n }\n if (key === 'batch' && typeof value === 'function') {\n return async (statements: object[]) => {\n const results = await (value as (s: object[]) => Promise<unknown[]>).call(binding, statements.map((stmt) => unwrapped.get(stmt) ?? stmt))\n for (const result of results ?? []) await observe('batch', result)\n return results\n }\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n}\n\n/** The serialized size of a result set, from its first, middle and last rows. */\nexport function estimatedBytes(results: readonly unknown[]): number {\n const picks = [...new Set([0, Math.floor(results.length / 2), results.length - 1])]\n const sampled = picks.reduce((sum, index) => sum + (JSON.stringify(results[index]) ?? '').length, 0)\n return Math.round((sampled / picks.length) * results.length)\n}\n\nfunction rowsOf(result: unknown): number | null {\n if (Array.isArray(result)) return result.length\n const results = (result as { results?: unknown } | null)?.results\n return Array.isArray(results) ? results.length : null\n}\n"],"mappings":";AASO,IAAM,iBAAiB;AAAA;AAAA,EAE5B,YAAY,IAAI,OAAO;AAAA;AAAA,EAEvB,iBAAiB,KAAK,OAAO;AAAA;AAAA,EAE7B,gBAAgB,IAAI,OAAO;AAAA;AAAA,EAE3B,YAAY;AAAA;AAAA,EAEZ,gBAAgB,KAAK;AAAA;AAAA,EAErB,iBAAiB,KAAK;AAAA;AAAA,EAEtB,gBAAgB;AAAA;AAAA,EAEhB,YAAY;AACd;AAqBO,IAAM,oBAAgD;AAAA,EAC3D;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAA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AU,MAAM,SAAU,QAAQ,MAAM;AAC7D;AAEA,SAAS,OAAO,QAAgC;AAC9C,MAAI,MAAM,QAAQ,MAAM,EAAG,QAAO,OAAO;AACzC,QAAM,UAAW,QAAyC;AAC1D,SAAO,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;AACnD;","names":[]}
|
|
@@ -46,6 +46,11 @@ export interface InvariantVerdict {
|
|
|
46
46
|
details: string[];
|
|
47
47
|
/** Measurements behind the verdict, for the report. */
|
|
48
48
|
data?: Record<string, unknown>;
|
|
49
|
+
/**
|
|
50
|
+
* Set when the app recorded this failure as known, with why and who owns the
|
|
51
|
+
* fix. The report counts it as not holding; it does not fail the suite.
|
|
52
|
+
*/
|
|
53
|
+
knownFailing?: string;
|
|
49
54
|
}
|
|
50
55
|
/** A verdict whose message names every finding, for a test runner's failure output. */
|
|
51
56
|
export declare function describeVerdict(verdict: InvariantVerdict): string;
|
|
@@ -5,8 +5,8 @@ import {
|
|
|
5
5
|
formatConformanceReport,
|
|
6
6
|
readDeploymentFacts,
|
|
7
7
|
readVerdicts
|
|
8
|
-
} from "../chunk-
|
|
9
|
-
import "../chunk-
|
|
8
|
+
} from "../chunk-PPPX26BF.js";
|
|
9
|
+
import "../chunk-YGUSZDMW.js";
|
|
10
10
|
import {
|
|
11
11
|
invokedAsScript
|
|
12
12
|
} from "../chunk-C3CAYGGQ.js";
|
|
@@ -16,7 +16,7 @@ export interface DeploymentFacts {
|
|
|
16
16
|
configuredCrons: string[];
|
|
17
17
|
hasD1: boolean;
|
|
18
18
|
}
|
|
19
|
-
export type InvariantStatus = 'pass' | 'fail' | 'not-applicable';
|
|
19
|
+
export type InvariantStatus = 'pass' | 'fail' | 'known-fail' | 'not-applicable';
|
|
20
20
|
export interface InvariantReport {
|
|
21
21
|
id: LaunchInvariantId;
|
|
22
22
|
title: string;
|
|
@@ -31,6 +31,8 @@ export interface ConformanceReport {
|
|
|
31
31
|
passed: number;
|
|
32
32
|
total: number;
|
|
33
33
|
testExitCode: number | null;
|
|
34
|
+
/** Invariants failing with a known-failing marker: not holding, but not failing the run. */
|
|
35
|
+
knownFailing: number;
|
|
34
36
|
invariants: InvariantReport[];
|
|
35
37
|
facts: DeploymentFacts;
|
|
36
38
|
}
|
|
@@ -4,13 +4,23 @@ import { type LimitAlarms } from './limit-alarms.js';
|
|
|
4
4
|
export { describeVerdict } from './catalog.js';
|
|
5
5
|
/** Set by `agent-app-invariants` to the file it reads verdicts from. */
|
|
6
6
|
export declare const INVARIANT_RESULTS_ENV = "AGENT_APP_INVARIANTS_RESULTS";
|
|
7
|
+
export interface RecordInvariantOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The app knows this check fails today: why, who owns the fix and the next
|
|
10
|
+
* check. The failure is recorded (the report counts the invariant as not
|
|
11
|
+
* holding) without failing the suite, so an app adopts the kit before every
|
|
12
|
+
* invariant holds. Once the check passes, this fails the caller until the
|
|
13
|
+
* marker is removed, so a fixed invariant cannot regress silently.
|
|
14
|
+
*/
|
|
15
|
+
knownFailing?: string;
|
|
16
|
+
}
|
|
7
17
|
/**
|
|
8
18
|
* Record a verdict for the conformance report and fail the caller when it did
|
|
9
19
|
* not pass. Returns the verdict on a pass.
|
|
10
20
|
*/
|
|
11
|
-
export declare function recordInvariant(verdict: InvariantVerdict): InvariantVerdict;
|
|
21
|
+
export declare function recordInvariant(verdict: InvariantVerdict, options?: RecordInvariantOptions): InvariantVerdict;
|
|
12
22
|
/** Record several verdicts; fails after recording all of them. */
|
|
13
|
-
export declare function recordInvariants(verdicts: readonly InvariantVerdict[]): InvariantVerdict[];
|
|
23
|
+
export declare function recordInvariants(verdicts: readonly InvariantVerdict[], options?: RecordInvariantOptions): InvariantVerdict[];
|
|
14
24
|
/** Run a full garbage collection, so a heap reading counts only live objects. */
|
|
15
25
|
export declare function forceGc(): void;
|
|
16
26
|
/** What a measured binding saw while one job ran. */
|
|
@@ -17,10 +17,10 @@ import {
|
|
|
17
17
|
recordInvariants,
|
|
18
18
|
recordedLongTurn,
|
|
19
19
|
stallingD1
|
|
20
|
-
} from "../chunk-
|
|
20
|
+
} from "../chunk-PPPX26BF.js";
|
|
21
21
|
import {
|
|
22
22
|
describeVerdict
|
|
23
|
-
} from "../chunk-
|
|
23
|
+
} from "../chunk-YGUSZDMW.js";
|
|
24
24
|
export {
|
|
25
25
|
INVARIANT_RESULTS_ENV,
|
|
26
26
|
PLATFORM_LIMITS,
|
package/dist/vault/index.js
CHANGED
package/dist/vault/lazy.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/vault/lazy.tsx
|
|
2
2
|
import { lazy } from "react";
|
|
3
3
|
var VaultPaneLazy = lazy(
|
|
4
|
-
() => import("../VaultPane-
|
|
4
|
+
() => import("../VaultPane-JUSNGOV7.js").then((m) => ({ default: m.VaultPane }))
|
|
5
5
|
);
|
|
6
6
|
export {
|
|
7
7
|
VaultPaneLazy
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/launch-invariants/catalog.ts","../src/launch-invariants/schedule.ts","../src/launch-invariants/limit-alarms.ts"],"sourcesContent":["/**\n * The launch invariants every agent app holds, and the budgets they are held to.\n *\n * Each one is a failure GTM shipped to production on 2026-10-10 and fixed by\n * hand. They are listed here once so every app checks the same rule with the\n * same numbers, and `agent-app-invariants` reports each by its id.\n */\n\n/** Budgets the invariants are measured against. */\nexport const LAUNCH_BUDGETS = {\n /** Most bytes one query may return in a scheduled job or report route: one sized batch with room for its listing. */\n queryBytes: 8 * 1024 * 1024,\n /** Most the live heap may grow while one scheduled job runs on a day-sized fixture. */\n heapGrowthBytes: 40 * 1024 * 1024,\n /** Most bytes of a large column one sized read returns; a single larger row is read alone. */\n sizedReadBytes: 4 * 1024 * 1024,\n /** Most stored events one long turn may write. */\n turnEvents: 5_000,\n /** A turn whose owner stopped reaches its terminal state within this long. */\n settleWithinMs: 15 * 60_000,\n /** Turn recovery and orphan settlement run at least this often. */\n recoveryEveryMs: 15 * 60_000,\n /** Longest a cached auth lookup may be served while the store cannot answer. */\n authCacheTtlMs: 60_000,\n /** A platform-limit alarm fires at this share of the limit. */\n alarmRatio: 0.8,\n} as const\n\nexport type LaunchInvariantId =\n | 'bounded-reads'\n | 'memory-budget'\n | 'isolated-jobs'\n | 'honest-settlement'\n | 'coalesced-events'\n | 'auth-survives-d1-stall'\n | 'authorize-before-stream'\n | 'limit-alarms'\n\nexport interface LaunchInvariant {\n id: LaunchInvariantId\n title: string\n /** The rule, as the conformance report states it. */\n rule: string\n /** The production failure the rule answers. */\n incident: string\n}\n\nexport const LAUNCH_INVARIANTS: readonly LaunchInvariant[] = [\n {\n id: 'bounded-reads',\n title: 'Bounded reads',\n rule: 'No query in a scheduled job or report route returns more than 8 MB; large columns are read in sized batches of at most 4 MB.',\n incident: 'GTM turn health read 500 replies with their parts (122 MB of a 128 MB Worker); the reliability report scanned 1.63 M events and overloaded D1.',\n },\n {\n id: 'memory-budget',\n title: 'Memory budget',\n rule: 'Every scheduled job runs on a day-sized fixture with live-heap growth of at most 40 MB, and every scheduled job is covered.',\n incident: 'GTM sweeps exceeded the Worker\\'s 128 MB six times; a regex slice kept in a Map pinned whole tool outputs.',\n },\n {\n id: 'isolated-jobs',\n title: 'Isolated scheduled jobs',\n rule: 'Each scheduled invocation runs exactly one job, and turn recovery and orphan settlement run at least every 15 minutes.',\n incident: 'At 21:00Z turn health ran out of memory while the hourly sweeps shared one run, and none of the eight queued after it ran.',\n },\n {\n id: 'honest-settlement',\n title: 'Honest turn settlement',\n rule: 'Every turn reaches exactly one terminal state (an answer, a typed failure with Retry, or a Stop counted on its own) within 15 minutes of its owner stopping; failures are attributed to the request time, and a completed run with an aborted tool is a failure.',\n incident: 'Stale running rows (51 settled by hand), failure notices 8–11 h late, and completions with aborted tools counted as answers.',\n },\n {\n id: 'coalesced-events',\n title: 'Coalesced turn events',\n rule: 'A recorded long turn stores at most 5,000 events: text and reasoning deltas are merged before storage.',\n incident: 'A reasoning model wrote 59,659 events in one turn and 1.63 M in a day.',\n },\n {\n id: 'auth-survives-d1-stall',\n title: 'Auth survives a D1 stall',\n rule: 'A key or session verified within 60 s keeps working while D1 errors or stalls; the cache is used only then, never past revoke or expiry, and is keyed by SHA-256.',\n incident: 'An overloaded D1 failed sign-in and API-key checks for credentials that were valid moments before.',\n },\n {\n id: 'authorize-before-stream',\n title: 'Authorization before any stream',\n rule: 'A refused request gets a plain response; no stream opens and no product state is touched before authorization resolves.',\n incident: 'agent-app 0.60.48–0.60.49 opened a progress-first stream before authorize ran.',\n },\n {\n id: 'limit-alarms',\n title: 'Platform-limit alarms at 80%',\n rule: 'Worker memory, D1 rows per query, sandbox disk, snapshot count and key rate each have a declared limit and an alarm that fires at 80%.',\n incident: '19 platform-limit events on 2026-10-10, each found after it failed a customer.',\n },\n]\n\n/** The invariant ids in report order. */\nexport const LAUNCH_INVARIANT_IDS: readonly LaunchInvariantId[] = LAUNCH_INVARIANTS.map((invariant) => invariant.id)\n\n/** One checked outcome of one invariant, for one subject (a job, a route, a scenario). */\nexport interface InvariantVerdict {\n invariant: LaunchInvariantId\n /** What was checked: a job name, a route, a scenario. */\n subject: string\n pass: boolean\n /** Findings, one line each. On a pass, what was proven. */\n details: string[]\n /** Measurements behind the verdict, for the report. */\n data?: Record<string, unknown>\n}\n\n/** A verdict whose message names every finding, for a test runner's failure output. */\nexport function describeVerdict(verdict: InvariantVerdict): string {\n const head = `${verdict.pass ? 'PASS' : 'FAIL'} ${verdict.invariant} — ${verdict.subject}`\n return verdict.details.length ? `${head}\\n ${verdict.details.join('\\n ')}` : head\n}\n","/**\n * Scheduled jobs that cannot take each other down.\n *\n * On 2026-10-10 at 21:00Z GTM's turn health ran out of memory while the hourly\n * sweeps shared one scheduled run, and none of the eight queued after it ran.\n * Here each scheduled invocation runs exactly one job. A cron can carry a\n * minute list (`0,1,2 * * * *`) with one job per minute, so a Worker keeps a\n * few trigger expressions while every job gets its own invocation, its own\n * memory and its own failure.\n *\n * Cloudflare hands the handler the configured string verbatim as `event.cron`,\n * so dispatch is exact-string; a tick no entry handles is reported as\n * unhandled instead of silently running nothing. {@link checkIsolatedJobs}\n * holds the table against the deployment's configured crons.\n */\nimport { LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\n\n/** One cron expression and the job it runs, or one job per listed minute. */\nexport type ScheduleEntry =\n | { cron: string; job: string }\n | { cron: string; minutes: Readonly<Record<number, string>> }\n\n/** One scheduled invocation: the cron, the minute for a minute-list entry, and the job it runs. */\nexport interface ScheduleSlot {\n cron: string\n minute?: number\n job: string\n}\n\nexport interface ScheduledJobInput<Ctx> {\n cron: string\n scheduledTime: Date\n context: Ctx\n /** 1 for the first try. */\n attempt: number\n}\n\nexport type ScheduledJob<Ctx> = (input: ScheduledJobInput<Ctx>) => Promise<unknown>\n\nexport interface ScheduledDispatchOptions<Ctx> {\n entries: readonly ScheduleEntry[]\n jobs: Readonly<Record<string, ScheduledJob<Ctx>>>\n /** Waits before each retry of a failed job; empty (the default) runs a job once. Jobs that retry must be idempotent. */\n retryDelaysMs?: readonly number[]\n log?: {\n info(message: string, detail?: Record<string, unknown>): void\n error(message: string, detail?: Record<string, unknown>): void\n }\n /** Tests pass a no-op. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport interface ScheduledJobOutcome {\n job: string\n ok: boolean\n attempts: number\n durationMs: number\n error?: string\n}\n\nexport interface ScheduledDispatchResult {\n handled: boolean\n job: string | null\n /** Settles when the job's last attempt ends; never rejects. */\n done: Promise<ScheduledJobOutcome | null>\n}\n\nexport interface ScheduledDispatch<Ctx> {\n readonly entries: readonly ScheduleEntry[]\n /** Every invocation the table can make. */\n slots(): ScheduleSlot[]\n /** The job a tick runs, or null when no entry handles it. */\n jobFor(cron: string, scheduledTime: number | Date): string | null\n /**\n * Run the tick's one job. With `waitUntil` the job runs in the background and\n * this returns at once; without it, this waits for the job.\n */\n dispatch(\n event: { cron: string; scheduledTime: number | Date },\n context: Ctx,\n waitUntil?: (promise: Promise<unknown>) => void,\n ): Promise<ScheduledDispatchResult>\n}\n\nexport function createScheduledDispatch<Ctx>(options: ScheduledDispatchOptions<Ctx>): ScheduledDispatch<Ctx> {\n const problems = validateEntries(options.entries, Object.keys(options.jobs))\n if (problems.length) throw new Error(`scheduled dispatch: ${problems.join('; ')}`)\n const byCron = new Map(options.entries.map((entry) => [entry.cron, entry]))\n const retryDelaysMs = options.retryDelaysMs ?? []\n const log = options.log ?? {\n info: (message: string, detail?: Record<string, unknown>) => console.log(message, detail ?? ''),\n error: (message: string, detail?: Record<string, unknown>) => console.error(message, detail ?? ''),\n }\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n\n function jobFor(cron: string, scheduledTime: number | Date): string | null {\n const entry = byCron.get(cron)\n if (!entry) return null\n if ('job' in entry) return entry.job\n const minute = new Date(scheduledTime).getUTCMinutes()\n return entry.minutes[minute] ?? null\n }\n\n async function runJob(job: string, cron: string, scheduledTime: Date, context: Ctx): Promise<ScheduledJobOutcome> {\n const run = options.jobs[job]!\n const started = Date.now()\n let lastError = ''\n for (let attempt = 1; attempt <= retryDelaysMs.length + 1; attempt += 1) {\n try {\n await run({ cron, scheduledTime, context, attempt })\n return { job, ok: true, attempts: attempt, durationMs: Date.now() - started }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error)\n const delay = retryDelaysMs[attempt - 1]\n if (delay === undefined) break\n log.error(`[scheduled] ${job} failed; retrying`, { attempt, error: lastError })\n await sleep(delay)\n }\n }\n log.error(`[scheduled] ${job} failed`, { attempts: retryDelaysMs.length + 1, error: lastError })\n return { job, ok: false, attempts: retryDelaysMs.length + 1, durationMs: Date.now() - started, error: lastError }\n }\n\n return {\n entries: options.entries,\n slots: () => slotsOf(options.entries),\n jobFor,\n async dispatch(event, context, waitUntil) {\n const scheduledTime = new Date(event.scheduledTime)\n const job = jobFor(event.cron, scheduledTime)\n if (!job) {\n log.error(`[scheduled] no job handles cron \"${event.cron}\" at minute ${scheduledTime.getUTCMinutes()}; the configured crons and the schedule disagree`)\n return { handled: false, job: null, done: Promise.resolve(null) }\n }\n const done = runJob(job, event.cron, scheduledTime, context)\n if (waitUntil) waitUntil(done)\n else await done\n return { handled: true, job, done }\n },\n }\n}\n\n/** Every invocation a schedule table can make. */\nexport function slotsOf(entries: readonly ScheduleEntry[]): ScheduleSlot[] {\n return entries.flatMap((entry) => 'job' in entry\n ? [{ cron: entry.cron, job: entry.job }]\n : Object.entries(entry.minutes).map(([minute, job]) => ({ cron: entry.cron, minute: Number(minute), job })))\n}\n\nfunction validateEntries(entries: readonly ScheduleEntry[], jobNames: readonly string[]): string[] {\n const problems: string[] = []\n const known = new Set(jobNames)\n const seen = new Set<string>()\n for (const entry of entries) {\n if (seen.has(entry.cron)) problems.push(`cron \"${entry.cron}\" is listed twice`)\n seen.add(entry.cron)\n const fields = entry.cron.trim().split(/\\s+/)\n if (fields.length !== 5) problems.push(`cron \"${entry.cron}\" does not have five fields`)\n for (const slot of slotsOf([entry])) {\n if (!known.has(slot.job)) problems.push(`cron \"${entry.cron}\" names job \"${slot.job}\", which is not defined`)\n }\n if ('minutes' in entry) {\n const listed = minuteList(fields[0] ?? '')\n const mapped = Object.keys(entry.minutes).map(Number).sort((a, b) => a - b)\n if (!listed) problems.push(`cron \"${entry.cron}\" maps jobs by minute, so its minute field must be a list of minutes`)\n else if (listed.join(',') !== mapped.join(',')) {\n problems.push(`cron \"${entry.cron}\" lists minutes ${listed.join(',')} but maps jobs to ${mapped.join(',')}`)\n }\n }\n }\n return problems\n}\n\n/** The minutes of a plain minute list (`5` or `0,15,30`), or null for any other form. */\nfunction minuteList(field: string): number[] | null {\n if (!/^\\d{1,2}(,\\d{1,2})*$/.test(field)) return null\n const minutes = field.split(',').map(Number)\n if (minutes.some((minute) => minute > 59)) return null\n return [...new Set(minutes)].sort((a, b) => a - b)\n}\n\n// ── cron analysis ────────────────────────────────────────────────────────────\n\nfunction expandField(field: string, min: number, max: number): Set<number> | null {\n const values = new Set<number>()\n for (const part of field.split(',')) {\n const match = /^(\\*|\\d+(?:-\\d+)?)(?:\\/(\\d+))?$/.exec(part)\n if (!match) return null\n const [, range, stepText] = match\n const step = stepText ? Number(stepText) : 1\n if (!(step >= 1)) return null\n let lo = min\n let hi = max\n if (range !== '*') {\n const [a, b] = range!.split('-').map(Number)\n lo = a!\n hi = b ?? (stepText ? max : a!)\n }\n if (lo < min || hi > max || lo > hi) return null\n for (let value = lo; value <= hi; value += step) values.add(value)\n }\n return values\n}\n\n/**\n * The minutes of the day (0–1439, UTC) a cron fires, or null when it does not\n * fire every day (a day-of-month, month or weekday restriction) or cannot be read.\n */\nexport function cronDailyFirings(cron: string): Set<number> | null {\n const fields = cron.trim().split(/\\s+/)\n if (fields.length !== 5) return null\n const [minuteField, hourField, dayField, monthField, weekdayField] = fields as [string, string, string, string, string]\n if (dayField !== '*' || monthField !== '*' || (weekdayField !== '*' && weekdayField !== '?')) return null\n const minutes = expandField(minuteField, 0, 59)\n const hours = expandField(hourField, 0, 23)\n if (!minutes || !hours) return null\n const firings = new Set<number>()\n for (const hour of hours) for (const minute of minutes) firings.add(hour * 60 + minute)\n return firings\n}\n\n/** The longest wait, in minutes, between consecutive firings over a day, or null when they do not fire daily. */\nexport function longestGapMinutes(firings: Iterable<number>): number | null {\n const sorted = [...new Set(firings)].sort((a, b) => a - b)\n if (sorted.length === 0) return null\n let gap = sorted[0]! + 1440 - sorted[sorted.length - 1]!\n for (let index = 1; index < sorted.length; index += 1) gap = Math.max(gap, sorted[index]! - sorted[index - 1]!)\n return gap\n}\n\n/** The cron expressions a wrangler config declares, top level and per environment. */\nexport interface WranglerCrons {\n top: string[]\n envs: Record<string, string[]>\n}\n\n/** Read `[triggers] crons` (and `[env.<name>.triggers]`) from wrangler.toml, or `triggers.crons` from wrangler.json(c). */\nexport function parseWranglerCrons(source: string, format: 'toml' | 'json'): WranglerCrons {\n return format === 'json' ? parseJsonCrons(source) : parseTomlCrons(source)\n}\n\nfunction parseTomlCrons(source: string): WranglerCrons {\n const result: WranglerCrons = { top: [], envs: {} }\n let table = ''\n let collecting: string[] | null = null\n let buffer = ''\n for (const raw of source.split('\\n')) {\n const line = stripTomlComment(raw)\n if (collecting) {\n buffer += ` ${line}`\n if (line.includes(']')) {\n collecting.push(...quoted(buffer))\n collecting = null\n buffer = ''\n }\n continue\n }\n const header = /^\\s*\\[([^\\[\\]]+)\\]\\s*$/.exec(line)\n if (header) {\n table = header[1]!.trim()\n continue\n }\n const assignment = /^\\s*crons\\s*=\\s*(.*)$/.exec(line)\n if (!assignment) continue\n const envName = /^env\\.([^.]+)\\.triggers$/.exec(table)?.[1]\n const target = table === 'triggers' ? result.top : envName ? (result.envs[envName] ??= []) : null\n if (!target) continue\n const rest = assignment[1]!\n if (rest.includes(']')) target.push(...quoted(rest))\n else {\n collecting = target\n buffer = rest\n }\n }\n return result\n}\n\nfunction stripTomlComment(line: string): string {\n let quote: string | null = null\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index]!\n if (quote) {\n if (char === quote) quote = null\n } else if (char === '\"' || char === \"'\") quote = char\n else if (char === '#') return line.slice(0, index)\n }\n return line\n}\n\nfunction quoted(text: string): string[] {\n return [...text.matchAll(/\"([^\"]*)\"|'([^']*)'/g)].map((match) => match[1] ?? match[2] ?? '')\n}\n\nfunction parseJsonCrons(source: string): WranglerCrons {\n const config = JSON.parse(stripJsonComments(source)) as {\n triggers?: { crons?: string[] }\n env?: Record<string, { triggers?: { crons?: string[] } }>\n }\n return {\n top: [...(config.triggers?.crons ?? [])],\n envs: Object.fromEntries(Object.entries(config.env ?? {})\n .filter(([, env]) => Array.isArray(env.triggers?.crons))\n .map(([name, env]) => [name, [...env.triggers!.crons!]])),\n }\n}\n\nfunction stripJsonComments(source: string): string {\n let out = ''\n let inString = false\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index]!\n const next = source[index + 1]\n if (inString) {\n out += char\n if (char === '\\\\') out += source[++index] ?? ''\n else if (char === '\"') inString = false\n continue\n }\n if (char === '\"') {\n inString = true\n out += char\n } else if (char === '/' && next === '/') {\n while (index < source.length && source[index] !== '\\n') index += 1\n out += '\\n'\n } else if (char === '/' && next === '*') {\n index += 2\n while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) index += 1\n index += 1\n } else out += char\n }\n return out.replace(/,(\\s*[}\\]])/g, '$1')\n}\n\n// ── the invariant ────────────────────────────────────────────────────────────\n\n/** What one scheduled invocation was observed to run. */\nexport interface ObservedSlot {\n cron: string\n minute?: number\n /** The jobs the invocation ran; exactly one passes. */\n jobs: readonly string[]\n}\n\nexport interface IsolatedJobsInput {\n /** Every cron the deployment configures, from each wrangler environment. */\n configuredCrons: readonly string[]\n /** What each invocation runs: from {@link slotsOf} for a {@link createScheduledDispatch} table, or observed by driving the app's own handler. */\n slots: readonly ObservedSlot[]\n /** Jobs that recover and settle turns; each must run at least every 15 minutes. */\n recoveryJobs: readonly string[]\n /** Default {@link LAUNCH_BUDGETS.recoveryEveryMs}. */\n everyMs?: number\n}\n\n/** One job per invocation, the table and the deployment agree, and recovery runs at least every 15 minutes. */\nexport function checkIsolatedJobs(input: IsolatedJobsInput): InvariantVerdict {\n const everyMinutes = (input.everyMs ?? LAUNCH_BUDGETS.recoveryEveryMs) / 60_000\n const findings: string[] = []\n const configured = new Set(input.configuredCrons)\n const dispatched = new Set(input.slots.map((slot) => slot.cron))\n for (const cron of configured) if (!dispatched.has(cron)) findings.push(`configured cron \"${cron}\" runs no job: no schedule entry matches it`)\n for (const cron of dispatched) if (!configured.has(cron)) findings.push(`schedule cron \"${cron}\" is not configured, so it never runs`)\n for (const slot of input.slots) {\n const where = `cron \"${slot.cron}\"${slot.minute !== undefined ? ` at minute ${slot.minute}` : ''}`\n if (slot.jobs.length !== 1) findings.push(`${where} runs ${slot.jobs.length} jobs in one invocation (${slot.jobs.join(', ') || 'none'}); one failure ends the rest`)\n }\n const byCron = new Map<string, ObservedSlot[]>()\n for (const slot of input.slots) byCron.set(slot.cron, [...(byCron.get(slot.cron) ?? []), slot])\n for (const [cron, slots] of byCron) {\n const minuteSlots = slots.filter((slot) => slot.minute !== undefined)\n if (minuteSlots.length === 0) continue\n const listed = minuteList(cron.trim().split(/\\s+/)[0] ?? '')\n const mapped = [...new Set(minuteSlots.map((slot) => slot.minute!))].sort((a, b) => a - b)\n if (!listed || listed.join(',') !== mapped.join(',')) {\n findings.push(`cron \"${cron}\" fires at minutes ${listed?.join(',') ?? '(not a minute list)'} but jobs are mapped to ${mapped.join(',')}`)\n }\n }\n if (input.recoveryJobs.length === 0) findings.push('no turn recovery or orphan settlement job is declared')\n const gaps: Record<string, number | null> = {}\n for (const job of input.recoveryJobs) {\n const firings = new Set<number>()\n let daily = false\n for (const slot of input.slots) {\n if (slot.jobs.length !== 1 || slot.jobs[0] !== job) continue\n const fires = cronDailyFirings(slot.cron)\n if (!fires) continue\n daily = true\n for (const minuteOfDay of fires) if (slot.minute === undefined || minuteOfDay % 60 === slot.minute) firings.add(minuteOfDay)\n }\n const gap = daily ? longestGapMinutes(firings) : null\n gaps[job] = gap\n if (gap === null) findings.push(`recovery job \"${job}\" is not scheduled to run every day on its own`)\n else if (gap > everyMinutes) findings.push(`recovery job \"${job}\" can wait ${gap} minutes between runs; the most is ${everyMinutes}`)\n }\n return {\n invariant: 'isolated-jobs',\n subject: 'schedule',\n pass: findings.length === 0,\n details: findings.length ? findings : [\n `${input.slots.length} scheduled invocations, one job each, across ${configured.size} configured crons`,\n ...input.recoveryJobs.map((job) => `${job} runs at least every ${gaps[job]} minutes`),\n ],\n data: { configuredCrons: [...configured], slots: input.slots.length, recoveryGapsMinutes: gaps },\n }\n}\n","/**\n * Alarms that fire at 80% of a platform limit, before the limit fails a customer.\n *\n * On 2026-10-10 GTM recorded 19 platform-limit events (Worker memory, D1,\n * sandbox disk, snapshot count, key rate) and learned of each one after it had\n * failed someone. Each resource here has a declared limit; an observation at\n * or above 80% of it delivers a warning, and at or above the limit a critical\n * alert, through the same {@link AlertSink} the turn-health sweep uses (wrap it\n * in `createThrottledAlertSink` so a hot loop pages once).\n *\n * Where each observation comes from:\n * - `d1-rows-per-query`: {@link withD1LimitAlarms} reads `meta.rows_read` on every query.\n * - `worker-memory`: workerd exposes no heap reading, so the D1 wrapper observes\n * the bytes each response returns (the reads that overran memory today), and a\n * tail consumer reports an `exceededMemory` outcome at the full limit.\n * - `sandbox-disk` and `snapshot-count`: the Sandbox SDK's box usage and snapshot list, read on a schedule.\n * - `key-rate`: the per-key request counter the operator API keeps.\n */\nimport type { AlertSink, TurnHealthAlert } from '../turn-health/sink.js'\nimport { LAUNCH_BUDGETS } from './catalog.js'\n\nexport type LimitResource = 'worker-memory' | 'd1-rows-per-query' | 'sandbox-disk' | 'snapshot-count' | 'key-rate'\n\nexport const LIMIT_RESOURCES: readonly LimitResource[] = [\n 'worker-memory',\n 'd1-rows-per-query',\n 'sandbox-disk',\n 'snapshot-count',\n 'key-rate',\n]\n\n/** The limit of each resource, in its own unit: bytes, rows, bytes, snapshots, requests per minute. */\nexport type LimitBudgets = Readonly<Record<LimitResource, number>>\n\nconst UNITS: Readonly<Record<LimitResource, string>> = {\n 'worker-memory': 'bytes',\n 'd1-rows-per-query': 'rows',\n 'sandbox-disk': 'bytes',\n 'snapshot-count': 'snapshots',\n 'key-rate': 'requests/min',\n}\n\nexport type LimitLevel = 'ok' | 'warning' | 'critical'\n\nexport interface LimitObservation {\n resource: LimitResource\n used: number\n limit: number\n /** used / limit. */\n share: number\n level: LimitLevel\n}\n\nexport interface LimitAlarms {\n readonly budgets: LimitBudgets\n /** Record one reading; a warning or critical reading is delivered before this resolves. */\n observe(resource: LimitResource, used: number, context?: { subject?: string; detail?: string }): Promise<LimitObservation>\n}\n\nexport interface LimitAlarmOptions {\n product: string\n budgets: LimitBudgets\n sink: AlertSink\n /** Default {@link LAUNCH_BUDGETS.alarmRatio}; a product cannot raise it past the limit itself. */\n ratio?: number\n now?: () => number\n}\n\nexport function createLimitAlarms(options: LimitAlarmOptions): LimitAlarms {\n const ratio = Math.min(options.ratio ?? LAUNCH_BUDGETS.alarmRatio, 1)\n const now = options.now ?? (() => Date.now())\n for (const resource of LIMIT_RESOURCES) {\n const limit = options.budgets[resource]\n if (!(typeof limit === 'number' && limit > 0 && Number.isFinite(limit))) {\n throw new Error(`limit alarms: ${resource} needs a positive limit`)\n }\n }\n return {\n budgets: options.budgets,\n async observe(resource, used, context) {\n const limit = options.budgets[resource]\n const share = used / limit\n const level: LimitLevel = share >= 1 ? 'critical' : share >= ratio ? 'warning' : 'ok'\n const observation = { resource, used, limit, share, level }\n if (level === 'ok') return observation\n const alert: TurnHealthAlert = {\n product: options.product,\n severity: level,\n // Keyed by product and resource only, so a throttled sink pages once per resource.\n key: `limit:${options.product}:${resource}`,\n title: `${options.product}: ${resource} at ${Math.round(share * 100)}% of its limit`,\n details: [\n `${formatAmount(used, resource)} of ${formatAmount(limit, resource)} ${UNITS[resource]}`,\n ...(context?.subject ? [`in ${context.subject}`] : []),\n ...(context?.detail ? [context.detail] : []),\n ],\n data: { resource, used, limit, share, ...(context?.subject ? { subject: context.subject } : {}) },\n at: now(),\n }\n await options.sink.deliver(alert)\n return observation\n },\n }\n}\n\nfunction formatAmount(value: number, resource: LimitResource): string {\n if (UNITS[resource] === 'bytes') return `${(value / (1024 * 1024)).toFixed(1)} MB`\n return Math.round(value).toLocaleString('en-US')\n}\n\n/** The D1 surface the wrapper measures; Cloudflare `D1Database` satisfies it. */\ninterface D1Measurable {\n prepare(sql: string): unknown\n}\n\n/**\n * The D1 binding with each query's rows read and response size observed.\n * Rows read come from `meta.rows_read` (the rows D1 scanned, not only those\n * returned). The response size is estimated from three sampled rows, so the\n * wrapper never serializes a whole response: that copy would double the memory\n * of the very read it watches.\n */\nexport function withD1LimitAlarms<D extends D1Measurable>(d1: D, alarms: LimitAlarms, options: { subject?: string } = {}): D {\n const observe = (sql: string, result: unknown) => {\n const meta = (result as { meta?: { rows_read?: unknown } } | null)?.meta\n const rowsRead = typeof meta?.rows_read === 'number' ? meta.rows_read : rowsOf(result)\n const pending: Promise<unknown>[] = []\n if (rowsRead !== null) pending.push(alarms.observe('d1-rows-per-query', rowsRead, { subject: options.subject, detail: sql }))\n const results = (result as { results?: unknown[] } | null)?.results ?? (Array.isArray(result) ? result : null)\n if (results && results.length > 0) {\n pending.push(alarms.observe('worker-memory', estimatedBytes(results), { subject: options.subject, detail: `one response: ${sql}` }))\n }\n // An alarm delivery failure must not fail the query that triggered it.\n return Promise.all(pending).catch(() => undefined)\n }\n // D1's batch() takes only its own statements, so a batch is given the unwrapped ones.\n const unwrapped = new WeakMap<object, object>()\n const statement = (target: object, sql: string): object => {\n const wrapped = new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object, sql)\n if (key === 'all' || key === 'raw' || key === 'run' || key === 'first') {\n return async (...args: unknown[]) => {\n const result: unknown = await value.apply(stmt, args)\n if (key !== 'first') await observe(sql, result)\n return result\n }\n }\n return value.bind(stmt)\n },\n })\n unwrapped.set(wrapped, target)\n return wrapped\n }\n return new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') {\n return (sql: string) => statement((value as (sql: string) => object).call(binding, sql), sql.replace(/\\s+/g, ' ').slice(0, 160))\n }\n if (key === 'batch' && typeof value === 'function') {\n return async (statements: object[]) => {\n const results = await (value as (s: object[]) => Promise<unknown[]>).call(binding, statements.map((stmt) => unwrapped.get(stmt) ?? stmt))\n for (const result of results ?? []) await observe('batch', result)\n return results\n }\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n}\n\n/** The serialized size of a result set, from its first, middle and last rows. */\nexport function estimatedBytes(results: readonly unknown[]): number {\n const picks = [...new Set([0, Math.floor(results.length / 2), results.length - 1])]\n const sampled = picks.reduce((sum, index) => sum + (JSON.stringify(results[index]) ?? '').length, 0)\n return Math.round((sampled / picks.length) * results.length)\n}\n\nfunction rowsOf(result: unknown): number | null {\n if (Array.isArray(result)) return result.length\n const results = (result as { results?: unknown } | null)?.results\n return Array.isArray(results) ? results.length : null\n}\n"],"mappings":";AASO,IAAM,iBAAiB;AAAA;AAAA,EAE5B,YAAY,IAAI,OAAO;AAAA;AAAA,EAEvB,iBAAiB,KAAK,OAAO;AAAA;AAAA,EAE7B,gBAAgB,IAAI,OAAO;AAAA;AAAA,EAE3B,YAAY;AAAA;AAAA,EAEZ,gBAAgB,KAAK;AAAA;AAAA,EAErB,iBAAiB,KAAK;AAAA;AAAA,EAEtB,gBAAgB;AAAA;AAAA,EAEhB,YAAY;AACd;AAqBO,IAAM,oBAAgD;AAAA,EAC3D;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AACF;AAGO,IAAM,uBAAqD,kBAAkB,IAAI,CAAC,cAAc,UAAU,EAAE;AAe5G,SAAS,gBAAgB,SAAmC;AAC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AAM,IAAI;AAAA,IACnB,IAAI,SAAS,KAAK;AAChB,YAAM,QAAQ,QAAQ,IAAI,SAAS,GAAG;AACtC,UAAI,QAAQ,WAAW;AACrB,eAAO,CAAC,QAAgB,UAAW,MAAkC,KAAK,SAAS,GAAG,GAAG,IAAI,QAAQ,QAAQ,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;AAAA,MACjI;AACA,UAAI,QAAQ,WAAW,OAAO,UAAU,YAAY;AAClD,eAAO,OAAO,eAAyB;AACrC,gBAAM,UAAU,MAAO,MAA8C,KAAK,SAAS,WAAW,IAAI,CAAC,SAAS,UAAU,IAAI,IAAI,KAAK,IAAI,CAAC;AACxI,qBAAW,UAAU,WAAW,CAAC,EAAG,OAAM,QAAQ,SAAS,MAAM;AACjE,iBAAO;AAAA,QACT;AAAA,MACF;AACA,aAAO,OAAO,UAAU,aAAa,MAAM,KAAK,OAAO,IAAI;AAAA,IAC7D;AAAA,EACF,CAAC;AACH;AAGO,SAAS,eAAe,SAAqC;AAClE,QAAM,QAAQ,CAAC,GAAG,oBAAI,IAAI,CAAC,GAAG,KAAK,MAAM,QAAQ,SAAS,CAAC,GAAG,QAAQ,SAAS,CAAC,CAAC,CAAC;AAClF,QAAM,UAAU,MAAM,OAAO,CAAC,KAAK,UAAU,OAAO,KAAK,UAAU,QAAQ,KAAK,CAAC,KAAK,IAAI,QAAQ,CAAC;AACnG,SAAO,KAAK,MAAO,UAAU,MAAM,SAAU,QAAQ,MAAM;AAC7D;AAEA,SAAS,OAAO,QAAgC;AAC9C,MAAI,MAAM,QAAQ,MAAM,EAAG,QAAO,OAAO;AACzC,QAAM,UAAW,QAAyC;AAC1D,SAAO,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;AACnD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/launch-invariants/testing.ts","../src/launch-invariants/conformance.ts"],"sourcesContent":["/**\n * `/launch-invariants/testing` — the checks an app runs in its own test suite.\n *\n * Each check drives the app's real code through a small adapter and returns an\n * {@link InvariantVerdict}. {@link recordInvariant} fails the calling test with\n * the verdict's findings and, when `agent-app-invariants` runs the suite,\n * records the verdict so the conformance report can say which invariant\n * passed. The checks need no test runner: vitest, node:test and plain scripts\n * all work.\n *\n * Node-only (`node:v8`, `node:vm`, `node:fs`): import it from tests, never from\n * a Worker.\n */\nimport { appendFileSync } from 'node:fs'\nimport v8 from 'node:v8'\nimport vm from 'node:vm'\nimport type { AlertSink, TurnHealthAlert } from '../turn-health/sink.js'\nimport { describeVerdict, LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\nimport { LIMIT_RESOURCES, type LimitAlarms } from './limit-alarms.js'\n\nexport { describeVerdict } from './catalog.js'\n\n/** Set by `agent-app-invariants` to the file it reads verdicts from. */\nexport const INVARIANT_RESULTS_ENV = 'AGENT_APP_INVARIANTS_RESULTS'\n\n/**\n * Record a verdict for the conformance report and fail the caller when it did\n * not pass. Returns the verdict on a pass.\n */\nexport function recordInvariant(verdict: InvariantVerdict): InvariantVerdict {\n const file = process.env[INVARIANT_RESULTS_ENV]\n if (file) appendFileSync(file, `${JSON.stringify({ ...verdict, at: new Date().toISOString() })}\\n`)\n if (!verdict.pass) throw new Error(describeVerdict(verdict))\n return verdict\n}\n\n/** Record several verdicts; fails after recording all of them. */\nexport function recordInvariants(verdicts: readonly InvariantVerdict[]): InvariantVerdict[] {\n const failures: string[] = []\n for (const verdict of verdicts) {\n try {\n recordInvariant(verdict)\n } catch (error) {\n failures.push(error instanceof Error ? error.message : String(error))\n }\n }\n if (failures.length) throw new Error(failures.join('\\n'))\n return [...verdicts]\n}\n\n// ── heap ─────────────────────────────────────────────────────────────────────\n\nlet gc: (() => void) | undefined\n\n/** Run a full garbage collection, so a heap reading counts only live objects. */\nexport function forceGc(): void {\n if (!gc) {\n v8.setFlagsFromString('--expose_gc')\n gc = vm.runInNewContext('gc') as () => void\n }\n gc()\n}\n\n// ── measured D1 ──────────────────────────────────────────────────────────────\n\nconst MB = 1024 * 1024\n\n/** What a measured binding saw while one job ran. */\nexport interface D1Reads {\n queries: number\n maxQueryBytes: number\n /** The query that returned the most bytes. */\n largestSql: string\n peakHeapBytes: number\n /** The query running when the heap peaked: where a job holds what it read. */\n peakSql: string\n}\n\nfunction emptyReads(): D1Reads {\n return { queries: 0, maxQueryBytes: 0, largestSql: '', peakHeapBytes: 0, peakSql: '' }\n}\n\n/**\n * The D1 binding with every response measured (serialized bytes) and the live\n * heap sampled after a collection before and after every query. Works over\n * Cloudflare D1 and the sqlite-backed D1 shims apps test with. A database\n * engine that keeps its pages off the JS heap (node:sqlite, better-sqlite3)\n * leaves heap growth to the job's own objects.\n */\nexport function measureD1<D extends object>(d1: D, reads: D1Reads = emptyReads(), options: { sampleHeap?: boolean } = {}): { d1: D; reads: D1Reads } {\n const sampleHeap = options.sampleHeap ?? true\n const sample = (sql: string) => {\n if (!sampleHeap) return\n forceGc()\n const heap = process.memoryUsage().heapUsed\n if (heap > reads.peakHeapBytes) {\n reads.peakHeapBytes = heap\n reads.peakSql = sql\n }\n }\n const measure = (sql: string, result: unknown) => {\n reads.queries += 1\n const bytes = Buffer.byteLength(JSON.stringify(result) ?? '')\n if (bytes > reads.maxQueryBytes) {\n reads.maxQueryBytes = bytes\n reads.largestSql = sql\n }\n }\n const statement = (target: object, sql: string): object => new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object, sql)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return async (...args: unknown[]) => {\n sample(sql)\n const result: unknown = await value.apply(stmt, args)\n measure(sql, result)\n sample(sql)\n return result\n }\n }\n return value.bind(stmt)\n },\n })\n const unwrap = new WeakMap<object, object>()\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') {\n return (sql: string) => {\n const stmt = (value as (sql: string) => object).call(binding, sql)\n const wrapped = statement(stmt, sql.replace(/\\s+/g, ' ').trim().slice(0, 200))\n unwrap.set(wrapped, stmt)\n return wrapped\n }\n }\n if (key === 'batch') {\n return async (statements: object[]) => {\n sample('batch')\n const result: unknown = await (value as (s: object[]) => Promise<unknown>).call(binding, statements.map((stmt) => unwrap.get(stmt) ?? stmt))\n measure('batch', result)\n sample('batch')\n return result\n }\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return { d1: proxy, reads }\n}\n\n/** One scheduled job (or report route) as the budget check runs it. */\nexport interface BudgetedJob {\n name: string\n run: () => Promise<unknown>\n /** False for a job that reads nothing from D1 (it then passes bounded reads vacuously). Default true. */\n readsD1?: boolean\n}\n\nexport interface JobMeasurement {\n name: string\n reads: D1Reads\n heapGrowthBytes: number\n error?: string\n}\n\nexport interface ScheduledJobBudgetOptions {\n /** The app's D1 over its day-sized fixture. */\n d1: object\n /** Point the app's database accessor at the measured binding (`setD1`, `setDatabase(drizzle(...))`). */\n install: (measured: object) => void\n jobs: readonly BudgetedJob[]\n /** Every job the app schedules, by the names {@link jobs} uses. Each must be measured. */\n scheduled: readonly string[]\n maxQueryBytes?: number\n maxHeapGrowthBytes?: number\n /** Silence the jobs' own logging while they run. Default true. */\n quiet?: boolean\n}\n\n/** Run one job against a measured binding. */\nexport async function measureJob(job: BudgetedJob, d1: object, install: (measured: object) => void, quiet = true): Promise<JobMeasurement> {\n const { d1: measured, reads } = measureD1(d1)\n install(measured)\n forceGc()\n const baseline = process.memoryUsage().heapUsed\n reads.peakHeapBytes = baseline\n const restore = quiet ? silenceConsole() : () => {}\n let error: string | undefined\n try {\n await job.run()\n } catch (caught) {\n error = caught instanceof Error ? caught.message : String(caught)\n } finally {\n restore()\n }\n forceGc()\n const after = process.memoryUsage().heapUsed\n if (after > reads.peakHeapBytes) {\n reads.peakHeapBytes = after\n reads.peakSql = reads.peakSql ? `${reads.peakSql} (still held when the job returned)` : '(after the job returned)'\n }\n return { name: job.name, reads, heapGrowthBytes: reads.peakHeapBytes - baseline, ...(error ? { error } : {}) }\n}\n\nfunction silenceConsole(): () => void {\n const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error }\n console.log = console.info = console.warn = console.error = () => {}\n return () => Object.assign(console, saved)\n}\n\n/**\n * Bounded reads and the memory budget for every scheduled job, on the app's\n * day-sized fixture. Returns a bounded-reads and a memory-budget verdict per\n * job, and a coverage verdict naming any scheduled job that was not run.\n */\nexport async function checkScheduledJobBudgets(options: ScheduledJobBudgetOptions): Promise<InvariantVerdict[]> {\n const maxQueryBytes = options.maxQueryBytes ?? LAUNCH_BUDGETS.queryBytes\n const maxHeap = options.maxHeapGrowthBytes ?? LAUNCH_BUDGETS.heapGrowthBytes\n const verdicts: InvariantVerdict[] = []\n const measured = new Set<string>()\n for (const job of options.jobs) {\n const m = await measureJob(job, options.d1, options.install, options.quiet ?? true)\n measured.add(job.name)\n const failed = m.error ? [`the job threw on the fixture: ${m.error}`] : []\n const readFindings = [...failed]\n if ((job.readsD1 ?? true) && m.reads.queries === 0) readFindings.push('made no D1 query on the fixture; the fixture does not reach it, or it reads through another binding')\n if (m.reads.maxQueryBytes > maxQueryBytes) {\n readFindings.push(`one query returned ${(m.reads.maxQueryBytes / MB).toFixed(1)} MB (the most is ${(maxQueryBytes / MB).toFixed(0)} MB): ${m.reads.largestSql}`)\n }\n verdicts.push({\n invariant: 'bounded-reads',\n subject: job.name,\n pass: readFindings.length === 0,\n details: readFindings.length ? readFindings : [`${m.reads.queries} queries, largest ${(m.reads.maxQueryBytes / MB).toFixed(2)} MB`],\n data: { queries: m.reads.queries, maxQueryBytes: m.reads.maxQueryBytes, largestSql: m.reads.largestSql },\n })\n const heapFindings = [...failed]\n if (m.heapGrowthBytes > maxHeap) {\n heapFindings.push(`the live heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB (the most is ${(maxHeap / MB).toFixed(0)} MB), at its peak around: ${m.reads.peakSql}`)\n }\n verdicts.push({\n invariant: 'memory-budget',\n subject: job.name,\n pass: heapFindings.length === 0,\n details: heapFindings.length ? heapFindings : [`heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB`],\n data: { heapGrowthBytes: m.heapGrowthBytes, peakSql: m.reads.peakSql },\n })\n }\n const missing = options.scheduled.filter((name) => !measured.has(name))\n verdicts.push({\n invariant: 'memory-budget',\n subject: 'coverage',\n pass: missing.length === 0 && options.scheduled.length > 0,\n details: missing.length\n ? missing.map((name) => `${name} is scheduled but not run on the fixture`)\n : options.scheduled.length === 0\n ? ['no scheduled jobs were named; pass every job the app schedules']\n : [`all ${options.scheduled.length} scheduled jobs ran on the fixture`],\n data: { scheduled: [...options.scheduled], measured: [...measured] },\n })\n return verdicts\n}\n\n// ── a D1 that stalls ─────────────────────────────────────────────────────────\n\nexport type StallMode = 'ok' | 'error' | 'hang'\n\n/** The D1 binding with a switch that makes every query fail or never answer, as an overloaded D1 did. */\nexport function stallingD1<D extends object>(d1: D): { d1: D; stall(mode: StallMode): void; readonly mode: StallMode } {\n let mode: StallMode = 'ok'\n const fail = (): Promise<never> => mode === 'hang'\n ? new Promise<never>(() => {})\n : Promise.reject(new Error('D1_ERROR: Network connection lost.'))\n const unwrapped = new WeakMap<object, object>()\n const statement = (target: object): object => {\n const wrapped = new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return (...args: unknown[]) => (mode === 'ok' ? value.apply(stmt, args) : fail())\n }\n return value.bind(stmt)\n },\n })\n unwrapped.set(wrapped, target)\n return wrapped\n }\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') return (sql: string) => statement((value as (sql: string) => object).call(binding, sql))\n if (key === 'batch') {\n return (statements: object[]) => (mode === 'ok'\n ? (value as (s: object[]) => unknown).call(binding, statements.map((stmt) => unwrapped.get(stmt) ?? stmt))\n : fail())\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return {\n d1: proxy,\n stall(next) {\n mode = next\n },\n get mode() {\n return mode\n },\n }\n}\n\n/** Move `Date.now` forward for the duration of a check; returns the restore. */\nfunction shiftableClock(): { advance(ms: number): void; restore(): void } {\n const real = Date.now\n let offset = 0\n Date.now = () => real() + offset\n return {\n advance(ms) {\n offset += ms\n },\n restore() {\n Date.now = real\n },\n }\n}\n\n// ── auth survives a D1 stall ─────────────────────────────────────────────────\n\nexport interface AuthStallOptions {\n /** A label for the lookup: \"session\", \"API key\". */\n subject: string\n /** Three distinct valid credentials the app's store accepts. */\n credentials: { cached: string; revoked: string; aged: string }\n /** The app's real lookup: truthy when the credential is accepted. A throw or a falsy value is a refusal. */\n verify: (credential: string) => Promise<unknown>\n /** The app's real revoke path (revoke the key, sign the session out). */\n revoke: (credential: string) => Promise<void>\n /** Switch the D1 the lookup reads. */\n stall: (mode: StallMode) => void\n /** The keys the app's auth caches hold. */\n cacheKeys: () => string[]\n /** Include a stall that never answers (costs one lookup deadline, 2.5 s). Default true. */\n hang?: boolean\n}\n\n/**\n * A verified credential keeps working while D1 errors or stalls; it is refused\n * once revoked, and once its last verification is more than 60 s old; and the\n * cache holds SHA-256 keys, not secrets. Uses the app's real lookup, revoke\n * path and D1, with `Date.now` moved forward to age the cache.\n */\nexport async function checkAuthSurvivesStall(options: AuthStallOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n const accepted = async (credential: string): Promise<boolean> => {\n try {\n return Boolean(await options.verify(credential))\n } catch {\n return false\n }\n }\n const { cached, revoked, aged } = options.credentials\n const clock = shiftableClock()\n try {\n options.stall('ok')\n for (const credential of [cached, revoked, aged]) {\n if (!(await accepted(credential))) findings.push(`a valid credential was refused while D1 was healthy (${options.subject})`)\n }\n for (const key of options.cacheKeys()) {\n if (!/^[0-9a-f]{64}$/.test(key) || [cached, revoked, aged].some((credential) => key.includes(credential))) {\n findings.push(`the auth cache holds a key that is not a SHA-256 digest: ${key.slice(0, 12)}…`)\n }\n }\n await options.revoke(revoked)\n if (await accepted(revoked)) findings.push('a revoked credential was accepted while D1 was healthy')\n\n options.stall('error')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 errored')\n if (await accepted(revoked)) findings.push('a revoked credential was accepted from the cache while D1 errored')\n if (options.hang ?? true) {\n options.stall('hang')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 did not answer')\n }\n\n clock.advance(LAUNCH_BUDGETS.authCacheTtlMs + 1_000)\n options.stall('error')\n if (await accepted(aged)) findings.push(`a credential last verified more than ${LAUNCH_BUDGETS.authCacheTtlMs / 1000} s ago was accepted from the cache while D1 errored`)\n } finally {\n options.stall('ok')\n clock.restore()\n }\n return {\n invariant: 'auth-survives-d1-stall',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [\n 'served while D1 errored and while it stalled; refused after revoke and after the 60 s cache window; keys are SHA-256',\n ],\n }\n}\n\n// ── authorization before any stream ──────────────────────────────────────────\n\nexport interface AuthorizeBeforeStreamOptions {\n subject: string\n /** The app's real route handler, as its router mounts it. */\n handle: (request: Request) => Promise<Response>\n /** Requests the route must refuse: no session, another workspace's thread, a revoked key. */\n refused: ReadonlyArray<{ name: string; request: () => Request; status?: readonly number[] }>\n /** Product state the route touched (rows written, producers started); empty after every refusal. */\n touched?: () => readonly string[]\n}\n\nconst STREAM_TYPES = /event-stream|ndjson|x-turn-progress/i\n\n/** Each refused request gets a plain 4xx, opens no stream and touches nothing. */\nexport async function checkAuthorizeBeforeStream(options: AuthorizeBeforeStreamOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const probe of options.refused) {\n const before = options.touched?.().length ?? 0\n const response = await options.handle(probe.request())\n const allowed = probe.status ?? [401, 403, 404]\n if (!allowed.includes(response.status)) findings.push(`${probe.name}: answered ${response.status}, expected ${allowed.join(' or ')}`)\n const type = response.headers.get('content-type') ?? ''\n if (STREAM_TYPES.test(type)) findings.push(`${probe.name}: opened a ${type} stream before refusing`)\n for (const [name] of response.headers) {\n if (/turn-progress|x-turn-id/i.test(name)) findings.push(`${probe.name}: refusal carries turn header ${name}`)\n }\n await response.body?.cancel().catch(() => undefined)\n const after = options.touched?.() ?? []\n if (after.length > before) findings.push(`${probe.name}: touched ${after.slice(before).join(', ')} before refusing`)\n }\n return {\n invariant: 'authorize-before-stream',\n subject: options.subject,\n pass: findings.length === 0 && options.refused.length > 0,\n details: findings.length ? findings : options.refused.length\n ? [`${options.refused.length} refused requests answered plainly with nothing touched`]\n : ['no refused requests were probed'],\n }\n}\n\n// ── coalesced turn events ────────────────────────────────────────────────────\n\n/** One event of the recorded long turn and the turn-relative time it arrived. */\nexport interface TimedTurnEvent {\n atMs: number\n event: Record<string, unknown>\n}\n\n/**\n * The long turn GTM recorded on 2026-10-10, reproduced in shape: a reasoning\n * model streaming three events per token (the harness's raw part update, a\n * model-processing heartbeat and the delta), with tool calls between runs of\n * reasoning and text. 59,659 events over about ten minutes, as that turn wrote\n * them before coalescing.\n */\nexport function recordedLongTurn(options: { tokens?: number; toolCalls?: number; tokenMs?: number } = {}): TimedTurnEvent[] {\n const tokens = options.tokens ?? 19_866\n const toolCalls = options.toolCalls ?? 30\n const tokenMs = options.tokenMs ?? 30\n const events: TimedTurnEvent[] = [{ atMs: 0, event: { type: 'turn', turnId: 'recorded-long-turn' } }]\n const toolEvery = Math.max(1, Math.floor(tokens / (toolCalls + 1)))\n let tool = 0\n let part = 0\n for (let index = 0; index < tokens; index += 1) {\n const atMs = (index + 1) * tokenMs\n if (index > 0 && index % toolEvery === 0 && tool < toolCalls) {\n tool += 1\n part += 1\n events.push({ atMs, event: { type: 'tool_call', id: `call_${tool}`, name: 'bash', input: { command: 'ls' } } })\n events.push({ atMs: atMs + 1, event: { type: 'tool_result', id: `call_${tool}`, output: 'ok' } })\n }\n const kind = part % 2 === 0 ? 'reasoning' : 'text'\n const partId = `prt_${part}`\n events.push({ atMs, event: { type: 'raw', data: { type: 'raw', backend: 'opencode', event: { type: kind, timestamp: atMs, part: { id: partId, type: kind, metadata: { at: atMs } } } } } })\n events.push({ atMs, event: { type: 'model-processing', data: { elapsedMs: atMs } } })\n events.push({ atMs, event: { type: kind, text: `t${index} ` } })\n }\n return events\n}\n\nexport interface CoalescedTurnOptions {\n subject: string\n /**\n * Start persisting one turn through the app's real turn persistence (its turn\n * store and buffer, as its chat route builds them). `detach` hands the turn\n * to a durable owner the way the route's completion handoff does; omit it when\n * the app has no detached lane.\n */\n open: (turnId: string) => Promise<{\n onEvent(event: unknown): Promise<void>\n detach?(): Promise<void>\n done(): Promise<void>\n }>\n /** Stored events for the turn. */\n count: (turnId: string) => Promise<number>\n maxEvents?: number\n fixture?: readonly TimedTurnEvent[]\n}\n\n/** The recorded long turn stores at most 5,000 events, attached and after a handoff. */\nexport async function checkCoalescedTurn(options: CoalescedTurnOptions): Promise<InvariantVerdict> {\n const maxEvents = options.maxEvents ?? LAUNCH_BUDGETS.turnEvents\n const fixture = options.fixture ?? recordedLongTurn()\n const findings: string[] = []\n const stored: Record<string, number> = {}\n const real = Date.now\n for (const lane of ['attached', 'detached'] as const) {\n const turnId = `invariant-long-turn-${lane}`\n const start = real()\n let clock = start\n Date.now = () => clock\n try {\n const tap = await options.open(turnId)\n if (lane === 'detached' && !tap.detach) continue\n for (const [index, item] of fixture.entries()) {\n clock = start + item.atMs\n await tap.onEvent(item.event)\n if (lane === 'detached' && index === 0) await tap.detach!()\n }\n clock = start + (fixture.at(-1)?.atMs ?? 0) + 1\n await tap.done()\n stored[lane] = await options.count(turnId)\n } finally {\n Date.now = real\n }\n if (stored[lane] === 0) findings.push(`${lane}: the turn stored no events; the check did not reach the app's turn store`)\n if (stored[lane]! > maxEvents) findings.push(`${lane}: the recorded long turn (${fixture.length.toLocaleString('en-US')} events) stored ${stored[lane]!.toLocaleString('en-US')}; the most is ${maxEvents.toLocaleString('en-US')}`)\n }\n return {\n invariant: 'coalesced-events',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : Object.entries(stored).map(([lane, count]) => `${lane}: ${fixture.length.toLocaleString('en-US')} events stored as ${count.toLocaleString('en-US')}`),\n data: { fixtureEvents: fixture.length, stored },\n }\n}\n\n// ── limit alarms ─────────────────────────────────────────────────────────────\n\n/** Hard platform limits a declared budget may not exceed. */\nexport const PLATFORM_LIMITS = {\n /** A Worker isolate's memory. */\n 'worker-memory': 128 * MB,\n /** Platform snapshots per sandbox; the cap GTM hit on 2026-10-10. */\n 'snapshot-count': 25,\n /** Requests per minute per operator key. */\n 'key-rate': 60,\n} as const\n\nexport interface LimitAlarmCheckOptions {\n subject: string\n /** Build the app's real limit alarms (its budgets and wiring) over a capturing sink. */\n create: (sink: AlertSink) => LimitAlarms | Promise<LimitAlarms>\n}\n\n/** Every resource alarms at 80% and not below, escalates at the limit, and no budget exceeds the platform's. */\nexport async function checkLimitAlarms(options: LimitAlarmCheckOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const resource of LIMIT_RESOURCES) {\n const delivered: TurnHealthAlert[] = []\n const alarms = await options.create({ deliver: async (alert) => { delivered.push(alert) } })\n const limit = alarms.budgets[resource]\n const platform = (PLATFORM_LIMITS as Partial<Record<string, number>>)[resource]\n if (platform !== undefined && limit > platform) findings.push(`${resource}: the declared limit ${limit} is above the platform's ${platform}`)\n await alarms.observe(resource, limit * 0.79)\n if (delivered.length) findings.push(`${resource}: alarmed at 79% of its limit`)\n await alarms.observe(resource, limit * LAUNCH_BUDGETS.alarmRatio)\n if (delivered.length !== 1 || delivered[0]?.severity !== 'warning') findings.push(`${resource}: did not warn at 80% of its limit`)\n await alarms.observe(resource, limit)\n if (delivered.length !== 2 || delivered[1]?.severity !== 'critical') findings.push(`${resource}: did not raise a critical alert at its limit`)\n }\n return {\n invariant: 'limit-alarms',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [`${LIMIT_RESOURCES.join(', ')} warn at 80% and page at the limit`],\n }\n}\n\nexport {\n buildConformanceReport,\n formatConformanceReport,\n readDeploymentFacts,\n readVerdicts,\n type ConformanceReport,\n type DeploymentFacts,\n type InvariantReport,\n type InvariantStatus,\n type LaunchInvariantsConfig,\n} from './conformance.js'\n","/**\n * The conformance report: which launch invariants an app holds.\n *\n * `agent-app-invariants` runs the app's invariant tests with\n * `AGENT_APP_INVARIANTS_RESULTS` set, reads the verdicts they recorded, and\n * checks what it can see without the app's code: the crons each wrangler\n * environment configures, and whether the app has a D1 binding at all. An\n * invariant passes when at least one verdict was recorded for it and every\n * recorded verdict passed. Not applicable is accepted only where the\n * deployment shows it: no configured crons, or no D1 binding.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { LAUNCH_INVARIANTS, type InvariantVerdict, type LaunchInvariantId } from './catalog.js'\nimport { parseWranglerCrons } from './schedule.js'\n\n/** `launch-invariants.config.mjs` (or `.json`) at the app root. */\nexport interface LaunchInvariantsConfig {\n /** The app's name in the report. */\n product: string\n /** The command that runs the app's invariant tests, e.g. `pnpm exec vitest run tests/launch-invariants.test.ts`. */\n test: string\n /** Wrangler configs, relative to the app root. Default: the first of wrangler.toml, wrangler.jsonc, wrangler.json. */\n wrangler?: readonly string[]\n /** Invariants the deployment shows do not apply, with the reason. */\n notApplicable?: Partial<Record<LaunchInvariantId, string>>\n}\n\n/** What the deployment declares, read from its wrangler configs. */\nexport interface DeploymentFacts {\n wranglerFiles: string[]\n configuredCrons: string[]\n hasD1: boolean\n}\n\nexport type InvariantStatus = 'pass' | 'fail' | 'not-applicable'\n\nexport interface InvariantReport {\n id: LaunchInvariantId\n title: string\n status: InvariantStatus\n /** Why it failed or does not apply; on a pass, what was proven. */\n lines: string[]\n verdicts: number\n}\n\nexport interface ConformanceReport {\n product: string\n pass: boolean\n passed: number\n total: number\n testExitCode: number | null\n invariants: InvariantReport[]\n facts: DeploymentFacts\n}\n\n/** Read the crons and D1 bindings the app's wrangler configs declare. */\nexport function readDeploymentFacts(appDir: string, files?: readonly string[]): DeploymentFacts {\n const candidates = files ?? ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json'].filter((file) => existsSync(join(appDir, file))).slice(0, 1)\n const crons = new Set<string>()\n let hasD1 = false\n for (const file of candidates) {\n const source = readFileSync(join(appDir, file), 'utf8')\n const json = /\\.jsonc?$/.test(file)\n const parsed = parseWranglerCrons(source, json ? 'json' : 'toml')\n for (const cron of [...parsed.top, ...Object.values(parsed.envs).flat()]) crons.add(cron)\n if (json ? /\"d1_databases\"\\s*:\\s*\\[\\s*\\{/.test(source) : /^\\s*\\[\\[(?:env\\.[^.\\]]+\\.)?d1_databases\\]\\]/m.test(source)) hasD1 = true\n }\n return { wranglerFiles: [...candidates], configuredCrons: [...crons], hasD1 }\n}\n\nconst NOT_APPLICABLE_WHEN: Partial<Record<LaunchInvariantId, { holds: (facts: DeploymentFacts) => boolean; condition: string }>> = {\n 'isolated-jobs': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'memory-budget': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'bounded-reads': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n 'auth-survives-d1-stall': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n}\n\n/** Parse the results file the invariant tests appended to. */\nexport function readVerdicts(source: string): InvariantVerdict[] {\n return source.split('\\n').filter((line) => line.trim()).flatMap((line) => {\n try {\n return [JSON.parse(line) as InvariantVerdict]\n } catch {\n return []\n }\n })\n}\n\n/** Judge each invariant from the recorded verdicts and the deployment facts. */\nexport function buildConformanceReport(input: {\n config: LaunchInvariantsConfig\n facts: DeploymentFacts\n verdicts: readonly InvariantVerdict[]\n testExitCode: number | null\n}): ConformanceReport {\n const { config, facts } = input\n const invariants = LAUNCH_INVARIANTS.map((invariant): InvariantReport => {\n const verdicts = input.verdicts.filter((verdict) => verdict.invariant === invariant.id)\n const reason = config.notApplicable?.[invariant.id]\n if (reason !== undefined) {\n const rule = NOT_APPLICABLE_WHEN[invariant.id]\n if (rule?.holds(facts)) return { id: invariant.id, title: invariant.title, status: 'not-applicable', lines: [`${reason} (verified: ${rule.condition})`], verdicts: verdicts.length }\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [rule\n ? `declared not applicable (\"${reason}\"), but the deployment does not show ${rule.condition}`\n : `declared not applicable (\"${reason}\"), but this invariant applies to every agent app`],\n verdicts: verdicts.length,\n }\n }\n if (verdicts.length === 0) {\n return { id: invariant.id, title: invariant.title, status: 'fail', lines: [`no check recorded a verdict; ${invariant.rule}`], verdicts: 0 }\n }\n const failed = verdicts.filter((verdict) => !verdict.pass)\n const lines = failed.length\n ? failed.flatMap((verdict) => verdict.details.map((detail) => `${verdict.subject}: ${detail}`))\n : verdicts.map((verdict) => `${verdict.subject}: ${verdict.details[0] ?? 'passed'}`)\n if (invariant.id === 'isolated-jobs' && failed.length === 0) {\n const checked = new Set(verdicts.flatMap((verdict) => (verdict.data?.configuredCrons as string[] | undefined) ?? []))\n const unchecked = facts.configuredCrons.filter((cron) => !checked.has(cron))\n if (unchecked.length) {\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [`the check did not read every configured cron: ${unchecked.map((cron) => `\"${cron}\"`).join(', ')} (from ${facts.wranglerFiles.join(', ')})`],\n verdicts: verdicts.length,\n }\n }\n }\n return { id: invariant.id, title: invariant.title, status: failed.length ? 'fail' : 'pass', lines, verdicts: verdicts.length }\n })\n const passed = invariants.filter((invariant) => invariant.status !== 'fail').length\n return {\n product: config.product,\n pass: passed === invariants.length && input.testExitCode === 0,\n passed,\n total: invariants.length,\n testExitCode: input.testExitCode,\n invariants,\n facts,\n }\n}\n\n/** The report as the CLI prints it. */\nexport function formatConformanceReport(report: ConformanceReport): string {\n const mark: Record<InvariantStatus, string> = { pass: 'PASS', fail: 'FAIL', 'not-applicable': 'N/A ' }\n const lines = [`launch invariants — ${report.product}: ${report.passed} of ${report.total} hold`]\n for (const invariant of report.invariants) {\n lines.push(` ${mark[invariant.status]} ${invariant.id} — ${invariant.title}`)\n const shown = invariant.status === 'fail' ? invariant.lines : invariant.lines.slice(0, 3)\n for (const line of shown) lines.push(` ${line}`)\n if (invariant.status !== 'fail' && invariant.lines.length > shown.length) lines.push(` … ${invariant.lines.length - shown.length} more`)\n }\n if (report.testExitCode !== 0) lines.push(` the invariant test command exited ${report.testExitCode ?? 'by signal'}`)\n lines.push(report.pass ? 'RESULT: launch-grade' : 'RESULT: not launch-grade')\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;;;AAaA,SAAS,sBAAsB;AAC/B,OAAO,QAAQ;AACf,OAAO,QAAQ;;;ACJf,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AA6Cd,SAAS,oBAAoB,QAAgB,OAA4C;AAC9F,QAAM,aAAa,SAAS,CAAC,iBAAiB,kBAAkB,eAAe,EAAE,OAAO,CAAC,SAAS,WAAW,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC;AAC5I,QAAM,QAAQ,oBAAI,IAAY;AAC9B,MAAI,QAAQ;AACZ,aAAW,QAAQ,YAAY;AAC7B,UAAM,SAAS,aAAa,KAAK,QAAQ,IAAI,GAAG,MAAM;AACtD,UAAM,OAAO,YAAY,KAAK,IAAI;AAClC,UAAM,SAAS,mBAAmB,QAAQ,OAAO,SAAS,MAAM;AAChE,eAAW,QAAQ,CAAC,GAAG,OAAO,KAAK,GAAG,OAAO,OAAO,OAAO,IAAI,EAAE,KAAK,CAAC,EAAG,OAAM,IAAI,IAAI;AACxF,QAAI,OAAO,+BAA+B,KAAK,MAAM,IAAI,+CAA+C,KAAK,MAAM,EAAG,SAAQ;AAAA,EAChI;AACA,SAAO,EAAE,eAAe,CAAC,GAAG,UAAU,GAAG,iBAAiB,CAAC,GAAG,KAAK,GAAG,MAAM;AAC9E;AAEA,IAAM,sBAA6H;AAAA,EACjI,iBAAiB,EAAE,OAAO,CAAC,UAAU,MAAM,gBAAgB,WAA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