@warmdrift/kgauto-compiler 2.0.0-alpha.77 → 2.0.0-alpha.78

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,6 +1,6 @@
1
1
  import {
2
2
  tryGetProfile
3
- } from "./chunk-N36LE3MK.mjs";
3
+ } from "./chunk-VVRDFE6T.mjs";
4
4
 
5
5
  // src/brain-query.ts
6
6
  var FRESH_SNAPSHOT = {
@@ -323,6 +323,17 @@ function getReachabilityDiagnostic(opts = {}) {
323
323
  }
324
324
  return out;
325
325
  }
326
+ var BRAIN_READ_ENV_NAMES = {
327
+ endpoint: "KGAUTO_V2_BRAIN_SUPABASE_URL",
328
+ jwt: "KGAUTO_V2_BRAIN_JWT",
329
+ anonKey: "KGAUTO_V2_BRAIN_ANON_KEY",
330
+ /** Accepted fallbacks, in resolution order after the canonical name. */
331
+ fallbacks: {
332
+ endpoint: ["KGAUTO_V2_BRAIN_URL"],
333
+ jwt: ["GLASSBOX_BRAIN_JWT"],
334
+ anonKey: []
335
+ }
336
+ };
326
337
  function readBrainReadEnv(envSource = defaultEnv()) {
327
338
  const endpoint = readKeyValue(envSource.KGAUTO_V2_BRAIN_SUPABASE_URL) ?? readKeyValue(envSource.KGAUTO_V2_BRAIN_URL);
328
339
  const jwt = readKeyValue(envSource.KGAUTO_V2_BRAIN_JWT) ?? readKeyValue(envSource.GLASSBOX_BRAIN_JWT);
@@ -704,6 +715,7 @@ export {
704
715
  isProviderReachable,
705
716
  isModelReachable,
706
717
  getReachabilityDiagnostic,
718
+ BRAIN_READ_ENV_NAMES,
707
719
  readBrainReadEnv,
708
720
  isSameModelRetryEnabledFromEnv,
709
721
  loadChainsFromBrain,
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var LIBRARY_VERSION = "2.0.0-alpha.77";
2
+ var LIBRARY_VERSION = "2.0.0-alpha.78";
3
3
 
4
4
  // src/key-health.ts
5
5
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -363,6 +363,22 @@ var PROFILES_RAW = [
363
363
  threshold: 16,
364
364
  action: "drop_to_top_relevant",
365
365
  reason: "Haiku reliability degrades above ~16 tools"
366
+ },
367
+ {
368
+ // alpha.78 — the declared `structuredOutput: 'grammar'` does NOT
369
+ // hold on long-input summarize. MEASURED (brain, playbacksam):
370
+ // 21 disambiguated `structured_output_parse_failed` fallover rows
371
+ // 2026-07-22..27, tokens_in 12,280–31,450; PB's gate counted 20/20
372
+ // in-window failures. Clean traffic p50 sits at ~9K tokens_in, so
373
+ // 12K gates the failing band without touching the working one.
374
+ // Short-input summarize carries no failure evidence and stays
375
+ // ungated — this is why it's a cliff, not an archetype-wide
376
+ // `structuredOutputHint: 'avoid'`.
377
+ metric: "input_tokens",
378
+ threshold: 12e3,
379
+ action: "quality_gate_structured",
380
+ whenIntent: "summarize",
381
+ reason: "Structured-output parse failures at 100% in-window on long-input summarize (measured on playbacksam, 2026-07-25..27; haiku only led when input size made price dominate, then failed every time)."
366
382
  }
367
383
  ],
368
384
  costInputPer1m: 1,
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-Caq-hOIj.mjs';
2
- export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-Caq-hOIj.mjs';
3
- import '../ir-CRV1_taF.mjs';
1
+ import { G as GlassboxEvent } from '../types-DpcAMmk-.mjs';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-DpcAMmk-.mjs';
3
+ import '../ir-BFwWhj2s.mjs';
4
4
  import '../dialect.mjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-C5BX9bzi.js';
2
- export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-C5BX9bzi.js';
3
- import '../ir-C02EIElQ.js';
1
+ import { G as GlassboxEvent } from '../types-B4kz3Vs0.js';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-B4kz3Vs0.js';
3
+ import '../ir-DZKS1tI7.js';
4
4
  import '../dialect.js';
5
5
 
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-3WdGMqin.mjs';
2
- import '../ir-CRV1_taF.mjs';
1
+ import { T as TraceHealth } from '../types-hjzSWxtv.mjs';
2
+ import '../ir-BFwWhj2s.mjs';
3
3
  import '../dialect.mjs';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-CkRvjxrI.js';
2
- import '../ir-C02EIElQ.js';
1
+ import { T as TraceHealth } from '../types-D_fLt_Xv.js';
2
+ import '../ir-DZKS1tI7.js';
3
3
  import '../dialect.js';
4
4
 
5
5
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-Caq-hOIj.mjs';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-3WdGMqin.mjs';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-3WdGMqin.mjs';
4
- import '../ir-CRV1_taF.mjs';
1
+ import { G as GlassboxEvent } from '../types-DpcAMmk-.mjs';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-hjzSWxtv.mjs';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-hjzSWxtv.mjs';
4
+ import '../ir-BFwWhj2s.mjs';
5
5
  import '../dialect.mjs';
6
6
 
7
7
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-C5BX9bzi.js';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-CkRvjxrI.js';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-CkRvjxrI.js';
4
- import '../ir-C02EIElQ.js';
1
+ import { G as GlassboxEvent } from '../types-B4kz3Vs0.js';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-D_fLt_Xv.js';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-D_fLt_Xv.js';
4
+ import '../ir-DZKS1tI7.js';
5
5
  import '../dialect.js';
6
6
 
7
7
  /**
@@ -417,6 +417,22 @@ var PROFILES_RAW = [
417
417
  threshold: 16,
418
418
  action: "drop_to_top_relevant",
419
419
  reason: "Haiku reliability degrades above ~16 tools"
420
+ },
421
+ {
422
+ // alpha.78 — the declared `structuredOutput: 'grammar'` does NOT
423
+ // hold on long-input summarize. MEASURED (brain, playbacksam):
424
+ // 21 disambiguated `structured_output_parse_failed` fallover rows
425
+ // 2026-07-22..27, tokens_in 12,280–31,450; PB's gate counted 20/20
426
+ // in-window failures. Clean traffic p50 sits at ~9K tokens_in, so
427
+ // 12K gates the failing band without touching the working one.
428
+ // Short-input summarize carries no failure evidence and stays
429
+ // ungated — this is why it's a cliff, not an archetype-wide
430
+ // `structuredOutputHint: 'avoid'`.
431
+ metric: "input_tokens",
432
+ threshold: 12e3,
433
+ action: "quality_gate_structured",
434
+ whenIntent: "summarize",
435
+ reason: "Structured-output parse failures at 100% in-window on long-input summarize (measured on playbacksam, 2026-07-25..27; haiku only led when input size made price dominate, then failed every time)."
420
436
  }
421
437
  ],
422
438
  costInputPer1m: 1,
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  ARCHETYPE_FLOOR_DEFAULT,
3
3
  getDefaultFallbackChain
4
- } from "../chunk-46U2NVOL.mjs";
4
+ } from "../chunk-FT2FN6ZP.mjs";
5
5
  import {
6
6
  tryGetProfile
7
- } from "../chunk-N36LE3MK.mjs";
7
+ } from "../chunk-VVRDFE6T.mjs";
8
8
  import {
9
9
  subscribe,
10
10
  subscribeApp
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { a as TraceDetail } from '../../types-3WdGMqin.mjs';
3
- import '../../ir-CRV1_taF.mjs';
2
+ import { a as TraceDetail } from '../../types-hjzSWxtv.mjs';
3
+ import '../../ir-BFwWhj2s.mjs';
4
4
  import '../../dialect.mjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { a as TraceDetail } from '../../types-CkRvjxrI.js';
3
- import '../../ir-C02EIElQ.js';
2
+ import { a as TraceDetail } from '../../types-D_fLt_Xv.js';
3
+ import '../../ir-DZKS1tI7.js';
4
4
  import '../../dialect.js';
5
5
 
6
6
  /**
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, F as FallbackReason, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-CRV1_taF.mjs';
2
- export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as parseGoldenCaptureRate, K as resolveGoldenCaptureRate, L as shouldCaptureGolden } from './ir-CRV1_taF.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, F as FallbackReason, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-BFwWhj2s.mjs';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as hasMutation, K as mutationId, L as parseGoldenCaptureRate, Q as resolveGoldenCaptureRate, U as shouldCaptureGolden } from './ir-BFwWhj2s.mjs';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.mjs';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.mjs';
5
5
  export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.mjs';
@@ -74,6 +74,20 @@ interface ExecuteOptions {
74
74
  * and `!opts.noStream`.
75
75
  */
76
76
  onChunk?: (chunk: string) => void;
77
+ /**
78
+ * alpha.78 — abort signal for the provider fetch. call() composes
79
+ * `AbortSignal.timeout(attemptTimeoutMs)` with the caller's own
80
+ * `CallOptions.abortSignal`; direct execute() consumers may pass anything.
81
+ * TimeoutError reasons classify retryable `timeout` (chain walks);
82
+ * AbortError reasons classify terminal `aborted` (caller cancelled).
83
+ */
84
+ signal?: AbortSignal;
85
+ /**
86
+ * alpha.78 — per-chunk stall bound, streaming paths only (see
87
+ * StreamingOptions.stallTimeoutMs). Ignored on non-streaming requests,
88
+ * where `signal` carries the total attempt bound instead.
89
+ */
90
+ stallTimeoutMs?: number;
77
91
  }
