@warmdrift/kgauto-compiler 2.0.0-alpha.4 → 2.0.0-alpha.41

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 +87 -3
  2. package/dist/chunk-JQGRWJZO.mjs +1216 -0
  3. package/dist/chunk-NBO4R5PC.mjs +313 -0
  4. package/dist/chunk-P3TOAEG4.mjs +56 -0
  5. package/dist/chunk-RO22VFIF.mjs +29 -0
  6. package/dist/chunk-XJZRDGHF.mjs +683 -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 +2473 -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 +1706 -9
  24. package/dist/index.d.ts +1706 -9
  25. package/dist/index.js +4743 -312
  26. package/dist/index.mjs +2935 -275
  27. package/dist/ir-DYpvUSEw.d.ts +1197 -0
  28. package/dist/ir-D_kgJcaV.d.mts +1197 -0
  29. package/dist/profiles.d.mts +164 -2
  30. package/dist/profiles.d.ts +164 -2
  31. package/dist/profiles.js +820 -11
  32. package/dist/profiles.mjs +5 -1
  33. package/dist/types-C8gOJ7hV.d.ts +149 -0
  34. package/dist/types-CYY769Ls.d.mts +149 -0
  35. package/dist/types-DigtHnEt.d.ts +131 -0
  36. package/dist/types-MkiWUPM8.d.mts +131 -0
  37. package/package.json +42 -6
  38. package/dist/chunk-MBEI5UOM.mjs +0 -409
  39. package/dist/profiles-CDttLtaD.d.ts +0 -521
  40. package/dist/profiles-CH_nKPjp.d.mts +0 -521
package/dist/index.d.ts 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-CDttLtaD.js';
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-CDttLtaD.js';
3
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, IntentArchetypeName, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, B as BestPracticeAdvisory, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-DYpvUSEw.js';
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, T as ToolCall, x as ToolDefinition } from './ir-DYpvUSEw.js';
3
+ import { ModelProfile } from './profiles.js';
4
+ export { ALIASES, CacheStrategy, CliffRule, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, profilesByProvider, tryGetProfile } from './profiles.js';
5
+ import { IntentArchetypeName } from './dialect.js';
6
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
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;
@@ -83,15 +104,128 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
83
104
  declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
84
105
 
85
106
  /**
86
- * Brain client fire-and-forget telemetry to the central kgauto Supabase.
107
+ * alpha.33AI-SDK streamText helpers.
87
108
  *
88
- * The brain is the centralized learning store. Apps POST outcomes here;
89
- * mutations flow back through a separate pull (in v2.1).
109
+ * The cross-consumer pattern surfaced 2026-05-20 (`streamText-cache-marker-
110
+ * propagation-gap` on `command-center/interfaces/kgauto.md ## Requested`):
111
+ * AI-SDK consumers using `streamText({ system: <string>, messages:
112
+ * convertToModelMessages(messages), model })` silently drop the Anthropic
113
+ * `cache_control` markers the compiler emits on `result.request.messages`.
114
+ * Two losses on that line:
115
+ * (a) `convertToModelMessages()` reads raw inputs not the lowered output,
116
+ * dropping per-message providerOptions; and
117
+ * (b) `streamText({ system: '<string>' })` strips any providerOptions
118
+ * on the system prefix.
90
119
  *
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.
120
+ * Net effect prior to this surface: `cache_read_input_tokens = 0` across
121
+ * every measured production call by IC + tt-intel even though both
122
+ * consumers had `historyCachePolicy: { strategy: 'all-but-latest' }` wired
123
+ * since alpha.5. The compiler did the right thing; the consumer integration
124
+ * pattern lost the markers at the wire boundary.
125
+ *
126
+ * This helper closes the gap. Pass the consumer's already-converted messages
127
+ * + the kgauto CompileResult and get back a `{ system, messages }` pair
128
+ * with cacheControl re-attached at the deterministic indices the compiler
129
+ * computed (`diagnostics.historyCacheMarkIndex` + `systemMessages` with
130
+ * its own cacheControl markers).
131
+ *
132
+ * No I/O. Pure transform. Idempotent — calling twice with the same inputs
133
+ * produces structurally-identical output.
93
134
  */
94
135
 
136
+ /**
137
+ * AI-SDK-shaped converted-message structure. Matches what
138
+ * `convertToModelMessages()` returns at the wire layer. We don't import
139
+ * the AI-SDK type to avoid pulling that dep into the kgauto-compiler
140
+ * package — consumers pass their own already-converted messages.
141
+ */
142
+ interface AISDKConvertedMessage {
143
+ role: 'system' | 'user' | 'assistant' | 'tool';
144
+ content: unknown;
145
+ providerOptions?: {
146
+ anthropic?: {
147
+ cacheControl?: {
148
+ type: 'ephemeral';
149
+ };
150
+ };
151
+ };
152
+ }
153
+ /**
154
+ * Result of `attachCacheControlToStreamTextInput()` — ready to spread into
155
+ * `streamText(...)` directly.
156
+ *
157
+ * The `system` field is either the structured `SystemModelMessage[]` form
158
+ * (when the compiler computed at least one cacheable section + chose
159
+ * Anthropic) or the flat-string concatenation (when no cacheable sections
160
+ * exist OR the provider isn't Anthropic). Consumers can pass either form
161
+ * to `streamText({ system })` — the AI-SDK accepts both.
162
+ */
163
+ interface AttachCacheControlResult {
164
+ system: string | SystemModelMessage[];
165
+ messages: AISDKConvertedMessage[];
166
+ }
167
+ /**
168
+ * Attach Anthropic cache_control markers to a streamText input that the
169
+ * consumer has already prepared via `convertToModelMessages()`. Reads
170
+ * `result.diagnostics.historyCacheMarkIndex` for the position-on-history
171
+ * marker and `result.systemMessages` for the per-section system markers.
172
+ *
173
+ * The flat-string `system` form is returned when:
174
+ * - the compiler produced no `systemMessages` (e.g., zero sections kept), or
175
+ * - the chosen provider is not Anthropic, so cacheControl wouldn't
176
+ * achieve anything at the wire layer (other providers cache implicitly
177
+ * based on prefix shape, no marker needed).
178
+ *
179
+ * Otherwise the structured `SystemModelMessage[]` form is returned —
180
+ * preserves the per-section cacheControl markers across `streamText`.
181
+ *
182
+ * @param result - kgauto CompileResult from `compile(ir, opts)`
183
+ * @param convertedMessages - the consumer's already-converted messages
184
+ * (from `convertToModelMessages(rawMessages)` in their AI-SDK call site)
185
+ * @returns `{ system, messages }` ready to spread into `streamText(...)`
186
+ */
187
+ declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
188
+
189
+ /**
190
+ * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
191
+ * perf / pricing / models registry). Enabled by default when endpoint is
192
+ * set; per-table opt-out via explicit `false`.
193
+ *
194
+ * Locked via /plan-eng-review 2026-05-15 (decision D3). Structured group
195
+ * keeps the BrainConfig surface clean as more brain-driven tables ship.
196
+ */
197
+ interface BrainQueryConfig {
198
+ /** Default true when endpoint set. Brain-driven fallback chains. */
199
+ chains?: boolean;
200
+ /** Default true when endpoint set. Brain-driven archetype perf scores. */
201
+ perf?: boolean;
202
+ /** Default true when endpoint set. Brain-driven pricing with at-time resolution. */
203
+ pricing?: boolean;
204
+ /** Default true when endpoint set. Brain-driven model registry + aliases. */
205
+ models?: boolean;
206
+ /**
207
+ * alpha.38 — opt-in compile-time advisor for stale exclusions. Default
208
+ * `true` when endpoint is set. When enabled, the library reads
209
+ * `exclusion_findings` from the central kgauto-dashboard for the consumer's
210
+ * `app_id` (no consumer-side proxy work required) and surfaces a
211
+ * `stale-exclusion-candidate` advisory when compile()'s archetype has a
212
+ * recommend-probe finding open. Set `false` to silence (no fetch, no
213
+ * advisory).
214
+ */
215
+ findingsExclusions?: boolean;
216
+ /** SWR window in ms. Default 300_000 (5 min). */
217
+ cacheTtlMs?: number;
218
+ /** Override the GET URL when the read endpoint differs from the write one.
219
+ * Defaults to `${endpoint}/v2/config` when omitted. */
220
+ configEndpoint?: string;
221
+ /**
222
+ * alpha.38 — override the findings endpoint when the consumer wants to
223
+ * proxy `exclusion_findings` reads through their own service rather than
224
+ * reading directly from the kgauto-dashboard. Library appends `?app_id=X`.
225
+ * Defaults to `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`.
226
+ */
227
+ findingsEndpoint?: string;
228
+ }
95
229
  interface BrainConfig {
96
230
  /** Brain HTTP endpoint base URL (e.g., https://kgauto-brain.vercel.app/api). */
97
231
  endpoint: string;
@@ -103,6 +237,9 @@ interface BrainConfig {
103
237
  sync?: boolean;
104
238
  /** Optional fetch override (for tests). */
105
239
  fetchImpl?: typeof fetch;
240
+ /** alpha.11 — brain-query mode for config tables. Default-on per table
241
+ * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
242
+ brainQuery?: BrainQueryConfig;
106
243
  }
107
244
  declare function configureBrain(config: BrainConfig): void;
108
245
  declare function clearBrain(): void;
@@ -114,6 +251,90 @@ declare function clearBrain(): void;
114
251
  * network error is swallowed/forwarded to onError.
115
252
  */
116
253
  declare function record(input: RecordInput): Promise<void>;
254
+ /**
255
+ * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
256
+ *
257
+ * Exported so consumer proxies can `import { OutcomePayload } from
258
+ * '@warmdrift/kgauto-compiler'` instead of redefining the shape — that way
259
+ * TypeScript catches future schema additions (cache fields, advisory
260
+ * telemetry, etc.) at consumer build time, not silently at runtime.
261
+ *
262
+ * **Forward-compat rule:** consumer proxies should pass the body through to
263
+ * Supabase rather than reconstructing field-by-field. The recommended shape
264
+ * is `const row = { ...body }` (or `await supabase.from('compile_outcomes')
265
+ * .insert(body)` directly). Filtering proxies break schema evolution
266
+ * silently — see s17 root-cause investigation 2026-05-10.
267
+ */
268
+ interface OutcomePayload {
269
+ handle: string;
270
+ app_id?: string;
271
+ intent_archetype?: string;
272
+ /** The model that ACTUALLY RAN (post-fallback). */
273
+ model?: string;
274
+ /** The model v2 compile() originally targeted. NULL when no fallback. */
275
+ requested_model?: string;
276
+ provider?: string;
277
+ shape_key?: string;
278
+ learning_key?: string;
279
+ mutations_applied: string[];
280
+ tokens_in: number;
281
+ tokens_out: number;
282
+ estimated_tokens_in?: number;
283
+ latency_ms: number;
284
+ success: boolean;
285
+ empty_response: boolean;
286
+ error_type?: string;
287
+ tools_called?: string[];
288
+ oracle_score?: number;
289
+ oracle_dimensions?: Record<string, number>;
290
+ oracle_rationale?: string;
291
+ prompt_preview?: string;
292
+ response_preview?: string;
293
+ dialect_version: string;
294
+ cache_read_input_tokens?: number;
295
+ cache_creation_input_tokens?: number;
296
+ cost_usd_actual?: number;
297
+ ttft_ms?: number;
298
+ history_cacheable_tokens?: number;
299
+ history_tokens_at_compile?: number;
300
+ /**
301
+ * Mirrors `ir.constraints.toolOrchestration` from compile time. NULL when
302
+ * the consumer hadn't adopted the constraint (pre-alpha.20). Powers
303
+ * per-mode model-perf queries on the brain (the L-040 parallel-tool
304
+ * cliff lumps DeepSeek sequential perf with parallel without this).
305
+ */
306
+ tool_orchestration?: 'parallel' | 'sequential' | 'either' | null;
307
+ finish_reason?: string;
308
+ total_ms?: number;
309
+ tools_count?: number;
310
+ history_depth?: number;
311
+ system_prompt_chars?: number;
312
+ fell_over_from?: string;
313
+ fallback_reason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
314
+ /**
315
+ * Per-call SectionRewrite[] captured at compile time. Omitted (sent as
316
+ * undefined → stored NULL) when no rewrites fired. Powers cross-app
317
+ * learning aggregates ("rule X fired N times on (app, model, archetype),
318
+ * downstream outcome quality lifted by M points").
319
+ */
320
+ section_rewrites_applied?: SectionRewrite[] | null;
321
+ }
322
+ /**
323
+ * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
324
+ *
325
+ * Fires after the consumer's UX surfaces an approve/reject event (e.g., user
326
+ * clicks Approve on a hunt result). Joins to the original `compile_outcomes`
327
+ * row via outcomeId — enables per-(model, archetype) approve-rate measurement
328
+ * once N ≥ 10 outcomes accumulate.
329
+ *
330
+ * Fire-and-forget by default (matches record() semantics). Set BrainConfig.sync
331
+ * = true for runtime contexts that can't tolerate fire-and-forget teardown
332
+ * (Vercel Edge, Cloudflare Workers, AWS Lambda) — see L-086.
333
+ *
334
+ * Returns OutcomeResult with ok: false + stable reason on persistence
335
+ * failure. Never throws.
336
+ */
337
+ declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
117
338
 
118
339
  /**
119
340
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -189,6 +410,1482 @@ declare function resetTokenizer(): void;
189
410
  */
190
411
  declare function countTokens(text: string): number;
191
412
 
413
+ /**
414
+ * Best-practice advisor — alpha.6 Phase 1.
415
+ *
416
+ * Inspects an IR + the selected profile + compile diagnostics and emits a
417
+ * list of `BestPracticeAdvisory` entries describing detected gaps. Runs
418
+ * after `lower()` in the compile pipeline; the result lands on
419
+ * `CompileResult.advisories` for the consumer to log, surface, or filter.
420
+ *
421
+ * Driven by interfaces/kgauto.md `best-practice-advisories` (IC, 2026-05-07).
422
+ * Phase 1 ships 4 starter rules sourced from the s14 kgauto comment +
423
+ * s15 empirical seed of brain anti-patterns:
424
+ *
425
+ * 1. `caching-off-on-claude` system >2000 chars on Anthropic, no cacheable=true
426
+ * 2. `single-chunk-system` Anthropic, only one PromptSection >1000 chars
427
+ * 3. `tool-bloat` >10 tools on a short-output archetype
428
+ * 4. `history-uncached-on-claude` Anthropic, ≥2 history messages, no historyCachePolicy
429
+ *
430
+ * Each rule is a pure function: (ir, result, profile) → BestPracticeAdvisory[].
431
+ * No side effects. No randomness. Deterministic for a given IR.
432
+ *
433
+ * The thresholds (2000 chars, 1000 chars, 10 tools, 2 history) are chosen
434
+ * to balance noise vs. signal — too low fires on innocuous calls, too high
435
+ * misses real waste. They may tune with brain evidence over time; for now
436
+ * they're literals in the rule bodies. Make them configurable when the
437
+ * cost-watcher's R-rules graduate to here.
438
+ */
439
+
440
+ /** Subset of CompileResult fields the advisor needs. */
441
+ type AdvisorContext = Pick<CompileResult, 'target' | 'provider' | 'tokensIn' | 'diagnostics'>;
442
+ /**
443
+ * Optional Phase 2 (alpha.22) context — fallback chain + a profile resolver
444
+ * for cross-model comparison. Three new rules
445
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) consume
446
+ * this to surface measurement-substrate signals (alpha.20 clean-attribution +
447
+ * alpha.21 grounding labels) as actionable consumer guidance.
448
+ *
449
+ * When `fallbackChain` is empty, rules 1 + 3 stay silent (nothing to
450
+ * compare against). When `profileResolver` is omitted, the rules degrade
451
+ * gracefully — they can still inspect the chosen profile but not chain
452
+ * alternatives. Rule 2 (`model-stale-evidence`) is independent of chain
453
+ * shape and works on the chosen model alone.
454
+ */
455
+ interface RunAdvisorPhase2Context {
456
+ fallbackChain: string[];
457
+ profileResolver?: (id: string) => ModelProfile | undefined;
458
+ /**
459
+ * alpha.29 — translator rewrites that fired this compile. When a rewrite
460
+ * cleared the cliff (e.g. `tool_call_contract` → sequential-tool preamble
461
+ * + `parallelToolCalls: false`), the matching cliff advisor
462
+ * (`archetype-perf-floor-breach`) MUST suppress for the same call. Without
463
+ * suppression both fire — the advisory contradicts the rewrite ("cliff is
464
+ * unaddressed" vs "we just addressed it").
465
+ *
466
+ * Empty array / undefined → no suppression (alpha.28 behavior preserved).
467
+ */
468
+ sectionRewritesApplied?: SectionRewrite[];
469
+ }
470
+ /**
471
+ * Run all phased rules and return collected advisories. Order is fixed so
472
+ * output is stable across runs. The `policy` argument is alpha.9 — the
473
+ * `single-model-array` rule needs to know whether the consumer explicitly
474
+ * declared `posture: 'locked'` (in which case single-model is intentional
475
+ * and shouldn't warn).
476
+ *
477
+ * `phase2` is alpha.22 — gives the advisor access to the fallback chain +
478
+ * a profile resolver so the three new compile-time recommendation rules
479
+ * (`cost-mismatched-archetype`, `model-stale-evidence`, `tier-down`) can
480
+ * compare the chosen model against in-chain alternatives. Optional for
481
+ * backward compatibility with consumers calling `runAdvisor()` directly.
482
+ */
483
+ declare function runAdvisor(ir: PromptIR, result: AdvisorContext, profile: ModelProfile, policy?: CompilePolicy, phase2?: RunAdvisorPhase2Context): BestPracticeAdvisory[];
484
+
485
+ /**
486
+ * Translator primitive — alpha.31.
487
+ *
488
+ * Pure function. Walks `IR.sections`, matches each section's `kind` against
489
+ * a per-rule dispatch table keyed on (kind, profile, archetype), and applies
490
+ * a model-aware rewrite when a rule fires. Returns the rewritten IR + the
491
+ * list of rewrites for `CompileResult.sectionRewritesApplied` and brain
492
+ * persistence.
493
+ *
494
+ * This is the s37 translator-framing eureka in code: kgauto graduates from
495
+ * "gate" (alpha.28's cliff advisor: "consumer must accept adapter") to
496
+ * "translator" (alpha.29: "consumer declared the section kind, kgauto
497
+ * applies the adapter at compile time without consumer-side branching").
498
+ *
499
+ * Rules shipped:
500
+ *
501
+ * alpha.29 — tool_call_contract + archetypePerf[archetype] < TRANSLATOR_FLOOR
502
+ * → prepend sequential-tool-pattern guidance
503
+ * → emit wireOverrides: { parallelToolCalls: false }
504
+ * → rule_id: 'sequential-tool-cliff-below-floor'
505
+ *
506
+ * alpha.31 — narration_contract + profile.provider === 'anthropic'
507
+ * → prepend terse-log narration guidance
508
+ * → no wireOverrides
509
+ * → rule_id: 'narration-drift-anthropic'
510
+ *
511
+ * alpha.31 — narration_contract + profile.provider === 'deepseek'
512
+ * → prepend <thinking>-suppression guidance
513
+ * → no wireOverrides
514
+ * → rule_id: 'narration-thinking-leak-deepseek'
515
+ *
516
+ * Per-rule walk (alpha.31 refactor): the alpha.30 short-circuit
517
+ * `if (!cliffFires) return passthrough` was correct when only the
518
+ * cliff-gated tool_call_contract rule existed; alpha.31's narration rules
519
+ * fire on every call regardless of cliff (narration drift is steady-state,
520
+ * not a cliff condition). Each section now consults the dispatch table
521
+ * independently — first-match wins per (section.kind, profile, archetype).
522
+ *
523
+ * **Interaction with the cliff advisor (alpha.28):** when this translator
524
+ * fires for a `tool_call_contract` section, the advisor's
525
+ * `archetype-perf-floor-breach` rule MUST suppress for the same call — the
526
+ * cliff was structurally cleared by the rewrite, not unaddressed. The
527
+ * suppression check lives in `advisor.ts` and consults the
528
+ * `CompileResult.sectionRewritesApplied` list.
529
+ *
530
+ * Design contracts:
531
+ * command-center/advisory/kgauto/2026-05-21_alpha-29-translator-and-advisories-api.md
532
+ * command-center/advisory/kgauto/2026-05-22_alpha-31-narration-contract.md
533
+ */
534
+
535
+ /**
536
+ * Re-export of `ARCHETYPE_FLOOR_DEFAULT` as the canonical "translator fires
537
+ * below this score" threshold. Same constant as the cliff advisor — the
538
+ * single threshold is shared (alpha.28's "below this, advisor warns"; alpha.29's
539
+ * "below this, translator AUTO-APPLIES the adapter").
540
+ */
541
+ declare const TRANSLATOR_FLOOR = 6;
542
+ /**
543
+ * Stable identifier of the alpha.29 sequential-tool rule. Surfaces on
544
+ * `SectionRewrite.rule` and in brain aggregates. The brain treats this
545
+ * identifier together with the preamble string as the rule's wire
546
+ * fingerprint — both stay byte-stable across releases.
547
+ */
548
+ declare const RULE_SEQUENTIAL_TOOL_CLIFF = "sequential-tool-cliff-below-floor";
549
+ interface ApplySectionRewritesArgs {
550
+ ir: PromptIR;
551
+ profile: ModelProfile;
552
+ archetype: IntentArchetypeName;
553
+ }
554
+ interface ApplySectionRewritesResult {
555
+ /**
556
+ * IR with section.text fields possibly rewritten. When no rewrites fired,
557
+ * this is identical to the input IR (referentially distinct array but
558
+ * same section payloads).
559
+ */
560
+ rewrittenIR: PromptIR;
561
+ /**
562
+ * One entry per section the translator rewrote. Empty array when no
563
+ * rules fired. Order matches the corresponding section in
564
+ * `rewrittenIR.sections`.
565
+ */
566
+ rewrites: SectionRewrite[];
567
+ }
568
+ /**
569
+ * Pure function. Apply model-aware section rewrites to the IR at compile time.
570
+ *
571
+ * Discipline:
572
+ * - Never mutates the input IR; returns a new IR with new sections array
573
+ * when at least one rewrite fired; otherwise returns the input IR by
574
+ * reference (referential identity preserved on no-op).
575
+ * - Sections without a `kind` (or `kind === 'arbitrary'`) pass through
576
+ * unchanged.
577
+ * - Empty `sections` array → returns `{ rewrittenIR: ir, rewrites: [] }`.
578
+ * - Sections of the same `kind` are processed in array order; first-match
579
+ * wins per section. (Today every rule is a single-match rule.)
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * import { applySectionRewrites } from '@warmdrift/kgauto-compiler';
584
+ * import { getProfile } from '@warmdrift/kgauto-compiler';
585
+ *
586
+ * const { rewrittenIR, rewrites } = applySectionRewrites({
587
+ * ir,
588
+ * profile: getProfile('deepseek-v4-pro'),
589
+ * archetype: 'hunt',
590
+ * });
591
+ * if (rewrites.length > 0) console.log('translator fired:', rewrites);
592
+ * ```
593
+ */
594
+ declare function applySectionRewrites(args: ApplySectionRewritesArgs): ApplySectionRewritesResult;
595
+
596
+ /**
597
+ * advisories-api — structured advisories API (alpha.29 Workstream B).
598
+ *
599
+ * Closes the L-117 family bottleneck: kgauto's `result.advisories[]` (the
600
+ * compile-time warnings about caching-off, tool-bloat, archetype-perf-floor
601
+ * breaches, etc.) used to disappear after the consumer read the compile
602
+ * result. The s34 caching-off advisory pattern is the canonical failure: an
603
+ * advisory fired 100+ times in 24h on `generate::sonnet` at 99.4% empty
604
+ * rate, and nobody knew because there was no structured channel to surface
605
+ * "what's open right now?"
606
+ *
607
+ * Migration 020 ships the substrate: `compile_outcome_advisories` gains
608
+ * lifecycle columns (`resolved_at`, `resolution_source`, `resolution_note`)
609
+ * and the `actionable_advisories_v` view rolls per-firing rows into
610
+ * per-(app_id, code) tuples with deterministic stable ids + server-side
611
+ * auto-resolution.
612
+ *
613
+ * Public surface:
614
+ * getActionableAdvisories({ appId, severity?, status?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
615
+ * → Promise<ActionableAdvisory[]>
616
+ *
617
+ * markAdvisoryResolved({ id, resolutionNote?, brainEndpoint, brainJwt, brainAnonKey, fetch? })
618
+ * → Promise<{ ok: true } | { ok: false; reason: string }>
619
+ *
620
+ * Both functions are pure I/O — no module-level state. The fetch wiring
621
+ * mirrors `createProxyHandler` in `glassbox-routes/proxy.ts`: scoped JWT in
622
+ * `Authorization: Bearer`, `apikey` header carries the anon key.
623
+ *
624
+ * The auto-resolution rule is enforced server-side in `actionable_advisories_v`:
625
+ * • Latest firing > 14 days ago → status='resolved' (auto-pruned)
626
+ * • All firings have resolved_at set → status='resolved' (consumer-marked)
627
+ * • Otherwise → status='open'
628
+ *
629
+ * `markAdvisoryResolved` is the consumer override: "I fixed it; the next
630
+ * firing will reopen the rule, but until then it stays resolved."
631
+ */
632
+
633
+ /**
634
+ * Severity of an advisory. Maps to the `level` column on
635
+ * `compile_outcome_advisories` (info | warn | critical).
636
+ */
637
+ type AdvisorySeverity = 'info' | 'warn' | 'critical';
638
+ /**
639
+ * Status of an advisory rollup.
640
+ *
641
+ * - `open` — at least one unresolved firing in the last 14 days
642
+ * - `resolved` — either auto-pruned (no firings >14d) or consumer-marked
643
+ * - `snoozed` — reserved for alpha.30+ (snooze-until-date); type-accepted
644
+ * today but the view will never emit this value
645
+ */
646
+ type AdvisoryStatus = 'open' | 'snoozed' | 'resolved';
647
+ /**
648
+ * Source of resolution when status='resolved'.
649
+ *
650
+ * - `auto` — server-side rule auto-pruned (>14d since last firing)
651
+ * - `consumer-marked` — consumer called `markAdvisoryResolved`
652
+ * - `declined` — reserved (alpha.30+: consumer marked the suggestion
653
+ * inapplicable; the advisor will still fire but UIs can hide it)
654
+ */
655
+ type AdvisoryResolutionSource = 'auto' | 'consumer-marked' | 'declined';
656
+ /**
657
+ * Suggested-fix metadata. `null` when the advisor has no actionable fix
658
+ * (info-level rules can be observational). When set, the consumer's
659
+ * Admin UI can render a one-click apply (alpha.30+) or surface the
660
+ * before/after diff inline.
661
+ */
662
+ interface AdvisorySuggestedFix {
663
+ type: 'config-change' | 'one-liner' | 'env-var' | 'manual';
664
+ /** File:line hint if kgauto can infer (reserved — alpha.30+). */
665
+ siteHint?: string;
666
+ before?: string;
667
+ after?: string;
668
+ docsLink?: string;
669
+ }
670
+ /**
671
+ * Per-(app_id, code) advisory rollup. The `id` is stable across polls
672
+ * until the rule auto-resolves and re-opens (a new firing after the 14d
673
+ * boundary advances `opened_at` → new id). Treat id-changes as
674
+ * intentional "fresh re-open" signals.
675
+ *
676
+ * Wire-shape from `actionable_advisories_v`. The transformer maps the
677
+ * view's snake_case columns to camelCase. See `feedback_typed_boundary_transformers.md`
678
+ * (L-118) for the rationale.
679
+ */
680
+ interface ActionableAdvisory {
681
+ id: string;
682
+ rule: string;
683
+ severity: AdvisorySeverity;
684
+ openedAt: string;
685
+ lastObservedAt: string;
686
+ observationCount: number;
687
+ appliesTo: {
688
+ archetype?: IntentArchetypeName;
689
+ model?: string;
690
+ callSiteHint?: string;
691
+ };
692
+ message: string;
693
+ suggestedFix: AdvisorySuggestedFix | null;
694
+ /** Reserved — always `false` in alpha.29. alpha.30+ ships actual auto-apply. */
695
+ autoApplicable: boolean;
696
+ status: AdvisoryStatus;
697
+ resolvedAt?: string;
698
+ resolutionSource?: AdvisoryResolutionSource;
699
+ resolutionNote?: string;
700
+ }
701
+ /**
702
+ * Filter + transport for `getActionableAdvisories`. The brain JWT must
703
+ * carry an `app_id` claim matching `opts.appId` — RLS enforces tenant
704
+ * isolation on the underlying table, so a mismatch silently returns [].
705
+ */
706
+ interface GetActionableAdvisoriesOptions {
707
+ appId: string;
708
+ /** Severity filter; if omitted, all severities are returned. */
709
+ severity?: AdvisorySeverity;
710
+ /** Status filter; defaults to 'open'. Pass 'all' for the full set. */
711
+ status?: 'open' | 'snoozed' | 'resolved' | 'all';
712
+ brainEndpoint: string;
713
+ brainJwt: string;
714
+ brainAnonKey: string;
715
+ fetch?: typeof fetch;
716
+ }
717
+ interface MarkAdvisoryResolvedOptions {
718
+ /** Stable id from a prior `getActionableAdvisories` call. */
719
+ id: string;
720
+ resolutionNote?: string;
721
+ brainEndpoint: string;
722
+ brainJwt: string;
723
+ brainAnonKey: string;
724
+ fetch?: typeof fetch;
725
+ }
726
+ /**
727
+ * Query the open advisory set for an app. Pulls from
728
+ * `actionable_advisories_v` (per-(app_id, code) rollup with stable ids
729
+ * + server-side auto-resolution).
730
+ *
731
+ * Default behavior (no status filter): returns only `status='open'`.
732
+ * Pass `status: 'all'` to see resolved + open together — useful for
733
+ * Admin UIs that show "recently fixed" badges.
734
+ *
735
+ * Fetch failures bubble out as thrown Errors. (`markAdvisoryResolved`
736
+ * uses the ok/reason envelope; this read path throws to match
737
+ * existing kgauto query semantics where the consumer can decide to
738
+ * retry or render an error state.)
739
+ */
740
+ declare function getActionableAdvisories(opts: GetActionableAdvisoriesOptions): Promise<ActionableAdvisory[]>;
741
+ /**
742
+ * Mark an advisory as consumer-resolved.
743
+ *
744
+ * Lookup strategy:
745
+ * 1. Query `actionable_advisories_v?id=eq.<id>` to find the (app_id, code)
746
+ * tuple for this advisory.
747
+ * 2. PATCH the latest unresolved firing in `compile_outcome_advisories`
748
+ * matching that tuple via the underlying outcome's app_id.
749
+ *
750
+ * The (app_id, code) lookup is necessary because `compile_outcome_advisories`
751
+ * has no `app_id` column — it inherits scope via the FK to compile_outcomes.
752
+ * PostgREST cannot PATCH with a JOIN predicate, so the markAdvisoryResolved
753
+ * path is a two-step round-trip. The cost is one extra GET per resolve call;
754
+ * acceptable because marks are low-frequency operator actions, not per-call
755
+ * hot path.
756
+ *
757
+ * Idempotent re-marks: if the advisory is already resolved (no unresolved
758
+ * firings match), the PATCH affects zero rows and the call still returns
759
+ * `ok: true`. The function returns `ok: false` only on transport / auth /
760
+ * lookup failures.
761
+ *
762
+ * Returns ok/reason envelope (vs throwing) because consumer Admin UIs
763
+ * typically want to render the failure inline rather than crash.
764
+ */
765
+ declare function markAdvisoryResolved(opts: MarkAdvisoryResolvedOptions): Promise<{
766
+ ok: true;
767
+ } | {
768
+ ok: false;
769
+ reason: string;
770
+ }>;
771
+ /**
772
+ * Resolution sources supported by the alpha.39 `markExclusionFindingHandled`
773
+ * API. Mirrors the subset of `exclusion_findings.resolution_source` CHECK
774
+ * constraint values that consumers can self-set:
775
+ *
776
+ * - `'consumer-marked'` — generic "we've handled this; stop reminding."
777
+ * Use this for "we evaluated and chose not to act" or "we'll act when
778
+ * ready but acknowledge the finding now."
779
+ * - `'declined'` — explicit "this exclusion is intentional; do not surface
780
+ * again." Stronger signal than consumer-marked; useful for compliance
781
+ * exclusions, brand-promise exclusions, etc.
782
+ * - `'probed-unblock'` — alpha.40+ probe-path verdict: consumer ran a live
783
+ * probe and decided to unblock the excluded model. Library accepts the
784
+ * value today so the probe path doesn't need a follow-up API release.
785
+ * - `'probed-stay-excluded'` — alpha.40+ probe-path verdict: consumer
786
+ * probed and confirmed the exclusion. Same forward-compat shape as
787
+ * `'probed-unblock'`.
788
+ *
789
+ * The `'auto'` resolution_source is NOT exposed here — that's reserved
790
+ * for the brain's own automatic resolution (e.g. when the detection
791
+ * conditions no longer hold). Consumer code sets only the four values
792
+ * above.
793
+ */
794
+ type ExclusionResolutionSource = 'consumer-marked' | 'declined' | 'probed-unblock' | 'probed-stay-excluded';
795
+ interface MarkExclusionFindingHandledOptions {
796
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
797
+ appId: string;
798
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
799
+ archetype: string;
800
+ /** Canonical model id that the consumer had excluded. */
801
+ excludedModel: string;
802
+ /** Resolution semantics — see `ExclusionResolutionSource` for the four
803
+ * values consumers can set. */
804
+ resolution: ExclusionResolutionSource;
805
+ /** Optional free-form note explaining the decision. Surfaces in operator
806
+ * digests + dashboards alongside the resolution_source. */
807
+ resolutionNote?: string;
808
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). The
809
+ * function appends `/rest/v1/exclusion_findings?...`. */
810
+ brainEndpoint: string;
811
+ /** Consumer-scoped JWT carrying the `app_id` claim. The brain's RLS
812
+ * policy enforces that the JWT's app_id matches the finding's app_id;
813
+ * cross-tenant writes fail at the database layer regardless of input. */
814
+ brainJwt: string;
815
+ /** Supabase anon key for the `apikey` header (PostgREST requires it). */
816
+ brainAnonKey: string;
817
+ /** Injected fetch for tests. Defaults to global fetch. */
818
+ fetch?: typeof fetch;
819
+ }
820
+ /**
821
+ * Mark a stale-exclusion finding as handled. Returns an `ok/reason` envelope
822
+ * matching `markAdvisoryResolved` — consumer Admin UIs typically render the
823
+ * failure inline rather than crash.
824
+ *
825
+ * Idempotent: if no row matches the (app_id, archetype, excludedModel)
826
+ * tuple (already resolved, never existed, cron not yet UPSERTed), PostgREST
827
+ * returns 200 with zero affected rows and we return `{ ok: true }`. The
828
+ * caller's "I marked it as handled" intent is satisfied regardless of
829
+ * whether the row was already in that state.
830
+ *
831
+ * Reasons surfaced on failure:
832
+ * - `app_id_required` / `archetype_required` / `excluded_model_required`
833
+ * - `resolution_invalid` — `resolution` not one of the four documented values
834
+ * - `brain_auth_misconfig` — 401/403 (JWT / anon key wrong)
835
+ * - `brain_unavailable` — 5xx
836
+ * - `network_error:<message>` — fetch threw
837
+ * - `patch_failed:<status>` — anything else non-2xx
838
+ */
839
+ declare function markExclusionFindingHandled(opts: MarkExclusionFindingHandledOptions): Promise<{
840
+ ok: true;
841
+ } | {
842
+ ok: false;
843
+ reason: string;
844
+ }>;
845
+
846
+ /**
847
+ * Archetype-cliff compatibility — alpha.28 (tt-intel-Cairn ratified).
848
+ *
849
+ * One question, one answer: *given this model and this intent, can it work
850
+ * — and if not, what adapter (if any) would make it work?*
851
+ *
852
+ * Replaces the silent-archetype-cliff failure mode where a consumer picks a
853
+ * model that's structurally wrong for the intent and kgauto compiles cleanly
854
+ * without surfacing the gap. The triggering incident: tt-intel shipped
855
+ * `deepseek-v4-pro` as the hunt default per a local spec; the kgauto coord
856
+ * doc said L-040 — V4 is structurally wrong for hunt (sequential tools).
857
+ * `archetypePerf.hunt = 4` was already in the profile data. The compiler
858
+ * stayed silent. This API + the matching advisor rule surfaces it.
859
+ *
860
+ * Pure function. No network. No brain query. No side effects. ~1ms.
861
+ *
862
+ * Consultation doc:
863
+ * command-center/advisory/kgauto/2026-05-21_archetype-cliff-advisor.md
864
+ *
865
+ * Refinements applied per tt-intel-Cairn ratification (2026-05-21):
866
+ * R1: every variant carries `archetypePerf: number` (raw score) — and
867
+ * `requires-adapter` adds `archetypePerfWithAdapter: number` so
868
+ * consumer policy can be expressed as "accept adapter only when score
869
+ * crosses some threshold WITH the adapter on."
870
+ * R2: every variant carries a plain-English `reason: string`. No internal
871
+ * jargon ("L-040", "archetypePerf=4") — the consumer chooses whether
872
+ * to render it as UI hint or operator-tooling tooltip.
873
+ * R3: `Adapter` is a CLOSED discriminated union, not `| string`. alpha.28
874
+ * ships ONE variant (`toolOrchestration: 'sequential'`). Future
875
+ * adapter parameters extend the union explicitly in named releases.
876
+ * NO escape hatch — the whole point is catching "I added a new
877
+ * adapter and forgot to update consumer policy" at compile time.
878
+ */
879
+
880
+ /**
881
+ * Minimum `archetypePerf[archetype]` score to count as `compatible` under
882
+ * Option A (default policy). Below this, a documented adapter is needed
883
+ * to lift the model above the floor; if no adapter exists, the model is
884
+ * rejected.
885
+ *
886
+ * Matches `QUALITY_FLOOR_FOR_RECOMMENDATION` in `advisor.ts` — kgauto's
887
+ * library-wide convention for "below this score, swap recommendations stop."
888
+ */
889
+ declare const ARCHETYPE_FLOOR_DEFAULT = 6;
890
+ /**
891
+ * Absolute floor — below this, the cliff is too steep for ANY adapter to
892
+ * lift cleanly. Reserved under Option A (unused today; every below-floor
893
+ * case is gated by adapter availability). Would gate `reject` vs
894
+ * `requires-adapter` under a future Option B per consultation doc Q1.
895
+ *
896
+ * Exported so consumer-side policy can read it (e.g. "accept adapter only
897
+ * when archetypePerf >= ABSOLUTE_FLOOR + 1"). Not used internally by
898
+ * `getModelCompatibility` today — the gate is "does an adapter exist for
899
+ * this cliff?", not score-based.
900
+ */
901
+ declare const ABSOLUTE_FLOOR = 4;
902
+ /**
903
+ * The intent the call is expressing — archetype + optional orchestration
904
+ * mode. Same shape as `ir.intent.archetype` + `ir.constraints.toolOrchestration`
905
+ * so a consumer can pass `{ archetype: ir.intent.archetype,
906
+ * toolOrchestration: ir.constraints?.toolOrchestration }` directly.
907
+ */
908
+ interface CompatibilityIntent {
909
+ archetype: IntentArchetypeName;
910
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
911
+ }
912
+ /**
913
+ * `Adapter` — re-exported above. Canonical definition lives in `ir.ts` to
914
+ * avoid an import cycle (compatibility.ts → profiles.ts → ir.ts).
915
+ *
916
+ * **CLOSED discriminated union per R3.** Future adapter parameters extend
917
+ * the union explicitly in named alpha releases. No `| string` escape hatch
918
+ * — consumer policy code SHOULD write exhaustive `switch (adapter.parameter)`
919
+ * and rely on the compiler to flag "I added a new adapter parameter and
920
+ * forgot to update the consumer's policy."
921
+ *
922
+ * alpha.28 variants:
923
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
924
+ * Lifts DeepSeek V4-family on `hunt` from sequential-tool cliff (L-040).
925
+ * The "consequence" plain-English-ifies the trade-off:
926
+ * "Tool calls run one at a time — slower but reliable."
927
+ *
928
+ * alpha.29+ likely additions (per tt-intel-Cairn priority list):
929
+ * - `{ parameter: 'parallelToolCalls'; value: false; consequence }`
930
+ * - `{ parameter: 'maxTools'; value: number; consequence }`
931
+ * - `{ parameter: 'thinkingBudget'; value: 0; consequence }`
932
+ *
933
+ * Each new variant lands in its own named release with the union extended
934
+ * in `ir.ts`. Consumers see the change at compile time.
935
+ */
936
+ /**
937
+ * The compatibility verdict for a (model, intent) pair. Discriminated union
938
+ * on `status` — `compatible` | `requires-adapter` | `reject`.
939
+ *
940
+ * **Every variant carries `archetypePerf` (R1) + `reason` (R2):**
941
+ * - `archetypePerf` — the raw 0-10 score for (model, archetype). Lets
942
+ * consumers build their own thresholds without re-importing the profile
943
+ * registry.
944
+ * - `reason` — plain-English, consumer-renderable. NOT internal jargon
945
+ * like "L-040 cliff" or "archetypePerf=4". Examples in R2 ratification:
946
+ * - compatible: "Suited for hunt-style parallel discovery."
947
+ * - requires-adapter: "Best with sequential tool calls for hunt — slower but works."
948
+ * - reject: "Not suited for hunt — would underperform significantly."
949
+ *
950
+ * `requires-adapter` additionally carries:
951
+ * - `archetypePerfWithAdapter` — estimated post-adapter score. May be an
952
+ * estimate (we don't measure post-adapter scores yet); kgauto's prior is
953
+ * "adapter lifts to ARCHETYPE_FLOOR_DEFAULT + 1" unless brain-evidenced.
954
+ * - `adapter` — the closed-union variant describing the structural change.
955
+ *
956
+ * Backward-compat: an unknown model returns `reject` with a "model not
957
+ * registered" reason; callers never throw. Unknown archetype is impossible
958
+ * at the type level (`IntentArchetypeName` is a closed union).
959
+ */
960
+ type ModelCompatibility = {
961
+ status: 'compatible';
962
+ reason: string;
963
+ archetypePerf: number;
964
+ } | {
965
+ status: 'requires-adapter';
966
+ reason: string;
967
+ archetypePerf: number;
968
+ archetypePerfWithAdapter: number;
969
+ adapter: Adapter;
970
+ } | {
971
+ status: 'reject';
972
+ reason: string;
973
+ archetypePerf: number;
974
+ };
975
+ /**
976
+ * Compatibility query — *does this model fit this intent, and if not,
977
+ * what would?*
978
+ *
979
+ * **Rules (Option A from consultation doc Q1):**
980
+ * 1. If model is unregistered → `reject` with "model not registered" reason.
981
+ * 2. If intent provides `toolOrchestration: 'sequential'` AND that adapter
982
+ * silences the cliff (because the cliff IS the sequential-tool one)
983
+ * → return `compatible` with raw score (NOT the post-adapter estimate
984
+ * — caller already paid the adapter, score reflects reality).
985
+ * 3. If raw `archetypePerf[archetype] >= ARCHETYPE_FLOOR_DEFAULT`
986
+ * → `compatible`.
987
+ * 4. If below floor BUT a documented adapter exists that lifts to floor
988
+ * → `requires-adapter` with adapter + estimated post-adapter score.
989
+ * 5. If below floor AND no adapter exists → `reject`.
990
+ *
991
+ * **Pure function.** Deterministic for `(modelId, intent)`. No I/O.
992
+ *
993
+ * @example
994
+ * ```ts
995
+ * import { getModelCompatibility } from '@warmdrift/kgauto-compiler';
996
+ *
997
+ * const c = getModelCompatibility('deepseek-v4-pro', { archetype: 'hunt' });
998
+ * // → { status: 'requires-adapter',
999
+ * // reason: 'Best with sequential tool calls for hunt — slower but works.',
1000
+ * // archetypePerf: 4,
1001
+ * // archetypePerfWithAdapter: 7,
1002
+ * // adapter: {
1003
+ * // parameter: 'toolOrchestration',
1004
+ * // value: 'sequential',
1005
+ * // consequence: 'Tool calls run one at a time...'
1006
+ * // } }
1007
+ *
1008
+ * // With the adapter already declared:
1009
+ * const c2 = getModelCompatibility('deepseek-v4-pro', {
1010
+ * archetype: 'hunt',
1011
+ * toolOrchestration: 'sequential',
1012
+ * });
1013
+ * // → { status: 'compatible',
1014
+ * // reason: 'Suited for hunt with sequential tool calls.',
1015
+ * // archetypePerf: 4 }
1016
+ * ```
1017
+ */
1018
+ declare function getModelCompatibility(modelId: string, intent: CompatibilityIntent): ModelCompatibility;
1019
+
1020
+ /**
1021
+ * alpha.22 — sync introspection: is brain-query mode active for a given
1022
+ * table? Used by the advisor (`model-stale-evidence` rule) to decide
1023
+ * whether a `judgment`-grounded chosen model is a measurement gap worth
1024
+ * surfacing. Returns false on cold start, when configureBrain() was never
1025
+ * called, or when the consumer explicitly opted the table out via
1026
+ * `BrainConfig.brainQuery.<table> = false`.
1027
+ */
1028
+ declare function isBrainQueryActiveFor(table: string): boolean;
1029
+ interface GetPerAxisMetricsOpts {
1030
+ /** App id to filter on. Required. */
1031
+ appId: string;
1032
+ /** Intent archetype to filter on. Required. */
1033
+ archetype: string;
1034
+ /** Canonical model id to filter on. Required. */
1035
+ model: string;
1036
+ /**
1037
+ * Window in days. Default 30. Only rows with
1038
+ * `created_at > now() - windowDays` are counted.
1039
+ */
1040
+ windowDays?: number;
1041
+ /**
1042
+ * Consumer-declared quality floor (0..1 oracle/approve-rate scale).
1043
+ * When set, the response's `qualityFloorMet` is true/false; when omitted,
1044
+ * `qualityFloorMet` is null (no floor declared, no judgment).
1045
+ */
1046
+ qualityFloor?: number;
1047
+ /** Pluggable fetch (tests inject mock). Defaults to global fetch. */
1048
+ fetch?: typeof fetch;
1049
+ /**
1050
+ * PostgREST base endpoint (e.g. `https://kgauto-brain.vercel.app/api`).
1051
+ * When omitted, falls back to the active configureBrainQuery runtime's
1052
+ * endpoint. Returns null when neither is set.
1053
+ */
1054
+ endpoint?: string;
1055
+ /** Bearer token. Forwarded as `Authorization: Bearer ${apiKey}`. */
1056
+ apiKey?: string;
1057
+ }
1058
+ /**
1059
+ * Call the `get_per_axis_metrics` RPC and return the typed result.
1060
+ *
1061
+ * Returns null when:
1062
+ * - no endpoint provided AND no configureBrainQuery runtime active
1063
+ * - RPC returns empty / null / unexpected shape
1064
+ * - brain unreachable / fetch throws / HTTP error
1065
+ *
1066
+ * Never throws — operator-facing query, must not blow up the caller.
1067
+ */
1068
+ declare function getPerAxisMetrics(opts: GetPerAxisMetricsOpts): Promise<PerAxisMetrics | null>;
1069
+
1070
+ /**
1071
+ * env.ts — provider env-key resolution + reachability predicates.
1072
+ *
1073
+ * Centralizes the per-provider env var names that kgauto checks for
1074
+ * reachability. Used by:
1075
+ *
1076
+ * - execute.ts — to find an API key when one isn't passed via apiKeys
1077
+ * - call.ts — to auto-filter unreachable models from the fallback walk
1078
+ * - getDefaultFallbackChain — opt-in chain filter when consumer passes `reachability`
1079
+ * - operator scripts — getReachabilityDiagnostic() prints what's wired up
1080
+ *
1081
+ * Keeping the map in ONE place means execute() and the reachability check
1082
+ * always agree. Without this, kgauto could declare a model "reachable" because
1083
+ * env.ts found GOOGLE_GENERATIVE_AI_API_KEY, while execute() looks at
1084
+ * GOOGLE_API_KEY only and 401s — shipping the bug we're trying to fix.
1085
+ *
1086
+ * Resolution order (apiKeys takes precedence):
1087
+ * 1. opts.apiKeys?.[provider]
1088
+ * 2. process.env[name] for each name in PROVIDER_ENV_KEYS[provider] (first-present wins)
1089
+ *
1090
+ * alpha.10 (2026-05-14). Resolves the auto-filter-unreachable-models-silently
1091
+ * request from PB after first-deploy 401 on the alpha.9 summarize chain.
1092
+ */
1093
+
1094
+ /**
1095
+ * Providers kgauto can resolve keys for today. Subset of `Provider` — `mistral`
1096
+ * and `xai` are declared in the type union but not yet executable (no profiles,
1097
+ * no execute() handler, no env-var convention). Narrowing here keeps the
1098
+ * reachability check structurally honest.
1099
+ */
1100
+ type SupportedProvider = 'anthropic' | 'google' | 'openai' | 'deepseek';
1101
+ /**
1102
+ * Per-provider env var names kgauto recognizes. Order doesn't matter —
1103
+ * first-present wins. Multiple names per provider supported because Google
1104
+ * has historical drift (`GOOGLE_API_KEY` from older Google Cloud SDKs,
1105
+ * `GEMINI_API_KEY` in many examples, `GOOGLE_GENERATIVE_AI_API_KEY` is the
1106
+ * Vercel AI SDK convention used by IC + tt-intel adapters).
1107
+ *
1108
+ * Frozen so consumers/tests can't mutate (would break the cache invariant
1109
+ * that execute() and reachability checks agree).
1110
+ */
1111
+ declare const PROVIDER_ENV_KEYS: Readonly<Record<SupportedProvider, readonly string[]>>;
1112
+ interface ReachabilityOpts {
1113
+ /** Explicit keys (alpha.3 ApiKeys). Checked first; takes precedence over env. */
1114
+ apiKeys?: ApiKeys;
1115
+ /**
1116
+ * Override env source. Defaults to `process.env` in Node-shaped runtimes,
1117
+ * `{}` everywhere else. Pass `{}` explicitly in tests for hermetic runs.
1118
+ */
1119
+ envSource?: Record<string, string | undefined>;
1120
+ }
1121
+ /**
1122
+ * Resolve a usable API key for the provider. Returns the key string, or
1123
+ * undefined if neither apiKeys nor any of the env names are set.
1124
+ *
1125
+ * Used internally by execute.ts so the reachability check and the actual
1126
+ * call check stay in sync.
1127
+ */
1128
+ declare function resolveProviderKey(provider: Provider, opts?: ReachabilityOpts): string | undefined;
1129
+ /**
1130
+ * True iff the provider has a usable key — either via explicit `apiKeys`
1131
+ * or one of the `PROVIDER_ENV_KEYS[provider]` names is set in envSource.
1132
+ */
1133
+ declare function isProviderReachable(provider: Provider, opts?: ReachabilityOpts): boolean;
1134
+ /**
1135
+ * True iff the model's profile exists AND its provider is reachable.
1136
+ * Unknown model id returns false (treat as unreachable; the chain walker
1137
+ * will surface "no reachable models" if everything filters out).
1138
+ */
1139
+ declare function isModelReachable(modelId: string, opts?: ReachabilityOpts): boolean;
1140
+ interface ProviderReachability {
1141
+ reachable: boolean;
1142
+ /** How the key was found. `null` when unreachable. */
1143
+ via: 'apiKeys' | 'env' | null;
1144
+ /** Which env var name supplied the key (only when via === 'env'). */
1145
+ envKeyFound?: string;
1146
+ }
1147
+ /**
1148
+ * Snapshot of which providers are reachable from the current env / apiKeys.
1149
+ * Useful for operator scripts ("kgauto diagnose"), startup-time logging,
1150
+ * and the cost-watcher's "which consumer is missing what" report.
1151
+ *
1152
+ * Does NOT log the key value itself — only the env var name that supplied it.
1153
+ */
1154
+ declare function getReachabilityDiagnostic(opts?: ReachabilityOpts): Record<SupportedProvider, ProviderReachability>;
1155
+
1156
+ /**
1157
+ * getDefaultFallbackChain — the alpha.9 cascading ship.
1158
+ *
1159
+ * Returns a per-archetype fallback chain that walks the cost/performance
1160
+ * Pareto frontier (master plan §1.3 + §3). Three customer postures:
1161
+ *
1162
+ * locked — caller passes [theOneModel]; never call this function
1163
+ * preferred — caller passes `primary`; chain returned is [primary, ...fallbacks]
1164
+ * open — caller passes no `primary`; chain returned is [best, ...fallbacks]
1165
+ *
1166
+ * The chain at each step:
1167
+ * 1. Costs strictly less than the previous (no expensive sideways moves)
1168
+ * 2. Comes from a different provider than the previous step where possible
1169
+ * (correlated outages don't kill consecutive attempts)
1170
+ * 3. Stays above the archetype's perf floor (skip models scored <baseline
1171
+ * for archetypes where degradation would be unacceptable)
1172
+ *
1173
+ * In alpha.9 the chain is **hand-curated** per archetype (§3.3 starter
1174
+ * table). Brain-query mode lands in alpha.10. Policy.blockedModels filters
1175
+ * the result; policy.maxCostPerCallUsd is NOT applied here because the
1176
+ * function doesn't see the IR's token counts — that filtering happens at
1177
+ * `passScoreTargets()` time inside compile().
1178
+ *
1179
+ * The function is **pure** — no brain query, no I/O, no randomness. Same
1180
+ * inputs always produce the same chain.
1181
+ */
1182
+
1183
+ /**
1184
+ * Posture passed into `getDefaultFallbackChain`. The chain function only
1185
+ * sees `'open'` and `'preferred'` — callers in `'locked'` posture should
1186
+ * pass `models: [theOneModel]` directly and skip this function entirely.
1187
+ *
1188
+ * Equivalent to `CompilePolicy.posture` minus `'locked'`. Kept distinct so
1189
+ * the type system enforces "don't ask for a chain when you don't want one."
1190
+ */
1191
+ type FallbackPosture = 'open' | 'preferred';
1192
+ interface GetDefaultFallbackChainOpts {
1193
+ /** The archetype the call is performing. Drives chain shape. */
1194
+ archetype: IntentArchetypeName;
1195
+ /**
1196
+ * The user-selected or caller-anchored primary model. When provided, it
1197
+ * appears at position 0 of the returned chain and fallbacks follow.
1198
+ * When omitted, the function picks the best-perf model for the archetype
1199
+ * as position 0 (open posture).
1200
+ */
1201
+ primary?: string;
1202
+ /**
1203
+ * Informational. `'preferred'` and `'open'` produce the same chain shape
1204
+ * given the same `primary`/no-primary input — posture is a tag the brain
1205
+ * uses to distinguish "user-anchored" from "library-anchored" telemetry.
1206
+ */
1207
+ posture?: FallbackPosture;
1208
+ /**
1209
+ * Cap on chain length. Default 3. Min 1. Useful when the consumer wants
1210
+ * to keep the worst-case latency low (each fallback adds a round-trip).
1211
+ */
1212
+ maxDepth?: number;
1213
+ /**
1214
+ * Consumer-side gating. `blockedModels` are filtered from the chain.
1215
+ * `preferredModels` is informational (no boost applied at this layer —
1216
+ * compile()'s `passScoreTargets` handles preference ranking).
1217
+ * `maxCostPerCallUsd` is NOT applied here — needs IR-level token
1218
+ * estimation. Use compile()'s policy plumbing instead.
1219
+ */
1220
+ policy?: CompilePolicy;
1221
+ /**
1222
+ * alpha.10. When provided, the chain is filtered to models whose provider
1223
+ * has a reachable API key (via `apiKeys` or one of `PROVIDER_ENV_KEYS[provider]`).
1224
+ * Models whose provider can't be reached are silently dropped. If filtering
1225
+ * leaves the chain empty, returns `[]` — caller decides what to do (call()
1226
+ * throws CallError; this function stays pure).
1227
+ *
1228
+ * Pass `{}` to opt in with `process.env` as the env source. Pass `{ apiKeys, envSource }`
1229
+ * for explicit control (tests, non-Node runtimes). Omit entirely for the
1230
+ * legacy unfiltered behavior — preserves alpha.9 callers byte-for-byte.
1231
+ */
1232
+ reachability?: ReachabilityOpts;
1233
+ /**
1234
+ * alpha.20 E3: consumer-declared tool-orchestration shape. Currently
1235
+ * only affects `archetype: 'hunt'`, where 'sequential' swaps the
1236
+ * parallel-tool-tier-0 chain (Flash → Pro → Sonnet → Haiku) for a
1237
+ * DeepSeek-tier-0 chain (V4-Pro → Flash → Sonnet) — DeepSeek's L-040
1238
+ * parallel-tool cliff doesn't apply when the consumer commits to
1239
+ * single-step orchestration.
1240
+ *
1241
+ * Other archetypes are NOT mode-aware in this release — they ship the
1242
+ * same chain regardless of toolOrchestration. Future versions may
1243
+ * extend mode-awareness to ask/generate/etc. when brain evidence
1244
+ * supports it.
1245
+ *
1246
+ * Default (omitted or 'either'): parallel chain. Back-compat with all
1247
+ * pre-alpha.20 callers.
1248
+ */
1249
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
1250
+ }
1251
+ /**
1252
+ * Returns the fallback chain for an archetype as a plain `string[]` of
1253
+ * model ids.
1254
+ *
1255
+ * @deprecated since alpha.21 — prefer
1256
+ * {@link getDefaultFallbackChainWithGrounding}, which returns the same chain
1257
+ * shape with a `grounding` label on every entry (measured / capability-fact /
1258
+ * judgment). The string[] return is preserved indefinitely for back-compat —
1259
+ * no functional change in alpha.21. Existing callers don't need to migrate
1260
+ * unless they want to surface the grounding gap to users.
1261
+ */
1262
+ declare function getDefaultFallbackChain(opts: GetDefaultFallbackChainOpts): string[];
1263
+ /**
1264
+ * Returns a shallow copy of the hand-curated starter chain for an archetype.
1265
+ * Useful for tests + the `scripts/digest.mjs` operator readout.
1266
+ */
1267
+ declare function getStarterChain(archetype: IntentArchetypeName): string[];
1268
+ /**
1269
+ * Returns a shallow copy of all starter chains keyed by archetype.
1270
+ * Useful for the `digest.mjs` readout and consumer audits.
1271
+ */
1272
+ declare function getAllStarterChains(): Record<IntentArchetypeName, string[]>;
1273
+ /**
1274
+ * alpha.20 E3 introspection — returns the sequential-mode overlay for an
1275
+ * archetype, or `undefined` when no overlay is registered (the archetype
1276
+ * is mode-agnostic and reuses `STARTER_CHAINS[archetype]`).
1277
+ *
1278
+ * Useful for tests + the `scripts/digest.mjs` operator readout to surface
1279
+ * the mode-aware chains.
1280
+ */
1281
+ declare function getSequentialStarterChain(archetype: IntentArchetypeName): string[] | undefined;
1282
+ /**
1283
+ * alpha.21 (s78 Entry 1) — returns the fallback chain as `ChainEntry[]`,
1284
+ * with a `grounding` label on every position.
1285
+ *
1286
+ * Same selection logic as {@link getDefaultFallbackChain} (primary anchoring,
1287
+ * blockedModels filter, dedupe, reachability filter, maxDepth cap) — the
1288
+ * only difference is the return shape: each position is a `ChainEntry`
1289
+ * carrying `{ id, grounding, reason?, n? }` instead of a bare string.
1290
+ *
1291
+ * Use this when surfacing the chain to consumers who care WHY each entry
1292
+ * sits where it sits — Glass-Box panels, operator dashboards, eval
1293
+ * scaffolding deciding which entries deserve measurement priority.
1294
+ *
1295
+ * Returns `[]` when filtering empties the chain (same semantics as the
1296
+ * string variant) — consumer decides what to do.
1297
+ */
1298
+ declare function getDefaultFallbackChainWithGrounding(opts: GetDefaultFallbackChainOpts): ChainEntry[];
1299
+ /**
1300
+ * alpha.21 introspection — returns the grounded starter chain for an
1301
+ * archetype (no primary anchoring, no policy filtering, no maxDepth cap).
1302
+ * Use this when you want the raw, hand-curated grounded chain — every
1303
+ * entry carries a `grounding` label and optional reason/n.
1304
+ */
1305
+ declare function getStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[];
1306
+ /**
1307
+ * alpha.21 introspection — all grounded starter chains keyed by archetype.
1308
+ * Useful for the `digest.mjs` readout and consumer audits that want to
1309
+ * surface the grounding gap across the entire chain table.
1310
+ */
1311
+ declare function getAllStarterChainsWithGrounding(): Record<IntentArchetypeName, ChainEntry[]>;
1312
+ /**
1313
+ * alpha.21 introspection — sequential-mode overlay with grounding labels,
1314
+ * or `undefined` when no overlay is registered for the archetype.
1315
+ */
1316
+ declare function getSequentialStarterChainWithGrounding(archetype: IntentArchetypeName): ChainEntry[] | undefined;
1317
+
1318
+ /**
1319
+ * chains-brain — alpha.11 KG-11 adapter.
1320
+ *
1321
+ * Brain-driven STARTER_CHAINS for `getDefaultFallbackChain`. Reads
1322
+ * `kgauto_chains` table via the shared brain-query SWR cache (D6 + D8);
1323
+ * falls back to bundled STARTER_CHAINS on cold-start, brain-down, or
1324
+ * empty/missing table (D2 + D4).
1325
+ *
1326
+ * Behavioral note (locked via D2): the sync API surface returns bundled on
1327
+ * cold-start, with a background refresh fired. Subsequent calls within the
1328
+ * 5-min TTL return brain data. Vercel cold-start consumers see the seed
1329
+ * snapshot (functionally identical to pre-alpha.11); warm-start consumers
1330
+ * see live brain mutations within 5 min.
1331
+ */
1332
+ /**
1333
+ * Sync reader for the brain-driven chains map. Returns bundled
1334
+ * STARTER_CHAINS when brain-query is disabled, cold, or unreachable.
1335
+ */
1336
+ declare const loadChainsFromBrain: () => Record<"ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform", string[]>;
1337
+
1338
+ /**
1339
+ * archetype-perf-brain — alpha.11 KG-12 adapter.
1340
+ *
1341
+ * Brain-driven archetypePerf scores. Substrate for the future closed-loop
1342
+ * tuning engine (KG-12.5): brain telemetry → human or automated bumps →
1343
+ * brain UPDATE → consumers see new scores within 5-min cache TTL with
1344
+ * zero refresh.
1345
+ *
1346
+ * Today: data migrates to brain. No runtime call site reads archetypePerf
1347
+ * (it's metadata for the master plan §2.5 anti-hallucination guardrail +
1348
+ * future auto-tuning). The adapter exists so future readers — auto-tuning
1349
+ * + operator scripts + KG-12.5 — have a shipped substrate to consume.
1350
+ */
1351
+
1352
+ type ArchetypePerfMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
1353
+ /**
1354
+ * alpha.21: per-(model, archetype) row count map. Same shape as
1355
+ * ArchetypePerfMap but stores brain row counts when the brain backs a
1356
+ * placement. Undefined entries → no row count seen → score is the
1357
+ * hand-curated cold-start prior (grounding='judgment').
1358
+ */
1359
+ type ArchetypePerfNMap = Map<string, Partial<Record<IntentArchetypeName, number>>>;
1360
+ /**
1361
+ * Sync reader for the brain-driven archetypePerf map. Returns bundled
1362
+ * profile.archetypePerf data when brain-query is disabled, cold, or
1363
+ * unreachable. Identical shape pre/post-alpha.11 by design (D2).
1364
+ */
1365
+ declare const loadArchetypePerfFromBrain: () => ArchetypePerfMap;
1366
+ /**
1367
+ * alpha.21 — sync reader for the brain row-count map paired with
1368
+ * archetype-perf. Returns empty map (no measured backing) on cold start /
1369
+ * brain-down / unreachable — all `getArchetypePerfScore` calls then
1370
+ * resolve to `grounding: 'judgment'`. When the brain table includes an
1371
+ * `n` column on each row, this map mirrors those counts so consumers can
1372
+ * see how many measurements back each score.
1373
+ */
1374
+ declare const loadArchetypePerfNFromBrain: () => ArchetypePerfNMap;
1375
+ /**
1376
+ * Threshold above which a brain row count counts as 'measured' grounding.
1377
+ * Below this, the score is treated as 'judgment' (cold-start prior or
1378
+ * not-yet-enough-evidence). Mirrors the alpha.20 `getCleanPerfScore`
1379
+ * `minRows` default — same rule for consistency.
1380
+ */
1381
+ declare const MEASURED_GROUNDING_MIN_N = 10;
1382
+ /**
1383
+ * alpha.21 — return shape for the extended {@link getArchetypePerfScore}.
1384
+ * Wraps the existing 0..10 score with:
1385
+ *
1386
+ * - `n`: brain row count backing this score (0 when no measurement).
1387
+ * - `grounding`: derived label — 'measured' when n >= 10, else 'judgment'.
1388
+ *
1389
+ * The score itself is unchanged from pre-alpha.21 (numeric, 5 = neutral
1390
+ * default). 'capability-fact' is NOT a perf-score grounding — capability
1391
+ * decisions live on chain entries, not on perf scores.
1392
+ */
1393
+ interface ArchetypePerfScoreResult {
1394
+ /** 0..10 perf score. 5 = neutral default when no entry exists. */
1395
+ score: number;
1396
+ /**
1397
+ * Brain row count backing this score. 0 when bundled (cold-start prior)
1398
+ * or when the brain row didn't carry an `n` column.
1399
+ */
1400
+ n: number;
1401
+ /**
1402
+ * Provenance — 'measured' when `n >= 10`, else 'judgment'.
1403
+ * Never 'capability-fact' (that label is reserved for chain-entry
1404
+ * inclusion/exclusion decisions).
1405
+ */
1406
+ grounding: Grounding;
1407
+ }
1408
+ /**
1409
+ * Per-model accessor with grounding (alpha.21). Returns 5 (neutral) when no
1410
+ * entry is found — consistent with the master plan §3.3 "missing archetypes
1411
+ * default to 5" convention documented in profiles.ts
1412
+ * ModelProfile.archetypePerf.
1413
+ *
1414
+ * Backwards-compat note: pre-alpha.21 callers expected `number` here. The
1415
+ * new return shape `{ score, n, grounding }` is a breaking shape change at
1416
+ * the type level, but `.score` carries the legacy value. Callers reading
1417
+ * `.score` field-by-field continue working; callers using the bare number
1418
+ * arithmetically need to switch to `.score`. The migration is single-line
1419
+ * (`const x = getArchetypePerfScore(...)` → `const x = getArchetypePerfScore(...).score`).
1420
+ */
1421
+ declare function getArchetypePerfScore(modelId: string, archetype: IntentArchetypeName): ArchetypePerfScoreResult;
1422
+
1423
+ /**
1424
+ * pricing-brain — alpha.11 KG-13 adapter.
1425
+ *
1426
+ * Brain-driven pricing data with **time-bounded resolution** (`valid_from`
1427
+ * / `valid_until` columns). The V4-Pro 75%-off promo through 2026-05-31
1428
+ * gets modeled as two rows; `at` parameter resolution picks the correct
1429
+ * row per call timestamp. Promo flips happen automatically at the
1430
+ * boundary without alpha cuts.
1431
+ *
1432
+ * SWR cache holds the FULL pricing snapshot (all active rows for all
1433
+ * models). Per-call `at` filtering is in-memory — keeps the SWR semantics
1434
+ * uniform with other adapters (one cache, one snapshot, sync reads).
1435
+ */
1436
+ interface PricingRow {
1437
+ modelId: string;
1438
+ costInputPer1m: number;
1439
+ costOutputPer1m: number;
1440
+ cacheInputPer1m?: number;
1441
+ cacheCreationPer1m?: number;
1442
+ validFrom: number;
1443
+ validUntil?: number;
1444
+ source?: string;
1445
+ }
1446
+ /**
1447
+ * Sync reader for the brain-driven pricing snapshot. Returns bundled
1448
+ * profile pricing when brain-query is disabled, cold, or unreachable.
1449
+ * Caller filters by `at` via {@link resolvePricingAt}.
1450
+ */
1451
+ declare const loadPricingFromBrain: () => PricingRow[];
1452
+ /**
1453
+ * Resolve the active pricing row for a model at a given timestamp.
1454
+ * Picks the row with the latest `valid_from <= at` whose
1455
+ * `valid_until > at` (or NULL — open-ended).
1456
+ *
1457
+ * Returns `undefined` when no row matches. Callers should fall back to
1458
+ * profile static pricing in that case.
1459
+ */
1460
+ declare function resolvePricingAt(modelId: string, at?: Date): PricingRow | undefined;
1461
+
1462
+ /**
1463
+ * models-brain — alpha.11 KG-14 adapter (the largest of the four).
1464
+ *
1465
+ * Brain-driven model registry + aliases. Two adapters share the same
1466
+ * SWR snapshot:
1467
+ *
1468
+ * - `loadModelsFromBrain()` — `Map<modelId, ModelProfile>` from
1469
+ * `kgauto_models` table (cliffs/lowering/recovery as JSONB columns).
1470
+ * - `loadAliasesFromBrain()` — `Record<aliasId, canonicalId>` from
1471
+ * `kgauto_aliases` table.
1472
+ *
1473
+ * After alpha.11, new-model onboarding becomes brain INSERT (vs PR + alpha
1474
+ * cut + 3 consumer refreshes). The auto-onboard pipeline
1475
+ * (`scripts/check-model-releases.mjs`) shifts from emitting profile.ts
1476
+ * edits to writing brain rows directly.
1477
+ *
1478
+ * **D5 — alias resolution stable regardless of canonical's active state.**
1479
+ * `canonicalId('deepseek-chat') → 'deepseek-v4-flash'` even when the
1480
+ * canonical row is `active=false`. Aliases are wire-format contracts;
1481
+ * legacy callers' resolution promise outlives the canonical's active
1482
+ * status. Deprecation (`active=false`) affects chain composition only.
1483
+ */
1484
+
1485
+ /**
1486
+ * Exported brain-row shape for `kgauto_models`. Mirrors the SQL table
1487
+ * (`v2/brain/migrations/010_kgauto_models_and_aliases.sql`) — column names
1488
+ * are snake_case to match PostgREST. Used by operator scripts that write
1489
+ * to brain (auto-onboard, promote-model) — see `profileToRow()`.
1490
+ *
1491
+ * Read path stays internal via `RawModelRow` to keep `rowToProfile()`'s
1492
+ * tolerance contract from leaking into write callers.
1493
+ */
1494
+ interface ModelBrainRow {
1495
+ model_id: string;
1496
+ provider: string;
1497
+ status?: string;
1498
+ max_context_tokens?: number;
1499
+ max_output_tokens?: number;
1500
+ max_tools?: number;
1501
+ parallel_tool_calls?: boolean;
1502
+ structured_output?: string;
1503
+ system_prompt_mode?: string;
1504
+ streaming?: boolean;
1505
+ cliffs?: unknown;
1506
+ lowering?: unknown;
1507
+ recovery?: unknown;
1508
+ strengths?: string[] | null;
1509
+ weaknesses?: string[] | null;
1510
+ cost_input_per_1m?: number;
1511
+ cost_output_per_1m?: number;
1512
+ notes?: string | null;
1513
+ verified_against_docs?: string | null;
1514
+ archetype_perf?: Record<string, number> | null;
1515
+ version_added?: string;
1516
+ version_removed?: string | null;
1517
+ active?: boolean;
1518
+ /** alpha.41 — model-family tag (migration 024 column). */
1519
+ family?: string | null;
1520
+ }
1521
+ interface ProfileToRowOptions {
1522
+ /** e.g. `'2.0.0-alpha.12'` — leave undefined to omit from row. */
1523
+ versionAdded?: string;
1524
+ /** Pass `null` to clear; omit to leave field unset. */
1525
+ versionRemoved?: string | null;
1526
+ /** Defaults to true if omitted. */
1527
+ active?: boolean;
1528
+ /**
1529
+ * Override verifiedAgainstDocs (e.g. set to `null` for auto-onboard).
1530
+ * When omitted, the profile's own value is used. Pass `null` explicitly
1531
+ * to write a SQL NULL (e.g. unverified auto-onboard rows).
1532
+ */
1533
+ verifiedAgainstDocs?: string | null;
1534
+ }
1535
+ /**
1536
+ * Inverse of `rowToProfile` — serialize a `ModelProfile` to a `kgauto_models`
1537
+ * row payload for INSERT/UPSERT. Used by operator scripts that write to
1538
+ * brain (auto-onboard pipeline, promote-model verification CLI).
1539
+ *
1540
+ * Row-level fields (`version_added`, `version_removed`, `active`) are
1541
+ * operator-controlled and pass through `opts`. `verifiedAgainstDocs` can
1542
+ * also be overridden via `opts` — auto-onboard explicitly passes `null` to
1543
+ * mark unverified rows (the column is DATE, doesn't accept the
1544
+ * `'UNVERIFIED-AUTO-ONBOARD'` sentinel used in PROFILES_RAW).
1545
+ */
1546
+ declare function profileToRow(profile: ModelProfile, opts?: ProfileToRowOptions): ModelBrainRow;
1547
+ /**
1548
+ * Sync reader for the brain-driven model registry. Returns bundled
1549
+ * PROFILES_RAW when brain-query is disabled, cold, or unreachable.
1550
+ */
1551
+ declare const loadModelsFromBrain: () => Map<string, ModelProfile>;
1552
+ /**
1553
+ * Sync reader for the brain-driven aliases map. Returns bundled ALIASES
1554
+ * when brain-query is disabled, cold, or unreachable.
1555
+ *
1556
+ * D5: this map carries both active and inactive canonical mappings —
1557
+ * alias resolution is stable regardless of canonical's `active` state.
1558
+ */
1559
+ declare const loadAliasesFromBrain: () => Record<string, string>;
1560
+
1561
+ /**
1562
+ * exclusion-findings-brain — alpha.38 KG-19 adapter.
1563
+ *
1564
+ * Per-tenant SWR cache for the `exclusion_findings` table populated by the
1565
+ * `kgauto-exclusion-re-evaluation-watch` cron (alpha.37 substrate). Distinct
1566
+ * from the cross-tenant `brain-query.ts` snapshot because exclusion findings
1567
+ * are scoped per `app_id` — one process = one consumer = one appId, but the
1568
+ * cache key supports multi-app processes by keying snapshots by appId.
1569
+ *
1570
+ * Architecture mirrors `brain-query.ts` but with a per-(appId) snapshot:
1571
+ *
1572
+ * - **Sync API surface.** `getStaleExclusionFindings({ appId, archetype })`
1573
+ * returns `ExclusionFindingRow[]` immediately. First call returns the
1574
+ * bundled fallback (empty array); async refresh fires in background;
1575
+ * subsequent calls within TTL return brain data.
1576
+ *
1577
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
1578
+ * per appId per TTL window. Tests can reset between cases.
1579
+ *
1580
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
1581
+ * silent bundled fallback (empty array). Never throws. Warns once per
1582
+ * process per error to avoid log spam.
1583
+ *
1584
+ * - **Opt-in.** Activation gated on `configureExclusionFindingsBrain()`
1585
+ * having been called with a runtime. The public `configureBrain()` in
1586
+ * brain.ts wires this up automatically when `BrainConfig.brainQuery
1587
+ * .findingsExclusions !== false`.
1588
+ *
1589
+ * Default endpoint:
1590
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions`
1591
+ * The route accepts `?app_id=X` and returns a JSON array of findings
1592
+ * for that app filtered to `resolved_at IS NULL`. Public read; data
1593
+ * carries no consumer PII (app id, archetype, model id, cost ratio,
1594
+ * savings estimate).
1595
+ */
1596
+ /**
1597
+ * Shape of one row from the `exclusion_findings` cache table. Mirrors the
1598
+ * snake_case JSONB returned by the brain RPC + the dashboard endpoint.
1599
+ * Camel-case mapping happens at the boundary (rowToFinding) so the in-memory
1600
+ * shape stays consistent with the rest of the library.
1601
+ */
1602
+ interface ExclusionFindingRow {
1603
+ /** Intent archetype the finding applies to (e.g. 'hunt', 'classify'). */
1604
+ archetype: string;
1605
+ /** Canonical model id that the consumer has excluded (zero traffic in window). */
1606
+ excludedModel: string;
1607
+ /** Provider of the excluded model (e.g. 'deepseek', 'openai'). */
1608
+ excludedProvider: string;
1609
+ /** Detection verdict — alpha.37 ships 'recommend-probe' only. */
1610
+ verdict: 'recommend-probe' | 'unblock' | 'stay-excluded' | 'inconclusive';
1611
+ /**
1612
+ * Estimated 30-day savings in USD if the excluded model becomes primary
1613
+ * on this archetype. Null when pricing is incomplete or excluded model is
1614
+ * more expensive than the leader.
1615
+ */
1616
+ estimatedSavingsUsd30d: number | null;
1617
+ /** Renderable summary; produced by the detector / RPC. */
1618
+ message: string;
1619
+ /** Actionable recommendation; produced by the detector / RPC. */
1620
+ suggestion: string;
1621
+ /** Detector confidence tier. */
1622
+ confidence: 'high' | 'medium' | 'low';
1623
+ /**
1624
+ * Free-form evidence pack (cost ratio, leader info, promo flags, parallel-
1625
+ * tool hint, etc.). Surfaced verbatim to advisor rules for richer messages.
1626
+ * Optional — older detector runs may not populate every field.
1627
+ */
1628
+ evidence?: Record<string, unknown>;
1629
+ }
1630
+ /**
1631
+ * Default endpoint hosted on the kgauto-dashboard. Public read — data carries
1632
+ * no PII (app id, archetype, model id, cost ratio, savings estimate). Mirrors
1633
+ * the cross-tenant `/api/kgauto-v2/config` pattern.
1634
+ */
1635
+ declare const DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
1636
+ /**
1637
+ * Sync introspection — is the findings-brain active? Used by advisor rules
1638
+ * to decide whether to even attempt a read.
1639
+ */
1640
+ declare function isExclusionFindingsBrainActive(): boolean;
1641
+ interface GetExclusionFindingsOpts {
1642
+ /** App id to read findings for. Required. */
1643
+ appId: string;
1644
+ /**
1645
+ * Optional archetype filter. When set, returns only findings where
1646
+ * `archetype` matches. When omitted, returns all findings for the app.
1647
+ */
1648
+ archetype?: string;
1649
+ }
1650
+ /**
1651
+ * Sync reader. Returns the cached findings for `appId`, optionally filtered
1652
+ * to a single archetype. First call returns empty array and triggers async
1653
+ * refresh; subsequent calls within TTL return brain data.
1654
+ *
1655
+ * NEVER throws. Brain down / endpoint misconfigured / mapper exception →
1656
+ * empty array.
1657
+ */
1658
+ declare function getStaleExclusionFindings(opts: GetExclusionFindingsOpts): ExclusionFindingRow[];
1659
+
1660
+ /**
1661
+ * Family resolution — alpha.41.
1662
+ *
1663
+ * "I want the latest Opus" → kgauto picks the current+active model in the
1664
+ * `claude-opus` family. Closes the loop where consumer code carries hardcoded
1665
+ * `claude-opus-4-6` literals long after `claude-opus-4-7` ships and goes
1666
+ * current — the s47 trigger (IC's `generate` chain still routing 43 calls to
1667
+ * legacy 4-6 in production).
1668
+ *
1669
+ * Two surfaces:
1670
+ * - `getRecommendedPrimary({ family, ..., fallback })` — public, sync,
1671
+ * used at IR-construction time when the consumer wants a literal id back
1672
+ * (with a fallback floor for cold-start brain).
1673
+ * - `resolveFamilyEntry({ family, archetype?, appId? })` — internal,
1674
+ * called from compile() when an IR's `models[]` entry is shaped
1675
+ * `{ family: string }`. Throws `FamilyResolutionError` on failure.
1676
+ *
1677
+ * Both routes share the same algorithm (locked in the alpha.41 Phase 0
1678
+ * design contract); they differ only in the fallback ergonomics. The
1679
+ * public route accepts a required `fallback: string`; the IR route throws.
1680
+ *
1681
+ * Pure resolution. No network. No async. Brain-registry reads go through
1682
+ * the existing SWR cache (`loadModelsFromBrain` from `models-brain.ts`) —
1683
+ * cold-start returns bundled profiles, which still resolve via the
1684
+ * `deriveFamilyFromModelId` fallback when the brain row's `family` column
1685
+ * is null (G1 contract: graceful pre-migration behavior).
1686
+ *
1687
+ * @see command-center/advisory/kgauto/2026-05-26_alpha-41-model-family-aliases-and-promotion-probe-watcher.md
1688
+ */
1689
+
1690
+ interface GetRecommendedPrimaryOptions {
1691
+ /**
1692
+ * Family tag (e.g. `'claude-opus'`, `'gemini-flash'`). See the Phase 0
1693
+ * design contract's family taxonomy table for the locked initial set;
1694
+ * extensible via brain migrations.
1695
+ */
1696
+ family: string;
1697
+ /**
1698
+ * Optional archetype gate. When provided, candidates must clear
1699
+ * {@link ARCHETYPE_FLOOR_DEFAULT} on `archetypePerf[archetype]`. Also used
1700
+ * as the primary sort key (DESC) when multiple candidates qualify.
1701
+ */
1702
+ archetype?: IntentArchetypeName;
1703
+ /**
1704
+ * Optional consumer-app id. When provided, candidates matching a
1705
+ * `stay-excluded` finding for `(appId, archetype)` in the
1706
+ * exclusion-findings cache (alpha.38 substrate) are filtered out.
1707
+ */
1708
+ appId?: string;
1709
+ /**
1710
+ * Consumer-posture tag. `'locked'` short-circuits resolution and returns
1711
+ * the literal `fallback` unconditionally — useful for compliance /
1712
+ * contract / brand-promise flows where the consumer doesn't want kgauto
1713
+ * picking the model on their behalf.
1714
+ */
1715
+ posture?: 'preferred' | 'open' | 'locked';
1716
+ /**
1717
+ * Last-resort literal model id. REQUIRED. Returned when (a) brain
1718
+ * registry is cold / no candidates exist, (b) `posture === 'locked'`,
1719
+ * (c) every candidate was filtered out by archetype / exclusion gates.
1720
+ *
1721
+ * The fallback is NOT validated against the family — kgauto trusts the
1722
+ * consumer to pass a meaningful floor. The contract intent is "even when
1723
+ * everything below is on fire, you still get a model id back."
1724
+ */
1725
+ fallback: string;
1726
+ }
1727
+ /**
1728
+ * Thrown by `resolveFamilyEntry` (the internal compile-time twin) when a
1729
+ * `{ family: string }` IR entry can't resolve to any current+active model.
1730
+ * Surfaces with the family string + a one-line cause so consumer error
1731
+ * handling can distinguish "you typo'd the family tag" from "brain is cold
1732
+ * and nothing matches."
1733
+ *
1734
+ * The public `getRecommendedPrimary` does NOT throw — it returns
1735
+ * `fallback` instead.
1736
+ */
1737
+ declare class FamilyResolutionError extends Error {
1738
+ readonly family: string;
1739
+ readonly cause: string;
1740
+ constructor(family: string, cause: string);
1741
+ }
1742
+ /**
1743
+ * Deterministic model_id → family inference. Pure function; no brain
1744
+ * lookup. Used as the runtime fallback when a brain row's `family` column
1745
+ * is null (pre-migration 024) and as the canonical mapping that migration
1746
+ * 024's CASE statement mirrors.
1747
+ *
1748
+ * Returns null for unrecognized ids — caller must handle (typically by
1749
+ * skipping the row in family resolution).
1750
+ *
1751
+ * Order matters: more specific patterns first (e.g. `flash-lite` before
1752
+ * `flash`; `pro` before `chat`). The brain-side CASE statement uses the
1753
+ * same priority.
1754
+ */
1755
+ declare function deriveFamilyFromModelId(modelId: string): string | null;
1756
+ /**
1757
+ * Public sync resolver. Pure (modulo brain snapshot read). Returns the
1758
+ * literal model id of the best candidate, or `fallback` when resolution
1759
+ * yields nothing.
1760
+ */
1761
+ declare function getRecommendedPrimary(opts: GetRecommendedPrimaryOptions): string;
1762
+
1763
+ /**
1764
+ * promote-ready-brain — alpha.41 substrate.
1765
+ *
1766
+ * Per-tenant SWR cache for the `promote_ready_findings` table populated by
1767
+ * the autonomous `promotion-probe-watcher` (Mode 2). Mirrors
1768
+ * `exclusion-findings-brain.ts` shape byte-for-byte where applicable; this
1769
+ * is the read-side substrate for the compile-time `promote-ready` advisor
1770
+ * rule.
1771
+ *
1772
+ * Architecture (mirror of exclusion-findings-brain):
1773
+ *
1774
+ * - **Sync API surface.** `getPromoteReadyFindings({ appId, archetype,
1775
+ * family })` returns `PromoteReadyFindingRow[]` immediately. First call
1776
+ * returns the bundled fallback (empty array); async refresh fires in
1777
+ * background; subsequent calls within TTL return brain data.
1778
+ *
1779
+ * - **Per-appId snapshot.** Each appId gets its own cache entry. One fetch
1780
+ * per appId per TTL window. Tests reset between cases via
1781
+ * `_testResetPromoteReadyFindings()`.
1782
+ *
1783
+ * - **Tolerant.** Brain down / endpoint misconfigured / unexpected shape →
1784
+ * silent bundled fallback (empty array). Never throws. Warns once per
1785
+ * process per error to avoid log spam.
1786
+ *
1787
+ * - **Opt-in.** Activation gated on `configurePromoteReadyBrain()` having
1788
+ * been called with a runtime. The public `configureBrain()` in brain.ts
1789
+ * wires this up automatically when
1790
+ * `BrainConfig.brainQuery.findingsPromoteReady !== false`.
1791
+ *
1792
+ * Plus: `markPromoteReadyHandled` — direct PostgREST PATCH against the
1793
+ * brain (no kgauto proxy). Mirrors `markExclusionFindingHandled` shape
1794
+ * byte-for-byte. Idempotent on `resolved_at=is.null` filter.
1795
+ *
1796
+ * Default endpoint:
1797
+ * `https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/promote-ready`
1798
+ * The route accepts `?app_id=X` and returns a JSON array of findings
1799
+ * for that app filtered to `resolved_at IS NULL`.
1800
+ */
1801
+
1802
+ /**
1803
+ * Shape of one row from the `promote_ready_findings` cache table. Mirrors
1804
+ * the snake_case JSONB returned by the brain endpoint, mapped to camelCase
1805
+ * at the boundary (rowToFinding) so the in-memory shape stays consistent
1806
+ * with the rest of the library.
1807
+ */
1808
+ interface PromoteReadyFindingRow {
1809
+ /** Intent archetype the finding applies to. */
1810
+ archetype: string;
1811
+ /** Model family (e.g. 'claude-opus', 'gemini-flash'). */
1812
+ family: string;
1813
+ /** The candidate model that the probe validated. */
1814
+ candidateModel: string;
1815
+ /** The current production model the candidate was compared against. */
1816
+ currentModel: string;
1817
+ /** Sample size of the probe run (typically 10). */
1818
+ sampleN: number;
1819
+ /** Fraction of probes where the judge verdict was 'candidate-better' or
1820
+ * 'tied'. 0.000 to 1.000. */
1821
+ judgePassRate: number;
1822
+ /** Mean judge score across the probe sample. 1.00 to 5.00. */
1823
+ judgeAvgScore: number;
1824
+ /** Signed cost delta as a fraction (negative = candidate is cheaper).
1825
+ * Null when pricing data was incomplete at probe time. */
1826
+ costDeltaPct: number | null;
1827
+ /** ISO timestamp of detection (when the probe wrote the row). */
1828
+ detectedAt: string;
1829
+ }
1830
+ /**
1831
+ * Resolution sources supported by alpha.41 `markPromoteReadyHandled`. The
1832
+ * three values map to the three CHECK-constrained resolution values on
1833
+ * `promote_ready_findings.resolution`:
1834
+ *
1835
+ * - `'promoted'` — consumer migrated to the candidate model. Strong
1836
+ * positive signal; the probe was right.
1837
+ * - `'declined'` — consumer evaluated and chose not to promote.
1838
+ * Strong negative signal; revisit only on new
1839
+ * family entries or material score swings.
1840
+ * - `'still-evaluating'` — consumer acknowledges the finding but defers
1841
+ * the decision. Acknowledges-without-deciding;
1842
+ * finding silences this cycle but next probe may
1843
+ * re-surface.
1844
+ */
1845
+ type PromoteReadyResolution = 'promoted' | 'declined' | 'still-evaluating';
1846
+ interface MarkPromoteReadyHandledOptions {
1847
+ /** App id the finding belongs to. Required (RLS scopes writes by this). */
1848
+ appId: string;
1849
+ /** Archetype the finding applies to (e.g. 'hunt', 'classify'). */
1850
+ archetype: IntentArchetypeName | string;
1851
+ /** Model family the finding applies to (e.g. 'claude-opus'). */
1852
+ family: string;
1853
+ /** Resolution semantics — see `PromoteReadyResolution`. */
1854
+ resolution: PromoteReadyResolution;
1855
+ /** Optional free-form note explaining the decision. */
1856
+ resolutionNote?: string;
1857
+ /** Brain Supabase URL base (e.g. `https://<project>.supabase.co`). */
1858
+ brainEndpoint: string;
1859
+ /** Consumer-scoped JWT carrying the `app_id` claim. */
1860
+ brainJwt: string;
1861
+ /** Supabase anon key for the `apikey` header. */
1862
+ brainAnonKey: string;
1863
+ /** Injected fetch for tests. Defaults to global fetch. */
1864
+ fetch?: typeof fetch;
1865
+ }
1866
+ /**
1867
+ * Mark a probe-validated promote-ready finding as handled. Returns an
1868
+ * `ok/reason` envelope matching `markExclusionFindingHandled`.
1869
+ *
1870
+ * Idempotent: if no row matches the (app_id, archetype, family) tuple
1871
+ * (already resolved, never existed, watcher not yet UPSERTed), PostgREST
1872
+ * returns 200/204 with zero affected rows and we return `{ ok: true }`.
1873
+ *
1874
+ * Reasons surfaced on failure:
1875
+ * - `app_id_required` / `archetype_required` / `family_required`
1876
+ * - `resolution_invalid` — not one of the three documented values
1877
+ * - `brain_auth_misconfig` — 401/403
1878
+ * - `brain_unavailable` — 5xx
1879
+ * - `network_error:<message>` — fetch threw
1880
+ * - `patch_failed:<status>` — anything else non-2xx
1881
+ */
1882
+ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions): Promise<{
1883
+ ok: true;
1884
+ } | {
1885
+ ok: false;
1886
+ reason: string;
1887
+ }>;
1888
+
192
1889
  /**
193
1890
  * @warmdrift/kgauto v2 — prompt compiler + central learning brain.
194
1891
  *
@@ -235,4 +1932,4 @@ declare function countTokens(text: string): number;
235
1932
  */
236
1933
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
237
1934
 
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 };
1935
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, 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, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, execute, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, profileToRow, record, recordOutcome, resetTokenizer, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };