@warmdrift/kgauto-compiler 2.0.0-alpha.5 → 2.0.0-alpha.52

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