78
92
  interface ExecuteOk {
79
93
  ok: true;
@@ -343,7 +357,20 @@ interface CompileForAISDKv6Result {
343
357
  historyCacheMarkIndex?: number;
344
358
  /** Compile handle — pass to `record()` after the call. */
345
359
  handle: string;
346
- /** Mutation ids the compiler fired (informational). */
360
+ /**
361
+ * Mutation ids the compiler fired (informational).
362
+ *
363
+ * ⚠️ alpha.78 — element type differs BY SURFACE: this adapter carries
364
+ * `string[]` (ids), while `CompileResult`/`CallResult.mutationsApplied`
365
+ * carry `MutationApplied[]` (objects with `description`, `rankDelta`, …).
366
+ * Coding to one surface's type while reading the other's runtime is a
367
+ * silent false negative (PB 2026-07-25). Use the shape-proof helpers
368
+ * `mutationId(m)` / `hasMutation(list, 'quality-gate-measured-*')` from
369
+ * the package root instead of `typeof` checks. Neither element type can
370
+ * change without breaking a live consumer (tt-intel joins these ids;
371
+ * object readers want `description`), so the divergence is documented
372
+ * rather than unified.
373
+ */
347
374
  mutationsApplied: string[];
348
375
  /** Best-practice advisories (alpha.6). Empty when none fired. */
349
376
  advisories: BestPracticeAdvisory[];
@@ -1119,7 +1146,7 @@ declare function runStrategyEvalWithAttribution(opts: Omit<GoldenEvalOptions, 'a
1119
1146
  * guard in `tests/version.test.ts` fails the suite (and therefore
1120
1147
  * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
1121
1148
  */
1122
- declare const LIBRARY_VERSION = "2.0.0-alpha.77";
1149
+ declare const LIBRARY_VERSION = "2.0.0-alpha.78";
1123
1150
 
1124
1151
  /**
1125
1152
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -1651,18 +1678,30 @@ interface GetActionableAdvisoriesOptions {
1651
1678
  severity?: AdvisorySeverity;
1652
1679
  /** Status filter; defaults to 'open'. Pass 'all' for the full set. */
1653
1680
  status?: 'open' | 'snoozed' | 'resolved' | 'all';
1654
- brainEndpoint: string;
1655
- brainJwt: string;
1656
- brainAnonKey: string;
1681
+ /**
1682
+ * alpha.78 (PB adoption-gap ask 2): the trio now DEFAULTS from
1683
+ * `readBrainReadEnv()` when omitted, so a consumer that passes nothing
1684
+ * gets correct behavior from the canonical env names instead of a
1685
+ * self-authored config error. Explicit values still win.
1686
+ */
1687
+ brainEndpoint?: string;
1688
+ brainJwt?: string;
1689
+ brainAnonKey?: string;
1657
1690
  fetch?: typeof fetch;
1658
1691
  }
1659
1692
  interface MarkAdvisoryResolvedOptions {
1660
1693
  /** Stable id from a prior `getActionableAdvisories` call. */
1661
1694
  id: string;
1662
1695
  resolutionNote?: string;
1663
- brainEndpoint: string;
1664
- brainJwt: string;
1665
- brainAnonKey: string;
1696
+ /**
1697
+ * alpha.78 (PB adoption-gap ask 2): the trio now DEFAULTS from
1698
+ * `readBrainReadEnv()` when omitted, so a consumer that passes nothing
1699
+ * gets correct behavior from the canonical env names instead of a
1700
+ * self-authored config error. Explicit values still win.
1701
+ */
1702
+ brainEndpoint?: string;
1703
+ brainJwt?: string;
1704
+ brainAnonKey?: string;
1666
1705
  fetch?: typeof fetch;
1667
1706
  }
1668
1707
  /**
@@ -1686,8 +1725,10 @@ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions):
1686
1725
  * Lookup strategy:
1687
1726
  * 1. Query `actionable_advisories_v?id=eq.<id>` to find the (app_id, code)
1688
1727
  * tuple for this advisory.
1689
- * 2. PATCH the latest unresolved firing in `compile_outcome_advisories`
1690
- * matching that tuple via the underlying outcome's app_id.
1728
+ * 2. PATCH EVERY unresolved firing in `compile_outcome_advisories`
1729
+ * matching that tuple via the underlying outcome's app_id. (One call
1730
+ * closes the whole rollup — the alpha.71-era docblock said "latest
1731
+ * firing", which was never what the code did; corrected alpha.78.)
1691
1732
  *
1692
1733
  * The (app_id, code) lookup is necessary because `compile_outcome_advisories`
1693
1734
  * has no `app_id` column — it inherits scope via the FK to compile_outcomes.
@@ -1696,16 +1737,27 @@ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions):
1696
1737
  * acceptable because marks are low-frequency operator actions, not per-call
1697
1738
  * hot path.
1698
1739
  *
1699
- * Idempotent re-marks: if the advisory is already resolved (no unresolved
1700
- * firings match), the PATCH affects zero rows and the call still returns
1701
- * `ok: true`. The function returns `ok: false` only on transport / auth /
1702
- * lookup failures.
1740
+ * alpha.78 envelope (PB `resolve-envelope-cannot-close-a-rollup`, 2026-07-25):
1741
+ * the return now reports WHAT HAPPENED, not that the request was received —
1742
+ * `firingsResolved` is the count of rows this call actually flipped, and
1743
+ * `status` is the rollup's state after the write. PB measured the old
1744
+ * `ok: true` live against prod: the PATCH was being RLS-filtered to zero
1745
+ * rows (consumer JWTs had read-grant but no update-grant — migration 049
1746
+ * adds it) and the envelope reported success anyway. "When an API can
1747
+ * succeed without doing anything, the return value should distinguish those
1748
+ * cases" — this is that distinction. `firingsResolved: 0, status: 'open'`
1749
+ * on a rollup you expected to close now points at the write grant.
1750
+ *
1751
+ * Idempotent re-marks stay ok: an already-resolved advisory returns
1752
+ * `{ ok: true, firingsResolved: 0, status: 'resolved' }`.
1703
1753
  *
1704
1754
  * Returns ok/reason envelope (vs throwing) because consumer Admin UIs
1705
1755
  * typically want to render the failure inline rather than crash.
1706
1756
  */
1707
1757
  declare function markAdvisoryResolved(opts: MarkAdvisoryResolvedOptions): Promise<{
1708
1758
  ok: true;
1759
+ firingsResolved: number;
1760
+ status: 'open' | 'resolved' | 'unknown';
1709
1761
  } | {
1710
1762
  ok: false;
1711
1763
  reason: string;
@@ -1748,14 +1800,17 @@ interface MarkExclusionFindingHandledOptions {
1748
1800
  * digests + dashboards alongside the resolution_source. */
1749
1801
  resolutionNote?: string;
1750
1802
  /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). The
1751
- * function appends `/rest/v1/exclusion_findings?...`. */
1752
- brainEndpoint: string;
1803
+ * function appends `/rest/v1/exclusion_findings?...`.
1804
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1805
+ brainEndpoint?: string;
1753
1806
  /** Consumer-scoped JWT carrying the `app_id` claim. The brain's RLS
1754
1807
  * policy enforces that the JWT's app_id matches the finding's app_id;
1755
- * cross-tenant writes fail at the database layer regardless of input. */
1756
- brainJwt: string;
1757
- /** Supabase anon key for the `apikey` header (PostgREST requires it). */
1758
- brainAnonKey: string;
1808
+ * cross-tenant writes fail at the database layer regardless of input.
1809
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1810
+ brainJwt?: string;
1811
+ /** Supabase anon key for the `apikey` header (PostgREST requires it).
1812
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1813
+ brainAnonKey?: string;
1759
1814
  /** Injected fetch for tests. Defaults to global fetch. */
1760
1815
  fetch?: typeof fetch;
1761
1816
  }
@@ -2153,6 +2208,23 @@ interface BrainReadEnv {
2153
2208
  */
2154
2209
  missingEnv: string[];
2155
2210
  }
2211
+ /**
2212
+ * alpha.78 (PB adoption-gap ask 2) — the canonical brain-read env names as
2213
+ * an exported constant, so consumers reference them instead of retyping
2214
+ * (PB invented three plausible-but-wrong names and carried the resulting
2215
+ * self-authored 503 for two months).
2216
+ */
2217
+ declare const BRAIN_READ_ENV_NAMES: {
2218
+ readonly endpoint: "KGAUTO_V2_BRAIN_SUPABASE_URL";
2219
+ readonly jwt: "KGAUTO_V2_BRAIN_JWT";
2220
+ readonly anonKey: "KGAUTO_V2_BRAIN_ANON_KEY";
2221
+ /** Accepted fallbacks, in resolution order after the canonical name. */
2222
+ readonly fallbacks: {
2223
+ readonly endpoint: readonly ["KGAUTO_V2_BRAIN_URL"];
2224
+ readonly jwt: readonly ["GLASSBOX_BRAIN_JWT"];
2225
+ readonly anonKey: readonly [];
2226
+ };
2227
+ };
2156
2228
  /**
2157
2229
  * Resolve brain-read env vars. Defaults to `process.env`; pass `envSource`
2158
2230
  * for hermetic tests. Trims surrounding whitespace and treats
@@ -2984,6 +3056,18 @@ interface PromotionRow {
2984
3056
  suppressQualityGate: boolean;
2985
3057
  /** ISO timestamp the promotion went active. */
2986
3058
  promotedAt: string;
3059
+ /**
3060
+ * alpha.78 — lifecycle status. The endpoint serves rolled_back rows only
3061
+ * when the library asks (`with_rollbacks=1`), so pre-.78 clients can
3062
+ * never receive one. Every reader that APPLIES a promotion must filter
3063
+ * to 'active'; rolled_back rows exist so advisors can see what the guard
3064
+ * already adjudicated instead of re-recommending it (PB Finding 3).
3065
+ */
3066
+ status: 'active' | 'rolled_back';
3067
+ /** ISO timestamp of the guard's revert, rolled_back rows only. */
3068
+ rolledBackAt?: string;
3069
+ /** Guard's classification ('latency' | 'economics' | 'strategy' | …). */
3070
+ rollbackClass?: string;
2987
3071
  }
2988
3072
  interface PromotionsRuntime {
2989
3073
  /** Endpoint base URL. The library appends `?app_id=<id>`. */
@@ -3038,6 +3122,30 @@ interface GetApplicablePromotionOpts {
3038
3122
  * NEVER throws. Not configured / brain down / cold → undefined.
3039
3123
  */
3040
3124
  declare function getApplicablePromotion(opts: GetApplicablePromotionOpts): PromotionRow | undefined;
3125
+ /**
3126
+ * alpha.78 — how long a guard rollback suppresses re-recommending the same
3127
+ * model on the same surface. Matches the measured-failure evidence window:
3128
+ * a `rollback_class='latency'` revert deliberately keeps the model ELIGIBLE
3129
+ * long-term (traffic patterns change), so the suppression is windowed, not
3130
+ * permanent.
3131
+ */
3132
+ declare const ROLLBACK_SUPPRESSION_WINDOW_DAYS = 28;
3133
+ /**
3134
+ * alpha.78 (PB Finding 3) — sync reader: did the promotion guard recently
3135
+ * roll back `model` on `(appId, archetype)`? The cost advisor consults this
3136
+ * so it stops recommending "exactly the downswap your own machinery
3137
+ * auto-reverted three days ago" — an advisory acting on it would
3138
+ * re-litigate a decision the guard already made correctly. Same SWR
3139
+ * posture as `getApplicablePromotion`: cold/unconfigured → undefined
3140
+ * (advisor proceeds without rollback knowledge, as before alpha.78).
3141
+ */
3142
+ declare function getRecentRollback(opts: {
3143
+ appId: string;
3144
+ archetype: IntentArchetypeName | string;
3145
+ model: string;
3146
+ windowDays?: number;
3147
+ nowMs?: number;
3148
+ }): PromotionRow | undefined;
3041
3149
  /** Reset module state. Tests must call between cases. */
3042
3150
  declare function _testResetPromotions(): void;
3043
3151
  /** Wait for any in-flight refresh to settle. */
@@ -3141,11 +3249,30 @@ interface MeasuredFailureVerdict {
3141
3249
  n: number;
3142
3250
  nFail: number;
3143
3251
  }
3252
+ /**
3253
+ * alpha.78 — public row normalizer (PB 2026-07-25 trap): the counts
3254
+ * endpoint speaks snake_case (`intent_archetype`, `n_fail`) and this module
3255
+ * speaks camelCase. A consumer reproducing a gate decision by hand from the
3256
+ * endpoint previously got a silent `gated: false` — `wilsonLowerBound(
3257
+ * undefined, 13)` returns a clean 0 rather than throwing. Exported so the
3258
+ * bridge exists exactly once.
3259
+ */
3260
+ declare function mapMeasuredFailureRows(rows: unknown[]): SurfaceFailureRow[];
3144
3261
  /**
3145
3262
  * Pure decision, exported for tests and for the advisory text. Separated
3146
3263
  * from the I/O so the policy can be exercised without a brain.
3264
+ *
3265
+ * alpha.78 — accepts BOTH row shapes: the module's camelCase
3266
+ * `SurfaceFailureRow` and the counts endpoint's raw snake_case row. A
3267
+ * snake_case row previously slipped through the type system (all fields
3268
+ * `undefined`) and judged `gated: false` silently.
3147
3269
  */
3148
- declare function judgeMeasuredFailure(row: SurfaceFailureRow | undefined, cfg?: typeof MEASURED_FAILURE_CFG): MeasuredFailureVerdict | undefined;
3270
+ declare function judgeMeasuredFailure(row: SurfaceFailureRow | {
3271
+ intent_archetype: string;
3272
+ model: string;
3273
+ n: number | string;
3274
+ n_fail: number | string;
3275
+ } | undefined, cfg?: typeof MEASURED_FAILURE_CFG): MeasuredFailureVerdict | undefined;
3149
3276
  interface MeasuredFailureRuntime {
3150
3277
  /** Endpoint base URL. The library appends `?app_id=<id>`. */
3151
3278
  endpoint: string;
@@ -3404,4 +3531,4 @@ declare function planDecomposition(args: PlanDecompositionArgs): DecompositionPl
3404
3531
  */
3405
3532
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
3406
3533
 
3407
- export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };
3534
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };