@warmdrift/kgauto-compiler 2.0.0-alpha.7 → 2.0.0-alpha.71

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.
Files changed (55) hide show
  1. package/README.md +176 -46
  2. package/dist/brain-proxy.d.mts +113 -0
  3. package/dist/brain-proxy.d.ts +113 -0
  4. package/dist/brain-proxy.js +193 -0
  5. package/dist/brain-proxy.mjs +6 -0
  6. package/dist/chunk-4UO4CCSP.mjs +1620 -0
  7. package/dist/chunk-65ZMX5OT.mjs +169 -0
  8. package/dist/{chunk-5TI6PNSK.mjs → chunk-BVEXV5KC.mjs} +11 -0
  9. package/dist/chunk-NBO4R5PC.mjs +313 -0
  10. package/dist/chunk-P3TOAEG4.mjs +56 -0
  11. package/dist/chunk-RO22VFIF.mjs +29 -0
  12. package/dist/chunk-SBFSYCQG.mjs +719 -0
  13. package/dist/chunk-URFQR3SB.mjs +203 -0
  14. package/dist/dialect.d.mts +41 -3
  15. package/dist/dialect.d.ts +41 -3
  16. package/dist/dialect.js +14 -2
  17. package/dist/dialect.mjs +5 -3
  18. package/dist/glassbox/index.d.mts +59 -0
  19. package/dist/glassbox/index.d.ts +59 -0
  20. package/dist/glassbox/index.js +312 -0
  21. package/dist/glassbox/index.mjs +12 -0
  22. package/dist/glassbox-routes/format.d.mts +24 -0
  23. package/dist/glassbox-routes/format.d.ts +24 -0
  24. package/dist/glassbox-routes/format.js +86 -0
  25. package/dist/glassbox-routes/format.mjs +18 -0
  26. package/dist/glassbox-routes/index.d.mts +191 -0
  27. package/dist/glassbox-routes/index.d.ts +191 -0
  28. package/dist/glassbox-routes/index.js +2888 -0
  29. package/dist/glassbox-routes/index.mjs +667 -0
  30. package/dist/glassbox-routes/react/index.d.mts +74 -0
  31. package/dist/glassbox-routes/react/index.d.ts +74 -0
  32. package/dist/glassbox-routes/react/index.js +819 -0
  33. package/dist/glassbox-routes/react/index.mjs +754 -0
  34. package/dist/index.d.mts +2745 -17
  35. package/dist/index.d.ts +2745 -17
  36. package/dist/index.js +9006 -1651
  37. package/dist/index.mjs +5103 -367
  38. package/dist/ir-BEQ28muo.d.ts +1608 -0
  39. package/dist/ir-CnnJST_N.d.mts +1608 -0
  40. package/dist/key-health.d.mts +131 -0
  41. package/dist/key-health.d.ts +131 -0
  42. package/dist/key-health.js +228 -0
  43. package/dist/key-health.mjs +6 -0
  44. package/dist/profiles.d.mts +292 -2
  45. package/dist/profiles.d.ts +292 -2
  46. package/dist/profiles.js +1231 -16
  47. package/dist/profiles.mjs +9 -1
  48. package/dist/types-B--CYzMo.d.ts +131 -0
  49. package/dist/types-BDFrJkma.d.mts +131 -0
  50. package/dist/types-DSeJJ6tt.d.ts +149 -0
  51. package/dist/types-DeGRCTlJ.d.mts +149 -0
  52. package/package.json +54 -8
  53. package/dist/chunk-MBEI5UOM.mjs +0 -409
  54. package/dist/profiles-B3eNQ2py.d.ts +0 -619
  55. package/dist/profiles-Py8c7zjJ.d.mts +0 -619
package/dist/index.d.ts CHANGED
@@ -1,6 +1,11 @@
1
- import { M as ModelProfile, C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory } from './profiles-B3eNQ2py.js';
2
- export { f as ALIASES, g as CacheStrategy, h as CallAttempt, i as CallError, j as CliffRule, k as Constraints, H as HistoryCachePolicy, I as IntentDeclaration, L as LoweringSpec, l as Message, m as MutationApplied, n as NormalizedTokens, o as PromptSection, p as Provider, q as RecoveryRule, S as StructuredOutputCapability, r as SystemPromptMode, T as ToolCall, s as ToolDefinition, t as allProfiles, u as getProfile, v as profilesByProvider, w as tryGetProfile } from './profiles-B3eNQ2py.js';
3
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, IntentArchetypeName, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
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 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-BEQ28muo.js';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, 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-BEQ28muo.js';
3
+ import { ModelProfile, ArchetypeConvention } from './profiles.js';
4
+ export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.js';
5
+ export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.js';
6
+ export { KeyHealthConfig, KeyHealthProvider, KeyHealthResponseBody, KeyHealthResult, KeyHealthRoute, createKeyHealthRoute } from './key-health.js';
7
+ import { IntentArchetypeName, OutputMode } from './dialect.js';
8
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
4
9
 
5
10
  /**
6
11
  * compile() — the main orchestrator.
@@ -33,6 +38,15 @@ interface CompileOptions {
33
38
  * ceiling, boosts preferred. See CompilePolicy in ir.ts.
34
39
  */
35
40
  policy?: CompilePolicy;
41
+ /**
42
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage) —
43
+ * transport for the fan-out parent handle. Threaded from
44
+ * `CallOptions.parentHandle` on the call() path (and settable directly on the
45
+ * public compile() path). Release A does NOT route on it — it only labels the
46
+ * outcome row (fanout_role / trace_id / parent_handle) at record-registration
47
+ * time. `registerCompile` reads it to derive the linkage. Absent ⇒ root call.
48
+ */
49
+ parentHandle?: string;
36
50
  }
37
51
 
38
52
  /**
@@ -51,6 +65,15 @@ interface ExecuteOptions {
51
65
  apiKeys?: ApiKeys;
52
66
  fetchImpl?: typeof fetch;
53
67
  providerOverrides?: ProviderOverrides;
68
+ /**
69
+ * alpha.34. When supplied AND the chosen provider supports streaming, the
70
+ * execute() per-provider branch switches to SSE wire format and invokes
71
+ * `onChunk(delta)` once per text-delta event. Single-shot behavior
72
+ * preserved when omitted (current consumers unaffected). Wired from
73
+ * `CallOptions.onChunk` by `call()` after gating on `profile.streaming`
74
+ * and `!opts.noStream`.
75
+ */
76
+ onChunk?: (chunk: string) => void;
54
77
  }
55
78
  interface ExecuteOk {
56
79
  ok: true;
@@ -64,6 +87,19 @@ interface ExecuteErr {
64
87
  errorCode: string;
65
88
  message: string;
66
89
  raw: unknown;
90
+ /**
91
+ * alpha.66 — real token usage when the failure is a SYNTHESIZED
92
+ * structured-output contract violation (the provider returned 200 with
93
+ * usage; the response just violated the contract). Absent on transport-
94
+ * level failures (4xx/5xx/network) where no usage exists. Lets the
95
+ * brain's failure rows carry true `tokens_in` for the cliff class —
96
+ * PB's 2026-05-18 `chain-walk-on-structured-output-parse-failed` ask 4
97
+ * (tokens_in=0 on a 72s parse-fail made diagnosis ambiguous).
98
+ */
99
+ tokens?: {
100
+ input: number;
101
+ output: number;
102
+ };
67
103
  }
68
104
  type ExecuteResult = ExecuteOk | ExecuteErr;
69
105
  declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promise<ExecuteResult>;
@@ -90,17 +126,317 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
90
126
  * exhausted without success.
91
127
  */
92
128
  declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
129
+ /** Served-side result the AI-SDK consumer already holds from streamText. */
130
+ interface ProbeShadowServed {
131
+ /** Model id that actually served the user (becomes `current_model` on the row). */
132
+ model: string;
133
+ /** The served response text (stored as a preview; never the prompt). */
134
+ responseText: string;
135
+ /** Served prompt tokens (AI SDK `usage.promptTokens`). */
136
+ tokensIn: number;
137
+ /** Served completion tokens (AI SDK `usage.completionTokens`). */
138
+ tokensOut: number;
139
+ /** The user's actual wait in ms (alpha.46 served-latency axis). */
140
+ latencyMs: number;
141
+ }
142
+ /** Options for the standalone {@link probeShadow} export. */
143
+ interface ProbeShadowOptions {
144
+ /** The served leg the consumer supplies; kgauto runs the candidate leg. */
145
+ served: ProbeShadowServed;
146
+ /** Model id(s)/family alias(es) to shadow-test against the served model. */
147
+ candidates: string | string[];
148
+ /** Probability [0,1] a given call fires a probe. Default 0.05; pin 1 for dogfood. */
149
+ sampleRate?: number;
150
+ /** Phase 1 = 'off' (offline rollup). 'opus' inline judge is Phase 2. Default 'off'. */
151
+ judge?: 'off' | 'opus';
152
+ /** Override API keys (defaults: process.env). Gates candidate reachability. */
153
+ apiKeys?: ApiKeys;
154
+ /** Override fetch (for tests / custom transport). */
155
+ fetchImpl?: typeof fetch;
156
+ /** Provider-specific request fields shallow-merged into the candidate request. */
157
+ providerOverrides?: ProviderOverrides;
158
+ /** Forwarded to compile() for the candidate run (match the served-side compile). */
159
+ policy?: CompilePolicy;
160
+ toolRelevanceThreshold?: number;
161
+ compressHistoryAfter?: number;
162
+ }
163
+ /**
164
+ * s54 — standalone full-IR shadow probe for AI-SDK consumers (tt-intel hunt, IC
165
+ * chat) that own their own streamText round-trip and never call call(). Fire it
166
+ * from the streamText `onFinish` callback, wrapped in the platform's
167
+ * `waitUntil()` / `after()`, so it runs after the response is flushed — no
168
+ * blocking, no `sync:true`, no teardown race (cleaner than call()'s in-process
169
+ * fire-and-forget for Edge runtimes; L-086).
170
+ *
171
+ * Runs the SAME candidate loop as the call()-inline probe ({@link
172
+ * runProbeCandidates}): same gates (sample, self-skip, G4 judge-self,
173
+ * reachability, G6), same fidelity=1.0 full-IR rows, same alpha.46 latency
174
+ * capture. The consumer supplies the served leg it already has; kgauto runs the
175
+ * candidate(s) and writes the `probe_outcomes` row.
176
+ *
177
+ * Requires `configureBrain()` to have been called (same as call()).
178
+ * Fire-and-forget: never throws into the caller.
179
+ *
180
+ * @example
181
+ * const result = streamText({ model, system, messages,
182
+ * onFinish: ({ text, usage }) => {
183
+ * after(() => probeShadow(ir, {
184
+ * served: { model: servedModelId, responseText: text,
185
+ * tokensIn: usage.promptTokens, tokensOut: usage.completionTokens,
186
+ * latencyMs: Date.now() - t0 },
187
+ * candidates: ['deepseek-v4-pro'], sampleRate: 0.05,
188
+ * }));
189
+ * },
190
+ * });
191
+ */
192
+ declare function probeShadow(ir: PromptIR, opts: ProbeShadowOptions): Promise<void>;
193
+
194
+ /**
195
+ * alpha.33 — AI-SDK streamText helpers.
196
+ *
197
+ * The cross-consumer pattern surfaced 2026-05-20 (`streamText-cache-marker-
198
+ * propagation-gap` on `command-center/interfaces/kgauto.md ## Requested`):
199
+ * AI-SDK consumers using `streamText({ system: <string>, messages:
200
+ * convertToModelMessages(messages), model })` silently drop the Anthropic
201
+ * `cache_control` markers the compiler emits on `result.request.messages`.
202
+ * Two losses on that line:
203
+ * (a) `convertToModelMessages()` reads raw inputs not the lowered output,
204
+ * dropping per-message providerOptions; and
205
+ * (b) `streamText({ system: '<string>' })` strips any providerOptions
206
+ * on the system prefix.
207
+ *
208
+ * Net effect prior to this surface: `cache_read_input_tokens = 0` across
209
+ * every measured production call by IC + tt-intel even though both
210
+ * consumers had `historyCachePolicy: { strategy: 'all-but-latest' }` wired
211
+ * since alpha.5. The compiler did the right thing; the consumer integration
212
+ * pattern lost the markers at the wire boundary.
213
+ *
214
+ * This helper closes the gap. Pass the consumer's already-converted messages
215
+ * + the kgauto CompileResult and get back a `{ system, messages }` pair
216
+ * with cacheControl re-attached at the deterministic indices the compiler
217
+ * computed (`diagnostics.historyCacheMarkIndex` + `systemMessages` with
218
+ * its own cacheControl markers).
219
+ *
220
+ * No I/O. Pure transform. Idempotent — calling twice with the same inputs
221
+ * produces structurally-identical output.
222
+ */
223
+
224
+ /**
225
+ * AI-SDK-shaped converted-message structure. Matches what
226
+ * `convertToModelMessages()` returns at the wire layer. We don't import
227
+ * the AI-SDK type to avoid pulling that dep into the kgauto-compiler
228
+ * package — consumers pass their own already-converted messages.
229
+ */
230
+ interface AISDKConvertedMessage {
231
+ role: 'system' | 'user' | 'assistant' | 'tool';
232
+ content: unknown;
233
+ providerOptions?: {
234
+ anthropic?: {
235
+ cacheControl?: {
236
+ type: 'ephemeral';
237
+ };
238
+ };
239
+ };
240
+ }
241
+ /**
242
+ * Result of `attachCacheControlToStreamTextInput()` — ready to spread into
243
+ * `streamText(...)` directly.
244
+ *
245
+ * The `system` field is either the structured `SystemModelMessage[]` form
246
+ * (when the compiler computed at least one cacheable section + chose
247
+ * Anthropic) or the flat-string concatenation (when no cacheable sections
248
+ * exist OR the provider isn't Anthropic). Consumers can pass either form
249
+ * to `streamText({ system })` — the AI-SDK accepts both.
250
+ */
251
+ interface AttachCacheControlResult {
252
+ system: string | SystemModelMessage[];
253
+ messages: AISDKConvertedMessage[];
254
+ }
255
+ /**
256
+ * Attach Anthropic cache_control markers to a streamText input that the
257
+ * consumer has already prepared via `convertToModelMessages()`. Reads
258
+ * `result.diagnostics.historyCacheMarkIndex` for the position-on-history
259
+ * marker and `result.systemMessages` for the per-section system markers.
260
+ *
261
+ * The flat-string `system` form is returned when:
262
+ * - the compiler produced no `systemMessages` (e.g., zero sections kept), or
263
+ * - the chosen provider is not Anthropic, so cacheControl wouldn't
264
+ * achieve anything at the wire layer (other providers cache implicitly
265
+ * based on prefix shape, no marker needed).
266
+ *
267
+ * Otherwise the structured `SystemModelMessage[]` form is returned —
268
+ * preserves the per-section cacheControl markers across `streamText`.
269
+ *
270
+ * @param result - kgauto CompileResult from `compile(ir, opts)`
271
+ * @param convertedMessages - the consumer's already-converted messages
272
+ * (from `convertToModelMessages(rawMessages)` in their AI-SDK call site)
273
+ * @returns `{ system, messages }` ready to spread into `streamText(...)`
274
+ */
275
+ declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
93
276
 
94
277
  /**
95
- * Brain client fire-and-forget telemetry to the central kgauto Supabase.
278
+ * alpha.52official AI-SDK-v6 compile adapter + compile-then-discard guard.
279
+ *
280
+ * Until now each AI-SDK consumer (tt-intel, IC) hand-rolled this adapter in
281
+ * its own `lib/kgauto-v2/index.ts`: `compile()` → reassemble the system param
282
+ * per provider → extract kept tool names per provider → re-derive the history
283
+ * cache-mark index (a copy of the compiler's own `historyCacheMarkIndex`
284
+ * logic — drift-prone). This centralizes that boilerplate and DRYs the two
285
+ * near-identical wrappers.
96
286
  *
97
- * The brain is the centralized learning store. Apps POST outcomes here;
98
- * mutations flow back through a separate pull (in v2.1).
287
+ * It also closes the compile-then-discard hole. The discard pattern is:
288
+ *
289
+ * const c = compileForAISDKv6(ir); // compile runs
290
+ * const out = await generateText({ // …but a hand-built prompt
291
+ * model: getModel(otherId), prompt }); // + a DIFFERENT model run
292
+ * await record({ handle: c.handle, … }); // brain row attributed to `c`
293
+ *
294
+ * The recorded row's `mutations_applied` / `estimated_tokens_in` /
295
+ * `system_prompt_chars` then describe a compile that never reached the wire.
296
+ * A library-level runtime guard could NOT catch this while the adapter lived
297
+ * in consumer code (the consumer wrapper always reads `compile()`'s result to
298
+ * build its own object, so any getter there is "consumed" every time,
299
+ * regardless of whether the final caller used the wrapper output). With the
300
+ * adapter IN the library, the object the FINAL caller reads is library-owned,
301
+ * so consume-tracking getters on `.system` / `.model` / `.raw` detect non-use
302
+ * and `record()` warns. See `interfaces/kgauto.md` (## Requested:
303
+ * `compiled-output-discarded-guard`).
304
+ *
305
+ * The guard is OPT-IN-BY-USE: only `compileForAISDKv6` arms tracking, so
306
+ * `call()` paths and raw `compile()` users never see a false warning.
307
+ */
308
+
309
+ interface CompileForAISDKv6Result {
310
+ /**
311
+ * Pass to `streamText`/`generateText({ model })` — the caller maps this id
312
+ * to an AI-SDK `LanguageModel`. Reading this marks the compile "consumed"
313
+ * (silences the compile-then-discard guard).
314
+ */
315
+ readonly model: string;
316
+ /**
317
+ * System parameter for `streamText`/`generateText({ system })`. Returns the
318
+ * structured `SystemModelMessage[]` form when the target is Anthropic AND a
319
+ * cacheable section exists (preserves the cache_control marker across the
320
+ * wire); a flat concatenated string otherwise. Reading this marks
321
+ * "consumed". (Same rule as `attachCacheControlToStreamTextInput`.)
322
+ */
323
+ readonly system: string | SystemModelMessage[];
324
+ /**
325
+ * The raw kgauto `CompileResult` — for `attachCacheControlToStreamTextInput(raw, msgs)`
326
+ * and `probeShadow(raw.ir-equivalent, …)` paths. Reading this marks
327
+ * "consumed" (it means you're using the compile output via the raw result).
328
+ */
329
+ readonly raw: CompileResult;
330
+ /** Tool names that survived budget + relevance — filter your SDK tool map to these. */
331
+ keptToolNames: Set<string>;
332
+ /** providerOptions for `streamText` — Anthropic cache_control on the cacheable prefix. Undefined otherwise. */
333
+ providerOptions?: {
334
+ anthropic?: {
335
+ cacheControl?: {
336
+ type: 'ephemeral';
337
+ };
338
+ };
339
+ };
340
+ /**
341
+ * Index (into post-strip history) for the Anthropic history cache marker
342
+ * (alpha.33). Mirror of `result.diagnostics.historyCacheMarkIndex` — no
343
+ * consumer re-derivation needed. Undefined when no marker fires, and (since
344
+ * alpha.55) always undefined for non-Anthropic targets: the marker is an
345
+ * Anthropic wire concept, other providers cache prefixes implicitly. The
346
+ * ungated value remains on `diagnostics.historyCacheMarkIndex`.
347
+ */
348
+ historyCacheMarkIndex?: number;
349
+ /** Compile handle — pass to `record()` after the call. */
350
+ handle: string;
351
+ /** Mutation ids the compiler fired (informational). */
352
+ mutationsApplied: string[];
353
+ /** Best-practice advisories (alpha.6). Empty when none fired. */
354
+ advisories: BestPracticeAdvisory[];
355
+ /** Compiler diagnostics + the three commonly-logged top-level fields. */
356
+ diagnostics: CompileResult['diagnostics'] & {
357
+ targetProvider: string;
358
+ estimatedCostUsd: number;
359
+ fallbackChain: string[];
360
+ };
361
+ /** The compiled IR — pass to `probeShadow(ir, …)` in `onFinish` (alpha.48). */
362
+ ir: PromptIR;
363
+ }
364
+ /**
365
+ * Compile a `PromptIR` and lower it to an AI-SDK-v6 `streamText`/`generateText`
366
+ * bundle. Replaces the hand-rolled per-consumer adapter.
99
367
  *
100
- * Design: never blocks the caller. Failures are silent (logged via optional
101
- * onError hook). Uses fetch() works in Node 18+, Edge runtimes, and browsers.
368
+ * Arms the compile-then-discard guard: read `.system` / `.model` / `.raw` to
369
+ * serve the call. If you `record()` the handle without reading any of them,
370
+ * `record()` emits a dev-mode warning that the compile was discarded.
102
371
  */
372
+ declare function compileForAISDKv6(ir: PromptIR, opts?: CompileOptions): CompileForAISDKv6Result;
103
373
 
374
+ /**
375
+ * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
376
+ * perf / pricing / models registry). Enabled by default when endpoint is
377
+ * set; per-table opt-out via explicit `false`.
378
+ *
379
+ * Locked via /plan-eng-review 2026-05-15 (decision D3). Structured group
380
+ * keeps the BrainConfig surface clean as more brain-driven tables ship.
381
+ */
382
+ interface BrainQueryConfig {
383
+ /** Default true when endpoint set. Brain-driven fallback chains. */
384
+ chains?: boolean;
385
+ /** Default true when endpoint set. Brain-driven archetype perf scores. */
386
+ perf?: boolean;
387
+ /** Default true when endpoint set. Brain-driven pricing with at-time resolution. */
388
+ pricing?: boolean;
389
+ /** Default true when endpoint set. Brain-driven model registry + aliases. */
390
+ models?: boolean;
391
+ /**
392
+ * alpha.38 — opt-in compile-time advisor for stale exclusions. Default
393
+ * `true` when endpoint is set. When enabled, the library reads
394
+ * `exclusion_findings` from the central kgauto-dashboard for the consumer's
395
+ * `app_id` (no consumer-side proxy work required) and surfaces a
396
+ * `stale-exclusion-candidate` advisory when compile()'s archetype has a
397
+ * recommend-probe finding open. Set `false` to silence (no fetch, no
398
+ * advisory).
399
+ */
400
+ findingsExclusions?: boolean;
401
+ /**
402
+ * alpha.64 — hard opt-out of the surface-promotions fetch layer (Stage 2).
403
+ * Default true; only matters when consent (`BrainConfig.autoPromote` /
404
+ * `KGAUTO_AUTO_PROMOTE`) is present — without consent the layer is off
405
+ * regardless. Set `false` to disable the fetch even while consented
406
+ * (debug/emergency lever).
407
+ */
408
+ promotions?: boolean;
409
+ /** SWR window in ms. Default 300_000 (5 min). */
410
+ cacheTtlMs?: number;
411
+ /** Override the GET URL when the read endpoint differs from the write one.
412
+ * Defaults to `${endpoint}/v2/config` when omitted. */
413
+ configEndpoint?: string;
414
+ /**
415
+ * alpha.38 — override the findings endpoint when the consumer wants to
416
+ * proxy `exclusion_findings` reads through their own service rather than
417
+ * reading directly from the kgauto-dashboard. Library appends `?app_id=X`.
418
+ * Defaults to `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`.
419
+ */
420
+ findingsEndpoint?: string;
421
+ /**
422
+ * alpha.64 — override the surface-promotions endpoint (Stage 2). Only
423
+ * consulted when the consumer opted in via `BrainConfig.autoPromote` /
424
+ * `KGAUTO_AUTO_PROMOTE`. Library appends `?app_id=X`. Defaults to
425
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions`.
426
+ */
427
+ promotionsEndpoint?: string;
428
+ /**
429
+ * alpha.70 — hard opt-out of the measured-failure gate fetch layer.
430
+ * Default true (the gate is opt-OUT, see `BrainConfig.measuredFailureGate`).
431
+ */
432
+ measuredFailure?: boolean;
433
+ /**
434
+ * alpha.70 — override the measured-failure endpoint. Library appends
435
+ * `?app_id=X`. Defaults to
436
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure`.
437
+ */
438
+ measuredFailureEndpoint?: string;
439
+ }
104
440
  interface BrainConfig {
105
441
  /** Brain HTTP endpoint base URL (e.g., https://kgauto-brain.vercel.app/api). */
106
442
  endpoint: string;
@@ -112,16 +448,145 @@ interface BrainConfig {
112
448
  sync?: boolean;
113
449
  /** Optional fetch override (for tests). */
114
450
  fetchImpl?: typeof fetch;
451
+ /** alpha.11 — brain-query mode for config tables. Default-on per table
452
+ * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
453
+ brainQuery?: BrainQueryConfig;
454
+ /**
455
+ * alpha.52 — emit a dev-mode `console.warn` when a `compileForAISDKv6()`
456
+ * result is passed to record() but its `.system` / `.model` / `.raw` were
457
+ * never read (the compile-then-discard pattern: the recorded brain row's
458
+ * `mutations_applied` / `estimated_tokens_in` / `system_prompt_chars`
459
+ * describe a compile that did NOT shape the served call). Default: warn
460
+ * when `NODE_ENV !== 'production'`, silent in production. Set `true` to
461
+ * force-on (e.g. a prod audit window) or `false` to silence. No-op for
462
+ * `call()` paths and raw `compile()` users — only `compileForAISDKv6`
463
+ * arms the tracking, so good actors never see a false warning.
464
+ */
465
+ warnOnDiscardedCompile?: boolean;
466
+ /**
467
+ * alpha.59 — per-leg timeout (ms) applied to every brain WRITE POST
468
+ * (record() primary + advisory secondary, recordOutcome(),
469
+ * recordShadowProbe()) via `AbortSignal.timeout`. Default 10000.
470
+ *
471
+ * Why: `sync: true` puts these fetches on the USER path (Edge consumers
472
+ * await record() before responding), and alpha.56's representation
473
+ * passthrough added a second sequential POST (advisory secondary) to that
474
+ * same path — an unbounded hang on either leg holds the user to the Edge
475
+ * limit (GE's `brainconfig-first-class-timeout` filing; GE bounded it at
476
+ * 3s via a hand-rolled fetchImpl wrapper every sync consumer had to
477
+ * rediscover).
478
+ *
479
+ * A fired timeout follows each leg's existing degraded-brain path
480
+ * (fire-and-forget: swallowed via onError; sync: `persistence_failed`
481
+ * result — never a throw into the user path). Wraps the configured
482
+ * `fetchImpl` rather than replacing it, so it composes with
483
+ * consumer-supplied impls. Set `0` to disable (pre-alpha.59 unbounded
484
+ * behavior). Brain-query reads (config tables) are cached + SWR and are
485
+ * not affected.
486
+ */
487
+ timeoutMs?: number;
488
+ /**
489
+ * alpha.64 (Stage 2 of the eval trust ladder) — consent switch for the
490
+ * surface-promotion routing effect. Default OFF.
491
+ *
492
+ * When true (or when the `KGAUTO_AUTO_PROMOTE` env var is '1'/'true' and
493
+ * this field is left undefined — env-as-consent, the KGAUTO_GOLDEN_CAPTURE
494
+ * precedent; an explicit `false` here overrides the env), compile()
495
+ * consults the brain's active `kgauto_promotions` rows for this app and
496
+ * boosts the promoted model at scoring time. Promotions are written only
497
+ * by the automated golden-eval trigger after a promote-ready verdict on a
498
+ * price-dominant (cheaper) candidate, and every promotion sits behind the
499
+ * 7-day rollback guard (daily watcher auto-reverts on regression vs the
500
+ * frozen baseline).
501
+ *
502
+ * Not opted in ⇒ promotions have ZERO routing effect (they remain visible
503
+ * as advisories + dashboard rows). Consumer sovereignty is preserved even
504
+ * when opted in: `forceModel`, `policy.blockedModels`, and cost ceilings
505
+ * always win, and a non-empty `policy.preferredModels` defers the
506
+ * promotion entirely.
507
+ */
508
+ autoPromote?: boolean;
509
+ /**
510
+ * alpha.70 — the measured-failure quality gate. **Default ON** wherever
511
+ * the brain is configured; set `false` (or `KGAUTO_MEASURED_FAILURE_GATE=0`)
512
+ * to disable. An explicit value here wins over the env var.
513
+ *
514
+ * Why this is opt-OUT while `autoPromote` is opt-IN: a promotion silently
515
+ * changes WHICH model serves you on kgauto's evidence, so it needs
516
+ * consent. This gate only ever DE-RANKS a model that the consumer's own
517
+ * outcome rows show failing them — the failures are already being paid
518
+ * for on their bill and their users' latency, and the model stays
519
+ * available as a graceful fallback. Requiring an opt-in to stop paying
520
+ * would be the wrong default.
521
+ *
522
+ * Consumer sovereignty is unchanged: `forceModel` still wins. Unlike a
523
+ * promotion, `policy.preferredModels` does NOT defer the gate — a
524
+ * preference says which model you would like to lead, not that a
525
+ * measurably-failing one works.
526
+ */
527
+ measuredFailureGate?: boolean;
115
528
  }
116
529
  declare function configureBrain(config: BrainConfig): void;
117
530
  declare function clearBrain(): void;
531
+ interface BrainHealthSnapshot {
532
+ configState: 'configured' | 'not_configured';
533
+ /** Host of the configured endpoint (never the full URL — no secrets/paths). */
534
+ endpointHost?: string;
535
+ /** True when writes are awaited (BrainConfig.sync). */
536
+ sync: boolean;
537
+ /** Write POSTs attempted (all routes, primary + secondary). */
538
+ sent: number;
539
+ /** Write POSTs acknowledged 2xx without redirect. */
540
+ acked: number;
541
+ /** Write POSTs that failed (non-2xx, redirect, timeout, network throw). */
542
+ failed: number;
543
+ /** Subset of `failed` that failed the redirect check (middleware-drift class). */
544
+ redirected: number;
545
+ lastAckAt?: string;
546
+ lastFailureAt?: string;
547
+ /** Most recent failure message, truncated. */
548
+ lastFailure?: string;
549
+ deadLetterCount: number;
550
+ }
551
+ interface BrainDeadLetterEntry {
552
+ /** Brain route segment the payload was bound for. */
553
+ route: 'outcomes' | 'compile_outcome_quality' | 'probe_outcomes' | 'compile_outcome_advisories' | 'golden_irs';
554
+ /**
555
+ * Endpoint the payload was originally bound for. Flush replays ONLY entries
556
+ * matching the currently-configured endpoint — a reconfigure must never
557
+ * replay another brain's payloads into the new target (caught live by
558
+ * smoke-brain-timeout: a hung-socket test payload auto-flushed into the
559
+ * real brain after the smoke re-pointed configureBrain).
560
+ */
561
+ endpoint: string;
562
+ /** The exact JSON body that failed to land. */
563
+ payload: unknown;
564
+ failedAt: string;
565
+ /** Delivery attempts so far (1 = the original failed POST). */
566
+ attempts: number;
567
+ lastError: string;
568
+ }
118
569
  /**
119
- * Record the outcome of a compiled call. Fire-and-forget by default.
120
- *
121
- * Returns a Promise so callers in `sync` mode can await; in async mode the
122
- * promise resolves immediately (after the request is queued) and any
123
- * network error is swallowed/forwarded to onError.
570
+ * Process-local brain write delivery ledger. `acked` is the only number that
571
+ * means "a row landed" — fire-and-forget callers that need delivery evidence
572
+ * read this (or set `BrainConfig.sync`). Cheap enough to attach to any debug
573
+ * or health surface the consumer already exposes.
574
+ */
575
+ declare function brainHealth(): BrainHealthSnapshot;
576
+ /** Read-only view of the pending dead-letter (for consumer-side persistence). */
577
+ declare function peekBrainDeadLetter(): readonly BrainDeadLetterEntry[];
578
+ /**
579
+ * Replay pending dead-letter payloads against the configured brain. Delivered
580
+ * entries are removed; failures increment `attempts` and entries are dropped
581
+ * after 3 total attempts (bounded — never an infinite retry, per the Redis
582
+ * DLQ rule). Safe to call any time; no-ops when unconfigured or already
583
+ * flushing. Also runs opportunistically after any successful write.
124
584
  */
585
+ declare function flushBrainDeadLetter(): Promise<{
586
+ attempted: number;
587
+ delivered: number;
588
+ remaining: number;
589
+ }>;
125
590
  declare function record(input: RecordInput): Promise<void>;
126
591
  /**
127
592
  * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
@@ -168,8 +633,383 @@ interface OutcomePayload {
168
633
  cost_usd_actual?: number;
169
634
  ttft_ms?: number;
170
635
  history_cacheable_tokens?: number;
636
+ effort?: string;
171
637
  history_tokens_at_compile?: number;
638
+ /**
639
+ * Mirrors `ir.constraints.toolOrchestration` from compile time. NULL when
640
+ * the consumer hadn't adopted the constraint (pre-alpha.20). Powers
641
+ * per-mode model-perf queries on the brain (the L-040 parallel-tool
642
+ * cliff lumps DeepSeek sequential perf with parallel without this).
643
+ */
644
+ tool_orchestration?: 'parallel' | 'sequential' | 'either' | null;
645
+ finish_reason?: string;
646
+ total_ms?: number;
647
+ tools_count?: number;
648
+ history_depth?: number;
649
+ system_prompt_chars?: number;
650
+ fell_over_from?: string;
651
+ fallback_reason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
652
+ /**
653
+ * alpha.71 (migration 044) — the precise `errorCode` behind
654
+ * `fallback_reason`. Key OMITTED when no fallback fired, so brains that
655
+ * haven't applied 044 never see it.
656
+ */
657
+ fell_over_error_code?: string;
658
+ /**
659
+ * True when the same-model retry (CallOptions.sameModelRetry) fired
660
+ * during this call. Key OMITTED (not false) when no retry fired — safe
661
+ * against brains that haven't applied migration 039 yet.
662
+ */
663
+ retried_same_model?: boolean;
664
+ /**
665
+ * Per-call SectionRewrite[] captured at compile time. Omitted (sent as
666
+ * undefined → stored NULL) when no rewrites fired. Powers cross-app
667
+ * learning aggregates ("rule X fired N times on (app, model, archetype),
668
+ * downstream outcome quality lifted by M points").
669
+ */
670
+ section_rewrites_applied?: SectionRewrite[] | null;
671
+ /**
672
+ * R0 linkage (§5.0). Parent call's handle when this row is a fan-out branch;
673
+ * key OMITTED (undefined → dropped by JSON.stringify → stored NULL) for a
674
+ * root, safe against pre-042 brains.
675
+ */
676
+ parent_handle?: string;
677
+ /**
678
+ * R0 linkage (§5.0). Root handle of the fan-out trace (= parent_handle when a
679
+ * branch, else this row's own handle). Emitted for every registered compile.
680
+ */
681
+ trace_id?: string;
682
+ /**
683
+ * R0 linkage (§5.0). root | branch | composer. Emitted for every registered
684
+ * compile; surface baselines filter to root/NULL so branch traffic never
685
+ * contaminates a promotion/eval baseline. Release A emits only root/branch.
686
+ */
687
+ fanout_role?: 'root' | 'branch' | 'composer';
688
+ /**
689
+ * RD discipline gate-token accounting (§5.D). Measured token tax of the
690
+ * discipline_contract gate block; 0 when the gate didn't fire.
691
+ */
692
+ discipline_gate_tokens?: number;
693
+ }
694
+ /**
695
+ * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
696
+ *
697
+ * Fires after the consumer's UX surfaces an approve/reject event (e.g., user
698
+ * clicks Approve on a hunt result). Joins to the original `compile_outcomes`
699
+ * row via outcomeId — enables per-(model, archetype) approve-rate measurement
700
+ * once N ≥ 10 outcomes accumulate.
701
+ *
702
+ * Fire-and-forget by default (matches record() semantics). Set BrainConfig.sync
703
+ * = true for runtime contexts that can't tolerate fire-and-forget teardown
704
+ * (Vercel Edge, Cloudflare Workers, AWS Lambda) — see L-086.
705
+ *
706
+ * Returns (alpha.61): `{ok: true}` only when the POST was acknowledged 2xx
707
+ * (sync mode); `{ok: 'queued'}` in fire-and-forget mode (handed to the
708
+ * runtime, NOT acked — read `brainHealth()` for delivery evidence);
709
+ * `{ok: false, reason}` on known failure. Never throws.
710
+ */
711
+ declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
712
+ /**
713
+ * True when the active brain config requests synchronous (awaited) writes.
714
+ * call()'s shadow-probe path reads this to decide whether to await the probe
715
+ * (Edge/Worker/Lambda — L-086) or fire-and-forget (Node). False when no brain
716
+ * is configured.
717
+ */
718
+ declare function isBrainSync(): boolean;
719
+ /**
720
+ * Full-IR inline shadow-probe record input (Shape B, Phase 1 — s51). Carries
721
+ * ONLY response previews + metadata; the prompt (system/context/payload) is
722
+ * never included — `promptHash` is an irreversible grouping key, not content.
723
+ */
724
+ interface ShadowProbeRecordInput {
725
+ appId: string;
726
+ archetype: string;
727
+ family: string;
728
+ candidateModel: string;
729
+ currentModel: string;
730
+ /** Irreversible grouping hash (NOT the prompt). */
731
+ promptHash: string;
732
+ /** Served model's response, truncated (RESPONSE text only — never the prompt). */
733
+ currentResponsePreview?: string;
734
+ /** Candidate model's response, truncated. */
735
+ candidateResponsePreview?: string;
736
+ tokensCurrentIn?: number;
737
+ tokensCurrentOut?: number;
738
+ tokensCandidateIn?: number;
739
+ tokensCandidateOut?: number;
740
+ /**
741
+ * Wall-clock latency of the served call, ms (alpha.46). The third swap-decision
742
+ * axis alongside quality + cost — a verdict needs to know the candidate is
743
+ * slower, not just better/cheaper. Served latency mirrors
744
+ * `compile_outcomes.latency_ms`; carried here so a probe row is self-contained.
745
+ */
746
+ latencyCurrentMs?: number;
747
+ /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
748
+ latencyCandidateMs?: number;
749
+ /**
750
+ * alpha — probe-row class (migration 029; `candidate_error` added by 032).
751
+ * Defaults to `'completed'` (the pre-029 row shape: candidate ran, columns
752
+ * populated). `'aborted_latency_budget'` and `'skipped_slow_tier_sync'` are
753
+ * DIAGNOSTIC rows from sync-mode latency protection; `'candidate_error'`
754
+ * (alpha.53) is the failed-candidate diagnostic — the candidate call
755
+ * errored, with the error class + latency-at-death recorded instead of
756
+ * silence (the IC demo-night probe deaths were invisible for ~90 min under
757
+ * the old record-no-row rule). Diagnostic rows carry no candidate response
758
+ * and no verdict — no false quality signal. A verdict rollup MUST filter to
759
+ * `outcome='completed'`.
760
+ */
761
+ outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
762
+ /**
763
+ * alpha.53 (migration 032) — error class for `outcome='candidate_error'`
764
+ * rows. Values follow execute()'s taxonomy (`rate_limit`, `timeout`,
765
+ * `server_error`, `model_not_found`, `auth`, `invalid_request`, `unknown`)
766
+ * plus `execute_rejected` (the execute promise rejected outright). NULL /
767
+ * omitted on all other row classes.
768
+ */
769
+ errorClass?: string;
770
+ }
771
+ /**
772
+ * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
773
+ * Exported so a test can assert the G3 privacy invariant: the row carries NO
774
+ * prompt/system/context text — only response previews + metadata + a hash.
775
+ *
776
+ * Phase 1 (judge: 'off'): `judge_verdict` / `judge_score` are null — the row
777
+ * is an unjudged sample for the Phase-2 offline batch judge. `prompt_fidelity`
778
+ * is 1.0 by construction (the candidate ran the full IR, not a truncated
779
+ * preview), and `replay_source='inline-full-ir'` marks it as a trustworthy row
780
+ * (vs the watchers' lossy `replay-preview`).
781
+ */
782
+ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
783
+ app_id: string;
784
+ intent_archetype: string;
785
+ family: string;
786
+ candidate_model: string;
787
+ current_model: string;
788
+ prompt_hash: string;
789
+ current_response: string | null;
790
+ candidate_response: string | null;
791
+ judge_verdict: null;
792
+ judge_score: null;
793
+ tokens_current_in: number | null;
794
+ tokens_current_out: number | null;
795
+ tokens_candidate_in: number | null;
796
+ tokens_candidate_out: number | null;
797
+ latency_current_ms: number | null;
798
+ latency_candidate_ms: number | null;
799
+ prompt_fidelity: number;
800
+ replay_source: 'inline-full-ir';
801
+ outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
802
+ error_class: string | null;
803
+ };
804
+ /**
805
+ * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
806
+ * default; honors `BrainConfig.sync` (L-086). Never throws — failures route to
807
+ * onError. Mirrors record()'s POST shape; consumer proxies forward
808
+ * `/probe_outcomes` the same way they forward `/outcomes`.
809
+ */
810
+ declare function recordShadowProbe(input: ShadowProbeRecordInput): Promise<void>;
811
+ /**
812
+ * Golden-IR capture input. UNLIKE every other brain write, this row carries the
813
+ * RAW full PromptIR — an explicit, documented posture change from the s51
814
+ * "brain holds no raw consumer prompts" rule, gated on consumer opt-in
815
+ * (`KGAUTO_GOLDEN_CAPTURE` env / `CallOptions.goldenCapture`). The `consent`
816
+ * field records the provenance of that opt-in at capture time.
817
+ */
818
+ interface GoldenIrRecordInput {
819
+ appId: string;
820
+ archetype: string;
821
+ /** hashShape() of the call at compile time (peek before record() pops). */
822
+ shapeKey?: string;
823
+ /** The full PromptIR, verbatim. Plain JSON by construction (ir.ts). */
824
+ ir: unknown;
825
+ incumbentModel: string;
826
+ incumbentOutput?: string;
827
+ incumbentLatencyMs?: number;
828
+ incumbentTokensIn?: number;
829
+ incumbentTokensOut?: number;
830
+ /** 'sampled' (capture flag fired on live traffic) | 'curated' (operator). */
831
+ source: 'sampled' | 'curated';
832
+ /** Consent provenance, e.g. 'KGAUTO_GOLDEN_CAPTURE=0.1 (consumer env opt-in)'. */
833
+ consent: string;
834
+ /** Optional link back to the compile handle of the captured call. */
835
+ outcomeHandle?: string;
836
+ }
837
+ /** Pure builder for the `kgauto_golden_irs` row (snake_case wire shape). */
838
+ declare function buildGoldenIrRow(input: GoldenIrRecordInput): {
839
+ app_id: string;
840
+ intent_archetype: string;
841
+ shape_key: string | null;
842
+ ir: unknown;
843
+ incumbent_model: string;
844
+ incumbent_output: string | null;
845
+ incumbent_latency_ms: number | null;
846
+ incumbent_tokens_in: number | null;
847
+ incumbent_tokens_out: number | null;
848
+ source: 'sampled' | 'curated';
849
+ consent: string;
850
+ outcome_handle: string | null;
851
+ };
852
+ /**
853
+ * Persist one golden IR to `kgauto_golden_irs`. Same G1 write-leg discipline as
854
+ * every other brain route (redirect check, ledger, dead-letter); fire-and-forget
855
+ * by default, honors `BrainConfig.sync`. Never throws.
856
+ */
857
+ declare function recordGoldenIr(input: GoldenIrRecordInput): Promise<void>;
858
+
859
+ /**
860
+ * Golden-set eval engine (alpha.62, eval spine — design brief 2026-07-17).
861
+ *
862
+ * Implements the quality-floor-guarded model-swap contract:
863
+ *
864
+ * > A model replaces another on a surface only by demonstrating
865
+ * > same-or-better quality on that surface's real workload — never by
866
+ * > price, recency, or judgment alone.
867
+ *
868
+ * One eval run: load the active golden set for (app, archetype), replay every
869
+ * IR on BOTH the incumbent and the candidate (fresh outputs on both sides —
870
+ * fair comparison, no stale stored output), apply mechanical hard floors,
871
+ * then a pairwise LLM judge (order-swapped to cancel position bias), and
872
+ * aggregate under the non-inferiority rule:
873
+ *
874
+ * promote-ready ⇔ wins-or-ties ≥ threshold (default 80%)
875
+ * AND zero hard-floor violations
876
+ * AND candidate p50 latency ≤ ratio × incumbent p50
877
+ *
878
+ * Evidence lands as brain rows: one `kgauto_golden_eval_runs` aggregate + one
879
+ * `probe_outcomes` row per case (`replay_source='golden-replay'`, full
880
+ * fidelity by construction) + an evidence-attached advisory on the consumer's
881
+ * advisory surface (trust-ladder Stage 1: eval runs, human clicks promote).
882
+ *
883
+ * Judging is PAIRWISE, not absolute — it operationalizes the quality-floor
884
+ * Common Pattern directly ("same or better, never less"). Each pair is judged
885
+ * twice with A/B order swapped; disagreement between the two orders is scored
886
+ * a tie (the honest reading of positional noise).
887
+ *
888
+ * This module is operator-grade: it talks to the brain via direct PostgREST
889
+ * with a service key (the watchers' convention), never through consumer
890
+ * proxies, and it deliberately does NOT call record() — eval traffic must not
891
+ * pollute compile_outcomes.
892
+ */
893
+
894
+ /**
895
+ * What "better" means per archetype. Fed verbatim into the pairwise judge
896
+ * prompt. Kept deliberately short — the judge sees the full request, so the
897
+ * rubric only needs to name the failure modes that matter for the archetype.
898
+ */
899
+ declare const JUDGE_RUBRICS: Record<string, string>;
900
+ declare function rubricFor(archetype: string): string;
901
+ /** Render the golden IR's request for the judge (system sections + user turn). */
902
+ declare function renderIrForJudge(ir: PromptIR): string;
903
+ declare function buildPairwiseJudgePrompt(args: {
904
+ archetype: string;
905
+ renderedInput: string;
906
+ outputA: string;
907
+ outputB: string;
908
+ }): string;
909
+ type PairwiseWinner = 'A' | 'B' | 'tie';
910
+ /** Parse the judge's JSON verdict. Returns undefined when unparseable. */
911
+ declare function parseJudgeVerdict(raw: string): {
912
+ winner: PairwiseWinner;
913
+ rationale?: string;
914
+ } | undefined;
915
+ /**
916
+ * Combine the two order-swapped verdicts into a case verdict. Both verdicts
917
+ * are expressed in incumbent/candidate terms BEFORE this call (the caller
918
+ * un-swaps run 2). Agreement → that verdict; disagreement → 'tied' (positional
919
+ * noise reads as a tie, never as a win).
920
+ */
921
+ declare function combineOrderSwappedVerdicts(run1: 'candidate-better' | 'current-better' | 'tied', run2: 'candidate-better' | 'current-better' | 'tied'): 'candidate-better' | 'current-better' | 'tied';
922
+ interface GoldenEvalOptions {
923
+ appId: string;
924
+ archetype: string;
925
+ candidateModel: string;
926
+ /**
927
+ * Incumbent to compare against. Default: the most frequent incumbent_model
928
+ * across the loaded golden set (the surface's de-facto leader).
929
+ */
930
+ incumbentModel?: string;
931
+ /** Judge model id. Default 'claude-opus-4-8' (judge chain tier 0). */
932
+ judgeModel?: string;
933
+ /** Max golden cases to load (newest first). Default 50. */
934
+ limit?: number;
935
+ /** Non-inferiority threshold on wins-or-ties. Default 0.8. */
936
+ winOrTieThreshold?: number;
937
+ /** Latency hard floor: candidate p50 ≤ ratio × incumbent p50. Default 3. */
938
+ latencyFloorRatio?: number;
939
+ /** Minimum judged cases for a non-inconclusive verdict. Default 5. */
940
+ minJudgeableCases?: number;
941
+ /** What fired the eval. Default 'manual' (Stage 1). */
942
+ triggerSource?: 'manual' | 'supply' | 'price' | 'demand';
943
+ /** Brain access — direct PostgREST (operator convention). */
944
+ supabaseUrl: string;
945
+ serviceKey: string;
946
+ /** Provider keys for the replay + judge calls. Default: process.env. */
947
+ apiKeys?: ApiKeys;
948
+ fetchImpl?: typeof fetch;
949
+ /** Replay + judge but write NOTHING to the brain. */
950
+ dryRun?: boolean;
951
+ onProgress?: (message: string) => void;
952
+ }
953
+ interface GoldenEvalCase {
954
+ goldenIrId: number;
955
+ verdict: 'candidate-better' | 'tied' | 'current-better' | 'inconclusive';
956
+ judgeRationale?: string;
957
+ /** Hard-floor violations on the candidate side for this case. */
958
+ floorViolations: Array<'empty' | 'schema' | 'candidate_error'>;
959
+ errorClass?: string;
960
+ incumbent?: {
961
+ latencyMs: number;
962
+ tokensIn: number;
963
+ tokensOut: number;
964
+ text: string;
965
+ };
966
+ candidate?: {
967
+ latencyMs: number;
968
+ tokensIn: number;
969
+ tokensOut: number;
970
+ text: string;
971
+ };
972
+ /** Case excluded from the denominator (incumbent replay/judge failed). */
973
+ excludedReason?: string;
974
+ }
975
+ interface GoldenEvalRunResult {
976
+ verdict: 'promote-ready' | 'not-inferior' | 'inconclusive';
977
+ runId?: number;
978
+ appId: string;
979
+ archetype: string;
980
+ incumbentModel: string;
981
+ candidateModel: string;
982
+ judgeModel: string;
983
+ nCases: number;
984
+ wins: number;
985
+ ties: number;
986
+ losses: number;
987
+ floorViolations: number;
988
+ floorDetail: Record<string, number>;
989
+ winOrTieRatio: number | null;
990
+ latencyRatio: number | null;
991
+ costIncumbentUsd: number | null;
992
+ costCandidateUsd: number | null;
993
+ advisoryOutcomeId?: number;
994
+ cases: GoldenEvalCase[];
995
+ notes: string[];
172
996
  }
997
+ declare function runGoldenEval(opts: GoldenEvalOptions): Promise<GoldenEvalRunResult>;
998
+
999
+ /**
1000
+ * alpha.60 — the library's own version, baked as a constant so Edge/Worker
1001
+ * runtimes (no fs, no require) can report it on wire surfaces. First
1002
+ * consumer: `createKeyHealthRoute` carries it as `library_version`, which is
1003
+ * how the operator dashboard's Fleet panel sees per-consumer vendor drift
1004
+ * LIVE instead of via wrap-time package.json probes (the L-093 family
1005
+ * "declared state lags actual" fix at the vendor-version axis — s47 found
1006
+ * IC 13 alphas stale that way).
1007
+ *
1008
+ * Kept in sync with package.json by hand at each version bump; the drift
1009
+ * guard in `tests/version.test.ts` fails the suite (and therefore
1010
+ * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
1011
+ */
1012
+ declare const LIBRARY_VERSION = "2.0.0-alpha.71";
173
1013
 
174
1014
  /**
175
1015
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -222,6 +1062,34 @@ interface LLMJudgeOptions {
222
1062
  */
223
1063
  declare function buildLLMJudge(opts: LLMJudgeOptions): AppOracle;
224
1064
 
1065
+ /**
1066
+ * Resolve the effective ArchetypeConvention[] for a given selected profile,
1067
+ * walking family inheritance once. Model-specific entries on the selected
1068
+ * profile take precedence over family-level entries for the same archetype.
1069
+ *
1070
+ * Pure; safe to call from any context (probe-watcher uses the same logic
1071
+ * via `applyArchetypeConvention`).
1072
+ */
1073
+ declare function resolveConventionsForProfile(profile: ModelProfile): ArchetypeConvention[];
1074
+ /**
1075
+ * Pure helper: apply the matching ArchetypeConvention's suffix (and
1076
+ * prefix, when meaningful) to a plain prompt-text string. Used by the
1077
+ * exclusion-probe-watcher (`probeOne`) so probe calls carry the same
1078
+ * forcing-function shape consumers see at compile time. Without this,
1079
+ * every reasoner probe on a decisive archetype gets unfairly stay-excluded
1080
+ * for hedging — as ID 20 demonstrated on 2026-05-28.
1081
+ *
1082
+ * Resolution: looks up the family-rep profile for `family` and reads its
1083
+ * `archetypeConventions`. Returns the original text unchanged when no
1084
+ * convention matches or when the suffix is already present.
1085
+ *
1086
+ * @param promptText raw user-prompt text (or prompt_preview from outcome)
1087
+ * @param archetype intent_archetype from the finding row
1088
+ * @param family family tag from deriveFamilyFromModelId / brain row
1089
+ * @returns text with prefix/suffix applied (idempotent)
1090
+ */
1091
+ declare function applyArchetypeConvention(promptText: string, archetype: string, family: string): string;
1092
+
225
1093
  /**
226
1094
  * Tokenizer abstraction.
227
1095
  *
@@ -245,6 +1113,75 @@ declare function resetTokenizer(): void;
245
1113
  */
246
1114
  declare function countTokens(text: string): number;
247
1115
 
1116
+ /**
1117
+ * archetype-fits — alpha.43.
1118
+ *
1119
+ * Static table of "this archetype tends to be a better fit for this family"
1120
+ * recommendations. Powers the `cross-family-fit-candidate` compile-time
1121
+ * advisor (see `advisor-rules/cross-family-fit.ts`).
1122
+ *
1123
+ * Strategic framing (Sacha, 2026-05-28): "If we get better results and
1124
+ * better price then we do. Even if volume is currently low, that's not an
1125
+ * argument to not do it. Volume can increase quickly if tools is great to
1126
+ * use, let's not create future bottlenecks because we could have wired in
1127
+ * better solution at moment of knowing."
1128
+ *
1129
+ * The convention substrate (passApplyConventions) is the NEGATIVE side:
1130
+ * make a family usable on archetypes it currently fails. This table is the
1131
+ * POSITIVE side: actively surface that a different family is the better
1132
+ * fit for the archetype's shape — even when current volume is low.
1133
+ *
1134
+ * Entries are added only when:
1135
+ * - the archetype's shape and the family's behavior have a clear
1136
+ * architectural fit (not vibes)
1137
+ * - real-world evidence (brain rows, probe outcomes, or published
1138
+ * benchmark) backs the claim, OR the reasoning is structurally so clear
1139
+ * that "wait for volume" would create a future bottleneck
1140
+ *
1141
+ * Alpha.43 ships two entries — `plan` and `critique`. Both fit the
1142
+ * reasoner-family architectural read: plan is multi-step reasoning;
1143
+ * critique rewards epistemic humility and explicit reasoning. Other
1144
+ * archetype-family-fits ride later alphas as evidence accumulates.
1145
+ *
1146
+ * Anti-pattern: do NOT add archetype-family-fits for archetypes where the
1147
+ * fit is unclear (summarize, classify, extract, hunt with parallel tools).
1148
+ * The advisor only earns trust when its recommendations land.
1149
+ */
1150
+
1151
+ /**
1152
+ * One archetype-family-fit recommendation. Read by the compile-time
1153
+ * `cross-family-fit-candidate` advisor to decide when to surface a positive
1154
+ * recommendation. The advisor pulls `costGuidance` verbatim into the
1155
+ * advisory message.
1156
+ */
1157
+ interface ArchetypeFamilyFit {
1158
+ /** Intent archetype this fit applies to. */
1159
+ archetype: IntentArchetypeName;
1160
+ /** Family tag that fits the archetype better than alternatives. Matches the
1161
+ * same family taxonomy used by `family-resolution.deriveFamilyFromModelId`
1162
+ * (e.g. `'deepseek-reasoner'`, `'gemini-flash'`, `'claude-opus'`). */
1163
+ betterFitFamily: string;
1164
+ /** Architectural / evidentiary justification. Appears in the advisor's
1165
+ * internal logs and the advisory `evidence` payload, NOT verbatim in the
1166
+ * consumer-facing message. */
1167
+ reason: string;
1168
+ /** Cost-context clause surfaced VERBATIM in the consumer-facing advisory
1169
+ * message (e.g. "substantially cheaper at current pricing"). Keep
1170
+ * declarative; the advisor wraps this into the larger sentence. */
1171
+ costGuidance: string;
1172
+ }
1173
+ /**
1174
+ * Frozen registry. Add entries by extending the array. Order is irrelevant
1175
+ * — the advisor filters by `(archetype, currentFamily)` independently.
1176
+ */
1177
+ declare const ARCHETYPE_FAMILY_FITS: readonly ArchetypeFamilyFit[];
1178
+ /**
1179
+ * Pure lookup: does `(archetype, currentFamily)` have a better-fit family?
1180
+ * Returns the fit entry when the current family is NOT the better fit; null
1181
+ * otherwise. Used by the advisor to decide whether to fire.
1182
+ */
1183
+ declare function findBetterFit(archetype: string, currentFamily: string): ArchetypeFamilyFit | null;
1184
+
248
1185
  /**
249
1186
  * Best-practice advisor — alpha.6 Phase 1.
250
1187
  *
@@ -275,10 +1212,1801 @@ declare function countTokens(text: string): number;
275
1212
  /** Subset of CompileResult fields the advisor needs. */
276
1213
  type AdvisorContext = Pick<CompileResult, 'target' | 'provider' | 'tokensIn' | 'diagnostics'>;
