@tangle-network/agent-app 0.60.240 → 0.60.241
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/{chunk-YNM44SQC.js → chunk-5OXWETUE.js} +16 -2
- package/dist/chunk-5OXWETUE.js.map +1 -0
- package/dist/rollout/cli.d.ts +3 -0
- package/dist/rollout/cli.js +9 -3
- package/dist/rollout/cli.js.map +1 -1
- package/dist/rollout/d1.js +2 -1
- package/dist/rollout/d1.js.map +1 -1
- package/dist/rollout/index.d.ts +3 -1
- package/dist/rollout/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-YNM44SQC.js.map +0 -1
|
@@ -86,6 +86,7 @@ function assignRolloutArm(turnId, treatmentPct) {
|
|
|
86
86
|
for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619);
|
|
87
87
|
return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? "treatment" : "control";
|
|
88
88
|
}
|
|
89
|
+
var DEFAULT_MEASUREMENT_TIMEOUT_MS = 5e3;
|
|
89
90
|
async function decideRollout(input) {
|
|
90
91
|
const { plan, fromValue, toValue } = input;
|
|
91
92
|
validateRolloutPlan(plan);
|
|
@@ -117,9 +118,20 @@ async function decideRollout(input) {
|
|
|
117
118
|
if (target > current + 1) return record("refused", [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map((stage) => stage.name).join(", ")}`], null);
|
|
118
119
|
}
|
|
119
120
|
if (!fromStage) return record("allowed", [], null);
|
|
121
|
+
const timeoutMs = input.measurementTimeoutMs ?? DEFAULT_MEASUREMENT_TIMEOUT_MS;
|
|
122
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("measurementTimeoutMs must be positive");
|
|
123
|
+
const abort = new AbortController();
|
|
124
|
+
let timer;
|
|
120
125
|
let measured;
|
|
121
126
|
try {
|
|
122
|
-
|
|
127
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
128
|
+
timer = setTimeout(() => {
|
|
129
|
+
const error = new Error("measurement timed out");
|
|
130
|
+
abort.abort(error);
|
|
131
|
+
reject(error);
|
|
132
|
+
}, timeoutMs);
|
|
133
|
+
});
|
|
134
|
+
measured = await Promise.race([input.measure(fromStage, abort.signal), deadline]);
|
|
123
135
|
} catch (error) {
|
|
124
136
|
return record(
|
|
125
137
|
narrowing ? "allowed" : "undecided",
|
|
@@ -127,6 +139,8 @@ async function decideRollout(input) {
|
|
|
127
139
|
null,
|
|
128
140
|
{ [fromStage.name]: fromStage.minSamples }
|
|
129
141
|
);
|
|
142
|
+
} finally {
|
|
143
|
+
clearTimeout(timer);
|
|
130
144
|
}
|
|
131
145
|
const lane = measured?.lane ?? fromStage.name;
|
|
132
146
|
const requirements = { ...measured?.sampleRequirements };
|
|
@@ -157,4 +171,4 @@ export {
|
|
|
157
171
|
assignRolloutArm,
|
|
158
172
|
decideRollout
|
|
159
173
|
};
|
|
160
|
-
//# sourceMappingURL=chunk-
|
|
174
|
+
//# sourceMappingURL=chunk-5OXWETUE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rollout/index.ts"],"sourcesContent":["/**\n * Rollout guard: a staged rollout widens only when the stage it leaves met\n * that stage's kill lines on measured production numbers.\n *\n * WHY. Hospitality's routed lane widened from two QA workspaces to `*` at a\n * first-words p50 of 3.54 s, past kill lines of 2.5 s and 3.0 s\n * (hospitality-agent #382, 2026-10-11). The numbers existed; nothing read them\n * before the list changed. This module is the one place that reads them.\n *\n * THE LIST. A rollout is one comma-separated value, usually a deploy variable\n * such as `HOSPITALITY_ROUTED_BUSINESS_IDS`: workspace ids, `*` for every\n * workspace, `!<id>` to keep one out whatever else matches, and\n * `new-since:<ISO time>` for workspaces created at or after that time.\n * {@link rolloutAdmits} is the reference reading of that grammar.\n *\n * THE RULE ({@link decideRollout}).\n * - Narrowing is always allowed. Holds and widenings measure the current stage.\n * - A widening must land on a declared stage, the next one after the current\n * value's stage, never past it.\n * - The stage being left must have at least `minSamples` measured turns and\n * every kill line met. A missing metric leaves the decision undecided.\n * - Missing samples are undecided; a measured breach names each reason (`first_words_p50_ms 3540 over kill line 2500`).\n *\n * Every decision, allowed, refused or undecided, is returned as one record the caller\n * persists (the CLI appends it to a JSONL ledger and hands it to the\n * config's `record`).\n */\n\n/** A kill line: the measured value must stay at or under `max` and at or over `min`. */\nexport interface RolloutKillLine {\n max?: number\n min?: number\n}\n\nexport interface RolloutStage {\n /** Short name used in refusals and records, e.g. `qa`, `all-but-recenter`. */\n name: string\n /** The exact list value that defines this stage. */\n value: string\n /** Turns the stage must have served, measured, before the rollout may leave it. */\n minSamples: number\n /** Metric name → line. Metric names are the product's, e.g. `first_words_p50_ms`, `failure_rate`. */\n kill: Record<string, RolloutKillLine>\n}\n\nexport interface RolloutPlan {\n /** e.g. `hospitality-routed-chat`. */\n name: string\n /** The deploy variable that carries the list, e.g. `HOSPITALITY_ROUTED_BUSINESS_IDS`. */\n variable: string\n /** In widening order. */\n stages: RolloutStage[]\n}\n\n/** Production numbers for one stage, from the product's own instrument. */\nexport interface StageMeasurement {\n stage: string\n samples: number\n /** Lane name for the stage sample floor; defaults to the stage name. */\n lane?: string\n /** Additional lane sample floors, evaluated as missing evidence rather than breaches. */\n sampleRequirements?: Record<string, { samples: number; minSamples: number }>\n metrics: Record<string, number | null | undefined>\n /** Where the numbers came from (ledger, query, soak), for the record. */\n source?: string\n window?: { from: string; to: string }\n}\n\nexport interface RolloutDecision {\n rollout: string\n variable: string\n from: { value: string; stage: string | null }\n to: { value: string; stage: string | null }\n widens: boolean\n decision: 'allowed' | 'refused' | 'undecided'\n recommendation: 'widen' | 'hold' | 'narrow' | 'refuse'\n turnsNeeded: Record<string, number>\n /** Breaches or evidence deficits, including observations made while narrowing. */\n reasons: string[]\n measured: StageMeasurement | null\n at: string\n}\n\nexport interface ParsedRolloutList {\n all: boolean\n ids: ReadonlySet<string>\n excluded: ReadonlySet<string>\n /** Epoch ms of each `new-since:` entry. */\n newSince: readonly number[]\n}\n\nexport function parseRolloutList(value: string | null | undefined): ParsedRolloutList {\n const ids = new Set<string>()\n const excluded = new Set<string>()\n const newSince: number[] = []\n let all = false\n for (const raw of (value ?? '').split(',')) {\n const entry = raw.trim()\n if (!entry) continue\n if (entry === '*') all = true\n else if (entry.startsWith('!')) excluded.add(entry.slice(1).trim())\n else if (entry.startsWith('new-since:')) {\n const at = Date.parse(entry.slice('new-since:'.length))\n if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`)\n newSince.push(at)\n } else ids.add(entry)\n }\n return { all, ids, excluded, newSince }\n}\n\n/** Whether a list admits one workspace. `createdAt` (epoch ms) is needed only for `new-since:` entries. */\nexport function rolloutAdmits(value: string | ParsedRolloutList, workspace: { id: string; createdAt?: number }): boolean {\n const list = typeof value === 'string' ? parseRolloutList(value) : value\n if (list.excluded.has(workspace.id)) return false\n if (list.all || list.ids.has(workspace.id)) return true\n return workspace.createdAt !== undefined && list.newSince.some(at => workspace.createdAt! >= at)\n}\n\n/**\n * Whether `to` may admit a workspace `from` does not. Conservative: a change it\n * cannot prove narrower counts as a widening.\n */\nexport function rolloutWidens(fromValue: string, toValue: string): boolean {\n const from = parseRolloutList(fromValue)\n const to = parseRolloutList(toValue)\n if (to.all) {\n if (!from.all) return true\n // Under `*` on both sides, only a dropped exclusion widens.\n return [...from.excluded].some(id => !to.excluded.has(id))\n }\n if ([...to.ids].some(id => !rolloutAdmits(from, { id }))) return true\n // An id `from` admitted only because it was listed, which `to` now excludes, narrows; nothing else here widens.\n const earliest = (list: ParsedRolloutList) => list.newSince.length ? Math.min(...list.newSince) : Infinity\n if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true\n return false\n}\n\n/** Canonical form for matching a value to a stage: entries trimmed and sorted. */\nexport function normalizeRolloutValue(value: string): string {\n return value.split(',').map(entry => entry.trim()).filter(Boolean).sort().join(',')\n}\n\nfunction stageOf(plan: RolloutPlan, value: string): RolloutStage | null {\n const key = normalizeRolloutValue(value)\n return plan.stages.find(stage => normalizeRolloutValue(stage.value) === key) ?? null\n}\n\n/** Finite measured breaches only. Missing observations and sample floors are evidence deficits. */\nexport function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[] {\n if (!measured || measured.stage !== stage.name) return []\n return Object.entries(stage.kill).flatMap(([metric, line]) => {\n const value = measured.metrics[metric]\n if (typeof value !== 'number' || !Number.isFinite(value)) return []\n return [\n ...(line.max !== undefined && value > line.max ? [`${metric} ${value} over kill line ${line.max}`] : []),\n ...(line.min !== undefined && value < line.min && !metric.endsWith('samples') ? [`${metric} ${value} under kill line ${line.min}`] : []),\n ]\n })\n}\n\nexport function validateRolloutPlan(plan: RolloutPlan): void {\n if (!plan.name || !plan.variable) throw new Error('a rollout plan needs a name and a variable')\n if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`)\n const names = new Set<string>()\n const values = new Set<string>()\n for (const stage of plan.stages) {\n if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`)\n names.add(stage.name)\n const value = normalizeRolloutValue(stage.value)\n if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`)\n values.add(value)\n parseRolloutList(stage.value)\n if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {\n throw new Error(`stage ${stage.name} needs minSamples of at least 1`)\n }\n if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`)\n }\n for (let index = 1; index < plan.stages.length; index++) {\n const previous = plan.stages[index - 1]!\n const stage = plan.stages[index]!\n if (!rolloutWidens(previous.value, stage.value)) {\n throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`)\n }\n }\n}\n\n/** Stable per-turn percentage assignment; the product records the returned arm on its row and trace. */\nexport function assignRolloutArm(turnId: string, treatmentPct: number): 'control' | 'treatment' {\n if (!Number.isFinite(treatmentPct) || treatmentPct < 0 || treatmentPct > 100) {\n throw new RangeError('treatmentPct must be between 0 and 100')\n }\n let hash = 2166136261\n for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619)\n return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? 'treatment' : 'control'\n}\n\nconst DEFAULT_MEASUREMENT_TIMEOUT_MS = 5_000\n\n/** Measure the current stage for widening, holding and narrowing. Narrowing always remains available. */\nexport async function decideRollout(input: {\n plan: RolloutPlan\n fromValue: string\n toValue: string\n measure(stage: RolloutStage, signal?: AbortSignal): Promise<StageMeasurement | null>\n /** Bound observation even when the product instrument ignores cancellation. */\n measurementTimeoutMs?: number\n now?: () => Date\n}): Promise<RolloutDecision> {\n const { plan, fromValue, toValue } = input\n validateRolloutPlan(plan)\n const fromStage = stageOf(plan, fromValue)\n const toStage = stageOf(plan, toValue)\n const widens = rolloutWidens(fromValue, toValue)\n const narrowing = !widens && normalizeRolloutValue(fromValue) !== normalizeRolloutValue(toValue)\n const record = (decision: RolloutDecision['decision'], reasons: string[], measured: StageMeasurement | null,\n turnsNeeded: Record<string, number> = {}, breach = false): RolloutDecision => ({\n rollout: plan.name, variable: plan.variable,\n from: { value: fromValue, stage: fromStage?.name ?? null },\n to: { value: toValue, stage: toStage?.name ?? null }, widens, decision,\n recommendation: narrowing || breach ? 'narrow' : decision === 'refused' ? 'refuse' : decision === 'undecided' ? 'hold' : widens ? 'widen' : 'hold',\n turnsNeeded, reasons, measured, at: (input.now?.() ?? new Date()).toISOString(),\n })\n if (widens) {\n if (!toStage) return record('refused', [`${toValue} is not a declared stage of ${plan.name}`], null)\n const target = plan.stages.indexOf(toStage)\n if (!fromStage) {\n const empty = !normalizeRolloutValue(fromValue)\n return empty && target === 0 ? record('allowed', [], null)\n : record('refused', [`the current value ${fromValue || '(empty)'} is not a declared stage of ${plan.name}`], null)\n }\n const current = plan.stages.indexOf(fromStage)\n if (target > current + 1) return record('refused', [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map(stage => stage.name).join(', ')}`], null)\n }\n if (!fromStage) return record('allowed', [], null)\n const timeoutMs = input.measurementTimeoutMs ?? DEFAULT_MEASUREMENT_TIMEOUT_MS\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError('measurementTimeoutMs must be positive')\n const abort = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let measured: StageMeasurement | null\n try {\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n const error = new Error('measurement timed out')\n abort.abort(error)\n reject(error)\n }, timeoutMs)\n })\n measured = await Promise.race([input.measure(fromStage, abort.signal), deadline])\n }\n catch (error) {\n return record(narrowing ? 'allowed' : 'undecided', [`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null,\n { [fromStage.name]: fromStage.minSamples })\n } finally {\n clearTimeout(timer)\n }\n const lane = measured?.lane ?? fromStage.name\n const requirements = { ...measured?.sampleRequirements }\n requirements[lane] = {\n samples: Math.min(measured?.samples ?? 0, requirements[lane]?.samples ?? Infinity),\n minSamples: Math.max(fromStage.minSamples, requirements[lane]?.minSamples ?? 0),\n }\n // Older product configs expressed control floors as *_samples minimum kill lines.\n for (const [metric, line] of Object.entries(fromStage.kill)) {\n if (metric.endsWith('samples') && line.min !== undefined) {\n requirements[metric] = { samples: measured?.metrics[metric] ?? 0, minSamples: line.min }\n }\n }\n const turnsNeeded = Object.fromEntries(Object.entries(requirements)\n .map(([lane, floor]) => [lane, Math.max(0, Math.ceil(floor.minSamples - (Number.isFinite(floor.samples) ? floor.samples : 0)))] as const)\n .filter(([, needed]) => needed > 0))\n const measuredStage = measured?.stage === fromStage.name\n const breaches = killLineBreaches(fromStage, measured)\n const missing = !measuredStage ? [`stage ${fromStage.name} has no matching measurement`]\n : Object.keys(fromStage.kill).filter(metric => !Number.isFinite(measured!.metrics[metric])).map(metric => `${metric} was not measured`)\n const reasons = [...breaches, ...missing, ...Object.entries(turnsNeeded).map(([lane, needed]) => `${lane} needs ${needed} more turns`)]\n return record(narrowing ? 'allowed' : breaches.length ? 'ref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C;AACtI,SAAO,OAAO,YAAY,YAAY,SAAS,SAAS,YAAY,QAAQ,SAAS,cAAc,WAAW,SAAS,UAAU,aAAa,SAAS,SAAS,CAAC;AACnK;","names":["reasons","measured","turnsNeeded","lane"]}
|
package/dist/rollout/cli.d.ts
CHANGED
|
@@ -5,7 +5,10 @@ export interface RolloutConfig {
|
|
|
5
5
|
measure(input: {
|
|
6
6
|
plan: RolloutPlan;
|
|
7
7
|
stage: RolloutStage;
|
|
8
|
+
signal?: AbortSignal;
|
|
8
9
|
}): Promise<StageMeasurement | null>;
|
|
10
|
+
/** Shared observation deadline; see decideRollout. */
|
|
11
|
+
measurementTimeoutMs?: number;
|
|
9
12
|
record?(decision: RolloutDecision): Promise<void> | void;
|
|
10
13
|
/** Default `wrangler.toml`. */
|
|
11
14
|
wrangler?: string;
|
package/dist/rollout/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
decideRollout
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-5OXWETUE.js";
|
|
5
5
|
import {
|
|
6
6
|
invokedAsScript
|
|
7
7
|
} from "../chunk-C3CAYGGQ.js";
|
|
@@ -88,7 +88,13 @@ async function runRolloutCheck(args) {
|
|
|
88
88
|
for (const plan of plans) {
|
|
89
89
|
const fromValue = args.from ?? readWranglerVar(base, plan.variable) ?? "";
|
|
90
90
|
const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? "";
|
|
91
|
-
const decision = await decideRollout({
|
|
91
|
+
const decision = await decideRollout({
|
|
92
|
+
plan,
|
|
93
|
+
fromValue,
|
|
94
|
+
toValue,
|
|
95
|
+
measure: (stage, signal) => config.measure({ plan, stage, signal }),
|
|
96
|
+
measurementTimeoutMs: config.measurementTimeoutMs
|
|
97
|
+
});
|
|
92
98
|
decisions.push(decision);
|
|
93
99
|
const ledger = resolve(args.appDir, args.record);
|
|
94
100
|
mkdirSync(dirname(ledger), { recursive: true });
|
|
@@ -125,7 +131,7 @@ async function main() {
|
|
|
125
131
|
}
|
|
126
132
|
if (invokedAsScript(import.meta.url, process.argv[1])) {
|
|
127
133
|
main().then((code) => {
|
|
128
|
-
process.
|
|
134
|
+
process.stdout.write("", () => process.stderr.write("", () => process.exit(code)));
|
|
129
135
|
});
|
|
130
136
|
}
|
|
131
137
|
export {
|
package/dist/rollout/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-rollout-check` — refuse a deploy that widens a staged rollout\n * before the stage it leaves met its kill lines.\n *\n * Runs in the app's repo, in the step that ships (ship.sh verify, or the PR\n * check). Add `rollout.config.mjs` at the root:\n *\n * export default {\n * plans: [{\n * name: 'hospitality-routed-chat',\n * variable: 'HOSPITALITY_ROUTED_BUSINESS_IDS',\n * stages: [\n * { name: 'qa', value: 'ws-a,ws-b', minSamples: 30,\n * kill: { first_words_p50_ms: { max: 2500 }, failure_rate: { max: 0 } } },\n * { name: 'all', value: '*', minSamples: 200,\n * kill: { first_words_p50_ms: { max: 1500 }, failure_rate: { max: 0.01 } } },\n * ],\n * }],\n * // The product's own instrument: production numbers for the stage being left.\n * async measure({ plan, stage }) { return { stage: stage.name, samples, metrics: { … }, source } },\n * // Optional: keep the decision somewhere durable as well as the JSONL ledger.\n * async record(decision) {},\n * }\n *\n * The new value is read from the `[vars]` of wrangler.toml; the current one\n * from the same file at `--base` (default `origin/main`), or given with\n * `--from`. `--to` overrides the new value.\n *\n * Usage: agent-app-rollout-check [appDir] [--config <file>] [--base <git ref>]\n * [--from <value>] [--to <value>] [--plan <name>] [--record <jsonl>]\n * Exits 0 when allowed, 1 for a measured refusal, 3 for insufficient widening evidence, 2 on a usage error. Undecided holds exit 0.\n */\nimport { execFileSync } from 'node:child_process'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { decideRollout, type RolloutDecision, type RolloutPlan, type RolloutStage, type StageMeasurement } from './index.js'\n\nexport interface RolloutConfig {\n plans: RolloutPlan[]\n measure(input: { plan: RolloutPlan; stage: RolloutStage }): Promise<StageMeasurement | null>\n record?(decision: RolloutDecision): Promise<void> | void\n /** Default `wrangler.toml`. */\n wrangler?: string\n}\n\ninterface CliArgs {\n appDir: string\n config?: string\n base: string\n from?: string\n to?: string\n plan?: string\n record: string\n}\n\nconst CONFIG_NAMES = ['rollout.config.mjs', 'rollout.config.js']\n\nfunction parseArgs(argv: readonly string[]): CliArgs {\n const args: CliArgs = { appDir: process.cwd(), base: 'origin/main', record: '.rollout/decisions.jsonl' }\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index]!\n const value = () => {\n const next = argv[++index]\n if (next === undefined) throw new Error(`${arg} needs a value`)\n return next\n }\n if (arg === '--config') args.config = value()\n else if (arg === '--base') args.base = value()\n else if (arg === '--from') args.from = value()\n else if (arg === '--to') args.to = value()\n else if (arg === '--plan') args.plan = value()\n else if (arg === '--record') args.record = value()\n else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)\n else args.appDir = resolve(arg)\n }\n return args\n}\n\n/** A top-level `[vars]` string value from wrangler.toml source; environments are not read. */\nexport function readWranglerVar(source: string, name: string): string | null {\n let inVars = false\n for (const line of source.split('\\n')) {\n const header = line.match(/^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/)\n if (header) {\n inVars = header[1]!.trim() === 'vars'\n continue\n }\n if (!inVars) continue\n const entry = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (entry && entry[1] === name) return JSON.parse(`\"${entry[2]}\"`) as string\n }\n return null\n}\n\nasync function loadConfig(appDir: string, explicit?: string): Promise<RolloutConfig> {\n const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map(name => join(appDir, name)).find(path => existsSync(path))\n if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`)\n const config = ((await import(pathToFileURL(file).href)) as { default: RolloutConfig }).default\n if (!Array.isArray(config?.plans) || typeof config.measure !== 'function') {\n throw new Error(`${file} must export { plans, measure }`)\n }\n return config\n}\n\nfunction gitShow(cwd: string, spec: string): string | null {\n try {\n return execFileSync('git', ['show', spec], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n } catch {\n return null\n }\n}\n\n/**\n * The file at `ref`. Under agent-app-signoff the app runs in a clean copy with\n * no `.git`; signoff names the source checkout and the copy's root, so the\n * base is read from the source at the same repo-relative path.\n */\nfunction wranglerAt(appDir: string, file: string, ref: string, env: NodeJS.ProcessEnv = process.env): string {\n const local = gitShow(appDir, `${ref}:./${file}`)\n if (local !== null) return local\n const source = env.SIGNOFF_SOURCE_REPO\n const tree = env.SIGNOFF_TREE\n if (source && tree) {\n const path = relative(resolve(tree), resolve(appDir, file))\n if (!path.startsWith('..') && !isAbsolute(path)) {\n const fromSource = gitShow(source, `${ref}:${path.split(sep).join('/')}`)\n if (fromSource !== null) return fromSource\n }\n }\n throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`)\n}\n\nexport async function runRolloutCheck(args: CliArgs): Promise<RolloutDecision[]> {\n const config = await loadConfig(args.appDir, args.config)\n const file = config.wrangler ?? 'wrangler.toml'\n const plans = args.plan ? config.plans.filter(plan => plan.name === args.plan) : config.plans\n if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : 'the config declares no plans')\n if (plans.length > 1 && (args.from !== undefined || args.to !== undefined)) throw new Error('--from and --to need --plan')\n const head = readFileSync(join(args.appDir, file), 'utf8')\n const base = args.from === undefined ? wranglerAt(args.appDir, file, args.base) : null\n const decisions: RolloutDecision[] = []\n for (const plan of plans) {\n const fromValue = args.from ?? readWranglerVar(base!, plan.variable) ?? ''\n const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? ''\n const decision = await decideRollout({ plan, fromValue, toValue, measure: stage => config.measure({ plan, stage }) })\n decisions.push(decision)\n const ledger = resolve(args.appDir, args.record)\n mkdirSync(dirname(ledger), { recursive: true })\n appendFileSync(ledger, `${JSON.stringify(decision)}\\n`)\n await config.record?.(decision)\n }\n return decisions\n}\n\nfunction describe(decision: RolloutDecision): string {\n const move = `${decision.from.stage ?? decision.from.value ?? '(empty)'} -> ${decision.to.stage ?? decision.to.value}`\n if (decision.decision === 'allowed') {\n return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? '' : ' (not a widening)'}`\n }\n return `rollout ${decision.rollout}: ${decision.decision.toUpperCase()} ${move} (${decision.recommendation})\\n${decision.reasons.map(reason => ` - ${reason}`).join('\\n')}`\n}\n\nasync function main(): Promise<number> {\n let args: CliArgs\n try {\n args = parseArgs(process.argv.slice(2))\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 2\n }\n try {\n const decisions = await runRolloutCheck(args)\n for (const decision of decisions) console.log(describe(decision))\n return decisions.some(decision => decision.decision === 'refused') ? 1 : decisions.some(decision => decision.decision === 'undecided' && decision.widens) ? 3 : 0\n } catch (error) {\n console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n main().then(code => { process.exitCode = code })\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY,WAAW,oBAAoB;AACpE,SAAS,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAClE,SAAS,qBAAqB;AAsB9B,IAAM,eAAe,CAAC,sBAAsB,mBAAmB;AAE/D,SAAS,UAAU,MAAkC;AACnD,QAAM,OAAgB,EAAE,QAAQ,QAAQ,IAAI,GAAG,MAAM,eAAe,QAAQ,2BAA2B;AACvG,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,S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AAQ,IAAI,YAAU,OAAO,MAAM,EAAE,EAAE,KAAK,IAAI,CAAC;AAC5K;AAEA,eAAe,OAAwB;AACrC,MAAI;AACJ,MAAI;AACF,WAAO,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAAA,EACxC,SAAS,OAAO;AACd,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,YAAY,MAAM,gBAAgB,IAAI;AAC5C,eAAW,YAAY,UAAW,SAAQ,IAAI,SAAS,QAAQ,CAAC;AAChE,WAAO,UAAU,KAAK,cAAY,SAAS,aAAa,SAAS,IAAI,IAAI,UAAU,KAAK,cAAY,SAAS,aAAa,eAAe,SAAS,MAAM,IAAI,IAAI;AAAA,EAClK,SAAS,OAAO;AACd,YAAQ,MAAM,4BAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAClG,WAAO;AAAA,EACT;AACF;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AACrD,OAAK,EAAE,KAAK,UAAQ;AAAE,YAAQ,WAAW;AAAA,EAAK,CAAC;AACjD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-rollout-check` — refuse a deploy that widens a staged rollout\n * before the stage it leaves met its kill lines.\n *\n * Runs in the app's repo, in the step that ships (ship.sh verify, or the PR\n * check). Add `rollout.config.mjs` at the root:\n *\n * export default {\n * plans: [{\n * name: 'hospitality-routed-chat',\n * variable: 'HOSPITALITY_ROUTED_BUSINESS_IDS',\n * stages: [\n * { name: 'qa', value: 'ws-a,ws-b', minSamples: 30,\n * kill: { first_words_p50_ms: { max: 2500 }, failure_rate: { max: 0 } } },\n * { name: 'all', value: '*', minSamples: 200,\n * kill: { first_words_p50_ms: { max: 1500 }, failure_rate: { max: 0.01 } } },\n * ],\n * }],\n * // The product's own instrument: production numbers for the stage being left.\n * async measure({ plan, stage }) { return { stage: stage.name, samples, metrics: { … }, source } },\n * // Optional: keep the decision somewhere durable as well as the JSONL ledger.\n * async record(decision) {},\n * }\n *\n * The new value is read from the `[vars]` of wrangler.toml; the current one\n * from the same file at `--base` (default `origin/main`), or given with\n * `--from`. `--to` overrides the new value.\n *\n * Usage: agent-app-rollout-check [appDir] [--config <file>] [--base <git ref>]\n * [--from <value>] [--to <value>] [--plan <name>] [--record <jsonl>]\n * Exits 0 when allowed, 1 for a measured refusal, 3 for insufficient widening evidence, 2 on a usage error. Undecided holds exit 0.\n */\nimport { execFileSync } from 'node:child_process'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { decideRollout, type RolloutDecision, type RolloutPlan, type RolloutStage, type StageMeasurement } from './index.js'\n\nexport interface RolloutConfig {\n plans: RolloutPlan[]\n measure(input: { plan: RolloutPlan; stage: RolloutStage; signal?: AbortSignal }): Promise<StageMeasurement | null>\n /** Shared observation deadline; see decideRollout. */\n measurementTimeoutMs?: number\n record?(decision: RolloutDecision): Promise<void> | void\n /** Default `wrangler.toml`. */\n wrangler?: string\n}\n\ninterface CliArgs {\n appDir: string\n config?: string\n base: string\n from?: string\n to?: string\n plan?: string\n record: string\n}\n\nconst CONFIG_NAMES = ['rollout.config.mjs', 'rollout.config.js']\n\nfunction parseArgs(argv: readonly string[]): CliArgs {\n const args: CliArgs = { appDir: process.cwd(), base: 'origin/main', record: '.rollout/decisions.jsonl' }\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index]!\n const value = () => {\n const next = argv[++index]\n if (next === undefined) throw new Error(`${arg} needs a value`)\n return next\n }\n if (arg === '--config') args.config = value()\n else if (arg === '--base') args.base = value()\n else if (arg === '--from') args.from = value()\n else if (arg === '--to') args.to = value()\n else if (arg === '--plan') args.plan = value()\n else if (arg === '--record') args.record = value()\n else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)\n else args.appDir = resolve(arg)\n }\n return args\n}\n\n/** A top-level `[vars]` string value from wrangler.toml source; environments are not read. */\nexport function readWranglerVar(source: string, name: string): string | null {\n let inVars = false\n for (const line of source.split('\\n')) {\n const header = line.match(/^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/)\n if (header) {\n inVars = header[1]!.trim() === 'vars'\n continue\n }\n if (!inVars) continue\n const entry = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (entry && entry[1] === name) return JSON.parse(`\"${entry[2]}\"`) as string\n }\n return null\n}\n\nasync function loadConfig(appDir: string, explicit?: string): Promise<RolloutConfig> {\n const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map(name => join(appDir, name)).find(path => existsSync(path))\n if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`)\n const config = ((await import(pathToFileURL(file).href)) as { default: RolloutConfig }).default\n if (!Array.isArray(config?.plans) || typeof config.measure !== 'function') {\n throw new Error(`${file} must export { plans, measure }`)\n }\n return config\n}\n\nfunction gitShow(cwd: string, spec: string): string | null {\n try {\n return execFileSync('git', ['show', spec], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n } catch {\n return null\n }\n}\n\n/**\n * The file at `ref`. Under agent-app-signoff the app runs in a clean copy with\n * no `.git`; signoff names the source checkout and the copy's root, so the\n * base is read from the source at the same repo-relative path.\n */\nfunction wranglerAt(appDir: string, file: string, ref: string, env: NodeJS.ProcessEnv = process.env): string {\n const local = gitShow(appDir, `${ref}:./${file}`)\n if (local !== null) return local\n const source = env.SIGNOFF_SOURCE_REPO\n const tree = env.SIGNOFF_TREE\n if (source && tree) {\n const path = relative(resolve(tree), resolve(appDir, file))\n if (!path.startsWith('..') && !isAbsolute(path)) {\n const fromSource = gitShow(source, `${ref}:${path.split(sep).join('/')}`)\n if (fromSource !== null) return fromSource\n }\n }\n throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`)\n}\n\nexport async function runRolloutCheck(args: CliArgs): Promise<RolloutDecision[]> {\n const config = await loadConfig(args.appDir, args.config)\n const file = config.wrangler ?? 'wrangler.toml'\n const plans = args.plan ? config.plans.filter(plan => plan.name === args.plan) : config.plans\n if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : 'the config declares no plans')\n if (plans.length > 1 && (args.from !== undefined || args.to !== undefined)) throw new Error('--from and --to need --plan')\n const head = readFileSync(join(args.appDir, file), 'utf8')\n const base = args.from === undefined ? wranglerAt(args.appDir, file, args.base) : null\n const decisions: RolloutDecision[] = []\n for (const plan of plans) {\n const fromValue = args.from ?? readWranglerVar(base!, plan.variable) ?? ''\n const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? ''\n const decision = await decideRollout({\n plan, fromValue, toValue,\n measure: (stage, signal) => config.measure({ plan, stage, signal }),\n measurementTimeoutMs: config.measurementTimeoutMs,\n })\n decisions.push(decision)\n const ledger = resolve(args.appDir, args.record)\n mkdirSync(dirname(ledger), { recursive: true })\n appendFileSync(ledger, `${JSON.stringify(decision)}\\n`)\n await config.record?.(decision)\n }\n return decisions\n}\n\nfunction describe(decision: RolloutDecision): string {\n const move = `${decision.from.stage ?? decision.from.value ?? '(empty)'} -> ${decision.to.stage ?? decision.to.value}`\n if (decision.decision === 'allowed') {\n return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? '' : ' (not a widening)'}`\n }\n return `rollout ${decision.rollout}: ${decision.decision.toUpperCase()} ${move} (${decision.recommendation})\\n${decision.reasons.map(reason => ` - ${reason}`).join('\\n')}`\n}\n\nasync function main(): Promise<number> {\n let args: CliArgs\n try {\n args = parseArgs(process.argv.slice(2))\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 2\n }\n try {\n const decisions = await runRolloutCheck(args)\n for (const decision of decisions) console.log(describe(decision))\n return decisions.some(decision => decision.decision === 'refused') ? 1 : decisions.some(decision => decision.decision === 'undecided' && decision.widens) ? 3 : 0\n } catch (error) {\n console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n // A timed-out product instrument can leave an uncooperative socket open.\n // All durable records are awaited by main; flush the receipt before ending the CLI.\n main().then(code => {\n process.stdout.write('', () => process.stderr.write('', () => process.exit(code)))\n })\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY,WAAW,oBAAoB;AACpE,SAAS,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAClE,SAAS,qBAAqB;AAwB9B,IAAM,eAAe,CAAC,sBAAsB,mBAAmB;AAE/D,SAAS,UAAU,MAAkC;AACnD,QAAM,OAAgB,EAAE,QAAQ,QAAQ,IAAI,GAAG,MAAM,eAAe,QAAQ,2BAA2B;AACvG,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,MAAM,KAAK,KAAK;AACtB,UAAM,QAAQ,MAAM;AAClB,YAAM,OAAO,KAAK,EAAE,KAAK;AACzB,UAAI,SAAS,OAAW,OAAM,IAAI,MAAM,GAAG,GAAG,gBAAgB;AAC9D,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,WAAY,MAAK,SAAS,MAAM;AAAA,aACnC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,OAAQ,MAAK,KAAK,MAAM;AAAA,aAChC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,WAAY,MAAK,SAAS,MAAM;AAAA,aACxC,IAAI,WAAW,IAAI,EAAG,OAAM,IAAI,MAAM,kBAAkB,GAAG,EAAE;AAAA,QACjE,MAA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,eAAe,SAAS,MAAM,IAAI,IAAI;AAAA,EAClK,SAAS,OAAO;AACd,YAAQ,MAAM,4BAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAClG,WAAO;AAAA,EACT;AACF;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AAGrD,OAAK,EAAE,KAAK,UAAQ;AAClB,YAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,KAAK,IAAI,CAAC,CAAC;AAAA,EACnF,CAAC;AACH;","names":[]}
|
package/dist/rollout/d1.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
rolloutAdmits
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-5OXWETUE.js";
|
|
4
4
|
|
|
5
5
|
// src/rollout/d1.ts
|
|
6
6
|
var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
|
|
@@ -93,6 +93,7 @@ function createD1TurnTimingStore(options) {
|
|
|
93
93
|
const rows = results.filter((row) => rolloutAdmits(input.stage.value, { id: row.workspace_id })).map((row) => ({ firstVisibleMs: row.first_visible_ms ?? void 0, firstTextMs: row.first_text_ms ?? void 0, settledMs: row.settled_ms, failed: row.failed === 1 }));
|
|
94
94
|
return {
|
|
95
95
|
stage: input.stage.name,
|
|
96
|
+
lane: input.lane,
|
|
96
97
|
samples: rows.length,
|
|
97
98
|
metrics: stageMetrics(rows),
|
|
98
99
|
source: `rollout_turn_timing lane=${input.lane}`,
|
package/dist/rollout/d1.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n arm?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstVisibleMs === undefined ? null : Math.round(row.firstVisibleMs),\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now(),\n row.admissionMs === undefined ? null : Math.round(row.admissionMs),\n row.model ?? null, row.revision ?? null, row.arm ?? null).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to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c,MAAM,MAAM,OAAO,EAAE,IAAI,IAAI,aAAa,CAAC,CAAC,EACxE,IAAI,UAAQ,EAAE,gBAAgB,IAAI,oBAAoB,QAAW,aAAa,IAAI,iBAAiB,QAAW,WAAW,IAAI,YAAY,QAAQ,IAAI,WAAW,EAAE,EAAE;AACvK,aAAO;AAAA,QACL,OAAO,MAAM,MAAM;AAAA,QACnB,SAAS,KAAK;AAAA,QACd,SAAS,aAAa,IAAI;AAAA,QAC1B,QAAQ,4BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\nexport interface TurnTimingRow {\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n arm?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstVisibleMs === undefined ? null : Math.round(row.firstVisibleMs),\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now(),\n row.admissionMs === undefined ? null : Math.round(row.admissionMs),\n row.model ?? null, row.revision ?? null, row.arm ?? null).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;AAuBO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBvC,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BvD,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,CAAC,CAAC;AACrF;AAGO,SAAS,aAAa,MAAqG;AAChI,QAAM,eAAe,KAAK,QAAQ,SAAO,IAAI,kBAAkB,OAA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ts
CHANGED
|
@@ -117,6 +117,8 @@ export declare function decideRollout(input: {
|
|
|
117
117
|
plan: RolloutPlan;
|
|
118
118
|
fromValue: string;
|
|
119
119
|
toValue: string;
|
|
120
|
-
measure(stage: RolloutStage): Promise<StageMeasurement | null>;
|
|
120
|
+
measure(stage: RolloutStage, signal?: AbortSignal): Promise<StageMeasurement | null>;
|
|
121
|
+
/** Bound observation even when the product instrument ignores cancellation. */
|
|
122
|
+
measurementTimeoutMs?: number;
|
|
121
123
|
now?: () => Date;
|
|
122
124
|
}): Promise<RolloutDecision>;
|
package/dist/rollout/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rollout/index.ts"],"sourcesContent":["/**\n * Rollout guard: a staged rollout widens only when the stage it leaves met\n * that stage's kill lines on measured production numbers.\n *\n * WHY. Hospitality's routed lane widened from two QA workspaces to `*` at a\n * first-words p50 of 3.54 s, past kill lines of 2.5 s and 3.0 s\n * (hospitality-agent #382, 2026-10-11). The numbers existed; nothing read them\n * before the list changed. This module is the one place that reads them.\n *\n * THE LIST. A rollout is one comma-separated value, usually a deploy variable\n * such as `HOSPITALITY_ROUTED_BUSINESS_IDS`: workspace ids, `*` for every\n * workspace, `!<id>` to keep one out whatever else matches, and\n * `new-since:<ISO time>` for workspaces created at or after that time.\n * {@link rolloutAdmits} is the reference reading of that grammar.\n *\n * THE RULE ({@link decideRollout}).\n * - Narrowing is always allowed. Holds and widenings measure the current stage.\n * - A widening must land on a declared stage, the next one after the current\n * value's stage, never past it.\n * - The stage being left must have at least `minSamples` measured turns and\n * every kill line met. A missing metric leaves the decision undecided.\n * - Missing samples are undecided; a measured breach names each reason (`first_words_p50_ms 3540 over kill line 2500`).\n *\n * Every decision, allowed, refused or undecided, is returned as one record the caller\n * persists (the CLI appends it to a JSONL ledger and hands it to the\n * config's `record`).\n */\n\n/** A kill line: the measured value must stay at or under `max` and at or over `min`. */\nexport interface RolloutKillLine {\n max?: number\n min?: number\n}\n\nexport interface RolloutStage {\n /** Short name used in refusals and records, e.g. `qa`, `all-but-recenter`. */\n name: string\n /** The exact list value that defines this stage. */\n value: string\n /** Turns the stage must have served, measured, before the rollout may leave it. */\n minSamples: number\n /** Metric name → line. Metric names are the product's, e.g. `first_words_p50_ms`, `failure_rate`. */\n kill: Record<string, RolloutKillLine>\n}\n\nexport interface RolloutPlan {\n /** e.g. `hospitality-routed-chat`. */\n name: string\n /** The deploy variable that carries the list, e.g. `HOSPITALITY_ROUTED_BUSINESS_IDS`. */\n variable: string\n /** In widening order. */\n stages: RolloutStage[]\n}\n\n/** Production numbers for one stage, from the product's own instrument. */\nexport interface StageMeasurement {\n stage: string\n samples: number\n /** Lane name for the stage sample floor; defaults to the stage name. */\n lane?: string\n /** Additional lane sample floors, evaluated as missing evidence rather than breaches. */\n sampleRequirements?: Record<string, { samples: number; minSamples: number }>\n metrics: Record<string, number | null | undefined>\n /** Where the numbers came from (ledger, query, soak), for the record. */\n source?: string\n window?: { from: string; to: string }\n}\n\nexport interface RolloutDecision {\n rollout: string\n variable: string\n from: { value: string; stage: string | null }\n to: { value: string; stage: string | null }\n widens: boolean\n decision: 'allowed' | 'refused' | 'undecided'\n recommendation: 'widen' | 'hold' | 'narrow' | 'refuse'\n turnsNeeded: Record<string, number>\n /** Breaches or evidence deficits, including observations made while narrowing. */\n reasons: string[]\n measured: StageMeasurement | null\n at: string\n}\n\nexport interface ParsedRolloutList {\n all: boolean\n ids: ReadonlySet<string>\n excluded: ReadonlySet<string>\n /** Epoch ms of each `new-since:` entry. */\n newSince: readonly number[]\n}\n\nexport function parseRolloutList(value: string | null | undefined): ParsedRolloutList {\n const ids = new Set<string>()\n const excluded = new Set<string>()\n const newSince: number[] = []\n let all = false\n for (const raw of (value ?? '').split(',')) {\n const entry = raw.trim()\n if (!entry) continue\n if (entry === '*') all = true\n else if (entry.startsWith('!')) excluded.add(entry.slice(1).trim())\n else if (entry.startsWith('new-since:')) {\n const at = Date.parse(entry.slice('new-since:'.length))\n if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`)\n newSince.push(at)\n } else ids.add(entry)\n }\n return { all, ids, excluded, newSince }\n}\n\n/** Whether a list admits one workspace. `createdAt` (epoch ms) is needed only for `new-since:` entries. */\nexport function rolloutAdmits(value: string | ParsedRolloutList, workspace: { id: string; createdAt?: number }): boolean {\n const list = typeof value === 'string' ? parseRolloutList(value) : value\n if (list.excluded.has(workspace.id)) return false\n if (list.all || list.ids.has(workspace.id)) return true\n return workspace.createdAt !== undefined && list.newSince.some(at => workspace.createdAt! >= at)\n}\n\n/**\n * Whether `to` may admit a workspace `from` does not. Conservative: a change it\n * cannot prove narrower counts as a widening.\n */\nexport function rolloutWidens(fromValue: string, toValue: string): boolean {\n const from = parseRolloutList(fromValue)\n const to = parseRolloutList(toValue)\n if (to.all) {\n if (!from.all) return true\n // Under `*` on both sides, only a dropped exclusion widens.\n return [...from.excluded].some(id => !to.excluded.has(id))\n }\n if ([...to.ids].some(id => !rolloutAdmits(from, { id }))) return true\n // An id `from` admitted only because it was listed, which `to` now excludes, narrows; nothing else here widens.\n const earliest = (list: ParsedRolloutList) => list.newSince.length ? Math.min(...list.newSince) : Infinity\n if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true\n return false\n}\n\n/** Canonical form for matching a value to a stage: entries trimmed and sorted. */\nexport function normalizeRolloutValue(value: string): string {\n return value.split(',').map(entry => entry.trim()).filter(Boolean).sort().join(',')\n}\n\nfunction stageOf(plan: RolloutPlan, value: string): RolloutStage | null {\n const key = normalizeRolloutValue(value)\n return plan.stages.find(stage => normalizeRolloutValue(stage.value) === key) ?? null\n}\n\n/** Finite measured breaches only. Missing observations and sample floors are evidence deficits. */\nexport function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[] {\n if (!measured || measured.stage !== stage.name) return []\n return Object.entries(stage.kill).flatMap(([metric, line]) => {\n const value = measured.metrics[metric]\n if (typeof value !== 'number' || !Number.isFinite(value)) return []\n return [\n ...(line.max !== undefined && value > line.max ? [`${metric} ${value} over kill line ${line.max}`] : []),\n ...(line.min !== undefined && value < line.min && !metric.endsWith('samples') ? [`${metric} ${value} under kill line ${line.min}`] : []),\n ]\n })\n}\n\nexport function validateRolloutPlan(plan: RolloutPlan): void {\n if (!plan.name || !plan.variable) throw new Error('a rollout plan needs a name and a variable')\n if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`)\n const names = new Set<string>()\n const values = new Set<string>()\n for (const stage of plan.stages) {\n if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`)\n names.add(stage.name)\n const value = normalizeRolloutValue(stage.value)\n if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`)\n values.add(value)\n parseRolloutList(stage.value)\n if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {\n throw new Error(`stage ${stage.name} needs minSamples of at least 1`)\n }\n if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`)\n }\n for (let index = 1; index < plan.stages.length; index++) {\n const previous = plan.stages[index - 1]!\n const stage = plan.stages[index]!\n if (!rolloutWidens(previous.value, stage.value)) {\n throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`)\n }\n }\n}\n\n/** Stable per-turn percentage assignment; the product records the returned arm on its row and trace. */\nexport function assignRolloutArm(turnId: string, treatmentPct: number): 'control' | 'treatment' {\n if (!Number.isFinite(treatmentPct) || treatmentPct < 0 || treatmentPct > 100) {\n throw new RangeError('treatmentPct must be between 0 and 100')\n }\n let hash = 2166136261\n for (let i = 0; i < turnId.length; i++) hash = Math.imul(hash ^ turnId.charCodeAt(i), 16777619)\n return (hash >>> 0) / 2 ** 32 < treatmentPct / 100 ? 'treatment' : 'control'\n}\n\n/** Measure the current stage for widening, holding and narrowing. Narrowing always remains available. */\nexport async function decideRollout(input: {\n plan: RolloutPlan\n fromValue: string\n toValue: string\n measure(stage: RolloutStage): Promise<StageMeasurement | null>\n now?: () => Date\n}): Promise<RolloutDecision> {\n const { plan, fromValue, toValue } = input\n validateRolloutPlan(plan)\n const fromStage = stageOf(plan, fromValue)\n const toStage = stageOf(plan, toValue)\n const widens = rolloutWidens(fromValue, toValue)\n const narrowing = !widens && normalizeRolloutValue(fromValue) !== normalizeRolloutValue(toValue)\n const record = (decision: RolloutDecision['decision'], reasons: string[], measured: StageMeasurement | null,\n turnsNeeded: Record<string, number> = {}, breach = false): RolloutDecision => ({\n rollout: plan.name, variable: plan.variable,\n from: { value: fromValue, stage: fromStage?.name ?? null },\n to: { value: toValue, stage: toStage?.name ?? null }, widens, decision,\n recommendation: narrowing || breach ? 'narrow' : decision === 'refused' ? 'refuse' : decision === 'undecided' ? 'hold' : widens ? 'widen' : 'hold',\n turnsNeeded, reasons, measured, at: (input.now?.() ?? new Date()).toISOString(),\n })\n if (widens) {\n if (!toStage) return record('refused', [`${toValue} is not a declared stage of ${plan.name}`], null)\n const target = plan.stages.indexOf(toStage)\n if (!fromStage) {\n const empty = !normalizeRolloutValue(fromValue)\n return empty && target === 0 ? record('allowed', [], null)\n : record('refused', [`the current value ${fromValue || '(empty)'} is not a declared stage of ${plan.name}`], null)\n }\n const current = plan.stages.indexOf(fromStage)\n if (target > current + 1) return record('refused', [`${toStage.name} skips ${plan.stages.slice(current + 1, target).map(stage => stage.name).join(', ')}`], null)\n }\n if (!fromStage) return record('allowed', [], null)\n let measured: StageMeasurement | null\n try { measured = await input.measure(fromStage) }\n catch (error) {\n return record(narrowing ? 'allowed' : 'undecided', [`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null,\n { [fromStage.name]: fromStage.minSamples })\n }\n const lane = measured?.lane ?? fromStage.name\n const requirements = { ...measured?.sampleRequirements }\n requirements[lane] = {\n samples: Math.min(measured?.samples ?? 0, requirements[lane]?.samples ?? Infinity),\n minSamples: Math.max(fromStage.minSamples, requirements[lane]?.minSamples ?? 0),\n }\n // Older product configs expressed control floors as *_samples minimum kill lines.\n for (const [metric, line] of Object.entries(fromStage.kill)) {\n if (metric.endsWith('samples') && line.min !== undefined) {\n requirements[metric] = { samples: measured?.metrics[metric] ?? 0, minSamples: line.min }\n }\n }\n const turnsNeeded = Object.fromEntries(Object.entries(requirements)\n .map(([lane, floor]) => [lane, Math.max(0, Math.ceil(floor.minSamples - (Number.isFinite(floor.samples) ? floor.samples : 0)))] as const)\n .filter(([, needed]) => needed > 0))\n const measuredStage = measured?.stage === fromStage.name\n const breaches = killLineBreaches(fromStage, measured)\n const missing = !measuredStage ? [`stage ${fromStage.name} has no matching measurement`]\n : Object.keys(fromStage.kill).filter(metric => !Number.isFinite(measured!.metrics[metric])).map(metric => `${metric} was not measured`)\n const reasons = [...breaches, ...missing, ...Object.entries(turnsNeeded).map(([lane, needed]) => `${lane} needs ${needed} more turns`)]\n return record(narrowing ? 'allowed' : breaches.length ? 'refused' : reasons.length ? 'undecided' : 'allowed', reasons, measured, turnsNeeded, breaches.length > 0)\n}\n"],"mappings":";AA2FO,SAAS,iBAAiB,OAAqD;AACpF,QAAM,MAAM,oBAAI,IAAY;AAC5B,QAAM,WAAW,oBAAI,IAAY;AACjC,QAAM,WAAqB,CAAC;AAC5B,MAAI,MAAM;AACV,aAAW,QAAQ,SAAS,IAAI,MAAM,GAAG,GAAG;AAC1C,UAAM,QAAQ,IAAI,KAAK;AACvB,QAAI,CAAC,MAAO;AACZ,QAAI,UAAU,IAAK,OAAM;AAAA,aAChB,MAAM,WAAW,GAAG,EAAG,UAAS,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,CAAC;AAAA,aACzD,MAAM,WAAW,YAAY,GAAG;AACvC,YAAM,KAAK,KAAK,MAAM,MAAM,MAAM,aAAa,MAAM,CAAC;AACtD,UAAI,CAAC,OAAO,SAAS,EAAE,EAAG,OAAM,IAAI,MAAM,sBAAsB,KAAK,sBAAsB;AAC3F,eAAS,KAAK,EAAE;AAAA,IAClB,MAAO,KAAI,IAAI,KAAK;AAAA,EACtB;AACA,SAAO,EAAE,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