@warmdrift/kgauto-compiler 2.0.0-alpha.8 → 2.0.0-alpha.80

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-65ZMX5OT.mjs +169 -0
  7. package/dist/{chunk-5TI6PNSK.mjs → chunk-BVEXV5KC.mjs} +11 -0
  8. package/dist/chunk-CIBHU67M.mjs +203 -0
  9. package/dist/chunk-NBO4R5PC.mjs +313 -0
  10. package/dist/chunk-P3TOAEG4.mjs +56 -0
  11. package/dist/chunk-PMTT4H5W.mjs +825 -0
  12. package/dist/chunk-RO22VFIF.mjs +29 -0
  13. package/dist/chunk-VVRDFE6T.mjs +1707 -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 +3057 -0
  29. package/dist/glassbox-routes/index.mjs +668 -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 +3449 -21
  35. package/dist/index.d.ts +3449 -21
  36. package/dist/index.js +10208 -1681
  37. package/dist/index.mjs +5891 -186
  38. package/dist/ir-BFwWhj2s.d.mts +1707 -0
  39. package/dist/ir-DZKS1tI7.d.ts +1707 -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 +302 -2
  45. package/dist/profiles.d.ts +302 -2
  46. package/dist/profiles.js +1320 -18
  47. package/dist/profiles.mjs +9 -1
  48. package/dist/types-B4kz3Vs0.d.ts +131 -0
  49. package/dist/types-D_fLt_Xv.d.ts +142 -0
  50. package/dist/types-DpcAMmk-.d.mts +131 -0
  51. package/dist/types-hjzSWxtv.d.mts +142 -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.mts 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-Py8c7zjJ.mjs';
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-Py8c7zjJ.mjs';
3
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, IntentArchetypeName, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, F as FallbackReason, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-BFwWhj2s.mjs';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as hasMutation, K as mutationId, L as parseGoldenCaptureRate, Q as resolveGoldenCaptureRate, U as shouldCaptureGolden } from './ir-BFwWhj2s.mjs';
3
+ import { ModelProfile, ArchetypeConvention } from './profiles.mjs';
4
+ export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.mjs';
5
+ export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.mjs';
6
+ export { KeyHealthConfig, KeyHealthProvider, KeyHealthResponseBody, KeyHealthResult, KeyHealthRoute, createKeyHealthRoute } from './key-health.mjs';
7
+ import { IntentArchetypeName, OutputMode } from './dialect.mjs';
8
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
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,29 @@ 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;
77
+ /**
78
+ * alpha.78 — abort signal for the provider fetch. call() composes
79
+ * `AbortSignal.timeout(attemptTimeoutMs)` with the caller's own
80
+ * `CallOptions.abortSignal`; direct execute() consumers may pass anything.
81
+ * TimeoutError reasons classify retryable `timeout` (chain walks);
82
+ * AbortError reasons classify terminal `aborted` (caller cancelled).
83
+ */
84
+ signal?: AbortSignal;
85
+ /**
86
+ * alpha.78 — per-chunk stall bound, streaming paths only (see
87
+ * StreamingOptions.stallTimeoutMs). Ignored on non-streaming requests,
88
+ * where `signal` carries the total attempt bound instead.
89
+ */
90
+ stallTimeoutMs?: number;
54
91
  }