277
1214
  /**
278
- * Run all Phase 1 rules and return collected advisories. Order is fixed
279
- * (same as the rule list above) so output is stable across runs.
1215
+ * Optional Phase 2 (alpha.22) context fallback chain + a profile resolver
1216
+ * for cross-model comparison. Three new rules
1217
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) consume
1218
+ * this to surface measurement-substrate signals (alpha.20 clean-attribution +
1219
+ * alpha.21 grounding labels) as actionable consumer guidance.
1220
+ *
1221
+ * When `fallbackChain` is empty, rules 1 + 3 stay silent (nothing to
1222
+ * compare against). When `profileResolver` is omitted, the rules degrade
1223
+ * gracefully — they can still inspect the chosen profile but not chain
1224
+ * alternatives. Rule 2 (`model-stale-evidence`) is independent of chain
1225
+ * shape and works on the chosen model alone.
1226
+ */
1227
+ interface RunAdvisorPhase2Context {
1228
+ fallbackChain: string[];
1229
+ profileResolver?: (id: string) => ModelProfile | undefined;
1230
+ /**
1231
+ * alpha.29 — translator rewrites that fired this compile. When a rewrite
1232
+ * cleared the cliff (e.g. `tool_call_contract` → sequential-tool preamble
1233
+ * + `parallelToolCalls: false`), the matching cliff advisor
1234
+ * (`archetype-perf-floor-breach`) MUST suppress for the same call. Without
1235
+ * suppression both fire — the advisory contradicts the rewrite ("cliff is
1236
+ * unaddressed" vs "we just addressed it").
1237
+ *
1238
+ * Empty array / undefined → no suppression (alpha.28 behavior preserved).
1239
+ */
1240
+ sectionRewritesApplied?: SectionRewrite[];
1241
+ }
1242
+ /**
1243
+ * alpha.42 — rule codes whose advisories are positioned for kgauto (not
1244
+ * the consumer) to act on. Used by `compile()` to default the `ownership`
1245
+ * stamp on each advisory when the rule didn't self-declare. Consumer-side
1246
+ * rules don't need to be listed — they default to `'consumer-actionable'`
1247
+ * via fall-through.
1248
+ *
1249
+ * - `model-stale-evidence`: kgauto's profile data is out of date; the
1250
+ * consumer can't fix that, kgauto needs to update profiles or refresh
1251
+ * archetypePerf scores.
1252
+ * - `promote-ready`: kgauto's promotion-probe-watcher detected a
1253
+ * candidate model worth promoting; consumer-side adoption is downstream
1254
+ * of kgauto adding it to the chain / family taxonomy.
1255
+ *
1256
+ * Frozen so consumers and tests can't mutate the global ownership map.
1257
+ */
1258
+ declare const PRODUCER_OWNED_RULE_CODES: ReadonlySet<string>;
1259
+ /**
1260
+ * alpha.42 — pure function used by `compile()` to decide ownership for an
1261
+ * advisory. Rule-self-declared wins; falls back to the static map; defaults
1262
+ * `consumer-actionable`. Exported so consumer-side code (or a Glass-Box
1263
+ * renderer) can derive the same classification from a rule code alone
1264
+ * without needing the advisory object.
1265
+ */
1266
+ declare function deriveOwnership(code: string, selfDeclared?: 'consumer-actionable' | 'producer-owned'): 'consumer-actionable' | 'producer-owned';
1267
+ /**
1268
+ * Run all phased rules and return collected advisories. Order is fixed so
1269
+ * output is stable across runs. The `policy` argument is alpha.9 — the
1270
+ * `single-model-array` rule needs to know whether the consumer explicitly
1271
+ * declared `posture: 'locked'` (in which case single-model is intentional
1272
+ * and shouldn't warn).
1273
+ *
1274
+ * `phase2` is alpha.22 — gives the advisor access to the fallback chain +
1275
+ * a profile resolver so the three new compile-time recommendation rules
1276
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) can
1277
+ * compare the chosen model against in-chain alternatives. Optional for
1278
+ * backward compatibility with consumers calling `runAdvisor()` directly.
1279
+ */
1280
+ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile, policy?: CompilePolicy, phase2?: RunAdvisorPhase2Context): BestPracticeAdvisory[];
1281
+
1282
+ /**
1283
+ * Translator primitive — alpha.31.
1284
+ *
1285
+ * Pure function. Walks `IR.sections`, matches each section's `kind` against
1286
+ * a per-rule dispatch table keyed on (kind, profile, archetype), and applies
1287
+ * a model-aware rewrite when a rule fires. Returns the rewritten IR + the
1288
+ * list of rewrites for `CompileResult.sectionRewritesApplied` and brain
1289
+ * persistence.
1290
+ *
1291
+ * This is the s37 translator-framing eureka in code: kgauto graduates from
1292
+ * "gate" (alpha.28's cliff advisor: "consumer must accept adapter") to
1293
+ * "translator" (alpha.29: "consumer declared the section kind, kgauto
1294
+ * applies the adapter at compile time without consumer-side branching").
1295
+ *
1296
+ * Rules shipped:
1297
+ *
1298
+ * alpha.29 — tool_call_contract + archetypePerf[archetype] < TRANSLATOR_FLOOR
1299
+ * → prepend sequential-tool-pattern guidance
1300
+ * → emit wireOverrides: { parallelToolCalls: false }
1301
+ * → rule_id: 'sequential-tool-cliff-below-floor'
1302
+ *
1303
+ * alpha.31 — narration_contract + profile.provider === 'anthropic'
1304
+ * → prepend terse-log narration guidance
1305
+ * → no wireOverrides
1306
+ * → rule_id: 'narration-drift-anthropic'
1307
+ *
1308
+ * alpha.31 — narration_contract + profile.provider === 'deepseek'
1309
+ * → prepend <thinking>-suppression guidance
1310
+ * → no wireOverrides
1311
+ * → rule_id: 'narration-thinking-leak-deepseek'
1312
+ *
1313
+ * Per-rule walk (alpha.31 refactor): the alpha.30 short-circuit
1314
+ * `if (!cliffFires) return passthrough` was correct when only the
1315
+ * cliff-gated tool_call_contract rule existed; alpha.31's narration rules
1316
+ * fire on every call regardless of cliff (narration drift is steady-state,
1317
+ * not a cliff condition). Each section now consults the dispatch table
1318
+ * independently — first-match wins per (section.kind, profile, archetype).
1319
+ *
1320
+ * **Interaction with the cliff advisor (alpha.28):** when this translator
1321
+ * fires for a `tool_call_contract` section, the advisor's
1322
+ * `archetype-perf-floor-breach` rule MUST suppress for the same call — the
1323
+ * cliff was structurally cleared by the rewrite, not unaddressed. The
1324
+ * suppression check lives in `advisor.ts` and consults the
1325
+ * `CompileResult.sectionRewritesApplied` list.
1326
+ *
1327
+ * Design contracts:
1328
+ * command-center/advisory/kgauto/2026-05-21_alpha-29-translator-and-advisories-api.md
1329
+ * command-center/advisory/kgauto/2026-05-22_alpha-31-narration-contract.md
1330
+ */
1331
+
1332
+ /**
1333
+ * Re-export of `ARCHETYPE_FLOOR_DEFAULT` as the canonical "translator fires
1334
+ * below this score" threshold. Same constant as the cliff advisor — the
1335
+ * single threshold is shared (alpha.28's "below this, advisor warns"; alpha.29's
1336
+ * "below this, translator AUTO-APPLIES the adapter").
1337
+ */
1338
+ declare const TRANSLATOR_FLOOR = 6;
1339
+ /**
1340
+ * Stable identifier of the alpha.29 sequential-tool rule. Surfaces on
1341
+ * `SectionRewrite.rule` and in brain aggregates. The brain treats this
1342
+ * identifier together with the preamble string as the rule's wire
1343
+ * fingerprint — both stay byte-stable across releases.
1344
+ */
1345
+ declare const RULE_SEQUENTIAL_TOOL_CLIFF = "sequential-tool-cliff-below-floor";
1346
+ interface ApplySectionRewritesArgs {
1347
+ ir: PromptIR;
1348
+ profile: ModelProfile;
1349
+ archetype: IntentArchetypeName;
1350
+ /**
1351
+ * alpha.68 / Release A — resolved output shape for Factor C (§5.D). `'json'`
1352
+ * ⇒ structured surface (the discipline gate MUST NOT fire — gates 5+6 are
1353
+ * shape-altering and would break the consumer's parser). `'text'` ⇒ free-form
1354
+ * surface (the gate may fire). Optional: when omitted, derived from
1355
+ * `ir.constraints?.structuredOutput` (true ⇒ 'json', else 'text') so callers
1356
+ * / tests need not pass it. compile() passes it explicitly.
1357
+ */
1358
+ outputMode?: OutputMode;
1359
+ }
1360
+ interface ApplySectionRewritesResult {
1361
+ /**
1362
+ * IR with section.text fields possibly rewritten. When no rewrites fired,
1363
+ * this is identical to the input IR (referentially distinct array but
1364
+ * same section payloads).
1365
+ */
1366
+ rewrittenIR: PromptIR;
1367
+ /**
1368
+ * One entry per section the translator rewrote. Empty array when no
1369
+ * rules fired. Order matches the corresponding section in
1370
+ * `rewrittenIR.sections`.
1371
+ */
1372
+ rewrites: SectionRewrite[];
1373
+ }
1374
+ /**
1375
+ * Pure function. Apply model-aware section rewrites to the IR at compile time.
1376
+ *
1377
+ * Discipline:
1378
+ * - Never mutates the input IR; returns a new IR with new sections array
1379
+ * when at least one rewrite fired; otherwise returns the input IR by
1380
+ * reference (referential identity preserved on no-op).
1381
+ * - Sections without a `kind` (or `kind === 'arbitrary'`) pass through
1382
+ * unchanged.
1383
+ * - Empty `sections` array → returns `{ rewrittenIR: ir, rewrites: [] }`.
1384
+ * - Sections of the same `kind` are processed in array order; first-match
1385
+ * wins per section. (Today every rule is a single-match rule.)
1386
+ *
1387
+ * @example
1388
+ * ```ts
1389
+ * import { applySectionRewrites } from '@warmdrift/kgauto-compiler';
1390
+ * import { getProfile } from '@warmdrift/kgauto-compiler';
1391
+ *
1392
+ * const { rewrittenIR, rewrites } = applySectionRewrites({
1393
+ * ir,
1394
+ * profile: getProfile('deepseek-v4-pro'),
1395
+ * archetype: 'hunt',
1396
+ * });
1397
+ * if (rewrites.length > 0) console.log('translator fired:', rewrites);
1398
+ * ```
1399
+ */
1400
+ declare function applySectionRewrites(args: ApplySectionRewritesArgs): ApplySectionRewritesResult;
1401
+
1402
+ /**
1403
+ * advisories-api — structured advisories API (alpha.29 Workstream B).
1404
+ *
1405
+ * Closes the L-117 family bottleneck: kgauto's `result.advisories[]` (the
1406
+ * compile-time warnings about caching-off, tool-bloat, archetype-perf-floor
1407
+ * breaches, etc.) used to disappear after the consumer read the compile
1408
+ * result. The s34 caching-off advisory pattern is the canonical failure: an
1409
+ * advisory fired 100+ times in 24h on `generate::sonnet` at 99.4% empty
1410
+ * rate, and nobody knew because there was no structured channel to surface
1411
+ * "what's open right now?"
1412
+ *
1413
+ * Migration 020 ships the substrate: `compile_outcome_advisories` gains
1414
+ * lifecycle columns (`resolved_at`, `resolution_source`, `resolution_note`)
1415
+ * and the `actionable_advisories_v` view rolls per-firing rows into
1416
+ * per-(app_id, code) tuples with deterministic stable ids + server-side
1417
+ * auto-resolution.
1418
+ *
1419
+ * Public surface:
1420
+ * getActionableAdvisories({ appId, severity?, status?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1421
+ * → Promise<ActionableAdvisory[]>
1422
+ *
1423
+ * markAdvisoryResolved({ id, resolutionNote?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1424
+ * → Promise<{ ok: true } | { ok: false; reason: string }>
1425
+ *
1426
+ * Both functions are pure I/O — no module-level state. The fetch wiring
1427
+ * mirrors `createProxyHandler` in `glassbox-routes/proxy.ts`: scoped JWT in
1428
+ * `Authorization: Bearer`, `apikey` header carries the anon key.
1429
+ *
1430
+ * The auto-resolution rule is enforced server-side in `actionable_advisories_v`:
1431
+ * • Latest firing > 14 days ago → status='resolved' (auto-pruned)
1432
+ * • All firings have resolved_at set → status='resolved' (consumer-marked)
1433
+ * • Otherwise → status='open'
1434
+ *
1435
+ * `markAdvisoryResolved` is the consumer override: "I fixed it; the next
1436
+ * firing will reopen the rule, but until then it stays resolved."
1437
+ */
1438
+
1439
+ /**
1440
+ * Severity of an advisory. Maps to the `level` column on
1441
+ * `compile_outcome_advisories` (info | warn | critical).
1442
+ */
1443
+ type AdvisorySeverity = 'info' | 'warn' | 'critical';
1444
+ /**
1445
+ * Status of an advisory rollup.
1446
+ *
1447
+ * - `open` — at least one unresolved firing in the last 14 days
1448
+ * - `resolved` — either auto-pruned (no firings >14d) or consumer-marked
1449
+ * - `snoozed` — reserved for alpha.30+ (snooze-until-date); type-accepted
1450
+ * today but the view will never emit this value
1451
+ */
1452
+ type AdvisoryStatus = 'open' | 'snoozed' | 'resolved';
1453
+ /**
1454
+ * Source of resolution when status='resolved'.
1455
+ *
1456
+ * - `auto` — server-side rule auto-pruned (>14d since last firing)
1457
+ * - `consumer-marked` — consumer called `markAdvisoryResolved`
1458
+ * - `declined` — reserved (alpha.30+: consumer marked the suggestion
1459
+ * inapplicable; the advisor will still fire but UIs can hide it)
1460
+ */
1461
+ type AdvisoryResolutionSource = 'auto' | 'consumer-marked' | 'declined';
1462
+ /**
1463
+ * Suggested-fix metadata. `null` when the advisor has no actionable fix
1464
+ * (info-level rules can be observational). When set, the consumer's
1465
+ * Admin UI can render a one-click apply (alpha.30+) or surface the
1466
+ * before/after diff inline.
1467
+ */
1468
+ interface AdvisorySuggestedFix {
1469
+ type: 'config-change' | 'one-liner' | 'env-var' | 'manual';
1470
+ /** File:line hint if kgauto can infer (reserved — alpha.30+). */
1471
+ siteHint?: string;
1472
+ before?: string;
1473
+ after?: string;
1474
+ docsLink?: string;
1475
+ }
1476
+ /**
1477
+ * Per-(app_id, code) advisory rollup. The `id` is stable across polls
1478
+ * until the rule auto-resolves and re-opens (a new firing after the 14d
1479
+ * boundary advances `opened_at` → new id). Treat id-changes as
1480
+ * intentional "fresh re-open" signals.
1481
+ *
1482
+ * Wire-shape from `actionable_advisories_v`. The transformer maps the
1483
+ * view's snake_case columns to camelCase. See `feedback_typed_boundary_transformers.md`
1484
+ * (L-118) for the rationale.
1485
+ */
1486
+ interface ActionableAdvisory {
1487
+ id: string;
1488
+ rule: string;
1489
+ severity: AdvisorySeverity;
1490
+ openedAt: string;
1491
+ lastObservedAt: string;
1492
+ observationCount: number;
1493
+ appliesTo: {
1494
+ archetype?: IntentArchetypeName;
1495
+ model?: string;
1496
+ callSiteHint?: string;
1497
+ };
1498
+ message: string;
1499
+ suggestedFix: AdvisorySuggestedFix | null;
1500
+ /** Reserved — always `false` in alpha.29. alpha.30+ ships actual auto-apply. */
1501
+ autoApplicable: boolean;
1502
+ status: AdvisoryStatus;
1503
+ resolvedAt?: string;
1504
+ resolutionSource?: AdvisoryResolutionSource;
1505
+ resolutionNote?: string;
1506
+ }
1507
+ /**
1508
+ * Filter + transport for `getActionableAdvisories`. The brain JWT must
1509
+ * carry an `app_id` claim matching `opts.appId` — RLS enforces tenant
1510
+ * isolation on the underlying table, so a mismatch silently returns [].
1511
+ */
1512
+ interface GetActionableAdvisoriesOptions {
1513
+ appId: string;
1514
+ /** Severity filter; if omitted, all severities are returned. */
1515
+ severity?: AdvisorySeverity;
1516
+ /** Status filter; defaults to 'open'. Pass 'all' for the full set. */
1517
+ status?: 'open' | 'snoozed' | 'resolved' | 'all';
1518
+ brainEndpoint: string;
1519
+ brainJwt: string;
1520
+ brainAnonKey: string;
1521
+ fetch?: typeof fetch;
1522
+ }
1523
+ interface MarkAdvisoryResolvedOptions {
1524
+ /** Stable id from a prior `getActionableAdvisories` call. */
1525
+ id: string;
1526
+ resolutionNote?: string;
1527
+ brainEndpoint: string;
1528
+ brainJwt: string;
1529
+ brainAnonKey: string;
1530
+ fetch?: typeof fetch;
1531
+ }
1532
+ /**
1533
+ * Query the open advisory set for an app. Pulls from
1534
+ * `actionable_advisories_v` (per-(app_id, code) rollup with stable ids
1535
+ * + server-side auto-resolution).
1536
+ *
1537
+ * Default behavior (no status filter): returns only `status='open'`.
1538
+ * Pass `status: 'all'` to see resolved + open together — useful for
1539
+ * Admin UIs that show "recently fixed" badges.
1540
+ *
1541
+ * Fetch failures bubble out as thrown Errors. (`markAdvisoryResolved`
1542
+ * uses the ok/reason envelope; this read path throws to match
1543
+ * existing kgauto query semantics where the consumer can decide to
1544
+ * retry or render an error state.)
1545
+ */
1546
+ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions): Promise<ActionableAdvisory[]>;
1547
+ /**
1548
+ * Mark an advisory as consumer-resolved.
1549
+ *
1550
+ * Lookup strategy:
1551
+ * 1. Query `actionable_advisories_v?id=eq.<id>` to find the (app_id, code)
1552
+ * tuple for this advisory.
1553
+ * 2. PATCH the latest unresolved firing in `compile_outcome_advisories`
1554
+ * matching that tuple via the underlying outcome's app_id.
1555
+ *
1556
+ * The (app_id, code) lookup is necessary because `compile_outcome_advisories`
1557
+ * has no `app_id` column — it inherits scope via the FK to compile_outcomes.
1558
+ * PostgREST cannot PATCH with a JOIN predicate, so the markAdvisoryResolved
1559
+ * path is a two-step round-trip. The cost is one extra GET per resolve call;
1560
+ * acceptable because marks are low-frequency operator actions, not per-call
1561
+ * hot path.
1562
+ *
1563
+ * Idempotent re-marks: if the advisory is already resolved (no unresolved
1564
+ * firings match), the PATCH affects zero rows and the call still returns
1565
+ * `ok: true`. The function returns `ok: false` only on transport / auth /
1566
+ * lookup failures.
1567
+ *
1568
+ * Returns ok/reason envelope (vs throwing) because consumer Admin UIs
1569
+ * typically want to render the failure inline rather than crash.
1570
+ */
1571
+ declare function markAdvisoryResolved(opts: MarkAdvisoryResolvedOptions): Promise<{
1572
+ ok: true;
1573
+ } | {
1574
+ ok: false;
1575
+ reason: string;
1576
+ }>;
1577
+ /**
1578
+ * Resolution sources supported by the alpha.39 `markExclusionFindingHandled`
1579
+ * API. Mirrors the subset of `exclusion_findings.resolution_source` CHECK
1580
+ * constraint values that consumers can self-set:
1581
+ *
1582
+ * - `'consumer-marked'` — generic "we've handled this; stop reminding."
1583
+ * Use this for "we evaluated and chose not to act" or "we'll act when
1584
+ * ready but acknowledge the finding now."
1585
+ * - `'declined'` — explicit "this exclusion is intentional; do not surface
1586
+ * again." Stronger signal than consumer-marked; useful for compliance
1587
+ * exclusions, brand-promise exclusions, etc.
1588
+ * - `'probed-unblock'` — alpha.40+ probe-path verdict: consumer ran a live
1589
+ * probe and decided to unblock the excluded model. Library accepts the
1590
+ * value today so the probe path doesn't need a follow-up API release.
1591
+ * - `'probed-stay-excluded'` — alpha.40+ probe-path verdict: consumer
1592
+ * probed and confirmed the exclusion. Same forward-compat shape as
1593
+ * `'probed-unblock'`.
1594
+ *
1595
+ * The `'auto'` resolution_source is NOT exposed here — that's reserved
1596
+ * for the brain's own automatic resolution (e.g. when the detection
1597
+ * conditions no longer hold). Consumer code sets only the four values
1598
+ * above.
1599
+ */
1600
+ type ExclusionResolutionSource = 'consumer-marked' | 'declined' | 'probed-unblock' | 'probed-stay-excluded';
1601
+ interface MarkExclusionFindingHandledOptions {
1602
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
1603
+ appId: string;
1604
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
1605
+ archetype: string;
1606
+ /** Canonical model id that the consumer had excluded. */
1607
+ excludedModel: string;
1608
+ /** Resolution semantics — see `ExclusionResolutionSource` for the four
1609
+ * values consumers can set. */
1610
+ resolution: ExclusionResolutionSource;
1611
+ /** Optional free-form note explaining the decision. Surfaces in operator
1612
+ * digests + dashboards alongside the resolution_source. */
1613
+ resolutionNote?: string;
1614
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). The
1615
+ * function appends `/rest/v1/exclusion_findings?...`. */
1616
+ brainEndpoint: string;
1617
+ /** Consumer-scoped JWT carrying the `app_id` claim. The brain's RLS
1618
+ * policy enforces that the JWT's app_id matches the finding's app_id;
1619
+ * cross-tenant writes fail at the database layer regardless of input. */
1620
+ brainJwt: string;
1621
+ /** Supabase anon key for the `apikey` header (PostgREST requires it). */
1622
+ brainAnonKey: string;
1623
+ /** Injected fetch for tests. Defaults to global fetch. */
1624
+ fetch?: typeof fetch;
1625
+ }
1626
+ /**
1627
+ * Mark a stale-exclusion finding as handled. Returns an `ok/reason` envelope
1628
+ * matching `markAdvisoryResolved` — consumer Admin UIs typically render the
1629
+ * failure inline rather than crash.
1630
+ *
1631
+ * Idempotent: if no row matches the (app_id, archetype, excludedModel)
1632
+ * tuple (already resolved, never existed, cron not yet UPSERTed), PostgREST
1633
+ * returns 200 with zero affected rows and we return `{ ok: true }`. The
1634
+ * caller's "I marked it as handled" intent is satisfied regardless of
1635
+ * whether the row was already in that state.
1636
+ *
1637
+ * Reasons surfaced on failure:
1638
+ * - `app_id_required` / `archetype_required` / `excluded_model_required`
1639
+ * - `resolution_invalid` — `resolution` not one of the four documented values
1640
+ * - `brain_auth_misconfig` — 401/403 (JWT / anon key wrong)
1641
+ * - `brain_unavailable` — 5xx
1642
+ * - `network_error:<message>` — fetch threw
1643
+ * - `patch_failed:<status>` — anything else non-2xx
1644
+ */
1645
+ declare function markExclusionFindingHandled(opts: MarkExclusionFindingHandledOptions): Promise<{
1646
+ ok: true;
1647
+ } | {
1648
+ ok: false;
1649
+ reason: string;
1650
+ }>;
1651
+
1652
+ /**
1653
+ * Archetype-cliff compatibility — alpha.28 (tt-intel-Cairn ratified).
1654
+ *
1655
+ * One question, one answer: *given this model and this intent, can it work
1656
+ * — and if not, what adapter (if any) would make it work?*
1657
+ *
1658
+ * Replaces the silent-archetype-cliff failure mode where a consumer picks a
1659
+ * model that's structurally wrong for the intent and kgauto compiles cleanly
1660
+ * without surfacing the gap. The triggering incident: tt-intel shipped
1661
+ * `deepseek-v4-pro` as the hunt default per a local spec; the kgauto coord
1662
+ * doc said L-040 — V4 is structurally wrong for hunt (sequential tools).
1663
+ * `archetypePerf.hunt = 4` was already in the profile data. The compiler
1664
+ * stayed silent. This API + the matching advisor rule surfaces it.
1665
+ *
1666
+ * Pure function. No network. No brain query. No side effects. ~1ms.
1667
+ *
1668
+ * Consultation doc:
1669
+ * command-center/advisory/kgauto/2026-05-21_archetype-cliff-advisor.md
1670
+ *
1671
+ * Refinements applied per tt-intel-Cairn ratification (2026-05-21):
1672
+ * R1: every variant carries `archetypePerf: number` (raw score) — and
1673
+ * `requires-adapter` adds `archetypePerfWithAdapter: number` so
1674
+ * consumer policy can be expressed as "accept adapter only when score
1675
+ * crosses some threshold WITH the adapter on."
1676
+ * R2: every variant carries a plain-English `reason: string`. No internal
1677
+ * jargon ("L-040", "archetypePerf=4") — the consumer chooses whether
1678
+ * to render it as UI hint or operator-tooling tooltip.
1679
+ * R3: `Adapter` is a CLOSED discriminated union, not `| string`. alpha.28
1680
+ * ships ONE variant (`toolOrchestration: 'sequential'`). Future
1681
+ * adapter parameters extend the union explicitly in named releases.
1682
+ * NO escape hatch — the whole point is catching "I added a new
1683
+ * adapter and forgot to update consumer policy" at compile time.
1684
+ */
1685
+
1686
+ /**
1687
+ * Minimum `archetypePerf[archetype]` score to count as `compatible` under
1688
+ * Option A (default policy). Below this, a documented adapter is needed
1689
+ * to lift the model above the floor; if no adapter exists, the model is
1690
+ * rejected.
1691
+ *
1692
+ * Matches `QUALITY_FLOOR_FOR_RECOMMENDATION` in `advisor.ts` — kgauto's
1693
+ * library-wide convention for "below this score, swap recommendations stop."
1694
+ */
1695
+ declare const ARCHETYPE_FLOOR_DEFAULT = 6;
1696
+ /**
1697
+ * Absolute floor — below this, the cliff is too steep for ANY adapter to
1698
+ * lift cleanly. Reserved under Option A (unused today; every below-floor
1699
+ * case is gated by adapter availability). Would gate `reject` vs
1700
+ * `requires-adapter` under a future Option B per consultation doc Q1.
1701
+ *
1702
+ * Exported so consumer-side policy can read it (e.g. "accept adapter only
1703
+ * when archetypePerf >= ABSOLUTE_FLOOR + 1"). Not used internally by
1704
+ * `getModelCompatibility` today — the gate is "does an adapter exist for
1705
+ * this cliff?", not score-based.
1706
+ */
1707
+ declare const ABSOLUTE_FLOOR = 4;
1708
+ /**
1709
+ * The intent the call is expressing — archetype + optional orchestration
1710
+ * mode. Same shape as `ir.intent.archetype` + `ir.constraints.toolOrchestration`
1711
+ * so a consumer can pass `{ archetype: ir.intent.archetype,
1712
+ * toolOrchestration: ir.constraints?.toolOrchestration }` directly.
1713
+ */
1714
+ interface CompatibilityIntent {
1715
+ archetype: IntentArchetypeName;
1716
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
1717
+ }
1718
+ /**
1719
+ * `Adapter` — re-exported above. Canonical definition lives in `ir.ts` to
1720
+ * avoid an import cycle (compatibility.ts → profiles.ts → ir.ts).
1721
+ *
1722
+ * **CLOSED discriminated union per R3.** Future adapter parameters extend
1723
+ * the union explicitly in named alpha releases. No `| string` escape hatch
1724
+ * — consumer policy code SHOULD write exhaustive `switch (adapter.parameter)`
1725
+ * and rely on the compiler to flag "I added a new adapter parameter and
1726
+ * forgot to update the consumer's policy."
1727
+ *
1728
+ * alpha.28 variants:
1729
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
1730
+ * Lifts DeepSeek V4-family on `hunt` from sequential-tool cliff (L-040).
1731
+ * The "consequence" plain-English-ifies the trade-off:
1732
+ * "Tool calls run one at a time — slower but reliable."
1733
+ *
1734
+ * alpha.29+ likely additions (per tt-intel-Cairn priority list):
1735
+ * - `{ parameter: 'parallelToolCalls'; value: false; consequence }`
1736
+ * - `{ parameter: 'maxTools'; value: number; consequence }`
1737
+ * - `{ parameter: 'thinkingBudget'; value: 0; consequence }`
1738
+ *
1739
+ * Each new variant lands in its own named release with the union extended
1740
+ * in `ir.ts`. Consumers see the change at compile time.
1741
+ */
1742
+ /**
1743
+ * The compatibility verdict for a (model, intent) pair. Discriminated union
1744
+ * on `status` — `compatible` | `requires-adapter` | `reject`.
1745
+ *
1746
+ * **Every variant carries `archetypePerf` (R1) + `reason` (R2):**
1747
+ * - `archetypePerf` — the raw 0-10 score for (model, archetype). Lets
1748
+ * consumers build their own thresholds without re-importing the profile
1749
+ * registry.
1750
+ * - `reason` — plain-English, consumer-renderable. NOT internal jargon
1751
+ * like "L-040 cliff" or "archetypePerf=4". Examples in R2 ratification:
1752
+ * - compatible: "Suited for hunt-style parallel discovery."
1753
+ * - requires-adapter: "Best with sequential tool calls for hunt — slower but works."
1754
+ * - reject: "Not suited for hunt — would underperform significantly."
1755
+ *
1756
+ * `requires-adapter` additionally carries:
1757
+ * - `archetypePerfWithAdapter` — estimated post-adapter score. May be an
1758
+ * estimate (we don't measure post-adapter scores yet); kgauto's prior is
1759
+ * "adapter lifts to ARCHETYPE_FLOOR_DEFAULT + 1" unless brain-evidenced.
1760
+ * - `adapter` — the closed-union variant describing the structural change.
1761
+ *
1762
+ * Backward-compat: an unknown model returns `reject` with a "model not
1763
+ * registered" reason; callers never throw. Unknown archetype is impossible
1764
+ * at the type level (`IntentArchetypeName` is a closed union).
1765
+ */
1766
+ type ModelCompatibility = {
1767
+ status: 'compatible';
1768
+ reason: string;
1769
+ archetypePerf: number;
1770
+ } | {
1771
+ status: 'requires-adapter';
1772
+ reason: string;
1773
+ archetypePerf: number;
1774
+ archetypePerfWithAdapter: number;
1775
+ adapter: Adapter;
1776
+ } | {
1777
+ status: 'reject';
1778
+ reason: string;
1779
+ archetypePerf: number;
1780
+ };
1781
+ /**
1782
+ * Compatibility query — *does this model fit this intent, and if not,
1783
+ * what would?*
1784
+ *
1785
+ * **Rules (Option A from consultation doc Q1):**
1786
+ * 1. If model is unregistered → `reject` with "model not registered" reason.
1787
+ * 2. If intent provides `toolOrchestration: 'sequential'` AND that adapter
1788
+ * silences the cliff (because the cliff IS the sequential-tool one)
1789
+ * → return `compatible` with raw score (NOT the post-adapter estimate
1790
+ * — caller already paid the adapter, score reflects reality).
1791
+ * 3. If raw `archetypePerf[archetype] >= ARCHETYPE_FLOOR_DEFAULT`
1792
+ * → `compatible`.
1793
+ * 4. If below floor BUT a documented adapter exists that lifts to floor
1794
+ * → `requires-adapter` with adapter + estimated post-adapter score.
1795
+ * 5. If below floor AND no adapter exists → `reject`.
1796
+ *
1797
+ * **Pure function.** Deterministic for `(modelId, intent)`. No I/O.
1798
+ *
1799
+ * @example
1800
+ * ```ts
1801
+ * import { getModelCompatibility } from '@warmdrift/kgauto-compiler';
1802
+ *
1803
+ * const c = getModelCompatibility('deepseek-v4-pro', { archetype: 'hunt' });
1804
+ * // → { status: 'requires-adapter',
1805
+ * // reason: 'Best with sequential tool calls for hunt — slower but works.',
1806
+ * // archetypePerf: 4,
1807
+ * // archetypePerfWithAdapter: 7,
1808
+ * // adapter: {
1809
+ * // parameter: 'toolOrchestration',
1810
+ * // value: 'sequential',
1811
+ * // consequence: 'Tool calls run one at a time...'
1812
+ * // } }
1813
+ *
1814
+ * // With the adapter already declared:
1815
+ * const c2 = getModelCompatibility('deepseek-v4-pro', {
1816
+ * archetype: 'hunt',
1817
+ * toolOrchestration: 'sequential',
1818
+ * });
1819
+ * // → { status: 'compatible',
1820
+ * // reason: 'Suited for hunt with sequential tool calls.',
1821
+ * // archetypePerf: 4 }
1822
+ * ```
1823
+ */
1824
+ declare function getModelCompatibility(modelId: string, intent: CompatibilityIntent): ModelCompatibility;
1825
+
1826
+ /**
1827
+ * alpha.22 — sync introspection: is brain-query mode active for a given
1828
+ * table? Used by the advisor (`model-stale-evidence` rule) to decide
1829
+ * whether a `judgment`-grounded chosen model is a measurement gap worth
1830
+ * surfacing. Returns false on cold start, when configureBrain() was never
1831
+ * called, or when the consumer explicitly opted the table out via
1832
+ * `BrainConfig.brainQuery.<table> = false`.
1833
+ */
1834
+ declare function isBrainQueryActiveFor(table: string): boolean;
1835
+ interface GetPerAxisMetricsOpts {
1836
+ /** App id to filter on. Required. */
1837
+ appId: string;
1838
+ /** Intent archetype to filter on. Required. */
1839
+ archetype: string;
1840
+ /** Canonical model id to filter on. Required. */
1841
+ model: string;
1842
+ /**
1843
+ * Window in days. Default 30. Only rows with
1844
+ * `created_at > now() - windowDays` are counted.
1845
+ */
1846
+ windowDays?: number;
1847
+ /**
1848
+ * Consumer-declared quality floor (0..1 oracle/approve-rate scale).
1849
+ * When set, the response's `qualityFloorMet` is true/false; when omitted,
1850
+ * `qualityFloorMet` is null (no floor declared, no judgment).
1851
+ */
1852
+ qualityFloor?: number;
1853
+ /** Pluggable fetch (tests inject mock). Defaults to global fetch. */
1854
+ fetch?: typeof fetch;
1855
+ /**
1856
+ * PostgREST base endpoint (e.g. `https://kgauto-brain.vercel.app/api`).
1857
+ * When omitted, falls back to the active configureBrainQuery runtime's
1858
+ * endpoint. Returns null when neither is set.
1859
+ */
1860
+ endpoint?: string;
1861
+ /** Bearer token. Forwarded as `Authorization: Bearer ${apiKey}`. */
1862
+ apiKey?: string;
1863
+ }
1864
+ /**
1865
+ * Call the `get_per_axis_metrics` RPC and return the typed result.
1866
+ *
1867
+ * Returns null when:
1868
+ * - no endpoint provided AND no configureBrainQuery runtime active
1869
+ * - RPC returns empty / null / unexpected shape
1870
+ * - brain unreachable / fetch throws / HTTP error
1871
+ *
1872
+ * Never throws — operator-facing query, must not blow up the caller.
1873
+ */
1874
+ declare function getPerAxisMetrics(opts: GetPerAxisMetricsOpts): Promise<PerAxisMetrics | null>;
1875
+
1876
+ /**
1877
+ * env.ts — provider env-key resolution + reachability predicates.
1878
+ *
1879
+ * Centralizes the per-provider env var names that kgauto checks for
1880
+ * reachability. Used by:
1881
+ *
1882
+ * - execute.ts — to find an API key when one isn't passed via apiKeys
1883
+ * - call.ts — to auto-filter unreachable models from the fallback walk
1884
+ * - getDefaultFallbackChain — opt-in chain filter when consumer passes `reachability`
1885
+ * - operator scripts — getReachabilityDiagnostic() prints what's wired up
1886
+ *
1887
+ * Keeping the map in ONE place means execute() and the reachability check
1888
+ * always agree. Without this, kgauto could declare a model "reachable" because
1889
+ * env.ts found GOOGLE_GENERATIVE_AI_API_KEY, while execute() looks at
1890
+ * GOOGLE_API_KEY only and 401s — shipping the bug we're trying to fix.
1891
+ *
1892
+ * Resolution order (apiKeys takes precedence):
1893
+ * 1. opts.apiKeys?.[provider]
1894
+ * 2. process.env[name] for each name in PROVIDER_ENV_KEYS[provider] (first-present wins)
1895
+ *
1896
+ * alpha.10 (2026-05-14). Resolves the auto-filter-unreachable-models-silently
1897
+ * request from PB after first-deploy 401 on the alpha.9 summarize chain.
1898
+ */
1899
+
1900
+ /**
1901
+ * Providers kgauto can resolve keys for today. Subset of `Provider` — `mistral`
1902
+ * and `xai` are declared in the type union but not yet executable (no profiles,
1903
+ * no execute() handler, no env-var convention). Narrowing here keeps the
1904
+ * reachability check structurally honest.
1905
+ */
1906
+ type SupportedProvider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'zai' | 'moonshot';
1907
+ /**
1908
+ * Per-provider env var names kgauto recognizes. Order doesn't matter —
1909
+ * first-present wins. Multiple names per provider supported because Google
1910
+ * has historical drift (`GOOGLE_API_KEY` from older Google Cloud SDKs,
1911
+ * `GEMINI_API_KEY` in many examples, `GOOGLE_GENERATIVE_AI_API_KEY` is the
1912
+ * Vercel AI SDK convention used by IC + tt-intel adapters).
1913
+ *
1914
+ * Frozen so consumers/tests can't mutate (would break the cache invariant
1915
+ * that execute() and reachability checks agree).
1916
+ */
1917
+ declare const PROVIDER_ENV_KEYS: Readonly<Record<SupportedProvider, readonly string[]>>;
1918
+ interface ReachabilityOpts {
1919
+ /** Explicit keys (alpha.3 ApiKeys). Checked first; takes precedence over env. */
1920
+ apiKeys?: ApiKeys;
1921
+ /**
1922
+ * Override env source. Defaults to `process.env` in Node-shaped runtimes,
1923
+ * `{}` everywhere else. Pass `{}` explicitly in tests for hermetic runs.
1924
+ */
1925
+ envSource?: Record<string, string | undefined>;
1926
+ }
1927
+ /**
1928
+ * Resolve a usable API key for the provider. Returns the key string, or
1929
+ * undefined if neither apiKeys nor any of the env names are set.
1930
+ *
1931
+ * Used internally by execute.ts so the reachability check and the actual
1932
+ * call check stay in sync.
1933
+ */
1934
+ declare function resolveProviderKey(provider: Provider, opts?: ReachabilityOpts): string | undefined;
1935
+ /**
1936
+ * True iff the provider has a usable key — either via explicit `apiKeys`
1937
+ * or one of the `PROVIDER_ENV_KEYS[provider]` names is set in envSource.
1938
+ */
1939
+ declare function isProviderReachable(provider: Provider, opts?: ReachabilityOpts): boolean;
1940
+ /**
1941
+ * True iff the model's profile exists AND its provider is reachable.
1942
+ * Unknown model id returns false (treat as unreachable; the chain walker
1943
+ * will surface "no reachable models" if everything filters out).
1944
+ */
1945
+ declare function isModelReachable(modelId: string, opts?: ReachabilityOpts): boolean;
1946
+ interface ProviderReachability {
1947
+ reachable: boolean;
1948
+ /** How the key was found. `null` when unreachable. */
1949
+ via: 'apiKeys' | 'env' | null;
1950
+ /** Which env var name supplied the key (only when via === 'env'). */
1951
+ envKeyFound?: string;
1952
+ }
1953
+ /**
1954
+ * Snapshot of which providers are reachable from the current env / apiKeys.
1955
+ * Useful for operator scripts ("kgauto diagnose"), startup-time logging,
1956
+ * and the cost-watcher's "which consumer is missing what" report.
1957
+ *
1958
+ * Does NOT log the key value itself — only the env var name that supplied it.
1959
+ */
1960
+ declare function getReachabilityDiagnostic(opts?: ReachabilityOpts): Record<SupportedProvider, ProviderReachability>;
1961
+ /**
1962
+ * Brain-read env contract — canonical names + accepted fallbacks for the
1963
+ * env vars kgauto's brain-read APIs need.
1964
+ *
1965
+ * Affected APIs: `getActionableAdvisories`, `markAdvisoryResolved`,
1966
+ * `markExclusionFindingHandled`, `markPromoteReadyHandled`,
1967
+ * `getStaleExclusionFindings`, and future brain-read surfaces. Each accepts
1968
+ * `brainEndpoint`/`brainJwt`/`brainAnonKey` as call-site arguments; this
1969
+ * helper centralizes resolution from the consumer's environment.
1970
+ *
1971
+ * Resolution order (first-truthy-trimmed wins):
1972
+ * endpoint = KGAUTO_V2_BRAIN_SUPABASE_URL ?? KGAUTO_V2_BRAIN_URL
1973
+ * jwt = KGAUTO_V2_BRAIN_JWT ?? GLASSBOX_BRAIN_JWT
1974
+ * anonKey = KGAUTO_V2_BRAIN_ANON_KEY (no fallback)
1975
+ *
1976
+ * Why fallbacks exist:
1977
+ *
1978
+ * 1. Pre-alpha.42, some consumers set `KGAUTO_V2_BRAIN_URL` pointing at
1979
+ * the kgauto-dashboard URL (write target). The canonical
1980
+ * `KGAUTO_V2_BRAIN_SUPABASE_URL` is the Supabase project URL (read
1981
+ * target — PostgREST against `/rest/v1/`). Until consumers split the
1982
+ * two names, the fallback grabs whichever URL is set. When BOTH are
1983
+ * set, canonical wins (the consumer has explicitly split).
1984
+ *
1985
+ * 2. The s33 Glass-Box ship provisioned `GLASSBOX_BRAIN_JWT` across all
1986
+ * consumers with the same `app_id` claim shape, signed by the same
1987
+ * JWT_SECRET. Reusing it for brain-read avoids re-minting + re-pasting
1988
+ * a second JWT per consumer per surface.
1989
+ *
1990
+ * `missingEnv` lists the CANONICAL names that aren't satisfied by either
1991
+ * canonical OR fallback. Consumer policy: if `missingEnv.length > 0`,
1992
+ * render `not_configured`; otherwise pass `endpoint`/`jwt`/`anonKey` to
1993
+ * `getActionableAdvisories({ ... })` et al.
1994
+ *
1995
+ * Pre-trim semantics carry from `readKeyValue` — paste-newline-trap
1996
+ * (L-060 / L-083 / L-108) closure extends to brain env vars.
1997
+ *
1998
+ * Filed by tt-intel-Cairn (s89, 2026-05-27) after the s89 actionable-
1999
+ * advisories ref template hit `malformed brain response` on prod because
2000
+ * the endpoint env var pointed at the kgauto-dashboard URL instead of the
2001
+ * Supabase URL, AND because IC's ref template used a third env name
2002
+ * (`KGAUTO_V2_BRAIN_ENDPOINT`) that was unset. Three distinct name shapes
2003
+ * across two consumers — the durable closure is one canonical contract.
2004
+ */
2005
+ interface BrainReadEnv {
2006
+ /** Supabase project URL (PostgREST base). Undefined when neither canonical nor fallback is set. */
2007
+ endpoint?: string;
2008
+ /** JWT carrying `app_id` claim, signed by brain JWT_SECRET. Undefined when neither canonical nor fallback is set. */
2009
+ jwt?: string;
2010
+ /** Supabase anon (publishable) key. Undefined when not set. */
2011
+ anonKey?: string;
2012
+ /**
2013
+ * Canonical names not satisfied by either canonical OR fallback. Subset
2014
+ * (in order) of:
2015
+ * ['KGAUTO_V2_BRAIN_SUPABASE_URL', 'KGAUTO_V2_BRAIN_JWT', 'KGAUTO_V2_BRAIN_ANON_KEY']
2016
+ * Consumer policy: render `not_configured` when length > 0.
2017
+ */
2018
+ missingEnv: string[];
2019
+ }
2020
+ /**
2021
+ * Resolve brain-read env vars. Defaults to `process.env`; pass `envSource`
2022
+ * for hermetic tests. Trims surrounding whitespace and treats
2023
+ * empty-after-trim as unset (same shape as `resolveProviderKey`).
2024
+ */
2025
+ declare function readBrainReadEnv(envSource?: Record<string, string | undefined>): BrainReadEnv;
2026
+
2027
+ /**
2028
+ * getDefaultFallbackChain — the alpha.9 cascading ship.
2029
+ *
2030
+ * Returns a per-archetype fallback chain that walks the cost/performance
2031
+ * Pareto frontier (master plan §1.3 + §3). Three customer postures:
2032
+ *
2033
+ * locked — caller passes [theOneModel]; never call this function
2034
+ * preferred — caller passes `primary`; chain returned is [primary, ...fallbacks]
2035
+ * open — caller passes no `primary`; chain returned is [best, ...fallbacks]
2036
+ *
2037
+ * The chain at each step:
2038
+ * 1. Costs strictly less than the previous (no expensive sideways moves)
2039
+ * 2. Comes from a different provider than the previous step where possible
2040
+ * (correlated outages don't kill consecutive attempts)
2041
+ * 3. Stays above the archetype's perf floor (skip models scored <baseline
2042
+ * for archetypes where degradation would be unacceptable)
2043
+ *
2044
+ * In alpha.9 the chain is **hand-curated** per archetype (§3.3 starter
2045
+ * table). Brain-query mode lands in alpha.10. Policy.blockedModels filters
2046
+ * the result; policy.maxCostPerCallUsd is NOT applied here because the
2047
+ * function doesn't see the IR's token counts — that filtering happens at
2048
+ * `passScoreTargets()` time inside compile().
2049
+ *
2050
+ * The function is **pure** — no brain query, no I/O, no randomness. Same
2051
+ * inputs always produce the same chain.
2052
+ */
2053
+
2054
+ /**
2055
+ * Posture passed into `getDefaultFallbackChain`. The chain function only
2056
+ * sees `'open'` and `'preferred'` — callers in `'locked'` posture should
2057
+ * pass `models: [theOneModel]` directly and skip this function entirely.
2058
+ *
2059
+ * Equivalent to `CompilePolicy.posture` minus `'locked'`. Kept distinct so
2060
+ * the type system enforces "don't ask for a chain when you don't want one."
2061
+ */
2062
+ type FallbackPosture = 'open' | 'preferred';
2063
+ interface GetDefaultFallbackChainOpts {
2064
+ /** The archetype the call is performing. Drives chain shape. */
2065
+ archetype: IntentArchetypeName;
2066
+ /**
2067
+ * The user-selected or caller-anchored primary model. When provided, it
2068
+ * appears at position 0 of the returned chain and fallbacks follow.
2069
+ * When omitted, the function picks the best-perf model for the archetype
2070
+ * as position 0 (open posture).
2071
+ */
2072
+ primary?: string;
2073
+ /**
2074
+ * Informational. `'preferred'` and `'open'` produce the same chain shape
2075
+ * given the same `primary`/no-primary input — posture is a tag the brain
2076
+ * uses to distinguish "user-anchored" from "library-anchored" telemetry.
2077
+ */
2078
+ posture?: FallbackPosture;
2079
+ /**
2080
+ * Cap on chain length. Default 3. Min 1. Useful when the consumer wants
2081
+ * to keep the worst-case latency low (each fallback adds a round-trip).
2082
+ */
2083
+ maxDepth?: number;
2084
+ /**
2085
+ * Consumer-side gating. `blockedModels` are filtered from the chain.
2086
+ * `preferredModels` is informational (no boost applied at this layer —
2087
+ * compile()'s `passScoreTargets` handles preference ranking).
2088
+ * `maxCostPerCallUsd` is NOT applied here — needs IR-level token
2089
+ * estimation. Use compile()'s policy plumbing instead.
2090
+ */
2091
+ policy?: CompilePolicy;
2092
+ /**
2093
+ * alpha.10. When provided, the chain is filtered to models whose provider
2094
+ * has a reachable API key (via `apiKeys` or one of `PROVIDER_ENV_KEYS[provider]`).
2095
+ * Models whose provider can't be reached are silently dropped. If filtering
2096
+ * leaves the chain empty, returns `[]` — caller decides what to do (call()
2097
+ * throws CallError; this function stays pure).
2098
+ *
2099
+ * Pass `{}` to opt in with `process.env` as the env source. Pass `{ apiKeys, envSource }`
2100
+ * for explicit control (tests, non-Node runtimes). Omit entirely for the
2101
+ * legacy unfiltered behavior — preserves alpha.9 callers byte-for-byte.
2102
+ */
2103
+ reachability?: ReachabilityOpts;
2104
+ /**
2105
+ * alpha.20 E3: consumer-declared tool-orchestration shape. Currently
2106
+ * only affects `archetype: 'hunt'`, where 'sequential' swaps the
2107
+ * parallel-tool-tier-0 chain (Flash → Pro → Sonnet → Haiku) for a
2108
+ * DeepSeek-tier-0 chain (V4-Pro → Flash → Sonnet) — DeepSeek's L-040
2109
+ * parallel-tool cliff doesn't apply when the consumer commits to
2110
+ * single-step orchestration.
2111
+ *
2112
+ * Other archetypes are NOT mode-aware in this release — they ship the
2113
+ * same chain regardless of toolOrchestration. Future versions may
2114
+ * extend mode-awareness to ask/generate/etc. when brain evidence
2115
+ * supports it.
2116
+ *
2117
+ * Default (omitted or 'either'): parallel chain. Back-compat with all
2118
+ * pre-alpha.20 callers.
2119
+ */
2120
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
2121
+ }
2122
+ /**
2123
+ * Returns the fallback chain for an archetype as a plain `string[]` of
2124
+ * model ids.
2125
+ *
2126
+ * @deprecated since alpha.21 — prefer
2127
+ * {@link getDefaultFallbackChainWithGrounding}, which returns the same chain
2128
+ * shape with a `grounding` label on every entry (measured / capability-fact /
2129
+ * judgment). The string[] return is preserved indefinitely for back-compat —
2130
+ * no functional change in alpha.21. Existing callers don't need to migrate
2131
+ * unless they want to surface the grounding gap to users.
2132
+ */
2133
+ declare function getDefaultFallbackChain(opts: GetDefaultFallbackChainOpts): string[];
2134
+ /**
2135
+ * Returns a shallow copy of the hand-curated starter chain for an archetype.
2136
+ * Useful for tests + the `scripts/digest.mjs` operator readout.
2137
+ */
2138
+ declare function getStarterChain(archetype: IntentArchetypeName): string[];
2139
+ /**
2140
+ * Returns a shallow copy of all starter chains keyed by archetype.
2141
+ * Useful for the `digest.mjs` readout and consumer audits.
2142
+ */
2143
+ declare function getAllStarterChains(): Record<IntentArchetypeName, string[]>;
2144
+ /**
2145
+ * alpha.20 E3 introspection — returns the sequential-mode overlay for an
2146
+ * archetype, or `undefined` when no overlay is registered (the archetype
2147
+ * is mode-agnostic and reuses `STARTER_CHAINS[archetype]`).
2148
+ *
2149
+ * Useful for tests + the `scripts/digest.mjs` operator readout to surface
2150
+ * the mode-aware chains.
2151
+ */
2152
+ declare function getSequentialStarterChain(archetype: IntentArchetypeName): string[] | undefined;
2153
+ /**
2154
+ * alpha.21 (s78 Entry 1) — returns the fallback chain as `ChainEntry[]`,
2155
+ * with a `grounding` label on every position.
2156
+ *
2157
+ * Same selection logic as {@link getDefaultFallbackChain} (primary anchoring,
2158
+ * blockedModels filter, dedupe, reachability filter, maxDepth cap) — the
2159
+ * only difference is the return shape: each position is a `ChainEntry`
2160
+ * carrying `{ id, grounding, reason?, n? }` instead of a bare string.
2161
+ *
2162
+ * Use this when surfacing the chain to consumers who care WHY each entry
2163
+ * sits where it sits — Glass-Box panels, operator dashboards, eval
2164
+ * scaffolding deciding which entries deserve measurement priority.
2165
+ *
2166
+ * Returns `[]` when filtering empties the chain (same semantics as the
2167
+ * string variant) — consumer decides what to do.
2168
+ */
2169
+ declare function getDefaultFallbackChainWithGrounding(opts: GetDefaultFallbackChainOpts): ChainEntry[];
2170
+ /**
2171
+ * alpha.21 introspection — returns the grounded starter chain for an
2172
+ * archetype (no primary anchoring, no policy filtering, no maxDepth cap).
2173
+ * Use this when you want the raw, hand-curated grounded chain — every
2174
+ * entry carries a `grounding` label and optional reason/n.
2175
+ */
2176
+ declare function getStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[];
2177
+ /**
2178
+ * alpha.21 introspection — all grounded starter chains keyed by archetype.
2179
+ * Useful for the `digest.mjs` readout and consumer audits that want to
2180
+ * surface the grounding gap across the entire chain table.
2181
+ */
2182
+ declare function getAllStarterChainsWithGrounding(): Record<IntentArchetypeName, ChainEntry[]>;
2183
+ /**
2184
+ * alpha.21 introspection — sequential-mode overlay with grounding labels,
2185
+ * or `undefined` when no overlay is registered for the archetype.
2186
+ */
2187
+ declare function getSequentialStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[] | undefined;
2188
+
2189
+ /**
2190
+ * chains-brain — alpha.11 KG-11 adapter.
2191
+ *
2192
+ * Brain-driven STARTER_CHAINS for `getDefaultFallbackChain`. Reads
2193
+ * `kgauto_chains` table via the shared brain-query SWR cache (D6 + D8);
2194
+ * falls back to bundled STARTER_CHAINS on cold-start, brain-down, or
2195
+ * empty/missing table (D2 + D4).
2196
+ *
2197
+ * Behavioral note (locked via D2): the sync API surface returns bundled on
2198
+ * cold-start, with a background refresh fired. Subsequent calls within the
2199
+ * 5-min TTL return brain data. Vercel cold-start consumers see the seed
2200
+ * snapshot (functionally identical to pre-alpha.11); warm-start consumers
2201
+ * see live brain mutations within 5 min.
2202
+ */
2203
+ /**
2204
+ * Sync reader for the brain-driven chains map. Returns bundled
2205
+ * STARTER_CHAINS when brain-query is disabled, cold, or unreachable.
2206
+ */
2207
+ declare const loadChainsFromBrain: () => Record<"ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform" | "judge", string[]>;
2208
+
2209
+ /**
2210
+ * archetype-perf-brain — alpha.11 KG-12 adapter.
2211
+ *
2212
+ * Brain-driven archetypePerf scores. Substrate for the future closed-loop
2213
+ * tuning engine (KG-12.5): brain telemetry → human or automated bumps →
2214
+ * brain UPDATE → consumers see new scores within 5-min cache TTL with
2215
+ * zero refresh.
2216
+ *
2217
+ * Today: data migrates to brain. No runtime call site reads archetypePerf
2218
+ * (it's metadata for the master plan §2.5 anti-hallucination guardrail +
2219
+ * future auto-tuning). The adapter exists so future readers — auto-tuning
2220
+ * + operator scripts + KG-12.5 — have a shipped substrate to consume.
2221
+ */
2222
+
2223
+ type ArchetypePerfMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
2224
+ /**
2225
+ * alpha.21: per-(model, archetype) row count map. Same shape as
2226
+ * ArchetypePerfMap but stores brain row counts when the brain backs a
2227
+ * placement. Undefined entries → no row count seen → score is the
2228
+ * hand-curated cold-start prior (grounding='judgment').
2229
+ */
2230
+ type ArchetypePerfNMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
2231
+ /**
2232
+ * Sync reader for the brain-driven archetypePerf map. Returns bundled
2233
+ * profile.archetypePerf data when brain-query is disabled, cold, or
2234
+ * unreachable. Identical shape pre/post-alpha.11 by design (D2).
2235
+ */
2236
+ declare const loadArchetypePerfFromBrain: () => ArchetypePerfMap;
2237
+ /**
2238
+ * alpha.21 — sync reader for the brain row-count map paired with
2239
+ * archetype-perf. Returns empty map (no measured backing) on cold start /
2240
+ * brain-down / unreachable — all `getArchetypePerfScore` calls then
2241
+ * resolve to `grounding: 'judgment'`. When the brain table includes an
2242
+ * `n` column on each row, this map mirrors those counts so consumers can
2243
+ * see how many measurements back each score.
2244
+ */
2245
+ declare const loadArchetypePerfNFromBrain: () => ArchetypePerfNMap;
2246
+ /**
2247
+ * Threshold above which a brain row count counts as 'measured' grounding.
2248
+ * Below this, the score is treated as 'judgment' (cold-start prior or
2249
+ * not-yet-enough-evidence). Mirrors the alpha.20 `getCleanPerfScore`
2250
+ * `minRows` default — same rule for consistency.
2251
+ */
2252
+ declare const MEASURED_GROUNDING_MIN_N = 10;
2253
+ /**
2254
+ * alpha.21 — return shape for the extended {@link getArchetypePerfScore}.
2255
+ * Wraps the existing 0..10 score with:
2256
+ *
2257
+ * - `n`: brain row count backing this score (0 when no measurement).
2258
+ * - `grounding`: derived label — 'measured' when n >= 10, else 'judgment'.
2259
+ *
2260
+ * The score itself is unchanged from pre-alpha.21 (numeric, 5 = neutral
2261
+ * default). 'capability-fact' is NOT a perf-score grounding — capability
2262
+ * decisions live on chain entries, not on perf scores.
2263
+ */
2264
+ interface ArchetypePerfScoreResult {
2265
+ /** 0..10 perf score. 5 = neutral default when no entry exists. */
2266
+ score: number;
2267
+ /**
2268
+ * Brain row count backing this score. 0 when bundled (cold-start prior)
2269
+ * or when the brain row didn't carry an `n` column.
2270
+ */
2271
+ n: number;
2272
+ /**
2273
+ * Provenance — 'measured' when `n >= 10`, else 'judgment'.
2274
+ * Never 'capability-fact' (that label is reserved for chain-entry
2275
+ * inclusion/exclusion decisions).
2276
+ */
2277
+ grounding: Grounding;
2278
+ }
2279
+ /**
2280
+ * Per-model accessor with grounding (alpha.21). Returns 5 (neutral) when no
2281
+ * entry is found — consistent with the master plan §3.3 "missing archetypes
2282
+ * default to 5" convention documented in profiles.ts
2283
+ * ModelProfile.archetypePerf.
2284
+ *
2285
+ * Backwards-compat note: pre-alpha.21 callers expected `number` here. The
2286
+ * new return shape `{ score, n, grounding }` is a breaking shape change at
2287
+ * the type level, but `.score` carries the legacy value. Callers reading
2288
+ * `.score` field-by-field continue working; callers using the bare number
2289
+ * arithmetically need to switch to `.score`. The migration is single-line
2290
+ * (`const x = getArchetypePerfScore(...)` → `const x = getArchetypePerfScore(...).score`).
2291
+ */
2292
+ declare function getArchetypePerfScore(modelId: string, archetype: IntentArchetypeName): ArchetypePerfScoreResult;
2293
+
2294
+ /**
2295
+ * pricing-brain — alpha.11 KG-13 adapter.
2296
+ *
2297
+ * Brain-driven pricing data with **time-bounded resolution** (`valid_from`
2298
+ * / `valid_until` columns). The V4-Pro 75%-off promo through 2026-05-31
2299
+ * gets modeled as two rows; `at` parameter resolution picks the correct
2300
+ * row per call timestamp. Promo flips happen automatically at the
2301
+ * boundary without alpha cuts.
2302
+ *
2303
+ * SWR cache holds the FULL pricing snapshot (all active rows for all
2304
+ * models). Per-call `at` filtering is in-memory — keeps the SWR semantics
2305
+ * uniform with other adapters (one cache, one snapshot, sync reads).
2306
+ */
2307
+ interface PricingRow {
2308
+ modelId: string;
2309
+ costInputPer1m: number;
2310
+ costOutputPer1m: number;
2311
+ cacheInputPer1m?: number;
2312
+ cacheCreationPer1m?: number;
2313
+ validFrom: number;
2314
+ validUntil?: number;
2315
+ source?: string;
2316
+ }
2317
+ /**
2318
+ * Sync reader for the brain-driven pricing snapshot. Returns bundled
2319
+ * profile pricing when brain-query is disabled, cold, or unreachable.
2320
+ * Caller filters by `at` via {@link resolvePricingAt}.
2321
+ */
2322
+ declare const loadPricingFromBrain: () => PricingRow[];
2323
+ /**
2324
+ * Resolve the active pricing row for a model at a given timestamp.
2325
+ * Picks the row with the latest `valid_from <= at` whose
2326
+ * `valid_until > at` (or NULL — open-ended).
2327
+ *
2328
+ * Returns `undefined` when no row matches. Callers should fall back to
2329
+ * profile static pricing in that case.
2330
+ */
2331
+ declare function resolvePricingAt(modelId: string, at?: Date): PricingRow | undefined;
2332
+
2333
+ /**
2334
+ * models-brain — alpha.11 KG-14 adapter (the largest of the four).
2335
+ *
2336
+ * Brain-driven model registry + aliases. Two adapters share the same
2337
+ * SWR snapshot:
2338
+ *
2339
+ * - `loadModelsFromBrain()` — `Map<modelId, ModelProfile>` from
2340
+ * `kgauto_models` table (cliffs/lowering/recovery as JSONB columns).
2341
+ * - `loadAliasesFromBrain()` — `Record<aliasId, canonicalId>` from
2342
+ * `kgauto_aliases` table.
2343
+ *
2344
+ * After alpha.11, new-model onboarding becomes brain INSERT (vs PR + alpha
2345
+ * cut + 3 consumer refreshes). The auto-onboard pipeline
2346
+ * (`scripts/check-model-releases.mjs`) shifts from emitting profile.ts
2347
+ * edits to writing brain rows directly.
2348
+ *
2349
+ * **D5 — alias resolution stable regardless of canonical's active state.**
2350
+ * `canonicalId('deepseek-chat') → 'deepseek-v4-flash'` even when the
2351
+ * canonical row is `active=false`. Aliases are wire-format contracts;
2352
+ * legacy callers' resolution promise outlives the canonical's active
2353
+ * status. Deprecation (`active=false`) affects chain composition only.
2354
+ */
2355
+
2356
+ /**
2357
+ * Exported brain-row shape for `kgauto_models`. Mirrors the SQL table
2358
+ * (`v2/brain/migrations/010_kgauto_models_and_aliases.sql`) — column names
2359
+ * are snake_case to match PostgREST. Used by operator scripts that write
2360
+ * to brain (auto-onboard, promote-model) — see `profileToRow()`.
2361
+ *
2362
+ * Read path stays internal via `RawModelRow` to keep `rowToProfile()`'s
2363
+ * tolerance contract from leaking into write callers.
2364
+ */
2365
+ interface ModelBrainRow {
2366
+ model_id: string;
2367
+ provider: string;
2368
+ status?: string;
2369
+ max_context_tokens?: number;
2370
+ max_output_tokens?: number;
2371
+ max_tools?: number;
2372
+ parallel_tool_calls?: boolean;
2373
+ structured_output?: string;
2374
+ system_prompt_mode?: string;
2375
+ streaming?: boolean;
2376
+ cliffs?: unknown;
2377
+ lowering?: unknown;
2378
+ recovery?: unknown;
2379
+ strengths?: string[] | null;
2380
+ weaknesses?: string[] | null;
2381
+ cost_input_per_1m?: number;
2382
+ cost_output_per_1m?: number;
2383
+ notes?: string | null;
2384
+ verified_against_docs?: string | null;
2385
+ archetype_perf?: Record<string, number> | null;
2386
+ version_added?: string;
2387
+ version_removed?: string | null;
2388
+ active?: boolean;
2389
+ /** alpha.41 — model-family tag (migration 024 column). */
2390
+ family?: string | null;
2391
+ /** alpha.49 — explicit latency bucket (migration 028 column). */
2392
+ latency_tier?: string | null;
2393
+ /** alpha.49 — per-archetype prompt-shape conventions (migration 028 column). */
2394
+ archetype_conventions?: ArchetypeConvention[] | null;
2395
+ }
2396
+ interface ProfileToRowOptions {
2397
+ /** e.g. `'2.0.0-alpha.12'` — leave undefined to omit from row. */
2398
+ versionAdded?: string;
2399
+ /** Pass `null` to clear; omit to leave field unset. */
2400
+ versionRemoved?: string | null;
2401
+ /** Defaults to true if omitted. */
2402
+ active?: boolean;
2403
+ /**
2404
+ * Override verifiedAgainstDocs (e.g. set to `null` for auto-onboard).
2405
+ * When omitted, the profile's own value is used. Pass `null` explicitly
2406
+ * to write a SQL NULL (e.g. unverified auto-onboard rows).
2407
+ */
2408
+ verifiedAgainstDocs?: string | null;
2409
+ }
2410
+ /**
2411
+ * Inverse of `rowToProfile` — serialize a `ModelProfile` to a `kgauto_models`
2412
+ * row payload for INSERT/UPSERT. Used by operator scripts that write to
2413
+ * brain (auto-onboard pipeline, promote-model verification CLI).
2414
+ *
2415
+ * Row-level fields (`version_added`, `version_removed`, `active`) are
2416
+ * operator-controlled and pass through `opts`. `verifiedAgainstDocs` can
2417
+ * also be overridden via `opts` — auto-onboard explicitly passes `null` to
2418
+ * mark unverified rows (the column is DATE, doesn't accept the
2419
+ * `'UNVERIFIED-AUTO-ONBOARD'` sentinel used in PROFILES_RAW).
2420
+ */
2421
+ declare function profileToRow(profile: ModelProfile, opts?: ProfileToRowOptions): ModelBrainRow;
2422
+ /**
2423
+ * Sync reader for the brain-driven model registry. Returns bundled
2424
+ * PROFILES_RAW when brain-query is disabled, cold, or unreachable.
2425
+ */
2426
+ declare const loadModelsFromBrain: () => Map<string, ModelProfile>;
2427
+ /**
2428
+ * Sync reader for the brain-driven aliases map. Returns bundled ALIASES
2429
+ * when brain-query is disabled, cold, or unreachable.
2430
+ *
2431
+ * D5: this map carries both active and inactive canonical mappings —
2432
+ * alias resolution is stable regardless of canonical's `active` state.
2433
+ */
2434
+ declare const loadAliasesFromBrain: () => Record<string, string>;
2435
+
2436
+ /**
2437
+ * exclusion-findings-brain — alpha.38 KG-19 adapter.
2438
+ *
2439
+ * Per-tenant SWR cache for the `exclusion_findings` table populated by the
2440
+ * `kgauto-exclusion-re-evaluation-watch` cron (alpha.37 substrate). Distinct
2441
+ * from the cross-tenant `brain-query.ts` snapshot because exclusion findings
2442
+ * are scoped per `app_id` — one process = one consumer = one appId, but the
2443
+ * cache key supports multi-app processes by keying snapshots by appId.
2444
+ *
2445
+ * Architecture mirrors `brain-query.ts` but with a per-(appId) snapshot:
2446
+ *
2447
+ * - **Sync API surface.** `getStaleExclusionFindings({ appId, archetype })`
2448
+ * returns `ExclusionFindingRow[]` immediately. First call returns the
2449
+ * bundled fallback (empty array); async refresh fires in background;
2450
+ * subsequent calls within TTL return brain data.
2451
+ *
2452
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
2453
+ * per appId per TTL window. Tests can reset between cases.
2454
+ *
2455
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
2456
+ * silent bundled fallback (empty array). Never throws. Warns once per
2457
+ * process per error to avoid log spam.
2458
+ *
2459
+ * - **Opt-in.** Activation gated on `configureExclusionFindingsBrain()`
2460
+ * having been called with a runtime. The public `configureBrain()` in
2461
+ * brain.ts wires this up automatically when `BrainConfig.brainQuery
2462
+ * .findingsExclusions !== false`.
2463
+ *
2464
+ * Default endpoint:
2465
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`
2466
+ * The route accepts `?app_id=X` and returns a JSON array of findings
2467
+ * for that app filtered to `resolved_at IS NULL`. Public read; data
2468
+ * carries no consumer PII (app id, archetype, model id, cost ratio,
2469
+ * savings estimate).
2470
+ */
2471
+ /**
2472
+ * Shape of one row from the `exclusion_findings` cache table. Mirrors the
2473
+ * snake_case JSONB returned by the brain RPC + the dashboard endpoint.
2474
+ * Camel-case mapping happens at the boundary (rowToFinding) so the in-memory
2475
+ * shape stays consistent with the rest of the library.
2476
+ */
2477
+ interface ExclusionFindingRow {
2478
+ /** Intent archetype the finding applies to (e.g. 'hunt', 'classify'). */
2479
+ archetype: string;
2480
+ /** Canonical model id that the consumer has excluded (zero traffic in window). */
2481
+ excludedModel: string;
2482
+ /** Provider of the excluded model (e.g. 'deepseek', 'openai'). */
2483
+ excludedProvider: string;
2484
+ /** Detection verdict — alpha.37 ships 'recommend-probe' only. */
2485
+ verdict: 'recommend-probe' | 'unblock' | 'stay-excluded' | 'inconclusive';
2486
+ /**
2487
+ * Estimated 30-day savings in USD if the excluded model becomes primary
2488
+ * on this archetype. Null when pricing is incomplete or excluded model is
2489
+ * more expensive than the leader.
2490
+ */
2491
+ estimatedSavingsUsd30d: number | null;
2492
+ /** Renderable summary; produced by the detector / RPC. */
2493
+ message: string;
2494
+ /** Actionable recommendation; produced by the detector / RPC. */
2495
+ suggestion: string;
2496
+ /** Detector confidence tier. */
2497
+ confidence: 'high' | 'medium' | 'low';
2498
+ /**
2499
+ * Free-form evidence pack (cost ratio, leader info, promo flags, parallel-
2500
+ * tool hint, etc.). Surfaced verbatim to advisor rules for richer messages.
2501
+ * Optional — older detector runs may not populate every field.
2502
+ */
2503
+ evidence?: Record<string, unknown>;
2504
+ }
2505
+ /**
2506
+ * Default endpoint hosted on the kgauto-dashboard. Public read — data carries
2507
+ * no PII (app id, archetype, model id, cost ratio, savings estimate). Mirrors
2508
+ * the cross-tenant `/api/kgauto-v2/config` pattern.
2509
+ */
2510
+ declare const DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
2511
+ /**
2512
+ * Sync introspection — is the findings-brain active? Used by advisor rules
2513
+ * to decide whether to even attempt a read.
2514
+ */
2515
+ declare function isExclusionFindingsBrainActive(): boolean;
2516
+ interface GetExclusionFindingsOpts {
2517
+ /** App id to read findings for. Required. */
2518
+ appId: string;
2519
+ /**
2520
+ * Optional archetype filter. When set, returns only findings where
2521
+ * `archetype` matches. When omitted, returns all findings for the app.
2522
+ */
2523
+ archetype?: string;
2524
+ }
2525
+ /**
2526
+ * Sync reader. Returns the cached findings for `appId`, optionally filtered
2527
+ * to a single archetype. First call returns empty array and triggers async
2528
+ * refresh; subsequent calls within TTL return brain data.
2529
+ *
2530
+ * NEVER throws. Brain down / endpoint misconfigured / mapper exception →
2531
+ * empty array.
2532
+ */
2533
+ declare function getStaleExclusionFindings(opts: GetExclusionFindingsOpts): ExclusionFindingRow[];
2534
+
2535
+ /**
2536
+ * Family resolution — alpha.41.
2537
+ *
2538
+ * "I want the latest Opus" → kgauto picks the current+active model in the
2539
+ * `claude-opus` family. Closes the loop where consumer code carries hardcoded
2540
+ * `claude-opus-4-6` literals long after `claude-opus-4-7` ships and goes
2541
+ * current — the s47 trigger (IC's `generate` chain still routing 43 calls to
2542
+ * legacy 4-6 in production).
2543
+ *
2544
+ * Two surfaces:
2545
+ * - `getRecommendedPrimary({ family, ..., fallback })` — public, sync,
2546
+ * used at IR-construction time when the consumer wants a literal id back
2547
+ * (with a fallback floor for cold-start brain).
2548
+ * - `resolveFamilyEntry({ family, archetype?, appId? })` — internal,
2549
+ * called from compile() when an IR's `models[]` entry is shaped
2550
+ * `{ family: string }`. Throws `FamilyResolutionError` on failure.
2551
+ *
2552
+ * Both routes share the same algorithm (locked in the alpha.41 Phase 0
2553
+ * design contract); they differ only in the fallback ergonomics. The
2554
+ * public route accepts a required `fallback: string`; the IR route throws.
2555
+ *
2556
+ * Pure resolution. No network. No async. Brain-registry reads go through
2557
+ * the existing SWR cache (`loadModelsFromBrain` from `models-brain.ts`) —
2558
+ * cold-start returns bundled profiles, which still resolve via the
2559
+ * `deriveFamilyFromModelId` fallback when the brain row's `family` column
2560
+ * is null (G1 contract: graceful pre-migration behavior).
2561
+ *
2562
+ * @see command-center/advisory/kgauto/2026-05-26_alpha-41-model-family-aliases-and-promotion-probe-watcher.md
2563
+ */
2564
+
2565
+ interface GetRecommendedPrimaryOptions {
2566
+ /**
2567
+ * Family tag (e.g. `'claude-opus'`, `'gemini-flash'`). See the Phase 0
2568
+ * design contract's family taxonomy table for the locked initial set;
2569
+ * extensible via brain migrations.
2570
+ */
2571
+ family: string;
2572
+ /**
2573
+ * Optional archetype gate. When provided, candidates must clear
2574
+ * {@link ARCHETYPE_FLOOR_DEFAULT} on `archetypePerf[archetype]`. Also used
2575
+ * as the primary sort key (DESC) when multiple candidates qualify.
2576
+ */
2577
+ archetype?: IntentArchetypeName;
2578
+ /**
2579
+ * Optional consumer-app id. When provided, candidates matching a
2580
+ * `stay-excluded` finding for `(appId, archetype)` in the
2581
+ * exclusion-findings cache (alpha.38 substrate) are filtered out.
2582
+ */
2583
+ appId?: string;
2584
+ /**
2585
+ * Consumer-posture tag. `'locked'` short-circuits resolution and returns
2586
+ * the literal `fallback` unconditionally — useful for compliance /
2587
+ * contract / brand-promise flows where the consumer doesn't want kgauto
2588
+ * picking the model on their behalf.
2589
+ */
2590
+ posture?: 'preferred' | 'open' | 'locked';
2591
+ /**
2592
+ * Last-resort literal model id. REQUIRED. Returned when (a) brain
2593
+ * registry is cold / no candidates exist, (b) `posture === 'locked'`,
2594
+ * (c) every candidate was filtered out by archetype / exclusion gates.
2595
+ *
2596
+ * The fallback is NOT validated against the family — kgauto trusts the
2597
+ * consumer to pass a meaningful floor. The contract intent is "even when
2598
+ * everything below is on fire, you still get a model id back."
2599
+ */
2600
+ fallback: string;
2601
+ }
2602
+ /**
2603
+ * Thrown by `resolveFamilyEntry` (the internal compile-time twin) when a
2604
+ * `{ family: string }` IR entry can't resolve to any current+active model.
2605
+ * Surfaces with the family string + a one-line cause so consumer error
2606
+ * handling can distinguish "you typo'd the family tag" from "brain is cold
2607
+ * and nothing matches."
2608
+ *
2609
+ * The public `getRecommendedPrimary` does NOT throw — it returns
2610
+ * `fallback` instead.
2611
+ */
2612
+ declare class FamilyResolutionError extends Error {
2613
+ readonly family: string;
2614
+ readonly cause: string;
2615
+ constructor(family: string, cause: string);
2616
+ }
2617
+ /**
2618
+ * Deterministic model_id → family inference. Pure function; no brain
2619
+ * lookup. Used as the runtime fallback when a brain row's `family` column
2620
+ * is null (pre-migration 024) and as the canonical mapping that migration
2621
+ * 024's CASE statement mirrors.
2622
+ *
2623
+ * Returns null for unrecognized ids — caller must handle (typically by
2624
+ * skipping the row in family resolution).
2625
+ *
2626
+ * Order matters: more specific patterns first (e.g. `flash-lite` before
2627
+ * `flash`; `pro` before `chat`). The brain-side CASE statement uses the
2628
+ * same priority.
2629
+ */
2630
+ declare function deriveFamilyFromModelId(modelId: string): string | null;
2631
+ /**
2632
+ * Public sync resolver. Pure (modulo brain snapshot read). Returns the
2633
+ * literal model id of the best candidate, or `fallback` when resolution
2634
+ * yields nothing.
2635
+ */
2636
+ declare function getRecommendedPrimary(opts: GetRecommendedPrimaryOptions): string;
2637
+
2638
+ /**
2639
+ * promote-ready-brain — alpha.41 substrate.
2640
+ *
2641
+ * Per-tenant SWR cache for the `promote_ready_findings` table populated by
2642
+ * the autonomous `promotion-probe-watcher` (Mode 2). Mirrors
2643
+ * `exclusion-findings-brain.ts` shape byte-for-byte where applicable; this
2644
+ * is the read-side substrate for the compile-time `promote-ready` advisor
2645
+ * rule.
2646
+ *
2647
+ * Architecture (mirror of exclusion-findings-brain):
2648
+ *
2649
+ * - **Sync API surface.** `getPromoteReadyFindings({ appId, archetype,
2650
+ * family })` returns `PromoteReadyFindingRow[]` immediately. First call
2651
+ * returns the bundled fallback (empty array); async refresh fires in
2652
+ * background; subsequent calls within TTL return brain data.
2653
+ *
2654
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
2655
+ * per appId per TTL window. Tests reset between cases via
2656
+ * `_testResetPromoteReadyFindings()`.
2657
+ *
2658
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
2659
+ * silent bundled fallback (empty array). Never throws. Warns once per
2660
+ * process per error to avoid log spam.
2661
+ *
2662
+ * - **Opt-in.** Activation gated on `configurePromoteReadyBrain()` having
2663
+ * been called with a runtime. The public `configureBrain()` in brain.ts
2664
+ * wires this up automatically when
2665
+ * `BrainConfig.brainQuery.findingsPromoteReady !== false`.
2666
+ *
2667
+ * Plus: `markPromoteReadyHandled` — direct PostgREST PATCH against the
2668
+ * brain (no kgauto proxy). Mirrors `markExclusionFindingHandled` shape
2669
+ * byte-for-byte. Idempotent on `resolved_at=is.null` filter.
2670
+ *
2671
+ * Default endpoint:
2672
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/promote-ready`
2673
+ * The route accepts `?app_id=X` and returns a JSON array of findings
2674
+ * for that app filtered to `resolved_at IS NULL`.
2675
+ */
2676
+
2677
+ /**
2678
+ * Shape of one row from the `promote_ready_findings` cache table. Mirrors
2679
+ * the snake_case JSONB returned by the brain endpoint, mapped to camelCase
2680
+ * at the boundary (rowToFinding) so the in-memory shape stays consistent
2681
+ * with the rest of the library.
2682
+ */
2683
+ interface PromoteReadyFindingRow {
2684
+ /** Intent archetype the finding applies to. */
2685
+ archetype: string;
2686
+ /** Model family (e.g. 'claude-opus', 'gemini-flash'). */
2687
+ family: string;
2688
+ /** The candidate model that the probe validated. */
2689
+ candidateModel: string;
2690
+ /** The current production model the candidate was compared against. */
2691
+ currentModel: string;
2692
+ /** Sample size of the probe run (typically 10). */
2693
+ sampleN: number;
2694
+ /** Fraction of probes where the judge verdict was 'candidate-better' or
2695
+ * 'tied'. 0.000 to 1.000. */
2696
+ judgePassRate: number;
2697
+ /** Mean judge score across the probe sample. 1.00 to 5.00. */
2698
+ judgeAvgScore: number;
2699
+ /** Signed cost delta as a fraction (negative = candidate is cheaper).
2700
+ * Null when pricing data was incomplete at probe time. */
2701
+ costDeltaPct: number | null;
2702
+ /** ISO timestamp of detection (when the probe wrote the row). */
2703
+ detectedAt: string;
2704
+ }
2705
+ /**
2706
+ * Resolution sources supported by alpha.41 `markPromoteReadyHandled`. The
2707
+ * three values map to the three CHECK-constrained resolution values on
2708
+ * `promote_ready_findings.resolution`:
2709
+ *
2710
+ * - `'promoted'` — consumer migrated to the candidate model. Strong
2711
+ * positive signal; the probe was right.
2712
+ * - `'declined'` — consumer evaluated and chose not to promote.
2713
+ * Strong negative signal; revisit only on new
2714
+ * family entries or material score swings.
2715
+ * - `'still-evaluating'` — consumer acknowledges the finding but defers
2716
+ * the decision. Acknowledges-without-deciding;
2717
+ * finding silences this cycle but next probe may
2718
+ * re-surface.
2719
+ */
2720
+ type PromoteReadyResolution = 'promoted' | 'declined' | 'still-evaluating';
2721
+ interface MarkPromoteReadyHandledOptions {
2722
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
2723
+ appId: string;
2724
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
2725
+ archetype: IntentArchetypeName | string;
2726
+ /** Model family the finding applies to (e.g. 'claude-opus'). */
2727
+ family: string;
2728
+ /** Resolution semantics — see `PromoteReadyResolution`. */
2729
+ resolution: PromoteReadyResolution;
2730
+ /** Optional free-form note explaining the decision. */
2731
+ resolutionNote?: string;
2732
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). */
2733
+ brainEndpoint: string;
2734
+ /** Consumer-scoped JWT carrying the `app_id` claim. */
2735
+ brainJwt: string;
2736
+ /** Supabase anon key for the `apikey` header. */
2737
+ brainAnonKey: string;
2738
+ /** Injected fetch for tests. Defaults to global fetch. */
2739
+ fetch?: typeof fetch;
2740
+ }
2741
+ /**
2742
+ * Mark a probe-validated promote-ready finding as handled. Returns an
2743
+ * `ok/reason` envelope matching `markExclusionFindingHandled`.
2744
+ *
2745
+ * Idempotent: if no row matches the (app_id, archetype, family) tuple
2746
+ * (already resolved, never existed, watcher not yet UPSERTed), PostgREST
2747
+ * returns 200/204 with zero affected rows and we return `{ ok: true }`.
2748
+ *
2749
+ * Reasons surfaced on failure:
2750
+ * - `app_id_required` / `archetype_required` / `family_required`
2751
+ * - `resolution_invalid` — not one of the three documented values
2752
+ * - `brain_auth_misconfig` — 401/403
2753
+ * - `brain_unavailable` — 5xx
2754
+ * - `network_error:<message>` — fetch threw
2755
+ * - `patch_failed:<status>` — anything else non-2xx
2756
+ */
2757
+ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions): Promise<{
2758
+ ok: true;
2759
+ } | {
2760
+ ok: false;
2761
+ reason: string;
2762
+ }>;
2763
+
2764
+ /**
2765
+ * promotions-brain — alpha.64 Stage-2 substrate.
2766
+ *
2767
+ * Per-tenant SWR cache for the `kgauto_promotions` table populated by the
2768
+ * golden-eval trigger's auto-promote actor (Stage 2 of the eval trust
2769
+ * ladder: auto-promote downswaps behind the 7-day rollback guard). Mirrors
2770
+ * `promote-ready-brain.ts` shape where applicable; this is the read-side
2771
+ * substrate for the compile-time promotion boost in `passScoreTargets`.
2772
+ *
2773
+ * Design contract:
2774
+ * command-center/advisory/kgauto/2026-07-18_stage2-auto-promote-design.md
2775
+ *
2776
+ * Consent posture: the routing effect is OPT-IN, default OFF. The cache is
2777
+ * only activated by `configureBrain()` when the consumer opted in via
2778
+ * `BrainConfig.autoPromote: true` or the `KGAUTO_AUTO_PROMOTE` env var
2779
+ * (config field wins when both are present — mirror of the
2780
+ * `KGAUTO_GOLDEN_CAPTURE` env-as-consent precedent). Not opted in ⇒ this
2781
+ * module never fetches and `getApplicablePromotion` returns undefined ⇒
2782
+ * zero behavior change anywhere in compile().
2783
+ *
2784
+ * Architecture (mirror of promote-ready-brain):
2785
+ * - Sync API surface: `getApplicablePromotion({ appId, archetype })`
2786
+ * returns immediately. First call returns undefined (cold) and fires an
2787
+ * async refresh; subsequent calls within TTL return brain data.
2788
+ * - Per-appId snapshot; one fetch per appId per TTL window.
2789
+ * - Tolerant: brain down / misconfigured / unexpected shape → undefined.
2790
+ * Never throws. Warns once per process.
2791
+ *
2792
+ * A rollback (`status='rolled_back'` PATCHed by the promotion-guard
2793
+ * watcher) drops the row from the endpoint's `status=active` filter, so
2794
+ * routing reverts within one TTL window — the mechanism the 7-day guard's
2795
+ * auto-revert rests on.
2796
+ */
2797
+
2798
+ /**
2799
+ * One active surface promotion, camelCase-mapped at the boundary from the
2800
+ * snake_case endpoint row (typed-boundary-transformer convention).
2801
+ */
2802
+ interface PromotionRow {
2803
+ /** Brain row id — cited in the `promotion-applied` mutation for Glass-Box. */
2804
+ id: number;
2805
+ /** Intent archetype the promotion applies to. */
2806
+ archetype: string;
2807
+ /** The model this surface now routes to. */
2808
+ promotedModel: string;
2809
+ /** The model it replaced (the eval's incumbent). */
2810
+ incumbentModel: string;
2811
+ /** The promote-ready kgauto_golden_eval_runs row this rests on. */
2812
+ evalRunId: number | null;
2813
+ /**
2814
+ * Evidence-supersedes-judgment: skip the alpha.49 schema-weak
2815
+ * quality-gate penalty for the promoted model on this surface (the eval
2816
+ * measured the schema floor holding on real workload).
2817
+ */
2818
+ suppressQualityGate: boolean;
2819
+ /** ISO timestamp the promotion went active. */
2820
+ promotedAt: string;
2821
+ }
2822
+ interface PromotionsRuntime {
2823
+ /** Endpoint base URL. The library appends `?app_id=<id>`. */
2824
+ endpoint: string;
2825
+ /** Stale-while-revalidate window in ms. */
2826
+ ttlMs: number;
2827
+ /** Pluggable fetch. */
2828
+ fetchImpl: typeof fetch;
2829
+ /** Optional warn hook. */
2830
+ onError?: (err: unknown) => void;
2831
+ }
2832
+ /**
2833
+ * Default endpoint hosted on the kgauto-dashboard. Serves `status='active'`
2834
+ * kgauto_promotions rows for one app_id. Mirrors the findings convention.
2835
+ */
2836
+ declare const DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
2837
+ /**
2838
+ * True when the KGAUTO_AUTO_PROMOTE env var opts this process in.
2839
+ * Accepted truthy forms: '1', 'true' (case-insensitive). Everything else —
2840
+ * unset, '', '0', 'false' — is OFF. Read at configureBrain() time, not per
2841
+ * call.
2842
+ */
2843
+ declare function isAutoPromoteEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
2844
+ /**
2845
+ * Wire (or rewire) the runtime. Pass undefined to disable. Resets all
2846
+ * snapshots. Called from `configureBrain()` ONLY when the consumer opted in.
2847
+ */
2848
+ declare function configurePromotionsBrain(rt: PromotionsRuntime | undefined): void;
2849
+ /** Sync introspection — is the promotions brain active (i.e. opted in)? */
2850
+ declare function isPromotionsBrainActive(): boolean;
2851
+ interface GetApplicablePromotionOpts {
2852
+ /** App id to read promotions for. Required. */
2853
+ appId: string;
2854
+ /** Archetype of the compile in flight. Required. */
2855
+ archetype: IntentArchetypeName | string;
2856
+ }
2857
+ /**
2858
+ * Sync reader. Returns the active promotion for `(appId, archetype)` or
2859
+ * undefined. First call returns undefined and triggers async refresh;
2860
+ * subsequent calls within TTL return brain data. The brain enforces one
2861
+ * active promotion per surface (partial unique index), so at most one row
2862
+ * matches.
2863
+ *
2864
+ * NEVER throws. Not configured / brain down / cold → undefined.
2865
+ */
2866
+ declare function getApplicablePromotion(opts: GetApplicablePromotionOpts): PromotionRow | undefined;
2867
+ /** Reset module state. Tests must call between cases. */
2868
+ declare function _testResetPromotions(): void;
2869
+ /** Wait for any in-flight refresh to settle. */
2870
+ declare function _testWaitForPromotionsRefresh(): Promise<void>;
2871
+
2872
+ /**
2873
+ * measured-failure-brain — the CREATE-a-gate direction of
2874
+ * measured-supersedes-judgment (alpha.70).
2875
+ *
2876
+ * alpha.49 gives kgauto a quality gate that fires off a model profile's
2877
+ * DECLARED conventions (`archetypeConventions.structuredOutputHint: 'avoid'`).
2878
+ * alpha.64 let a MEASURED eval verdict SUPPRESS that gate
2879
+ * (`kgauto_promotions.suppress_quality_gate`). Nothing could go the other
2880
+ * way — a model whose declarations are wrong could not have a gate CREATED
2881
+ * for it, which is precisely the case where declarations cannot be trusted.
2882
+ *
2883
+ * The originating evidence: `claude-haiku-4-5` on playbacksam/summarize
2884
+ * declares `structuredOutput: 'grammar'` + `archetypePerf.summarize: 8`, so
2885
+ * every quality signal reads green and it wins the surface on price — while
2886
+ * failing **12 of 12 in-window attempts** (2026-07-14..25, seven in one
2887
+ * day). The brain held that evidence and nothing could act on it.
2888
+ *
2889
+ * ── Design notes ───────────────────────────────────────────────────────
2890
+ *
2891
+ * **No stored decision.** The gate is DERIVED from a rolling 28d window
2892
+ * (`kgauto_surface_model_failure_v`), never written down. That kills the
2893
+ * flap problem by construction — there is no state to flap — and it means
2894
+ * a gated model un-gates itself once its failures age out. Combined with
2895
+ * the gate being a DE-RANK (out of leadership, retained as graceful
2896
+ * fallback) rather than a hard block, the model keeps earning evidence, so
2897
+ * this cannot become the exclusion-lock-in trap where a blocked model can
2898
+ * never prove itself again.
2899
+ *
2900
+ * **The threshold is a confidence bound, not a fixed sample floor.** A flat
2901
+ * `minSample: 20` (promotion-guard's rate floor) would NOT have fired on
2902
+ * haiku's n=12 — the consumer would keep paying while we waited for a
2903
+ * rounder number. But distinguishing 100% from 5% needs far fewer trials
2904
+ * than distinguishing 2% from 6%. Gating on the Wilson score lower bound
2905
+ * makes the sample requirement adapt to the effect size automatically,
2906
+ * which is the alpha.67 insight ("the sample floor for a median can be far
2907
+ * lower than for a rate") generalised properly.
2908
+ *
2909
+ * **Direct app-scoped read, not the config-endpoint cache.** Modelled on
2910
+ * `promotions-brain.ts`, deliberately NOT `createBrainQueryCache` — that
2911
+ * routes through the dashboard `/v2/config` projection, which is the third
2912
+ * layer in the L-073 "executable knowledge is dropped at every transport
2913
+ * boundary" chain. One fewer place to forget a field.
2914
+ */
2915
+
2916
+ /**
2917
+ * One row of the rolling-window evidence view, per (app, archetype, model).
2918
+ * Raw counts only — the brain serves facts, this module decides.
2919
+ */
2920
+ interface SurfaceFailureRow {
2921
+ archetype: string;
2922
+ model: string;
2923
+ /** Total attempts in-window (served + quality walkaways). */
2924
+ n: number;
2925
+ /** Attempts that failed on the quality axis. */
2926
+ nFail: number;
2927
+ }
2928
+ declare const MEASURED_FAILURE_CFG: {
2929
+ /**
2930
+ * Hard minimum attempts before ANY gate may be created. Guards against
2931
+ * pathological tiny samples that the confidence bound alone would let
2932
+ * through in edge cases. At 5-for-5 the bound clears the threshold; at
2933
+ * 3-for-3 it does not, which is the behaviour we want (three failures is
2934
+ * a bad day, five in a row is a pattern).
2935
+ */
2936
+ readonly minSample: 5;
2937
+ /**
2938
+ * Gate when we are 95% confident the model fails MORE OFTEN THAN IT
2939
+ * SUCCEEDS on this surface. Deliberately unarguable rather than tuned —
2940
+ * a model that probably fails the majority of the time has no business
2941
+ * leading a surface, whatever its declared scores say.
2942
+ */
2943
+ readonly lowerBoundThreshold: 0.5;
2944
+ /** 95% one-sided-ish confidence (standard two-sided z at α=0.05). */
2945
+ readonly z: 1.96;
2946
+ /** Must match the view's window. Documented here for the advisory text. */
2947
+ readonly windowDays: 28;
2948
+ };
2949
+ /**
2950
+ * Wilson score interval, lower bound. Preferred over the normal
2951
+ * approximation because it stays sane at the extremes — at p̂ = 1 the
2952
+ * normal approximation gives a zero-width interval (it would gate on a
2953
+ * single failure), while Wilson correctly returns a bound that tightens
2954
+ * with n.
2955
+ *
2956
+ * Returns 0 for n <= 0.
2957
+ */
2958
+ declare function wilsonLowerBound(failures: number, n: number, z?: number): number;
2959
+ interface MeasuredFailureVerdict {
2960
+ /** Whether the measured-failure quality gate fires for this tuple. */
2961
+ gated: boolean;
2962
+ /** Observed failure rate in-window. */
2963
+ rate: number;
2964
+ /** 95% lower confidence bound on that rate — what the gate tests. */
2965
+ lowerBound: number;
2966
+ /** Attempts backing the verdict. */
2967
+ n: number;
2968
+ nFail: number;
2969
+ }
2970
+ /**
2971
+ * Pure decision, exported for tests and for the advisory text. Separated
2972
+ * from the I/O so the policy can be exercised without a brain.
2973
+ */
2974
+ declare function judgeMeasuredFailure(row: SurfaceFailureRow | undefined, cfg?: typeof MEASURED_FAILURE_CFG): MeasuredFailureVerdict | undefined;
2975
+ interface MeasuredFailureRuntime {
2976
+ /** Endpoint base URL. The library appends `?app_id=<id>`. */
2977
+ endpoint: string;
2978
+ /** Stale-while-revalidate window in ms. */
2979
+ ttlMs: number;
2980
+ fetchImpl: typeof fetch;
2981
+ onError?: (err: unknown) => void;
2982
+ }
2983
+ /** Default endpoint on the kgauto-dashboard. Mirrors the promotions convention. */
2984
+ declare const DEFAULT_MEASURED_FAILURE_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure";
2985
+ /**
2986
+ * Opt-out env switch. UNLIKE auto-promote this defaults ON wherever the
2987
+ * brain is configured, because the gate is protective: it only ever
2988
+ * de-ranks a model the consumer's OWN traffic shows to be failing them, and
2989
+ * the failure is already being paid for. Set `KGAUTO_MEASURED_FAILURE_GATE=0`
2990
+ * (or 'false') to disable.
2991
+ */
2992
+ declare function isMeasuredFailureGateEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
2993
+ declare function configureMeasuredFailureBrain(rt: MeasuredFailureRuntime | undefined): void;
2994
+ declare function isMeasuredFailureBrainActive(): boolean;
2995
+ interface GetMeasuredFailureOpts {
2996
+ appId: string;
2997
+ archetype: IntentArchetypeName | string;
2998
+ model: string;
2999
+ }
3000
+ /**
3001
+ * Sync reader. Returns the verdict for `(appId, archetype, model)` or
3002
+ * undefined (not configured / cold / below minSample / brain down).
3003
+ *
3004
+ * NEVER throws. Cold start returns undefined and warms in the background —
3005
+ * same posture as every other brain-driven lever in compile().
280
3006
  */
281
- declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile): BestPracticeAdvisory[];
3007
+ declare function getMeasuredFailureVerdict(opts: GetMeasuredFailureOpts): MeasuredFailureVerdict | undefined;
3008
+ declare function _testResetMeasuredFailure(): void;
3009
+ declare function _testWaitForMeasuredFailureRefresh(): Promise<void>;
282
3010
 
283
3011
  /**
284
3012
  * @warmdrift/kgauto v2 — prompt compiler + central learning brain.
@@ -326,4 +3054,4 @@ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: Model
326
3054
  */
327
3055
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
328
3056
 
329
- export { ApiKeys, type AppOracle, BestPracticeAdvisory, type BrainConfig, CallOptions, CallResult, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type LLMJudgeOptions, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, PromptIR, ProviderOverrides, RecordInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, execute, record, resetTokenizer, runAdvisor, setTokenizer };
3057
+ 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, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, 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 PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, type SurfaceFailureRow, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, 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, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, setTokenizer, wilsonLowerBound };