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

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