@warmdrift/kgauto-compiler 2.0.0-alpha.8 → 2.0.0-alpha.80

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 (55) hide show
  1. package/README.md +176 -46
  2. package/dist/brain-proxy.d.mts +113 -0
  3. package/dist/brain-proxy.d.ts +113 -0
  4. package/dist/brain-proxy.js +193 -0
  5. package/dist/brain-proxy.mjs +6 -0
  6. package/dist/chunk-65ZMX5OT.mjs +169 -0
  7. package/dist/{chunk-5TI6PNSK.mjs → chunk-BVEXV5KC.mjs} +11 -0
  8. package/dist/chunk-CIBHU67M.mjs +203 -0
  9. package/dist/chunk-NBO4R5PC.mjs +313 -0
  10. package/dist/chunk-P3TOAEG4.mjs +56 -0
  11. package/dist/chunk-PMTT4H5W.mjs +825 -0
  12. package/dist/chunk-RO22VFIF.mjs +29 -0
  13. package/dist/chunk-VVRDFE6T.mjs +1707 -0
  14. package/dist/dialect.d.mts +41 -3
  15. package/dist/dialect.d.ts +41 -3
  16. package/dist/dialect.js +14 -2
  17. package/dist/dialect.mjs +5 -3
  18. package/dist/glassbox/index.d.mts +59 -0
  19. package/dist/glassbox/index.d.ts +59 -0
  20. package/dist/glassbox/index.js +312 -0
  21. package/dist/glassbox/index.mjs +12 -0
  22. package/dist/glassbox-routes/format.d.mts +24 -0
  23. package/dist/glassbox-routes/format.d.ts +24 -0
  24. package/dist/glassbox-routes/format.js +86 -0
  25. package/dist/glassbox-routes/format.mjs +18 -0
  26. package/dist/glassbox-routes/index.d.mts +191 -0
  27. package/dist/glassbox-routes/index.d.ts +191 -0
  28. package/dist/glassbox-routes/index.js +3057 -0
  29. package/dist/glassbox-routes/index.mjs +668 -0
  30. package/dist/glassbox-routes/react/index.d.mts +74 -0
  31. package/dist/glassbox-routes/react/index.d.ts +74 -0
  32. package/dist/glassbox-routes/react/index.js +819 -0
  33. package/dist/glassbox-routes/react/index.mjs +754 -0
  34. package/dist/index.d.mts +3449 -21
  35. package/dist/index.d.ts +3449 -21
  36. package/dist/index.js +10208 -1681
  37. package/dist/index.mjs +5891 -186
  38. package/dist/ir-BFwWhj2s.d.mts +1707 -0
  39. package/dist/ir-DZKS1tI7.d.ts +1707 -0
  40. package/dist/key-health.d.mts +131 -0
  41. package/dist/key-health.d.ts +131 -0
  42. package/dist/key-health.js +228 -0
  43. package/dist/key-health.mjs +6 -0
  44. package/dist/profiles.d.mts +302 -2
  45. package/dist/profiles.d.ts +302 -2
  46. package/dist/profiles.js +1320 -18
  47. package/dist/profiles.mjs +9 -1
  48. package/dist/types-B4kz3Vs0.d.ts +131 -0
  49. package/dist/types-D_fLt_Xv.d.ts +142 -0
  50. package/dist/types-DpcAMmk-.d.mts +131 -0
  51. package/dist/types-hjzSWxtv.d.mts +142 -0
  52. package/package.json +54 -8
  53. package/dist/chunk-MBEI5UOM.mjs +0 -409
  54. package/dist/profiles-B3eNQ2py.d.ts +0 -619
  55. package/dist/profiles-Py8c7zjJ.d.mts +0 -619
@@ -0,0 +1,1707 @@
1
+ import { IntentArchetypeName, OutputMode } from './dialect.mjs';
2
+
3
+ /**
4
+ * Golden-set capture (alpha.62, eval spine — design brief 2026-07-17).
5
+ *
6
+ * The eval-driven self-improvement contract needs a replay corpus: 20–50 real
7
+ * historical IRs per (app, archetype), stored WITH the incumbent's output.
8
+ * This module is the capture side — a sampling gate on call()'s success path
9
+ * that stores the full PromptIR + served response to `kgauto_golden_irs`.
10
+ *
11
+ * ## Consent posture (s51 amendment, ratified 2026-07-17)
12
+ *
13
+ * Golden rows carry RAW prompts — a deliberate, documented departure from the
14
+ * s51 "brain holds no raw consumer prompts" rule. Capture is therefore
15
+ * strictly opt-in:
16
+ *
17
+ * - `KGAUTO_GOLDEN_CAPTURE=0.1` in the consumer's environment (the env var
18
+ * IS the consent act — the consumer's operator sets it knowingly), or
19
+ * - `CallOptions.goldenCapture.sampleRate` in consumer code.
20
+ *
21
+ * Default is 0 (off): absent flag, empty string, non-finite, or ≤0 all mean
22
+ * "never capture". Every stored row records its consent provenance in the
23
+ * `consent` column. Reads are strictly app-scoped (RLS) — a consumer can only
24
+ * ever see its own raw prompts.
25
+ */
26
+
27
+ /** Consumer-facing capture options (CallOptions.goldenCapture). */
28
+ interface GoldenCaptureOptions {
29
+ /**
30
+ * Probability [0..1] that a successful call's IR + output is stored as a
31
+ * golden row. Overrides the KGAUTO_GOLDEN_CAPTURE env var when set.
32
+ */
33
+ sampleRate?: number;
34
+ /**
35
+ * Optional free-text appended to the stored consent provenance (e.g. a
36
+ * ticket ref or the operator who approved capture for this surface).
37
+ */
38
+ consentNote?: string;
39
+ }
40
+ /**
41
+ * Parse a capture-rate env value. Mirrors the consumer-side
42
+ * `parseShadowProbeRate` semantics playbacksam established: undefined, empty,
43
+ * or non-finite → 0 (default-OFF); result clamped to [0, 1].
44
+ */
45
+ declare function parseGoldenCaptureRate(raw: string | undefined): number;
46
+ /**
47
+ * Resolve the effective capture rate: explicit option wins; otherwise the
48
+ * KGAUTO_GOLDEN_CAPTURE env var (when a process env exists — Edge-safe).
49
+ */
50
+ declare function resolveGoldenCaptureRate(optRate?: number): number;
51
+ /** Sampling gate. Injectable rng for tests (same shape as shouldSampleProbe). */
52
+ declare function shouldCaptureGolden(rate: number, rng?: () => number): boolean;
53
+ /** Everything call()'s success path has in scope when capture fires. */
54
+ interface GoldenCaptureContext {
55
+ ir: PromptIR;
56
+ servedModel: string;
57
+ response: NormalizedResponse;
58
+ latencyMs: number;
59
+ handle: string;
60
+ /** Compile-time shape key (peeked before record() popped the registry). */
61
+ shapeKey?: string;
62
+ /** How the rate was resolved — recorded as consent provenance. */
63
+ consent: string;
64
+ }
65
+ /**
66
+ * Store one golden row from a live served call. Fire-and-forget discipline is
67
+ * recordGoldenIr()'s (dead-letter, ledger, honors BrainConfig.sync); this
68
+ * wrapper only shapes the row. Never throws.
69
+ */
70
+ declare function captureGoldenIr(ctx: GoldenCaptureContext): Promise<void>;
71
+
72
+ /**
73
+ * A semantically-named section of the system prompt. Sections enable
74
+ * intent-aware slicing (drop sections not tagged for this intent), dedupe
75
+ * (collapse identical sections across files), and cache marking (identify
76
+ * the stable prefix).
77
+ */
78
+ interface PromptSection {
79
+ /** Stable identifier — used for slicing, dedupe, and cache markers. */
80
+ id: string;
81
+ /** Section text. */
82
+ text: string;
83
+ /**
84
+ * Which intents this section applies to. Empty = applies to all intents.
85
+ * Pass `compile()` will drop sections whose intents array doesn't include
86
+ * the current intent.
87
+ */
88
+ intents?: IntentArchetypeName[];
89
+ /**
90
+ * If true, this section is part of the stable cacheable prefix. The lower
91
+ * pass uses this to place cache markers correctly per target.
92
+ */
93
+ cacheable?: boolean;
94
+ /**
95
+ * Section weight when ordering — lower = earlier in the assembled prompt.
96
+ * Defaults to insertion order.
97
+ */
98
+ weight?: number;
99
+ /**
100
+ * alpha.29+ — declares the section's semantic kind so kgauto can apply
101
+ * model-aware rewrites at compile time. Default `'arbitrary'` (when
102
+ * unset) for full back-compat — pre-alpha.29 sections continue working
103
+ * unchanged.
104
+ *
105
+ * alpha.29 ships rewrites for `tool_call_contract` only. Other kinds are
106
+ * type-accepted but pass through. alpha.30+ will add rewrites for
107
+ * `narration_contract`, `role_intro`, etc.
108
+ *
109
+ * See `translator.ts` for the rewrite engine that consumes this field.
110
+ */
111
+ kind?: SectionKind;
112
+ }
113
+ /**
114
+ * alpha.29+ — semantic kind tag for a `PromptSection`. The translator
115
+ * (`v2/src/translator.ts`) consumes this to apply model-aware rewrites at
116
+ * compile time. CLOSED union; future kinds extend it explicitly in named
117
+ * alpha releases.
118
+ *
119
+ * alpha.29 ships rewrites for `tool_call_contract` only. Other kinds are
120
+ * type-accepted but pass through.
121
+ *
122
+ * - `role_intro` — "You are a helpful assistant", persona blocks
123
+ * - `tool_call_contract` — tool-use rules ("call X then Y"); the alpha.29
124
+ * translator rewrites this for models with a
125
+ * sequential-tool cliff on the active archetype
126
+ * - `narration_contract` — output-format rules ("don't narrate your steps");
127
+ * alpha.30+ candidate
128
+ * - `discipline_contract`— alpha.68 / Release A (delegation-fanout-accelerator
129
+ * §5.D): surface-scaffolding gate block. When declared
130
+ * on a role/system section, the translator prepends the
131
+ * frozen `discipline-gates-v1` preamble subject to a
132
+ * two-factor eligibility screen — Factor A (archetype:
133
+ * hunt/summarize/plan/critique/judge) AND Factor C
134
+ * (output-shape: text only, never json/tool_call).
135
+ * Clears no cliff, emits no wireOverrides ⇒ no advisor
136
+ * suppression. See `translator.ts`.
137
+ * - `user_turn` — when sections carry user content rather than
138
+ * system context (rare)
139
+ * - `reference` — supporting reference data the model may consult
140
+ * - `arbitrary` — explicit pass-through (default when unset)
141
+ */
142
+ type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'discipline_contract' | 'user_turn' | 'reference' | 'arbitrary';
143
+ interface ToolDefinition {
144
+ name: string;
145
+ description?: string;
146
+ parameters?: Record<string, unknown>;
147
+ /**
148
+ * Per-intent relevance scores. Compile uses these to drop irrelevant tools.
149
+ * Missing intents default to 0.5 (neutral).
150
+ */
151
+ relevanceByIntent?: Partial<Record<IntentArchetypeName, number>>;
152
+ /** Pass-through for provider-specific fields (Anthropic input_schema, etc.). */
153
+ [key: string]: unknown;
154
+ }
155
+ interface Message {
156
+ role: 'system' | 'user' | 'assistant' | 'tool';
157
+ content: string;
158
+ /** Optional structured parts (tool calls, results) — passed through to lowering. */
159
+ parts?: unknown[];
160
+ /** For tool messages — which tool this corresponds to. */
161
+ toolName?: string;
162
+ /** For tool messages — the call id. */
163
+ toolCallId?: string;
164
+ }
165
+ /**
166
+ * The compile-time intent declaration. `name` is the app's local label;
167
+ * `archetype` is the canonical dialect-v1 archetype the app maps it to.
168
+ *
169
+ * Apps with their own intent vocabulary (tt-intelligence's "ask"/"hunt"/
170
+ * "dashboard") declare the mapping here. The brain learns by archetype, not
171
+ * by app-local name.
172
+ */
173
+ interface IntentDeclaration {
174
+ /** App-local intent name (free-form, for app's own debugging). */
175
+ name: string;
176
+ /** Canonical dialect-v1 archetype. Required for cross-app learning. */
177
+ archetype: IntentArchetypeName;
178
+ }
179
+ /**
180
+ * alpha.57 — dialect-level reasoning-effort tier (data-first).
181
+ *
182
+ * Vocabulary is a portfolio-level tier ladder (low → max), NOT any provider's
183
+ * wire value — mapping to `reasoning_effort` (OpenAI) / thinking budgets
184
+ * (Anthropic) / `thinkingConfig` (Gemini) stays consumer-side until
185
+ * routing-on-effort ships. Declaring it records the tier on the brain row
186
+ * (`compile_outcomes.effort`, migration 033) so effort×archetype quality
187
+ * evidence accumulates BEFORE any routing logic exists — same data-first
188
+ * sequencing as `tool_orchestration` (alpha.20).
189
+ */
190
+ type EffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
191
+ interface Constraints {
192
+ /** Hard latency ceiling — compiler will down-rank slow models. Advisory. */
193
+ maxLatencyMs?: number;
194
+ /** Hard cost ceiling per call (USD). Advisory. */
195
+ maxCostUsd?: number;
196
+ /**
197
+ * alpha.57 (data-first): the reasoning-effort tier the consumer ran (or
198
+ * intends to run) this call at. RECORDED, NOT APPLIED — the compiler does
199
+ * not emit provider thinking/effort params from this field and does not
200
+ * route on it yet; it flows to `compile_outcomes.effort` via record()'s
201
+ * registry auto-enrich (same pattern as `mutationsApplied`/advisories).
202
+ * Declare it truthfully: this is consumer-reported ground truth, like
203
+ * `tokensIn`/`latencyMs`. Does NOT enter the shape key (no learning-key
204
+ * fragmentation).
205
+ */
206
+ effort?: EffortLevel;
207
+ /** Caller wants structured (JSON) output. */
208
+ structuredOutput?: boolean;
209
+ /**
210
+ * alpha.69 — consumer-declared output shape. Overrides the inference in
211
+ * `resolveOutputMode` (structuredOutput ⇒ json · tools ⇒ tool_call · else
212
+ * text), which is deliberately conservative: it cannot see that an agentic
213
+ * surface carrying tools ultimately emits prose to the user.
214
+ *
215
+ * Declaring `'text'` on a tool-carrying surface is what re-opens the
216
+ * alpha.68 discipline gates for it (Factor C is a hard screen on inferred
217
+ * `tool_call`, because wrongly firing breaks a parser while wrongly
218
+ * withholding only forgoes a lift). Declare it truthfully — it is
219
+ * consumer-reported ground truth about what the model emits, and it feeds
220
+ * `shape_key`, so a false declaration fragments the learning key AND lets
221
+ * shape-altering rules fire on a structured surface.
222
+ */
223
+ outputMode?: OutputMode;
224
+ /** Hint: caller expects a short response (used to disable thinking on Gemini). */
225
+ expectedShortOutput?: boolean;
226
+ /** Hint: max response words. */
227
+ maxResponseWords?: number;
228
+ /** Override target model selection — if set, compiler uses this instead of routing. */
229
+ forceModel?: string;
230
+ /**
231
+ * alpha.20: consumer-declared tool-orchestration shape for this call.
232
+ * - 'parallel': model may fire multiple tool calls per step (current
233
+ * default behavior; the L-040 cliff applies — DeepSeek's
234
+ * `tool_count >= 1` cliff trims tools because parallel-tool throughput
235
+ * collapses to sequential semantics).
236
+ * - 'sequential': consumer commits to one tool call per step (the agentic
237
+ * loop pattern). DeepSeek V4-Flash + V4-Pro can compete cleanly in
238
+ * this mode — the L-040 cliff is silenced and the hunt chain shifts
239
+ * to a DeepSeek-tier-1 ordering.
240
+ * - 'either': consumer doesn't care; library picks the parallel chain
241
+ * (status-quo default) and may upgrade to brain-driven per-mode perf
242
+ * selection in a future release.
243
+ *
244
+ * Affects:
245
+ * - Chain composition for `archetype: 'hunt'` (see
246
+ * `getDefaultFallbackChain` and `STARTER_CHAINS_BY_MODE`).
247
+ * - L-040 cliff in `passApplyCliffs` (silent when 'sequential').
248
+ *
249
+ * Default (when undefined): equivalent to 'parallel' for back-compat
250
+ * with every pre-alpha.20 caller.
251
+ */
252
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
253
+ }
254
+ /**
255
+ * Cache marker policy for the messages array (history + currentTurn).
256
+ *
257
+ * Anthropic positional caching: a `cache_control` marker on a content block
258
+ * tells the API "remember the prefix up through this block." On a subsequent
259
+ * request whose first N tokens match, those N billed at the cached rate
260
+ * (10% of the input price). Without a marker, every call re-pays for the
261
+ * entire history.
262
+ *
263
+ * - `'none'` (default when omitted): no history cache marker. System-level
264
+ * cache markers from `PromptSection.cacheable=true` still apply.
265
+ * - `'all-but-latest'`: marks the message immediately preceding `currentTurn`
266
+ * (the last history entry). On the next call, that entire history prefix
267
+ * is cacheable. Good fit for chat/agent loops where every prior turn is
268
+ * stable.
269
+ * - `'fixed-suffix'`: marks the message `suffix` positions from the end of
270
+ * `history`. Use when the last few turns are volatile (e.g., scratchpad,
271
+ * draft revisions) but the earlier prefix is stable.
272
+ *
273
+ * For non-Anthropic providers, no wire-format marker is emitted (Gemini /
274
+ * OpenAI / DeepSeek implicit caching takes effect automatically when a
275
+ * stable prefix is reused). The compiler still computes
276
+ * `diagnostics.historyCacheableTokens` for telemetry on every provider.
277
+ *
278
+ * alpha.5.
279
+ */
280
+ type HistoryCachePolicy = {
281
+ strategy: 'none';
282
+ } | {
283
+ strategy: 'all-but-latest';
284
+ } | {
285
+ strategy: 'fixed-suffix';
286
+ suffix: number;
287
+ };
288
+ /**
289
+ * Consumer-declared policy for model selection. Lives outside the IR
290
+ * (passed via CompileOptions) because it's a SESSION/APP-level constraint,
291
+ * not a per-call shape.
292
+ *
293
+ * The original tt-intelligence scenario (s11): user capped Anthropic
294
+ * spending on Sonnet for cost reasons. v2 compile() kept picking Sonnet
295
+ * as the best target, Hunter's preflight hit the cap and fell back to
296
+ * Flash — every single call. CompilePolicy.blockedModels lets the
297
+ * consumer tell kgauto "don't pick Sonnet right now" and the compiler
298
+ * routes to the next-best option directly. No wasted preflight tax.
299
+ *
300
+ * This is the "coach knows the constraints" feature — kgauto stops
301
+ * recommending things the consumer has already ruled out.
302
+ */
303
+ interface CompilePolicy {
304
+ /**
305
+ * Model IDs the consumer has gated. Compile() will never select these.
306
+ * Use for: cost caps, account-level rate limits, "this model is broken
307
+ * for our workload" decisions.
308
+ */
309
+ blockedModels?: string[];
310
+ /**
311
+ * Hard ceiling on estimated input cost per call (USD). Models whose
312
+ * estimated cost exceeds this are rejected. Use for: budget enforcement
313
+ * on high-volume routes.
314
+ */
315
+ maxCostPerCallUsd?: number;
316
+ /**
317
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.1) — trace-level
318
+ * cost ceiling (USD) across a fan-out `trace_id`'s cumulative spend.
319
+ *
320
+ * RECORDED / INERT in Release A: nothing fans out yet, so this field is
321
+ * accepted and carried but the compiler enforces NOTHING from it. It is
322
+ * enforced by the `delegate` primitive against the running trace spend in
323
+ * Release D. Kept distinct from `maxCostPerCallUsd` because that per-call
324
+ * ceiling is trivially evadable N times under fan-out — a fan-out budget
325
+ * has to be trace-scoped, not per-call.
326
+ */
327
+ maxCostPerTraceUsd?: number;
328
+ /**
329
+ * Model IDs the consumer prefers. When multiple models fit, preferred
330
+ * models get a rank boost (large enough to overcome small quality
331
+ * differences but not large enough to override hard rejects).
332
+ */
333
+ preferredModels?: string[];
334
+ /**
335
+ * Customer-posture tag (master plan §1.2, alpha.9).
336
+ *
337
+ * - `'locked'` — compliance/contract/brand-promise. Caller passes
338
+ * exactly one model; no fallback is desired. kgauto
339
+ * never walks the chain.
340
+ * - `'preferred'` — user-selected primary, fallback chain as safety
341
+ * net. On 429/5xx, walk the chain and surface
342
+ * `fellOverFrom` so the consumer can show "Claude
343
+ * was busy; we used Pro for this answer."
344
+ * - `'open'` — library picks the chain. Model identity is
345
+ * irrelevant; output is the contract.
346
+ *
347
+ * The field is **informational** — kgauto's execution path is already
348
+ * determined by the shape of `ir.models`. Posture surfaces in
349
+ * telemetry so the cost-watcher can distinguish "locked failed, no
350
+ * fallback was tried" from "open chain exhausted." Default: when
351
+ * `ir.models.length === 1` posture is treated as `'locked'` by the
352
+ * advisor; otherwise unspecified.
353
+ */
354
+ posture?: 'locked' | 'preferred' | 'open';
355
+ }
356
+ /**
357
+ * alpha.41 — entry in `PromptIR.models[]`. Either a literal model id (the
358
+ * pre-alpha.41 shape, fully preserved) or a `{ family: string }` alias that
359
+ * resolves at compile() time to the latest-current model in that family.
360
+ *
361
+ * Family entries resolve via `resolveFamilyEntry` (internal twin of the
362
+ * public `getRecommendedPrimary`). Resolution fails CLOSED — a family that
363
+ * matches no current+active candidate throws `FamilyResolutionError` at
364
+ * compile time. Consumers who want a literal fallback should call
365
+ * `getRecommendedPrimary({ family, fallback, ... })` at IR-construction time
366
+ * and inline the resolved id, rather than passing `{ family }` into the IR.
367
+ *
368
+ * Family taxonomy is defined in `family-resolution.ts`; see also migration
369
+ * 024 (`kgauto_models.family` column + index).
370
+ */
371
+ type ChainModelEntry = string | {
372
+ family: string;
373
+ };
374
+ /**
375
+ * The IR — the input to compile().
376
+ */
377
+ interface PromptIR {
378
+ /** App identifier — required for multi-tenant brain. */
379
+ appId: string;
380
+ /** Intent declaration — what is this call doing? */
381
+ intent: IntentDeclaration;
382
+ /** Structured system prompt sections. */
383
+ sections: PromptSection[];
384
+ /** Available tools (compiler may drop based on intent relevance + budget). */
385
+ tools?: ToolDefinition[];
386
+ /** Conversation history (compiler may compress old turns). */
387
+ history?: Message[];
388
+ /** The user's current turn — never dropped. */
389
+ currentTurn?: Message;
390
+ /**
391
+ * Allowed model IDs (or family aliases — alpha.41+), in caller-preference
392
+ * order. Compiler resolves family entries to literal ids before scoring
393
+ * and picks among them. See {@link ChainModelEntry}.
394
+ *
395
+ * Internal passes downstream of compile()'s family-resolution step
396
+ * receive a narrowed `string[]` shape — `string` is a subtype of
397
+ * `ChainModelEntry`, so a `string[]` IS a `ChainModelEntry[]` at the
398
+ * type level. Code that needs to access string ids (passes.ts) reads
399
+ * via `getModelIds(ir)` from `models-runtime.ts` rather than narrowing
400
+ * inline.
401
+ */
402
+ models: ChainModelEntry[];
403
+ /** Compile constraints. */
404
+ constraints?: Constraints;
405
+ /**
406
+ * Cache marker placement policy for the messages array. Default = no
407
+ * history cache markers. See `HistoryCachePolicy` for semantics.
408
+ * alpha.5.
409
+ */
410
+ historyCachePolicy?: HistoryCachePolicy;
411
+ }
412
+ type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'zai' | 'moonshot' | 'mistral' | 'xai';
413
+ /**
414
+ * Mutation IDs that fired during compile. Empty in v1 (no mutation engine
415
+ * yet). Populated when the brain is online and pushing mutations.
416
+ */
417
+ type MutationApplied = {
418
+ id: string;
419
+ source: string;
420
+ passName: string;
421
+ description: string;
422
+ /**
423
+ * alpha.73 — the ranking delta this mutation applied, when it applied one.
424
+ * Negative de-ranks, positive boosts. Absent for mutations that do not touch
425
+ * rank (advisory/labelling mutations).
426
+ *
427
+ * Exists because a consumer could previously see *that* a gate fired and
428
+ * *why*, but not *how much* — which cannot distinguish "the gate did not see
429
+ * this model" from "the gate saw it and the penalty lost to a price
430
+ * advantage." PB spent two days and three wrong conclusions inside that gap
431
+ * (2026-07-25/26), and both wrong conclusions were inferences substituted
432
+ * for a quantity that was known at emit time and thrown away. Same class as
433
+ * the `rankedOn` request: a consumer cannot reason about ranking behaviour
434
+ * it cannot observe, so it will guess.
435
+ */
436
+ rankDelta?: number;
437
+ /**
438
+ * alpha.73 — the model's rank before and after this mutation, when it
439
+ * changed one. Together with `rankDelta` this answers the question a
440
+ * penalty magnitude alone cannot: whether the gated model still WON.
441
+ */
442
+ rankBefore?: number;
443
+ rankAfter?: number;
444
+ };
445
+ /**
446
+ * alpha.78 — shape-proof accessor for a mutation entry (PB filing
447
+ * 2026-07-25 addendum #2). TWO public surfaces share the name
448
+ * `mutationsApplied` with DIFFERENT element types: `CompileResult` /
449
+ * `CallResult` carry `MutationApplied[]` (objects), while
450
+ * `compileForAISDKv6` carries `string[]` (ids) — each internally
451
+ * consistent, but a consumer coding to one surface's d.ts while reading the
452
+ * other's runtime gets a silent false negative (`typeof m === 'string'`
453
+ * compiles clean, runs clean, and is wrong on every row). Neither element
454
+ * type can change without breaking a live consumer, so the fix is an
455
+ * accessor that is correct on both.
456
+ */
457
+ declare function mutationId(m: string | MutationApplied): string;
458
+ /**
459
+ * alpha.78 — does any mutation in the list match `idOrPrefix` (exact id, or
460
+ * prefix when it ends with `*`)? Works on both `mutationsApplied` element
461
+ * shapes. `hasMutation(result.mutationsApplied, 'quality-gate-measured-*')`
462
+ * is the gate-detection idiom PB hand-rolled in their deep-smoke.
463
+ */
464
+ declare function hasMutation(list: ReadonlyArray<string | MutationApplied> | undefined, idOrPrefix: string): boolean;
465
+ /**
466
+ * Target-specific wire request. Shape varies by provider — caller passes the
467
+ * right field to the right SDK.
468
+ */
469
+ type CompiledRequest = {
470
+ provider: 'anthropic';
471
+ model: string;
472
+ system: Array<{
473
+ type: 'text';
474
+ text: string;
475
+ cache_control?: {
476
+ type: 'ephemeral';
477
+ };
478
+ }>;
479
+ messages: Array<{
480
+ role: string;
481
+ content: unknown;
482
+ }>;
483
+ tools?: unknown[];
484
+ max_tokens?: number;
485
+ /**
486
+ * alpha.29 — emitted only when the translator's wire-overrides set
487
+ * `parallelToolCalls = false`. Shape per Anthropic Messages API docs:
488
+ * `{ type: 'auto', disable_parallel_tool_use: true }`. kgauto defaults
489
+ * to omitting `tool_choice` entirely (Anthropic defaults to auto + parallel),
490
+ * so this field's presence signals an explicit override.
491
+ */
492
+ tool_choice?: {
493
+ type: 'auto' | 'any' | 'tool' | 'none';
494
+ disable_parallel_tool_use?: boolean;
495
+ name?: string;
496
+ };
497
+ } | {
498
+ provider: 'google';
499
+ model: string;
500
+ systemInstruction?: {
501
+ role: 'system';
502
+ parts: Array<{
503
+ text: string;
504
+ }>;
505
+ };
506
+ contents: Array<{
507
+ role: string;
508
+ parts: unknown[];
509
+ }>;
510
+ tools?: unknown[];
511
+ generationConfig?: Record<string, unknown>;
512
+ cachedContent?: string;
513
+ } | {
514
+ provider: 'openai';
515
+ model: string;
516
+ messages: Array<{
517
+ role: string;
518
+ content: unknown;
519
+ }>;
520
+ tools?: unknown[];
521
+ response_format?: unknown;
522
+ reasoning_effort?: string;
523
+ /**
524
+ * alpha.29 — emitted only when the translator's wire-overrides set
525
+ * `parallelToolCalls = false`. OpenAI defaults parallel_tool_calls=true
526
+ * server-side; we explicit-set to false only when overriding.
527
+ */
528
+ parallel_tool_calls?: boolean;
529
+ } | {
530
+ provider: 'deepseek';
531
+ model: string;
532
+ messages: Array<{
533
+ role: string;
534
+ content: unknown;
535
+ }>;
536
+ tools?: unknown[];
537
+ } | {
538
+ provider: 'zai';
539
+ model: string;
540
+ messages: Array<{
541
+ role: string;
542
+ content: unknown;
543
+ }>;
544
+ tools?: unknown[];
545
+ response_format?: unknown;
546
+ /**
547
+ * alpha.65 — Z.ai thinking knob (docs.z.ai chat-completion reference):
548
+ * `thinking.type` is 'enabled' (default) or 'disabled'. Emitted only
549
+ * when a cliff forces thinking off (`force_thinking_budget_zero`);
550
+ * omitted otherwise so the provider default applies.
551
+ */
552
+ thinking?: {
553
+ type: 'enabled' | 'disabled';
554
+ };
555
+ } | {
556
+ provider: 'moonshot';
557
+ model: string;
558
+ messages: Array<{
559
+ role: string;
560
+ content: unknown;
561
+ }>;
562
+ tools?: unknown[];
563
+ response_format?: unknown;
564
+ };
565
+ /**
566
+ * Best-practice advisory emitted by the compiler at compile time. Non-fatal —
567
+ * consumers log, surface in dev tools, gate on `level === 'critical'` in CI,
568
+ * or ignore. The advisor inspects the IR + selected profile + diagnostics
569
+ * and emits one entry per detected gap.
570
+ *
571
+ * Codes are stable across releases. `suggestion` and `docsUrl` are optional
572
+ * but encouraged: suggestion = the actionable diff; docsUrl = the
573
+ * interfaces/kgauto.md anchor for context.
574
+ *
575
+ * alpha.6 Phase 1 starter rules:
576
+ * - `caching-off-on-claude` (warn) system >2000 chars on Anthropic, no cacheable=true
577
+ * - `single-chunk-system` (info) Anthropic, only one PromptSection >1000 chars
578
+ * - `tool-bloat` (warn) >10 tools on a short-output archetype
579
+ * - `history-uncached-on-claude` (warn) Anthropic, ≥2 history messages, no historyCachePolicy
580
+ *
581
+ * Phase 2 (catalog as `bestPractices` block in profiles) and Phase 3 (brain
582
+ * telemetry on `advisories_fired`) are alpha.7+ territory.
583
+ */
584
+ interface BestPracticeAdvisory {
585
+ /**
586
+ * Severity. `info` = informational; `warn` = behavioral pattern that's
587
+ * usually expensive or wrong; `critical` = likely bug or production-grade
588
+ * misuse. Phase 1 ships info + warn only.
589
+ */
590
+ level: 'info' | 'warn' | 'critical';
591
+ /** Stable kebab-case code. Consumers filter / gate by this. */
592
+ code: string;
593
+ /** Human-readable explanation of what was detected. */
594
+ message: string;
595
+ /** Optional: how to fix — actionable diff or pattern. */
596
+ suggestion?: string;
597
+ /** Optional: link to docs anchor for more context. */
598
+ docsUrl?: string;
599
+ /**
600
+ * alpha.20 — actionable category for routing/dashboard surfacing. When set,
601
+ * the brain persists this as `recommendation_type` on
602
+ * `compile_outcome_advisories` so consumers can filter "show me all
603
+ * client-side issues that are caching-fix recommendations." Optional;
604
+ * absent on legacy or uncategorized rules.
605
+ *
606
+ * - `'model-swap'` — swap to a different model fixes this
607
+ * - `'prompt-fix'` — restructure prompt (sections, tools, format)
608
+ * - `'caching-fix'` — add cache markers (system or history)
609
+ * - `'no-ai-needed'` — the call shouldn't be using an AI model
610
+ * - `'tier-down'` — current model is overkill for this archetype
611
+ * - `'architecture-change'` — the issue isn't fixable at the kgauto layer
612
+ */
613
+ recommendationType?: 'model-swap' | 'prompt-fix' | 'caching-fix' | 'no-ai-needed' | 'tier-down' | 'architecture-change';
614
+ /**
615
+ * alpha.36 — architectural recommendation when the call shouldn't be an
616
+ * AI call at all, or should be a cheaper non-AI substitute. Optional and
617
+ * orthogonal to {@link recommendationType}: when set, narrows the
618
+ * `no-ai-needed` / `architecture-change` rec-type into an actionable
619
+ * pattern the consumer can implement.
620
+ *
621
+ * - `'lookup-table'` — deterministic input → output mapping (≥95% agreement at high N). Build a domain table; fall back to AI for novel inputs.
622
+ * - `'memoization-cache'` — same canonical input recurs across sessions with equivalent output. Add an edge/KV cache keyed on canonical input.
623
+ * - `'tier-down'` — cheaper model tier delivers equal-or-better oracle score on this shape. Move primary to the cheaper tier.
624
+ * - `'deterministic-parser'` — `constraints.structuredOutput: true` calls where the schema is regex/JSON-extractable from the input.
625
+ * - `'precompute'` — input is derivable at build / cron / batch time; eliminate the per-request call entirely.
626
+ *
627
+ * Operator-side detection lives in `v2/scripts/no-ai-needed-detector.mjs`
628
+ * (alpha.36); a compile-time advisor rule that consumes the brain-side
629
+ * findings cache follows in a later alpha. Today populated only by the
630
+ * operator-side detector + the brain RPC `get_no_ai_needed_candidates`
631
+ * (migration 021).
632
+ */
633
+ recommendedArchitecture?: 'lookup-table' | 'memoization-cache' | 'tier-down' | 'deterministic-parser' | 'precompute';
634
+ /**
635
+ * alpha.28 — when a rule wants to surface a specific structural adaptation
636
+ * (not just a swap or a prompt fix), it attaches the adapter shape here.
637
+ * Shape is the canonical {@link Adapter} discriminated union defined in
638
+ * this module; `compatibility.ts` re-exports it so
639
+ * `getModelCompatibility()` and `BestPracticeAdvisory.suggestedAdaptation`
640
+ * share one source of truth.
641
+ *
642
+ * Today fired by `archetype-perf-floor-breach` (alpha.28) when a
643
+ * documented adapter exists for the chosen model's archetype cliff.
644
+ * Absent on rules without a structural adapter (caching-off-on-claude,
645
+ * tool-bloat, etc.) and on the `reject` branch of
646
+ * `archetype-perf-floor-breach` where no adapter would help.
647
+ *
648
+ * CLOSED discriminated union (R3 from consultation doc) — future adapter
649
+ * parameters extend the union in `compatibility.ts` in named alpha
650
+ * releases. No `| string` escape hatch; consumer code can write
651
+ * exhaustive `switch (suggestedAdaptation.parameter)`.
652
+ *
653
+ * Phase 2 cross-builder coherence: Builder A's
654
+ * `AdvisoryRecord.suggestedAdaptation` (in `glassbox-routes/types.ts`)
655
+ * MUST type to the same union. Phase 2 integration verifies.
656
+ */
657
+ suggestedAdaptation?: Adapter;
658
+ /**
659
+ * alpha.42 — the kgauto request handle that produced this advisory. Stamped
660
+ * by `compile()` after `runAdvisor()` returns, sourced from
661
+ * `CompileResult.handle`. Lets a consumer's admin UI pivot from advisory
662
+ * row → original trace (Glass-Box card, brain `compile_outcomes` lookup).
663
+ *
664
+ * Absent when the advisory was constructed outside the full `compile()`
665
+ * pipeline (e.g., a direct `runAdvisor()` call in tests). Always present
666
+ * on advisories returned from `compile().advisories`.
667
+ */
668
+ kgautoRequestId?: string;
669
+ /**
670
+ * alpha.42 — who is positioned to act on this advisory.
671
+ *
672
+ * - `'consumer-actionable'` (Class A): the consumer can fix this by
673
+ * changing their wire-up — add `cacheable: true` markers, swap their
674
+ * model literal, declare a section, etc. The admin UI should surface
675
+ * a one-click apply or a "fix it" CTA.
676
+ * - `'producer-owned'` (Class B): kgauto needs to ship a code or data
677
+ * change — update a profile, promote a model in the chain, fix a
678
+ * wire contract. The admin UI should surface this as informational
679
+ * ("kgauto is on it") and not present a consumer-side action.
680
+ *
681
+ * Stamped by `compile()` after `runAdvisor()` returns. Rules can self-
682
+ * declare via the matching field on their return; otherwise the stamp
683
+ * consults the static `PRODUCER_OWNED_RULE_CODES` set in `advisor.ts`,
684
+ * defaulting to `'consumer-actionable'` when the code isn't listed.
685
+ *
686
+ * Closes the s47 dogfood gap where the tt-intel admin UI conflated the
687
+ * two classes — consumers couldn't tell whether they should act or wait.
688
+ */
689
+ ownership?: 'consumer-actionable' | 'producer-owned';
690
+ }
691
+ /**
692
+ * alpha.28 — adapter shape attached to advisories and returned by
693
+ * `getModelCompatibility()`. A CLOSED discriminated union: future adapter
694
+ * parameters extend it explicitly in named alpha releases. NO `| string`
695
+ * escape hatch — consumer policy code SHOULD write exhaustive
696
+ * `switch (adapter.parameter)` and rely on the compiler to flag
697
+ * "I added a new adapter parameter and forgot to update consumer policy."
698
+ *
699
+ * Defined here (in `ir.ts`, the foundational types module) and re-exported
700
+ * from `compatibility.ts` for ergonomic consumer imports. Anchoring it
701
+ * here avoids the import cycle that would form if both files tried to be
702
+ * the source of truth (ir.ts → compatibility.ts → profiles.ts → ir.ts).
703
+ *
704
+ * alpha.28 variants:
705
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
706
+ * Lifts DeepSeek V4-family on `hunt` from the sequential-tool cliff
707
+ * (L-040). `consequence` is consumer-renderable plain English.
708
+ *
709
+ * Future alpha releases will add e.g. `parallelToolCalls`, `maxTools`,
710
+ * `thinkingBudget` (per tt-intel-Cairn priority list).
711
+ */
712
+ type Adapter = {
713
+ parameter: 'toolOrchestration';
714
+ value: 'sequential';
715
+ consequence: string;
716
+ };
717
+ /**
718
+ * alpha.29+ — record of a single section rewrite fired by the translator at
719
+ * compile time. Surfaces on `CompileResult.sectionRewritesApplied` and (in
720
+ * scrubbed wire form, without original/transformed text) on
721
+ * `TraceDetail.sectionRewritesApplied` for Glass-Box Coaching-card rendering.
722
+ *
723
+ * `originalText` / `transformedText` stay package-internal — they may carry
724
+ * consumer PII. The wire-shape variant (`TraceSectionRewrite` in
725
+ * `glassbox-routes/types.ts`) carries only `summary` for renderer use.
726
+ */
727
+ interface SectionRewrite {
728
+ /** Stable id of the `PromptSection` that was rewritten. */
729
+ sectionId: string;
730
+ /** The `kind` discriminator that matched the rewrite rule. */
731
+ kind: SectionKind;
732
+ /**
733
+ * Stable identifier of the rule that fired (e.g.
734
+ * `'sequential-tool-cliff-below-floor'`). Future rules add named ids; the
735
+ * brain aggregates by this value for cross-app learning.
736
+ */
737
+ rule: string;
738
+ /** The section's text BEFORE the rewrite fired. */
739
+ originalText: string;
740
+ /** The text the translator emitted into the IR for this section. */
741
+ transformedText: string;
742
+ /**
743
+ * Wire-level overrides emitted alongside the text rewrite. Merged into
744
+ * `CompileResult.wireOverrides` by `applySectionRewrites`. alpha.29 ships
745
+ * `parallelToolCalls`; the union extends as more wire-overrides surface.
746
+ */
747
+ wireOverrides?: {
748
+ parallelToolCalls?: boolean;
749
+ };
750
+ }
751
+ interface CompileResult {
752
+ /** Unique handle for this call — pass to record() to correlate the outcome. */
753
+ handle: string;
754
+ /** Selected target model id. */
755
+ target: string;
756
+ /** Selected provider. */
757
+ provider: Provider;
758
+ /** The wire request — pass the appropriate fields to your SDK. */
759
+ request: CompiledRequest;
760
+ /** Estimated tokens (input). */
761
+ tokensIn: number;
762
+ /** Estimated cost in USD (input portion). */
763
+ estimatedCostUsd: number;
764
+ /** Mutations that fired during compile (informational). */
765
+ mutationsApplied: MutationApplied[];
766
+ /** Fallback chain — try these in order if target fails. */
767
+ fallbackChain: string[];
768
+ /**
769
+ * Best-practice advisories emitted by the compiler. Non-fatal. Empty
770
+ * array when no rules fired. alpha.6 Phase 1.
771
+ */
772
+ advisories: BestPracticeAdvisory[];
773
+ /**
774
+ * alpha.29+ — per-section rewrites applied by the translator at compile
775
+ * time. Empty array means no rewrites fired (or pre-alpha.29 behavior —
776
+ * all sections default `kind: 'arbitrary'`, which is pass-through).
777
+ *
778
+ * Surfaces to:
779
+ * - Glass-Box Coaching card (via `TraceDetail.sectionRewritesApplied`,
780
+ * scrubbed of original/transformed text)
781
+ * - brain `compile_outcomes.section_rewrites_applied` (migration 019)
782
+ * for cross-app learning
783
+ */
784
+ sectionRewritesApplied: SectionRewrite[];
785
+ /**
786
+ * alpha.29+ — wire-level overrides emitted by translator rewrites. The
787
+ * provider lowering pass threads these through to the wire request before
788
+ * emit. Today only `parallelToolCalls: boolean`; the type extends as more
789
+ * wire-overrides surface.
790
+ *
791
+ * Undefined when no rewrite emitted overrides — the common case.
792
+ */
793
+ wireOverrides?: {
794
+ parallelToolCalls?: boolean;
795
+ };
796
+ /** Diagnostics for caller-side logging. */
797
+ diagnostics: {
798
+ sectionsKept: number;
799
+ sectionsDropped: number;
800
+ toolsKept: number;
801
+ toolsDropped: number;
802
+ historyKept: number;
803
+ historyDropped: number;
804
+ cacheableTokens: number;
805
+ estimatedCacheSavingsUsd: number;
806
+ /**
807
+ * Tokens in `history` (and `currentTurn` when before the marker) that
808
+ * fall within the cacheable prefix per `historyCachePolicy`. Always
809
+ * computed; only Anthropic actually emits a wire-format marker. For
810
+ * Gemini / OpenAI / DeepSeek, this represents the theoretical cacheable
811
+ * prefix that implicit caching may pick up — useful telemetry for the
812
+ * brain to learn which (app, model, archetype) tuples benefit most
813
+ * from history caching. alpha.5.
814
+ */
815
+ historyCacheableTokens: number;
816
+ /**
817
+ * Total tokens in input `history` (pre-compression). Computed regardless
818
+ * of whether `passCompressHistory` fired — surfaces how close a tuple is
819
+ * to its `compressHistoryAboveTokens` threshold so dashboards / cost-
820
+ * watchers can see the bloat axis the count-based threshold misses.
821
+ * 0 when history is empty. alpha.7.
822
+ */
823
+ historyTokensTotal: number;
824
+ /**
825
+ * alpha.20 E3. Consumer-declared tool-orchestration mode for this call,
826
+ * mirrored from `ir.constraints.toolOrchestration` for downstream
827
+ * observability (Glass-Box panel, brain telemetry, advisor logs).
828
+ * Undefined when the consumer hadn't adopted the constraint yet —
829
+ * treat as 'parallel' equivalent for back-compat.
830
+ */
831
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
832
+ /**
833
+ * alpha.33. Zero-based index into the resolved (post-compression) history
834
+ * array at which Anthropic prompt-cache marker should land — i.e., the
835
+ * last message that belongs to the stable cacheable prefix. Consumers
836
+ * using AI-SDK's `streamText({ messages: convertToModelMessages(...) })`
837
+ * lose the per-message `providerOptions.anthropic.cacheControl` markers
838
+ * the compiler emits on `result.request.messages`, because
839
+ * `convertToModelMessages` reads raw input not the lowered output.
840
+ * This index gives the consumer a single deterministic position to
841
+ * attach `cacheControl: { type: 'ephemeral' }` after their own conversion.
842
+ *
843
+ * Computation:
844
+ * - `historyCachePolicy.strategy === 'all-but-latest'`: history.length - 1
845
+ * (or undefined if history is empty)
846
+ * - `historyCachePolicy.strategy === 'fixed-suffix'` with `suffix: N`:
847
+ * history.length - 1 - N (undefined if N exceeds history length)
848
+ * - `historyCachePolicy.strategy === 'none'` or omitted: undefined
849
+ *
850
+ * The companion helper `attachCacheControlToStreamTextInput()` reads
851
+ * this field + the consumer's converted messages to perform the per-
852
+ * attempt mutation correctly. Filed by IC + tt-intel cross-consumer
853
+ * pattern 2026-05-20 (`streamText-cache-marker-propagation-gap`).
854
+ */
855
+ historyCacheMarkIndex?: number;
856
+ /**
857
+ * alpha.33. Zero-based index into the structured `systemMessages` array
858
+ * (see top-level `systemMessages` field) at which the cacheable system
859
+ * prefix ends. Useful when the consumer is building a multi-block
860
+ * system parameter for Anthropic streamText — they can attach
861
+ * `providerOptions.anthropic.cacheControl` to `systemMessages[index]`.
862
+ *
863
+ * Undefined when no section had `cacheable: true` OR `systemMessages` is
864
+ * empty. Matches `historyCacheMarkIndex` semantics on the history axis.
865
+ */
866
+ systemCacheMarkIndex?: number;
867
+ /**
868
+ * alpha.43. Cliff-style warnings surfaced by the convention pass
869
+ * (`passApplyConventions`) when the selected profile + archetype carry
870
+ * a `cliffWarning` whose preconditions are met. These are informational
871
+ * — they describe a structural mismatch between the call's shape and
872
+ * the chosen family (e.g. "reasoner family is wrong for parallel-tool
873
+ * hunt") so consumers can route differently next time.
874
+ *
875
+ * Empty array when no convention fired or no warnings surfaced.
876
+ * Separate from `cliff_guard` mutations in `mutationsApplied` — those
877
+ * are profile.cliffs[] runtime triggers; these are convention-level
878
+ * advisory text. Both can fire on the same call.
879
+ */
880
+ cliffWarnings: string[];
881
+ /**
882
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.D) — tokens added
883
+ * by the `discipline_contract` gate block on this call; 0 when the gate
884
+ * didn't fire (no eligible `discipline_contract` section, or Factor A /
885
+ * Factor C screened it out). Measured, never assumed: counted from the
886
+ * exact frozen preamble the translator prepended. Persisted to
887
+ * `compile_outcomes.discipline_gate_tokens` (migration 042) so the tax is a
888
+ * number the cost-watcher can weigh against the lift.
889
+ */
890
+ disciplineGateTokens: number;
891
+ };
892
+ /**
893
+ * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
894
+ * consumers. When the consumer's lowered request has cacheable section
895
+ * markers, the flat `system: string` form loses the marker assignment
896
+ * (every `streamText({ system: '<string>' })` call silently strips
897
+ * providerOptions). Pass `systemMessages` instead to `streamText({
898
+ * system: result.systemMessages })` so the cacheable prefix is structurally
899
+ * preserved.
900
+ *
901
+ * Each entry is a `SystemModelMessage`-shaped object:
902
+ * { role: 'system', content: string, providerOptions?: { anthropic?:
903
+ * { cacheControl: { type: 'ephemeral' } } } }
904
+ *
905
+ * Provider-agnostic on emit: only Anthropic actually consumes the
906
+ * cacheControl block; Gemini / OpenAI / DeepSeek receive the same
907
+ * shape but ignore the marker (matching their implicit-caching semantics).
908
+ *
909
+ * Empty array when the IR carried zero sections (rare; usually means the
910
+ * compiler dropped everything for the chosen intent). Consumers can fall
911
+ * back to `result.systemMessages.length === 0 ? '' : result.systemMessages`
912
+ * or use the helper `attachCacheControlToStreamTextInput()` which handles
913
+ * both shapes.
914
+ */
915
+ systemMessages: SystemModelMessage[];
916
+ }
917
+ /**
918
+ * alpha.33. AI-SDK-compatible system-message shape carried on
919
+ * `CompileResult.systemMessages`. Matches the AI-SDK `streamText({ system })`
920
+ * structured form — consumers can pass these directly without conversion.
921
+ *
922
+ * The `providerOptions` field is set ONLY for entries that came from a
923
+ * section with `cacheable: true` AND the chosen provider is Anthropic AND
924
+ * the compiler computed a non-zero `cacheableTokens`. Other providers see
925
+ * `providerOptions: undefined` (or omitted entirely).
926
+ */
927
+ interface SystemModelMessage {
928
+ role: 'system';
929
+ content: string;
930
+ providerOptions?: {
931
+ anthropic?: {
932
+ cacheControl: {
933
+ type: 'ephemeral';
934
+ };
935
+ };
936
+ };
937
+ }
938
+ /**
939
+ * Token usage normalized across providers. `cached` and `cacheCreated` are
940
+ * Anthropic prompt-cache reads/writes (Gemini implicit caching populates
941
+ * `cached` from `usageMetadata.cachedContentTokenCount`; OpenAI populates
942
+ * from `prompt_tokens_details.cached_tokens`).
943
+ */
944
+ interface NormalizedTokens {
945
+ input: number;
946
+ output: number;
947
+ total: number;
948
+ cached?: number;
949
+ cacheCreated?: number;
950
+ }
951
+ /**
952
+ * Tool call in a provider-agnostic shape. Anthropic `tool_use` blocks,
953
+ * Google `functionCall` parts, and OpenAI/DeepSeek `tool_calls[]` all
954
+ * collapse to this.
955
+ */
956
+ interface ToolCall {
957
+ id: string;
958
+ name: string;
959
+ args: Record<string, unknown>;
960
+ }
961
+ interface NormalizedResponse {
962
+ /** Main text body. Empty string if response had no text content. */
963
+ text: string;
964
+ /**
965
+ * Parsed structured output. Populated when ir.constraints.structuredOutput
966
+ * is true and JSON.parse(text) succeeds. Null otherwise.
967
+ */
968
+ structuredOutput: unknown | null;
969
+ /** Tool calls in normalized shape. Empty array if none. */
970
+ toolCalls: ToolCall[];
971
+ tokens: NormalizedTokens;
972
+ /** Provider-specific finish reason, passed through unchanged. */
973
+ finishReason?: string;
974
+ /** Untouched provider response — escape hatch for consumers needing fields not yet normalized. */
975
+ raw: unknown;
976
+ /** Set when structuredOutput parsing was attempted and failed. */
977
+ parseError?: string;
978
+ }
979
+ interface ApiKeys {
980
+ anthropic?: string;
981
+ google?: string;
982
+ openai?: string;
983
+ deepseek?: string;
984
+ zai?: string;
985
+ moonshot?: string;
986
+ }
987
+ /**
988
+ * Per-provider override fields shallow-merged into the lowered request before
989
+ * execution. Lets consumers reach Gemini `safetySettings`, Anthropic
990
+ * `tool_choice`, OpenAI `seed` etc. without bypassing kgauto.
991
+ */
992
+ interface ProviderOverrides {
993
+ anthropic?: Record<string, unknown>;
994
+ google?: Record<string, unknown>;
995
+ openai?: Record<string, unknown>;
996
+ deepseek?: Record<string, unknown>;
997
+ zai?: Record<string, unknown>;
998
+ moonshot?: Record<string, unknown>;
999
+ }
1000
+ /**
1001
+ * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
1002
+ *
1003
+ * When set on `call()`, after the primary response is served kgauto re-lowers
1004
+ * the SAME in-memory PromptIR to each candidate and runs it, persisting a
1005
+ * `probe_outcomes` row with `replay_source='inline-full-ir'` and
1006
+ * `prompt_fidelity=1.0` — a fair, full-prompt measurement (vs the watchers'
1007
+ * lossy `prompt_preview` replay). The probe NEVER blocks the user response and
1008
+ * NEVER persists the raw prompt (system/context/payload) — only response
1009
+ * previews + metadata, same policy the brain already holds.
1010
+ *
1011
+ * This is the trustworthy path that earns the right to a quality verdict;
1012
+ * `prompt_preview` replay is retired for verdicts (see CLAUDE.md).
1013
+ *
1014
+ * Phase 1 enforces `sampleRate` and runs the candidate with `judge: 'off'`
1015
+ * (responses stored for an offline batch judge). `judge: 'opus'` (inline
1016
+ * verdict) and `maxPerDay` (per-tuple daily cap, needs a brain-count read)
1017
+ * are accepted by the type but ENFORCED IN PHASE 2.
1018
+ */
1019
+ interface ShadowProbeConfig {
1020
+ /** Model id(s) or family alias(es) to shadow-test against the served model, on the same IR. */
1021
+ candidates: string | string[];
1022
+ /** Probability [0,1] that any given call fires a probe. Default 0.05. */
1023
+ sampleRate?: number;
1024
+ /**
1025
+ * 'off' (Phase 1 default): run candidate + store both responses for an
1026
+ * offline batch judge. 'opus': judge candidate-vs-served inline (Phase 2).
1027
+ */
1028
+ judge?: 'opus' | 'off';
1029
+ /** Per-(appId, archetype, candidate) daily cap. Phase 2 (needs brain-count read). Default 20. */
1030
+ maxPerDay?: number;
1031
+ /**
1032
+ * alpha — latency budget (ms) for the probe leg. **Only enforced in sync mode**
1033
+ * (`BrainConfig.sync === true`), where `call()` awaits the probe before returning
1034
+ * the served response (PB-class Edge consumers, L-086) and the candidate's
1035
+ * latency therefore lands on the user-facing critical path.
1036
+ *
1037
+ * The probe path races against this budget: if the candidate(s) don't finish
1038
+ * within `maxLatencyMs`, the probe aborts, `call()` returns the already-served
1039
+ * response immediately, and an `outcome='aborted_latency_budget'` row is
1040
+ * recorded (no verdict, no false quality data). **The user is never delayed
1041
+ * past the budget.** Default `15000`.
1042
+ *
1043
+ * No-op for fire-and-forget consumers (`sync` unset/false, and every
1044
+ * `probeShadow()` caller fired from `after()`/`waitUntil()`) — they don't block
1045
+ * the user, so there's no latency to bound. The probe runs to completion there.
1046
+ *
1047
+ * Root cause this closes (PB s57 dogfood incident, 2026-06-05): PB arms the
1048
+ * probe inline with `sync:true` on a `maxDuration:120` analyze route; arming a
1049
+ * `latency_tier='slow'` candidate (deepseek-v4-pro, ~78–84s) pushed total
1050
+ * handler time past the frontend's patience and the served analysis came back
1051
+ * empty. A sync probe had no latency budget — this field is the budget.
1052
+ */
1053
+ maxLatencyMs?: number;
1054
+ /**
1055
+ * alpha — when true (the default) **in sync mode**, skip a candidate whose
1056
+ * registry `latency_tier === 'slow'` *before starting it*: a slow-tier model
1057
+ * (e.g. deepseek-v4-pro / deepseek-v4-flash, both `slow` = ~24s+ p50) cannot
1058
+ * fit a sane inline budget, so starting it just to abort it wastes a provider
1059
+ * call. An `outcome='skipped_slow_tier_sync'` row is recorded so the offline
1060
+ * rollup can see the skip (not a silent drop, not a false verdict). Fail-safe.
1061
+ *
1062
+ * **The deeper rule (slow-reasoner → offline-mode):** inline shadow-probing is
1063
+ * for FAST candidates only. To evaluate a slow reasoner you need the offline /
1064
+ * async probe path (the Phase-2 batch direction) which runs off the response
1065
+ * entirely — never the inline sync probe. Set this `false` only if you've moved
1066
+ * the budget high enough that a slow candidate genuinely fits (rare), or you're
1067
+ * in a non-sync consumer where this flag is a no-op anyway.
1068
+ *
1069
+ * No-op for fire-and-forget consumers (`sync` unset/false; `probeShadow()`):
1070
+ * there's no user latency to protect, so slow candidates run normally. Default
1071
+ * `true`.
1072
+ */
1073
+ skipSlowTierInSync?: boolean;
1074
+ }
1075
+ interface CallOptions {
1076
+ /** Forwarded to compile(). */
1077
+ policy?: CompilePolicy;
1078
+ /**
1079
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage).
1080
+ * When set, this call is a fan-out BRANCH of the parent trace: the outcome
1081
+ * row records `fanout_role='branch'`, `parent_handle=<this value>`, and
1082
+ * `trace_id` inherits the parent handle (the trace root). Absent ⇒ this is a
1083
+ * root (user-facing) call: `fanout_role='root'`, `trace_id=<own handle>`.
1084
+ * Pass the parent's `CallResult.handle` / `CompileResult.handle`.
1085
+ *
1086
+ * Release A supports 1-level linkage (root → branch); deeper trees await the
1087
+ * `delegate` primitive in Release D. Labelling only — NOT a routing change.
1088
+ */
1089
+ parentHandle?: string;
1090
+ /**
1091
+ * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
1092
+ * measures the candidate(s) on the same IR after serving the primary,
1093
+ * fire-and-forget. See {@link ShadowProbeConfig}.
1094
+ */
1095
+ shadowProbe?: ShadowProbeConfig;
1096
+ /**
1097
+ * alpha.73 — how long `call()` may wait for the measured-failure gate's
1098
+ * first brain read before compiling, in ms. Default 400.
1099
+ *
1100
+ * Exists because `compile()` is synchronous and therefore reads only what
1101
+ * the SWR cache already holds: on a cold isolate that is nothing, so the
1102
+ * gate silently does not fire on the first compile — measured on
1103
+ * playbacksam as two billed inferences and ~27–34s of added latency, every
1104
+ * time an isolate is new. Low-traffic consumers are cold most of the time,
1105
+ * so this hits them hardest, inverting the usual severity ordering.
1106
+ *
1107
+ * The wait is bounded and never required: on timeout, brain-down, or no
1108
+ * brain configured, the call proceeds un-gated exactly as before. Set `0`
1109
+ * to disable the wait entirely (the background prefetch still runs, so
1110
+ * later calls in the same isolate are gated either way).
1111
+ */
1112
+ gateWarmupMs?: number;
1113
+ /**
1114
+ * alpha.78 — per-ATTEMPT time bound on the provider leg, in ms
1115
+ * (IC `per-call-timeout-on-call-options` + the portfolio-wide
1116
+ * unbounded-LLM-call scan). Without it the only ceiling is the serverless
1117
+ * route's `maxDuration`, and one hung socket eats the entire route budget
1118
+ * before the fallback chain — the product's whole promise — can walk.
1119
+ *
1120
+ * Semantics per attempt shape:
1121
+ * - non-streaming: total bound via `AbortSignal.timeout()`; firing
1122
+ * classifies retryable `timeout` (L-061) so the chain WALKS.
1123
+ * - streaming: per-chunk STALL bound (max silence between bytes,
1124
+ * covering time-to-first-byte) — a total bound would cut legitimate
1125
+ * long streams. Also classifies `timeout` on fire.
1126
+ *
1127
+ * Each wire attempt (including the same-model retry) gets a fresh budget.
1128
+ * Default: none — today's unbounded behavior, additive and opt-in; a
1129
+ * consumer-side bounds scan (tt-intel s114 shape) can then require it
1130
+ * mechanically. A hang recorded before this existed reads as model
1131
+ * latency in brain telemetry — transport stalls were indistinguishable
1132
+ * from slow models.
1133
+ */
1134
+ attemptTimeoutMs?: number;
1135
+ /**
1136
+ * alpha.78 — caller-owned cancellation (route-level deadline propagation).
1137
+ * Composed per-attempt with `attemptTimeoutMs` via `AbortSignal.any`.
1138
+ * Aborting classifies terminal `aborted` and stops the WHOLE chain walk —
1139
+ * the caller cancelled, so walking would spend money on an answer nobody
1140
+ * is waiting for. Distinct from a timeout, which walks.
1141
+ */
1142
+ abortSignal?: AbortSignal;
1143
+ toolRelevanceThreshold?: number;
1144
+ compressHistoryAfter?: number;
1145
+ /** Override API keys (defaults: process.env). */
1146
+ apiKeys?: ApiKeys;
1147
+ /** Provider-specific request fields shallow-merged into the lowered request. */
1148
+ providerOverrides?: ProviderOverrides;
1149
+ /** Override fetch (for tests). */
1150
+ fetchImpl?: typeof fetch;
1151
+ /** Disable retry/fallback walk on retryable errors. Default: enabled. */
1152
+ noFallback?: boolean;
1153
+ /**
1154
+ * alpha.10. Disable the silent auto-filter of unreachable models from the
1155
+ * fallback walk. Default: false (filter ON). Opt-out exists for tests +
1156
+ * the rare consumer that wants the legacy "fail at execute() with auth
1157
+ * error" behavior. When ON (default), models whose provider has no
1158
+ * resolvable API key are dropped from `targetsToTry` before the first
1159
+ * network call; if the chain empties entirely, throws CallError with
1160
+ * `lastErrorCode = 'no_reachable_models'`.
1161
+ *
1162
+ * Reachability source: `apiKeys` (this CallOptions) + `process.env` (via
1163
+ * `PROVIDER_ENV_KEYS`). Override env via env.ts's `ReachabilityOpts.envSource`
1164
+ * is not exposed here — `call()` always uses process.env. Use
1165
+ * `getDefaultFallbackChain({ reachability: { envSource } })` upstream
1166
+ * for hermetic test runs.
1167
+ */
1168
+ noAutoFilter?: boolean;
1169
+ /**
1170
+ * alpha.34. When provided AND the chosen provider supports streaming
1171
+ * (`profile.streaming === true`) AND `noStream` is not set, kgauto
1172
+ * enables provider-native SSE streaming at the wire layer and invokes
1173
+ * `onChunk(delta)` once per provider stream event. `delta` is the text
1174
+ * since the previous `onChunk` call (NOT cumulative) — provider
1175
+ * stream-shape headache normalized in kgauto's lowering layer.
1176
+ *
1177
+ * `CallResult.response.text` is still populated with the full assembled
1178
+ * response — kgauto buffers internally regardless of the callback.
1179
+ * Consumers can use either the streaming side-effect OR the final
1180
+ * `response.text`, doesn't matter.
1181
+ *
1182
+ * Tool calls + finish reason + usage are collected from stream events
1183
+ * and returned in the final `CallResult` exactly as the non-streaming
1184
+ * path would shape them. Brain telemetry latency = time-to-stream-end.
1185
+ *
1186
+ * Chain-walk semantics: if the streaming target fails mid-stream
1187
+ * (network error, retryable provider error), kgauto walks to the next
1188
+ * fallback target and restarts streaming from its first chunk —
1189
+ * `onChunk` fires fresh from the new target. Consumer detects via the
1190
+ * post-call `CallResult.fellOverFrom`. To opt out of fallback for
1191
+ * streaming, set `noFallback: true` alongside `onChunk`.
1192
+ *
1193
+ * Filed by playbacksam s42 (2026-05-22) as `streaming-output-callback-
1194
+ * on-callresult` for ComposeDrawer SSE; perceived-latency UX win
1195
+ * during 10-30s draft assembly.
1196
+ */
1197
+ onChunk?: (chunk: string) => void;
1198
+ /**
1199
+ * alpha.34. Explicit opt-out of streaming even when `onChunk` is
1200
+ * provided. Default: false (streaming enabled when `onChunk` is set).
1201
+ * Use when the consumer wants to pass `onChunk` conditionally without
1202
+ * branching the call site (e.g., capture chunks for instrumentation
1203
+ * without engaging streaming wire format).
1204
+ */
1205
+ noStream?: boolean;
1206
+ /**
1207
+ * alpha.62 (eval spine) — golden-set capture. When the resolved sample rate
1208
+ * is > 0, a successful non-empty call's FULL PromptIR + served output is
1209
+ * stored to the brain's `kgauto_golden_irs` replay corpus (raw prompt —
1210
+ * explicit opt-in; see golden.ts consent posture). `sampleRate` here
1211
+ * overrides the `KGAUTO_GOLDEN_CAPTURE` env var; when neither is set,
1212
+ * capture never fires.
1213
+ */
1214
+ goldenCapture?: GoldenCaptureOptions;
1215
+ /**
1216
+ * alpha.66 — one same-model retry on a structured-output contract violation
1217
+ * (`max_tokens_on_structured_output` / `structured_output_parse_failed`)
1218
+ * BEFORE chain-walking to a lower-ranked tier. Filed by playbacksam
1219
+ * 2026-07-18 (`structured-output-truncation-retry-same-model`): on PB's
1220
+ * summarize surface the walk destination is measured quality-inferior
1221
+ * (golden eval run #3), so one more attempt at the leader beats walking.
1222
+ *
1223
+ * Consent posture (matches KGAUTO_AUTO_PROMOTE / KGAUTO_GOLDEN_CAPTURE):
1224
+ * default OFF; `true` wins, explicit `false` beats the env, undefined
1225
+ * falls through to the `KGAUTO_SAME_MODEL_RETRY` env var ('1'/'true').
1226
+ * Default-off because the retry adds one full model round-trip of latency
1227
+ * in the failure class — the consumer decides whether their fallback tier
1228
+ * is bad enough to pay that.
1229
+ *
1230
+ * Bounds: at most ONE retry per call(), on whichever target hits the
1231
+ * contract violation first. Truncation-class retries additionally raise
1232
+ * any explicit wire output cap sitting below the profile's
1233
+ * `maxOutputTokens` (e.g. a terse-clamp or providerOverrides cap);
1234
+ * requests already at the profile ceiling re-roll unchanged.
1235
+ */
1236
+ sameModelRetry?: boolean;
1237
+ }
1238
+ interface CallAttempt {
1239
+ model: string;
1240
+ status: 'success' | 'retryable' | 'terminal';
1241
+ errorCode?: string;
1242
+ message?: string;
1243
+ /**
1244
+ * alpha.66 — true on the attempt row that was the one-shot same-model
1245
+ * retry (CallOptions.sameModelRetry). The preceding row for the same model
1246
+ * carries the contract violation that triggered it.
1247
+ */
1248
+ sameModelRetry?: boolean;
1249
+ }
1250
+ /**
1251
+ * Why fallback fired. Normalized for `CallResult.fallbackReason` (alpha.9).
1252
+ *
1253
+ * - `rate_limit` provider returned 429
1254
+ * - `provider_error` 5xx, network, or other retryable upstream issue
1255
+ * - `cost_cap` preflight policy.maxCostPerCallUsd rejected target
1256
+ * - `cliff` alpha.8 contract violation (MAX_TOKENS on
1257
+ * structured output, parse-failed JSON)
1258
+ * - `contract_violation` other compile-time-contract failures (reserved
1259
+ * for alpha.10+ — e.g. mid-stream policy rejects)
1260
+ * - `provider_auth_failed` alpha.14 — initial provider returned 401/403
1261
+ * (upstream key revocation, malformed-but-truthy
1262
+ * key). The chain walks to the next
1263
+ * non-same-provider target instead of
1264
+ * short-circuiting; same-provider remaining
1265
+ * entries skip with errorCode='auth_inferred'.
1266
+ * - `provider_billing_exhausted` alpha.77 — the provider's ACCOUNT is out
1267
+ * of credits (Anthropic "credit balance is too
1268
+ * low" 400, OpenAI insufficient_quota 429,
1269
+ * Google billing-disabled, DeepSeek 402). Walks
1270
+ * like auth and skips same-provider siblings
1271
+ * (errorCode='billing_exhausted_inferred').
1272
+ * Distinct from auth AND from rate_limit because
1273
+ * its disposition is distinct: it never clears
1274
+ * on its own — a human funds the account.
1275
+ */
1276
+ type FallbackReason = 'rate_limit' | 'provider_error' | 'cost_cap' | 'cliff' | 'contract_violation' | 'provider_auth_failed' | 'provider_billing_exhausted';
1277
+ interface CallResult {
1278
+ /** Compile handle (still valid for record() if consumer wants to add oracle scores later). */
1279
+ handle: string;
1280
+ /** The model that ACTUALLY served the response (post-fallback). */
1281
+ actualModel: string;
1282
+ /** What compile() originally targeted. */
1283
+ requestedModel: string;
1284
+ provider: Provider;
1285
+ response: NormalizedResponse;
1286
+ latencyMs: number;
1287
+ /** Mutations that fired during compile (informational, mirrors CompileResult.mutationsApplied). */
1288
+ mutationsApplied: MutationApplied[];
1289
+ /** One entry per provider attempt — observability for retry/fallback walks. */
1290
+ attempts: CallAttempt[];
1291
+ /**
1292
+ * Alpha.9 normalization of fallback-walk telemetry. When the chain
1293
+ * succeeded on the first attempt, these collapse to:
1294
+ * - `servedBy === requestedModel`
1295
+ * - `fellOverFrom` undefined
1296
+ * - `fallbackReason` undefined
1297
+ *
1298
+ * When fallback fired:
1299
+ * - `servedBy` = `actualModel` (the model that produced the response)
1300
+ * - `fellOverFrom` = `requestedModel` (what the caller / compile() asked for)
1301
+ * - `fallbackReason` = normalized cause derived from the first
1302
+ * non-success attempt's `errorCode`
1303
+ *
1304
+ * Consumer UX use: show "Claude was busy; we used Pro for this answer"
1305
+ * when `fellOverFrom` is set (master plan §3.6).
1306
+ */
1307
+ /** Model that actually answered. Equal to `actualModel`; kept distinct for clarity. */
1308
+ servedBy: string;
1309
+ /** Set only when fallback fired. Equal to `requestedModel` in that case. */
1310
+ fellOverFrom?: string;
1311
+ /** Set only when fallback fired. Normalized cause. */
1312
+ fallbackReason?: FallbackReason;
1313
+ /**
1314
+ * alpha.71 — the PRECISE `errorCode` of the attempt that drove the chain,
1315
+ * unnormalized. `fallbackReason` is a six-value summary and one of its
1316
+ * values, `'cliff'`, absorbs two failures with OPPOSITE remedies:
1317
+ *
1318
+ * - `max_tokens_on_structured_output` — the output budget was too small
1319
+ * for the requested shape ⇒ raise the cap / add an output-budget cliff.
1320
+ * - `structured_output_parse_failed` — the model emitted non-JSON ⇒ its
1321
+ * declared `structuredOutput` capability is wrong for this shape.
1322
+ *
1323
+ * The code was already computed in `attempts[]` and thrown away at record
1324
+ * time, so a surface could accumulate a dozen identical `'cliff'` rows that
1325
+ * still could not tell an operator which fix applies. (Found diagnosing
1326
+ * claude-haiku-4-5's 12-of-12 failures on playbacksam/summarize, where the
1327
+ * measured-failure gate correctly stopped the bleeding but the evidence
1328
+ * could not name the cause.)
1329
+ */
1330
+ fellOverErrorCode?: string;
1331
+ /**
1332
+ * alpha.66 — true when the one-shot same-model retry
1333
+ * (CallOptions.sameModelRetry) fired during this call, regardless of
1334
+ * whether the retry rescued the call or the chain walked afterwards.
1335
+ * Cross-check `attempts[]` (the `sameModelRetry: true` row) and
1336
+ * `fellOverFrom` to distinguish rescued-by-retry from retried-then-walked.
1337
+ */
1338
+ retriedSameModel?: boolean;
1339
+ /**
1340
+ * alpha.10. Models that auto-filter dropped from the fallback walk because
1341
+ * their provider had no reachable API key. Empty when nothing was filtered
1342
+ * (the common case once consumers have all the keys they need). Surfaces
1343
+ * silent self-heal so consumers can log/audit what happened without
1344
+ * defeating the "kgauto just gets" UX.
1345
+ *
1346
+ * Empty array (not undefined) when filter ran but dropped nothing —
1347
+ * distinguishes "filter ran cleanly" from "filter was disabled" (`undefined`
1348
+ * when `noAutoFilter: true`).
1349
+ */
1350
+ unreachableFiltered?: string[];
1351
+ /**
1352
+ * alpha.16. Models that policy.blockedModels filtering dropped from the
1353
+ * fallback walk. Defense-in-depth at the call() boundary — compile()'s
1354
+ * passScoreTargets already excludes blocked entries from the initial
1355
+ * target + fallbackChain, but if a consumer re-shapes the chain and
1356
+ * threads policy through only partially, this filter catches the gap.
1357
+ *
1358
+ * Resolves TT-40 follow-on `policy-block-not-enforced-on-fallback-chain`
1359
+ * (2026-05-15) where mutations_applied recorded the block intent but
1360
+ * the call walker landed on the blocked model anyway.
1361
+ *
1362
+ * Undefined when no filter ran (no blockedModels set). Populated only
1363
+ * when filter ran AND dropped at least one entry — empty drops are
1364
+ * stored as `undefined` to keep brain telemetry quiet on the common
1365
+ * case.
1366
+ */
1367
+ policyBlockedFiltered?: string[];
1368
+ /**
1369
+ * alpha.17. Unique identifier for this call() invocation, generated at
1370
+ * call() entry via crypto.randomUUID(). Returned on success and emitted
1371
+ * as the routing key for Glass-Box observability events
1372
+ * (compile.start, compile.done, execute.attempt, execute.success,
1373
+ * fallback.walked, advisory.fired). Pass the same id to
1374
+ * `subscribe(traceId)` from `@warmdrift/kgauto-compiler/glassbox` to
1375
+ * tap the in-flight event stream.
1376
+ *
1377
+ * Always present on success. Additive, non-breaking.
1378
+ */
1379
+ traceId: string;
1380
+ /**
1381
+ * alpha.44. Best-practice advisories emitted by the compile that actually
1382
+ * served the response (mirrors `CompileResult.advisories`; uses the SERVED
1383
+ * compile on fallback, same as `mutationsApplied`). Empty array when no
1384
+ * rules fired.
1385
+ *
1386
+ * Closes IC's `callForAgent` side-finding (2026-05-26): call() consumers
1387
+ * (agent paths — sweep / dyad / session-title) previously had no way to
1388
+ * `logAdvisories('[kgauto-v2 ...]', advisories)` like compile() consumers
1389
+ * (chat / intake) do, because the advisories were consumed internally
1390
+ * (trace events, brain record) but never returned. Additive, non-breaking.
1391
+ */
1392
+ advisories: BestPracticeAdvisory[];
1393
+ }
1394
+ /**
1395
+ * Thrown when call() exhausts the fallback chain without success.
1396
+ * `attempts` carries every model tried + classification.
1397
+ */
1398
+ declare class CallError extends Error {
1399
+ readonly attempts: CallAttempt[];
1400
+ readonly lastErrorCode?: string;
1401
+ readonly lastStatus?: number;
1402
+ constructor(message: string, attempts: CallAttempt[], lastStatus?: number, lastErrorCode?: string);
1403
+ }
1404
+ interface OracleScore {
1405
+ /** 0..1 overall quality. */
1406
+ score: number;
1407
+ /** Optional per-dimension breakdown. */
1408
+ dimensions?: Record<string, number>;
1409
+ /** Free-form explanation for debugging. */
1410
+ rationale?: string;
1411
+ }
1412
+ interface RecordInput {
1413
+ /** Handle from CompileResult. */
1414
+ handle: string;
1415
+ /** Actual tokens consumed (post-call). */
1416
+ tokensIn: number;
1417
+ tokensOut: number;
1418
+ /** Wall-clock latency in ms. */
1419
+ latencyMs: number;
1420
+ /** True iff the call returned a usable response. */
1421
+ success: boolean;
1422
+ /** True iff the call returned 0 output tokens despite success. */
1423
+ emptyResponse?: boolean;
1424
+ /** Provider error code if any. */
1425
+ errorType?: string;
1426
+ /** Tools actually invoked by the model. */
1427
+ toolsCalled?: string[];
1428
+ /** Oracle quality score — required for learning to fire. */
1429
+ oracleScore?: OracleScore;
1430
+ /** Optional: scrubbed prompt/response previews for debugging. */
1431
+ promptPreview?: string;
1432
+ responsePreview?: string;
1433
+ /**
1434
+ * The model that ACTUALLY RAN. Set this when consumer-side fallback ran
1435
+ * a different model than v2 compile() targeted. Brain stores this as
1436
+ * `model` (the truth) and the original target as `requested_model`.
1437
+ *
1438
+ * Omit when no fallback occurred — brain stores compile target as `model`
1439
+ * (still the truth in that case) and `requested_model` stays NULL.
1440
+ *
1441
+ * s11 fix: prevents the brain from misattributing fallback traffic to
1442
+ * the originally-requested model.
1443
+ */
1444
+ actualModel?: string;
1445
+ /**
1446
+ * Override `mutations_applied` for this outcome. Set by `call()` when
1447
+ * fallback fires — the served compile's mutations (which actually shaped
1448
+ * the request that went on the wire) replace the initial compile's
1449
+ * mutations (registered against the handle). Without this override, fallback
1450
+ * traffic is attributed to the initial compile's mutations and the brain's
1451
+ * mutation effectiveness stats become misleading.
1452
+ *
1453
+ * alpha.4: extends s11 truth-in-logging to mutations.
1454
+ */
1455
+ mutationsApplied?: string[];
1456
+ /**
1457
+ * Cache read input tokens, when supported by the provider.
1458
+ * - Anthropic: `usage.cache_read_input_tokens`
1459
+ * - Google (implicit caching): `usageMetadata.cachedContentTokenCount`
1460
+ * - OpenAI: `usage.prompt_tokens_details.cached_tokens`
1461
+ *
1462
+ * Powers the cost-and-efficiency-watcher (interfaces/kgauto.md, alpha.4):
1463
+ * `tokens_in - cache_read_input_tokens` is the un-cached new context per call.
1464
+ */
1465
+ cacheReadInputTokens?: number;
1466
+ /**
1467
+ * Cache creation input tokens (Anthropic-specific).
1468
+ * `usage.cache_creation_input_tokens`. The first call that pays the 25%
1469
+ * upcharge to write a cache marker; subsequent calls hit `cacheRead`.
1470
+ */
1471
+ cacheCreationInputTokens?: number;
1472
+ /**
1473
+ * Time to first token (ms). Optional; populated when the provider/SDK
1474
+ * surfaces it. Distinct from `latencyMs` (end-to-end wall clock).
1475
+ */
1476
+ ttftMs?: number;
1477
+ /**
1478
+ * alpha.57 (data-first) — the reasoning-effort tier this call actually ran
1479
+ * at. Overrides the compile-declared `constraints.effort` when both are
1480
+ * present (input wins — same precedence as `mutationsApplied`/`advisories`).
1481
+ * When omitted, record() auto-enriches from the registry-cached compile
1482
+ * declaration. Undefined end-to-end → the `effort` key is absent from the
1483
+ * outcome payload entirely (safe against pre-migration-033 brains).
1484
+ */
1485
+ effort?: EffortLevel;
1486
+ /**
1487
+ * alpha.20 — advisories fired at compile() time. Persisted to the brain's
1488
+ * `compile_outcome_advisories` sibling table via a second POST that fires
1489
+ * AFTER the primary outcome insert succeeds. Best-effort: a failed
1490
+ * advisory POST is logged via onError but does NOT throw or roll back the
1491
+ * primary outcome row.
1492
+ *
1493
+ * Pass `result.advisories` from the CompileResult directly. The brain
1494
+ * uses these to compute the `empty_rate_clean` comparator (rows with
1495
+ * zero advisories fired) so consumers can distinguish "model is bad"
1496
+ * from "client sent a bloated/uncached/malformed request."
1497
+ *
1498
+ * Empty array / undefined → no second POST fires.
1499
+ */
1500
+ advisories?: BestPracticeAdvisory[];
1501
+ /**
1502
+ * alpha.28 — Glass-Box renderer substrate fields (migration 018).
1503
+ *
1504
+ * All optional. When omitted, brain stores NULL and the renderer falls
1505
+ * back to "—" / hidden rows. Library callers (`call.ts`) populate what
1506
+ * they observe; adapter / SDK consumers can populate the rest from their
1507
+ * own provider response surface.
1508
+ */
1509
+ /**
1510
+ * Provider finish reason. Captured from NormalizedResponse.finishReason
1511
+ * (Anthropic `stop_reason`, Google `finishReason`, OpenAI `finish_reason`).
1512
+ * Lower-case canonicalization is the brain's job; consumers can pass
1513
+ * raw provider strings.
1514
+ */
1515
+ finishReason?: string;
1516
+ /**
1517
+ * End-to-end wall-clock latency in ms. Distinct from `latencyMs` only
1518
+ * insofar as `latencyMs` was the historical name for the same metric;
1519
+ * `totalMs` is the new column on `compile_outcomes` (migration 018).
1520
+ * When omitted, brain mirrors `latency_ms`.
1521
+ */
1522
+ totalMs?: number;
1523
+ /** Tools kept after the tool-relevance pass. */
1524
+ toolsCount?: number;
1525
+ /** Number of history messages at compile time. */
1526
+ historyDepth?: number;
1527
+ /** Rendered system prompt size in characters. */
1528
+ systemPromptChars?: number;
1529
+ /** Model originally targeted when a fallback fired. */
1530
+ fellOverFrom?: string;
1531
+ /**
1532
+ * Why the fallback fired — the SAME closed set as CallResult.fallbackReason
1533
+ * (one derivation; the alpha.77 DTS break caught this field's inline copy
1534
+ * drifting when the canonical union grew a member).
1535
+ */
1536
+ fallbackReason?: FallbackReason;
1537
+ /**
1538
+ * alpha.66 — true when the one-shot same-model retry fired during this
1539
+ * call (migration 039 `retried_same_model`). Powers the offline rollup:
1540
+ * retry rate on the cliff class, and — joined with `fell_over_from` —
1541
+ * how often the retry rescued the call vs the chain walking anyway.
1542
+ */
1543
+ retriedSameModel?: boolean;
1544
+ /**
1545
+ * alpha.71 — the precise `errorCode` of the attempt that drove the chain
1546
+ * (migration 044). Set automatically by `call()`; a consumer driving
1547
+ * `record()` by hand may pass it. See `CallResult.fellOverErrorCode` for
1548
+ * why the normalized `fallbackReason` is insufficient on its own.
1549
+ */
1550
+ fellOverErrorCode?: string;
1551
+ }
1552
+ /**
1553
+ * alpha.20 Entry 4: kinds of consumer-declared outcomes feeding the quality
1554
+ * loop. Surfaces in `recordOutcome()` as the verdict the consumer's UX is
1555
+ * forwarding to the brain.
1556
+ *
1557
+ * - `approved` user explicitly approved (thumbs up, "looks good", accepted)
1558
+ * - `rejected` user explicitly rejected (thumbs down, "redo", discarded)
1559
+ * - `partial` accepted with edits or partial use (mixed signal)
1560
+ * - `engaged` user engaged with the output (copy/scroll/dwell)
1561
+ * - `abandoned` user abandoned the response (closed, navigated away)
1562
+ * - `unknown` verdict could not be inferred — recorded for completeness
1563
+ */
1564
+ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned' | 'unknown';
1565
+ /**
1566
+ * Input to `recordOutcome()` — consumer's verdict on a previously-compiled
1567
+ * call. Joins to the original `compile_outcomes` row via outcomeId,
1568
+ * enabling per-(model, archetype) approve-rate measurement once N ≥ 10
1569
+ * outcomes accumulate.
1570
+ */
1571
+ interface RecordOutcomeInput {
1572
+ /**
1573
+ * Joins to compile_outcomes.id. Pass the compile `handle` string
1574
+ * (CompileResult.handle / CallResult.handle) — consumer proxies resolve
1575
+ * handle → compile_outcomes.id via the `compile_outcomes.handle` column
1576
+ * (reference implementations: PB `api/kgauto-v2/compile_outcome_quality.js`,
1577
+ * tt-intel/IC `app/api/kgauto/v2/compile_outcome_quality/route.ts`). A
1578
+ * numeric compile_outcomes.id also works if the caller already has it.
1579
+ * (There is no `CompileResult.outcomeId` field — the brain assigns the row
1580
+ * id at insert; `handle` is the consumer-visible correlator.)
1581
+ */
1582
+ outcomeId: number | string;
1583
+ /** What did the user / system do with this output? */
1584
+ outcome: OutcomeKind;
1585
+ /** Optional 1-5 user rating (e.g., thumbs up/down with intensity, NPS-style). */
1586
+ rating?: 1 | 2 | 3 | 4 | 5;
1587
+ /** Optional free-text reason (e.g., user-typed feedback, system-inferred cause). */
1588
+ reason?: string;
1589
+ /**
1590
+ * Optional model-reported confidence at compile time (0..1). Used for
1591
+ * Brier-score calibration in later phases (alpha.21+) — pair this with
1592
+ * the actual `outcome` to compute calibration error.
1593
+ */
1594
+ observedConfidence?: number;
1595
+ }
1596
+ /**
1597
+ * Return shape of `recordOutcome()`. Never throws — persistence failures
1598
+ * surface as `ok: false` with a stable `reason` string.
1599
+ */
1600
+ interface OutcomeResult {
1601
+ /**
1602
+ * `true` — the POST was acknowledged 2xx (sync mode only).
1603
+ * `'queued'` (alpha.61) — fire-and-forget mode: the write was handed to the
1604
+ * runtime but NOT acknowledged; delivery is unknown at return time. Read
1605
+ * `brainHealth()` or set `BrainConfig.sync` for delivery evidence.
1606
+ * `false` — brain not configured, or the POST failed (sync mode).
1607
+ * Both truthy values pass `if (result.ok)`; pre-alpha.61 code that treated
1608
+ * the fire-and-forget `true` as an ack was reading a false signal.
1609
+ */
1610
+ ok: boolean | 'queued';
1611
+ /** Stable reason code when ok=false. One of: 'brain_not_configured' | 'persistence_failed'. */
1612
+ reason?: string;
1613
+ }
1614
+ /**
1615
+ * alpha.21 (s78 Entry 1): provenance label on a chain entry. Surfaces WHY
1616
+ * an entry sits where it sits so consumers can distinguish:
1617
+ *
1618
+ * - 'measured' brain has N>=10 rows with a measurable quality
1619
+ * outcome backing this placement. The number lives on
1620
+ * `ChainEntry.n`.
1621
+ * - 'capability-fact' inclusion or exclusion driven by a published or
1622
+ * measured CAPABILITY (L-040 cliff, ctx window cap,
1623
+ * structured-output support). Not an opinion — a
1624
+ * fact about what the model can/can't do.
1625
+ * - 'judgment' engineer's pick, no measured backing yet. Cold-start
1626
+ * prior; entirely valid until evidence accumulates.
1627
+ *
1628
+ * "Judgment" is HONEST, not a downgrade. Most of `STARTER_CHAINS` lands here
1629
+ * in alpha.21 — that's the point: consumers can SEE the grounding gap and
1630
+ * prioritize the measurement work that would graduate them to 'measured'.
1631
+ */
1632
+ type Grounding = 'measured' | 'capability-fact' | 'judgment';
1633
+ /**
1634
+ * alpha.21 (s78 Entry 1): a single position in a fallback chain, carrying its
1635
+ * provenance label and an optional human-readable reason. The shape replaces
1636
+ * the old `string[]` representation everywhere chains are surfaced externally.
1637
+ *
1638
+ * `n` is REQUIRED when `grounding === 'measured'` — the runtime helper
1639
+ * `makeMeasuredEntry()` enforces this. For 'capability-fact' and 'judgment'
1640
+ * entries, `n` is undefined.
1641
+ */
1642
+ interface ChainEntry {
1643
+ /** Canonical model id (post-alias). */
1644
+ id: string;
1645
+ /** Why this entry sits in this position. */
1646
+ grounding: Grounding;
1647
+ /**
1648
+ * Optional one-liner explaining the grounding decision. The inline comments
1649
+ * that historically lived next to STARTER_CHAINS entries are now expressed
1650
+ * here as machine-readable text.
1651
+ */
1652
+ reason?: string;
1653
+ /**
1654
+ * When `grounding === 'measured'`, the brain row count that backs this
1655
+ * placement. Undefined for 'capability-fact' and 'judgment' entries.
1656
+ */
1657
+ n?: number;
1658
+ }
1659
+ /**
1660
+ * alpha.21 introspection shape — a per-archetype chain with grounding on
1661
+ * every position. Consumers reading this never see naked string ids;
1662
+ * everything carries provenance.
1663
+ */
1664
+ interface ChainWithGrounding {
1665
+ archetype: IntentArchetypeName;
1666
+ /** Ordered: position 0 = primary, rising index = fallback positions. */
1667
+ entries: ChainEntry[];
1668
+ }
1669
+ /** alpha.23 (s78 Phase 3): per-axis metrics returned by the brain RPC. */
1670
+ interface PerAxisMetrics {
1671
+ appId: string;
1672
+ archetype: string;
1673
+ model: string;
1674
+ windowDays: number;
1675
+ /** Total brain rows for this tuple in the window. */
1676
+ nRows: number;
1677
+ /** Subset of nRows with zero advisories fired — the "clean signal" comparator. */
1678
+ nRowsClean: number;
1679
+ /** Count of compile_outcome_quality entries joining to this tuple's outcomes. */
1680
+ nQualityOutcomes: number;
1681
+ /** Approve rate from quality outcomes. null when nQualityOutcomes === 0. */
1682
+ magicRate: number | null;
1683
+ /** Whether magicRate >= consumer-declared qualityFloor. null when no floor declared OR no outcomes. */
1684
+ qualityFloorMet: boolean | null;
1685
+ costEfficiency: {
1686
+ avgCostUsd: number | null;
1687
+ avgCostUsdClean: number | null;
1688
+ avgInputTokens: number | null;
1689
+ avgOutputTokens: number | null;
1690
+ inputTokenRatio: number | null;
1691
+ };
1692
+ timeEfficiency: {
1693
+ avgLatencyMs: number | null;
1694
+ avgTtftMs: number | null;
1695
+ };
1696
+ reliability: {
1697
+ successRate: number | null;
1698
+ successRateClean: number | null;
1699
+ emptyRate: number | null;
1700
+ emptyRateClean: number | null;
1701
+ };
1702
+ evidenceFreshnessDays: number | null;
1703
+ }
1704
+ /** Per-axis metrics keyed by model — used for chain-comparison views. */
1705
+ type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1706
+
1707
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, captureGoldenIr as D, type EffortLevel as E, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, hasMutation as J, mutationId as K, parseGoldenCaptureRate as L, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, resolveGoldenCaptureRate as Q, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, shouldCaptureGolden as U, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OracleScore as h, type Adapter as i, type PerAxisMetrics as j, type Provider as k, type ChainEntry as l, type CallAttempt as m, CallError as n, type ChainModelEntry as o, type ChainWithGrounding as p, type Constraints as q, type GoldenCaptureOptions as r, type MutationApplied as s, type NormalizedTokens as t, type OutcomeKind as u, type PerAxisMetricsByModel as v, type PromptSection as w, type SectionKind as x, type ShadowProbeConfig as y, type ToolDefinition as z };