@tangle-network/agent-app 0.60.239 → 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.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createChatTurnRoutes,
3
3
  streamChatRouteAsSandboxEvents
4
- } from "../chunk-QW6PFYJS.js";
4
+ } from "../chunk-LSXJJL4I.js";
5
5
  import "../chunk-TCGZFSN5.js";
6
6
  import "../chunk-FENBDSIW.js";
7
7
  import "../chunk-RN4WPTBH.js";
@@ -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;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  decideRollout
4
- } from "../chunk-4JUEOVQS.js";
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({ plan, fromValue, toValue, measure: (stage) => config.measure({ plan, stage }) });
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 });
@@ -103,7 +109,7 @@ function describe(decision) {
103
109
  if (decision.decision === "allowed") {
104
110
  return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? "" : " (not a widening)"}`;
105
111
  }
106
- return `rollout ${decision.rollout}: REFUSED ${move}
112
+ return `rollout ${decision.rollout}: ${decision.decision.toUpperCase()} ${move} (${decision.recommendation})
107
113
  ${decision.reasons.map((reason) => ` - ${reason}`).join("\n")}`;
108
114
  }
109
115
  async function main() {
@@ -117,7 +123,7 @@ async function main() {
117
123
  try {
118
124
  const decisions = await runRolloutCheck(args);
119
125
  for (const decision of decisions) console.log(describe(decision));
120
- return decisions.some((decision) => decision.decision === "refused") ? 1 : 0;
126
+ return decisions.some((decision) => decision.decision === "refused") ? 1 : decisions.some((decision) => decision.decision === "undecided" && decision.widens) ? 3 : 0;
121
127
  } catch (error) {
122
128
  console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`);
123
129
  return 2;
@@ -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.exitCode = code;
134
+ process.stdout.write("", () => process.stderr.write("", () => process.exit(code)));
129
135
  });
130
136
  }
131
137
  export {
@@ -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 every plan's change is allowed, 1 when one is refused, 2 on a usage error.\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}: REFUSED ${move}\\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 : 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 =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EA,SAAS,SAAS,UAAmC;AACnD,QAAM,OAAO,GAAG,SAAS,KAAK,SAAS,SAAS,KAAK,SAAS,SAAS,OAAO,SAAS,GAAG,SAAS,SAAS,GAAG,KAAK;AACpH,MAAI,SAAS,aAAa,WAAW;AACnC,WAAO,WAAW,SAAS,OAAO,aAAa,IAAI,GAAG,SAAS,SAAS,KAAK,mBAAmB;AAAA,EAClG;AACA,SAAO,WAAW,SAAS,OAAO,aAAa,IAAI;AAAA,EAAK,SAAS,QAAQ,IAAI,YAAU,OAAO,MAAM,EAAE,EAAE,KAAK,IAAI,CAAC;AACpH;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;AAAA,EAC3E,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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AAU,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;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":[]}
@@ -21,10 +21,17 @@ export interface D1LikeForRollout {
21
21
  };
22
22
  };
23
23
  }
24
- export declare 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 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";
24
+ export declare 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";
25
25
  /** Apply once through the product migration runner to existing tables; historical rows stay NULL. */
26
26
  export declare const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL = "ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;";
27
+ /** Apply once through the product migration runner; old rows remain unknown. */
28
+ export declare 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";
27
29
  export interface TurnTimingRow {
30
+ /** Request receipt to lifecycle start, before the existing relative durations. */
31
+ admissionMs?: number;
32
+ model?: string;
33
+ revision?: string;
34
+ arm?: string;
28
35
  turnId: string;
29
36
  /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */
30
37
  rollout: string;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  rolloutAdmits
3
- } from "../chunk-4JUEOVQS.js";
3
+ } from "../chunk-5OXWETUE.js";
4
4
 
5
5
  // src/rollout/d1.ts
6
6
  var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
@@ -9,6 +9,10 @@ CREATE TABLE IF NOT EXISTS rollout_turn_timing (
9
9
  rollout TEXT NOT NULL,
10
10
  workspace_id TEXT NOT NULL,
11
11
  lane TEXT NOT NULL,
12
+ admission_ms INTEGER,
13
+ model TEXT,
14
+ revision TEXT,
15
+ arm TEXT,
12
16
  first_visible_ms INTEGER,
13
17
  first_text_ms INTEGER,
14
18
  settled_ms INTEGER NOT NULL,
@@ -19,6 +23,12 @@ CREATE TABLE IF NOT EXISTS rollout_turn_timing (
19
23
  CREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);
20
24
  `;
21
25
  var ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL = `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`;
26
+ var ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `
27
+ ALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;
28
+ ALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;
29
+ ALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;
30
+ ALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;
31
+ `;
22
32
  var MEASURE_ROW_LIMIT = 2e4;
23
33
  function percentile(sorted, p) {
24
34
  if (!sorted.length) return null;
@@ -47,8 +57,8 @@ function createD1TurnTimingStore(options) {
47
57
  try {
48
58
  await options.db.prepare(
49
59
  `INSERT OR IGNORE INTO rollout_turn_timing
50
- (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at)
51
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
60
+ (turn_id, rollout, workspace_id, lane, first_visible_ms, first_text_ms, settled_ms, failed, failure_code, at, admission_ms, model, revision, arm)
61
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
52
62
  ).bind(
53
63
  row.turnId,
54
64
  row.rollout,
@@ -59,7 +69,11 @@ function createD1TurnTimingStore(options) {
59
69
  Math.round(row.settledMs),
60
70
  row.failed ? 1 : 0,
61
71
  row.failureCode ?? null,
62
- row.at ?? now()
72
+ row.at ?? now(),
73
+ row.admissionMs === void 0 ? null : Math.round(row.admissionMs),
74
+ row.model ?? null,
75
+ row.revision ?? null,
76
+ row.arm ?? null
63
77
  ).run();
64
78
  } catch (error) {
65
79
  console.error(JSON.stringify({
@@ -79,6 +93,7 @@ function createD1TurnTimingStore(options) {
79
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 }));
80
94
  return {
81
95
  stage: input.stage.name,
96
+ lane: input.lane,
82
97
  samples: rows.length,
83
98
  metrics: stageMetrics(rows),
84
99
  source: `rollout_turn_timing lane=${input.lane}`,
@@ -89,6 +104,7 @@ function createD1TurnTimingStore(options) {
89
104
  }
90
105
  export {
91
106
  ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL,
107
+ ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL,
92
108
  ROLLOUT_TURN_TIMING_SCHEMA_SQL,
93
109
  createD1TurnTimingStore,
94
110
  stageMetrics
@@ -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 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\nexport interface TurnTimingRow {\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)\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()).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: 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;AAiBvC,IAAM,kDACX;AAqBF,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,OAAO,CAAC,IAAI,CAAC,IAAI,cAAc,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AACrH,QAAM,aAAa,KAAK,QAAQ,SAAO,IAAI,gBAAgB,UAAa,IAAI,gBAAgB,OAAO,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAC/I,QAAM,UAAU,KAAK,OAAO,SAAO,CAAC,IAAI,MAAM,EAAE,IAAI,SAAO,IAAI,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAC9F,SAAO;AAAA,IACL,sBAAsB,WAAW,cAAc,EAAE;AAAA,IACjD,sBAAsB,WAAW,cAAc,EAAE;AAAA,IACjD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AK,MAAM,SAAS,MAAM,MAAM,MAAM,OAAO,iBAAiB,EAAE,IAE/D;AACH,YAAM,OAAO,QACV,OAAO,SAAO,cAAc,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,C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I,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -14,16 +14,14 @@
14
14
  * {@link rolloutAdmits} is the reference reading of that grammar.
15
15
  *
16
16
  * THE RULE ({@link decideRollout}).
17
- * - A change that admits no workspace the current value did not (a narrowing,
18
- * a rollback, the same stage) is always allowed: a guard that can block a
19
- * rollback is worse than none.
17
+ * - Narrowing is always allowed. Holds and widenings measure the current stage.
20
18
  * - A widening must land on a declared stage, the next one after the current
21
19
  * value's stage, never past it.
22
20
  * - The stage being left must have at least `minSamples` measured turns and
23
- * every kill line met. A metric that was not measured fails its line.
24
- * - A refusal names each reason (`first_words_p50_ms 3540 over kill line 2500`).
21
+ * every kill line met. A missing metric leaves the decision undecided.
22
+ * - Missing samples are undecided; a measured breach names each reason (`first_words_p50_ms 3540 over kill line 2500`).
25
23
  *
26
- * Every decision, allowed or refused, is returned as one record the caller
24
+ * Every decision, allowed, refused or undecided, is returned as one record the caller
27
25
  * persists (the CLI appends it to a JSONL ledger and hands it to the
28
26
  * config's `record`).
29
27
  */
@@ -54,6 +52,13 @@ export interface RolloutPlan {
54
52
  export interface StageMeasurement {
55
53
  stage: string;
56
54
  samples: number;
55
+ /** Lane name for the stage sample floor; defaults to the stage name. */
56
+ lane?: string;
57
+ /** Additional lane sample floors, evaluated as missing evidence rather than breaches. */
58
+ sampleRequirements?: Record<string, {
59
+ samples: number;
60
+ minSamples: number;
61
+ }>;
57
62
  metrics: Record<string, number | null | undefined>;
58
63
  /** Where the numbers came from (ledger, query, soak), for the record. */
59
64
  source?: string;
@@ -74,8 +79,10 @@ export interface RolloutDecision {
74
79
  stage: string | null;
75
80
  };
76
81
  widens: boolean;
77
- decision: 'allowed' | 'refused';
78
- /** Empty when allowed; each refusal reason otherwise. */
82
+ decision: 'allowed' | 'refused' | 'undecided';
83
+ recommendation: 'widen' | 'hold' | 'narrow' | 'refuse';
84
+ turnsNeeded: Record<string, number>;
85
+ /** Breaches or evidence deficits, including observations made while narrowing. */
79
86
  reasons: string[];
80
87
  measured: StageMeasurement | null;
81
88
  at: string;
@@ -100,17 +107,18 @@ export declare function rolloutAdmits(value: string | ParsedRolloutList, workspa
100
107
  export declare function rolloutWidens(fromValue: string, toValue: string): boolean;
101
108
  /** Canonical form for matching a value to a stage: entries trimmed and sorted. */
102
109
  export declare function normalizeRolloutValue(value: string): string;
103
- /** Each kill line the measurement misses, as a reason. Empty when every line holds. */
110
+ /** Finite measured breaches only. Missing observations and sample floors are evidence deficits. */
104
111
  export declare function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[];
105
112
  export declare function validateRolloutPlan(plan: RolloutPlan): void;
106
- /**
107
- * Decide one change of the list. `measure` is called only for a widening, and
108
- * only for the stage being left.
109
- */
113
+ /** Stable per-turn percentage assignment; the product records the returned arm on its row and trace. */
114
+ export declare function assignRolloutArm(turnId: string, treatmentPct: number): 'control' | 'treatment';
115
+ /** Measure the current stage for widening, holding and narrowing. Narrowing always remains available. */
110
116
  export declare function decideRollout(input: {
111
117
  plan: RolloutPlan;
112
118
  fromValue: string;
113
119
  toValue: string;
114
- 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;
115
123
  now?: () => Date;
116
124
  }): Promise<RolloutDecision>;
@@ -1,4 +1,5 @@
1
1
  import {
2
+ assignRolloutArm,
2
3
  decideRollout,
3
4
  killLineBreaches,
4
5
  normalizeRolloutValue,
@@ -6,8 +7,9 @@ import {
6
7
  rolloutAdmits,
7
8
  rolloutWidens,
8
9
  validateRolloutPlan
9
- } from "../chunk-4JUEOVQS.js";
10
+ } from "../chunk-5OXWETUE.js";
10
11
  export {
12
+ assignRolloutArm,
11
13
  decideRollout,
12
14
  killLineBreaches,
13
15
  normalizeRolloutValue,
@@ -100,7 +100,7 @@ import {
100
100
  warmBinOf,
101
101
  warmWeekdayOf,
102
102
  writeProfileFilesToBox
103
- } from "../chunk-GNWGP3PA.js";
103
+ } from "../chunk-P2E5TZUZ.js";
104
104
  import {
105
105
  EGRESS_PROXY_RECOVERY_PHASE,
106
106
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -31,6 +31,8 @@ export declare class SandboxRunError extends Error {
31
31
  }
32
32
  /** The engine's per-call tool context (`RouterTurnToolContext`), kept structural so this module does not import the engine. */
33
33
  export interface SandboxToolContext {
34
+ /** The engine-resolved member request, including checkpoint continuation. */
35
+ userMessage?: string;
34
36
  emit(kind: string, data?: unknown): void;
35
37
  /** The turn's trace and this call's `tool.call` span (`runRouterTurn` supplies both). The box claim, the box run and the
36
38
  * trace id sent to the Sandbox API follow from them; without them nothing is recorded. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.239",
3
+ "version": "0.60.241",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1,134 +0,0 @@
1
- // src/rollout/index.ts
2
- function parseRolloutList(value) {
3
- const ids = /* @__PURE__ */ new Set();
4
- const excluded = /* @__PURE__ */ new Set();
5
- const newSince = [];
6
- let all = false;
7
- for (const raw of (value ?? "").split(",")) {
8
- const entry = raw.trim();
9
- if (!entry) continue;
10
- if (entry === "*") all = true;
11
- else if (entry.startsWith("!")) excluded.add(entry.slice(1).trim());
12
- else if (entry.startsWith("new-since:")) {
13
- const at = Date.parse(entry.slice("new-since:".length));
14
- if (!Number.isFinite(at)) throw new Error(`rollout list entry ${entry} is not a valid time`);
15
- newSince.push(at);
16
- } else ids.add(entry);
17
- }
18
- return { all, ids, excluded, newSince };
19
- }
20
- function rolloutAdmits(value, workspace) {
21
- const list = typeof value === "string" ? parseRolloutList(value) : value;
22
- if (list.excluded.has(workspace.id)) return false;
23
- if (list.all || list.ids.has(workspace.id)) return true;
24
- return workspace.createdAt !== void 0 && list.newSince.some((at) => workspace.createdAt >= at);
25
- }
26
- function rolloutWidens(fromValue, toValue) {
27
- const from = parseRolloutList(fromValue);
28
- const to = parseRolloutList(toValue);
29
- if (to.all) {
30
- if (!from.all) return true;
31
- return [...from.excluded].some((id) => !to.excluded.has(id));
32
- }
33
- if ([...to.ids].some((id) => !rolloutAdmits(from, { id }))) return true;
34
- const earliest = (list) => list.newSince.length ? Math.min(...list.newSince) : Infinity;
35
- if (to.newSince.length && !from.all && earliest(to) < earliest(from)) return true;
36
- return false;
37
- }
38
- function normalizeRolloutValue(value) {
39
- return value.split(",").map((entry) => entry.trim()).filter(Boolean).sort().join(",");
40
- }
41
- function stageOf(plan, value) {
42
- const key = normalizeRolloutValue(value);
43
- return plan.stages.find((stage) => normalizeRolloutValue(stage.value) === key) ?? null;
44
- }
45
- function killLineBreaches(stage, measured) {
46
- if (!measured) return [`stage ${stage.name} has no measurement`];
47
- if (measured.stage !== stage.name) return [`measurement is for stage ${measured.stage}, not ${stage.name}`];
48
- const reasons = [];
49
- if (!(measured.samples >= stage.minSamples)) {
50
- reasons.push(`stage ${stage.name} has ${measured.samples} measured turns, under its minimum of ${stage.minSamples}`);
51
- }
52
- for (const [metric, line] of Object.entries(stage.kill)) {
53
- const value = measured.metrics[metric];
54
- if (typeof value !== "number" || !Number.isFinite(value)) {
55
- reasons.push(`${metric} was not measured`);
56
- continue;
57
- }
58
- if (line.max !== void 0 && value > line.max) reasons.push(`${metric} ${value} over kill line ${line.max}`);
59
- if (line.min !== void 0 && value < line.min) reasons.push(`${metric} ${value} under kill line ${line.min}`);
60
- }
61
- return reasons;
62
- }
63
- function validateRolloutPlan(plan) {
64
- if (!plan.name || !plan.variable) throw new Error("a rollout plan needs a name and a variable");
65
- if (!plan.stages.length) throw new Error(`rollout ${plan.name} declares no stages`);
66
- const names = /* @__PURE__ */ new Set();
67
- const values = /* @__PURE__ */ new Set();
68
- for (const stage of plan.stages) {
69
- if (names.has(stage.name)) throw new Error(`rollout ${plan.name} repeats stage ${stage.name}`);
70
- names.add(stage.name);
71
- const value = normalizeRolloutValue(stage.value);
72
- if (values.has(value)) throw new Error(`rollout ${plan.name} gives two stages the value ${stage.value}`);
73
- values.add(value);
74
- parseRolloutList(stage.value);
75
- if (!Number.isInteger(stage.minSamples) || stage.minSamples < 1) {
76
- throw new Error(`stage ${stage.name} needs minSamples of at least 1`);
77
- }
78
- if (!Object.keys(stage.kill).length) throw new Error(`stage ${stage.name} declares no kill lines`);
79
- }
80
- for (let index = 1; index < plan.stages.length; index++) {
81
- const previous = plan.stages[index - 1];
82
- const stage = plan.stages[index];
83
- if (!rolloutWidens(previous.value, stage.value)) {
84
- throw new Error(`stage ${stage.name} does not widen stage ${previous.name}`);
85
- }
86
- }
87
- }
88
- async function decideRollout(input) {
89
- const { plan, fromValue, toValue } = input;
90
- validateRolloutPlan(plan);
91
- const fromStage = stageOf(plan, fromValue);
92
- const toStage = stageOf(plan, toValue);
93
- const widens = rolloutWidens(fromValue, toValue);
94
- const record = (reasons, measured2) => ({
95
- rollout: plan.name,
96
- variable: plan.variable,
97
- from: { value: fromValue, stage: fromStage?.name ?? null },
98
- to: { value: toValue, stage: toStage?.name ?? null },
99
- widens,
100
- decision: reasons.length ? "refused" : "allowed",
101
- reasons,
102
- measured: measured2,
103
- at: (input.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
104
- });
105
- if (!widens) return record([], null);
106
- if (!toStage) return record([`${toValue} is not a declared stage of ${plan.name}`], null);
107
- const target = plan.stages.indexOf(toStage);
108
- if (!fromStage) {
109
- const empty = !normalizeRolloutValue(fromValue);
110
- return record(empty && target === 0 ? [] : [`the current value ${fromValue || "(empty)"} is not a declared stage of ${plan.name}`], null);
111
- }
112
- const current = plan.stages.indexOf(fromStage);
113
- if (target > current + 1) {
114
- return record([`${toStage.name} skips ${plan.stages.slice(current + 1, target).map((stage) => stage.name).join(", ")}`], null);
115
- }
116
- let measured;
117
- try {
118
- measured = await input.measure(fromStage);
119
- } catch (error) {
120
- return record([`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null);
121
- }
122
- return record(killLineBreaches(fromStage, measured), measured);
123
- }
124
-
125
- export {
126
- parseRolloutList,
127
- rolloutAdmits,
128
- rolloutWidens,
129
- normalizeRolloutValue,
130
- killLineBreaches,
131
- validateRolloutPlan,
132
- decideRollout
133
- };
134
- //# sourceMappingURL=chunk-4JUEOVQS.js.map
@@ -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 * - A change that admits no workspace the current value did not (a narrowing,\n * a rollback, the same stage) is always allowed: a guard that can block a\n * rollback is worse than none.\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 metric that was not measured fails its line.\n * - A refusal names each reason (`first_words_p50_ms 3540 over kill line 2500`).\n *\n * Every decision, allowed or refused, 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 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'\n /** Empty when allowed; each refusal reason otherwise. */\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/** Each kill line the measurement misses, as a reason. Empty when every line holds. */\nexport function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[] {\n if (!measured) return [`stage ${stage.name} has no measurement`]\n if (measured.stage !== stage.name) return [`measurement is for stage ${measured.stage}, not ${stage.name}`]\n const reasons: string[] = []\n if (!(measured.samples >= stage.minSamples)) {\n reasons.push(`stage ${stage.name} has ${measured.samples} measured turns, under its minimum of ${stage.minSamples}`)\n }\n for (const [metric, line] of Object.entries(stage.kill)) {\n const value = measured.metrics[metric]\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n reasons.push(`${metric} was not measured`)\n continue\n }\n if (line.max !== undefined && value > line.max) reasons.push(`${metric} ${value} over kill line ${line.max}`)\n if (line.min !== undefined && value < line.min) reasons.push(`${metric} ${value} under kill line ${line.min}`)\n }\n return reasons\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/**\n * Decide one change of the list. `measure` is called only for a widening, and\n * only for the stage being left.\n */\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 record = (reasons: string[], measured: StageMeasurement | null): RolloutDecision => ({\n rollout: plan.name,\n variable: plan.variable,\n from: { value: fromValue, stage: fromStage?.name ?? null },\n to: { value: toValue, stage: toStage?.name ?? null },\n widens,\n decision: reasons.length ? 'refused' : 'allowed',\n reasons,\n measured,\n at: (input.now?.() ?? new Date()).toISOString(),\n })\n if (!widens) return record([], null)\n if (!toStage) return record([`${toValue} is not a declared stage of ${plan.name}`], null)\n const target = plan.stages.indexOf(toStage)\n // An empty list admits nobody, so the first stage is the only widening it may take without numbers.\n if (!fromStage) {\n const empty = !normalizeRolloutValue(fromValue)\n return record(empty && target === 0 ? [] : [`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) {\n return record([`${toStage.name} skips ${plan.stages.slice(current + 1, target).map(stage => stage.name).join(', ')}`], null)\n }\n let measured: StageMeasurement | null\n try {\n measured = await input.measure(fromStage)\n } catch (error) {\n return record([`measuring stage ${fromStage.name} failed: ${error instanceof Error ? error.message : String(error)}`], null)\n }\n return record(killLineBreaches(fromStage, measured), measured)\n}\n"],"mappings":";AAuFO,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,KAAK,KAAK,UAAU,SAAS;AACxC;AAGO,SAAS,cAAc,OAAmC,WAAwD;AACvH,QAAM,OAAO,OAAO,UAAU,WAAW,iBAAiB,KAAK,IAAI;AACnE,MAAI,KAAK,SAAS,IAAI,UAAU,EAAE,E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