55
92
  interface ExecuteOk {
56
93
  ok: true;
@@ -64,6 +101,19 @@ interface ExecuteErr {
64
101
  errorCode: string;
65
102
  message: string;
66
103
  raw: unknown;
104
+ /**
105
+ * alpha.66 — real token usage when the failure is a SYNTHESIZED
106
+ * structured-output contract violation (the provider returned 200 with
107
+ * usage; the response just violated the contract). Absent on transport-
108
+ * level failures (4xx/5xx/network) where no usage exists. Lets the
109
+ * brain's failure rows carry true `tokens_in` for the cliff class —
110
+ * PB's 2026-05-18 `chain-walk-on-structured-output-parse-failed` ask 4
111
+ * (tokens_in=0 on a 72s parse-fail made diagnosis ambiguous).
112
+ */
113
+ tokens?: {
114
+ input: number;
115
+ output: number;
116
+ };
67
117
  }
68
118
  type ExecuteResult = ExecuteOk | ExecuteErr;
69
119
  declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promise<ExecuteResult>;
@@ -84,26 +134,347 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
84
134
  * Hard cap at fallbackChain.length + 1 attempts. Terminal errors short-circuit.
85
135
  */
86
136
 
137
+ declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
138
+ /** Served-side result the AI-SDK consumer already holds from streamText. */
139
+ interface ProbeShadowServed {
140
+ /** Model id that actually served the user (becomes `current_model` on the row). */
141
+ model: string;
142
+ /** The served response text (stored as a preview; never the prompt). */
143
+ responseText: string;
144
+ /** Served prompt tokens (AI SDK `usage.promptTokens`). */
145
+ tokensIn: number;
146
+ /** Served completion tokens (AI SDK `usage.completionTokens`). */
147
+ tokensOut: number;
148
+ /** The user's actual wait in ms (alpha.46 served-latency axis). */
149
+ latencyMs: number;
150
+ }
151
+ /** Options for the standalone {@link probeShadow} export. */
152
+ interface ProbeShadowOptions {
153
+ /** The served leg the consumer supplies; kgauto runs the candidate leg. */
154
+ served: ProbeShadowServed;
155
+ /** Model id(s)/family alias(es) to shadow-test against the served model. */
156
+ candidates: string | string[];
157
+ /** Probability [0,1] a given call fires a probe. Default 0.05; pin 1 for dogfood. */
158
+ sampleRate?: number;
159
+ /** Phase 1 = 'off' (offline rollup). 'opus' inline judge is Phase 2. Default 'off'. */
160
+ judge?: 'off' | 'opus';
161
+ /** Override API keys (defaults: process.env). Gates candidate reachability. */
162
+ apiKeys?: ApiKeys;
163
+ /** Override fetch (for tests / custom transport). */
164
+ fetchImpl?: typeof fetch;
165
+ /** Provider-specific request fields shallow-merged into the candidate request. */
166
+ providerOverrides?: ProviderOverrides;
167
+ /** Forwarded to compile() for the candidate run (match the served-side compile). */
168
+ policy?: CompilePolicy;
169
+ toolRelevanceThreshold?: number;
170
+ compressHistoryAfter?: number;
171
+ }
172
+ /**
173
+ * s54 — standalone full-IR shadow probe for AI-SDK consumers (tt-intel hunt, IC
174
+ * chat) that own their own streamText round-trip and never call call(). Fire it
175
+ * from the streamText `onFinish` callback, wrapped in the platform's
176
+ * `waitUntil()` / `after()`, so it runs after the response is flushed — no
177
+ * blocking, no `sync:true`, no teardown race (cleaner than call()'s in-process
178
+ * fire-and-forget for Edge runtimes; L-086).
179
+ *
180
+ * Runs the SAME candidate loop as the call()-inline probe ({@link
181
+ * runProbeCandidates}): same gates (sample, self-skip, G4 judge-self,
182
+ * reachability, G6), same fidelity=1.0 full-IR rows, same alpha.46 latency
183
+ * capture. The consumer supplies the served leg it already has; kgauto runs the
184
+ * candidate(s) and writes the `probe_outcomes` row.
185
+ *
186
+ * Requires `configureBrain()` to have been called (same as call()).
187
+ * Fire-and-forget: never throws into the caller.
188
+ *
189
+ * @example
190
+ * const result = streamText({ model, system, messages,
191
+ * onFinish: ({ text, usage }) => {
192
+ * after(() => probeShadow(ir, {
193
+ * served: { model: servedModelId, responseText: text,
194
+ * tokensIn: usage.promptTokens, tokensOut: usage.completionTokens,
195
+ * latencyMs: Date.now() - t0 },
196
+ * candidates: ['deepseek-v4-pro'], sampleRate: 0.05,
197
+ * }));
198
+ * },
199
+ * });
200
+ */
201
+ declare function probeShadow(ir: PromptIR, opts: ProbeShadowOptions): Promise<void>;
202
+
87
203
  /**
88
- * Compile, execute, normalize, record. Returns a CallResult once a provider
89
- * actually serves the request. Throws CallError if the fallback chain is
90
- * exhausted without success.
204
+ * alpha.33 AI-SDK streamText helpers.
205
+ *
206
+ * The cross-consumer pattern surfaced 2026-05-20 (`streamText-cache-marker-
207
+ * propagation-gap` on `command-center/interfaces/kgauto.md ## Requested`):
208
+ * AI-SDK consumers using `streamText({ system: <string>, messages:
209
+ * convertToModelMessages(messages), model })` silently drop the Anthropic
210
+ * `cache_control` markers the compiler emits on `result.request.messages`.
211
+ * Two losses on that line:
212
+ * (a) `convertToModelMessages()` reads raw inputs not the lowered output,
213
+ * dropping per-message providerOptions; and
214
+ * (b) `streamText({ system: '<string>' })` strips any providerOptions
215
+ * on the system prefix.
216
+ *
217
+ * Net effect prior to this surface: `cache_read_input_tokens = 0` across
218
+ * every measured production call by IC + tt-intel even though both
219
+ * consumers had `historyCachePolicy: { strategy: 'all-but-latest' }` wired
220
+ * since alpha.5. The compiler did the right thing; the consumer integration
221
+ * pattern lost the markers at the wire boundary.
222
+ *
223
+ * This helper closes the gap. Pass the consumer's already-converted messages
224
+ * + the kgauto CompileResult and get back a `{ system, messages }` pair
225
+ * with cacheControl re-attached at the deterministic indices the compiler
226
+ * computed (`diagnostics.historyCacheMarkIndex` + `systemMessages` with
227
+ * its own cacheControl markers).
228
+ *
229
+ * No I/O. Pure transform. Idempotent — calling twice with the same inputs
230
+ * produces structurally-identical output.
91
231
  */
92
- declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
93
232
 
94
233
  /**
95
- * Brain client — fire-and-forget telemetry to the central kgauto Supabase.
234
+ * AI-SDK-shaped converted-message structure. Matches what
235
+ * `convertToModelMessages()` returns at the wire layer. We don't import
236
+ * the AI-SDK type to avoid pulling that dep into the kgauto-compiler
237
+ * package — consumers pass their own already-converted messages.
238
+ */
239
+ interface AISDKConvertedMessage {
240
+ role: 'system' | 'user' | 'assistant' | 'tool';
241
+ content: unknown;
242
+ providerOptions?: {
243
+ anthropic?: {
244
+ cacheControl?: {
245
+ type: 'ephemeral';
246
+ };
247
+ };
248
+ };
249
+ }
250
+ /**
251
+ * Result of `attachCacheControlToStreamTextInput()` — ready to spread into
252
+ * `streamText(...)` directly.
253
+ *
254
+ * The `system` field is either the structured `SystemModelMessage[]` form
255
+ * (when the compiler computed at least one cacheable section + chose
256
+ * Anthropic) or the flat-string concatenation (when no cacheable sections
257
+ * exist OR the provider isn't Anthropic). Consumers can pass either form
258
+ * to `streamText({ system })` — the AI-SDK accepts both.
259
+ */
260
+ interface AttachCacheControlResult {
261
+ system: string | SystemModelMessage[];
262
+ messages: AISDKConvertedMessage[];
263
+ }
264
+ /**
265
+ * Attach Anthropic cache_control markers to a streamText input that the
266
+ * consumer has already prepared via `convertToModelMessages()`. Reads
267
+ * `result.diagnostics.historyCacheMarkIndex` for the position-on-history
268
+ * marker and `result.systemMessages` for the per-section system markers.
269
+ *
270
+ * The flat-string `system` form is returned when:
271
+ * - the compiler produced no `systemMessages` (e.g., zero sections kept), or
272
+ * - the chosen provider is not Anthropic, so cacheControl wouldn't
273
+ * achieve anything at the wire layer (other providers cache implicitly
274
+ * based on prefix shape, no marker needed).
275
+ *
276
+ * Otherwise the structured `SystemModelMessage[]` form is returned —
277
+ * preserves the per-section cacheControl markers across `streamText`.
278
+ *
279
+ * @param result - kgauto CompileResult from `compile(ir, opts)`
280
+ * @param convertedMessages - the consumer's already-converted messages
281
+ * (from `convertToModelMessages(rawMessages)` in their AI-SDK call site)
282
+ * @returns `{ system, messages }` ready to spread into `streamText(...)`
283
+ */
284
+ declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
285
+
286
+ /**
287
+ * alpha.52 — official AI-SDK-v6 compile adapter + compile-then-discard guard.
288
+ *
289
+ * Until now each AI-SDK consumer (tt-intel, IC) hand-rolled this adapter in
290
+ * its own `lib/kgauto-v2/index.ts`: `compile()` → reassemble the system param
291
+ * per provider → extract kept tool names per provider → re-derive the history
292
+ * cache-mark index (a copy of the compiler's own `historyCacheMarkIndex`
293
+ * logic — drift-prone). This centralizes that boilerplate and DRYs the two
294
+ * near-identical wrappers.
96
295
  *
97
- * The brain is the centralized learning store. Apps POST outcomes here;
98
- * mutations flow back through a separate pull (in v2.1).
296
+ * It also closes the compile-then-discard hole. The discard pattern is:
297
+ *
298
+ * const c = compileForAISDKv6(ir); // compile runs
299
+ * const out = await generateText({ // …but a hand-built prompt
300
+ * model: getModel(otherId), prompt }); // + a DIFFERENT model run
301
+ * await record({ handle: c.handle, … }); // brain row attributed to `c`
302
+ *
303
+ * The recorded row's `mutations_applied` / `estimated_tokens_in` /
304
+ * `system_prompt_chars` then describe a compile that never reached the wire.
305
+ * A library-level runtime guard could NOT catch this while the adapter lived
306
+ * in consumer code (the consumer wrapper always reads `compile()`'s result to
307
+ * build its own object, so any getter there is "consumed" every time,
308
+ * regardless of whether the final caller used the wrapper output). With the
309
+ * adapter IN the library, the object the FINAL caller reads is library-owned,
310
+ * so consume-tracking getters on `.system` / `.model` / `.raw` detect non-use
311
+ * and `record()` warns. See `interfaces/kgauto.md` (## Requested:
312
+ * `compiled-output-discarded-guard`).
313
+ *
314
+ * The guard is OPT-IN-BY-USE: only `compileForAISDKv6` arms tracking, so
315
+ * `call()` paths and raw `compile()` users never see a false warning.
316
+ */
317
+
318
+ interface CompileForAISDKv6Result {
319
+ /**
320
+ * Pass to `streamText`/`generateText({ model })` — the caller maps this id
321
+ * to an AI-SDK `LanguageModel`. Reading this marks the compile "consumed"
322
+ * (silences the compile-then-discard guard).
323
+ */
324
+ readonly model: string;
325
+ /**
326
+ * System parameter for `streamText`/`generateText({ system })`. Returns the
327
+ * structured `SystemModelMessage[]` form when the target is Anthropic AND a
328
+ * cacheable section exists (preserves the cache_control marker across the
329
+ * wire); a flat concatenated string otherwise. Reading this marks
330
+ * "consumed". (Same rule as `attachCacheControlToStreamTextInput`.)
331
+ */
332
+ readonly system: string | SystemModelMessage[];
333
+ /**
334
+ * The raw kgauto `CompileResult` — for `attachCacheControlToStreamTextInput(raw, msgs)`
335
+ * and `probeShadow(raw.ir-equivalent, …)` paths. Reading this marks
336
+ * "consumed" (it means you're using the compile output via the raw result).
337
+ */
338
+ readonly raw: CompileResult;
339
+ /** Tool names that survived budget + relevance — filter your SDK tool map to these. */
340
+ keptToolNames: Set<string>;
341
+ /** providerOptions for `streamText` — Anthropic cache_control on the cacheable prefix. Undefined otherwise. */
342
+ providerOptions?: {
343
+ anthropic?: {
344
+ cacheControl?: {
345
+ type: 'ephemeral';
346
+ };
347
+ };
348
+ };
349
+ /**
350
+ * Index (into post-strip history) for the Anthropic history cache marker
351
+ * (alpha.33). Mirror of `result.diagnostics.historyCacheMarkIndex` — no
352
+ * consumer re-derivation needed. Undefined when no marker fires, and (since
353
+ * alpha.55) always undefined for non-Anthropic targets: the marker is an
354
+ * Anthropic wire concept, other providers cache prefixes implicitly. The
355
+ * ungated value remains on `diagnostics.historyCacheMarkIndex`.
356
+ */
357
+ historyCacheMarkIndex?: number;
358
+ /** Compile handle — pass to `record()` after the call. */
359
+ handle: string;
360
+ /**
361
+ * Mutation ids the compiler fired (informational).
362
+ *
363
+ * ⚠️ alpha.78 — element type differs BY SURFACE: this adapter carries
364
+ * `string[]` (ids), while `CompileResult`/`CallResult.mutationsApplied`
365
+ * carry `MutationApplied[]` (objects with `description`, `rankDelta`, …).
366
+ * Coding to one surface's type while reading the other's runtime is a
367
+ * silent false negative (PB 2026-07-25). Use the shape-proof helpers
368
+ * `mutationId(m)` / `hasMutation(list, 'quality-gate-measured-*')` from
369
+ * the package root instead of `typeof` checks. Neither element type can
370
+ * change without breaking a live consumer (tt-intel joins these ids;
371
+ * object readers want `description`), so the divergence is documented
372
+ * rather than unified.
373
+ */
374
+ mutationsApplied: string[];
375
+ /** Best-practice advisories (alpha.6). Empty when none fired. */
376
+ advisories: BestPracticeAdvisory[];
377
+ /** Compiler diagnostics + the three commonly-logged top-level fields. */
378
+ diagnostics: CompileResult['diagnostics'] & {
379
+ targetProvider: string;
380
+ estimatedCostUsd: number;
381
+ fallbackChain: string[];
382
+ };
383
+ /** The compiled IR — pass to `probeShadow(ir, …)` in `onFinish` (alpha.48). */
384
+ ir: PromptIR;
385
+ }
386
+ /**
387
+ * Compile a `PromptIR` and lower it to an AI-SDK-v6 `streamText`/`generateText`
388
+ * bundle. Replaces the hand-rolled per-consumer adapter.
99
389
  *
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.
390
+ * Arms the compile-then-discard guard: read `.system` / `.model` / `.raw` to
391
+ * serve the call. If you `record()` the handle without reading any of them,
392
+ * `record()` emits a dev-mode warning that the compile was discarded.
102
393
  */
394
+ declare function compileForAISDKv6(ir: PromptIR, opts?: CompileOptions): CompileForAISDKv6Result;
103
395
 
396
+ /**
397
+ * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
398
+ * perf / pricing / models registry). Enabled by default when endpoint is
399
+ * set; per-table opt-out via explicit `false`.
400
+ *
401
+ * Locked via /plan-eng-review 2026-05-15 (decision D3). Structured group
402
+ * keeps the BrainConfig surface clean as more brain-driven tables ship.
403
+ */
404
+ interface BrainQueryConfig {
405
+ /** Default true when endpoint set. Brain-driven fallback chains. */
406
+ chains?: boolean;
407
+ /** Default true when endpoint set. Brain-driven archetype perf scores. */
408
+ perf?: boolean;
409
+ /** Default true when endpoint set. Brain-driven pricing with at-time resolution. */
410
+ pricing?: boolean;
411
+ /** Default true when endpoint set. Brain-driven model registry + aliases. */
412
+ models?: boolean;
413
+ /**
414
+ * alpha.38 — opt-in compile-time advisor for stale exclusions. Default
415
+ * `true` when endpoint is set. When enabled, the library reads
416
+ * `exclusion_findings` from the central kgauto-dashboard for the consumer's
417
+ * `app_id` (no consumer-side proxy work required) and surfaces a
418
+ * `stale-exclusion-candidate` advisory when compile()'s archetype has a
419
+ * recommend-probe finding open. Set `false` to silence (no fetch, no
420
+ * advisory).
421
+ */
422
+ findingsExclusions?: boolean;
423
+ /**
424
+ * alpha.64 — hard opt-out of the surface-promotions fetch layer (Stage 2).
425
+ * Default true; only matters when consent (`BrainConfig.autoPromote` /
426
+ * `KGAUTO_AUTO_PROMOTE`) is present — without consent the layer is off
427
+ * regardless. Set `false` to disable the fetch even while consented
428
+ * (debug/emergency lever).
429
+ */
430
+ promotions?: boolean;
431
+ /** SWR window in ms. Default 300_000 (5 min). */
432
+ cacheTtlMs?: number;
433
+ /** Override the GET URL when the read endpoint differs from the write one.
434
+ * Defaults to `${endpoint}/v2/config` when omitted. */
435
+ configEndpoint?: string;
436
+ /**
437
+ * alpha.38 — override the findings endpoint when the consumer wants to
438
+ * proxy `exclusion_findings` reads through their own service rather than
439
+ * reading directly from the kgauto-dashboard. Library appends `?app_id=X`.
440
+ * Defaults to `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`.
441
+ */
442
+ findingsEndpoint?: string;
443
+ /**
444
+ * alpha.64 — override the surface-promotions endpoint (Stage 2). Only
445
+ * consulted when the consumer opted in via `BrainConfig.autoPromote` /
446
+ * `KGAUTO_AUTO_PROMOTE`. Library appends `?app_id=X`. Defaults to
447
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions`.
448
+ */
449
+ promotionsEndpoint?: string;
450
+ /**
451
+ * alpha.70 — hard opt-out of the measured-failure gate fetch layer.
452
+ * Default true (the gate is opt-OUT, see `BrainConfig.measuredFailureGate`).
453
+ */
454
+ measuredFailure?: boolean;
455
+ /**
456
+ * alpha.70 — override the measured-failure endpoint. Library appends
457
+ * `?app_id=X`. Defaults to
458
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure`.
459
+ */
460
+ measuredFailureEndpoint?: string;
461
+ }
104
462
  interface BrainConfig {
105
463
  /** Brain HTTP endpoint base URL (e.g., https://kgauto-brain.vercel.app/api). */
106
464
  endpoint: string;
465
+ /**
466
+ * alpha.73 — the consumer's app id, declared once so brain-driven levers can
467
+ * start their first read at configuration time instead of at the first
468
+ * compile.
469
+ *
470
+ * Optional and purely an optimisation: every IR already carries `appId`, and
471
+ * omitting this changes no verdict — it only means the measured-failure
472
+ * gate's warm-up starts when `call()` runs rather than when the module
473
+ * initialises. Declaring it lets a short-lived isolate spend its startup
474
+ * time on the fetch, so the bounded wait in `call()` usually costs nothing.
475
+ * Consumers running one app per process should set it.
476
+ */
477
+ appId?: string;
107
478
  /** Bearer token for auth. */
108
479
  apiKey?: string;
109
480
  /** Optional error hook for debugging. Defaults to console.warn. */
@@ -112,16 +483,145 @@ interface BrainConfig {
112
483
  sync?: boolean;
113
484
  /** Optional fetch override (for tests). */
114
485
  fetchImpl?: typeof fetch;
486
+ /** alpha.11 — brain-query mode for config tables. Default-on per table
487
+ * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
488
+ brainQuery?: BrainQueryConfig;
489
+ /**
490
+ * alpha.52 — emit a dev-mode `console.warn` when a `compileForAISDKv6()`
491
+ * result is passed to record() but its `.system` / `.model` / `.raw` were
492
+ * never read (the compile-then-discard pattern: the recorded brain row's
493
+ * `mutations_applied` / `estimated_tokens_in` / `system_prompt_chars`
494
+ * describe a compile that did NOT shape the served call). Default: warn
495
+ * when `NODE_ENV !== 'production'`, silent in production. Set `true` to
496
+ * force-on (e.g. a prod audit window) or `false` to silence. No-op for
497
+ * `call()` paths and raw `compile()` users — only `compileForAISDKv6`
498
+ * arms the tracking, so good actors never see a false warning.
499
+ */
500
+ warnOnDiscardedCompile?: boolean;
501
+ /**
502
+ * alpha.59 — per-leg timeout (ms) applied to every brain WRITE POST
503
+ * (record() primary + advisory secondary, recordOutcome(),
504
+ * recordShadowProbe()) via `AbortSignal.timeout`. Default 10000.
505
+ *
506
+ * Why: `sync: true` puts these fetches on the USER path (Edge consumers
507
+ * await record() before responding), and alpha.56's representation
508
+ * passthrough added a second sequential POST (advisory secondary) to that
509
+ * same path — an unbounded hang on either leg holds the user to the Edge
510
+ * limit (GE's `brainconfig-first-class-timeout` filing; GE bounded it at
511
+ * 3s via a hand-rolled fetchImpl wrapper every sync consumer had to
512
+ * rediscover).
513
+ *
514
+ * A fired timeout follows each leg's existing degraded-brain path
515
+ * (fire-and-forget: swallowed via onError; sync: `persistence_failed`
516
+ * result — never a throw into the user path). Wraps the configured
517
+ * `fetchImpl` rather than replacing it, so it composes with
518
+ * consumer-supplied impls. Set `0` to disable (pre-alpha.59 unbounded
519
+ * behavior). Brain-query reads (config tables) are cached + SWR and are
520
+ * not affected.
521
+ */
522
+ timeoutMs?: number;
523
+ /**
524
+ * alpha.64 (Stage 2 of the eval trust ladder) — consent switch for the
525
+ * surface-promotion routing effect. Default OFF.
526
+ *
527
+ * When true (or when the `KGAUTO_AUTO_PROMOTE` env var is '1'/'true' and
528
+ * this field is left undefined — env-as-consent, the KGAUTO_GOLDEN_CAPTURE
529
+ * precedent; an explicit `false` here overrides the env), compile()
530
+ * consults the brain's active `kgauto_promotions` rows for this app and
531
+ * boosts the promoted model at scoring time. Promotions are written only
532
+ * by the automated golden-eval trigger after a promote-ready verdict on a
533
+ * price-dominant (cheaper) candidate, and every promotion sits behind the
534
+ * 7-day rollback guard (daily watcher auto-reverts on regression vs the
535
+ * frozen baseline).
536
+ *
537
+ * Not opted in ⇒ promotions have ZERO routing effect (they remain visible
538
+ * as advisories + dashboard rows). Consumer sovereignty is preserved even
539
+ * when opted in: `forceModel`, `policy.blockedModels`, and cost ceilings
540
+ * always win, and a non-empty `policy.preferredModels` defers the
541
+ * promotion entirely.
542
+ */
543
+ autoPromote?: boolean;
544
+ /**
545
+ * alpha.70 — the measured-failure quality gate. **Default ON** wherever
546
+ * the brain is configured; set `false` (or `KGAUTO_MEASURED_FAILURE_GATE=0`)
547
+ * to disable. An explicit value here wins over the env var.
548
+ *
549
+ * Why this is opt-OUT while `autoPromote` is opt-IN: a promotion silently
550
+ * changes WHICH model serves you on kgauto's evidence, so it needs
551
+ * consent. This gate only ever DE-RANKS a model that the consumer's own
552
+ * outcome rows show failing them — the failures are already being paid
553
+ * for on their bill and their users' latency, and the model stays
554
+ * available as a graceful fallback. Requiring an opt-in to stop paying
555
+ * would be the wrong default.
556
+ *
557
+ * Consumer sovereignty is unchanged: `forceModel` still wins. Unlike a
558
+ * promotion, `policy.preferredModels` does NOT defer the gate — a
559
+ * preference says which model you would like to lead, not that a
560
+ * measurably-failing one works.
561
+ */
562
+ measuredFailureGate?: boolean;
115
563
  }
116
564
  declare function configureBrain(config: BrainConfig): void;
117
565
  declare function clearBrain(): void;
566
+ interface BrainHealthSnapshot {
567
+ configState: 'configured' | 'not_configured';
568
+ /** Host of the configured endpoint (never the full URL — no secrets/paths). */
569
+ endpointHost?: string;
570
+ /** True when writes are awaited (BrainConfig.sync). */
571
+ sync: boolean;
572
+ /** Write POSTs attempted (all routes, primary + secondary). */
573
+ sent: number;
574
+ /** Write POSTs acknowledged 2xx without redirect. */
575
+ acked: number;
576
+ /** Write POSTs that failed (non-2xx, redirect, timeout, network throw). */
577
+ failed: number;
578
+ /** Subset of `failed` that failed the redirect check (middleware-drift class). */
579
+ redirected: number;
580
+ lastAckAt?: string;
581
+ lastFailureAt?: string;
582
+ /** Most recent failure message, truncated. */
583
+ lastFailure?: string;
584
+ deadLetterCount: number;
585
+ }
586
+ interface BrainDeadLetterEntry {
587
+ /** Brain route segment the payload was bound for. */
588
+ route: 'outcomes' | 'compile_outcome_quality' | 'probe_outcomes' | 'compile_outcome_advisories' | 'golden_irs';
589
+ /**
590
+ * Endpoint the payload was originally bound for. Flush replays ONLY entries
591
+ * matching the currently-configured endpoint — a reconfigure must never
592
+ * replay another brain's payloads into the new target (caught live by
593
+ * smoke-brain-timeout: a hung-socket test payload auto-flushed into the
594
+ * real brain after the smoke re-pointed configureBrain).
595
+ */
596
+ endpoint: string;
597
+ /** The exact JSON body that failed to land. */
598
+ payload: unknown;
599
+ failedAt: string;
600
+ /** Delivery attempts so far (1 = the original failed POST). */
601
+ attempts: number;
602
+ lastError: string;
603
+ }
118
604
  /**
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.
605
+ * Process-local brain write delivery ledger. `acked` is the only number that
606
+ * means "a row landed" — fire-and-forget callers that need delivery evidence
607
+ * read this (or set `BrainConfig.sync`). Cheap enough to attach to any debug
608
+ * or health surface the consumer already exposes.
609
+ */
610
+ declare function brainHealth(): BrainHealthSnapshot;
611
+ /** Read-only view of the pending dead-letter (for consumer-side persistence). */
612
+ declare function peekBrainDeadLetter(): readonly BrainDeadLetterEntry[];
613
+ /**
614
+ * Replay pending dead-letter payloads against the configured brain. Delivered
615
+ * entries are removed; failures increment `attempts` and entries are dropped
616
+ * after 3 total attempts (bounded — never an infinite retry, per the Redis
617
+ * DLQ rule). Safe to call any time; no-ops when unconfigured or already
618
+ * flushing. Also runs opportunistically after any successful write.
124
619
  */
620
+ declare function flushBrainDeadLetter(): Promise<{
621
+ attempted: number;
622
+ delivered: number;
623
+ remaining: number;
624
+ }>;
125
625
  declare function record(input: RecordInput): Promise<void>;
126
626
  /**
127
627
  * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
@@ -168,8 +668,485 @@ interface OutcomePayload {
168
668
  cost_usd_actual?: number;
169
669
  ttft_ms?: number;
170
670
  history_cacheable_tokens?: number;
671
+ effort?: string;
171
672
  history_tokens_at_compile?: number;
673
+ /**
674
+ * Mirrors `ir.constraints.toolOrchestration` from compile time. NULL when
675
+ * the consumer hadn't adopted the constraint (pre-alpha.20). Powers
676
+ * per-mode model-perf queries on the brain (the L-040 parallel-tool
677
+ * cliff lumps DeepSeek sequential perf with parallel without this).
678
+ */
679
+ tool_orchestration?: 'parallel' | 'sequential' | 'either' | null;
680
+ finish_reason?: string;
681
+ total_ms?: number;
682
+ tools_count?: number;
683
+ history_depth?: number;
684
+ system_prompt_chars?: number;
685
+ fell_over_from?: string;
686
+ fallback_reason?: FallbackReason;
687
+ /**
688
+ * alpha.71 (migration 044) — the precise `errorCode` behind
689
+ * `fallback_reason`. Key OMITTED when no fallback fired, so brains that
690
+ * haven't applied 044 never see it.
691
+ */
692
+ fell_over_error_code?: string;
693
+ /**
694
+ * True when the same-model retry (CallOptions.sameModelRetry) fired
695
+ * during this call. Key OMITTED (not false) when no retry fired — safe
696
+ * against brains that haven't applied migration 039 yet.
697
+ */
698
+ retried_same_model?: boolean;
699
+ /**
700
+ * Per-call SectionRewrite[] captured at compile time. Omitted (sent as
701
+ * undefined → stored NULL) when no rewrites fired. Powers cross-app
702
+ * learning aggregates ("rule X fired N times on (app, model, archetype),
703
+ * downstream outcome quality lifted by M points").
704
+ */
705
+ section_rewrites_applied?: SectionRewrite[] | null;
706
+ /**
707
+ * R0 linkage (§5.0). Parent call's handle when this row is a fan-out branch;
708
+ * key OMITTED (undefined → dropped by JSON.stringify → stored NULL) for a
709
+ * root, safe against pre-042 brains.
710
+ */
711
+ parent_handle?: string;
712
+ /**
713
+ * R0 linkage (§5.0). Root handle of the fan-out trace (= parent_handle when a
714
+ * branch, else this row's own handle). Emitted for every registered compile.
715
+ */
716
+ trace_id?: string;
717
+ /**
718
+ * R0 linkage (§5.0). root | branch | composer. Emitted for every registered
719
+ * compile; surface baselines filter to root/NULL so branch traffic never
720
+ * contaminates a promotion/eval baseline. Release A emits only root/branch.
721
+ */
722
+ fanout_role?: 'root' | 'branch' | 'composer';
723
+ /**
724
+ * RD discipline gate-token accounting (§5.D). Measured token tax of the
725
+ * discipline_contract gate block; 0 when the gate didn't fire.
726
+ */
727
+ discipline_gate_tokens?: number;
728
+ }
729
+ /**
730
+ * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
731
+ *
732
+ * Fires after the consumer's UX surfaces an approve/reject event (e.g., user
733
+ * clicks Approve on a hunt result). Joins to the original `compile_outcomes`
734
+ * row via outcomeId — enables per-(model, archetype) approve-rate measurement
735
+ * once N ≥ 10 outcomes accumulate.
736
+ *
737
+ * Fire-and-forget by default (matches record() semantics). Set BrainConfig.sync
738
+ * = true for runtime contexts that can't tolerate fire-and-forget teardown
739
+ * (Vercel Edge, Cloudflare Workers, AWS Lambda) — see L-086.
740
+ *
741
+ * Returns (alpha.61): `{ok: true}` only when the POST was acknowledged 2xx
742
+ * (sync mode); `{ok: 'queued'}` in fire-and-forget mode (handed to the
743
+ * runtime, NOT acked — read `brainHealth()` for delivery evidence);
744
+ * `{ok: false, reason}` on known failure. Never throws.
745
+ */
746
+ declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
747
+ /**
748
+ * True when the active brain config requests synchronous (awaited) writes.
749
+ * call()'s shadow-probe path reads this to decide whether to await the probe
750
+ * (Edge/Worker/Lambda — L-086) or fire-and-forget (Node). False when no brain
751
+ * is configured.
752
+ */
753
+ declare function isBrainSync(): boolean;
754
+ /**
755
+ * Full-IR inline shadow-probe record input (Shape B, Phase 1 — s51). Carries
756
+ * ONLY response previews + metadata; the prompt (system/context/payload) is
757
+ * never included — `promptHash` is an irreversible grouping key, not content.
758
+ */
759
+ interface ShadowProbeRecordInput {
760
+ appId: string;
761
+ archetype: string;
762
+ family: string;
763
+ candidateModel: string;
764
+ currentModel: string;
765
+ /** Irreversible grouping hash (NOT the prompt). */
766
+ promptHash: string;
767
+ /** Served model's response, truncated (RESPONSE text only — never the prompt). */
768
+ currentResponsePreview?: string;
769
+ /** Candidate model's response, truncated. */
770
+ candidateResponsePreview?: string;
771
+ tokensCurrentIn?: number;
772
+ tokensCurrentOut?: number;
773
+ tokensCandidateIn?: number;
774
+ tokensCandidateOut?: number;
775
+ /**
776
+ * Wall-clock latency of the served call, ms (alpha.46). The third swap-decision
777
+ * axis alongside quality + cost — a verdict needs to know the candidate is
778
+ * slower, not just better/cheaper. Served latency mirrors
779
+ * `compile_outcomes.latency_ms`; carried here so a probe row is self-contained.
780
+ */
781
+ latencyCurrentMs?: number;
782
+ /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
783
+ latencyCandidateMs?: number;
784
+ /**
785
+ * alpha — probe-row class (migration 029; `candidate_error` added by 032).
786
+ * Defaults to `'completed'` (the pre-029 row shape: candidate ran, columns
787
+ * populated). `'aborted_latency_budget'` and `'skipped_slow_tier_sync'` are
788
+ * DIAGNOSTIC rows from sync-mode latency protection; `'candidate_error'`
789
+ * (alpha.53) is the failed-candidate diagnostic — the candidate call
790
+ * errored, with the error class + latency-at-death recorded instead of
791
+ * silence (the IC demo-night probe deaths were invisible for ~90 min under
792
+ * the old record-no-row rule). Diagnostic rows carry no candidate response
793
+ * and no verdict — no false quality signal. A verdict rollup MUST filter to
794
+ * `outcome='completed'`.
795
+ */
796
+ outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
797
+ /**
798
+ * alpha.53 (migration 032) — error class for `outcome='candidate_error'`
799
+ * rows. Values follow execute()'s taxonomy (`rate_limit`, `timeout`,
800
+ * `server_error`, `model_not_found`, `auth`, `invalid_request`, `unknown`)
801
+ * plus `execute_rejected` (the execute promise rejected outright). NULL /
802
+ * omitted on all other row classes.
803
+ */
804
+ errorClass?: string;
805
+ }
806
+ /**
807
+ * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
808
+ * Exported so a test can assert the G3 privacy invariant: the row carries NO
809
+ * prompt/system/context text — only response previews + metadata + a hash.
810
+ *
811
+ * Phase 1 (judge: 'off'): `judge_verdict` / `judge_score` are null — the row
812
+ * is an unjudged sample for the Phase-2 offline batch judge. `prompt_fidelity`
813
+ * is 1.0 by construction (the candidate ran the full IR, not a truncated
814
+ * preview), and `replay_source='inline-full-ir'` marks it as a trustworthy row
815
+ * (vs the watchers' lossy `replay-preview`).
816
+ */
817
+ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
818
+ app_id: string;
819
+ intent_archetype: string;
820
+ family: string;
821
+ candidate_model: string;
822
+ current_model: string;
823
+ prompt_hash: string;
824
+ current_response: string | null;
825
+ candidate_response: string | null;
826
+ judge_verdict: null;
827
+ judge_score: null;
828
+ tokens_current_in: number | null;
829
+ tokens_current_out: number | null;
830
+ tokens_candidate_in: number | null;
831
+ tokens_candidate_out: number | null;
832
+ latency_current_ms: number | null;
833
+ latency_candidate_ms: number | null;
834
+ prompt_fidelity: number;
835
+ replay_source: 'inline-full-ir';
836
+ outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
837
+ error_class: string | null;
838
+ };
839
+ /**
840
+ * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
841
+ * default; honors `BrainConfig.sync` (L-086). Never throws — failures route to
842
+ * onError. Mirrors record()'s POST shape; consumer proxies forward
843
+ * `/probe_outcomes` the same way they forward `/outcomes`.
844
+ */
845
+ declare function recordShadowProbe(input: ShadowProbeRecordInput): Promise<void>;
846
+ /**
847
+ * Golden-IR capture input. UNLIKE every other brain write, this row carries the
848
+ * RAW full PromptIR — an explicit, documented posture change from the s51
849
+ * "brain holds no raw consumer prompts" rule, gated on consumer opt-in
850
+ * (`KGAUTO_GOLDEN_CAPTURE` env / `CallOptions.goldenCapture`). The `consent`
851
+ * field records the provenance of that opt-in at capture time.
852
+ */
853
+ interface GoldenIrRecordInput {
854
+ appId: string;
855
+ archetype: string;
856
+ /** hashShape() of the call at compile time (peek before record() pops). */
857
+ shapeKey?: string;
858
+ /** The full PromptIR, verbatim. Plain JSON by construction (ir.ts). */
859
+ ir: unknown;
860
+ incumbentModel: string;
861
+ incumbentOutput?: string;
862
+ incumbentLatencyMs?: number;
863
+ incumbentTokensIn?: number;
864
+ incumbentTokensOut?: number;
865
+ /** 'sampled' (capture flag fired on live traffic) | 'curated' (operator). */
866
+ source: 'sampled' | 'curated';
867
+ /** Consent provenance, e.g. 'KGAUTO_GOLDEN_CAPTURE=0.1 (consumer env opt-in)'. */
868
+ consent: string;
869
+ /** Optional link back to the compile handle of the captured call. */
870
+ outcomeHandle?: string;
871
+ }
872
+ /** Pure builder for the `kgauto_golden_irs` row (snake_case wire shape). */
873
+ declare function buildGoldenIrRow(input: GoldenIrRecordInput): {
874
+ app_id: string;
875
+ intent_archetype: string;
876
+ shape_key: string | null;
877
+ ir: unknown;
878
+ incumbent_model: string;
879
+ incumbent_output: string | null;
880
+ incumbent_latency_ms: number | null;
881
+ incumbent_tokens_in: number | null;
882
+ incumbent_tokens_out: number | null;
883
+ source: 'sampled' | 'curated';
884
+ consent: string;
885
+ outcome_handle: string | null;
886
+ };
887
+ /**
888
+ * Persist one golden IR to `kgauto_golden_irs`. Same G1 write-leg discipline as
889
+ * every other brain route (redirect check, ledger, dead-letter); fire-and-forget
890
+ * by default, honors `BrainConfig.sync`. Never throws.
891
+ */
892
+ declare function recordGoldenIr(input: GoldenIrRecordInput): Promise<void>;
893
+
894
+ /**
895
+ * Golden-set eval engine (alpha.62, eval spine — design brief 2026-07-17).
896
+ *
897
+ * Implements the quality-floor-guarded model-swap contract:
898
+ *
899
+ * > A model replaces another on a surface only by demonstrating
900
+ * > same-or-better quality on that surface's real workload — never by
901
+ * > price, recency, or judgment alone.
902
+ *
903
+ * One eval run: load the active golden set for (app, archetype), replay every
904
+ * IR on BOTH the incumbent and the candidate (fresh outputs on both sides —
905
+ * fair comparison, no stale stored output), apply mechanical hard floors,
906
+ * then a pairwise LLM judge (order-swapped to cancel position bias), and
907
+ * aggregate under the non-inferiority rule:
908
+ *
909
+ * promote-ready ⇔ wins-or-ties ≥ threshold (default 80%)
910
+ * AND zero hard-floor violations
911
+ * AND candidate p50 latency ≤ ratio × incumbent p50
912
+ *
913
+ * Evidence lands as brain rows: one `kgauto_golden_eval_runs` aggregate + one
914
+ * `probe_outcomes` row per case (`replay_source='golden-replay'`, full
915
+ * fidelity by construction) + an evidence-attached advisory on the consumer's
916
+ * advisory surface (trust-ladder Stage 1: eval runs, human clicks promote).
917
+ *
918
+ * Judging is PAIRWISE, not absolute — it operationalizes the quality-floor
919
+ * Common Pattern directly ("same or better, never less"). Each pair is judged
920
+ * twice with A/B order swapped; disagreement between the two orders is scored
921
+ * a tie (the honest reading of positional noise).
922
+ *
923
+ * This module is operator-grade: it talks to the brain via direct PostgREST
924
+ * with a service key (the watchers' convention), never through consumer
925
+ * proxies, and it deliberately does NOT call record() — eval traffic must not
926
+ * pollute compile_outcomes.
927
+ */
928
+
929
+ /**
930
+ * What "better" means per archetype. Fed verbatim into the pairwise judge
931
+ * prompt. Kept deliberately short — the judge sees the full request, so the
932
+ * rubric only needs to name the failure modes that matter for the archetype.
933
+ */
934
+ declare const JUDGE_RUBRICS: Record<string, string>;
935
+ declare function rubricFor(archetype: string): string;
936
+ /** Render the golden IR's request for the judge (system sections + user turn). */
937
+ declare function renderIrForJudge(ir: PromptIR): string;
938
+ declare function buildPairwiseJudgePrompt(args: {
939
+ archetype: string;
940
+ renderedInput: string;
941
+ outputA: string;
942
+ outputB: string;
943
+ }): string;
944
+ type PairwiseWinner = 'A' | 'B' | 'tie';
945
+ /** Parse the judge's JSON verdict. Returns undefined when unparseable. */
946
+ declare function parseJudgeVerdict(raw: string): {
947
+ winner: PairwiseWinner;
948
+ rationale?: string;
949
+ } | undefined;
950
+ /**
951
+ * Combine the two order-swapped verdicts into a case verdict. Both verdicts
952
+ * are expressed in incumbent/candidate terms BEFORE this call (the caller
953
+ * un-swaps run 2). Agreement → that verdict; disagreement → 'tied' (positional
954
+ * noise reads as a tie, never as a win).
955
+ */
956
+ declare function combineOrderSwappedVerdicts(run1: 'candidate-better' | 'current-better' | 'tied', run2: 'candidate-better' | 'current-better' | 'tied'): 'candidate-better' | 'current-better' | 'tied';
957
+ /**
958
+ * Release B — the eval's comparison primitive is arm-agnostic: a MODEL
959
+ * comparison varies `model` and holds `ir`; a STRATEGY comparison varies
960
+ * `ir` and holds `model`. Same replay, same judge, same order-swap, same
961
+ * floors.
962
+ */
963
+ type GoldenEvalAxis = 'model' | 'strategy';
964
+ /** Strategies the eval can measure. Closed set — a strategy is only
965
+ * measurable against its exact frozen bytes. The `-alt` wording is
966
+ * EVAL-ONLY: it exists to attribute a v1 loss to wording vs mechanism
967
+ * (§6) and never ships in a production compile. */
968
+ type GoldenEvalStrategyId = 'discipline-gates-v1' | 'discipline-gates-v1-alt';
969
+ interface GoldenEvalOptions {
970
+ appId: string;
971
+ archetype: string;
972
+ /**
973
+ * Release B — comparison axis. Default 'model' (alpha.62 behavior,
974
+ * unchanged). On 'strategy': arm A = the golden IR as stored (gates-off),
975
+ * arm B = the same IR with a `discipline_contract` section appended
976
+ * (gates-on), both replayed on ONE model (`strategyModel` or the resolved
977
+ * incumbent). `candidateModel` is ignored on the strategy axis;
978
+ * `strategy` is required.
979
+ */
980
+ axis?: GoldenEvalAxis;
981
+ /** Required when axis==='strategy': the strategy under measurement. */
982
+ strategy?: GoldenEvalStrategyId;
983
+ /**
984
+ * axis==='strategy' only: the model both arms run on. Default: the
985
+ * resolved incumbent (most-captured model in the golden set).
986
+ */
987
+ strategyModel?: string;
988
+ /** Required when axis is 'model' (the default). */
989
+ candidateModel?: string;
990
+ /**
991
+ * Incumbent to compare against. Default: the most frequent incumbent_model
992
+ * across the loaded golden set (the surface's de-facto leader).
993
+ */
994
+ incumbentModel?: string;
995
+ /** Judge model id. Default 'claude-opus-4-8' (judge chain tier 0). */
996
+ judgeModel?: string;
997
+ /** Max golden cases to load (newest first). Default 50. */
998
+ limit?: number;
999
+ /** Non-inferiority threshold on wins-or-ties. Default 0.8. */
1000
+ winOrTieThreshold?: number;
1001
+ /** Latency hard floor: candidate p50 ≤ ratio × incumbent p50. Default 3. */
1002
+ latencyFloorRatio?: number;
1003
+ /** Minimum judged cases for a non-inconclusive verdict. Default 5. */
1004
+ minJudgeableCases?: number;
1005
+ /** What fired the eval. Default 'manual' (Stage 1). */
1006
+ triggerSource?: 'manual' | 'supply' | 'price' | 'demand';
1007
+ /** Brain access — direct PostgREST (operator convention). */
1008
+ supabaseUrl: string;
1009
+ serviceKey: string;
1010
+ /** Provider keys for the replay + judge calls. Default: process.env. */
1011
+ apiKeys?: ApiKeys;
1012
+ fetchImpl?: typeof fetch;
1013
+ /** Replay + judge but write NOTHING to the brain. */
1014
+ dryRun?: boolean;
1015
+ onProgress?: (message: string) => void;
1016
+ }
1017
+ interface GoldenEvalCase {
1018
+ goldenIrId: number;
1019
+ verdict: 'candidate-better' | 'tied' | 'current-better' | 'inconclusive';
1020
+ /**
1021
+ * Release B — the RAW order-swapped pair, in incumbent/candidate terms,
1022
+ * BEFORE `combineOrderSwappedVerdicts` folds disagreement into 'tied'.
1023
+ * The fold is public API and unchanged; this records what it discards,
1024
+ * because positional DISAGREEMENT RATE is an objective reliability metric
1025
+ * needing no ground truth (§4.0 — the strategy experiment's primary
1026
+ * metric is positional consistency, not judge quality).
1027
+ */
1028
+ orderVerdicts?: {
1029
+ run1: 'candidate-better' | 'current-better' | 'tied';
1030
+ run2: 'candidate-better' | 'current-better' | 'tied';
1031
+ };
1032
+ judgeRationale?: string;
1033
+ /** Hard-floor violations on the candidate side for this case. */
1034
+ floorViolations: Array<'empty' | 'schema' | 'candidate_error'>;
1035
+ errorClass?: string;
1036
+ incumbent?: {
1037
+ latencyMs: number;
1038
+ tokensIn: number;
1039
+ tokensOut: number;
1040
+ text: string;
1041
+ };
1042
+ candidate?: {
1043
+ latencyMs: number;
1044
+ tokensIn: number;
1045
+ tokensOut: number;
1046
+ text: string;
1047
+ };
1048
+ /** Case excluded from the denominator (incumbent replay/judge failed). */
1049
+ excludedReason?: string;
1050
+ }
1051
+ interface GoldenEvalRunResult {
1052
+ verdict: 'promote-ready' | 'not-inferior' | 'inconclusive';
1053
+ runId?: number;
1054
+ /**
1055
+ * Release B — which axis produced this verdict. Load-bearing, not
1056
+ * cosmetic: a results table that can't tell you which axis produced a
1057
+ * verdict is a false-attribution engine. On 'strategy',
1058
+ * incumbentModel === candidateModel (the model held constant) and
1059
+ * `strategy` names the arm-B mutation.
1060
+ */
1061
+ axis: GoldenEvalAxis;
1062
+ strategy?: GoldenEvalStrategyId;
1063
+ appId: string;
1064
+ archetype: string;
1065
+ incumbentModel: string;
1066
+ candidateModel: string;
1067
+ judgeModel: string;
1068
+ nCases: number;
1069
+ wins: number;
1070
+ ties: number;
1071
+ losses: number;
1072
+ floorViolations: number;
1073
+ floorDetail: Record<string, number>;
1074
+ winOrTieRatio: number | null;
1075
+ latencyRatio: number | null;
1076
+ costIncumbentUsd: number | null;
1077
+ costCandidateUsd: number | null;
1078
+ advisoryOutcomeId?: number;
1079
+ cases: GoldenEvalCase[];
1080
+ notes: string[];
1081
+ }
1082
+ declare function withDisciplineContract(ir: PromptIR): PromptIR;
1083
+ declare const DISCIPLINE_GATES_V1_ALT_HEADER = "Before stating any conclusion, run this check:";
1084
+ declare function altGatesBlockFor(args: {
1085
+ outputMode: 'text' | 'json' | 'tool_call';
1086
+ hasTools: boolean;
1087
+ }): string;
1088
+ /**
1089
+ * The alt arm injects its block DIRECTLY as an untagged section — it must
1090
+ * not carry `kind: 'discipline_contract'`, or the translator would prepend
1091
+ * the v1 bytes on top and the arm would measure both wordings at once. The
1092
+ * variant choice mirrors matchRule()'s exactly (same outputMode + hasTools
1093
+ * inputs), so the alt arm no-ops nowhere v1 fires and fires nowhere v1
1094
+ * no-ops — the attribution is about WORDING, and everything else is held.
1095
+ */
1096
+ declare function withAltDisciplineContract(ir: PromptIR): PromptIR;
1097
+ declare function runGoldenEval(opts: GoldenEvalOptions): Promise<GoldenEvalRunResult>;
1098
+ /**
1099
+ * Aggregate outcome of one strategy run, in gates-on terms. 'loses' is the
1100
+ * only branch that costs a third replay — and the only one where wording
1101
+ * attribution matters.
1102
+ */
1103
+ type StrategyOutcome = 'wins' | 'ties' | 'loses' | 'inconclusive';
1104
+ declare function classifyStrategyOutcome(r: GoldenEvalRunResult): StrategyOutcome;
1105
+ /**
1106
+ * The §6 attribution matrix. The load-bearing distinction: a WORDING failure
1107
+ * recorded as a mechanism failure would let Factor B permanently disable a
1108
+ * real capability on evidence about one author's prose.
1109
+ *
1110
+ * v1 vs off | alt vs off | attribution
1111
+ * ----------+------------+----------------------------------------------
1112
+ * wins | (not run) | mechanism-works — ship
1113
+ * ties | (not run) | no-lift — inconclusive at this n, re-eval later
1114
+ * loses | wins | wording-failure — do NOT disable the mechanism
1115
+ * loses | loses | mechanism-failure — well-evidenced; Factor B may disable
1116
+ * loses | ties/inc. | wording-inconclusive — no disable on ambiguity
1117
+ */
1118
+ type StrategyAttribution = 'mechanism-works' | 'no-lift' | 'wording-failure' | 'mechanism-failure' | 'wording-inconclusive' | 'inconclusive';
1119
+ interface StrategyAttributionResult {
1120
+ attribution: StrategyAttribution;
1121
+ primary: GoldenEvalRunResult;
1122
+ /** Present ONLY when the primary lost (the loss-triggered third arm). */
1123
+ alt?: GoldenEvalRunResult;
1124
+ /** The authorship limitation, restated on every result so no downstream
1125
+ * reader can cite an attribution without it. */
1126
+ limitation: string;
172
1127
  }
1128
+ declare const STRATEGY_AUTHORSHIP_LIMITATION: string;
1129
+ /**
1130
+ * Run the strategy eval with loss-triggered wording attribution: v1 first;
1131
+ * the alt arm replays ONLY on a v1 loss (mirrors the engine's retry
1132
+ * posture — don't pay for extra evidence until a result demands it).
1133
+ */
1134
+ declare function runStrategyEvalWithAttribution(opts: Omit<GoldenEvalOptions, 'axis' | 'strategy' | 'candidateModel'>): Promise<StrategyAttributionResult>;
1135
+
1136
+ /**
1137
+ * alpha.60 — the library's own version, baked as a constant so Edge/Worker
1138
+ * runtimes (no fs, no require) can report it on wire surfaces. First
1139
+ * consumer: `createKeyHealthRoute` carries it as `library_version`, which is
1140
+ * how the operator dashboard's Fleet panel sees per-consumer vendor drift
1141
+ * LIVE instead of via wrap-time package.json probes (the L-093 family
1142
+ * "declared state lags actual" fix at the vendor-version axis — s47 found
1143
+ * IC 13 alphas stale that way).
1144
+ *
1145
+ * Kept in sync with package.json by hand at each version bump; the drift
1146
+ * guard in `tests/version.test.ts` fails the suite (and therefore
1147
+ * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
1148
+ */
1149
+ declare const LIBRARY_VERSION = "2.0.0-alpha.80";
173
1150
 
174
1151
  /**
175
1152
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -222,6 +1199,34 @@ interface LLMJudgeOptions {
222
1199
  */
223
1200
  declare function buildLLMJudge(opts: LLMJudgeOptions): AppOracle;
224
1201
 
1202
+ /**
1203
+ * Resolve the effective ArchetypeConvention[] for a given selected profile,
1204
+ * walking family inheritance once. Model-specific entries on the selected
1205
+ * profile take precedence over family-level entries for the same archetype.
1206
+ *
1207
+ * Pure; safe to call from any context (probe-watcher uses the same logic
1208
+ * via `applyArchetypeConvention`).
1209
+ */
1210
+ declare function resolveConventionsForProfile(profile: ModelProfile): ArchetypeConvention[];
1211
+ /**
1212
+ * Pure helper: apply the matching ArchetypeConvention's suffix (and
1213
+ * prefix, when meaningful) to a plain prompt-text string. Used by the
1214
+ * exclusion-probe-watcher (`probeOne`) so probe calls carry the same
1215
+ * forcing-function shape consumers see at compile time. Without this,
1216
+ * every reasoner probe on a decisive archetype gets unfairly stay-excluded
1217
+ * for hedging — as ID 20 demonstrated on 2026-05-28.
1218
+ *
1219
+ * Resolution: looks up the family-rep profile for `family` and reads its
1220
+ * `archetypeConventions`. Returns the original text unchanged when no
1221
+ * convention matches or when the suffix is already present.
1222
+ *
1223
+ * @param promptText raw user-prompt text (or prompt_preview from outcome)
1224
+ * @param archetype intent_archetype from the finding row
1225
+ * @param family family tag from deriveFamilyFromModelId / brain row
1226
+ * @returns text with prefix/suffix applied (idempotent)
1227
+ */
1228
+ declare function applyArchetypeConvention(promptText: string, archetype: string, family: string): string;
1229
+
225
1230
  /**
226
1231
  * Tokenizer abstraction.
227
1232
  *
@@ -245,6 +1250,224 @@ declare function resetTokenizer(): void;
245
1250
  */
246
1251
  declare function countTokens(text: string): number;
247
1252
 
1253
+ /**
1254
+ * delegate — Release D, the R2 primitive (delegation-fanout accelerator §5.2,
1255
+ * design contract advisory/kgauto/2026-07-24_delegation-fanout-accelerator-design.md).
1256
+ *
1257
+ * A consumer-mountable TOOL the orchestrating model calls mid-loop:
1258
+ * `{ sub_archetype, input, quality_floor? }`. kgauto selects the executor
1259
+ * from evidence, runs the sub-call through the compiler + call(), returns
1260
+ * the result into the loop, links parent↔child rows (R0), and enforces
1261
+ * `policy.maxCostPerTraceUsd` against the running trace spend — the field
1262
+ * that shipped INERT in Release A precisely so this release could turn it on.
1263
+ *
1264
+ * THE AUTHORITY SPLIT IS THE CONTAINMENT (§3):
1265
+ * - the MODEL decides whether and what to delegate (kgauto never
1266
+ * decomposes uninvited — §10);
1267
+ * - KGAUTO decides only who runs it — and never selects a model absent
1268
+ * from the consumer's declared `ir.models`;
1269
+ * - the CONSUMER consents: default OFF, `KGAUTO_AUTO_PROMOTE` posture
1270
+ * (explicit option beats `KGAUTO_DELEGATE` env; neither ⇒ the handler
1271
+ * refuses observably, never silently).
1272
+ *
1273
+ * Budget refusals and floor refusals are RETURNED to the model as
1274
+ * structured tool results, never thrown — the orchestrator must be able to
1275
+ * compose with what it has (a refusal mid-loop that crashes the loop would
1276
+ * convert a budget into an outage).
1277
+ *
1278
+ * Composition-verification (§7a): every sub-result is 'trusted' until the
1279
+ * orchestrator/consumer reports otherwise via `reportComposition` —
1280
+ * absence-of-report IS the recorded state (migration 052). Rung 3 reads
1281
+ * this to attribute composition failures to stitching, not executor choice.
1282
+ *
1283
+ * Trace-budget honesty (v1 limits, stated where consumers read):
1284
+ * - the in-process ledger sums DELEGATED spend for this trace (parent's
1285
+ * own root-call spend is not visible to a library ledger until a
1286
+ * brain-informed ledger lands; documented on `maxCostPerTraceUsd`);
1287
+ * - enforcement is estimate-ahead: a sub-call whose compile-time estimate
1288
+ * would cross the ceiling is refused BEFORE any spend;
1289
+ * - realized spend is computed from actual tokens × the executor
1290
+ * profile's prices after each sub-call.
1291
+ */
1292
+
1293
+ declare function isDelegateEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
1294
+ /** Arguments the ORCHESTRATING MODEL supplies when it calls the tool. */
1295
+ interface DelegateToolArgs {
1296
+ /** The sub-task's archetype — its own learning_key downstream. */
1297
+ sub_archetype: IntentArchetypeName | string;
1298
+ /** Complete, self-contained sub-task input. The model owns fidelity here
1299
+ * (authority split): kgauto runs exactly what it is handed. */
1300
+ input: string;
1301
+ /**
1302
+ * Minimum archetype-perf score (0..10) the executor must carry for this
1303
+ * sub-archetype. Candidates below the floor are excluded BEFORE ranking;
1304
+ * if nothing in the parent's declared pool clears it, the tool refuses
1305
+ * with the scores so the model can lower the floor or do the work itself.
1306
+ */
1307
+ quality_floor?: number;
1308
+ }
1309
+ type DelegateRefusalReason = 'delegate_not_enabled' | 'invalid_sub_archetype' | 'no_qualified_executor' | 'trace_budget_exhausted' | 'call_failed';
1310
+ type DelegateResult = {
1311
+ ok: true;
1312
+ /** The sub-result text (or serialized structured output). */
1313
+ output: string;
1314
+ /** Branch handle — pass to reportComposition; joins the brain row. */
1315
+ subHandle: string;
1316
+ executorModel: string;
1317
+ costUsd: number;
1318
+ latencyMs: number;
1319
+ /** Always 'trusted' at return time — flips only via reportComposition. */
1320
+ verification: 'trusted';
1321
+ } | {
1322
+ ok: false;
1323
+ reason: DelegateRefusalReason;
1324
+ /** Human/model-readable detail — written to be COMPOSABLE (“continue
1325
+ * without this sub-result”), never a stack trace. */
1326
+ detail: string;
1327
+ };
1328
+ /**
1329
+ * Provider-agnostic tool definition. Consumers adapt `inputSchema` to their
1330
+ * SDK's tool shape (AI-SDK `parameters`, Anthropic `input_schema`, …). The
1331
+ * description IS prompt surface — it teaches the model the authority split
1332
+ * and the compose-on-refusal discipline (gates 4/5 of discipline-gates-v1
1333
+ * in tool-description form).
1334
+ */
1335
+ declare const DELEGATE_TOOL_DEFINITION: {
1336
+ readonly name: "delegate";
1337
+ readonly description: string;
1338
+ readonly inputSchema: {
1339
+ readonly type: "object";
1340
+ readonly properties: {
1341
+ readonly sub_archetype: {
1342
+ readonly type: "string";
1343
+ readonly enum: ("ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform" | "judge")[];
1344
+ readonly description: "What kind of work the sub-task is (its routing archetype).";
1345
+ };
1346
+ readonly input: {
1347
+ readonly type: "string";
1348
+ readonly description: "Complete, self-contained sub-task input. Include everything the executor needs — it sees nothing else.";
1349
+ };
1350
+ readonly quality_floor: {
1351
+ readonly type: "number";
1352
+ readonly minimum: 0;
1353
+ readonly maximum: 10;
1354
+ readonly description: "Optional minimum executor quality score (0-10) for this archetype. Omit to accept the evidence-ranked default.";
1355
+ };
1356
+ };
1357
+ readonly required: readonly ["sub_archetype", "input"];
1358
+ readonly additionalProperties: false;
1359
+ };
1360
+ };
1361
+ interface CreateDelegateOpts {
1362
+ /** The PARENT call's IR — supplies the declared model pool (the containment
1363
+ * boundary), appId, and dialect context. */
1364
+ parentIr: PromptIR;
1365
+ /** The parent's compile/call handle — R0 linkage root. Branch rows record
1366
+ * `parent_handle=<this>` and inherit `trace_id`. */
1367
+ parentHandle: string;
1368
+ /**
1369
+ * Options forwarded to the sub-`call()` (apiKeys, fetchImpl,
1370
+ * attemptTimeoutMs, policy…). `policy.maxCostPerTraceUsd` here is what the
1371
+ * ledger enforces. `parentHandle` is set by the factory — a value passed
1372
+ * in callOpts is overridden.
1373
+ */
1374
+ callOpts?: CallOptions & {
1375
+ policy?: CompilePolicy;
1376
+ };
1377
+ /** Explicit consent — beats KGAUTO_DELEGATE env (AUTO_PROMOTE posture). */
1378
+ enabled?: boolean;
1379
+ }
1380
+ interface DelegateHandle {
1381
+ toolDefinition: typeof DELEGATE_TOOL_DEFINITION;
1382
+ handler: (args: DelegateToolArgs) => Promise<DelegateResult>;
1383
+ /**
1384
+ * §7a — report what the orchestrator did with a sub-result. Writes a
1385
+ * migration-052 row via the brain-read env trio (RLS-scoped to appId).
1386
+ * Unreported sub-results are 'trusted' by definition — report only
1387
+ * 'verified' and 'discarded'.
1388
+ */
1389
+ reportComposition: (report: {
1390
+ subHandle: string;
1391
+ disposition: 'verified' | 'discarded';
1392
+ note?: string;
1393
+ }) => Promise<{
1394
+ ok: boolean;
1395
+ reason?: string;
1396
+ }>;
1397
+ /** Ledger introspection: delegated spend recorded for this trace so far. */
1398
+ traceSpendUsd: () => number;
1399
+ }
1400
+ declare function createDelegate(opts: CreateDelegateOpts): DelegateHandle;
1401
+
1402
+ /**
1403
+ * archetype-fits — alpha.43.
1404
+ *
1405
+ * Static table of "this archetype tends to be a better fit for this family"
1406
+ * recommendations. Powers the `cross-family-fit-candidate` compile-time
1407
+ * advisor (see `advisor-rules/cross-family-fit.ts`).
1408
+ *
1409
+ * Strategic framing (Sacha, 2026-05-28): "If we get better results and
1410
+ * better price then we do. Even if volume is currently low, that's not an
1411
+ * argument to not do it. Volume can increase quickly if tools is great to
1412
+ * use, let's not create future bottlenecks because we could have wired in
1413
+ * better solution at moment of knowing."
1414
+ *
1415
+ * The convention substrate (passApplyConventions) is the NEGATIVE side:
1416
+ * make a family usable on archetypes it currently fails. This table is the
1417
+ * POSITIVE side: actively surface that a different family is the better
1418
+ * fit for the archetype's shape — even when current volume is low.
1419
+ *
1420
+ * Entries are added only when:
1421
+ * - the archetype's shape and the family's behavior have a clear
1422
+ * architectural fit (not vibes)
1423
+ * - real-world evidence (brain rows, probe outcomes, or published
1424
+ * benchmark) backs the claim, OR the reasoning is structurally so clear
1425
+ * that "wait for volume" would create a future bottleneck
1426
+ *
1427
+ * Alpha.43 ships two entries — `plan` and `critique`. Both fit the
1428
+ * reasoner-family architectural read: plan is multi-step reasoning;
1429
+ * critique rewards epistemic humility and explicit reasoning. Other
1430
+ * archetype-family-fits ride later alphas as evidence accumulates.
1431
+ *
1432
+ * Anti-pattern: do NOT add archetype-family-fits for archetypes where the
1433
+ * fit is unclear (summarize, classify, extract, hunt with parallel tools).
1434
+ * The advisor only earns trust when its recommendations land.
1435
+ */
1436
+
1437
+ /**
1438
+ * One archetype-family-fit recommendation. Read by the compile-time
1439
+ * `cross-family-fit-candidate` advisor to decide when to surface a positive
1440
+ * recommendation. The advisor pulls `costGuidance` verbatim into the
1441
+ * advisory message.
1442
+ */
1443
+ interface ArchetypeFamilyFit {
1444
+ /** Intent archetype this fit applies to. */
1445
+ archetype: IntentArchetypeName;
1446
+ /** Family tag that fits the archetype better than alternatives. Matches the
1447
+ * same family taxonomy used by `family-resolution.deriveFamilyFromModelId`
1448
+ * (e.g. `'deepseek-reasoner'`, `'gemini-flash'`, `'claude-opus'`). */
1449
+ betterFitFamily: string;
1450
+ /** Architectural / evidentiary justification. Appears in the advisor's
1451
+ * internal logs and the advisory `evidence` payload, NOT verbatim in the
1452
+ * consumer-facing message. */
1453
+ reason: string;
1454
+ /** Cost-context clause surfaced VERBATIM in the consumer-facing advisory
1455
+ * message (e.g. "substantially cheaper at current pricing"). Keep
1456
+ * declarative; the advisor wraps this into the larger sentence. */
1457
+ costGuidance: string;
1458
+ }
1459
+ /**
1460
+ * Frozen registry. Add entries by extending the array. Order is irrelevant
1461
+ * — the advisor filters by `(archetype, currentFamily)` independently.
1462
+ */
1463
+ declare const ARCHETYPE_FAMILY_FITS: readonly ArchetypeFamilyFit[];
1464
+ /**
1465
+ * Pure lookup: does `(archetype, currentFamily)` have a better-fit family?
1466
+ * Returns the fit entry when the current family is NOT the better fit; null
1467
+ * otherwise. Used by the advisor to decide whether to fire.
1468
+ */
1469
+ declare function findBetterFit(archetype: string, currentFamily: string): ArchetypeFamilyFit | null;
1470
+
248
1471
  /**
249
1472
  * Best-practice advisor — alpha.6 Phase 1.
250
1473
  *
@@ -275,10 +1498,2215 @@ declare function countTokens(text: string): number;
275
1498
  /** Subset of CompileResult fields the advisor needs. */
276
1499
  type AdvisorContext = Pick<CompileResult, 'target' | 'provider' | 'tokensIn' | 'diagnostics'>;
277
1500
  /**
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.
1501
+ * Optional Phase 2 (alpha.22) context fallback chain + a profile resolver
1502
+ * for cross-model comparison. Three new rules
1503
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) consume
1504
+ * this to surface measurement-substrate signals (alpha.20 clean-attribution +
1505
+ * alpha.21 grounding labels) as actionable consumer guidance.
1506
+ *
1507
+ * When `fallbackChain` is empty, rules 1 + 3 stay silent (nothing to
1508
+ * compare against). When `profileResolver` is omitted, the rules degrade
1509
+ * gracefully — they can still inspect the chosen profile but not chain
1510
+ * alternatives. Rule 2 (`model-stale-evidence`) is independent of chain
1511
+ * shape and works on the chosen model alone.
1512
+ */
1513
+ interface RunAdvisorPhase2Context {
1514
+ fallbackChain: string[];
1515
+ profileResolver?: (id: string) => ModelProfile | undefined;
1516
+ /**
1517
+ * alpha.29 — translator rewrites that fired this compile. When a rewrite
1518
+ * cleared the cliff (e.g. `tool_call_contract` → sequential-tool preamble
1519
+ * + `parallelToolCalls: false`), the matching cliff advisor
1520
+ * (`archetype-perf-floor-breach`) MUST suppress for the same call. Without
1521
+ * suppression both fire — the advisory contradicts the rewrite ("cliff is
1522
+ * unaddressed" vs "we just addressed it").
1523
+ *
1524
+ * Empty array / undefined → no suppression (alpha.28 behavior preserved).
1525
+ */
1526
+ sectionRewritesApplied?: SectionRewrite[];
1527
+ }
1528
+ /**
1529
+ * alpha.42 — rule codes whose advisories are positioned for kgauto (not
1530
+ * the consumer) to act on. Used by `compile()` to default the `ownership`
1531
+ * stamp on each advisory when the rule didn't self-declare. Consumer-side
1532
+ * rules don't need to be listed — they default to `'consumer-actionable'`
1533
+ * via fall-through.
1534
+ *
1535
+ * - `model-stale-evidence`: kgauto's profile data is out of date; the
1536
+ * consumer can't fix that, kgauto needs to update profiles or refresh
1537
+ * archetypePerf scores.
1538
+ * - `promote-ready`: kgauto's promotion-probe-watcher detected a
1539
+ * candidate model worth promoting; consumer-side adoption is downstream
1540
+ * of kgauto adding it to the chain / family taxonomy.
1541
+ *
1542
+ * Frozen so consumers and tests can't mutate the global ownership map.
280
1543
  */
281
- declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile): BestPracticeAdvisory[];
1544
+ declare const PRODUCER_OWNED_RULE_CODES: ReadonlySet<string>;
1545
+ /**
1546
+ * alpha.42 — pure function used by `compile()` to decide ownership for an
1547
+ * advisory. Rule-self-declared wins; falls back to the static map; defaults
1548
+ * `consumer-actionable`. Exported so consumer-side code (or a Glass-Box
1549
+ * renderer) can derive the same classification from a rule code alone
1550
+ * without needing the advisory object.
1551
+ */
1552
+ declare function deriveOwnership(code: string, selfDeclared?: 'consumer-actionable' | 'producer-owned'): 'consumer-actionable' | 'producer-owned';
1553
+ /**
1554
+ * Run all phased rules and return collected advisories. Order is fixed so
1555
+ * output is stable across runs. The `policy` argument is alpha.9 — the
1556
+ * `single-model-array` rule needs to know whether the consumer explicitly
1557
+ * declared `posture: 'locked'` (in which case single-model is intentional
1558
+ * and shouldn't warn).
1559
+ *
1560
+ * `phase2` is alpha.22 — gives the advisor access to the fallback chain +
1561
+ * a profile resolver so the three new compile-time recommendation rules
1562
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) can
1563
+ * compare the chosen model against in-chain alternatives. Optional for
1564
+ * backward compatibility with consumers calling `runAdvisor()` directly.
1565
+ */
1566
+ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile, policy?: CompilePolicy, phase2?: RunAdvisorPhase2Context): BestPracticeAdvisory[];
1567
+
1568
+ /**
1569
+ * Translator primitive — alpha.31.
1570
+ *
1571
+ * Pure function. Walks `IR.sections`, matches each section's `kind` against
1572
+ * a per-rule dispatch table keyed on (kind, profile, archetype), and applies
1573
+ * a model-aware rewrite when a rule fires. Returns the rewritten IR + the
1574
+ * list of rewrites for `CompileResult.sectionRewritesApplied` and brain
1575
+ * persistence.
1576
+ *
1577
+ * This is the s37 translator-framing eureka in code: kgauto graduates from
1578
+ * "gate" (alpha.28's cliff advisor: "consumer must accept adapter") to
1579
+ * "translator" (alpha.29: "consumer declared the section kind, kgauto
1580
+ * applies the adapter at compile time without consumer-side branching").
1581
+ *
1582
+ * Rules shipped:
1583
+ *
1584
+ * alpha.29 — tool_call_contract + archetypePerf[archetype] < TRANSLATOR_FLOOR
1585
+ * → prepend sequential-tool-pattern guidance
1586
+ * → emit wireOverrides: { parallelToolCalls: false }
1587
+ * → rule_id: 'sequential-tool-cliff-below-floor'
1588
+ *
1589
+ * alpha.31 — narration_contract + profile.provider === 'anthropic'
1590
+ * → prepend terse-log narration guidance
1591
+ * → no wireOverrides
1592
+ * → rule_id: 'narration-drift-anthropic'
1593
+ *
1594
+ * alpha.31 — narration_contract + profile.provider === 'deepseek'
1595
+ * → prepend <thinking>-suppression guidance
1596
+ * → no wireOverrides
1597
+ * → rule_id: 'narration-thinking-leak-deepseek'
1598
+ *
1599
+ * Per-rule walk (alpha.31 refactor): the alpha.30 short-circuit
1600
+ * `if (!cliffFires) return passthrough` was correct when only the
1601
+ * cliff-gated tool_call_contract rule existed; alpha.31's narration rules
1602
+ * fire on every call regardless of cliff (narration drift is steady-state,
1603
+ * not a cliff condition). Each section now consults the dispatch table
1604
+ * independently — first-match wins per (section.kind, profile, archetype).
1605
+ *
1606
+ * **Interaction with the cliff advisor (alpha.28):** when this translator
1607
+ * fires for a `tool_call_contract` section, the advisor's
1608
+ * `archetype-perf-floor-breach` rule MUST suppress for the same call — the
1609
+ * cliff was structurally cleared by the rewrite, not unaddressed. The
1610
+ * suppression check lives in `advisor.ts` and consults the
1611
+ * `CompileResult.sectionRewritesApplied` list.
1612
+ *
1613
+ * Design contracts:
1614
+ * command-center/advisory/kgauto/2026-05-21_alpha-29-translator-and-advisories-api.md
1615
+ * command-center/advisory/kgauto/2026-05-22_alpha-31-narration-contract.md
1616
+ */
1617
+
1618
+ /**
1619
+ * Re-export of `ARCHETYPE_FLOOR_DEFAULT` as the canonical "translator fires
1620
+ * below this score" threshold. Same constant as the cliff advisor — the
1621
+ * single threshold is shared (alpha.28's "below this, advisor warns"; alpha.29's
1622
+ * "below this, translator AUTO-APPLIES the adapter").
1623
+ */
1624
+ declare const TRANSLATOR_FLOOR = 6;
1625
+ /**
1626
+ * Stable identifier of the alpha.29 sequential-tool rule. Surfaces on
1627
+ * `SectionRewrite.rule` and in brain aggregates. The brain treats this
1628
+ * identifier together with the preamble string as the rule's wire
1629
+ * fingerprint — both stay byte-stable across releases.
1630
+ */
1631
+ declare const RULE_SEQUENTIAL_TOOL_CLIFF = "sequential-tool-cliff-below-floor";
1632
+ /**
1633
+ * alpha.68 / Release A — stable identifier of the discipline-gates rule.
1634
+ * Fires on `discipline_contract` sections that pass the two-factor eligibility
1635
+ * screen (Factor A archetype + Factor C output-shape). Surfaces on
1636
+ * `SectionRewrite.rule` and in brain aggregates.
1637
+ *
1638
+ * Versioned (`v1`) deliberately: Factor B evidence (Release B) is only valid
1639
+ * against the EXACT bytes that produced it, so a silent gate edit would
1640
+ * invalidate every standing verdict. A real gate change bumps this to `v2` and
1641
+ * resets Factor B to unmeasured for every tuple.
1642
+ */
1643
+ declare const RULE_DISCIPLINE_GATES_V1 = "discipline-gates-v1";
1644
+ /**
1645
+ * Release B — stable identifier of the STRUCTURED-SAFE discipline-gates
1646
+ * variant (design contract §5.D second clause, discharged via §4.0's merge:
1647
+ * "the judge must run gates 1–4 only — which IS Path 1's structured-safe
1648
+ * variant, arrived at as a subset-drop of frozen bytes rather than new
1649
+ * prose"). Fires where the full block is Factor-C-forbidden: `json` and
1650
+ * `tool_call` surfaces, where gates 5+6 are shape-altering and would
1651
+ * manufacture the structured-output violations alpha.66 retries.
1652
+ *
1653
+ * Versioned with the SAME v1 stamp as its parent: its bytes are a strict
1654
+ * subset of `discipline-gates-v1`'s, so a v1 wording change is a variant
1655
+ * wording change by construction, and both bump together.
1656
+ */
1657
+ declare const RULE_DISCIPLINE_GATES_V1_STRUCTURED = "discipline-gates-v1-structured";
1658
+ interface ApplySectionRewritesArgs {
1659
+ ir: PromptIR;
1660
+ profile: ModelProfile;
1661
+ archetype: IntentArchetypeName;
1662
+ /**
1663
+ * alpha.68 / Release A — resolved output shape for Factor C (§5.D). `'json'`
1664
+ * ⇒ structured surface (the discipline gate MUST NOT fire — gates 5+6 are
1665
+ * shape-altering and would break the consumer's parser). `'text'` ⇒ free-form
1666
+ * surface (the gate may fire). Optional: when omitted, derived from
1667
+ * `ir.constraints?.structuredOutput` (true ⇒ 'json', else 'text') so callers
1668
+ * / tests need not pass it. compile() passes it explicitly.
1669
+ */
1670
+ outputMode?: OutputMode;
1671
+ }
1672
+ interface ApplySectionRewritesResult {
1673
+ /**
1674
+ * IR with section.text fields possibly rewritten. When no rewrites fired,
1675
+ * this is identical to the input IR (referentially distinct array but
1676
+ * same section payloads).
1677
+ */
1678
+ rewrittenIR: PromptIR;
1679
+ /**
1680
+ * One entry per section the translator rewrote. Empty array when no
1681
+ * rules fired. Order matches the corresponding section in
1682
+ * `rewrittenIR.sections`.
1683
+ */
1684
+ rewrites: SectionRewrite[];
1685
+ }
1686
+ /**
1687
+ * Pure function. Apply model-aware section rewrites to the IR at compile time.
1688
+ *
1689
+ * Discipline:
1690
+ * - Never mutates the input IR; returns a new IR with new sections array
1691
+ * when at least one rewrite fired; otherwise returns the input IR by
1692
+ * reference (referential identity preserved on no-op).
1693
+ * - Sections without a `kind` (or `kind === 'arbitrary'`) pass through
1694
+ * unchanged.
1695
+ * - Empty `sections` array → returns `{ rewrittenIR: ir, rewrites: [] }`.
1696
+ * - Sections of the same `kind` are processed in array order; first-match
1697
+ * wins per section. (Today every rule is a single-match rule.)
1698
+ *
1699
+ * @example
1700
+ * ```ts
1701
+ * import { applySectionRewrites } from '@warmdrift/kgauto-compiler';
1702
+ * import { getProfile } from '@warmdrift/kgauto-compiler';
1703
+ *
1704
+ * const { rewrittenIR, rewrites } = applySectionRewrites({
1705
+ * ir,
1706
+ * profile: getProfile('deepseek-v4-pro'),
1707
+ * archetype: 'hunt',
1708
+ * });
1709
+ * if (rewrites.length > 0) console.log('translator fired:', rewrites);
1710
+ * ```
1711
+ */
1712
+ declare function applySectionRewrites(args: ApplySectionRewritesArgs): ApplySectionRewritesResult;
1713
+
1714
+ /**
1715
+ * advisories-api — structured advisories API (alpha.29 Workstream B).
1716
+ *
1717
+ * Closes the L-117 family bottleneck: kgauto's `result.advisories[]` (the
1718
+ * compile-time warnings about caching-off, tool-bloat, archetype-perf-floor
1719
+ * breaches, etc.) used to disappear after the consumer read the compile
1720
+ * result. The s34 caching-off advisory pattern is the canonical failure: an
1721
+ * advisory fired 100+ times in 24h on `generate::sonnet` at 99.4% empty
1722
+ * rate, and nobody knew because there was no structured channel to surface
1723
+ * "what's open right now?"
1724
+ *
1725
+ * Migration 020 ships the substrate: `compile_outcome_advisories` gains
1726
+ * lifecycle columns (`resolved_at`, `resolution_source`, `resolution_note`)
1727
+ * and the `actionable_advisories_v` view rolls per-firing rows into
1728
+ * per-(app_id, code) tuples with deterministic stable ids + server-side
1729
+ * auto-resolution.
1730
+ *
1731
+ * Public surface:
1732
+ * getActionableAdvisories({ appId, severity?, status?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1733
+ * → Promise<ActionableAdvisory[]>
1734
+ *
1735
+ * markAdvisoryResolved({ id, resolutionNote?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1736
+ * → Promise<{ ok: true } | { ok: false; reason: string }>
1737
+ *
1738
+ * Both functions are pure I/O — no module-level state. The fetch wiring
1739
+ * mirrors `createProxyHandler` in `glassbox-routes/proxy.ts`: scoped JWT in
1740
+ * `Authorization: Bearer`, `apikey` header carries the anon key.
1741
+ *
1742
+ * The auto-resolution rule is enforced server-side in `actionable_advisories_v`:
1743
+ * • Latest firing > 14 days ago → status='resolved' (auto-pruned)
1744
+ * • All firings have resolved_at set → status='resolved' (consumer-marked)
1745
+ * • Otherwise → status='open'
1746
+ *
1747
+ * `markAdvisoryResolved` is the consumer override: "I fixed it; the next
1748
+ * firing will reopen the rule, but until then it stays resolved."
1749
+ */
1750
+
1751
+ /**
1752
+ * Severity of an advisory. Maps to the `level` column on
1753
+ * `compile_outcome_advisories` (info | warn | critical).
1754
+ */
1755
+ type AdvisorySeverity = 'info' | 'warn' | 'critical';
1756
+ /**
1757
+ * Status of an advisory rollup.
1758
+ *
1759
+ * - `open` — at least one unresolved firing in the last 14 days
1760
+ * - `resolved` — either auto-pruned (no firings >14d) or consumer-marked
1761
+ * - `snoozed` — reserved for alpha.30+ (snooze-until-date); type-accepted
1762
+ * today but the view will never emit this value
1763
+ */
1764
+ type AdvisoryStatus = 'open' | 'snoozed' | 'resolved';
1765
+ /**
1766
+ * Source of resolution when status='resolved'.
1767
+ *
1768
+ * - `auto` — server-side rule auto-pruned (>14d since last firing)
1769
+ * - `consumer-marked` — consumer called `markAdvisoryResolved`
1770
+ * - `declined` — reserved (alpha.30+: consumer marked the suggestion
1771
+ * inapplicable; the advisor will still fire but UIs can hide it)
1772
+ */
1773
+ type AdvisoryResolutionSource = 'auto' | 'consumer-marked' | 'declined';
1774
+ /**
1775
+ * Suggested-fix metadata. `null` when the advisor has no actionable fix
1776
+ * (info-level rules can be observational). When set, the consumer's
1777
+ * Admin UI can render a one-click apply (alpha.30+) or surface the
1778
+ * before/after diff inline.
1779
+ */
1780
+ interface AdvisorySuggestedFix {
1781
+ type: 'config-change' | 'one-liner' | 'env-var' | 'manual';
1782
+ /** File:line hint if kgauto can infer (reserved — alpha.30+). */
1783
+ siteHint?: string;
1784
+ before?: string;
1785
+ after?: string;
1786
+ docsLink?: string;
1787
+ }
1788
+ /**
1789
+ * Per-(app_id, code) advisory rollup. The `id` is stable across polls
1790
+ * until the rule auto-resolves and re-opens (a new firing after the 14d
1791
+ * boundary advances `opened_at` → new id). Treat id-changes as
1792
+ * intentional "fresh re-open" signals.
1793
+ *
1794
+ * Wire-shape from `actionable_advisories_v`. The transformer maps the
1795
+ * view's snake_case columns to camelCase. See `feedback_typed_boundary_transformers.md`
1796
+ * (L-118) for the rationale.
1797
+ */
1798
+ interface ActionableAdvisory {
1799
+ id: string;
1800
+ rule: string;
1801
+ severity: AdvisorySeverity;
1802
+ openedAt: string;
1803
+ lastObservedAt: string;
1804
+ observationCount: number;
1805
+ appliesTo: {
1806
+ archetype?: IntentArchetypeName;
1807
+ model?: string;
1808
+ callSiteHint?: string;
1809
+ };
1810
+ message: string;
1811
+ suggestedFix: AdvisorySuggestedFix | null;
1812
+ /** Reserved — always `false` in alpha.29. alpha.30+ ships actual auto-apply. */
1813
+ autoApplicable: boolean;
1814
+ status: AdvisoryStatus;
1815
+ resolvedAt?: string;
1816
+ resolutionSource?: AdvisoryResolutionSource;
1817
+ resolutionNote?: string;
1818
+ }
1819
+ /**
1820
+ * Filter + transport for `getActionableAdvisories`. The brain JWT must
1821
+ * carry an `app_id` claim matching `opts.appId` — RLS enforces tenant
1822
+ * isolation on the underlying table, so a mismatch silently returns [].
1823
+ */
1824
+ interface GetActionableAdvisoriesOptions {
1825
+ appId: string;
1826
+ /** Severity filter; if omitted, all severities are returned. */
1827
+ severity?: AdvisorySeverity;
1828
+ /** Status filter; defaults to 'open'. Pass 'all' for the full set. */
1829
+ status?: 'open' | 'snoozed' | 'resolved' | 'all';
1830
+ /**
1831
+ * alpha.78 (PB adoption-gap ask 2): the trio now DEFAULTS from
1832
+ * `readBrainReadEnv()` when omitted, so a consumer that passes nothing
1833
+ * gets correct behavior from the canonical env names instead of a
1834
+ * self-authored config error. Explicit values still win.
1835
+ */
1836
+ brainEndpoint?: string;
1837
+ brainJwt?: string;
1838
+ brainAnonKey?: string;
1839
+ fetch?: typeof fetch;
1840
+ }
1841
+ interface MarkAdvisoryResolvedOptions {
1842
+ /** Stable id from a prior `getActionableAdvisories` call. */
1843
+ id: string;
1844
+ resolutionNote?: string;
1845
+ /**
1846
+ * alpha.78 (PB adoption-gap ask 2): the trio now DEFAULTS from
1847
+ * `readBrainReadEnv()` when omitted, so a consumer that passes nothing
1848
+ * gets correct behavior from the canonical env names instead of a
1849
+ * self-authored config error. Explicit values still win.
1850
+ */
1851
+ brainEndpoint?: string;
1852
+ brainJwt?: string;
1853
+ brainAnonKey?: string;
1854
+ fetch?: typeof fetch;
1855
+ }
1856
+ /**
1857
+ * Query the open advisory set for an app. Pulls from
1858
+ * `actionable_advisories_v` (per-(app_id, code) rollup with stable ids
1859
+ * + server-side auto-resolution).
1860
+ *
1861
+ * Default behavior (no status filter): returns only `status='open'`.
1862
+ * Pass `status: 'all'` to see resolved + open together — useful for
1863
+ * Admin UIs that show "recently fixed" badges.
1864
+ *
1865
+ * Fetch failures bubble out as thrown Errors. (`markAdvisoryResolved`
1866
+ * uses the ok/reason envelope; this read path throws to match
1867
+ * existing kgauto query semantics where the consumer can decide to
1868
+ * retry or render an error state.)
1869
+ */
1870
+ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions): Promise<ActionableAdvisory[]>;
1871
+ /**
1872
+ * Mark an advisory as consumer-resolved.
1873
+ *
1874
+ * Lookup strategy:
1875
+ * 1. Query `actionable_advisories_v?id=eq.<id>` to find the (app_id, code)
1876
+ * tuple for this advisory.
1877
+ * 2. PATCH EVERY unresolved firing in `compile_outcome_advisories`
1878
+ * matching that tuple via the underlying outcome's app_id. (One call
1879
+ * closes the whole rollup — the alpha.71-era docblock said "latest
1880
+ * firing", which was never what the code did; corrected alpha.78.)
1881
+ *
1882
+ * The (app_id, code) lookup is necessary because `compile_outcome_advisories`
1883
+ * has no `app_id` column — it inherits scope via the FK to compile_outcomes.
1884
+ * PostgREST cannot PATCH with a JOIN predicate, so the markAdvisoryResolved
1885
+ * path is a two-step round-trip. The cost is one extra GET per resolve call;
1886
+ * acceptable because marks are low-frequency operator actions, not per-call
1887
+ * hot path.
1888
+ *
1889
+ * alpha.78 envelope (PB `resolve-envelope-cannot-close-a-rollup`, 2026-07-25):
1890
+ * the return now reports WHAT HAPPENED, not that the request was received —
1891
+ * `firingsResolved` is the count of rows this call actually flipped, and
1892
+ * `status` is the rollup's state after the write. PB measured the old
1893
+ * `ok: true` live against prod: the PATCH was being RLS-filtered to zero
1894
+ * rows (consumer JWTs had read-grant but no update-grant — migration 049
1895
+ * adds it) and the envelope reported success anyway. "When an API can
1896
+ * succeed without doing anything, the return value should distinguish those
1897
+ * cases" — this is that distinction. `firingsResolved: 0, status: 'open'`
1898
+ * on a rollup you expected to close now points at the write grant.
1899
+ *
1900
+ * Idempotent re-marks stay ok: an already-resolved advisory returns
1901
+ * `{ ok: true, firingsResolved: 0, status: 'resolved' }`.
1902
+ *
1903
+ * Returns ok/reason envelope (vs throwing) because consumer Admin UIs
1904
+ * typically want to render the failure inline rather than crash.
1905
+ */
1906
+ declare function markAdvisoryResolved(opts: MarkAdvisoryResolvedOptions): Promise<{
1907
+ ok: true;
1908
+ firingsResolved: number;
1909
+ status: 'open' | 'resolved' | 'unknown';
1910
+ } | {
1911
+ ok: false;
1912
+ reason: string;
1913
+ }>;
1914
+ /**
1915
+ * Resolution sources supported by the alpha.39 `markExclusionFindingHandled`
1916
+ * API. Mirrors the subset of `exclusion_findings.resolution_source` CHECK
1917
+ * constraint values that consumers can self-set:
1918
+ *
1919
+ * - `'consumer-marked'` — generic "we've handled this; stop reminding."
1920
+ * Use this for "we evaluated and chose not to act" or "we'll act when
1921
+ * ready but acknowledge the finding now."
1922
+ * - `'declined'` — explicit "this exclusion is intentional; do not surface
1923
+ * again." Stronger signal than consumer-marked; useful for compliance
1924
+ * exclusions, brand-promise exclusions, etc.
1925
+ * - `'probed-unblock'` — alpha.40+ probe-path verdict: consumer ran a live
1926
+ * probe and decided to unblock the excluded model. Library accepts the
1927
+ * value today so the probe path doesn't need a follow-up API release.
1928
+ * - `'probed-stay-excluded'` — alpha.40+ probe-path verdict: consumer
1929
+ * probed and confirmed the exclusion. Same forward-compat shape as
1930
+ * `'probed-unblock'`.
1931
+ *
1932
+ * The `'auto'` resolution_source is NOT exposed here — that's reserved
1933
+ * for the brain's own automatic resolution (e.g. when the detection
1934
+ * conditions no longer hold). Consumer code sets only the four values
1935
+ * above.
1936
+ */
1937
+ type ExclusionResolutionSource = 'consumer-marked' | 'declined' | 'probed-unblock' | 'probed-stay-excluded';
1938
+ interface MarkExclusionFindingHandledOptions {
1939
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
1940
+ appId: string;
1941
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
1942
+ archetype: string;
1943
+ /** Canonical model id that the consumer had excluded. */
1944
+ excludedModel: string;
1945
+ /** Resolution semantics — see `ExclusionResolutionSource` for the four
1946
+ * values consumers can set. */
1947
+ resolution: ExclusionResolutionSource;
1948
+ /** Optional free-form note explaining the decision. Surfaces in operator
1949
+ * digests + dashboards alongside the resolution_source. */
1950
+ resolutionNote?: string;
1951
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). The
1952
+ * function appends `/rest/v1/exclusion_findings?...`.
1953
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1954
+ brainEndpoint?: string;
1955
+ /** Consumer-scoped JWT carrying the `app_id` claim. The brain's RLS
1956
+ * policy enforces that the JWT's app_id matches the finding's app_id;
1957
+ * cross-tenant writes fail at the database layer regardless of input.
1958
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1959
+ brainJwt?: string;
1960
+ /** Supabase anon key for the `apikey` header (PostgREST requires it).
1961
+ * alpha.78: defaults from `readBrainReadEnv()` when omitted. */
1962
+ brainAnonKey?: string;
1963
+ /** Injected fetch for tests. Defaults to global fetch. */
1964
+ fetch?: typeof fetch;
1965
+ }
1966
+ /**
1967
+ * Mark a stale-exclusion finding as handled. Returns an `ok/reason` envelope
1968
+ * matching `markAdvisoryResolved` — consumer Admin UIs typically render the
1969
+ * failure inline rather than crash.
1970
+ *
1971
+ * Idempotent: if no row matches the (app_id, archetype, excludedModel)
1972
+ * tuple (already resolved, never existed, cron not yet UPSERTed), PostgREST
1973
+ * returns 200 with zero affected rows and we return `{ ok: true }`. The
1974
+ * caller's "I marked it as handled" intent is satisfied regardless of
1975
+ * whether the row was already in that state.
1976
+ *
1977
+ * Reasons surfaced on failure:
1978
+ * - `app_id_required` / `archetype_required` / `excluded_model_required`
1979
+ * - `resolution_invalid` — `resolution` not one of the four documented values
1980
+ * - `brain_auth_misconfig` — 401/403 (JWT / anon key wrong)
1981
+ * - `brain_unavailable` — 5xx
1982
+ * - `network_error:<message>` — fetch threw
1983
+ * - `patch_failed:<status>` — anything else non-2xx
1984
+ */
1985
+ declare function markExclusionFindingHandled(opts: MarkExclusionFindingHandledOptions): Promise<{
1986
+ ok: true;
1987
+ } | {
1988
+ ok: false;
1989
+ reason: string;
1990
+ }>;
1991
+
1992
+ /**
1993
+ * Archetype-cliff compatibility — alpha.28 (tt-intel-Cairn ratified).
1994
+ *
1995
+ * One question, one answer: *given this model and this intent, can it work
1996
+ * — and if not, what adapter (if any) would make it work?*
1997
+ *
1998
+ * Replaces the silent-archetype-cliff failure mode where a consumer picks a
1999
+ * model that's structurally wrong for the intent and kgauto compiles cleanly
2000
+ * without surfacing the gap. The triggering incident: tt-intel shipped
2001
+ * `deepseek-v4-pro` as the hunt default per a local spec; the kgauto coord
2002
+ * doc said L-040 — V4 is structurally wrong for hunt (sequential tools).
2003
+ * `archetypePerf.hunt = 4` was already in the profile data. The compiler
2004
+ * stayed silent. This API + the matching advisor rule surfaces it.
2005
+ *
2006
+ * Pure function. No network. No brain query. No side effects. ~1ms.
2007
+ *
2008
+ * Consultation doc:
2009
+ * command-center/advisory/kgauto/2026-05-21_archetype-cliff-advisor.md
2010
+ *
2011
+ * Refinements applied per tt-intel-Cairn ratification (2026-05-21):
2012
+ * R1: every variant carries `archetypePerf: number` (raw score) — and
2013
+ * `requires-adapter` adds `archetypePerfWithAdapter: number` so
2014
+ * consumer policy can be expressed as "accept adapter only when score
2015
+ * crosses some threshold WITH the adapter on."
2016
+ * R2: every variant carries a plain-English `reason: string`. No internal
2017
+ * jargon ("L-040", "archetypePerf=4") — the consumer chooses whether
2018
+ * to render it as UI hint or operator-tooling tooltip.
2019
+ * R3: `Adapter` is a CLOSED discriminated union, not `| string`. alpha.28
2020
+ * ships ONE variant (`toolOrchestration: 'sequential'`). Future
2021
+ * adapter parameters extend the union explicitly in named releases.
2022
+ * NO escape hatch — the whole point is catching "I added a new
2023
+ * adapter and forgot to update consumer policy" at compile time.
2024
+ */
2025
+
2026
+ /**
2027
+ * Minimum `archetypePerf[archetype]` score to count as `compatible` under
2028
+ * Option A (default policy). Below this, a documented adapter is needed
2029
+ * to lift the model above the floor; if no adapter exists, the model is
2030
+ * rejected.
2031
+ *
2032
+ * Matches `QUALITY_FLOOR_FOR_RECOMMENDATION` in `advisor.ts` — kgauto's
2033
+ * library-wide convention for "below this score, swap recommendations stop."
2034
+ */
2035
+ declare const ARCHETYPE_FLOOR_DEFAULT = 6;
2036
+ /**
2037
+ * Absolute floor — below this, the cliff is too steep for ANY adapter to
2038
+ * lift cleanly. Reserved under Option A (unused today; every below-floor
2039
+ * case is gated by adapter availability). Would gate `reject` vs
2040
+ * `requires-adapter` under a future Option B per consultation doc Q1.
2041
+ *
2042
+ * Exported so consumer-side policy can read it (e.g. "accept adapter only
2043
+ * when archetypePerf >= ABSOLUTE_FLOOR + 1"). Not used internally by
2044
+ * `getModelCompatibility` today — the gate is "does an adapter exist for
2045
+ * this cliff?", not score-based.
2046
+ */
2047
+ declare const ABSOLUTE_FLOOR = 4;
2048
+ /**
2049
+ * The intent the call is expressing — archetype + optional orchestration
2050
+ * mode. Same shape as `ir.intent.archetype` + `ir.constraints.toolOrchestration`
2051
+ * so a consumer can pass `{ archetype: ir.intent.archetype,
2052
+ * toolOrchestration: ir.constraints?.toolOrchestration }` directly.
2053
+ */
2054
+ interface CompatibilityIntent {
2055
+ archetype: IntentArchetypeName;
2056
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
2057
+ }
2058
+ /**
2059
+ * `Adapter` — re-exported above. Canonical definition lives in `ir.ts` to
2060
+ * avoid an import cycle (compatibility.ts → profiles.ts → ir.ts).
2061
+ *
2062
+ * **CLOSED discriminated union per R3.** Future adapter parameters extend
2063
+ * the union explicitly in named alpha releases. No `| string` escape hatch
2064
+ * — consumer policy code SHOULD write exhaustive `switch (adapter.parameter)`
2065
+ * and rely on the compiler to flag "I added a new adapter parameter and
2066
+ * forgot to update the consumer's policy."
2067
+ *
2068
+ * alpha.28 variants:
2069
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
2070
+ * Lifts DeepSeek V4-family on `hunt` from sequential-tool cliff (L-040).
2071
+ * The "consequence" plain-English-ifies the trade-off:
2072
+ * "Tool calls run one at a time — slower but reliable."
2073
+ *
2074
+ * alpha.29+ likely additions (per tt-intel-Cairn priority list):
2075
+ * - `{ parameter: 'parallelToolCalls'; value: false; consequence }`
2076
+ * - `{ parameter: 'maxTools'; value: number; consequence }`
2077
+ * - `{ parameter: 'thinkingBudget'; value: 0; consequence }`
2078
+ *
2079
+ * Each new variant lands in its own named release with the union extended
2080
+ * in `ir.ts`. Consumers see the change at compile time.
2081
+ */
2082
+ /**
2083
+ * The compatibility verdict for a (model, intent) pair. Discriminated union
2084
+ * on `status` — `compatible` | `requires-adapter` | `reject`.
2085
+ *
2086
+ * **Every variant carries `archetypePerf` (R1) + `reason` (R2):**
2087
+ * - `archetypePerf` — the raw 0-10 score for (model, archetype). Lets
2088
+ * consumers build their own thresholds without re-importing the profile
2089
+ * registry.
2090
+ * - `reason` — plain-English, consumer-renderable. NOT internal jargon
2091
+ * like "L-040 cliff" or "archetypePerf=4". Examples in R2 ratification:
2092
+ * - compatible: "Suited for hunt-style parallel discovery."
2093
+ * - requires-adapter: "Best with sequential tool calls for hunt — slower but works."
2094
+ * - reject: "Not suited for hunt — would underperform significantly."
2095
+ *
2096
+ * `requires-adapter` additionally carries:
2097
+ * - `archetypePerfWithAdapter` — estimated post-adapter score. May be an
2098
+ * estimate (we don't measure post-adapter scores yet); kgauto's prior is
2099
+ * "adapter lifts to ARCHETYPE_FLOOR_DEFAULT + 1" unless brain-evidenced.
2100
+ * - `adapter` — the closed-union variant describing the structural change.
2101
+ *
2102
+ * Backward-compat: an unknown model returns `reject` with a "model not
2103
+ * registered" reason; callers never throw. Unknown archetype is impossible
2104
+ * at the type level (`IntentArchetypeName` is a closed union).
2105
+ */
2106
+ type ModelCompatibility = {
2107
+ status: 'compatible';
2108
+ reason: string;
2109
+ archetypePerf: number;
2110
+ } | {
2111
+ status: 'requires-adapter';
2112
+ reason: string;
2113
+ archetypePerf: number;
2114
+ archetypePerfWithAdapter: number;
2115
+ adapter: Adapter;
2116
+ } | {
2117
+ status: 'reject';
2118
+ reason: string;
2119
+ archetypePerf: number;
2120
+ };
2121
+ /**
2122
+ * Compatibility query — *does this model fit this intent, and if not,
2123
+ * what would?*
2124
+ *
2125
+ * **Rules (Option A from consultation doc Q1):**
2126
+ * 1. If model is unregistered → `reject` with "model not registered" reason.
2127
+ * 2. If intent provides `toolOrchestration: 'sequential'` AND that adapter
2128
+ * silences the cliff (because the cliff IS the sequential-tool one)
2129
+ * → return `compatible` with raw score (NOT the post-adapter estimate
2130
+ * — caller already paid the adapter, score reflects reality).
2131
+ * 3. If raw `archetypePerf[archetype] >= ARCHETYPE_FLOOR_DEFAULT`
2132
+ * → `compatible`.
2133
+ * 4. If below floor BUT a documented adapter exists that lifts to floor
2134
+ * → `requires-adapter` with adapter + estimated post-adapter score.
2135
+ * 5. If below floor AND no adapter exists → `reject`.
2136
+ *
2137
+ * **Pure function.** Deterministic for `(modelId, intent)`. No I/O.
2138
+ *
2139
+ * @example
2140
+ * ```ts
2141
+ * import { getModelCompatibility } from '@warmdrift/kgauto-compiler';
2142
+ *
2143
+ * const c = getModelCompatibility('deepseek-v4-pro', { archetype: 'hunt' });
2144
+ * // → { status: 'requires-adapter',
2145
+ * // reason: 'Best with sequential tool calls for hunt — slower but works.',
2146
+ * // archetypePerf: 4,
2147
+ * // archetypePerfWithAdapter: 7,
2148
+ * // adapter: {
2149
+ * // parameter: 'toolOrchestration',
2150
+ * // value: 'sequential',
2151
+ * // consequence: 'Tool calls run one at a time...'
2152
+ * // } }
2153
+ *
2154
+ * // With the adapter already declared:
2155
+ * const c2 = getModelCompatibility('deepseek-v4-pro', {
2156
+ * archetype: 'hunt',
2157
+ * toolOrchestration: 'sequential',
2158
+ * });
2159
+ * // → { status: 'compatible',
2160
+ * // reason: 'Suited for hunt with sequential tool calls.',
2161
+ * // archetypePerf: 4 }
2162
+ * ```
2163
+ */
2164
+ declare function getModelCompatibility(modelId: string, intent: CompatibilityIntent): ModelCompatibility;
2165
+
2166
+ /**
2167
+ * alpha.22 — sync introspection: is brain-query mode active for a given
2168
+ * table? Used by the advisor (`model-stale-evidence` rule) to decide
2169
+ * whether a `judgment`-grounded chosen model is a measurement gap worth
2170
+ * surfacing. Returns false on cold start, when configureBrain() was never
2171
+ * called, or when the consumer explicitly opted the table out via
2172
+ * `BrainConfig.brainQuery.<table> = false`.
2173
+ */
2174
+ declare function isBrainQueryActiveFor(table: string): boolean;
2175
+ interface GetPerAxisMetricsOpts {
2176
+ /** App id to filter on. Required. */
2177
+ appId: string;
2178
+ /** Intent archetype to filter on. Required. */
2179
+ archetype: string;
2180
+ /** Canonical model id to filter on. Required. */
2181
+ model: string;
2182
+ /**
2183
+ * Window in days. Default 30. Only rows with
2184
+ * `created_at > now() - windowDays` are counted.
2185
+ */
2186
+ windowDays?: number;
2187
+ /**
2188
+ * Consumer-declared quality floor (0..1 oracle/approve-rate scale).
2189
+ * When set, the response's `qualityFloorMet` is true/false; when omitted,
2190
+ * `qualityFloorMet` is null (no floor declared, no judgment).
2191
+ */
2192
+ qualityFloor?: number;
2193
+ /** Pluggable fetch (tests inject mock). Defaults to global fetch. */
2194
+ fetch?: typeof fetch;
2195
+ /**
2196
+ * PostgREST base endpoint (e.g. `https://kgauto-brain.vercel.app/api`).
2197
+ * When omitted, falls back to the active configureBrainQuery runtime's
2198
+ * endpoint. Returns null when neither is set.
2199
+ */
2200
+ endpoint?: string;
2201
+ /** Bearer token. Forwarded as `Authorization: Bearer ${apiKey}`. */
2202
+ apiKey?: string;
2203
+ }
2204
+ /**
2205
+ * Call the `get_per_axis_metrics` RPC and return the typed result.
2206
+ *
2207
+ * Returns null when:
2208
+ * - no endpoint provided AND no configureBrainQuery runtime active
2209
+ * - RPC returns empty / null / unexpected shape
2210
+ * - brain unreachable / fetch throws / HTTP error
2211
+ *
2212
+ * Never throws — operator-facing query, must not blow up the caller.
2213
+ */
2214
+ declare function getPerAxisMetrics(opts: GetPerAxisMetricsOpts): Promise<PerAxisMetrics | null>;
2215
+
2216
+ /**
2217
+ * env.ts — provider env-key resolution + reachability predicates.
2218
+ *
2219
+ * Centralizes the per-provider env var names that kgauto checks for
2220
+ * reachability. Used by:
2221
+ *
2222
+ * - execute.ts — to find an API key when one isn't passed via apiKeys
2223
+ * - call.ts — to auto-filter unreachable models from the fallback walk
2224
+ * - getDefaultFallbackChain — opt-in chain filter when consumer passes `reachability`
2225
+ * - operator scripts — getReachabilityDiagnostic() prints what's wired up
2226
+ *
2227
+ * Keeping the map in ONE place means execute() and the reachability check
2228
+ * always agree. Without this, kgauto could declare a model "reachable" because
2229
+ * env.ts found GOOGLE_GENERATIVE_AI_API_KEY, while execute() looks at
2230
+ * GOOGLE_API_KEY only and 401s — shipping the bug we're trying to fix.
2231
+ *
2232
+ * Resolution order (apiKeys takes precedence):
2233
+ * 1. opts.apiKeys?.[provider]
2234
+ * 2. process.env[name] for each name in PROVIDER_ENV_KEYS[provider] (first-present wins)
2235
+ *
2236
+ * alpha.10 (2026-05-14). Resolves the auto-filter-unreachable-models-silently
2237
+ * request from PB after first-deploy 401 on the alpha.9 summarize chain.
2238
+ */
2239
+
2240
+ /**
2241
+ * Providers kgauto can resolve keys for today. Subset of `Provider` — `mistral`
2242
+ * and `xai` are declared in the type union but not yet executable (no profiles,
2243
+ * no execute() handler, no env-var convention). Narrowing here keeps the
2244
+ * reachability check structurally honest.
2245
+ */
2246
+ type SupportedProvider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'zai' | 'moonshot';
2247
+ /**
2248
+ * Per-provider env var names kgauto recognizes. Order doesn't matter —
2249
+ * first-present wins. Multiple names per provider supported because Google
2250
+ * has historical drift (`GOOGLE_API_KEY` from older Google Cloud SDKs,
2251
+ * `GEMINI_API_KEY` in many examples, `GOOGLE_GENERATIVE_AI_API_KEY` is the
2252
+ * Vercel AI SDK convention used by IC + tt-intel adapters).
2253
+ *
2254
+ * Frozen so consumers/tests can't mutate (would break the cache invariant
2255
+ * that execute() and reachability checks agree).
2256
+ */
2257
+ declare const PROVIDER_ENV_KEYS: Readonly<Record<SupportedProvider, readonly string[]>>;
2258
+ interface ReachabilityOpts {
2259
+ /** Explicit keys (alpha.3 ApiKeys). Checked first; takes precedence over env. */
2260
+ apiKeys?: ApiKeys;
2261
+ /**
2262
+ * Override env source. Defaults to `process.env` in Node-shaped runtimes,
2263
+ * `{}` everywhere else. Pass `{}` explicitly in tests for hermetic runs.
2264
+ */
2265
+ envSource?: Record<string, string | undefined>;
2266
+ }
2267
+ /**
2268
+ * Resolve a usable API key for the provider. Returns the key string, or
2269
+ * undefined if neither apiKeys nor any of the env names are set.
2270
+ *
2271
+ * Used internally by execute.ts so the reachability check and the actual
2272
+ * call check stay in sync.
2273
+ */
2274
+ declare function resolveProviderKey(provider: Provider, opts?: ReachabilityOpts): string | undefined;
2275
+ /**
2276
+ * True iff the provider has a usable key — either via explicit `apiKeys`
2277
+ * or one of the `PROVIDER_ENV_KEYS[provider]` names is set in envSource.
2278
+ */
2279
+ declare function isProviderReachable(provider: Provider, opts?: ReachabilityOpts): boolean;
2280
+ /**
2281
+ * True iff the model's profile exists AND its provider is reachable.
2282
+ * Unknown model id returns false (treat as unreachable; the chain walker
2283
+ * will surface "no reachable models" if everything filters out).
2284
+ */
2285
+ declare function isModelReachable(modelId: string, opts?: ReachabilityOpts): boolean;
2286
+ interface ProviderReachability {
2287
+ reachable: boolean;
2288
+ /** How the key was found. `null` when unreachable. */
2289
+ via: 'apiKeys' | 'env' | null;
2290
+ /** Which env var name supplied the key (only when via === 'env'). */
2291
+ envKeyFound?: string;
2292
+ }
2293
+ /**
2294
+ * Snapshot of which providers are reachable from the current env / apiKeys.
2295
+ * Useful for operator scripts ("kgauto diagnose"), startup-time logging,
2296
+ * and the cost-watcher's "which consumer is missing what" report.
2297
+ *
2298
+ * Does NOT log the key value itself — only the env var name that supplied it.
2299
+ */
2300
+ declare function getReachabilityDiagnostic(opts?: ReachabilityOpts): Record<SupportedProvider, ProviderReachability>;
2301
+ /**
2302
+ * Brain-read env contract — canonical names + accepted fallbacks for the
2303
+ * env vars kgauto's brain-read APIs need.
2304
+ *
2305
+ * Affected APIs: `getActionableAdvisories`, `markAdvisoryResolved`,
2306
+ * `markExclusionFindingHandled`, `markPromoteReadyHandled`,
2307
+ * `getStaleExclusionFindings`, and future brain-read surfaces. Each accepts
2308
+ * `brainEndpoint`/`brainJwt`/`brainAnonKey` as call-site arguments; this
2309
+ * helper centralizes resolution from the consumer's environment.
2310
+ *
2311
+ * Resolution order (first-truthy-trimmed wins):
2312
+ * endpoint = KGAUTO_V2_BRAIN_SUPABASE_URL ?? KGAUTO_V2_BRAIN_URL
2313
+ * jwt = KGAUTO_V2_BRAIN_JWT ?? GLASSBOX_BRAIN_JWT
2314
+ * anonKey = KGAUTO_V2_BRAIN_ANON_KEY (no fallback)
2315
+ *
2316
+ * Why fallbacks exist:
2317
+ *
2318
+ * 1. Pre-alpha.42, some consumers set `KGAUTO_V2_BRAIN_URL` pointing at
2319
+ * the kgauto-dashboard URL (write target). The canonical
2320
+ * `KGAUTO_V2_BRAIN_SUPABASE_URL` is the Supabase project URL (read
2321
+ * target — PostgREST against `/rest/v1/`). Until consumers split the
2322
+ * two names, the fallback grabs whichever URL is set. When BOTH are
2323
+ * set, canonical wins (the consumer has explicitly split).
2324
+ *
2325
+ * 2. The s33 Glass-Box ship provisioned `GLASSBOX_BRAIN_JWT` across all
2326
+ * consumers with the same `app_id` claim shape, signed by the same
2327
+ * JWT_SECRET. Reusing it for brain-read avoids re-minting + re-pasting
2328
+ * a second JWT per consumer per surface.
2329
+ *
2330
+ * `missingEnv` lists the CANONICAL names that aren't satisfied by either
2331
+ * canonical OR fallback. Consumer policy: if `missingEnv.length > 0`,
2332
+ * render `not_configured`; otherwise pass `endpoint`/`jwt`/`anonKey` to
2333
+ * `getActionableAdvisories({ ... })` et al.
2334
+ *
2335
+ * Pre-trim semantics carry from `readKeyValue` — paste-newline-trap
2336
+ * (L-060 / L-083 / L-108) closure extends to brain env vars.
2337
+ *
2338
+ * Filed by tt-intel-Cairn (s89, 2026-05-27) after the s89 actionable-
2339
+ * advisories ref template hit `malformed brain response` on prod because
2340
+ * the endpoint env var pointed at the kgauto-dashboard URL instead of the
2341
+ * Supabase URL, AND because IC's ref template used a third env name
2342
+ * (`KGAUTO_V2_BRAIN_ENDPOINT`) that was unset. Three distinct name shapes
2343
+ * across two consumers — the durable closure is one canonical contract.
2344
+ */
2345
+ interface BrainReadEnv {
2346
+ /** Supabase project URL (PostgREST base). Undefined when neither canonical nor fallback is set. */
2347
+ endpoint?: string;
2348
+ /** JWT carrying `app_id` claim, signed by brain JWT_SECRET. Undefined when neither canonical nor fallback is set. */
2349
+ jwt?: string;
2350
+ /** Supabase anon (publishable) key. Undefined when not set. */
2351
+ anonKey?: string;
2352
+ /**
2353
+ * Canonical names not satisfied by either canonical OR fallback. Subset
2354
+ * (in order) of:
2355
+ * ['KGAUTO_V2_BRAIN_SUPABASE_URL', 'KGAUTO_V2_BRAIN_JWT', 'KGAUTO_V2_BRAIN_ANON_KEY']
2356
+ * Consumer policy: render `not_configured` when length > 0.
2357
+ */
2358
+ missingEnv: string[];
2359
+ }
2360
+ /**
2361
+ * alpha.78 (PB adoption-gap ask 2) — the canonical brain-read env names as
2362
+ * an exported constant, so consumers reference them instead of retyping
2363
+ * (PB invented three plausible-but-wrong names and carried the resulting
2364
+ * self-authored 503 for two months).
2365
+ */
2366
+ declare const BRAIN_READ_ENV_NAMES: {
2367
+ readonly endpoint: "KGAUTO_V2_BRAIN_SUPABASE_URL";
2368
+ readonly jwt: "KGAUTO_V2_BRAIN_JWT";
2369
+ readonly anonKey: "KGAUTO_V2_BRAIN_ANON_KEY";
2370
+ /** Accepted fallbacks, in resolution order after the canonical name. */
2371
+ readonly fallbacks: {
2372
+ readonly endpoint: readonly ["KGAUTO_V2_BRAIN_URL"];
2373
+ readonly jwt: readonly ["GLASSBOX_BRAIN_JWT"];
2374
+ readonly anonKey: readonly [];
2375
+ };
2376
+ };
2377
+ /**
2378
+ * Resolve brain-read env vars. Defaults to `process.env`; pass `envSource`
2379
+ * for hermetic tests. Trims surrounding whitespace and treats
2380
+ * empty-after-trim as unset (same shape as `resolveProviderKey`).
2381
+ */
2382
+ declare function readBrainReadEnv(envSource?: Record<string, string | undefined>): BrainReadEnv;
2383
+
2384
+ /**
2385
+ * getDefaultFallbackChain — the alpha.9 cascading ship.
2386
+ *
2387
+ * Returns a per-archetype fallback chain that walks the cost/performance
2388
+ * Pareto frontier (master plan §1.3 + §3). Three customer postures:
2389
+ *
2390
+ * locked — caller passes [theOneModel]; never call this function
2391
+ * preferred — caller passes `primary`; chain returned is [primary, ...fallbacks]
2392
+ * open — caller passes no `primary`; chain returned is [best, ...fallbacks]
2393
+ *
2394
+ * ## What the default chain optimizes for — READ THIS BEFORE CITING IT
2395
+ *
2396
+ * The default (`optimizeFor: 'quality'`) chain is ordered by **archetype
2397
+ * performance with provider diversity**, NOT by cost. It is a reliability
2398
+ * ladder: "if tier 0 fails, who else can do this job well."
2399
+ *
2400
+ * This docstring previously claimed each step "costs strictly less than the
2401
+ * previous." **That claim was false for all ten archetypes** (verified
2402
+ * 2026-07-29, alpha.80) and it was load-bearing — kgauto's own cost
2403
+ * advisories cited `posture: 'open'` as a cost remedy on the strength of it.
2404
+ * For `ask`, open posture leads with `claude-sonnet-4-6` at ~8.6x the cost
2405
+ * of the model the cost advisories recommend. tt-intel came within one
2406
+ * un-run function call of tripling their hottest path's spend by following
2407
+ * kgauto's own documented advice. See
2408
+ * `advisory/kgauto/from-tt-intelligence/2026-07-28_chain-builder-and-cost-advisories-give-opposite-answers.md`.
2409
+ *
2410
+ * Some non-monotone steps are deliberate and correct: `plan` walks UP to
2411
+ * Opus on 429, `critique`/`judge` never degrade below a reasoning floor,
2412
+ * and cross-provider anchors are chosen for outage-independence rather
2413
+ * than price. The defect was the unconditional claim, not the chains.
2414
+ *
2415
+ * The default chain at each step:
2416
+ * 1. Comes from a different provider than the previous step where possible
2417
+ * (correlated outages don't kill consecutive attempts)
2418
+ * 2. Stays above the archetype's perf floor (skip models scored <baseline
2419
+ * for archetypes where degradation would be unacceptable)
2420
+ * 3. Makes NO cost guarantee. Pass `optimizeFor: 'cost'` when cost order
2421
+ * is what you want — that mode DOES guarantee monotone-cheaper, and
2422
+ * `assertChainCostMonotonicity` pins it.
2423
+ *
2424
+ * In alpha.9 the chain is **hand-curated** per archetype (§3.3 starter
2425
+ * table). Brain-query mode lands in alpha.10. Policy.blockedModels filters
2426
+ * the result; policy.maxCostPerCallUsd is NOT applied here because the
2427
+ * function doesn't see the IR's token counts — that filtering happens at
2428
+ * `passScoreTargets()` time inside compile().
2429
+ *
2430
+ * The function is **pure** — no brain query, no I/O, no randomness. Same
2431
+ * inputs always produce the same chain.
2432
+ */
2433
+
2434
+ /**
2435
+ * Posture passed into `getDefaultFallbackChain`. The chain function only
2436
+ * sees `'open'` and `'preferred'` — callers in `'locked'` posture should
2437
+ * pass `models: [theOneModel]` directly and skip this function entirely.
2438
+ *
2439
+ * Equivalent to `CompilePolicy.posture` minus `'locked'`. Kept distinct so
2440
+ * the type system enforces "don't ask for a chain when you don't want one."
2441
+ */
2442
+ type FallbackPosture = 'open' | 'preferred';
2443
+ interface GetDefaultFallbackChainOpts {
2444
+ /** The archetype the call is performing. Drives chain shape. */
2445
+ archetype: IntentArchetypeName;
2446
+ /**
2447
+ * The user-selected or caller-anchored primary model. When provided, it
2448
+ * appears at position 0 of the returned chain and fallbacks follow.
2449
+ * When omitted, the function picks the best-perf model for the archetype
2450
+ * as position 0 (open posture).
2451
+ */
2452
+ primary?: string;
2453
+ /**
2454
+ * Informational. `'preferred'` and `'open'` produce the same chain shape
2455
+ * given the same `primary`/no-primary input — posture is a tag the brain
2456
+ * uses to distinguish "user-anchored" from "library-anchored" telemetry.
2457
+ */
2458
+ posture?: FallbackPosture;
2459
+ /**
2460
+ * Cap on chain length. Default 3. Min 1. Useful when the consumer wants
2461
+ * to keep the worst-case latency low (each fallback adds a round-trip).
2462
+ */
2463
+ maxDepth?: number;
2464
+ /**
2465
+ * Consumer-side gating. `blockedModels` are filtered from the chain.
2466
+ * `preferredModels` is informational (no boost applied at this layer —
2467
+ * compile()'s `passScoreTargets` handles preference ranking).
2468
+ * `maxCostPerCallUsd` is NOT applied here — needs IR-level token
2469
+ * estimation. Use compile()'s policy plumbing instead.
2470
+ */
2471
+ policy?: CompilePolicy;
2472
+ /**
2473
+ * alpha.10. When provided, the chain is filtered to models whose provider
2474
+ * has a reachable API key (via `apiKeys` or one of `PROVIDER_ENV_KEYS[provider]`).
2475
+ * Models whose provider can't be reached are silently dropped. If filtering
2476
+ * leaves the chain empty, returns `[]` — caller decides what to do (call()
2477
+ * throws CallError; this function stays pure).
2478
+ *
2479
+ * Pass `{}` to opt in with `process.env` as the env source. Pass `{ apiKeys, envSource }`
2480
+ * for explicit control (tests, non-Node runtimes). Omit entirely for the
2481
+ * legacy unfiltered behavior — preserves alpha.9 callers byte-for-byte.
2482
+ */
2483
+ reachability?: ReachabilityOpts;
2484
+ /**
2485
+ * alpha.20 E3: consumer-declared tool-orchestration shape. Currently
2486
+ * only affects `archetype: 'hunt'`, where 'sequential' swaps the
2487
+ * parallel-tool-tier-0 chain (Flash → Pro → Sonnet → Haiku) for a
2488
+ * DeepSeek-tier-0 chain (V4-Pro → Flash → Sonnet) — DeepSeek's L-040
2489
+ * parallel-tool cliff doesn't apply when the consumer commits to
2490
+ * single-step orchestration.
2491
+ *
2492
+ * Other archetypes are NOT mode-aware in this release — they ship the
2493
+ * same chain regardless of toolOrchestration. Future versions may
2494
+ * extend mode-awareness to ask/generate/etc. when brain evidence
2495
+ * supports it.
2496
+ *
2497
+ * Default (omitted or 'either'): parallel chain. Back-compat with all
2498
+ * pre-alpha.20 callers.
2499
+ */
2500
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
2501
+ /**
2502
+ * alpha.80 — what the chain ORDER optimizes for.
2503
+ *
2504
+ * 'quality' (default) — status quo, byte-for-byte. Hand-curated /
2505
+ * brain-loaded archetype ladder: best perf first, provider diversity
2506
+ * down the chain. Makes NO cost guarantee (see module docstring).
2507
+ *
2508
+ * 'cost' — cheapest-first among every `status: 'current'` model whose
2509
+ * `archetypePerf[archetype]` clears {@link ARCHETYPE_FLOOR_DEFAULT}.
2510
+ * Guarantees monotone-cheaper. Considers the WHOLE roster, not just
2511
+ * the curated chain — which is the point: `gemini-2.5-flash` ties
2512
+ * `claude-haiku-4-5` on `ask` perf at a third of the price and is
2513
+ * absent from the curated `ask` ladder entirely.
2514
+ *
2515
+ * The quality floor is what keeps 'cost' honest: a model with no evidence
2516
+ * scores the neutral 5 and is therefore excluded, so cost mode can never
2517
+ * bottom-feed into unmeasured models. Quality stays a binary floor; cost
2518
+ * optimizes only above it.
2519
+ *
2520
+ * Default 'quality' — existing consumers see zero change on bump.
2521
+ */
2522
+ optimizeFor?: 'quality' | 'cost';
2523
+ }
2524
+ /**
2525
+ * Reference call shape used to RANK models by cost. Deliberately a blend
2526
+ * rather than input-only: ranking by `costInputPer1m` alone (which the
2527
+ * advisor's `cost-mismatched-archetype` rule does) mis-orders any pair
2528
+ * whose output multiple differs, and real traffic runs input-heavy
2529
+ * (L-050: >85% input is the universal efficiency signal).
2530
+ *
2531
+ * This ranks; it does not bill. `estimateChainCostUsd` is exported so
2532
+ * callers who know their real shape can compute against it instead.
2533
+ */
2534
+ declare const COST_RANKING_REFERENCE_SHAPE: {
2535
+ readonly inputTokens: 4000;
2536
+ readonly outputTokens: 250;
2537
+ };
2538
+ /**
2539
+ * Estimated USD for one call at a given shape. Exported so the advisor and
2540
+ * consumer-side code share ONE derivation of "what does this model cost
2541
+ * here" — two independent derivations of one concept will drift (s75).
2542
+ */
2543
+ declare function estimateChainCostUsd(profile: ModelProfile, shape?: {
2544
+ inputTokens: number;
2545
+ outputTokens: number;
2546
+ }): number;
2547
+ /**
2548
+ * How many distinct providers a chain spans. `1` means every fallback shares
2549
+ * one provider's fate — the chain buys you retries, not outage independence.
2550
+ * Exported so a cost-mode consumer can check what they traded away.
2551
+ */
2552
+ declare function chainProviderSpread(chain: readonly string[]): number;
2553
+ /**
2554
+ * Returns the fallback chain for an archetype as a plain `string[]` of
2555
+ * model ids.
2556
+ *
2557
+ * @deprecated since alpha.21 — prefer
2558
+ * {@link getDefaultFallbackChainWithGrounding}, which returns the same chain
2559
+ * shape with a `grounding` label on every entry (measured / capability-fact /
2560
+ * judgment). The string[] return is preserved indefinitely for back-compat —
2561
+ * no functional change in alpha.21. Existing callers don't need to migrate
2562
+ * unless they want to surface the grounding gap to users.
2563
+ */
2564
+ declare function getDefaultFallbackChain(opts: GetDefaultFallbackChainOpts): string[];
2565
+ /**
2566
+ * Returns a shallow copy of the hand-curated starter chain for an archetype.
2567
+ * Useful for tests + the `scripts/digest.mjs` operator readout.
2568
+ */
2569
+ declare function getStarterChain(archetype: IntentArchetypeName): string[];
2570
+ /**
2571
+ * Returns a shallow copy of all starter chains keyed by archetype.
2572
+ * Useful for the `digest.mjs` readout and consumer audits.
2573
+ */
2574
+ declare function getAllStarterChains(): Record<IntentArchetypeName, string[]>;
2575
+ /**
2576
+ * alpha.20 E3 introspection — returns the sequential-mode overlay for an
2577
+ * archetype, or `undefined` when no overlay is registered (the archetype
2578
+ * is mode-agnostic and reuses `STARTER_CHAINS[archetype]`).
2579
+ *
2580
+ * Useful for tests + the `scripts/digest.mjs` operator readout to surface
2581
+ * the mode-aware chains.
2582
+ */
2583
+ declare function getSequentialStarterChain(archetype: IntentArchetypeName): string[] | undefined;
2584
+ /**
2585
+ * alpha.21 (s78 Entry 1) — returns the fallback chain as `ChainEntry[]`,
2586
+ * with a `grounding` label on every position.
2587
+ *
2588
+ * Same selection logic as {@link getDefaultFallbackChain} (primary anchoring,
2589
+ * blockedModels filter, dedupe, reachability filter, maxDepth cap) — the
2590
+ * only difference is the return shape: each position is a `ChainEntry`
2591
+ * carrying `{ id, grounding, reason?, n? }` instead of a bare string.
2592
+ *
2593
+ * Use this when surfacing the chain to consumers who care WHY each entry
2594
+ * sits where it sits — Glass-Box panels, operator dashboards, eval
2595
+ * scaffolding deciding which entries deserve measurement priority.
2596
+ *
2597
+ * Returns `[]` when filtering empties the chain (same semantics as the
2598
+ * string variant) — consumer decides what to do.
2599
+ */
2600
+ declare function getDefaultFallbackChainWithGrounding(opts: GetDefaultFallbackChainOpts): ChainEntry[];
2601
+ /**
2602
+ * alpha.21 introspection — returns the grounded starter chain for an
2603
+ * archetype (no primary anchoring, no policy filtering, no maxDepth cap).
2604
+ * Use this when you want the raw, hand-curated grounded chain — every
2605
+ * entry carries a `grounding` label and optional reason/n.
2606
+ */
2607
+ declare function getStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[];
2608
+ /**
2609
+ * alpha.21 introspection — all grounded starter chains keyed by archetype.
2610
+ * Useful for the `digest.mjs` readout and consumer audits that want to
2611
+ * surface the grounding gap across the entire chain table.
2612
+ */
2613
+ declare function getAllStarterChainsWithGrounding(): Record<IntentArchetypeName, ChainEntry[]>;
2614
+ /**
2615
+ * alpha.21 introspection — sequential-mode overlay with grounding labels,
2616
+ * or `undefined` when no overlay is registered for the archetype.
2617
+ */
2618
+ declare function getSequentialStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[] | undefined;
2619
+
2620
+ /**
2621
+ * chains-brain — alpha.11 KG-11 adapter.
2622
+ *
2623
+ * Brain-driven STARTER_CHAINS for `getDefaultFallbackChain`. Reads
2624
+ * `kgauto_chains` table via the shared brain-query SWR cache (D6 + D8);
2625
+ * falls back to bundled STARTER_CHAINS on cold-start, brain-down, or
2626
+ * empty/missing table (D2 + D4).
2627
+ *
2628
+ * Behavioral note (locked via D2): the sync API surface returns bundled on
2629
+ * cold-start, with a background refresh fired. Subsequent calls within the
2630
+ * 5-min TTL return brain data. Vercel cold-start consumers see the seed
2631
+ * snapshot (functionally identical to pre-alpha.11); warm-start consumers
2632
+ * see live brain mutations within 5 min.
2633
+ */
2634
+ /**
2635
+ * Sync reader for the brain-driven chains map. Returns bundled
2636
+ * STARTER_CHAINS when brain-query is disabled, cold, or unreachable.
2637
+ */
2638
+ declare const loadChainsFromBrain: () => Record<"ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform" | "judge", string[]>;
2639
+
2640
+ /**
2641
+ * archetype-perf-brain — alpha.11 KG-12 adapter.
2642
+ *
2643
+ * Brain-driven archetypePerf scores. Substrate for the future closed-loop
2644
+ * tuning engine (KG-12.5): brain telemetry → human or automated bumps →
2645
+ * brain UPDATE → consumers see new scores within 5-min cache TTL with
2646
+ * zero refresh.
2647
+ *
2648
+ * Today: data migrates to brain. No runtime call site reads archetypePerf
2649
+ * (it's metadata for the master plan §2.5 anti-hallucination guardrail +
2650
+ * future auto-tuning). The adapter exists so future readers — auto-tuning
2651
+ * + operator scripts + KG-12.5 — have a shipped substrate to consume.
2652
+ */
2653
+
2654
+ type ArchetypePerfMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
2655
+ /**
2656
+ * alpha.21: per-(model, archetype) row count map. Same shape as
2657
+ * ArchetypePerfMap but stores brain row counts when the brain backs a
2658
+ * placement. Undefined entries → no row count seen → score is the
2659
+ * hand-curated cold-start prior (grounding='judgment').
2660
+ */
2661
+ type ArchetypePerfNMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
2662
+ /**
2663
+ * Sync reader for the brain-driven archetypePerf map. Returns bundled
2664
+ * profile.archetypePerf data when brain-query is disabled, cold, or
2665
+ * unreachable. Identical shape pre/post-alpha.11 by design (D2).
2666
+ */
2667
+ declare const loadArchetypePerfFromBrain: () => ArchetypePerfMap;
2668
+ /**
2669
+ * alpha.21 — sync reader for the brain row-count map paired with
2670
+ * archetype-perf. Returns empty map (no measured backing) on cold start /
2671
+ * brain-down / unreachable — all `getArchetypePerfScore` calls then
2672
+ * resolve to `grounding: 'judgment'`. When the brain table includes an
2673
+ * `n` column on each row, this map mirrors those counts so consumers can
2674
+ * see how many measurements back each score.
2675
+ */
2676
+ declare const loadArchetypePerfNFromBrain: () => ArchetypePerfNMap;
2677
+ /**
2678
+ * Threshold above which a brain row count counts as 'measured' grounding.
2679
+ * Below this, the score is treated as 'judgment' (cold-start prior or
2680
+ * not-yet-enough-evidence). Mirrors the alpha.20 `getCleanPerfScore`
2681
+ * `minRows` default — same rule for consistency.
2682
+ */
2683
+ declare const MEASURED_GROUNDING_MIN_N = 10;
2684
+ /**
2685
+ * alpha.21 — return shape for the extended {@link getArchetypePerfScore}.
2686
+ * Wraps the existing 0..10 score with:
2687
+ *
2688
+ * - `n`: brain row count backing this score (0 when no measurement).
2689
+ * - `grounding`: derived label — 'measured' when n >= 10, else 'judgment'.
2690
+ *
2691
+ * The score itself is unchanged from pre-alpha.21 (numeric, 5 = neutral
2692
+ * default). 'capability-fact' is NOT a perf-score grounding — capability
2693
+ * decisions live on chain entries, not on perf scores.
2694
+ */
2695
+ interface ArchetypePerfScoreResult {
2696
+ /** 0..10 perf score. 5 = neutral default when no entry exists. */
2697
+ score: number;
2698
+ /**
2699
+ * Brain row count backing this score. 0 when bundled (cold-start prior)
2700
+ * or when the brain row didn't carry an `n` column.
2701
+ */
2702
+ n: number;
2703
+ /**
2704
+ * Provenance — 'measured' when `n >= 10`, else 'judgment'.
2705
+ * Never 'capability-fact' (that label is reserved for chain-entry
2706
+ * inclusion/exclusion decisions).
2707
+ */
2708
+ grounding: Grounding;
2709
+ }
2710
+ /**
2711
+ * Per-model accessor with grounding (alpha.21). Returns 5 (neutral) when no
2712
+ * entry is found — consistent with the master plan §3.3 "missing archetypes
2713
+ * default to 5" convention documented in profiles.ts
2714
+ * ModelProfile.archetypePerf.
2715
+ *
2716
+ * Backwards-compat note: pre-alpha.21 callers expected `number` here. The
2717
+ * new return shape `{ score, n, grounding }` is a breaking shape change at
2718
+ * the type level, but `.score` carries the legacy value. Callers reading
2719
+ * `.score` field-by-field continue working; callers using the bare number
2720
+ * arithmetically need to switch to `.score`. The migration is single-line
2721
+ * (`const x = getArchetypePerfScore(...)` → `const x = getArchetypePerfScore(...).score`).
2722
+ */
2723
+ declare function getArchetypePerfScore(modelId: string, archetype: IntentArchetypeName): ArchetypePerfScoreResult;
2724
+
2725
+ /**
2726
+ * pricing-brain — alpha.11 KG-13 adapter.
2727
+ *
2728
+ * Brain-driven pricing data with **time-bounded resolution** (`valid_from`
2729
+ * / `valid_until` columns). The V4-Pro 75%-off promo through 2026-05-31
2730
+ * gets modeled as two rows; `at` parameter resolution picks the correct
2731
+ * row per call timestamp. Promo flips happen automatically at the
2732
+ * boundary without alpha cuts.
2733
+ *
2734
+ * SWR cache holds the FULL pricing snapshot (all active rows for all
2735
+ * models). Per-call `at` filtering is in-memory — keeps the SWR semantics
2736
+ * uniform with other adapters (one cache, one snapshot, sync reads).
2737
+ */
2738
+ interface PricingRow {
2739
+ modelId: string;
2740
+ costInputPer1m: number;
2741
+ costOutputPer1m: number;
2742
+ cacheInputPer1m?: number;
2743
+ cacheCreationPer1m?: number;
2744
+ validFrom: number;
2745
+ validUntil?: number;
2746
+ source?: string;
2747
+ }
2748
+ /**
2749
+ * Sync reader for the brain-driven pricing snapshot. Returns bundled
2750
+ * profile pricing when brain-query is disabled, cold, or unreachable.
2751
+ * Caller filters by `at` via {@link resolvePricingAt}.
2752
+ */
2753
+ declare const loadPricingFromBrain: () => PricingRow[];
2754
+ /**
2755
+ * Resolve the active pricing row for a model at a given timestamp.
2756
+ * Picks the row with the latest `valid_from <= at` whose
2757
+ * `valid_until > at` (or NULL — open-ended).
2758
+ *
2759
+ * Returns `undefined` when no row matches. Callers should fall back to
2760
+ * profile static pricing in that case.
2761
+ */
2762
+ declare function resolvePricingAt(modelId: string, at?: Date): PricingRow | undefined;
2763
+
2764
+ /**
2765
+ * models-brain — alpha.11 KG-14 adapter (the largest of the four).
2766
+ *
2767
+ * Brain-driven model registry + aliases. Two adapters share the same
2768
+ * SWR snapshot:
2769
+ *
2770
+ * - `loadModelsFromBrain()` — `Map<modelId, ModelProfile>` from
2771
+ * `kgauto_models` table (cliffs/lowering/recovery as JSONB columns).
2772
+ * - `loadAliasesFromBrain()` — `Record<aliasId, canonicalId>` from
2773
+ * `kgauto_aliases` table.
2774
+ *
2775
+ * After alpha.11, new-model onboarding becomes brain INSERT (vs PR + alpha
2776
+ * cut + 3 consumer refreshes). The auto-onboard pipeline
2777
+ * (`scripts/check-model-releases.mjs`) shifts from emitting profile.ts
2778
+ * edits to writing brain rows directly.
2779
+ *
2780
+ * **D5 — alias resolution stable regardless of canonical's active state.**
2781
+ * `canonicalId('deepseek-chat') → 'deepseek-v4-flash'` even when the
2782
+ * canonical row is `active=false`. Aliases are wire-format contracts;
2783
+ * legacy callers' resolution promise outlives the canonical's active
2784
+ * status. Deprecation (`active=false`) affects chain composition only.
2785
+ */
2786
+
2787
+ /**
2788
+ * Exported brain-row shape for `kgauto_models`. Mirrors the SQL table
2789
+ * (`v2/brain/migrations/010_kgauto_models_and_aliases.sql`) — column names
2790
+ * are snake_case to match PostgREST. Used by operator scripts that write
2791
+ * to brain (auto-onboard, promote-model) — see `profileToRow()`.
2792
+ *
2793
+ * Read path stays internal via `RawModelRow` to keep `rowToProfile()`'s
2794
+ * tolerance contract from leaking into write callers.
2795
+ */
2796
+ interface ModelBrainRow {
2797
+ model_id: string;
2798
+ provider: string;
2799
+ status?: string;
2800
+ max_context_tokens?: number;
2801
+ max_output_tokens?: number;
2802
+ max_tools?: number;
2803
+ parallel_tool_calls?: boolean;
2804
+ structured_output?: string;
2805
+ system_prompt_mode?: string;
2806
+ streaming?: boolean;
2807
+ cliffs?: unknown;
2808
+ lowering?: unknown;
2809
+ recovery?: unknown;
2810
+ strengths?: string[] | null;
2811
+ weaknesses?: string[] | null;
2812
+ cost_input_per_1m?: number;
2813
+ cost_output_per_1m?: number;
2814
+ notes?: string | null;
2815
+ verified_against_docs?: string | null;
2816
+ archetype_perf?: Record<string, number> | null;
2817
+ version_added?: string;
2818
+ version_removed?: string | null;
2819
+ active?: boolean;
2820
+ /** alpha.41 — model-family tag (migration 024 column). */
2821
+ family?: string | null;
2822
+ /** alpha.49 — explicit latency bucket (migration 028 column). */
2823
+ latency_tier?: string | null;
2824
+ /** alpha.49 — per-archetype prompt-shape conventions (migration 028 column). */
2825
+ archetype_conventions?: ArchetypeConvention[] | null;
2826
+ }
2827
+ interface ProfileToRowOptions {
2828
+ /** e.g. `'2.0.0-alpha.12'` — leave undefined to omit from row. */
2829
+ versionAdded?: string;
2830
+ /** Pass `null` to clear; omit to leave field unset. */
2831
+ versionRemoved?: string | null;
2832
+ /** Defaults to true if omitted. */
2833
+ active?: boolean;
2834
+ /**
2835
+ * Override verifiedAgainstDocs (e.g. set to `null` for auto-onboard).
2836
+ * When omitted, the profile's own value is used. Pass `null` explicitly
2837
+ * to write a SQL NULL (e.g. unverified auto-onboard rows).
2838
+ */
2839
+ verifiedAgainstDocs?: string | null;
2840
+ }
2841
+ /**
2842
+ * Inverse of `rowToProfile` — serialize a `ModelProfile` to a `kgauto_models`
2843
+ * row payload for INSERT/UPSERT. Used by operator scripts that write to
2844
+ * brain (auto-onboard pipeline, promote-model verification CLI).
2845
+ *
2846
+ * Row-level fields (`version_added`, `version_removed`, `active`) are
2847
+ * operator-controlled and pass through `opts`. `verifiedAgainstDocs` can
2848
+ * also be overridden via `opts` — auto-onboard explicitly passes `null` to
2849
+ * mark unverified rows (the column is DATE, doesn't accept the
2850
+ * `'UNVERIFIED-AUTO-ONBOARD'` sentinel used in PROFILES_RAW).
2851
+ */
2852
+ declare function profileToRow(profile: ModelProfile, opts?: ProfileToRowOptions): ModelBrainRow;
2853
+ /**
2854
+ * Sync reader for the brain-driven model registry. Returns bundled
2855
+ * PROFILES_RAW when brain-query is disabled, cold, or unreachable.
2856
+ */
2857
+ declare const loadModelsFromBrain: () => Map<string, ModelProfile>;
2858
+ /**
2859
+ * Sync reader for the brain-driven aliases map. Returns bundled ALIASES
2860
+ * when brain-query is disabled, cold, or unreachable.
2861
+ *
2862
+ * D5: this map carries both active and inactive canonical mappings —
2863
+ * alias resolution is stable regardless of canonical's `active` state.
2864
+ */
2865
+ declare const loadAliasesFromBrain: () => Record<string, string>;
2866
+
2867
+ /**
2868
+ * exclusion-findings-brain — alpha.38 KG-19 adapter.
2869
+ *
2870
+ * Per-tenant SWR cache for the `exclusion_findings` table populated by the
2871
+ * `kgauto-exclusion-re-evaluation-watch` cron (alpha.37 substrate). Distinct
2872
+ * from the cross-tenant `brain-query.ts` snapshot because exclusion findings
2873
+ * are scoped per `app_id` — one process = one consumer = one appId, but the
2874
+ * cache key supports multi-app processes by keying snapshots by appId.
2875
+ *
2876
+ * Architecture mirrors `brain-query.ts` but with a per-(appId) snapshot:
2877
+ *
2878
+ * - **Sync API surface.** `getStaleExclusionFindings({ appId, archetype })`
2879
+ * returns `ExclusionFindingRow[]` immediately. First call returns the
2880
+ * bundled fallback (empty array); async refresh fires in background;
2881
+ * subsequent calls within TTL return brain data.
2882
+ *
2883
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
2884
+ * per appId per TTL window. Tests can reset between cases.
2885
+ *
2886
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
2887
+ * silent bundled fallback (empty array). Never throws. Warns once per
2888
+ * process per error to avoid log spam.
2889
+ *
2890
+ * - **Opt-in.** Activation gated on `configureExclusionFindingsBrain()`
2891
+ * having been called with a runtime. The public `configureBrain()` in
2892
+ * brain.ts wires this up automatically when `BrainConfig.brainQuery
2893
+ * .findingsExclusions !== false`.
2894
+ *
2895
+ * Default endpoint:
2896
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`
2897
+ * The route accepts `?app_id=X` and returns a JSON array of findings
2898
+ * for that app filtered to `resolved_at IS NULL`. Public read; data
2899
+ * carries no consumer PII (app id, archetype, model id, cost ratio,
2900
+ * savings estimate).
2901
+ */
2902
+ /**
2903
+ * Shape of one row from the `exclusion_findings` cache table. Mirrors the
2904
+ * snake_case JSONB returned by the brain RPC + the dashboard endpoint.
2905
+ * Camel-case mapping happens at the boundary (rowToFinding) so the in-memory
2906
+ * shape stays consistent with the rest of the library.
2907
+ */
2908
+ interface ExclusionFindingRow {
2909
+ /** Intent archetype the finding applies to (e.g. 'hunt', 'classify'). */
2910
+ archetype: string;
2911
+ /** Canonical model id that the consumer has excluded (zero traffic in window). */
2912
+ excludedModel: string;
2913
+ /** Provider of the excluded model (e.g. 'deepseek', 'openai'). */
2914
+ excludedProvider: string;
2915
+ /** Detection verdict — alpha.37 ships 'recommend-probe' only. */
2916
+ verdict: 'recommend-probe' | 'unblock' | 'stay-excluded' | 'inconclusive';
2917
+ /**
2918
+ * Estimated 30-day savings in USD if the excluded model becomes primary
2919
+ * on this archetype. Null when pricing is incomplete or excluded model is
2920
+ * more expensive than the leader.
2921
+ */
2922
+ estimatedSavingsUsd30d: number | null;
2923
+ /** Renderable summary; produced by the detector / RPC. */
2924
+ message: string;
2925
+ /** Actionable recommendation; produced by the detector / RPC. */
2926
+ suggestion: string;
2927
+ /** Detector confidence tier. */
2928
+ confidence: 'high' | 'medium' | 'low';
2929
+ /**
2930
+ * Free-form evidence pack (cost ratio, leader info, promo flags, parallel-
2931
+ * tool hint, etc.). Surfaced verbatim to advisor rules for richer messages.
2932
+ * Optional — older detector runs may not populate every field.
2933
+ */
2934
+ evidence?: Record<string, unknown>;
2935
+ }
2936
+ /**
2937
+ * Default endpoint hosted on the kgauto-dashboard. Public read — data carries
2938
+ * no PII (app id, archetype, model id, cost ratio, savings estimate). Mirrors
2939
+ * the cross-tenant `/api/kgauto-v2/config` pattern.
2940
+ */
2941
+ declare const DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
2942
+ /**
2943
+ * Sync introspection — is the findings-brain active? Used by advisor rules
2944
+ * to decide whether to even attempt a read.
2945
+ */
2946
+ declare function isExclusionFindingsBrainActive(): boolean;
2947
+ interface GetExclusionFindingsOpts {
2948
+ /** App id to read findings for. Required. */
2949
+ appId: string;
2950
+ /**
2951
+ * Optional archetype filter. When set, returns only findings where
2952
+ * `archetype` matches. When omitted, returns all findings for the app.
2953
+ */
2954
+ archetype?: string;
2955
+ }
2956
+ /**
2957
+ * Sync reader. Returns the cached findings for `appId`, optionally filtered
2958
+ * to a single archetype. First call returns empty array and triggers async
2959
+ * refresh; subsequent calls within TTL return brain data.
2960
+ *
2961
+ * NEVER throws. Brain down / endpoint misconfigured / mapper exception →
2962
+ * empty array.
2963
+ */
2964
+ declare function getStaleExclusionFindings(opts: GetExclusionFindingsOpts): ExclusionFindingRow[];
2965
+
2966
+ /**
2967
+ * Family resolution — alpha.41.
2968
+ *
2969
+ * "I want the latest Opus" → kgauto picks the current+active model in the
2970
+ * `claude-opus` family. Closes the loop where consumer code carries hardcoded
2971
+ * `claude-opus-4-6` literals long after `claude-opus-4-7` ships and goes
2972
+ * current — the s47 trigger (IC's `generate` chain still routing 43 calls to
2973
+ * legacy 4-6 in production).
2974
+ *
2975
+ * Two surfaces:
2976
+ * - `getRecommendedPrimary({ family, ..., fallback })` — public, sync,
2977
+ * used at IR-construction time when the consumer wants a literal id back
2978
+ * (with a fallback floor for cold-start brain).
2979
+ * - `resolveFamilyEntry({ family, archetype?, appId? })` — internal,
2980
+ * called from compile() when an IR's `models[]` entry is shaped
2981
+ * `{ family: string }`. Throws `FamilyResolutionError` on failure.
2982
+ *
2983
+ * Both routes share the same algorithm (locked in the alpha.41 Phase 0
2984
+ * design contract); they differ only in the fallback ergonomics. The
2985
+ * public route accepts a required `fallback: string`; the IR route throws.
2986
+ *
2987
+ * Pure resolution. No network. No async. Brain-registry reads go through
2988
+ * the existing SWR cache (`loadModelsFromBrain` from `models-brain.ts`) —
2989
+ * cold-start returns bundled profiles, which still resolve via the
2990
+ * `deriveFamilyFromModelId` fallback when the brain row's `family` column
2991
+ * is null (G1 contract: graceful pre-migration behavior).
2992
+ *
2993
+ * @see command-center/advisory/kgauto/2026-05-26_alpha-41-model-family-aliases-and-promotion-probe-watcher.md
2994
+ */
2995
+
2996
+ interface GetRecommendedPrimaryOptions {
2997
+ /**
2998
+ * Family tag (e.g. `'claude-opus'`, `'gemini-flash'`). See the Phase 0
2999
+ * design contract's family taxonomy table for the locked initial set;
3000
+ * extensible via brain migrations.
3001
+ */
3002
+ family: string;
3003
+ /**
3004
+ * Optional archetype gate. When provided, candidates must clear
3005
+ * {@link ARCHETYPE_FLOOR_DEFAULT} on `archetypePerf[archetype]`. Also used
3006
+ * as the primary sort key (DESC) when multiple candidates qualify.
3007
+ */
3008
+ archetype?: IntentArchetypeName;
3009
+ /**
3010
+ * Optional consumer-app id. When provided, candidates matching a
3011
+ * `stay-excluded` finding for `(appId, archetype)` in the
3012
+ * exclusion-findings cache (alpha.38 substrate) are filtered out.
3013
+ */
3014
+ appId?: string;
3015
+ /**
3016
+ * Consumer-posture tag. `'locked'` short-circuits resolution and returns
3017
+ * the literal `fallback` unconditionally — useful for compliance /
3018
+ * contract / brand-promise flows where the consumer doesn't want kgauto
3019
+ * picking the model on their behalf.
3020
+ */
3021
+ posture?: 'preferred' | 'open' | 'locked';
3022
+ /**
3023
+ * Last-resort literal model id. REQUIRED. Returned when (a) brain
3024
+ * registry is cold / no candidates exist, (b) `posture === 'locked'`,
3025
+ * (c) every candidate was filtered out by archetype / exclusion gates.
3026
+ *
3027
+ * The fallback is NOT validated against the family — kgauto trusts the
3028
+ * consumer to pass a meaningful floor. The contract intent is "even when
3029
+ * everything below is on fire, you still get a model id back."
3030
+ */
3031
+ fallback: string;
3032
+ }
3033
+ /**
3034
+ * Thrown by `resolveFamilyEntry` (the internal compile-time twin) when a
3035
+ * `{ family: string }` IR entry can't resolve to any current+active model.
3036
+ * Surfaces with the family string + a one-line cause so consumer error
3037
+ * handling can distinguish "you typo'd the family tag" from "brain is cold
3038
+ * and nothing matches."
3039
+ *
3040
+ * The public `getRecommendedPrimary` does NOT throw — it returns
3041
+ * `fallback` instead.
3042
+ */
3043
+ declare class FamilyResolutionError extends Error {
3044
+ readonly family: string;
3045
+ readonly cause: string;
3046
+ constructor(family: string, cause: string);
3047
+ }
3048
+ /**
3049
+ * Deterministic model_id → family inference. Pure function; no brain
3050
+ * lookup. Used as the runtime fallback when a brain row's `family` column
3051
+ * is null (pre-migration 024) and as the canonical mapping that migration
3052
+ * 024's CASE statement mirrors.
3053
+ *
3054
+ * Returns null for unrecognized ids — caller must handle (typically by
3055
+ * skipping the row in family resolution).
3056
+ *
3057
+ * Order matters: more specific patterns first (e.g. `flash-lite` before
3058
+ * `flash`; `pro` before `chat`). The brain-side CASE statement uses the
3059
+ * same priority.
3060
+ */
3061
+ declare function deriveFamilyFromModelId(modelId: string): string | null;
3062
+ /**
3063
+ * Public sync resolver. Pure (modulo brain snapshot read). Returns the
3064
+ * literal model id of the best candidate, or `fallback` when resolution
3065
+ * yields nothing.
3066
+ */
3067
+ declare function getRecommendedPrimary(opts: GetRecommendedPrimaryOptions): string;
3068
+
3069
+ /**
3070
+ * promote-ready-brain — alpha.41 substrate.
3071
+ *
3072
+ * Per-tenant SWR cache for the `promote_ready_findings` table populated by
3073
+ * the autonomous `promotion-probe-watcher` (Mode 2). Mirrors
3074
+ * `exclusion-findings-brain.ts` shape byte-for-byte where applicable; this
3075
+ * is the read-side substrate for the compile-time `promote-ready` advisor
3076
+ * rule.
3077
+ *
3078
+ * Architecture (mirror of exclusion-findings-brain):
3079
+ *
3080
+ * - **Sync API surface.** `getPromoteReadyFindings({ appId, archetype,
3081
+ * family })` returns `PromoteReadyFindingRow[]` immediately. First call
3082
+ * returns the bundled fallback (empty array); async refresh fires in
3083
+ * background; subsequent calls within TTL return brain data.
3084
+ *
3085
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
3086
+ * per appId per TTL window. Tests reset between cases via
3087
+ * `_testResetPromoteReadyFindings()`.
3088
+ *
3089
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
3090
+ * silent bundled fallback (empty array). Never throws. Warns once per
3091
+ * process per error to avoid log spam.
3092
+ *
3093
+ * - **Opt-in.** Activation gated on `configurePromoteReadyBrain()` having
3094
+ * been called with a runtime. The public `configureBrain()` in brain.ts
3095
+ * wires this up automatically when
3096
+ * `BrainConfig.brainQuery.findingsPromoteReady !== false`.
3097
+ *
3098
+ * Plus: `markPromoteReadyHandled` — direct PostgREST PATCH against the
3099
+ * brain (no kgauto proxy). Mirrors `markExclusionFindingHandled` shape
3100
+ * byte-for-byte. Idempotent on `resolved_at=is.null` filter.
3101
+ *
3102
+ * Default endpoint:
3103
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/promote-ready`
3104
+ * The route accepts `?app_id=X` and returns a JSON array of findings
3105
+ * for that app filtered to `resolved_at IS NULL`.
3106
+ */
3107
+
3108
+ /**
3109
+ * Shape of one row from the `promote_ready_findings` cache table. Mirrors
3110
+ * the snake_case JSONB returned by the brain endpoint, mapped to camelCase
3111
+ * at the boundary (rowToFinding) so the in-memory shape stays consistent
3112
+ * with the rest of the library.
3113
+ */
3114
+ interface PromoteReadyFindingRow {
3115
+ /** Intent archetype the finding applies to. */
3116
+ archetype: string;
3117
+ /** Model family (e.g. 'claude-opus', 'gemini-flash'). */
3118
+ family: string;
3119
+ /** The candidate model that the probe validated. */
3120
+ candidateModel: string;
3121
+ /** The current production model the candidate was compared against. */
3122
+ currentModel: string;
3123
+ /** Sample size of the probe run (typically 10). */
3124
+ sampleN: number;
3125
+ /** Fraction of probes where the judge verdict was 'candidate-better' or
3126
+ * 'tied'. 0.000 to 1.000. */
3127
+ judgePassRate: number;
3128
+ /** Mean judge score across the probe sample. 1.00 to 5.00. */
3129
+ judgeAvgScore: number;
3130
+ /** Signed cost delta as a fraction (negative = candidate is cheaper).
3131
+ * Null when pricing data was incomplete at probe time. */
3132
+ costDeltaPct: number | null;
3133
+ /** ISO timestamp of detection (when the probe wrote the row). */
3134
+ detectedAt: string;
3135
+ }
3136
+ /**
3137
+ * Resolution sources supported by alpha.41 `markPromoteReadyHandled`. The
3138
+ * three values map to the three CHECK-constrained resolution values on
3139
+ * `promote_ready_findings.resolution`:
3140
+ *
3141
+ * - `'promoted'` — consumer migrated to the candidate model. Strong
3142
+ * positive signal; the probe was right.
3143
+ * - `'declined'` — consumer evaluated and chose not to promote.
3144
+ * Strong negative signal; revisit only on new
3145
+ * family entries or material score swings.
3146
+ * - `'still-evaluating'` — consumer acknowledges the finding but defers
3147
+ * the decision. Acknowledges-without-deciding;
3148
+ * finding silences this cycle but next probe may
3149
+ * re-surface.
3150
+ */
3151
+ type PromoteReadyResolution = 'promoted' | 'declined' | 'still-evaluating';
3152
+ interface MarkPromoteReadyHandledOptions {
3153
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
3154
+ appId: string;
3155
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
3156
+ archetype: IntentArchetypeName | string;
3157
+ /** Model family the finding applies to (e.g. 'claude-opus'). */
3158
+ family: string;
3159
+ /** Resolution semantics — see `PromoteReadyResolution`. */
3160
+ resolution: PromoteReadyResolution;
3161
+ /** Optional free-form note explaining the decision. */
3162
+ resolutionNote?: string;
3163
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). */
3164
+ brainEndpoint: string;
3165
+ /** Consumer-scoped JWT carrying the `app_id` claim. */
3166
+ brainJwt: string;
3167
+ /** Supabase anon key for the `apikey` header. */
3168
+ brainAnonKey: string;
3169
+ /** Injected fetch for tests. Defaults to global fetch. */
3170
+ fetch?: typeof fetch;
3171
+ }
3172
+ /**
3173
+ * Mark a probe-validated promote-ready finding as handled. Returns an
3174
+ * `ok/reason` envelope matching `markExclusionFindingHandled`.
3175
+ *
3176
+ * Idempotent: if no row matches the (app_id, archetype, family) tuple
3177
+ * (already resolved, never existed, watcher not yet UPSERTed), PostgREST
3178
+ * returns 200/204 with zero affected rows and we return `{ ok: true }`.
3179
+ *
3180
+ * Reasons surfaced on failure:
3181
+ * - `app_id_required` / `archetype_required` / `family_required`
3182
+ * - `resolution_invalid` — not one of the three documented values
3183
+ * - `brain_auth_misconfig` — 401/403
3184
+ * - `brain_unavailable` — 5xx
3185
+ * - `network_error:<message>` — fetch threw
3186
+ * - `patch_failed:<status>` — anything else non-2xx
3187
+ */
3188
+ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions): Promise<{
3189
+ ok: true;
3190
+ } | {
3191
+ ok: false;
3192
+ reason: string;
3193
+ }>;
3194
+
3195
+ /**
3196
+ * promotions-brain — alpha.64 Stage-2 substrate.
3197
+ *
3198
+ * Per-tenant SWR cache for the `kgauto_promotions` table populated by the
3199
+ * golden-eval trigger's auto-promote actor (Stage 2 of the eval trust
3200
+ * ladder: auto-promote downswaps behind the 7-day rollback guard). Mirrors
3201
+ * `promote-ready-brain.ts` shape where applicable; this is the read-side
3202
+ * substrate for the compile-time promotion boost in `passScoreTargets`.
3203
+ *
3204
+ * Design contract:
3205
+ * command-center/advisory/kgauto/2026-07-18_stage2-auto-promote-design.md
3206
+ *
3207
+ * Consent posture: the routing effect is OPT-IN, default OFF. The cache is
3208
+ * only activated by `configureBrain()` when the consumer opted in via
3209
+ * `BrainConfig.autoPromote: true` or the `KGAUTO_AUTO_PROMOTE` env var
3210
+ * (config field wins when both are present — mirror of the
3211
+ * `KGAUTO_GOLDEN_CAPTURE` env-as-consent precedent). Not opted in ⇒ this
3212
+ * module never fetches and `getApplicablePromotion` returns undefined ⇒
3213
+ * zero behavior change anywhere in compile().
3214
+ *
3215
+ * Architecture (mirror of promote-ready-brain):
3216
+ * - Sync API surface: `getApplicablePromotion({ appId, archetype })`
3217
+ * returns immediately. First call returns undefined (cold) and fires an
3218
+ * async refresh; subsequent calls within TTL return brain data.
3219
+ * - Per-appId snapshot; one fetch per appId per TTL window.
3220
+ * - Tolerant: brain down / misconfigured / unexpected shape → undefined.
3221
+ * Never throws. Warns once per process.
3222
+ *
3223
+ * A rollback (`status='rolled_back'` PATCHed by the promotion-guard
3224
+ * watcher) drops the row from the endpoint's `status=active` filter, so
3225
+ * routing reverts within one TTL window — the mechanism the 7-day guard's
3226
+ * auto-revert rests on.
3227
+ */
3228
+
3229
+ /**
3230
+ * One active surface promotion, camelCase-mapped at the boundary from the
3231
+ * snake_case endpoint row (typed-boundary-transformer convention).
3232
+ */
3233
+ /**
3234
+ * Release B (alpha.75): `kgauto_promotions` carries two logical channels
3235
+ * sharing one table and one lifecycle (migration 047). `mode` is the
3236
+ * discriminator, and each mode has exactly ONE consumption site:
3237
+ *
3238
+ * mode reader effect
3239
+ * ---------- ---------------------------------- -------------------
3240
+ * downswap passScoreTargets (compile pass 5) which MODEL runs
3241
+ * strategy applySectionRewrites (pass 6.5) which IR runs
3242
+ *
3243
+ * The resolver is mode-filtered and no unfiltered accessor exists — an
3244
+ * unfiltered `.find()` was the §7 read-path bug: a strategy row has
3245
+ * promoted_model === incumbent_model, so one reaching the model-boost code
3246
+ * would boost the incumbent and could suppress the alpha.49 quality gate on
3247
+ * evidence that was never about quality-gating.
3248
+ */
3249
+ type PromotionMode = 'downswap' | 'strategy';
3250
+ interface PromotionRow {
3251
+ /** Brain row id — cited in the `promotion-applied` mutation for Glass-Box. */
3252
+ id: number;
3253
+ /** Intent archetype the promotion applies to. */
3254
+ archetype: string;
3255
+ /**
3256
+ * Channel discriminator (migration 047). Rows from a pre-047 endpoint
3257
+ * carry no `mode` on the wire and map to 'downswap' — every pre-047 row
3258
+ * IS a downswap, and strategy rows can only be written by post-047 code
3259
+ * whose endpoint serves the column.
3260
+ */
3261
+ mode: PromotionMode;
3262
+ /**
3263
+ * The strategy id for mode='strategy' rows (e.g. 'discipline-gates-v1');
3264
+ * null on downswaps. DB CHECK: (mode='strategy') = (strategy IS NOT NULL).
3265
+ */
3266
+ strategy: string | null;
3267
+ /** The model this surface now routes to. */
3268
+ promotedModel: string;
3269
+ /** The model it replaced (the eval's incumbent). */
3270
+ incumbentModel: string;
3271
+ /** The promote-ready kgauto_golden_eval_runs row this rests on. */
3272
+ evalRunId: number | null;
3273
+ /**
3274
+ * Evidence-supersedes-judgment: skip the alpha.49 schema-weak
3275
+ * quality-gate penalty for the promoted model on this surface (the eval
3276
+ * measured the schema floor holding on real workload). Always false on
3277
+ * strategy rows (DB CHECK kgauto_promotions_strategy_no_suppress).
3278
+ */
3279
+ suppressQualityGate: boolean;
3280
+ /** ISO timestamp the promotion went active. */
3281
+ promotedAt: string;
3282
+ /**
3283
+ * alpha.78 — lifecycle status. The endpoint serves rolled_back rows only
3284
+ * when the library asks (`with_rollbacks=1`), so pre-.78 clients can
3285
+ * never receive one. Every reader that APPLIES a promotion must filter
3286
+ * to 'active'; rolled_back rows exist so advisors can see what the guard
3287
+ * already adjudicated instead of re-recommending it (PB Finding 3).
3288
+ */
3289
+ status: 'active' | 'rolled_back';
3290
+ /** ISO timestamp of the guard's revert, rolled_back rows only. */
3291
+ rolledBackAt?: string;
3292
+ /** Guard's classification ('latency' | 'economics' | 'strategy' | …). */
3293
+ rollbackClass?: string;
3294
+ }
3295
+ interface PromotionsRuntime {
3296
+ /** Endpoint base URL. The library appends `?app_id=<id>`. */
3297
+ endpoint: string;
3298
+ /** Stale-while-revalidate window in ms. */
3299
+ ttlMs: number;
3300
+ /** Pluggable fetch. */
3301
+ fetchImpl: typeof fetch;
3302
+ /** Optional warn hook. */
3303
+ onError?: (err: unknown) => void;
3304
+ }
3305
+ /**
3306
+ * Default endpoint hosted on the kgauto-dashboard. Serves `status='active'`
3307
+ * kgauto_promotions rows for one app_id. Mirrors the findings convention.
3308
+ */
3309
+ declare const DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
3310
+ /**
3311
+ * True when the KGAUTO_AUTO_PROMOTE env var opts this process in.
3312
+ * Accepted truthy forms: '1', 'true' (case-insensitive). Everything else —
3313
+ * unset, '', '0', 'false' — is OFF. Read at configureBrain() time, not per
3314
+ * call.
3315
+ */
3316
+ declare function isAutoPromoteEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
3317
+ /**
3318
+ * Wire (or rewire) the runtime. Pass undefined to disable. Resets all
3319
+ * snapshots. Called from `configureBrain()` ONLY when the consumer opted in.
3320
+ */
3321
+ declare function configurePromotionsBrain(rt: PromotionsRuntime | undefined): void;
3322
+ /** Sync introspection — is the promotions brain active (i.e. opted in)? */
3323
+ declare function isPromotionsBrainActive(): boolean;
3324
+ interface GetApplicablePromotionOpts {
3325
+ /** App id to read promotions for. Required. */
3326
+ appId: string;
3327
+ /** Archetype of the compile in flight. Required. */
3328
+ archetype: IntentArchetypeName | string;
3329
+ /**
3330
+ * Channel to read (migration 047). Required — there is deliberately no
3331
+ * unfiltered accessor: with one active row per (surface, mode) legal, an
3332
+ * unfiltered first-match-wins `.find()` returns an arbitrary channel's
3333
+ * row, and a strategy row reaching the model-boost reader is the §7
3334
+ * read-path bug.
3335
+ */
3336
+ mode: PromotionMode;
3337
+ }
3338
+ /**
3339
+ * Sync reader. Returns the active promotion for `(appId, archetype, mode)`
3340
+ * or undefined. First call returns undefined and triggers async refresh;
3341
+ * subsequent calls within TTL return brain data. The brain enforces one
3342
+ * active promotion per (surface, mode) (partial unique index), so at most
3343
+ * one row matches.
3344
+ *
3345
+ * NEVER throws. Not configured / brain down / cold → undefined.
3346
+ */
3347
+ declare function getApplicablePromotion(opts: GetApplicablePromotionOpts): PromotionRow | undefined;
3348
+ /**
3349
+ * alpha.78 — how long a guard rollback suppresses re-recommending the same
3350
+ * model on the same surface. Matches the measured-failure evidence window:
3351
+ * a `rollback_class='latency'` revert deliberately keeps the model ELIGIBLE
3352
+ * long-term (traffic patterns change), so the suppression is windowed, not
3353
+ * permanent.
3354
+ */
3355
+ declare const ROLLBACK_SUPPRESSION_WINDOW_DAYS = 28;
3356
+ /**
3357
+ * alpha.78 (PB Finding 3) — sync reader: did the promotion guard recently
3358
+ * roll back `model` on `(appId, archetype)`? The cost advisor consults this
3359
+ * so it stops recommending "exactly the downswap your own machinery
3360
+ * auto-reverted three days ago" — an advisory acting on it would
3361
+ * re-litigate a decision the guard already made correctly. Same SWR
3362
+ * posture as `getApplicablePromotion`: cold/unconfigured → undefined
3363
+ * (advisor proceeds without rollback knowledge, as before alpha.78).
3364
+ */
3365
+ declare function getRecentRollback(opts: {
3366
+ appId: string;
3367
+ archetype: IntentArchetypeName | string;
3368
+ model: string;
3369
+ windowDays?: number;
3370
+ nowMs?: number;
3371
+ }): PromotionRow | undefined;
3372
+ /** Reset module state. Tests must call between cases. */
3373
+ declare function _testResetPromotions(): void;
3374
+ /** Wait for any in-flight refresh to settle. */
3375
+ declare function _testWaitForPromotionsRefresh(): Promise<void>;
3376
+
3377
+ /**
3378
+ * measured-failure-brain — the CREATE-a-gate direction of
3379
+ * measured-supersedes-judgment (alpha.70).
3380
+ *
3381
+ * alpha.49 gives kgauto a quality gate that fires off a model profile's
3382
+ * DECLARED conventions (`archetypeConventions.structuredOutputHint: 'avoid'`).
3383
+ * alpha.64 let a MEASURED eval verdict SUPPRESS that gate
3384
+ * (`kgauto_promotions.suppress_quality_gate`). Nothing could go the other
3385
+ * way — a model whose declarations are wrong could not have a gate CREATED
3386
+ * for it, which is precisely the case where declarations cannot be trusted.
3387
+ *
3388
+ * The originating evidence: `claude-haiku-4-5` on playbacksam/summarize
3389
+ * declares `structuredOutput: 'grammar'` + `archetypePerf.summarize: 8`, so
3390
+ * every quality signal reads green and it wins the surface on price — while
3391
+ * failing **12 of 12 in-window attempts** (2026-07-14..25, seven in one
3392
+ * day). The brain held that evidence and nothing could act on it.
3393
+ *
3394
+ * ── Design notes ───────────────────────────────────────────────────────
3395
+ *
3396
+ * **No stored decision.** The gate is DERIVED from a rolling 28d window
3397
+ * (`kgauto_surface_model_failure_v`), never written down. That kills the
3398
+ * flap problem by construction — there is no state to flap — and it means
3399
+ * a gated model un-gates itself once its failures age out. Combined with
3400
+ * the gate being a DE-RANK (out of leadership, retained as graceful
3401
+ * fallback) rather than a hard block, the model keeps earning evidence, so
3402
+ * this cannot become the exclusion-lock-in trap where a blocked model can
3403
+ * never prove itself again.
3404
+ *
3405
+ * **The threshold is a confidence bound, not a fixed sample floor.** A flat
3406
+ * `minSample: 20` (promotion-guard's rate floor) would NOT have fired on
3407
+ * haiku's n=12 — the consumer would keep paying while we waited for a
3408
+ * rounder number. But distinguishing 100% from 5% needs far fewer trials
3409
+ * than distinguishing 2% from 6%. Gating on the Wilson score lower bound
3410
+ * makes the sample requirement adapt to the effect size automatically,
3411
+ * which is the alpha.67 insight ("the sample floor for a median can be far
3412
+ * lower than for a rate") generalised properly.
3413
+ *
3414
+ * **Direct app-scoped read, not the config-endpoint cache.** Modelled on
3415
+ * `promotions-brain.ts`, deliberately NOT `createBrainQueryCache` — that
3416
+ * routes through the dashboard `/v2/config` projection, which is the third
3417
+ * layer in the L-073 "executable knowledge is dropped at every transport
3418
+ * boundary" chain. One fewer place to forget a field.
3419
+ */
3420
+
3421
+ /**
3422
+ * One row of the rolling-window evidence view, per (app, archetype, model).
3423
+ * Raw counts only — the brain serves facts, this module decides.
3424
+ */
3425
+ interface SurfaceFailureRow {
3426
+ archetype: string;
3427
+ model: string;
3428
+ /** Total attempts in-window (served + quality walkaways). */
3429
+ n: number;
3430
+ /** Attempts that failed on the quality axis. */
3431
+ nFail: number;
3432
+ }
3433
+ declare const MEASURED_FAILURE_CFG: {
3434
+ /**
3435
+ * Hard minimum attempts before ANY gate may be created. Guards against
3436
+ * pathological tiny samples that the confidence bound alone would let
3437
+ * through in edge cases. At 5-for-5 the bound clears the threshold; at
3438
+ * 3-for-3 it does not, which is the behaviour we want (three failures is
3439
+ * a bad day, five in a row is a pattern).
3440
+ */
3441
+ readonly minSample: 5;
3442
+ /**
3443
+ * Gate when we are 95% confident the model fails MORE OFTEN THAN IT
3444
+ * SUCCEEDS on this surface. Deliberately unarguable rather than tuned —
3445
+ * a model that probably fails the majority of the time has no business
3446
+ * leading a surface, whatever its declared scores say.
3447
+ */
3448
+ readonly lowerBoundThreshold: 0.5;
3449
+ /** 95% one-sided-ish confidence (standard two-sided z at α=0.05). */
3450
+ readonly z: 1.96;
3451
+ /** Must match the view's window. Documented here for the advisory text. */
3452
+ readonly windowDays: 28;
3453
+ };
3454
+ /**
3455
+ * Wilson score interval, lower bound. Preferred over the normal
3456
+ * approximation because it stays sane at the extremes — at p̂ = 1 the
3457
+ * normal approximation gives a zero-width interval (it would gate on a
3458
+ * single failure), while Wilson correctly returns a bound that tightens
3459
+ * with n.
3460
+ *
3461
+ * Returns 0 for n <= 0.
3462
+ */
3463
+ declare function wilsonLowerBound(failures: number, n: number, z?: number): number;
3464
+ interface MeasuredFailureVerdict {
3465
+ /** Whether the measured-failure quality gate fires for this tuple. */
3466
+ gated: boolean;
3467
+ /** Observed failure rate in-window. */
3468
+ rate: number;
3469
+ /** 95% lower confidence bound on that rate — what the gate tests. */
3470
+ lowerBound: number;
3471
+ /** Attempts backing the verdict. */
3472
+ n: number;
3473
+ nFail: number;
3474
+ }
3475
+ /**
3476
+ * alpha.78 — public row normalizer (PB 2026-07-25 trap): the counts
3477
+ * endpoint speaks snake_case (`intent_archetype`, `n_fail`) and this module
3478
+ * speaks camelCase. A consumer reproducing a gate decision by hand from the
3479
+ * endpoint previously got a silent `gated: false` — `wilsonLowerBound(
3480
+ * undefined, 13)` returns a clean 0 rather than throwing. Exported so the
3481
+ * bridge exists exactly once.
3482
+ */
3483
+ declare function mapMeasuredFailureRows(rows: unknown[]): SurfaceFailureRow[];
3484
+ /**
3485
+ * Pure decision, exported for tests and for the advisory text. Separated
3486
+ * from the I/O so the policy can be exercised without a brain.
3487
+ *
3488
+ * alpha.78 — accepts BOTH row shapes: the module's camelCase
3489
+ * `SurfaceFailureRow` and the counts endpoint's raw snake_case row. A
3490
+ * snake_case row previously slipped through the type system (all fields
3491
+ * `undefined`) and judged `gated: false` silently.
3492
+ */
3493
+ declare function judgeMeasuredFailure(row: SurfaceFailureRow | {
3494
+ intent_archetype: string;
3495
+ model: string;
3496
+ n: number | string;
3497
+ n_fail: number | string;
3498
+ } | undefined, cfg?: typeof MEASURED_FAILURE_CFG): MeasuredFailureVerdict | undefined;
3499
+ interface MeasuredFailureRuntime {
3500
+ /** Endpoint base URL. The library appends `?app_id=<id>`. */
3501
+ endpoint: string;
3502
+ /** Stale-while-revalidate window in ms. */
3503
+ ttlMs: number;
3504
+ fetchImpl: typeof fetch;
3505
+ onError?: (err: unknown) => void;
3506
+ }
3507
+ /** Default endpoint on the kgauto-dashboard. Mirrors the promotions convention. */
3508
+ declare const DEFAULT_MEASURED_FAILURE_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure";
3509
+ /**
3510
+ * Opt-out env switch. UNLIKE auto-promote this defaults ON wherever the
3511
+ * brain is configured, because the gate is protective: it only ever
3512
+ * de-ranks a model the consumer's OWN traffic shows to be failing them, and
3513
+ * the failure is already being paid for. Set `KGAUTO_MEASURED_FAILURE_GATE=0`
3514
+ * (or 'false') to disable.
3515
+ */
3516
+ declare function isMeasuredFailureGateEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
3517
+ declare function configureMeasuredFailureBrain(rt: MeasuredFailureRuntime | undefined): void;
3518
+ declare function isMeasuredFailureBrainActive(): boolean;
3519
+ interface GetMeasuredFailureOpts {
3520
+ appId: string;
3521
+ archetype: IntentArchetypeName | string;
3522
+ model: string;
3523
+ }
3524
+ /**
3525
+ * alpha.73 — start the warm-up WITHOUT needing a compile to trigger it.
3526
+ *
3527
+ * The SWR posture below ("cold start returns undefined and warms in the
3528
+ * background") is right for a long-lived process and wrong for a
3529
+ * short-lived isolate, where the first compile IS most compiles. Measured on
3530
+ * playbacksam: on a cold isolate the gate was absent, `claude-haiku-4-5` led,
3531
+ * cliffed, was same-model retried and fell over to gemini — two billed
3532
+ * inferences and ~27–34s, every time an isolate is new. PB has ~1 user, so
3533
+ * its isolates are cold most of the time, which inverts the usual severity
3534
+ * ordering: this hits the LOWEST-traffic consumers hardest, and they are the
3535
+ * ones least able to absorb it.
3536
+ *
3537
+ * Kicking the fetch off at `configureBrain()` moves the refresh into the time
3538
+ * the isolate spends on everything else it does before its first compile.
3539
+ * Fire-and-forget and non-blocking: on its own this narrows the window rather
3540
+ * than closing it, which is why `awaitMeasuredFailureReady()` exists too.
3541
+ *
3542
+ * Returns the in-flight promise (or undefined when not configured / already
3543
+ * fresh) so a caller can await it. NEVER throws.
3544
+ */
3545
+ declare function prefetchMeasuredFailure(appId: string): Promise<void> | undefined;
3546
+ /**
3547
+ * alpha.73 — bounded await on the warm-up, for async callers only.
3548
+ *
3549
+ * `compile()` is synchronous and must stay so, so it cannot block on a fetch;
3550
+ * `call()` is async and is about to spend seconds on an inference, which makes
3551
+ * a few hundred milliseconds here a trivially good trade against the ~27–34s
3552
+ * and second billed inference a cold-blind gate costs.
3553
+ *
3554
+ * Deliberately bounded and deliberately silent on timeout: the gate is
3555
+ * protective, never required. If the brain is slow or down, the caller
3556
+ * proceeds un-gated exactly as it does today — this can delay a call by at
3557
+ * most `timeoutMs`, and can never fail one.
3558
+ *
3559
+ * NEVER throws.
3560
+ */
3561
+ declare function awaitMeasuredFailureReady(appId: string, timeoutMs: number): Promise<void>;
3562
+ /**
3563
+ * Sync reader. Returns the verdict for `(appId, archetype, model)` or
3564
+ * undefined (not configured / cold / below minSample / brain down).
3565
+ *
3566
+ * NEVER throws. Cold start returns undefined and warms in the background —
3567
+ * same posture as every other brain-driven lever in compile(). Async callers
3568
+ * that can afford a bounded wait should call `awaitMeasuredFailureReady()`
3569
+ * first; `call()` does.
3570
+ */
3571
+ declare function getMeasuredFailureVerdict(opts: GetMeasuredFailureOpts): MeasuredFailureVerdict | undefined;
3572
+ declare function _testResetMeasuredFailure(): void;
3573
+ declare function _testWaitForMeasuredFailureRefresh(): Promise<void>;
3574
+
3575
+ /**
3576
+ * Release C (Rung 1) — the decomposition coach's planning engine.
3577
+ *
3578
+ * Design contract §5.1: evidence-backed advisories on the existing surface —
3579
+ * "you're paying frontier prices for grunt work; here's the measured split."
3580
+ * No contract change; nothing here executes a fan-out. This module is PURE:
3581
+ * templates + arithmetic. The operator script feeds it measured surface
3582
+ * stats and evidence-picked executors; Release D's `delegate` primitive will
3583
+ * consume the SAME templates, so they live in the library, versioned.
3584
+ *
3585
+ * Honesty posture (the roster-with-receipts rule, applied to ourselves):
3586
+ *
3587
+ * - The per-step token SHARES are JUDGMENT v1 numbers — labelled as such
3588
+ * in every plan (`assumptions[]`), versioned so a future measured
3589
+ * replacement invalidates nothing silently. No consumer has fan-out
3590
+ * traffic yet (R0 shipped alpha.68, zero adopters), so there is nothing
3591
+ * to measure them from; the moment branch traffic exists, these
3592
+ * graduate per surface.
3593
+ * - Executor grounding is carried per step: 'measured' when the portfolio
3594
+ * corpus has real outcomes for (model, sub-archetype), 'judgment' when
3595
+ * the roster's archetypePerf is all we have.
3596
+ * - The coach's most credible output at low volume is "KEEP THE MONOLITH"
3597
+ * with the break-even volume stated — the never-worse floor in coach
3598
+ * form. The advisory only files when the split is MATERIAL (same $5/mo
3599
+ * felt-utility floor as promotions); the demo report renders every
3600
+ * analysis either way.
3601
+ */
3602
+
3603
+ declare const DECOMPOSITION_TEMPLATES_VERSION = "decomposition-templates-v1";
3604
+ interface DecompositionStep {
3605
+ /** Human-readable step name (stable — appears in advisories/recipes). */
3606
+ role: string;
3607
+ /** The sub-archetype this step runs as (its own learning_key downstream). */
3608
+ archetype: IntentArchetypeName;
3609
+ /**
3610
+ * Which tier runs the step. 'delegate' steps are the grunt work the coach
3611
+ * proposes moving to a cheap executor; 'anchor' steps stay on the
3612
+ * incumbent (composition is where fan-outs die — §7a — so the composer
3613
+ * anchors on the strong model by design).
3614
+ */
3615
+ tier: 'delegate' | 'anchor';
3616
+ /** Share of the monolith's INPUT tokens this step reads. JUDGMENT v1. */
3617
+ inputShare: number;
3618
+ /**
3619
+ * Tokens this step EMITS, as a share of the monolith's input (for
3620
+ * intermediate artifacts like extraction notes) — the next anchor step
3621
+ * reads these instead of the raw input. JUDGMENT v1.
3622
+ */
3623
+ emitsShareOfInput: number;
3624
+ /** Share of the monolith's OUTPUT tokens this step produces (0 for
3625
+ * intermediate steps; the anchor composer typically carries 1). */
3626
+ outputShare: number;
3627
+ }
3628
+ interface DecompositionTemplate {
3629
+ archetype: IntentArchetypeName;
3630
+ steps: DecompositionStep[];
3631
+ rationale: string;
3632
+ version: typeof DECOMPOSITION_TEMPLATES_VERSION;
3633
+ }
3634
+ /**
3635
+ * v1 covers the three judgment-heavy archetypes with a clear split shape.
3636
+ * Every share number below is a judgment estimate, stated in the plan's
3637
+ * assumptions — they exist to make the ARITHMETIC honest, not to claim
3638
+ * precision the corpus doesn't have yet.
3639
+ */
3640
+ declare const DECOMPOSITION_TEMPLATES: Partial<Record<IntentArchetypeName, DecompositionTemplate>>;
3641
+ interface SurfaceStats {
3642
+ appId: string;
3643
+ archetype: IntentArchetypeName | string;
3644
+ /** The model serving the monolith today (most-served in the window). */
3645
+ incumbentModel: string;
3646
+ nCalls: number;
3647
+ windowDays: number;
3648
+ avgTokensIn: number;
3649
+ avgTokensOut: number;
3650
+ }
3651
+ interface ExecutorCandidate {
3652
+ modelId: string;
3653
+ /** archetypePerf score on the STEP's archetype. */
3654
+ perfScore: number;
3655
+ grounding: 'measured' | 'judgment';
3656
+ costInputPer1m: number;
3657
+ costOutputPer1m: number;
3658
+ }
3659
+ interface ModelPricing {
3660
+ costInputPer1m: number;
3661
+ costOutputPer1m: number;
3662
+ }
3663
+ interface PlannedStep extends DecompositionStep {
3664
+ /** The picked executor ('delegate' steps) or the incumbent ('anchor'). */
3665
+ executorModel: string;
3666
+ executorGrounding: 'measured' | 'judgment';
3667
+ executorPerfScore: number | null;
3668
+ projectedCostPerCallUsd: number;
3669
+ }
3670
+ interface DecompositionPlan {
3671
+ appId: string;
3672
+ archetype: string;
3673
+ incumbentModel: string;
3674
+ template: DecompositionTemplate;
3675
+ steps: PlannedStep[];
3676
+ monolithCostPerCallUsd: number;
3677
+ splitCostPerCallUsd: number;
3678
+ savingPerCallUsd: number;
3679
+ monthlyCalls: number;
3680
+ projectedMonthlySavingUsd: number;
3681
+ /** Monthly calls at which the split clears the materiality floor. null
3682
+ * when the split doesn't save per-call at all (then no volume helps). */
3683
+ breakEvenMonthlyCalls: number | null;
3684
+ verdict: 'split-pays' | 'keep-monolith';
3685
+ verdictReason: string;
3686
+ /** Judgment inputs, stated. Every number that is not measured is here. */
3687
+ assumptions: string[];
3688
+ }
3689
+ declare const COACH_CFG: {
3690
+ /** Same felt-utility floor as promotions (alpha.67 family). */
3691
+ minMonthlySavingUsd: number;
3692
+ /** Executor must clear this archetypePerf on the step's archetype —
3693
+ * same floor as the translator/advisor (ARCHETYPE_FLOOR_DEFAULT). */
3694
+ executorPerfFloor: number;
3695
+ daysPerMonth: number;
3696
+ };
3697
+ interface PlanDecompositionArgs {
3698
+ stats: SurfaceStats;
3699
+ incumbentPricing: ModelPricing;
3700
+ /**
3701
+ * Evidence-picked executor per step archetype. Return undefined when no
3702
+ * candidate clears the perf floor — the plan then keeps that step on the
3703
+ * incumbent and says so (a coach must not route grunt work to a model
3704
+ * that can't do it just because it is cheap).
3705
+ */
3706
+ pickExecutor: (archetype: IntentArchetypeName) => ExecutorCandidate | undefined;
3707
+ cfg?: Partial<typeof COACH_CFG>;
3708
+ }
3709
+ declare function planDecomposition(args: PlanDecompositionArgs): DecompositionPlan | undefined;
282
3710
 
283
3711
  /**
284
3712
  * @warmdrift/kgauto v2 — prompt compiler + central learning brain.
@@ -326,4 +3754,4 @@ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: Model
326
3754
  */
327
3755
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
328
3756
 
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 };
3757
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, COST_RANKING_REFERENCE_SHAPE, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, type CreateDelegateOpts, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DELEGATE_TOOL_DEFINITION, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type DelegateHandle, type DelegateRefusalReason, type DelegateResult, type DelegateToolArgs, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, chainProviderSpread, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, createDelegate, deriveFamilyFromModelId, deriveOwnership, estimateChainCostUsd, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isDelegateEnabledFromEnv, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };