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

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