@warmdrift/kgauto-compiler 2.0.0-alpha.6 → 2.0.0-alpha.61

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 (50) hide show
  1. package/README.md +158 -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 +189 -0
  5. package/dist/brain-proxy.mjs +6 -0
  6. package/dist/chunk-3RMLZCUK.mjs +190 -0
  7. package/dist/chunk-IIMPJZNH.mjs +694 -0
  8. package/dist/chunk-IUWFML6Z.mjs +165 -0
  9. package/dist/chunk-NBO4R5PC.mjs +313 -0
  10. package/dist/chunk-P3TOAEG4.mjs +56 -0
  11. package/dist/chunk-QKXTMVCT.mjs +1470 -0
  12. package/dist/chunk-RO22VFIF.mjs +29 -0
  13. package/dist/glassbox/index.d.mts +59 -0
  14. package/dist/glassbox/index.d.ts +59 -0
  15. package/dist/glassbox/index.js +312 -0
  16. package/dist/glassbox/index.mjs +12 -0
  17. package/dist/glassbox-routes/format.d.mts +24 -0
  18. package/dist/glassbox-routes/format.d.ts +24 -0
  19. package/dist/glassbox-routes/format.js +86 -0
  20. package/dist/glassbox-routes/format.mjs +18 -0
  21. package/dist/glassbox-routes/index.d.mts +191 -0
  22. package/dist/glassbox-routes/index.d.ts +191 -0
  23. package/dist/glassbox-routes/index.js +2714 -0
  24. package/dist/glassbox-routes/index.mjs +663 -0
  25. package/dist/glassbox-routes/react/index.d.mts +74 -0
  26. package/dist/glassbox-routes/react/index.d.ts +74 -0
  27. package/dist/glassbox-routes/react/index.js +819 -0
  28. package/dist/glassbox-routes/react/index.mjs +754 -0
  29. package/dist/index.d.mts +2236 -17
  30. package/dist/index.d.ts +2236 -17
  31. package/dist/index.js +7402 -1596
  32. package/dist/index.mjs +3580 -164
  33. package/dist/ir-DAKlQsVb.d.mts +1386 -0
  34. package/dist/ir-DmUuJsWc.d.ts +1386 -0
  35. package/dist/key-health.d.mts +131 -0
  36. package/dist/key-health.d.ts +131 -0
  37. package/dist/key-health.js +215 -0
  38. package/dist/key-health.mjs +6 -0
  39. package/dist/profiles.d.mts +292 -2
  40. package/dist/profiles.d.ts +292 -2
  41. package/dist/profiles.js +1081 -16
  42. package/dist/profiles.mjs +9 -1
  43. package/dist/types-B8X1Pyhx.d.ts +149 -0
  44. package/dist/types-CssWqd0X.d.mts +131 -0
  45. package/dist/types-DR62iPcO.d.ts +131 -0
  46. package/dist/types-MRMBUqzY.d.mts +149 -0
  47. package/package.json +54 -8
  48. package/dist/chunk-MBEI5UOM.mjs +0 -409
  49. package/dist/profiles-CQnLkQ7b.d.ts +0 -611
  50. package/dist/profiles-zm6diETo.d.mts +0 -611
package/dist/index.d.ts CHANGED
@@ -1,6 +1,11 @@
1
- import { M as ModelProfile, C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory } from './profiles-CQnLkQ7b.js';
2
- export { f as ALIASES, g as CacheStrategy, h as CallAttempt, i as CallError, j as CliffRule, k as Constraints, H as HistoryCachePolicy, I as IntentDeclaration, L as LoweringSpec, l as Message, m as MutationApplied, n as NormalizedTokens, o as PromptSection, p as Provider, q as RecoveryRule, S as StructuredOutputCapability, r as SystemPromptMode, T as ToolCall, s as ToolDefinition, t as allProfiles, u as getProfile, v as profilesByProvider, w as tryGetProfile } from './profiles-CQnLkQ7b.js';
3
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, IntentArchetypeName, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-DmUuJsWc.js';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-DmUuJsWc.js';
3
+ import { ModelProfile, ArchetypeConvention } from './profiles.js';
4
+ export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.js';
5
+ export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.js';
6
+ export { KeyHealthConfig, KeyHealthProvider, KeyHealthResponseBody, KeyHealthResult, KeyHealthRoute, createKeyHealthRoute } from './key-health.js';
7
+ import { IntentArchetypeName } from './dialect.js';
8
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
4
9
 
5
10
  /**
6
11
  * compile() — the main orchestrator.
@@ -19,6 +24,15 @@ interface CompileOptions {
19
24
  toolRelevanceThreshold?: number;
20
25
  /** History compression — turns count threshold (default 8). */
21
26
  compressHistoryAfter?: number;
27
+ /**
28
+ * History compression — token threshold (alpha.7). When total history
29
+ * tokens exceed this AND there are more recent turns to keep, compress
30
+ * even when count threshold is below `compressHistoryAfter`. Catches
31
+ * fat-message bloat (tool-using agents pack many tool-call/result pairs
32
+ * into single assistant messages — count stays low, tokens explode).
33
+ * Default undefined (disabled — backward-compatible).
34
+ */
35
+ compressHistoryAboveTokens?: number;
22
36
  /**
23
37
  * Consumer-declared policy. Filters blocked models, enforces cost
24
38
  * ceiling, boosts preferred. See CompilePolicy in ir.ts.
@@ -42,6 +56,15 @@ interface ExecuteOptions {
42
56
  apiKeys?: ApiKeys;
43
57
  fetchImpl?: typeof fetch;
44
58
  providerOverrides?: ProviderOverrides;
59
+ /**
60
+ * alpha.34. When supplied AND the chosen provider supports streaming, the
61
+ * execute() per-provider branch switches to SSE wire format and invokes
62
+ * `onChunk(delta)` once per text-delta event. Single-shot behavior
63
+ * preserved when omitted (current consumers unaffected). Wired from
64
+ * `CallOptions.onChunk` by `call()` after gating on `profile.streaming`
65
+ * and `!opts.noStream`.
66
+ */
67
+ onChunk?: (chunk: string) => void;
45
68
  }
46
69
  interface ExecuteOk {
47
70
  ok: true;
@@ -81,17 +104,291 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
81
104
  * exhausted without success.
82
105
  */
83
106
  declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
107
+ /** Served-side result the AI-SDK consumer already holds from streamText. */
108
+ interface ProbeShadowServed {
109
+ /** Model id that actually served the user (becomes `current_model` on the row). */
110
+ model: string;
111
+ /** The served response text (stored as a preview; never the prompt). */
112
+ responseText: string;
113
+ /** Served prompt tokens (AI SDK `usage.promptTokens`). */
114
+ tokensIn: number;
115
+ /** Served completion tokens (AI SDK `usage.completionTokens`). */
116
+ tokensOut: number;
117
+ /** The user's actual wait in ms (alpha.46 served-latency axis). */
118
+ latencyMs: number;
119
+ }
120
+ /** Options for the standalone {@link probeShadow} export. */
121
+ interface ProbeShadowOptions {
122
+ /** The served leg the consumer supplies; kgauto runs the candidate leg. */
123
+ served: ProbeShadowServed;
124
+ /** Model id(s)/family alias(es) to shadow-test against the served model. */
125
+ candidates: string | string[];
126
+ /** Probability [0,1] a given call fires a probe. Default 0.05; pin 1 for dogfood. */
127
+ sampleRate?: number;
128
+ /** Phase 1 = 'off' (offline rollup). 'opus' inline judge is Phase 2. Default 'off'. */
129
+ judge?: 'off' | 'opus';
130
+ /** Override API keys (defaults: process.env). Gates candidate reachability. */
131
+ apiKeys?: ApiKeys;
132
+ /** Override fetch (for tests / custom transport). */
133
+ fetchImpl?: typeof fetch;
134
+ /** Provider-specific request fields shallow-merged into the candidate request. */
135
+ providerOverrides?: ProviderOverrides;
136
+ /** Forwarded to compile() for the candidate run (match the served-side compile). */
137
+ policy?: CompilePolicy;
138
+ toolRelevanceThreshold?: number;
139
+ compressHistoryAfter?: number;
140
+ }
141
+ /**
142
+ * s54 — standalone full-IR shadow probe for AI-SDK consumers (tt-intel hunt, IC
143
+ * chat) that own their own streamText round-trip and never call call(). Fire it
144
+ * from the streamText `onFinish` callback, wrapped in the platform's
145
+ * `waitUntil()` / `after()`, so it runs after the response is flushed — no
146
+ * blocking, no `sync:true`, no teardown race (cleaner than call()'s in-process
147
+ * fire-and-forget for Edge runtimes; L-086).
148
+ *
149
+ * Runs the SAME candidate loop as the call()-inline probe ({@link
150
+ * runProbeCandidates}): same gates (sample, self-skip, G4 judge-self,
151
+ * reachability, G6), same fidelity=1.0 full-IR rows, same alpha.46 latency
152
+ * capture. The consumer supplies the served leg it already has; kgauto runs the
153
+ * candidate(s) and writes the `probe_outcomes` row.
154
+ *
155
+ * Requires `configureBrain()` to have been called (same as call()).
156
+ * Fire-and-forget: never throws into the caller.
157
+ *
158
+ * @example
159
+ * const result = streamText({ model, system, messages,
160
+ * onFinish: ({ text, usage }) => {
161
+ * after(() => probeShadow(ir, {
162
+ * served: { model: servedModelId, responseText: text,
163
+ * tokensIn: usage.promptTokens, tokensOut: usage.completionTokens,
164
+ * latencyMs: Date.now() - t0 },
165
+ * candidates: ['deepseek-v4-pro'], sampleRate: 0.05,
166
+ * }));
167
+ * },
168
+ * });
169
+ */
170
+ declare function probeShadow(ir: PromptIR, opts: ProbeShadowOptions): Promise<void>;
171
+
172
+ /**
173
+ * alpha.33 — AI-SDK streamText helpers.
174
+ *
175
+ * The cross-consumer pattern surfaced 2026-05-20 (`streamText-cache-marker-
176
+ * propagation-gap` on `command-center/interfaces/kgauto.md ## Requested`):
177
+ * AI-SDK consumers using `streamText({ system: <string>, messages:
178
+ * convertToModelMessages(messages), model })` silently drop the Anthropic
179
+ * `cache_control` markers the compiler emits on `result.request.messages`.
180
+ * Two losses on that line:
181
+ * (a) `convertToModelMessages()` reads raw inputs not the lowered output,
182
+ * dropping per-message providerOptions; and
183
+ * (b) `streamText({ system: '<string>' })` strips any providerOptions
184
+ * on the system prefix.
185
+ *
186
+ * Net effect prior to this surface: `cache_read_input_tokens = 0` across
187
+ * every measured production call by IC + tt-intel even though both
188
+ * consumers had `historyCachePolicy: { strategy: 'all-but-latest' }` wired
189
+ * since alpha.5. The compiler did the right thing; the consumer integration
190
+ * pattern lost the markers at the wire boundary.
191
+ *
192
+ * This helper closes the gap. Pass the consumer's already-converted messages
193
+ * + the kgauto CompileResult and get back a `{ system, messages }` pair
194
+ * with cacheControl re-attached at the deterministic indices the compiler
195
+ * computed (`diagnostics.historyCacheMarkIndex` + `systemMessages` with
196
+ * its own cacheControl markers).
197
+ *
198
+ * No I/O. Pure transform. Idempotent — calling twice with the same inputs
199
+ * produces structurally-identical output.
200
+ */
201
+
202
+ /**
203
+ * AI-SDK-shaped converted-message structure. Matches what
204
+ * `convertToModelMessages()` returns at the wire layer. We don't import
205
+ * the AI-SDK type to avoid pulling that dep into the kgauto-compiler
206
+ * package — consumers pass their own already-converted messages.
207
+ */
208
+ interface AISDKConvertedMessage {
209
+ role: 'system' | 'user' | 'assistant' | 'tool';
210
+ content: unknown;
211
+ providerOptions?: {
212
+ anthropic?: {
213
+ cacheControl?: {
214
+ type: 'ephemeral';
215
+ };
216
+ };
217
+ };
218
+ }
219
+ /**
220
+ * Result of `attachCacheControlToStreamTextInput()` — ready to spread into
221
+ * `streamText(...)` directly.
222
+ *
223
+ * The `system` field is either the structured `SystemModelMessage[]` form
224
+ * (when the compiler computed at least one cacheable section + chose
225
+ * Anthropic) or the flat-string concatenation (when no cacheable sections
226
+ * exist OR the provider isn't Anthropic). Consumers can pass either form
227
+ * to `streamText({ system })` — the AI-SDK accepts both.
228
+ */
229
+ interface AttachCacheControlResult {
230
+ system: string | SystemModelMessage[];
231
+ messages: AISDKConvertedMessage[];
232
+ }
233
+ /**
234
+ * Attach Anthropic cache_control markers to a streamText input that the
235
+ * consumer has already prepared via `convertToModelMessages()`. Reads
236
+ * `result.diagnostics.historyCacheMarkIndex` for the position-on-history
237
+ * marker and `result.systemMessages` for the per-section system markers.
238
+ *
239
+ * The flat-string `system` form is returned when:
240
+ * - the compiler produced no `systemMessages` (e.g., zero sections kept), or
241
+ * - the chosen provider is not Anthropic, so cacheControl wouldn't
242
+ * achieve anything at the wire layer (other providers cache implicitly
243
+ * based on prefix shape, no marker needed).
244
+ *
245
+ * Otherwise the structured `SystemModelMessage[]` form is returned —
246
+ * preserves the per-section cacheControl markers across `streamText`.
247
+ *
248
+ * @param result - kgauto CompileResult from `compile(ir, opts)`
249
+ * @param convertedMessages - the consumer's already-converted messages
250
+ * (from `convertToModelMessages(rawMessages)` in their AI-SDK call site)
251
+ * @returns `{ system, messages }` ready to spread into `streamText(...)`
252
+ */
253
+ declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
84
254
 
85
255
  /**
86
- * Brain client fire-and-forget telemetry to the central kgauto Supabase.
256
+ * alpha.52official AI-SDK-v6 compile adapter + compile-then-discard guard.
257
+ *
258
+ * Until now each AI-SDK consumer (tt-intel, IC) hand-rolled this adapter in
259
+ * its own `lib/kgauto-v2/index.ts`: `compile()` → reassemble the system param
260
+ * per provider → extract kept tool names per provider → re-derive the history
261
+ * cache-mark index (a copy of the compiler's own `historyCacheMarkIndex`
262
+ * logic — drift-prone). This centralizes that boilerplate and DRYs the two
263
+ * near-identical wrappers.
264
+ *
265
+ * It also closes the compile-then-discard hole. The discard pattern is:
266
+ *
267
+ * const c = compileForAISDKv6(ir); // compile runs
268
+ * const out = await generateText({ // …but a hand-built prompt
269
+ * model: getModel(otherId), prompt }); // + a DIFFERENT model run
270
+ * await record({ handle: c.handle, … }); // brain row attributed to `c`
87
271
  *
88
- * The brain is the centralized learning store. Apps POST outcomes here;
89
- * mutations flow back through a separate pull (in v2.1).
272
+ * The recorded row's `mutations_applied` / `estimated_tokens_in` /
273
+ * `system_prompt_chars` then describe a compile that never reached the wire.
274
+ * A library-level runtime guard could NOT catch this while the adapter lived
275
+ * in consumer code (the consumer wrapper always reads `compile()`'s result to
276
+ * build its own object, so any getter there is "consumed" every time,
277
+ * regardless of whether the final caller used the wrapper output). With the
278
+ * adapter IN the library, the object the FINAL caller reads is library-owned,
279
+ * so consume-tracking getters on `.system` / `.model` / `.raw` detect non-use
280
+ * and `record()` warns. See `interfaces/kgauto.md` (## Requested:
281
+ * `compiled-output-discarded-guard`).
282
+ *
283
+ * The guard is OPT-IN-BY-USE: only `compileForAISDKv6` arms tracking, so
284
+ * `call()` paths and raw `compile()` users never see a false warning.
285
+ */
286
+
287
+ interface CompileForAISDKv6Result {
288
+ /**
289
+ * Pass to `streamText`/`generateText({ model })` — the caller maps this id
290
+ * to an AI-SDK `LanguageModel`. Reading this marks the compile "consumed"
291
+ * (silences the compile-then-discard guard).
292
+ */
293
+ readonly model: string;
294
+ /**
295
+ * System parameter for `streamText`/`generateText({ system })`. Returns the
296
+ * structured `SystemModelMessage[]` form when the target is Anthropic AND a
297
+ * cacheable section exists (preserves the cache_control marker across the
298
+ * wire); a flat concatenated string otherwise. Reading this marks
299
+ * "consumed". (Same rule as `attachCacheControlToStreamTextInput`.)
300
+ */
301
+ readonly system: string | SystemModelMessage[];
302
+ /**
303
+ * The raw kgauto `CompileResult` — for `attachCacheControlToStreamTextInput(raw, msgs)`
304
+ * and `probeShadow(raw.ir-equivalent, …)` paths. Reading this marks
305
+ * "consumed" (it means you're using the compile output via the raw result).
306
+ */
307
+ readonly raw: CompileResult;
308
+ /** Tool names that survived budget + relevance — filter your SDK tool map to these. */
309
+ keptToolNames: Set<string>;
310
+ /** providerOptions for `streamText` — Anthropic cache_control on the cacheable prefix. Undefined otherwise. */
311
+ providerOptions?: {
312
+ anthropic?: {
313
+ cacheControl?: {
314
+ type: 'ephemeral';
315
+ };
316
+ };
317
+ };
318
+ /**
319
+ * Index (into post-strip history) for the Anthropic history cache marker
320
+ * (alpha.33). Mirror of `result.diagnostics.historyCacheMarkIndex` — no
321
+ * consumer re-derivation needed. Undefined when no marker fires, and (since
322
+ * alpha.55) always undefined for non-Anthropic targets: the marker is an
323
+ * Anthropic wire concept, other providers cache prefixes implicitly. The
324
+ * ungated value remains on `diagnostics.historyCacheMarkIndex`.
325
+ */
326
+ historyCacheMarkIndex?: number;
327
+ /** Compile handle — pass to `record()` after the call. */
328
+ handle: string;
329
+ /** Mutation ids the compiler fired (informational). */
330
+ mutationsApplied: string[];
331
+ /** Best-practice advisories (alpha.6). Empty when none fired. */
332
+ advisories: BestPracticeAdvisory[];
333
+ /** Compiler diagnostics + the three commonly-logged top-level fields. */
334
+ diagnostics: CompileResult['diagnostics'] & {
335
+ targetProvider: string;
336
+ estimatedCostUsd: number;
337
+ fallbackChain: string[];
338
+ };
339
+ /** The compiled IR — pass to `probeShadow(ir, …)` in `onFinish` (alpha.48). */
340
+ ir: PromptIR;
341
+ }
342
+ /**
343
+ * Compile a `PromptIR` and lower it to an AI-SDK-v6 `streamText`/`generateText`
344
+ * bundle. Replaces the hand-rolled per-consumer adapter.
90
345
  *
91
- * Design: never blocks the caller. Failures are silent (logged via optional
92
- * onError hook). Uses fetch() works in Node 18+, Edge runtimes, and browsers.
346
+ * Arms the compile-then-discard guard: read `.system` / `.model` / `.raw` to
347
+ * serve the call. If you `record()` the handle without reading any of them,
348
+ * `record()` emits a dev-mode warning that the compile was discarded.
93
349
  */
350
+ declare function compileForAISDKv6(ir: PromptIR, opts?: CompileOptions): CompileForAISDKv6Result;
94
351
 
352
+ /**
353
+ * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
354
+ * perf / pricing / models registry). Enabled by default when endpoint is
355
+ * set; per-table opt-out via explicit `false`.
356
+ *
357
+ * Locked via /plan-eng-review 2026-05-15 (decision D3). Structured group
358
+ * keeps the BrainConfig surface clean as more brain-driven tables ship.
359
+ */
360
+ interface BrainQueryConfig {
361
+ /** Default true when endpoint set. Brain-driven fallback chains. */
362
+ chains?: boolean;
363
+ /** Default true when endpoint set. Brain-driven archetype perf scores. */
364
+ perf?: boolean;
365
+ /** Default true when endpoint set. Brain-driven pricing with at-time resolution. */
366
+ pricing?: boolean;
367
+ /** Default true when endpoint set. Brain-driven model registry + aliases. */
368
+ models?: boolean;
369
+ /**
370
+ * alpha.38 — opt-in compile-time advisor for stale exclusions. Default
371
+ * `true` when endpoint is set. When enabled, the library reads
372
+ * `exclusion_findings` from the central kgauto-dashboard for the consumer's
373
+ * `app_id` (no consumer-side proxy work required) and surfaces a
374
+ * `stale-exclusion-candidate` advisory when compile()'s archetype has a
375
+ * recommend-probe finding open. Set `false` to silence (no fetch, no
376
+ * advisory).
377
+ */
378
+ findingsExclusions?: boolean;
379
+ /** SWR window in ms. Default 300_000 (5 min). */
380
+ cacheTtlMs?: number;
381
+ /** Override the GET URL when the read endpoint differs from the write one.
382
+ * Defaults to `${endpoint}/v2/config` when omitted. */
383
+ configEndpoint?: string;
384
+ /**
385
+ * alpha.38 — override the findings endpoint when the consumer wants to
386
+ * proxy `exclusion_findings` reads through their own service rather than
387
+ * reading directly from the kgauto-dashboard. Library appends `?app_id=X`.
388
+ * Defaults to `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`.
389
+ */
390
+ findingsEndpoint?: string;
391
+ }
95
392
  interface BrainConfig {
96
393
  /** Brain HTTP endpoint base URL (e.g., https://kgauto-brain.vercel.app/api). */
97
394
  endpoint: string;
@@ -103,17 +400,307 @@ interface BrainConfig {
103
400
  sync?: boolean;
104
401
  /** Optional fetch override (for tests). */
105
402
  fetchImpl?: typeof fetch;
403
+ /** alpha.11 — brain-query mode for config tables. Default-on per table
404
+ * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
405
+ brainQuery?: BrainQueryConfig;
406
+ /**
407
+ * alpha.52 — emit a dev-mode `console.warn` when a `compileForAISDKv6()`
408
+ * result is passed to record() but its `.system` / `.model` / `.raw` were
409
+ * never read (the compile-then-discard pattern: the recorded brain row's
410
+ * `mutations_applied` / `estimated_tokens_in` / `system_prompt_chars`
411
+ * describe a compile that did NOT shape the served call). Default: warn
412
+ * when `NODE_ENV !== 'production'`, silent in production. Set `true` to
413
+ * force-on (e.g. a prod audit window) or `false` to silence. No-op for
414
+ * `call()` paths and raw `compile()` users — only `compileForAISDKv6`
415
+ * arms the tracking, so good actors never see a false warning.
416
+ */
417
+ warnOnDiscardedCompile?: boolean;
418
+ /**
419
+ * alpha.59 — per-leg timeout (ms) applied to every brain WRITE POST
420
+ * (record() primary + advisory secondary, recordOutcome(),
421
+ * recordShadowProbe()) via `AbortSignal.timeout`. Default 10000.
422
+ *
423
+ * Why: `sync: true` puts these fetches on the USER path (Edge consumers
424
+ * await record() before responding), and alpha.56's representation
425
+ * passthrough added a second sequential POST (advisory secondary) to that
426
+ * same path — an unbounded hang on either leg holds the user to the Edge
427
+ * limit (GE's `brainconfig-first-class-timeout` filing; GE bounded it at
428
+ * 3s via a hand-rolled fetchImpl wrapper every sync consumer had to
429
+ * rediscover).
430
+ *
431
+ * A fired timeout follows each leg's existing degraded-brain path
432
+ * (fire-and-forget: swallowed via onError; sync: `persistence_failed`
433
+ * result — never a throw into the user path). Wraps the configured
434
+ * `fetchImpl` rather than replacing it, so it composes with
435
+ * consumer-supplied impls. Set `0` to disable (pre-alpha.59 unbounded
436
+ * behavior). Brain-query reads (config tables) are cached + SWR and are
437
+ * not affected.
438
+ */
439
+ timeoutMs?: number;
106
440
  }
107
441
  declare function configureBrain(config: BrainConfig): void;
108
442
  declare function clearBrain(): void;
443
+ interface BrainHealthSnapshot {
444
+ configState: 'configured' | 'not_configured';
445
+ /** Host of the configured endpoint (never the full URL — no secrets/paths). */
446
+ endpointHost?: string;
447
+ /** True when writes are awaited (BrainConfig.sync). */
448
+ sync: boolean;
449
+ /** Write POSTs attempted (all routes, primary + secondary). */
450
+ sent: number;
451
+ /** Write POSTs acknowledged 2xx without redirect. */
452
+ acked: number;
453
+ /** Write POSTs that failed (non-2xx, redirect, timeout, network throw). */
454
+ failed: number;
455
+ /** Subset of `failed` that failed the redirect check (middleware-drift class). */
456
+ redirected: number;
457
+ lastAckAt?: string;
458
+ lastFailureAt?: string;
459
+ /** Most recent failure message, truncated. */
460
+ lastFailure?: string;
461
+ deadLetterCount: number;
462
+ }
463
+ interface BrainDeadLetterEntry {
464
+ /** Brain route segment the payload was bound for. */
465
+ route: 'outcomes' | 'compile_outcome_quality' | 'probe_outcomes' | 'compile_outcome_advisories';
466
+ /**
467
+ * Endpoint the payload was originally bound for. Flush replays ONLY entries
468
+ * matching the currently-configured endpoint — a reconfigure must never
469
+ * replay another brain's payloads into the new target (caught live by
470
+ * smoke-brain-timeout: a hung-socket test payload auto-flushed into the
471
+ * real brain after the smoke re-pointed configureBrain).
472
+ */
473
+ endpoint: string;
474
+ /** The exact JSON body that failed to land. */
475
+ payload: unknown;
476
+ failedAt: string;
477
+ /** Delivery attempts so far (1 = the original failed POST). */
478
+ attempts: number;
479
+ lastError: string;
480
+ }
109
481
  /**
110
- * Record the outcome of a compiled call. Fire-and-forget by default.
111
- *
112
- * Returns a Promise so callers in `sync` mode can await; in async mode the
113
- * promise resolves immediately (after the request is queued) and any
114
- * network error is swallowed/forwarded to onError.
482
+ * Process-local brain write delivery ledger. `acked` is the only number that
483
+ * means "a row landed" — fire-and-forget callers that need delivery evidence
484
+ * read this (or set `BrainConfig.sync`). Cheap enough to attach to any debug
485
+ * or health surface the consumer already exposes.
486
+ */
487
+ declare function brainHealth(): BrainHealthSnapshot;
488
+ /** Read-only view of the pending dead-letter (for consumer-side persistence). */
489
+ declare function peekBrainDeadLetter(): readonly BrainDeadLetterEntry[];
490
+ /**
491
+ * Replay pending dead-letter payloads against the configured brain. Delivered
492
+ * entries are removed; failures increment `attempts` and entries are dropped
493
+ * after 3 total attempts (bounded — never an infinite retry, per the Redis
494
+ * DLQ rule). Safe to call any time; no-ops when unconfigured or already
495
+ * flushing. Also runs opportunistically after any successful write.
115
496
  */
497
+ declare function flushBrainDeadLetter(): Promise<{
498
+ attempted: number;
499
+ delivered: number;
500
+ remaining: number;
501
+ }>;
116
502
  declare function record(input: RecordInput): Promise<void>;
503
+ /**
504
+ * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
505
+ *
506
+ * Exported so consumer proxies can `import { OutcomePayload } from
507
+ * '@warmdrift/kgauto-compiler'` instead of redefining the shape — that way
508
+ * TypeScript catches future schema additions (cache fields, advisory
509
+ * telemetry, etc.) at consumer build time, not silently at runtime.
510
+ *
511
+ * **Forward-compat rule:** consumer proxies should pass the body through to
512
+ * Supabase rather than reconstructing field-by-field. The recommended shape
513
+ * is `const row = { ...body }` (or `await supabase.from('compile_outcomes')
514
+ * .insert(body)` directly). Filtering proxies break schema evolution
515
+ * silently — see s17 root-cause investigation 2026-05-10.
516
+ */
517
+ interface OutcomePayload {
518
+ handle: string;
519
+ app_id?: string;
520
+ intent_archetype?: string;
521
+ /** The model that ACTUALLY RAN (post-fallback). */
522
+ model?: string;
523
+ /** The model v2 compile() originally targeted. NULL when no fallback. */
524
+ requested_model?: string;
525
+ provider?: string;
526
+ shape_key?: string;
527
+ learning_key?: string;
528
+ mutations_applied: string[];
529
+ tokens_in: number;
530
+ tokens_out: number;
531
+ estimated_tokens_in?: number;
532
+ latency_ms: number;
533
+ success: boolean;
534
+ empty_response: boolean;
535
+ error_type?: string;
536
+ tools_called?: string[];
537
+ oracle_score?: number;
538
+ oracle_dimensions?: Record<string, number>;
539
+ oracle_rationale?: string;
540
+ prompt_preview?: string;
541
+ response_preview?: string;
542
+ dialect_version: string;
543
+ cache_read_input_tokens?: number;
544
+ cache_creation_input_tokens?: number;
545
+ cost_usd_actual?: number;
546
+ ttft_ms?: number;
547
+ history_cacheable_tokens?: number;
548
+ effort?: string;
549
+ history_tokens_at_compile?: number;
550
+ /**
551
+ * Mirrors `ir.constraints.toolOrchestration` from compile time. NULL when
552
+ * the consumer hadn't adopted the constraint (pre-alpha.20). Powers
553
+ * per-mode model-perf queries on the brain (the L-040 parallel-tool
554
+ * cliff lumps DeepSeek sequential perf with parallel without this).
555
+ */
556
+ tool_orchestration?: 'parallel' | 'sequential' | 'either' | null;
557
+ finish_reason?: string;
558
+ total_ms?: number;
559
+ tools_count?: number;
560
+ history_depth?: number;
561
+ system_prompt_chars?: number;
562
+ fell_over_from?: string;
563
+ fallback_reason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
564
+ /**
565
+ * Per-call SectionRewrite[] captured at compile time. Omitted (sent as
566
+ * undefined → stored NULL) when no rewrites fired. Powers cross-app
567
+ * learning aggregates ("rule X fired N times on (app, model, archetype),
568
+ * downstream outcome quality lifted by M points").
569
+ */
570
+ section_rewrites_applied?: SectionRewrite[] | null;
571
+ }
572
+ /**
573
+ * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
574
+ *
575
+ * Fires after the consumer's UX surfaces an approve/reject event (e.g., user
576
+ * clicks Approve on a hunt result). Joins to the original `compile_outcomes`
577
+ * row via outcomeId — enables per-(model, archetype) approve-rate measurement
578
+ * once N ≥ 10 outcomes accumulate.
579
+ *
580
+ * Fire-and-forget by default (matches record() semantics). Set BrainConfig.sync
581
+ * = true for runtime contexts that can't tolerate fire-and-forget teardown
582
+ * (Vercel Edge, Cloudflare Workers, AWS Lambda) — see L-086.
583
+ *
584
+ * Returns (alpha.61): `{ok: true}` only when the POST was acknowledged 2xx
585
+ * (sync mode); `{ok: 'queued'}` in fire-and-forget mode (handed to the
586
+ * runtime, NOT acked — read `brainHealth()` for delivery evidence);
587
+ * `{ok: false, reason}` on known failure. Never throws.
588
+ */
589
+ declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
590
+ /**
591
+ * True when the active brain config requests synchronous (awaited) writes.
592
+ * call()'s shadow-probe path reads this to decide whether to await the probe
593
+ * (Edge/Worker/Lambda — L-086) or fire-and-forget (Node). False when no brain
594
+ * is configured.
595
+ */
596
+ declare function isBrainSync(): boolean;
597
+ /**
598
+ * Full-IR inline shadow-probe record input (Shape B, Phase 1 — s51). Carries
599
+ * ONLY response previews + metadata; the prompt (system/context/payload) is
600
+ * never included — `promptHash` is an irreversible grouping key, not content.
601
+ */
602
+ interface ShadowProbeRecordInput {
603
+ appId: string;
604
+ archetype: string;
605
+ family: string;
606
+ candidateModel: string;
607
+ currentModel: string;
608
+ /** Irreversible grouping hash (NOT the prompt). */
609
+ promptHash: string;
610
+ /** Served model's response, truncated (RESPONSE text only — never the prompt). */
611
+ currentResponsePreview?: string;
612
+ /** Candidate model's response, truncated. */
613
+ candidateResponsePreview?: string;
614
+ tokensCurrentIn?: number;
615
+ tokensCurrentOut?: number;
616
+ tokensCandidateIn?: number;
617
+ tokensCandidateOut?: number;
618
+ /**
619
+ * Wall-clock latency of the served call, ms (alpha.46). The third swap-decision
620
+ * axis alongside quality + cost — a verdict needs to know the candidate is
621
+ * slower, not just better/cheaper. Served latency mirrors
622
+ * `compile_outcomes.latency_ms`; carried here so a probe row is self-contained.
623
+ */
624
+ latencyCurrentMs?: number;
625
+ /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
626
+ latencyCandidateMs?: number;
627
+ /**
628
+ * alpha — probe-row class (migration 029; `candidate_error` added by 032).
629
+ * Defaults to `'completed'` (the pre-029 row shape: candidate ran, columns
630
+ * populated). `'aborted_latency_budget'` and `'skipped_slow_tier_sync'` are
631
+ * DIAGNOSTIC rows from sync-mode latency protection; `'candidate_error'`
632
+ * (alpha.53) is the failed-candidate diagnostic — the candidate call
633
+ * errored, with the error class + latency-at-death recorded instead of
634
+ * silence (the IC demo-night probe deaths were invisible for ~90 min under
635
+ * the old record-no-row rule). Diagnostic rows carry no candidate response
636
+ * and no verdict — no false quality signal. A verdict rollup MUST filter to
637
+ * `outcome='completed'`.
638
+ */
639
+ outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
640
+ /**
641
+ * alpha.53 (migration 032) — error class for `outcome='candidate_error'`
642
+ * rows. Values follow execute()'s taxonomy (`rate_limit`, `timeout`,
643
+ * `server_error`, `model_not_found`, `auth`, `invalid_request`, `unknown`)
644
+ * plus `execute_rejected` (the execute promise rejected outright). NULL /
645
+ * omitted on all other row classes.
646
+ */
647
+ errorClass?: string;
648
+ }
649
+ /**
650
+ * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
651
+ * Exported so a test can assert the G3 privacy invariant: the row carries NO
652
+ * prompt/system/context text — only response previews + metadata + a hash.
653
+ *
654
+ * Phase 1 (judge: 'off'): `judge_verdict` / `judge_score` are null — the row
655
+ * is an unjudged sample for the Phase-2 offline batch judge. `prompt_fidelity`
656
+ * is 1.0 by construction (the candidate ran the full IR, not a truncated
657
+ * preview), and `replay_source='inline-full-ir'` marks it as a trustworthy row
658
+ * (vs the watchers' lossy `replay-preview`).
659
+ */
660
+ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
661
+ app_id: string;
662
+ intent_archetype: string;
663
+ family: string;
664
+ candidate_model: string;
665
+ current_model: string;
666
+ prompt_hash: string;
667
+ current_response: string | null;
668
+ candidate_response: string | null;
669
+ judge_verdict: null;
670
+ judge_score: null;
671
+ tokens_current_in: number | null;
672
+ tokens_current_out: number | null;
673
+ tokens_candidate_in: number | null;
674
+ tokens_candidate_out: number | null;
675
+ latency_current_ms: number | null;
676
+ latency_candidate_ms: number | null;
677
+ prompt_fidelity: number;
678
+ replay_source: 'inline-full-ir';
679
+ outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
680
+ error_class: string | null;
681
+ };
682
+ /**
683
+ * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
684
+ * default; honors `BrainConfig.sync` (L-086). Never throws — failures route to
685
+ * onError. Mirrors record()'s POST shape; consumer proxies forward
686
+ * `/probe_outcomes` the same way they forward `/outcomes`.
687
+ */
688
+ declare function recordShadowProbe(input: ShadowProbeRecordInput): Promise<void>;
689
+
690
+ /**
691
+ * alpha.60 — the library's own version, baked as a constant so Edge/Worker
692
+ * runtimes (no fs, no require) can report it on wire surfaces. First
693
+ * consumer: `createKeyHealthRoute` carries it as `library_version`, which is
694
+ * how the operator dashboard's Fleet panel sees per-consumer vendor drift
695
+ * LIVE instead of via wrap-time package.json probes (the L-093 family
696
+ * "declared state lags actual" fix at the vendor-version axis — s47 found
697
+ * IC 13 alphas stale that way).
698
+ *
699
+ * Kept in sync with package.json by hand at each version bump; the drift
700
+ * guard in `tests/version.test.ts` fails the suite (and therefore
701
+ * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
702
+ */
703
+ declare const LIBRARY_VERSION = "2.0.0-alpha.61";
117
704
 
118
705
  /**
119
706
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -166,6 +753,34 @@ interface LLMJudgeOptions {
166
753
  */
167
754
  declare function buildLLMJudge(opts: LLMJudgeOptions): AppOracle;
168
755
 
756
+ /**
757
+ * Resolve the effective ArchetypeConvention[] for a given selected profile,
758
+ * walking family inheritance once. Model-specific entries on the selected
759
+ * profile take precedence over family-level entries for the same archetype.
760
+ *
761
+ * Pure; safe to call from any context (probe-watcher uses the same logic
762
+ * via `applyArchetypeConvention`).
763
+ */
764
+ declare function resolveConventionsForProfile(profile: ModelProfile): ArchetypeConvention[];
765
+ /**
766
+ * Pure helper: apply the matching ArchetypeConvention's suffix (and
767
+ * prefix, when meaningful) to a plain prompt-text string. Used by the
768
+ * exclusion-probe-watcher (`probeOne`) so probe calls carry the same
769
+ * forcing-function shape consumers see at compile time. Without this,
770
+ * every reasoner probe on a decisive archetype gets unfairly stay-excluded
771
+ * for hedging — as ID 20 demonstrated on 2026-05-28.
772
+ *
773
+ * Resolution: looks up the family-rep profile for `family` and reads its
774
+ * `archetypeConventions`. Returns the original text unchanged when no
775
+ * convention matches or when the suffix is already present.
776
+ *
777
+ * @param promptText raw user-prompt text (or prompt_preview from outcome)
778
+ * @param archetype intent_archetype from the finding row
779
+ * @param family family tag from deriveFamilyFromModelId / brain row
780
+ * @returns text with prefix/suffix applied (idempotent)
781
+ */
782
+ declare function applyArchetypeConvention(promptText: string, archetype: string, family: string): string;
783
+
169
784
  /**
170
785
  * Tokenizer abstraction.
171
786
  *
@@ -189,6 +804,75 @@ declare function resetTokenizer(): void;
189
804
  */
190
805
  declare function countTokens(text: string): number;
191
806
 
807
+ /**
808
+ * archetype-fits — alpha.43.
809
+ *
810
+ * Static table of "this archetype tends to be a better fit for this family"
811
+ * recommendations. Powers the `cross-family-fit-candidate` compile-time
812
+ * advisor (see `advisor-rules/cross-family-fit.ts`).
813
+ *
814
+ * Strategic framing (Sacha, 2026-05-28): "If we get better results and
815
+ * better price then we do. Even if volume is currently low, that's not an
816
+ * argument to not do it. Volume can increase quickly if tools is great to
817
+ * use, let's not create future bottlenecks because we could have wired in
818
+ * better solution at moment of knowing."
819
+ *
820
+ * The convention substrate (passApplyConventions) is the NEGATIVE side:
821
+ * make a family usable on archetypes it currently fails. This table is the
822
+ * POSITIVE side: actively surface that a different family is the better
823
+ * fit for the archetype's shape — even when current volume is low.
824
+ *
825
+ * Entries are added only when:
826
+ * - the archetype's shape and the family's behavior have a clear
827
+ * architectural fit (not vibes)
828
+ * - real-world evidence (brain rows, probe outcomes, or published
829
+ * benchmark) backs the claim, OR the reasoning is structurally so clear
830
+ * that "wait for volume" would create a future bottleneck
831
+ *
832
+ * Alpha.43 ships two entries — `plan` and `critique`. Both fit the
833
+ * reasoner-family architectural read: plan is multi-step reasoning;
834
+ * critique rewards epistemic humility and explicit reasoning. Other
835
+ * archetype-family-fits ride later alphas as evidence accumulates.
836
+ *
837
+ * Anti-pattern: do NOT add archetype-family-fits for archetypes where the
838
+ * fit is unclear (summarize, classify, extract, hunt with parallel tools).
839
+ * The advisor only earns trust when its recommendations land.
840
+ */
841
+
842
+ /**
843
+ * One archetype-family-fit recommendation. Read by the compile-time
844
+ * `cross-family-fit-candidate` advisor to decide when to surface a positive
845
+ * recommendation. The advisor pulls `costGuidance` verbatim into the
846
+ * advisory message.
847
+ */
848
+ interface ArchetypeFamilyFit {
849
+ /** Intent archetype this fit applies to. */
850
+ archetype: IntentArchetypeName;
851
+ /** Family tag that fits the archetype better than alternatives. Matches the
852
+ * same family taxonomy used by `family-resolution.deriveFamilyFromModelId`
853
+ * (e.g. `'deepseek-reasoner'`, `'gemini-flash'`, `'claude-opus'`). */
854
+ betterFitFamily: string;
855
+ /** Architectural / evidentiary justification. Appears in the advisor's
856
+ * internal logs and the advisory `evidence` payload, NOT verbatim in the
857
+ * consumer-facing message. */
858
+ reason: string;
859
+ /** Cost-context clause surfaced VERBATIM in the consumer-facing advisory
860
+ * message (e.g. "substantially cheaper at current pricing"). Keep
861
+ * declarative; the advisor wraps this into the larger sentence. */
862
+ costGuidance: string;
863
+ }
864
+ /**
865
+ * Frozen registry. Add entries by extending the array. Order is irrelevant
866
+ * — the advisor filters by `(archetype, currentFamily)` independently.
867
+ */
868
+ declare const ARCHETYPE_FAMILY_FITS: readonly ArchetypeFamilyFit[];
869
+ /**
870
+ * Pure lookup: does `(archetype, currentFamily)` have a better-fit family?
871
+ * Returns the fit entry when the current family is NOT the better fit; null
872
+ * otherwise. Used by the advisor to decide whether to fire.
873
+ */
874
+ declare function findBetterFit(archetype: string, currentFamily: string): ArchetypeFamilyFit | null;
875
+
192
876
  /**
193
877
  * Best-practice advisor — alpha.6 Phase 1.
194
878
  *
@@ -219,10 +903,1545 @@ declare function countTokens(text: string): number;
219
903
  /** Subset of CompileResult fields the advisor needs. */
220
904
  type AdvisorContext = Pick<CompileResult, 'target' | 'provider' | 'tokensIn' | 'diagnostics'>;
221
905
  /**
222
- * Run all Phase 1 rules and return collected advisories. Order is fixed
223
- * (same as the rule list above) so output is stable across runs.
906
+ * Optional Phase 2 (alpha.22) context fallback chain + a profile resolver
907
+ * for cross-model comparison. Three new rules
908
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) consume
909
+ * this to surface measurement-substrate signals (alpha.20 clean-attribution +
910
+ * alpha.21 grounding labels) as actionable consumer guidance.
911
+ *
912
+ * When `fallbackChain` is empty, rules 1 + 3 stay silent (nothing to
913
+ * compare against). When `profileResolver` is omitted, the rules degrade
914
+ * gracefully — they can still inspect the chosen profile but not chain
915
+ * alternatives. Rule 2 (`model-stale-evidence`) is independent of chain
916
+ * shape and works on the chosen model alone.
917
+ */
918
+ interface RunAdvisorPhase2Context {
919
+ fallbackChain: string[];
920
+ profileResolver?: (id: string) => ModelProfile | undefined;
921
+ /**
922
+ * alpha.29 — translator rewrites that fired this compile. When a rewrite
923
+ * cleared the cliff (e.g. `tool_call_contract` → sequential-tool preamble
924
+ * + `parallelToolCalls: false`), the matching cliff advisor
925
+ * (`archetype-perf-floor-breach`) MUST suppress for the same call. Without
926
+ * suppression both fire — the advisory contradicts the rewrite ("cliff is
927
+ * unaddressed" vs "we just addressed it").
928
+ *
929
+ * Empty array / undefined → no suppression (alpha.28 behavior preserved).
930
+ */
931
+ sectionRewritesApplied?: SectionRewrite[];
932
+ }
933
+ /**
934
+ * alpha.42 — rule codes whose advisories are positioned for kgauto (not
935
+ * the consumer) to act on. Used by `compile()` to default the `ownership`
936
+ * stamp on each advisory when the rule didn't self-declare. Consumer-side
937
+ * rules don't need to be listed — they default to `'consumer-actionable'`
938
+ * via fall-through.
939
+ *
940
+ * - `model-stale-evidence`: kgauto's profile data is out of date; the
941
+ * consumer can't fix that, kgauto needs to update profiles or refresh
942
+ * archetypePerf scores.
943
+ * - `promote-ready`: kgauto's promotion-probe-watcher detected a
944
+ * candidate model worth promoting; consumer-side adoption is downstream
945
+ * of kgauto adding it to the chain / family taxonomy.
946
+ *
947
+ * Frozen so consumers and tests can't mutate the global ownership map.
948
+ */
949
+ declare const PRODUCER_OWNED_RULE_CODES: ReadonlySet<string>;
950
+ /**
951
+ * alpha.42 — pure function used by `compile()` to decide ownership for an
952
+ * advisory. Rule-self-declared wins; falls back to the static map; defaults
953
+ * `consumer-actionable`. Exported so consumer-side code (or a Glass-Box
954
+ * renderer) can derive the same classification from a rule code alone
955
+ * without needing the advisory object.
956
+ */
957
+ declare function deriveOwnership(code: string, selfDeclared?: 'consumer-actionable' | 'producer-owned'): 'consumer-actionable' | 'producer-owned';
958
+ /**
959
+ * Run all phased rules and return collected advisories. Order is fixed so
960
+ * output is stable across runs. The `policy` argument is alpha.9 — the
961
+ * `single-model-array` rule needs to know whether the consumer explicitly
962
+ * declared `posture: 'locked'` (in which case single-model is intentional
963
+ * and shouldn't warn).
964
+ *
965
+ * `phase2` is alpha.22 — gives the advisor access to the fallback chain +
966
+ * a profile resolver so the three new compile-time recommendation rules
967
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) can
968
+ * compare the chosen model against in-chain alternatives. Optional for
969
+ * backward compatibility with consumers calling `runAdvisor()` directly.
970
+ */
971
+ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile, policy?: CompilePolicy, phase2?: RunAdvisorPhase2Context): BestPracticeAdvisory[];
972
+
973
+ /**
974
+ * Translator primitive — alpha.31.
975
+ *
976
+ * Pure function. Walks `IR.sections`, matches each section's `kind` against
977
+ * a per-rule dispatch table keyed on (kind, profile, archetype), and applies
978
+ * a model-aware rewrite when a rule fires. Returns the rewritten IR + the
979
+ * list of rewrites for `CompileResult.sectionRewritesApplied` and brain
980
+ * persistence.
981
+ *
982
+ * This is the s37 translator-framing eureka in code: kgauto graduates from
983
+ * "gate" (alpha.28's cliff advisor: "consumer must accept adapter") to
984
+ * "translator" (alpha.29: "consumer declared the section kind, kgauto
985
+ * applies the adapter at compile time without consumer-side branching").
986
+ *
987
+ * Rules shipped:
988
+ *
989
+ * alpha.29 — tool_call_contract + archetypePerf[archetype] < TRANSLATOR_FLOOR
990
+ * → prepend sequential-tool-pattern guidance
991
+ * → emit wireOverrides: { parallelToolCalls: false }
992
+ * → rule_id: 'sequential-tool-cliff-below-floor'
993
+ *
994
+ * alpha.31 — narration_contract + profile.provider === 'anthropic'
995
+ * → prepend terse-log narration guidance
996
+ * → no wireOverrides
997
+ * → rule_id: 'narration-drift-anthropic'
998
+ *
999
+ * alpha.31 — narration_contract + profile.provider === 'deepseek'
1000
+ * → prepend <thinking>-suppression guidance
1001
+ * → no wireOverrides
1002
+ * → rule_id: 'narration-thinking-leak-deepseek'
1003
+ *
1004
+ * Per-rule walk (alpha.31 refactor): the alpha.30 short-circuit
1005
+ * `if (!cliffFires) return passthrough` was correct when only the
1006
+ * cliff-gated tool_call_contract rule existed; alpha.31's narration rules
1007
+ * fire on every call regardless of cliff (narration drift is steady-state,
1008
+ * not a cliff condition). Each section now consults the dispatch table
1009
+ * independently — first-match wins per (section.kind, profile, archetype).
1010
+ *
1011
+ * **Interaction with the cliff advisor (alpha.28):** when this translator
1012
+ * fires for a `tool_call_contract` section, the advisor's
1013
+ * `archetype-perf-floor-breach` rule MUST suppress for the same call — the
1014
+ * cliff was structurally cleared by the rewrite, not unaddressed. The
1015
+ * suppression check lives in `advisor.ts` and consults the
1016
+ * `CompileResult.sectionRewritesApplied` list.
1017
+ *
1018
+ * Design contracts:
1019
+ * command-center/advisory/kgauto/2026-05-21_alpha-29-translator-and-advisories-api.md
1020
+ * command-center/advisory/kgauto/2026-05-22_alpha-31-narration-contract.md
1021
+ */
1022
+
1023
+ /**
1024
+ * Re-export of `ARCHETYPE_FLOOR_DEFAULT` as the canonical "translator fires
1025
+ * below this score" threshold. Same constant as the cliff advisor — the
1026
+ * single threshold is shared (alpha.28's "below this, advisor warns"; alpha.29's
1027
+ * "below this, translator AUTO-APPLIES the adapter").
1028
+ */
1029
+ declare const TRANSLATOR_FLOOR = 6;
1030
+ /**
1031
+ * Stable identifier of the alpha.29 sequential-tool rule. Surfaces on
1032
+ * `SectionRewrite.rule` and in brain aggregates. The brain treats this
1033
+ * identifier together with the preamble string as the rule's wire
1034
+ * fingerprint — both stay byte-stable across releases.
1035
+ */
1036
+ declare const RULE_SEQUENTIAL_TOOL_CLIFF = "sequential-tool-cliff-below-floor";
1037
+ interface ApplySectionRewritesArgs {
1038
+ ir: PromptIR;
1039
+ profile: ModelProfile;
1040
+ archetype: IntentArchetypeName;
1041
+ }
1042
+ interface ApplySectionRewritesResult {
1043
+ /**
1044
+ * IR with section.text fields possibly rewritten. When no rewrites fired,
1045
+ * this is identical to the input IR (referentially distinct array but
1046
+ * same section payloads).
1047
+ */
1048
+ rewrittenIR: PromptIR;
1049
+ /**
1050
+ * One entry per section the translator rewrote. Empty array when no
1051
+ * rules fired. Order matches the corresponding section in
1052
+ * `rewrittenIR.sections`.
1053
+ */
1054
+ rewrites: SectionRewrite[];
1055
+ }
1056
+ /**
1057
+ * Pure function. Apply model-aware section rewrites to the IR at compile time.
1058
+ *
1059
+ * Discipline:
1060
+ * - Never mutates the input IR; returns a new IR with new sections array
1061
+ * when at least one rewrite fired; otherwise returns the input IR by
1062
+ * reference (referential identity preserved on no-op).
1063
+ * - Sections without a `kind` (or `kind === 'arbitrary'`) pass through
1064
+ * unchanged.
1065
+ * - Empty `sections` array → returns `{ rewrittenIR: ir, rewrites: [] }`.
1066
+ * - Sections of the same `kind` are processed in array order; first-match
1067
+ * wins per section. (Today every rule is a single-match rule.)
1068
+ *
1069
+ * @example
1070
+ * ```ts
1071
+ * import { applySectionRewrites } from '@warmdrift/kgauto-compiler';
1072
+ * import { getProfile } from '@warmdrift/kgauto-compiler';
1073
+ *
1074
+ * const { rewrittenIR, rewrites } = applySectionRewrites({
1075
+ * ir,
1076
+ * profile: getProfile('deepseek-v4-pro'),
1077
+ * archetype: 'hunt',
1078
+ * });
1079
+ * if (rewrites.length > 0) console.log('translator fired:', rewrites);
1080
+ * ```
1081
+ */
1082
+ declare function applySectionRewrites(args: ApplySectionRewritesArgs): ApplySectionRewritesResult;
1083
+
1084
+ /**
1085
+ * advisories-api — structured advisories API (alpha.29 Workstream B).
1086
+ *
1087
+ * Closes the L-117 family bottleneck: kgauto's `result.advisories[]` (the
1088
+ * compile-time warnings about caching-off, tool-bloat, archetype-perf-floor
1089
+ * breaches, etc.) used to disappear after the consumer read the compile
1090
+ * result. The s34 caching-off advisory pattern is the canonical failure: an
1091
+ * advisory fired 100+ times in 24h on `generate::sonnet` at 99.4% empty
1092
+ * rate, and nobody knew because there was no structured channel to surface
1093
+ * "what's open right now?"
1094
+ *
1095
+ * Migration 020 ships the substrate: `compile_outcome_advisories` gains
1096
+ * lifecycle columns (`resolved_at`, `resolution_source`, `resolution_note`)
1097
+ * and the `actionable_advisories_v` view rolls per-firing rows into
1098
+ * per-(app_id, code) tuples with deterministic stable ids + server-side
1099
+ * auto-resolution.
1100
+ *
1101
+ * Public surface:
1102
+ * getActionableAdvisories({ appId, severity?, status?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1103
+ * → Promise<ActionableAdvisory[]>
1104
+ *
1105
+ * markAdvisoryResolved({ id, resolutionNote?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
1106
+ * → Promise<{ ok: true } | { ok: false; reason: string }>
1107
+ *
1108
+ * Both functions are pure I/O — no module-level state. The fetch wiring
1109
+ * mirrors `createProxyHandler` in `glassbox-routes/proxy.ts`: scoped JWT in
1110
+ * `Authorization: Bearer`, `apikey` header carries the anon key.
1111
+ *
1112
+ * The auto-resolution rule is enforced server-side in `actionable_advisories_v`:
1113
+ * • Latest firing > 14 days ago → status='resolved' (auto-pruned)
1114
+ * • All firings have resolved_at set → status='resolved' (consumer-marked)
1115
+ * • Otherwise → status='open'
1116
+ *
1117
+ * `markAdvisoryResolved` is the consumer override: "I fixed it; the next
1118
+ * firing will reopen the rule, but until then it stays resolved."
1119
+ */
1120
+
1121
+ /**
1122
+ * Severity of an advisory. Maps to the `level` column on
1123
+ * `compile_outcome_advisories` (info | warn | critical).
1124
+ */
1125
+ type AdvisorySeverity = 'info' | 'warn' | 'critical';
1126
+ /**
1127
+ * Status of an advisory rollup.
1128
+ *
1129
+ * - `open` — at least one unresolved firing in the last 14 days
1130
+ * - `resolved` — either auto-pruned (no firings >14d) or consumer-marked
1131
+ * - `snoozed` — reserved for alpha.30+ (snooze-until-date); type-accepted
1132
+ * today but the view will never emit this value
1133
+ */
1134
+ type AdvisoryStatus = 'open' | 'snoozed' | 'resolved';
1135
+ /**
1136
+ * Source of resolution when status='resolved'.
1137
+ *
1138
+ * - `auto` — server-side rule auto-pruned (>14d since last firing)
1139
+ * - `consumer-marked` — consumer called `markAdvisoryResolved`
1140
+ * - `declined` — reserved (alpha.30+: consumer marked the suggestion
1141
+ * inapplicable; the advisor will still fire but UIs can hide it)
1142
+ */
1143
+ type AdvisoryResolutionSource = 'auto' | 'consumer-marked' | 'declined';
1144
+ /**
1145
+ * Suggested-fix metadata. `null` when the advisor has no actionable fix
1146
+ * (info-level rules can be observational). When set, the consumer's
1147
+ * Admin UI can render a one-click apply (alpha.30+) or surface the
1148
+ * before/after diff inline.
1149
+ */
1150
+ interface AdvisorySuggestedFix {
1151
+ type: 'config-change' | 'one-liner' | 'env-var' | 'manual';
1152
+ /** File:line hint if kgauto can infer (reserved — alpha.30+). */
1153
+ siteHint?: string;
1154
+ before?: string;
1155
+ after?: string;
1156
+ docsLink?: string;
1157
+ }
1158
+ /**
1159
+ * Per-(app_id, code) advisory rollup. The `id` is stable across polls
1160
+ * until the rule auto-resolves and re-opens (a new firing after the 14d
1161
+ * boundary advances `opened_at` → new id). Treat id-changes as
1162
+ * intentional "fresh re-open" signals.
1163
+ *
1164
+ * Wire-shape from `actionable_advisories_v`. The transformer maps the
1165
+ * view's snake_case columns to camelCase. See `feedback_typed_boundary_transformers.md`
1166
+ * (L-118) for the rationale.
1167
+ */
1168
+ interface ActionableAdvisory {
1169
+ id: string;
1170
+ rule: string;
1171
+ severity: AdvisorySeverity;
1172
+ openedAt: string;
1173
+ lastObservedAt: string;
1174
+ observationCount: number;
1175
+ appliesTo: {
1176
+ archetype?: IntentArchetypeName;
1177
+ model?: string;
1178
+ callSiteHint?: string;
1179
+ };
1180
+ message: string;
1181
+ suggestedFix: AdvisorySuggestedFix | null;
1182
+ /** Reserved — always `false` in alpha.29. alpha.30+ ships actual auto-apply. */
1183
+ autoApplicable: boolean;
1184
+ status: AdvisoryStatus;
1185
+ resolvedAt?: string;
1186
+ resolutionSource?: AdvisoryResolutionSource;
1187
+ resolutionNote?: string;
1188
+ }
1189
+ /**
1190
+ * Filter + transport for `getActionableAdvisories`. The brain JWT must
1191
+ * carry an `app_id` claim matching `opts.appId` — RLS enforces tenant
1192
+ * isolation on the underlying table, so a mismatch silently returns [].
1193
+ */
1194
+ interface GetActionableAdvisoriesOptions {
1195
+ appId: string;
1196
+ /** Severity filter; if omitted, all severities are returned. */
1197
+ severity?: AdvisorySeverity;
1198
+ /** Status filter; defaults to 'open'. Pass 'all' for the full set. */
1199
+ status?: 'open' | 'snoozed' | 'resolved' | 'all';
1200
+ brainEndpoint: string;
1201
+ brainJwt: string;
1202
+ brainAnonKey: string;
1203
+ fetch?: typeof fetch;
1204
+ }
1205
+ interface MarkAdvisoryResolvedOptions {
1206
+ /** Stable id from a prior `getActionableAdvisories` call. */
1207
+ id: string;
1208
+ resolutionNote?: string;
1209
+ brainEndpoint: string;
1210
+ brainJwt: string;
1211
+ brainAnonKey: string;
1212
+ fetch?: typeof fetch;
1213
+ }
1214
+ /**
1215
+ * Query the open advisory set for an app. Pulls from
1216
+ * `actionable_advisories_v` (per-(app_id, code) rollup with stable ids
1217
+ * + server-side auto-resolution).
1218
+ *
1219
+ * Default behavior (no status filter): returns only `status='open'`.
1220
+ * Pass `status: 'all'` to see resolved + open together — useful for
1221
+ * Admin UIs that show "recently fixed" badges.
1222
+ *
1223
+ * Fetch failures bubble out as thrown Errors. (`markAdvisoryResolved`
1224
+ * uses the ok/reason envelope; this read path throws to match
1225
+ * existing kgauto query semantics where the consumer can decide to
1226
+ * retry or render an error state.)
1227
+ */
1228
+ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions): Promise<ActionableAdvisory[]>;
1229
+ /**
1230
+ * Mark an advisory as consumer-resolved.
1231
+ *
1232
+ * Lookup strategy:
1233
+ * 1. Query `actionable_advisories_v?id=eq.<id>` to find the (app_id, code)
1234
+ * tuple for this advisory.
1235
+ * 2. PATCH the latest unresolved firing in `compile_outcome_advisories`
1236
+ * matching that tuple via the underlying outcome's app_id.
1237
+ *
1238
+ * The (app_id, code) lookup is necessary because `compile_outcome_advisories`
1239
+ * has no `app_id` column — it inherits scope via the FK to compile_outcomes.
1240
+ * PostgREST cannot PATCH with a JOIN predicate, so the markAdvisoryResolved
1241
+ * path is a two-step round-trip. The cost is one extra GET per resolve call;
1242
+ * acceptable because marks are low-frequency operator actions, not per-call
1243
+ * hot path.
1244
+ *
1245
+ * Idempotent re-marks: if the advisory is already resolved (no unresolved
1246
+ * firings match), the PATCH affects zero rows and the call still returns
1247
+ * `ok: true`. The function returns `ok: false` only on transport / auth /
1248
+ * lookup failures.
1249
+ *
1250
+ * Returns ok/reason envelope (vs throwing) because consumer Admin UIs
1251
+ * typically want to render the failure inline rather than crash.
1252
+ */
1253
+ declare function markAdvisoryResolved(opts: MarkAdvisoryResolvedOptions): Promise<{
1254
+ ok: true;
1255
+ } | {
1256
+ ok: false;
1257
+ reason: string;
1258
+ }>;
1259
+ /**
1260
+ * Resolution sources supported by the alpha.39 `markExclusionFindingHandled`
1261
+ * API. Mirrors the subset of `exclusion_findings.resolution_source` CHECK
1262
+ * constraint values that consumers can self-set:
1263
+ *
1264
+ * - `'consumer-marked'` — generic "we've handled this; stop reminding."
1265
+ * Use this for "we evaluated and chose not to act" or "we'll act when
1266
+ * ready but acknowledge the finding now."
1267
+ * - `'declined'` — explicit "this exclusion is intentional; do not surface
1268
+ * again." Stronger signal than consumer-marked; useful for compliance
1269
+ * exclusions, brand-promise exclusions, etc.
1270
+ * - `'probed-unblock'` — alpha.40+ probe-path verdict: consumer ran a live
1271
+ * probe and decided to unblock the excluded model. Library accepts the
1272
+ * value today so the probe path doesn't need a follow-up API release.
1273
+ * - `'probed-stay-excluded'` — alpha.40+ probe-path verdict: consumer
1274
+ * probed and confirmed the exclusion. Same forward-compat shape as
1275
+ * `'probed-unblock'`.
1276
+ *
1277
+ * The `'auto'` resolution_source is NOT exposed here — that's reserved
1278
+ * for the brain's own automatic resolution (e.g. when the detection
1279
+ * conditions no longer hold). Consumer code sets only the four values
1280
+ * above.
1281
+ */
1282
+ type ExclusionResolutionSource = 'consumer-marked' | 'declined' | 'probed-unblock' | 'probed-stay-excluded';
1283
+ interface MarkExclusionFindingHandledOptions {
1284
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
1285
+ appId: string;
1286
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
1287
+ archetype: string;
1288
+ /** Canonical model id that the consumer had excluded. */
1289
+ excludedModel: string;
1290
+ /** Resolution semantics — see `ExclusionResolutionSource` for the four
1291
+ * values consumers can set. */
1292
+ resolution: ExclusionResolutionSource;
1293
+ /** Optional free-form note explaining the decision. Surfaces in operator
1294
+ * digests + dashboards alongside the resolution_source. */
1295
+ resolutionNote?: string;
1296
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). The
1297
+ * function appends `/rest/v1/exclusion_findings?...`. */
1298
+ brainEndpoint: string;
1299
+ /** Consumer-scoped JWT carrying the `app_id` claim. The brain's RLS
1300
+ * policy enforces that the JWT's app_id matches the finding's app_id;
1301
+ * cross-tenant writes fail at the database layer regardless of input. */
1302
+ brainJwt: string;
1303
+ /** Supabase anon key for the `apikey` header (PostgREST requires it). */
1304
+ brainAnonKey: string;
1305
+ /** Injected fetch for tests. Defaults to global fetch. */
1306
+ fetch?: typeof fetch;
1307
+ }
1308
+ /**
1309
+ * Mark a stale-exclusion finding as handled. Returns an `ok/reason` envelope
1310
+ * matching `markAdvisoryResolved` — consumer Admin UIs typically render the
1311
+ * failure inline rather than crash.
1312
+ *
1313
+ * Idempotent: if no row matches the (app_id, archetype, excludedModel)
1314
+ * tuple (already resolved, never existed, cron not yet UPSERTed), PostgREST
1315
+ * returns 200 with zero affected rows and we return `{ ok: true }`. The
1316
+ * caller's "I marked it as handled" intent is satisfied regardless of
1317
+ * whether the row was already in that state.
1318
+ *
1319
+ * Reasons surfaced on failure:
1320
+ * - `app_id_required` / `archetype_required` / `excluded_model_required`
1321
+ * - `resolution_invalid` — `resolution` not one of the four documented values
1322
+ * - `brain_auth_misconfig` — 401/403 (JWT / anon key wrong)
1323
+ * - `brain_unavailable` — 5xx
1324
+ * - `network_error:<message>` — fetch threw
1325
+ * - `patch_failed:<status>` — anything else non-2xx
1326
+ */
1327
+ declare function markExclusionFindingHandled(opts: MarkExclusionFindingHandledOptions): Promise<{
1328
+ ok: true;
1329
+ } | {
1330
+ ok: false;
1331
+ reason: string;
1332
+ }>;
1333
+
1334
+ /**
1335
+ * Archetype-cliff compatibility — alpha.28 (tt-intel-Cairn ratified).
1336
+ *
1337
+ * One question, one answer: *given this model and this intent, can it work
1338
+ * — and if not, what adapter (if any) would make it work?*
1339
+ *
1340
+ * Replaces the silent-archetype-cliff failure mode where a consumer picks a
1341
+ * model that's structurally wrong for the intent and kgauto compiles cleanly
1342
+ * without surfacing the gap. The triggering incident: tt-intel shipped
1343
+ * `deepseek-v4-pro` as the hunt default per a local spec; the kgauto coord
1344
+ * doc said L-040 — V4 is structurally wrong for hunt (sequential tools).
1345
+ * `archetypePerf.hunt = 4` was already in the profile data. The compiler
1346
+ * stayed silent. This API + the matching advisor rule surfaces it.
1347
+ *
1348
+ * Pure function. No network. No brain query. No side effects. ~1ms.
1349
+ *
1350
+ * Consultation doc:
1351
+ * command-center/advisory/kgauto/2026-05-21_archetype-cliff-advisor.md
1352
+ *
1353
+ * Refinements applied per tt-intel-Cairn ratification (2026-05-21):
1354
+ * R1: every variant carries `archetypePerf: number` (raw score) — and
1355
+ * `requires-adapter` adds `archetypePerfWithAdapter: number` so
1356
+ * consumer policy can be expressed as "accept adapter only when score
1357
+ * crosses some threshold WITH the adapter on."
1358
+ * R2: every variant carries a plain-English `reason: string`. No internal
1359
+ * jargon ("L-040", "archetypePerf=4") — the consumer chooses whether
1360
+ * to render it as UI hint or operator-tooling tooltip.
1361
+ * R3: `Adapter` is a CLOSED discriminated union, not `| string`. alpha.28
1362
+ * ships ONE variant (`toolOrchestration: 'sequential'`). Future
1363
+ * adapter parameters extend the union explicitly in named releases.
1364
+ * NO escape hatch — the whole point is catching "I added a new
1365
+ * adapter and forgot to update consumer policy" at compile time.
1366
+ */
1367
+
1368
+ /**
1369
+ * Minimum `archetypePerf[archetype]` score to count as `compatible` under
1370
+ * Option A (default policy). Below this, a documented adapter is needed
1371
+ * to lift the model above the floor; if no adapter exists, the model is
1372
+ * rejected.
1373
+ *
1374
+ * Matches `QUALITY_FLOOR_FOR_RECOMMENDATION` in `advisor.ts` — kgauto's
1375
+ * library-wide convention for "below this score, swap recommendations stop."
1376
+ */
1377
+ declare const ARCHETYPE_FLOOR_DEFAULT = 6;
1378
+ /**
1379
+ * Absolute floor — below this, the cliff is too steep for ANY adapter to
1380
+ * lift cleanly. Reserved under Option A (unused today; every below-floor
1381
+ * case is gated by adapter availability). Would gate `reject` vs
1382
+ * `requires-adapter` under a future Option B per consultation doc Q1.
1383
+ *
1384
+ * Exported so consumer-side policy can read it (e.g. "accept adapter only
1385
+ * when archetypePerf >= ABSOLUTE_FLOOR + 1"). Not used internally by
1386
+ * `getModelCompatibility` today — the gate is "does an adapter exist for
1387
+ * this cliff?", not score-based.
1388
+ */
1389
+ declare const ABSOLUTE_FLOOR = 4;
1390
+ /**
1391
+ * The intent the call is expressing — archetype + optional orchestration
1392
+ * mode. Same shape as `ir.intent.archetype` + `ir.constraints.toolOrchestration`
1393
+ * so a consumer can pass `{ archetype: ir.intent.archetype,
1394
+ * toolOrchestration: ir.constraints?.toolOrchestration }` directly.
1395
+ */
1396
+ interface CompatibilityIntent {
1397
+ archetype: IntentArchetypeName;
1398
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
1399
+ }
1400
+ /**
1401
+ * `Adapter` — re-exported above. Canonical definition lives in `ir.ts` to
1402
+ * avoid an import cycle (compatibility.ts → profiles.ts → ir.ts).
1403
+ *
1404
+ * **CLOSED discriminated union per R3.** Future adapter parameters extend
1405
+ * the union explicitly in named alpha releases. No `| string` escape hatch
1406
+ * — consumer policy code SHOULD write exhaustive `switch (adapter.parameter)`
1407
+ * and rely on the compiler to flag "I added a new adapter parameter and
1408
+ * forgot to update the consumer's policy."
1409
+ *
1410
+ * alpha.28 variants:
1411
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
1412
+ * Lifts DeepSeek V4-family on `hunt` from sequential-tool cliff (L-040).
1413
+ * The "consequence" plain-English-ifies the trade-off:
1414
+ * "Tool calls run one at a time — slower but reliable."
1415
+ *
1416
+ * alpha.29+ likely additions (per tt-intel-Cairn priority list):
1417
+ * - `{ parameter: 'parallelToolCalls'; value: false; consequence }`
1418
+ * - `{ parameter: 'maxTools'; value: number; consequence }`
1419
+ * - `{ parameter: 'thinkingBudget'; value: 0; consequence }`
1420
+ *
1421
+ * Each new variant lands in its own named release with the union extended
1422
+ * in `ir.ts`. Consumers see the change at compile time.
224
1423
  */
225
- declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile): BestPracticeAdvisory[];
1424
+ /**
1425
+ * The compatibility verdict for a (model, intent) pair. Discriminated union
1426
+ * on `status` — `compatible` | `requires-adapter` | `reject`.
1427
+ *
1428
+ * **Every variant carries `archetypePerf` (R1) + `reason` (R2):**
1429
+ * - `archetypePerf` — the raw 0-10 score for (model, archetype). Lets
1430
+ * consumers build their own thresholds without re-importing the profile
1431
+ * registry.
1432
+ * - `reason` — plain-English, consumer-renderable. NOT internal jargon
1433
+ * like "L-040 cliff" or "archetypePerf=4". Examples in R2 ratification:
1434
+ * - compatible: "Suited for hunt-style parallel discovery."
1435
+ * - requires-adapter: "Best with sequential tool calls for hunt — slower but works."
1436
+ * - reject: "Not suited for hunt — would underperform significantly."
1437
+ *
1438
+ * `requires-adapter` additionally carries:
1439
+ * - `archetypePerfWithAdapter` — estimated post-adapter score. May be an
1440
+ * estimate (we don't measure post-adapter scores yet); kgauto's prior is
1441
+ * "adapter lifts to ARCHETYPE_FLOOR_DEFAULT + 1" unless brain-evidenced.
1442
+ * - `adapter` — the closed-union variant describing the structural change.
1443
+ *
1444
+ * Backward-compat: an unknown model returns `reject` with a "model not
1445
+ * registered" reason; callers never throw. Unknown archetype is impossible
1446
+ * at the type level (`IntentArchetypeName` is a closed union).
1447
+ */
1448
+ type ModelCompatibility = {
1449
+ status: 'compatible';
1450
+ reason: string;
1451
+ archetypePerf: number;
1452
+ } | {
1453
+ status: 'requires-adapter';
1454
+ reason: string;
1455
+ archetypePerf: number;
1456
+ archetypePerfWithAdapter: number;
1457
+ adapter: Adapter;
1458
+ } | {
1459
+ status: 'reject';
1460
+ reason: string;
1461
+ archetypePerf: number;
1462
+ };
1463
+ /**
1464
+ * Compatibility query — *does this model fit this intent, and if not,
1465
+ * what would?*
1466
+ *
1467
+ * **Rules (Option A from consultation doc Q1):**
1468
+ * 1. If model is unregistered → `reject` with "model not registered" reason.
1469
+ * 2. If intent provides `toolOrchestration: 'sequential'` AND that adapter
1470
+ * silences the cliff (because the cliff IS the sequential-tool one)
1471
+ * → return `compatible` with raw score (NOT the post-adapter estimate
1472
+ * — caller already paid the adapter, score reflects reality).
1473
+ * 3. If raw `archetypePerf[archetype] >= ARCHETYPE_FLOOR_DEFAULT`
1474
+ * → `compatible`.
1475
+ * 4. If below floor BUT a documented adapter exists that lifts to floor
1476
+ * → `requires-adapter` with adapter + estimated post-adapter score.
1477
+ * 5. If below floor AND no adapter exists → `reject`.
1478
+ *
1479
+ * **Pure function.** Deterministic for `(modelId, intent)`. No I/O.
1480
+ *
1481
+ * @example
1482
+ * ```ts
1483
+ * import { getModelCompatibility } from '@warmdrift/kgauto-compiler';
1484
+ *
1485
+ * const c = getModelCompatibility('deepseek-v4-pro', { archetype: 'hunt' });
1486
+ * // → { status: 'requires-adapter',
1487
+ * // reason: 'Best with sequential tool calls for hunt — slower but works.',
1488
+ * // archetypePerf: 4,
1489
+ * // archetypePerfWithAdapter: 7,
1490
+ * // adapter: {
1491
+ * // parameter: 'toolOrchestration',
1492
+ * // value: 'sequential',
1493
+ * // consequence: 'Tool calls run one at a time...'
1494
+ * // } }
1495
+ *
1496
+ * // With the adapter already declared:
1497
+ * const c2 = getModelCompatibility('deepseek-v4-pro', {
1498
+ * archetype: 'hunt',
1499
+ * toolOrchestration: 'sequential',
1500
+ * });
1501
+ * // → { status: 'compatible',
1502
+ * // reason: 'Suited for hunt with sequential tool calls.',
1503
+ * // archetypePerf: 4 }
1504
+ * ```
1505
+ */
1506
+ declare function getModelCompatibility(modelId: string, intent: CompatibilityIntent): ModelCompatibility;
1507
+
1508
+ /**
1509
+ * alpha.22 — sync introspection: is brain-query mode active for a given
1510
+ * table? Used by the advisor (`model-stale-evidence` rule) to decide
1511
+ * whether a `judgment`-grounded chosen model is a measurement gap worth
1512
+ * surfacing. Returns false on cold start, when configureBrain() was never
1513
+ * called, or when the consumer explicitly opted the table out via
1514
+ * `BrainConfig.brainQuery.<table> = false`.
1515
+ */
1516
+ declare function isBrainQueryActiveFor(table: string): boolean;
1517
+ interface GetPerAxisMetricsOpts {
1518
+ /** App id to filter on. Required. */
1519
+ appId: string;
1520
+ /** Intent archetype to filter on. Required. */
1521
+ archetype: string;
1522
+ /** Canonical model id to filter on. Required. */
1523
+ model: string;
1524
+ /**
1525
+ * Window in days. Default 30. Only rows with
1526
+ * `created_at > now() - windowDays` are counted.
1527
+ */
1528
+ windowDays?: number;
1529
+ /**
1530
+ * Consumer-declared quality floor (0..1 oracle/approve-rate scale).
1531
+ * When set, the response's `qualityFloorMet` is true/false; when omitted,
1532
+ * `qualityFloorMet` is null (no floor declared, no judgment).
1533
+ */
1534
+ qualityFloor?: number;
1535
+ /** Pluggable fetch (tests inject mock). Defaults to global fetch. */
1536
+ fetch?: typeof fetch;
1537
+ /**
1538
+ * PostgREST base endpoint (e.g. `https://kgauto-brain.vercel.app/api`).
1539
+ * When omitted, falls back to the active configureBrainQuery runtime's
1540
+ * endpoint. Returns null when neither is set.
1541
+ */
1542
+ endpoint?: string;
1543
+ /** Bearer token. Forwarded as `Authorization: Bearer ${apiKey}`. */
1544
+ apiKey?: string;
1545
+ }
1546
+ /**
1547
+ * Call the `get_per_axis_metrics` RPC and return the typed result.
1548
+ *
1549
+ * Returns null when:
1550
+ * - no endpoint provided AND no configureBrainQuery runtime active
1551
+ * - RPC returns empty / null / unexpected shape
1552
+ * - brain unreachable / fetch throws / HTTP error
1553
+ *
1554
+ * Never throws — operator-facing query, must not blow up the caller.
1555
+ */
1556
+ declare function getPerAxisMetrics(opts: GetPerAxisMetricsOpts): Promise<PerAxisMetrics | null>;
1557
+
1558
+ /**
1559
+ * env.ts — provider env-key resolution + reachability predicates.
1560
+ *
1561
+ * Centralizes the per-provider env var names that kgauto checks for
1562
+ * reachability. Used by:
1563
+ *
1564
+ * - execute.ts — to find an API key when one isn't passed via apiKeys
1565
+ * - call.ts — to auto-filter unreachable models from the fallback walk
1566
+ * - getDefaultFallbackChain — opt-in chain filter when consumer passes `reachability`
1567
+ * - operator scripts — getReachabilityDiagnostic() prints what's wired up
1568
+ *
1569
+ * Keeping the map in ONE place means execute() and the reachability check
1570
+ * always agree. Without this, kgauto could declare a model "reachable" because
1571
+ * env.ts found GOOGLE_GENERATIVE_AI_API_KEY, while execute() looks at
1572
+ * GOOGLE_API_KEY only and 401s — shipping the bug we're trying to fix.
1573
+ *
1574
+ * Resolution order (apiKeys takes precedence):
1575
+ * 1. opts.apiKeys?.[provider]
1576
+ * 2. process.env[name] for each name in PROVIDER_ENV_KEYS[provider] (first-present wins)
1577
+ *
1578
+ * alpha.10 (2026-05-14). Resolves the auto-filter-unreachable-models-silently
1579
+ * request from PB after first-deploy 401 on the alpha.9 summarize chain.
1580
+ */
1581
+
1582
+ /**
1583
+ * Providers kgauto can resolve keys for today. Subset of `Provider` — `mistral`
1584
+ * and `xai` are declared in the type union but not yet executable (no profiles,
1585
+ * no execute() handler, no env-var convention). Narrowing here keeps the
1586
+ * reachability check structurally honest.
1587
+ */
1588
+ type SupportedProvider = 'anthropic' | 'google' | 'openai' | 'deepseek';
1589
+ /**
1590
+ * Per-provider env var names kgauto recognizes. Order doesn't matter —
1591
+ * first-present wins. Multiple names per provider supported because Google
1592
+ * has historical drift (`GOOGLE_API_KEY` from older Google Cloud SDKs,
1593
+ * `GEMINI_API_KEY` in many examples, `GOOGLE_GENERATIVE_AI_API_KEY` is the
1594
+ * Vercel AI SDK convention used by IC + tt-intel adapters).
1595
+ *
1596
+ * Frozen so consumers/tests can't mutate (would break the cache invariant
1597
+ * that execute() and reachability checks agree).
1598
+ */
1599
+ declare const PROVIDER_ENV_KEYS: Readonly<Record<SupportedProvider, readonly string[]>>;
1600
+ interface ReachabilityOpts {
1601
+ /** Explicit keys (alpha.3 ApiKeys). Checked first; takes precedence over env. */
1602
+ apiKeys?: ApiKeys;
1603
+ /**
1604
+ * Override env source. Defaults to `process.env` in Node-shaped runtimes,
1605
+ * `{}` everywhere else. Pass `{}` explicitly in tests for hermetic runs.
1606
+ */
1607
+ envSource?: Record<string, string | undefined>;
1608
+ }
1609
+ /**
1610
+ * Resolve a usable API key for the provider. Returns the key string, or
1611
+ * undefined if neither apiKeys nor any of the env names are set.
1612
+ *
1613
+ * Used internally by execute.ts so the reachability check and the actual
1614
+ * call check stay in sync.
1615
+ */
1616
+ declare function resolveProviderKey(provider: Provider, opts?: ReachabilityOpts): string | undefined;
1617
+ /**
1618
+ * True iff the provider has a usable key — either via explicit `apiKeys`
1619
+ * or one of the `PROVIDER_ENV_KEYS[provider]` names is set in envSource.
1620
+ */
1621
+ declare function isProviderReachable(provider: Provider, opts?: ReachabilityOpts): boolean;
1622
+ /**
1623
+ * True iff the model's profile exists AND its provider is reachable.
1624
+ * Unknown model id returns false (treat as unreachable; the chain walker
1625
+ * will surface "no reachable models" if everything filters out).
1626
+ */
1627
+ declare function isModelReachable(modelId: string, opts?: ReachabilityOpts): boolean;
1628
+ interface ProviderReachability {
1629
+ reachable: boolean;
1630
+ /** How the key was found. `null` when unreachable. */
1631
+ via: 'apiKeys' | 'env' | null;
1632
+ /** Which env var name supplied the key (only when via === 'env'). */
1633
+ envKeyFound?: string;
1634
+ }
1635
+ /**
1636
+ * Snapshot of which providers are reachable from the current env / apiKeys.
1637
+ * Useful for operator scripts ("kgauto diagnose"), startup-time logging,
1638
+ * and the cost-watcher's "which consumer is missing what" report.
1639
+ *
1640
+ * Does NOT log the key value itself — only the env var name that supplied it.
1641
+ */
1642
+ declare function getReachabilityDiagnostic(opts?: ReachabilityOpts): Record<SupportedProvider, ProviderReachability>;
1643
+ /**
1644
+ * Brain-read env contract — canonical names + accepted fallbacks for the
1645
+ * env vars kgauto's brain-read APIs need.
1646
+ *
1647
+ * Affected APIs: `getActionableAdvisories`, `markAdvisoryResolved`,
1648
+ * `markExclusionFindingHandled`, `markPromoteReadyHandled`,
1649
+ * `getStaleExclusionFindings`, and future brain-read surfaces. Each accepts
1650
+ * `brainEndpoint`/`brainJwt`/`brainAnonKey` as call-site arguments; this
1651
+ * helper centralizes resolution from the consumer's environment.
1652
+ *
1653
+ * Resolution order (first-truthy-trimmed wins):
1654
+ * endpoint = KGAUTO_V2_BRAIN_SUPABASE_URL ?? KGAUTO_V2_BRAIN_URL
1655
+ * jwt = KGAUTO_V2_BRAIN_JWT ?? GLASSBOX_BRAIN_JWT
1656
+ * anonKey = KGAUTO_V2_BRAIN_ANON_KEY (no fallback)
1657
+ *
1658
+ * Why fallbacks exist:
1659
+ *
1660
+ * 1. Pre-alpha.42, some consumers set `KGAUTO_V2_BRAIN_URL` pointing at
1661
+ * the kgauto-dashboard URL (write target). The canonical
1662
+ * `KGAUTO_V2_BRAIN_SUPABASE_URL` is the Supabase project URL (read
1663
+ * target — PostgREST against `/rest/v1/`). Until consumers split the
1664
+ * two names, the fallback grabs whichever URL is set. When BOTH are
1665
+ * set, canonical wins (the consumer has explicitly split).
1666
+ *
1667
+ * 2. The s33 Glass-Box ship provisioned `GLASSBOX_BRAIN_JWT` across all
1668
+ * consumers with the same `app_id` claim shape, signed by the same
1669
+ * JWT_SECRET. Reusing it for brain-read avoids re-minting + re-pasting
1670
+ * a second JWT per consumer per surface.
1671
+ *
1672
+ * `missingEnv` lists the CANONICAL names that aren't satisfied by either
1673
+ * canonical OR fallback. Consumer policy: if `missingEnv.length > 0`,
1674
+ * render `not_configured`; otherwise pass `endpoint`/`jwt`/`anonKey` to
1675
+ * `getActionableAdvisories({ ... })` et al.
1676
+ *
1677
+ * Pre-trim semantics carry from `readKeyValue` — paste-newline-trap
1678
+ * (L-060 / L-083 / L-108) closure extends to brain env vars.
1679
+ *
1680
+ * Filed by tt-intel-Cairn (s89, 2026-05-27) after the s89 actionable-
1681
+ * advisories ref template hit `malformed brain response` on prod because
1682
+ * the endpoint env var pointed at the kgauto-dashboard URL instead of the
1683
+ * Supabase URL, AND because IC's ref template used a third env name
1684
+ * (`KGAUTO_V2_BRAIN_ENDPOINT`) that was unset. Three distinct name shapes
1685
+ * across two consumers — the durable closure is one canonical contract.
1686
+ */
1687
+ interface BrainReadEnv {
1688
+ /** Supabase project URL (PostgREST base). Undefined when neither canonical nor fallback is set. */
1689
+ endpoint?: string;
1690
+ /** JWT carrying `app_id` claim, signed by brain JWT_SECRET. Undefined when neither canonical nor fallback is set. */
1691
+ jwt?: string;
1692
+ /** Supabase anon (publishable) key. Undefined when not set. */
1693
+ anonKey?: string;
1694
+ /**
1695
+ * Canonical names not satisfied by either canonical OR fallback. Subset
1696
+ * (in order) of:
1697
+ * ['KGAUTO_V2_BRAIN_SUPABASE_URL', 'KGAUTO_V2_BRAIN_JWT', 'KGAUTO_V2_BRAIN_ANON_KEY']
1698
+ * Consumer policy: render `not_configured` when length > 0.
1699
+ */
1700
+ missingEnv: string[];
1701
+ }
1702
+ /**
1703
+ * Resolve brain-read env vars. Defaults to `process.env`; pass `envSource`
1704
+ * for hermetic tests. Trims surrounding whitespace and treats
1705
+ * empty-after-trim as unset (same shape as `resolveProviderKey`).
1706
+ */
1707
+ declare function readBrainReadEnv(envSource?: Record<string, string | undefined>): BrainReadEnv;
1708
+
1709
+ /**
1710
+ * getDefaultFallbackChain — the alpha.9 cascading ship.
1711
+ *
1712
+ * Returns a per-archetype fallback chain that walks the cost/performance
1713
+ * Pareto frontier (master plan §1.3 + §3). Three customer postures:
1714
+ *
1715
+ * locked — caller passes [theOneModel]; never call this function
1716
+ * preferred — caller passes `primary`; chain returned is [primary, ...fallbacks]
1717
+ * open — caller passes no `primary`; chain returned is [best, ...fallbacks]
1718
+ *
1719
+ * The chain at each step:
1720
+ * 1. Costs strictly less than the previous (no expensive sideways moves)
1721
+ * 2. Comes from a different provider than the previous step where possible
1722
+ * (correlated outages don't kill consecutive attempts)
1723
+ * 3. Stays above the archetype's perf floor (skip models scored <baseline
1724
+ * for archetypes where degradation would be unacceptable)
1725
+ *
1726
+ * In alpha.9 the chain is **hand-curated** per archetype (§3.3 starter
1727
+ * table). Brain-query mode lands in alpha.10. Policy.blockedModels filters
1728
+ * the result; policy.maxCostPerCallUsd is NOT applied here because the
1729
+ * function doesn't see the IR's token counts — that filtering happens at
1730
+ * `passScoreTargets()` time inside compile().
1731
+ *
1732
+ * The function is **pure** — no brain query, no I/O, no randomness. Same
1733
+ * inputs always produce the same chain.
1734
+ */
1735
+
1736
+ /**
1737
+ * Posture passed into `getDefaultFallbackChain`. The chain function only
1738
+ * sees `'open'` and `'preferred'` — callers in `'locked'` posture should
1739
+ * pass `models: [theOneModel]` directly and skip this function entirely.
1740
+ *
1741
+ * Equivalent to `CompilePolicy.posture` minus `'locked'`. Kept distinct so
1742
+ * the type system enforces "don't ask for a chain when you don't want one."
1743
+ */
1744
+ type FallbackPosture = 'open' | 'preferred';
1745
+ interface GetDefaultFallbackChainOpts {
1746
+ /** The archetype the call is performing. Drives chain shape. */
1747
+ archetype: IntentArchetypeName;
1748
+ /**
1749
+ * The user-selected or caller-anchored primary model. When provided, it
1750
+ * appears at position 0 of the returned chain and fallbacks follow.
1751
+ * When omitted, the function picks the best-perf model for the archetype
1752
+ * as position 0 (open posture).
1753
+ */
1754
+ primary?: string;
1755
+ /**
1756
+ * Informational. `'preferred'` and `'open'` produce the same chain shape
1757
+ * given the same `primary`/no-primary input — posture is a tag the brain
1758
+ * uses to distinguish "user-anchored" from "library-anchored" telemetry.
1759
+ */
1760
+ posture?: FallbackPosture;
1761
+ /**
1762
+ * Cap on chain length. Default 3. Min 1. Useful when the consumer wants
1763
+ * to keep the worst-case latency low (each fallback adds a round-trip).
1764
+ */
1765
+ maxDepth?: number;
1766
+ /**
1767
+ * Consumer-side gating. `blockedModels` are filtered from the chain.
1768
+ * `preferredModels` is informational (no boost applied at this layer —
1769
+ * compile()'s `passScoreTargets` handles preference ranking).
1770
+ * `maxCostPerCallUsd` is NOT applied here — needs IR-level token
1771
+ * estimation. Use compile()'s policy plumbing instead.
1772
+ */
1773
+ policy?: CompilePolicy;
1774
+ /**
1775
+ * alpha.10. When provided, the chain is filtered to models whose provider
1776
+ * has a reachable API key (via `apiKeys` or one of `PROVIDER_ENV_KEYS[provider]`).
1777
+ * Models whose provider can't be reached are silently dropped. If filtering
1778
+ * leaves the chain empty, returns `[]` — caller decides what to do (call()
1779
+ * throws CallError; this function stays pure).
1780
+ *
1781
+ * Pass `{}` to opt in with `process.env` as the env source. Pass `{ apiKeys, envSource }`
1782
+ * for explicit control (tests, non-Node runtimes). Omit entirely for the
1783
+ * legacy unfiltered behavior — preserves alpha.9 callers byte-for-byte.
1784
+ */
1785
+ reachability?: ReachabilityOpts;
1786
+ /**
1787
+ * alpha.20 E3: consumer-declared tool-orchestration shape. Currently
1788
+ * only affects `archetype: 'hunt'`, where 'sequential' swaps the
1789
+ * parallel-tool-tier-0 chain (Flash → Pro → Sonnet → Haiku) for a
1790
+ * DeepSeek-tier-0 chain (V4-Pro → Flash → Sonnet) — DeepSeek's L-040
1791
+ * parallel-tool cliff doesn't apply when the consumer commits to
1792
+ * single-step orchestration.
1793
+ *
1794
+ * Other archetypes are NOT mode-aware in this release — they ship the
1795
+ * same chain regardless of toolOrchestration. Future versions may
1796
+ * extend mode-awareness to ask/generate/etc. when brain evidence
1797
+ * supports it.
1798
+ *
1799
+ * Default (omitted or 'either'): parallel chain. Back-compat with all
1800
+ * pre-alpha.20 callers.
1801
+ */
1802
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
1803
+ }
1804
+ /**
1805
+ * Returns the fallback chain for an archetype as a plain `string[]` of
1806
+ * model ids.
1807
+ *
1808
+ * @deprecated since alpha.21 — prefer
1809
+ * {@link getDefaultFallbackChainWithGrounding}, which returns the same chain
1810
+ * shape with a `grounding` label on every entry (measured / capability-fact /
1811
+ * judgment). The string[] return is preserved indefinitely for back-compat —
1812
+ * no functional change in alpha.21. Existing callers don't need to migrate
1813
+ * unless they want to surface the grounding gap to users.
1814
+ */
1815
+ declare function getDefaultFallbackChain(opts: GetDefaultFallbackChainOpts): string[];
1816
+ /**
1817
+ * Returns a shallow copy of the hand-curated starter chain for an archetype.
1818
+ * Useful for tests + the `scripts/digest.mjs` operator readout.
1819
+ */
1820
+ declare function getStarterChain(archetype: IntentArchetypeName): string[];
1821
+ /**
1822
+ * Returns a shallow copy of all starter chains keyed by archetype.
1823
+ * Useful for the `digest.mjs` readout and consumer audits.
1824
+ */
1825
+ declare function getAllStarterChains(): Record<IntentArchetypeName, string[]>;
1826
+ /**
1827
+ * alpha.20 E3 introspection — returns the sequential-mode overlay for an
1828
+ * archetype, or `undefined` when no overlay is registered (the archetype
1829
+ * is mode-agnostic and reuses `STARTER_CHAINS[archetype]`).
1830
+ *
1831
+ * Useful for tests + the `scripts/digest.mjs` operator readout to surface
1832
+ * the mode-aware chains.
1833
+ */
1834
+ declare function getSequentialStarterChain(archetype: IntentArchetypeName): string[] | undefined;
1835
+ /**
1836
+ * alpha.21 (s78 Entry 1) — returns the fallback chain as `ChainEntry[]`,
1837
+ * with a `grounding` label on every position.
1838
+ *
1839
+ * Same selection logic as {@link getDefaultFallbackChain} (primary anchoring,
1840
+ * blockedModels filter, dedupe, reachability filter, maxDepth cap) — the
1841
+ * only difference is the return shape: each position is a `ChainEntry`
1842
+ * carrying `{ id, grounding, reason?, n? }` instead of a bare string.
1843
+ *
1844
+ * Use this when surfacing the chain to consumers who care WHY each entry
1845
+ * sits where it sits — Glass-Box panels, operator dashboards, eval
1846
+ * scaffolding deciding which entries deserve measurement priority.
1847
+ *
1848
+ * Returns `[]` when filtering empties the chain (same semantics as the
1849
+ * string variant) — consumer decides what to do.
1850
+ */
1851
+ declare function getDefaultFallbackChainWithGrounding(opts: GetDefaultFallbackChainOpts): ChainEntry[];
1852
+ /**
1853
+ * alpha.21 introspection — returns the grounded starter chain for an
1854
+ * archetype (no primary anchoring, no policy filtering, no maxDepth cap).
1855
+ * Use this when you want the raw, hand-curated grounded chain — every
1856
+ * entry carries a `grounding` label and optional reason/n.
1857
+ */
1858
+ declare function getStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[];
1859
+ /**
1860
+ * alpha.21 introspection — all grounded starter chains keyed by archetype.
1861
+ * Useful for the `digest.mjs` readout and consumer audits that want to
1862
+ * surface the grounding gap across the entire chain table.
1863
+ */
1864
+ declare function getAllStarterChainsWithGrounding(): Record<IntentArchetypeName, ChainEntry[]>;
1865
+ /**
1866
+ * alpha.21 introspection — sequential-mode overlay with grounding labels,
1867
+ * or `undefined` when no overlay is registered for the archetype.
1868
+ */
1869
+ declare function getSequentialStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[] | undefined;
1870
+
1871
+ /**
1872
+ * chains-brain — alpha.11 KG-11 adapter.
1873
+ *
1874
+ * Brain-driven STARTER_CHAINS for `getDefaultFallbackChain`. Reads
1875
+ * `kgauto_chains` table via the shared brain-query SWR cache (D6 + D8);
1876
+ * falls back to bundled STARTER_CHAINS on cold-start, brain-down, or
1877
+ * empty/missing table (D2 + D4).
1878
+ *
1879
+ * Behavioral note (locked via D2): the sync API surface returns bundled on
1880
+ * cold-start, with a background refresh fired. Subsequent calls within the
1881
+ * 5-min TTL return brain data. Vercel cold-start consumers see the seed
1882
+ * snapshot (functionally identical to pre-alpha.11); warm-start consumers
1883
+ * see live brain mutations within 5 min.
1884
+ */
1885
+ /**
1886
+ * Sync reader for the brain-driven chains map. Returns bundled
1887
+ * STARTER_CHAINS when brain-query is disabled, cold, or unreachable.
1888
+ */
1889
+ declare const loadChainsFromBrain: () => Record<"ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform", string[]>;
1890
+
1891
+ /**
1892
+ * archetype-perf-brain — alpha.11 KG-12 adapter.
1893
+ *
1894
+ * Brain-driven archetypePerf scores. Substrate for the future closed-loop
1895
+ * tuning engine (KG-12.5): brain telemetry → human or automated bumps →
1896
+ * brain UPDATE → consumers see new scores within 5-min cache TTL with
1897
+ * zero refresh.
1898
+ *
1899
+ * Today: data migrates to brain. No runtime call site reads archetypePerf
1900
+ * (it's metadata for the master plan §2.5 anti-hallucination guardrail +
1901
+ * future auto-tuning). The adapter exists so future readers — auto-tuning
1902
+ * + operator scripts + KG-12.5 — have a shipped substrate to consume.
1903
+ */
1904
+
1905
+ type ArchetypePerfMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
1906
+ /**
1907
+ * alpha.21: per-(model, archetype) row count map. Same shape as
1908
+ * ArchetypePerfMap but stores brain row counts when the brain backs a
1909
+ * placement. Undefined entries → no row count seen → score is the
1910
+ * hand-curated cold-start prior (grounding='judgment').
1911
+ */
1912
+ type ArchetypePerfNMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
1913
+ /**
1914
+ * Sync reader for the brain-driven archetypePerf map. Returns bundled
1915
+ * profile.archetypePerf data when brain-query is disabled, cold, or
1916
+ * unreachable. Identical shape pre/post-alpha.11 by design (D2).
1917
+ */
1918
+ declare const loadArchetypePerfFromBrain: () => ArchetypePerfMap;
1919
+ /**
1920
+ * alpha.21 — sync reader for the brain row-count map paired with
1921
+ * archetype-perf. Returns empty map (no measured backing) on cold start /
1922
+ * brain-down / unreachable — all `getArchetypePerfScore` calls then
1923
+ * resolve to `grounding: 'judgment'`. When the brain table includes an
1924
+ * `n` column on each row, this map mirrors those counts so consumers can
1925
+ * see how many measurements back each score.
1926
+ */
1927
+ declare const loadArchetypePerfNFromBrain: () => ArchetypePerfNMap;
1928
+ /**
1929
+ * Threshold above which a brain row count counts as 'measured' grounding.
1930
+ * Below this, the score is treated as 'judgment' (cold-start prior or
1931
+ * not-yet-enough-evidence). Mirrors the alpha.20 `getCleanPerfScore`
1932
+ * `minRows` default — same rule for consistency.
1933
+ */
1934
+ declare const MEASURED_GROUNDING_MIN_N = 10;
1935
+ /**
1936
+ * alpha.21 — return shape for the extended {@link getArchetypePerfScore}.
1937
+ * Wraps the existing 0..10 score with:
1938
+ *
1939
+ * - `n`: brain row count backing this score (0 when no measurement).
1940
+ * - `grounding`: derived label — 'measured' when n >= 10, else 'judgment'.
1941
+ *
1942
+ * The score itself is unchanged from pre-alpha.21 (numeric, 5 = neutral
1943
+ * default). 'capability-fact' is NOT a perf-score grounding — capability
1944
+ * decisions live on chain entries, not on perf scores.
1945
+ */
1946
+ interface ArchetypePerfScoreResult {
1947
+ /** 0..10 perf score. 5 = neutral default when no entry exists. */
1948
+ score: number;
1949
+ /**
1950
+ * Brain row count backing this score. 0 when bundled (cold-start prior)
1951
+ * or when the brain row didn't carry an `n` column.
1952
+ */
1953
+ n: number;
1954
+ /**
1955
+ * Provenance — 'measured' when `n >= 10`, else 'judgment'.
1956
+ * Never 'capability-fact' (that label is reserved for chain-entry
1957
+ * inclusion/exclusion decisions).
1958
+ */
1959
+ grounding: Grounding;
1960
+ }
1961
+ /**
1962
+ * Per-model accessor with grounding (alpha.21). Returns 5 (neutral) when no
1963
+ * entry is found — consistent with the master plan §3.3 "missing archetypes
1964
+ * default to 5" convention documented in profiles.ts
1965
+ * ModelProfile.archetypePerf.
1966
+ *
1967
+ * Backwards-compat note: pre-alpha.21 callers expected `number` here. The
1968
+ * new return shape `{ score, n, grounding }` is a breaking shape change at
1969
+ * the type level, but `.score` carries the legacy value. Callers reading
1970
+ * `.score` field-by-field continue working; callers using the bare number
1971
+ * arithmetically need to switch to `.score`. The migration is single-line
1972
+ * (`const x = getArchetypePerfScore(...)` → `const x = getArchetypePerfScore(...).score`).
1973
+ */
1974
+ declare function getArchetypePerfScore(modelId: string, archetype: IntentArchetypeName): ArchetypePerfScoreResult;
1975
+
1976
+ /**
1977
+ * pricing-brain — alpha.11 KG-13 adapter.
1978
+ *
1979
+ * Brain-driven pricing data with **time-bounded resolution** (`valid_from`
1980
+ * / `valid_until` columns). The V4-Pro 75%-off promo through 2026-05-31
1981
+ * gets modeled as two rows; `at` parameter resolution picks the correct
1982
+ * row per call timestamp. Promo flips happen automatically at the
1983
+ * boundary without alpha cuts.
1984
+ *
1985
+ * SWR cache holds the FULL pricing snapshot (all active rows for all
1986
+ * models). Per-call `at` filtering is in-memory — keeps the SWR semantics
1987
+ * uniform with other adapters (one cache, one snapshot, sync reads).
1988
+ */
1989
+ interface PricingRow {
1990
+ modelId: string;
1991
+ costInputPer1m: number;
1992
+ costOutputPer1m: number;
1993
+ cacheInputPer1m?: number;
1994
+ cacheCreationPer1m?: number;
1995
+ validFrom: number;
1996
+ validUntil?: number;
1997
+ source?: string;
1998
+ }
1999
+ /**
2000
+ * Sync reader for the brain-driven pricing snapshot. Returns bundled
2001
+ * profile pricing when brain-query is disabled, cold, or unreachable.
2002
+ * Caller filters by `at` via {@link resolvePricingAt}.
2003
+ */
2004
+ declare const loadPricingFromBrain: () => PricingRow[];
2005
+ /**
2006
+ * Resolve the active pricing row for a model at a given timestamp.
2007
+ * Picks the row with the latest `valid_from <= at` whose
2008
+ * `valid_until > at` (or NULL — open-ended).
2009
+ *
2010
+ * Returns `undefined` when no row matches. Callers should fall back to
2011
+ * profile static pricing in that case.
2012
+ */
2013
+ declare function resolvePricingAt(modelId: string, at?: Date): PricingRow | undefined;
2014
+
2015
+ /**
2016
+ * models-brain — alpha.11 KG-14 adapter (the largest of the four).
2017
+ *
2018
+ * Brain-driven model registry + aliases. Two adapters share the same
2019
+ * SWR snapshot:
2020
+ *
2021
+ * - `loadModelsFromBrain()` — `Map<modelId, ModelProfile>` from
2022
+ * `kgauto_models` table (cliffs/lowering/recovery as JSONB columns).
2023
+ * - `loadAliasesFromBrain()` — `Record<aliasId, canonicalId>` from
2024
+ * `kgauto_aliases` table.
2025
+ *
2026
+ * After alpha.11, new-model onboarding becomes brain INSERT (vs PR + alpha
2027
+ * cut + 3 consumer refreshes). The auto-onboard pipeline
2028
+ * (`scripts/check-model-releases.mjs`) shifts from emitting profile.ts
2029
+ * edits to writing brain rows directly.
2030
+ *
2031
+ * **D5 — alias resolution stable regardless of canonical's active state.**
2032
+ * `canonicalId('deepseek-chat') → 'deepseek-v4-flash'` even when the
2033
+ * canonical row is `active=false`. Aliases are wire-format contracts;
2034
+ * legacy callers' resolution promise outlives the canonical's active
2035
+ * status. Deprecation (`active=false`) affects chain composition only.
2036
+ */
2037
+
2038
+ /**
2039
+ * Exported brain-row shape for `kgauto_models`. Mirrors the SQL table
2040
+ * (`v2/brain/migrations/010_kgauto_models_and_aliases.sql`) — column names
2041
+ * are snake_case to match PostgREST. Used by operator scripts that write
2042
+ * to brain (auto-onboard, promote-model) — see `profileToRow()`.
2043
+ *
2044
+ * Read path stays internal via `RawModelRow` to keep `rowToProfile()`'s
2045
+ * tolerance contract from leaking into write callers.
2046
+ */
2047
+ interface ModelBrainRow {
2048
+ model_id: string;
2049
+ provider: string;
2050
+ status?: string;
2051
+ max_context_tokens?: number;
2052
+ max_output_tokens?: number;
2053
+ max_tools?: number;
2054
+ parallel_tool_calls?: boolean;
2055
+ structured_output?: string;
2056
+ system_prompt_mode?: string;
2057
+ streaming?: boolean;
2058
+ cliffs?: unknown;
2059
+ lowering?: unknown;
2060
+ recovery?: unknown;
2061
+ strengths?: string[] | null;
2062
+ weaknesses?: string[] | null;
2063
+ cost_input_per_1m?: number;
2064
+ cost_output_per_1m?: number;
2065
+ notes?: string | null;
2066
+ verified_against_docs?: string | null;
2067
+ archetype_perf?: Record<string, number> | null;
2068
+ version_added?: string;
2069
+ version_removed?: string | null;
2070
+ active?: boolean;
2071
+ /** alpha.41 — model-family tag (migration 024 column). */
2072
+ family?: string | null;
2073
+ /** alpha.49 — explicit latency bucket (migration 028 column). */
2074
+ latency_tier?: string | null;
2075
+ /** alpha.49 — per-archetype prompt-shape conventions (migration 028 column). */
2076
+ archetype_conventions?: ArchetypeConvention[] | null;
2077
+ }
2078
+ interface ProfileToRowOptions {
2079
+ /** e.g. `'2.0.0-alpha.12'` — leave undefined to omit from row. */
2080
+ versionAdded?: string;
2081
+ /** Pass `null` to clear; omit to leave field unset. */
2082
+ versionRemoved?: string | null;
2083
+ /** Defaults to true if omitted. */
2084
+ active?: boolean;
2085
+ /**
2086
+ * Override verifiedAgainstDocs (e.g. set to `null` for auto-onboard).
2087
+ * When omitted, the profile's own value is used. Pass `null` explicitly
2088
+ * to write a SQL NULL (e.g. unverified auto-onboard rows).
2089
+ */
2090
+ verifiedAgainstDocs?: string | null;
2091
+ }
2092
+ /**
2093
+ * Inverse of `rowToProfile` — serialize a `ModelProfile` to a `kgauto_models`
2094
+ * row payload for INSERT/UPSERT. Used by operator scripts that write to
2095
+ * brain (auto-onboard pipeline, promote-model verification CLI).
2096
+ *
2097
+ * Row-level fields (`version_added`, `version_removed`, `active`) are
2098
+ * operator-controlled and pass through `opts`. `verifiedAgainstDocs` can
2099
+ * also be overridden via `opts` — auto-onboard explicitly passes `null` to
2100
+ * mark unverified rows (the column is DATE, doesn't accept the
2101
+ * `'UNVERIFIED-AUTO-ONBOARD'` sentinel used in PROFILES_RAW).
2102
+ */
2103
+ declare function profileToRow(profile: ModelProfile, opts?: ProfileToRowOptions): ModelBrainRow;
2104
+ /**
2105
+ * Sync reader for the brain-driven model registry. Returns bundled
2106
+ * PROFILES_RAW when brain-query is disabled, cold, or unreachable.
2107
+ */
2108
+ declare const loadModelsFromBrain: () => Map<string, ModelProfile>;
2109
+ /**
2110
+ * Sync reader for the brain-driven aliases map. Returns bundled ALIASES
2111
+ * when brain-query is disabled, cold, or unreachable.
2112
+ *
2113
+ * D5: this map carries both active and inactive canonical mappings —
2114
+ * alias resolution is stable regardless of canonical's `active` state.
2115
+ */
2116
+ declare const loadAliasesFromBrain: () => Record<string, string>;
2117
+
2118
+ /**
2119
+ * exclusion-findings-brain — alpha.38 KG-19 adapter.
2120
+ *
2121
+ * Per-tenant SWR cache for the `exclusion_findings` table populated by the
2122
+ * `kgauto-exclusion-re-evaluation-watch` cron (alpha.37 substrate). Distinct
2123
+ * from the cross-tenant `brain-query.ts` snapshot because exclusion findings
2124
+ * are scoped per `app_id` — one process = one consumer = one appId, but the
2125
+ * cache key supports multi-app processes by keying snapshots by appId.
2126
+ *
2127
+ * Architecture mirrors `brain-query.ts` but with a per-(appId) snapshot:
2128
+ *
2129
+ * - **Sync API surface.** `getStaleExclusionFindings({ appId, archetype })`
2130
+ * returns `ExclusionFindingRow[]` immediately. First call returns the
2131
+ * bundled fallback (empty array); async refresh fires in background;
2132
+ * subsequent calls within TTL return brain data.
2133
+ *
2134
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
2135
+ * per appId per TTL window. Tests can reset between cases.
2136
+ *
2137
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
2138
+ * silent bundled fallback (empty array). Never throws. Warns once per
2139
+ * process per error to avoid log spam.
2140
+ *
2141
+ * - **Opt-in.** Activation gated on `configureExclusionFindingsBrain()`
2142
+ * having been called with a runtime. The public `configureBrain()` in
2143
+ * brain.ts wires this up automatically when `BrainConfig.brainQuery
2144
+ * .findingsExclusions !== false`.
2145
+ *
2146
+ * Default endpoint:
2147
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`
2148
+ * The route accepts `?app_id=X` and returns a JSON array of findings
2149
+ * for that app filtered to `resolved_at IS NULL`. Public read; data
2150
+ * carries no consumer PII (app id, archetype, model id, cost ratio,
2151
+ * savings estimate).
2152
+ */
2153
+ /**
2154
+ * Shape of one row from the `exclusion_findings` cache table. Mirrors the
2155
+ * snake_case JSONB returned by the brain RPC + the dashboard endpoint.
2156
+ * Camel-case mapping happens at the boundary (rowToFinding) so the in-memory
2157
+ * shape stays consistent with the rest of the library.
2158
+ */
2159
+ interface ExclusionFindingRow {
2160
+ /** Intent archetype the finding applies to (e.g. 'hunt', 'classify'). */
2161
+ archetype: string;
2162
+ /** Canonical model id that the consumer has excluded (zero traffic in window). */
2163
+ excludedModel: string;
2164
+ /** Provider of the excluded model (e.g. 'deepseek', 'openai'). */
2165
+ excludedProvider: string;
2166
+ /** Detection verdict — alpha.37 ships 'recommend-probe' only. */
2167
+ verdict: 'recommend-probe' | 'unblock' | 'stay-excluded' | 'inconclusive';
2168
+ /**
2169
+ * Estimated 30-day savings in USD if the excluded model becomes primary
2170
+ * on this archetype. Null when pricing is incomplete or excluded model is
2171
+ * more expensive than the leader.
2172
+ */
2173
+ estimatedSavingsUsd30d: number | null;
2174
+ /** Renderable summary; produced by the detector / RPC. */
2175
+ message: string;
2176
+ /** Actionable recommendation; produced by the detector / RPC. */
2177
+ suggestion: string;
2178
+ /** Detector confidence tier. */
2179
+ confidence: 'high' | 'medium' | 'low';
2180
+ /**
2181
+ * Free-form evidence pack (cost ratio, leader info, promo flags, parallel-
2182
+ * tool hint, etc.). Surfaced verbatim to advisor rules for richer messages.
2183
+ * Optional — older detector runs may not populate every field.
2184
+ */
2185
+ evidence?: Record<string, unknown>;
2186
+ }
2187
+ /**
2188
+ * Default endpoint hosted on the kgauto-dashboard. Public read — data carries
2189
+ * no PII (app id, archetype, model id, cost ratio, savings estimate). Mirrors
2190
+ * the cross-tenant `/api/kgauto-v2/config` pattern.
2191
+ */
2192
+ declare const DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
2193
+ /**
2194
+ * Sync introspection — is the findings-brain active? Used by advisor rules
2195
+ * to decide whether to even attempt a read.
2196
+ */
2197
+ declare function isExclusionFindingsBrainActive(): boolean;
2198
+ interface GetExclusionFindingsOpts {
2199
+ /** App id to read findings for. Required. */
2200
+ appId: string;
2201
+ /**
2202
+ * Optional archetype filter. When set, returns only findings where
2203
+ * `archetype` matches. When omitted, returns all findings for the app.
2204
+ */
2205
+ archetype?: string;
2206
+ }
2207
+ /**
2208
+ * Sync reader. Returns the cached findings for `appId`, optionally filtered
2209
+ * to a single archetype. First call returns empty array and triggers async
2210
+ * refresh; subsequent calls within TTL return brain data.
2211
+ *
2212
+ * NEVER throws. Brain down / endpoint misconfigured / mapper exception →
2213
+ * empty array.
2214
+ */
2215
+ declare function getStaleExclusionFindings(opts: GetExclusionFindingsOpts): ExclusionFindingRow[];
2216
+
2217
+ /**
2218
+ * Family resolution — alpha.41.
2219
+ *
2220
+ * "I want the latest Opus" → kgauto picks the current+active model in the
2221
+ * `claude-opus` family. Closes the loop where consumer code carries hardcoded
2222
+ * `claude-opus-4-6` literals long after `claude-opus-4-7` ships and goes
2223
+ * current — the s47 trigger (IC's `generate` chain still routing 43 calls to
2224
+ * legacy 4-6 in production).
2225
+ *
2226
+ * Two surfaces:
2227
+ * - `getRecommendedPrimary({ family, ..., fallback })` — public, sync,
2228
+ * used at IR-construction time when the consumer wants a literal id back
2229
+ * (with a fallback floor for cold-start brain).
2230
+ * - `resolveFamilyEntry({ family, archetype?, appId? })` — internal,
2231
+ * called from compile() when an IR's `models[]` entry is shaped
2232
+ * `{ family: string }`. Throws `FamilyResolutionError` on failure.
2233
+ *
2234
+ * Both routes share the same algorithm (locked in the alpha.41 Phase 0
2235
+ * design contract); they differ only in the fallback ergonomics. The
2236
+ * public route accepts a required `fallback: string`; the IR route throws.
2237
+ *
2238
+ * Pure resolution. No network. No async. Brain-registry reads go through
2239
+ * the existing SWR cache (`loadModelsFromBrain` from `models-brain.ts`) —
2240
+ * cold-start returns bundled profiles, which still resolve via the
2241
+ * `deriveFamilyFromModelId` fallback when the brain row's `family` column
2242
+ * is null (G1 contract: graceful pre-migration behavior).
2243
+ *
2244
+ * @see command-center/advisory/kgauto/2026-05-26_alpha-41-model-family-aliases-and-promotion-probe-watcher.md
2245
+ */
2246
+
2247
+ interface GetRecommendedPrimaryOptions {
2248
+ /**
2249
+ * Family tag (e.g. `'claude-opus'`, `'gemini-flash'`). See the Phase 0
2250
+ * design contract's family taxonomy table for the locked initial set;
2251
+ * extensible via brain migrations.
2252
+ */
2253
+ family: string;
2254
+ /**
2255
+ * Optional archetype gate. When provided, candidates must clear
2256
+ * {@link ARCHETYPE_FLOOR_DEFAULT} on `archetypePerf[archetype]`. Also used
2257
+ * as the primary sort key (DESC) when multiple candidates qualify.
2258
+ */
2259
+ archetype?: IntentArchetypeName;
2260
+ /**
2261
+ * Optional consumer-app id. When provided, candidates matching a
2262
+ * `stay-excluded` finding for `(appId, archetype)` in the
2263
+ * exclusion-findings cache (alpha.38 substrate) are filtered out.
2264
+ */
2265
+ appId?: string;
2266
+ /**
2267
+ * Consumer-posture tag. `'locked'` short-circuits resolution and returns
2268
+ * the literal `fallback` unconditionally — useful for compliance /
2269
+ * contract / brand-promise flows where the consumer doesn't want kgauto
2270
+ * picking the model on their behalf.
2271
+ */
2272
+ posture?: 'preferred' | 'open' | 'locked';
2273
+ /**
2274
+ * Last-resort literal model id. REQUIRED. Returned when (a) brain
2275
+ * registry is cold / no candidates exist, (b) `posture === 'locked'`,
2276
+ * (c) every candidate was filtered out by archetype / exclusion gates.
2277
+ *
2278
+ * The fallback is NOT validated against the family — kgauto trusts the
2279
+ * consumer to pass a meaningful floor. The contract intent is "even when
2280
+ * everything below is on fire, you still get a model id back."
2281
+ */
2282
+ fallback: string;
2283
+ }
2284
+ /**
2285
+ * Thrown by `resolveFamilyEntry` (the internal compile-time twin) when a
2286
+ * `{ family: string }` IR entry can't resolve to any current+active model.
2287
+ * Surfaces with the family string + a one-line cause so consumer error
2288
+ * handling can distinguish "you typo'd the family tag" from "brain is cold
2289
+ * and nothing matches."
2290
+ *
2291
+ * The public `getRecommendedPrimary` does NOT throw — it returns
2292
+ * `fallback` instead.
2293
+ */
2294
+ declare class FamilyResolutionError extends Error {
2295
+ readonly family: string;
2296
+ readonly cause: string;
2297
+ constructor(family: string, cause: string);
2298
+ }
2299
+ /**
2300
+ * Deterministic model_id → family inference. Pure function; no brain
2301
+ * lookup. Used as the runtime fallback when a brain row's `family` column
2302
+ * is null (pre-migration 024) and as the canonical mapping that migration
2303
+ * 024's CASE statement mirrors.
2304
+ *
2305
+ * Returns null for unrecognized ids — caller must handle (typically by
2306
+ * skipping the row in family resolution).
2307
+ *
2308
+ * Order matters: more specific patterns first (e.g. `flash-lite` before
2309
+ * `flash`; `pro` before `chat`). The brain-side CASE statement uses the
2310
+ * same priority.
2311
+ */
2312
+ declare function deriveFamilyFromModelId(modelId: string): string | null;
2313
+ /**
2314
+ * Public sync resolver. Pure (modulo brain snapshot read). Returns the
2315
+ * literal model id of the best candidate, or `fallback` when resolution
2316
+ * yields nothing.
2317
+ */
2318
+ declare function getRecommendedPrimary(opts: GetRecommendedPrimaryOptions): string;
2319
+
2320
+ /**
2321
+ * promote-ready-brain — alpha.41 substrate.
2322
+ *
2323
+ * Per-tenant SWR cache for the `promote_ready_findings` table populated by
2324
+ * the autonomous `promotion-probe-watcher` (Mode 2). Mirrors
2325
+ * `exclusion-findings-brain.ts` shape byte-for-byte where applicable; this
2326
+ * is the read-side substrate for the compile-time `promote-ready` advisor
2327
+ * rule.
2328
+ *
2329
+ * Architecture (mirror of exclusion-findings-brain):
2330
+ *
2331
+ * - **Sync API surface.** `getPromoteReadyFindings({ appId, archetype,
2332
+ * family })` returns `PromoteReadyFindingRow[]` immediately. First call
2333
+ * returns the bundled fallback (empty array); async refresh fires in
2334
+ * background; subsequent calls within TTL return brain data.
2335
+ *
2336
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
2337
+ * per appId per TTL window. Tests reset between cases via
2338
+ * `_testResetPromoteReadyFindings()`.
2339
+ *
2340
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
2341
+ * silent bundled fallback (empty array). Never throws. Warns once per
2342
+ * process per error to avoid log spam.
2343
+ *
2344
+ * - **Opt-in.** Activation gated on `configurePromoteReadyBrain()` having
2345
+ * been called with a runtime. The public `configureBrain()` in brain.ts
2346
+ * wires this up automatically when
2347
+ * `BrainConfig.brainQuery.findingsPromoteReady !== false`.
2348
+ *
2349
+ * Plus: `markPromoteReadyHandled` — direct PostgREST PATCH against the
2350
+ * brain (no kgauto proxy). Mirrors `markExclusionFindingHandled` shape
2351
+ * byte-for-byte. Idempotent on `resolved_at=is.null` filter.
2352
+ *
2353
+ * Default endpoint:
2354
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/promote-ready`
2355
+ * The route accepts `?app_id=X` and returns a JSON array of findings
2356
+ * for that app filtered to `resolved_at IS NULL`.
2357
+ */
2358
+
2359
+ /**
2360
+ * Shape of one row from the `promote_ready_findings` cache table. Mirrors
2361
+ * the snake_case JSONB returned by the brain endpoint, mapped to camelCase
2362
+ * at the boundary (rowToFinding) so the in-memory shape stays consistent
2363
+ * with the rest of the library.
2364
+ */
2365
+ interface PromoteReadyFindingRow {
2366
+ /** Intent archetype the finding applies to. */
2367
+ archetype: string;
2368
+ /** Model family (e.g. 'claude-opus', 'gemini-flash'). */
2369
+ family: string;
2370
+ /** The candidate model that the probe validated. */
2371
+ candidateModel: string;
2372
+ /** The current production model the candidate was compared against. */
2373
+ currentModel: string;
2374
+ /** Sample size of the probe run (typically 10). */
2375
+ sampleN: number;
2376
+ /** Fraction of probes where the judge verdict was 'candidate-better' or
2377
+ * 'tied'. 0.000 to 1.000. */
2378
+ judgePassRate: number;
2379
+ /** Mean judge score across the probe sample. 1.00 to 5.00. */
2380
+ judgeAvgScore: number;
2381
+ /** Signed cost delta as a fraction (negative = candidate is cheaper).
2382
+ * Null when pricing data was incomplete at probe time. */
2383
+ costDeltaPct: number | null;
2384
+ /** ISO timestamp of detection (when the probe wrote the row). */
2385
+ detectedAt: string;
2386
+ }
2387
+ /**
2388
+ * Resolution sources supported by alpha.41 `markPromoteReadyHandled`. The
2389
+ * three values map to the three CHECK-constrained resolution values on
2390
+ * `promote_ready_findings.resolution`:
2391
+ *
2392
+ * - `'promoted'` — consumer migrated to the candidate model. Strong
2393
+ * positive signal; the probe was right.
2394
+ * - `'declined'` — consumer evaluated and chose not to promote.
2395
+ * Strong negative signal; revisit only on new
2396
+ * family entries or material score swings.
2397
+ * - `'still-evaluating'` — consumer acknowledges the finding but defers
2398
+ * the decision. Acknowledges-without-deciding;
2399
+ * finding silences this cycle but next probe may
2400
+ * re-surface.
2401
+ */
2402
+ type PromoteReadyResolution = 'promoted' | 'declined' | 'still-evaluating';
2403
+ interface MarkPromoteReadyHandledOptions {
2404
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
2405
+ appId: string;
2406
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
2407
+ archetype: IntentArchetypeName | string;
2408
+ /** Model family the finding applies to (e.g. 'claude-opus'). */
2409
+ family: string;
2410
+ /** Resolution semantics — see `PromoteReadyResolution`. */
2411
+ resolution: PromoteReadyResolution;
2412
+ /** Optional free-form note explaining the decision. */
2413
+ resolutionNote?: string;
2414
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). */
2415
+ brainEndpoint: string;
2416
+ /** Consumer-scoped JWT carrying the `app_id` claim. */
2417
+ brainJwt: string;
2418
+ /** Supabase anon key for the `apikey` header. */
2419
+ brainAnonKey: string;
2420
+ /** Injected fetch for tests. Defaults to global fetch. */
2421
+ fetch?: typeof fetch;
2422
+ }
2423
+ /**
2424
+ * Mark a probe-validated promote-ready finding as handled. Returns an
2425
+ * `ok/reason` envelope matching `markExclusionFindingHandled`.
2426
+ *
2427
+ * Idempotent: if no row matches the (app_id, archetype, family) tuple
2428
+ * (already resolved, never existed, watcher not yet UPSERTed), PostgREST
2429
+ * returns 200/204 with zero affected rows and we return `{ ok: true }`.
2430
+ *
2431
+ * Reasons surfaced on failure:
2432
+ * - `app_id_required` / `archetype_required` / `family_required`
2433
+ * - `resolution_invalid` — not one of the three documented values
2434
+ * - `brain_auth_misconfig` — 401/403
2435
+ * - `brain_unavailable` — 5xx
2436
+ * - `network_error:<message>` — fetch threw
2437
+ * - `patch_failed:<status>` — anything else non-2xx
2438
+ */
2439
+ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions): Promise<{
2440
+ ok: true;
2441
+ } | {
2442
+ ok: false;
2443
+ reason: string;
2444
+ }>;
226
2445
 
227
2446
  /**
228
2447
  * @warmdrift/kgauto v2 — prompt compiler + central learning brain.
@@ -270,4 +2489,4 @@ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: Model
270
2489
  */
271
2490
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
272
2491
 
273
- 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, PromptIR, ProviderOverrides, RecordInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, execute, record, resetTokenizer, runAdvisor, setTokenizer };
2492
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, Grounding, IntentArchetypeName, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, compileForAISDKv6, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, peekBrainDeadLetter, probeShadow, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };