@warmdrift/kgauto-compiler 2.0.0-alpha.44 → 2.0.0-alpha.46

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.
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-B5DzMhYm.mjs';
2
- export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-B5DzMhYm.mjs';
3
- import '../ir-DARjQnvZ.mjs';
1
+ import { G as GlassboxEvent } from '../types-DMJqRzDF.mjs';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-DMJqRzDF.mjs';
3
+ import '../ir-BBKgsUX7.mjs';
4
4
  import '../dialect.mjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-BDqNQxuX.js';
2
- export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-BDqNQxuX.js';
3
- import '../ir-DAUBaPhd.js';
1
+ import { G as GlassboxEvent } from '../types-Bzw8tH-7.js';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-Bzw8tH-7.js';
3
+ import '../ir-D3n-pBYI.js';
4
4
  import '../dialect.js';
5
5
 
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-Rq_fywDq.mjs';
2
- import '../ir-DARjQnvZ.mjs';
1
+ import { T as TraceHealth } from '../types-xBWYk9Mm.mjs';
2
+ import '../ir-BBKgsUX7.mjs';
3
3
  import '../dialect.mjs';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-CfVyRbCl.js';
2
- import '../ir-DAUBaPhd.js';
1
+ import { T as TraceHealth } from '../types-B6z-8phQ.js';
2
+ import '../ir-D3n-pBYI.js';
3
3
  import '../dialect.js';
4
4
 
5
5
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-B5DzMhYm.mjs';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-Rq_fywDq.mjs';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-Rq_fywDq.mjs';
4
- import '../ir-DARjQnvZ.mjs';
1
+ import { G as GlassboxEvent } from '../types-DMJqRzDF.mjs';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-xBWYk9Mm.mjs';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-xBWYk9Mm.mjs';
4
+ import '../ir-BBKgsUX7.mjs';
5
5
  import '../dialect.mjs';
6
6
 
7
7
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-BDqNQxuX.js';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-CfVyRbCl.js';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-CfVyRbCl.js';
4
- import '../ir-DAUBaPhd.js';
1
+ import { G as GlassboxEvent } from '../types-Bzw8tH-7.js';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-B6z-8phQ.js';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-B6z-8phQ.js';
4
+ import '../ir-D3n-pBYI.js';
5
5
  import '../dialect.js';
6
6
 
7
7
  /**
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { a as TraceDetail } from '../../types-Rq_fywDq.mjs';
3
- import '../../ir-DARjQnvZ.mjs';
2
+ import { a as TraceDetail } from '../../types-xBWYk9Mm.mjs';
3
+ import '../../ir-BBKgsUX7.mjs';
4
4
  import '../../dialect.mjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { a as TraceDetail } from '../../types-CfVyRbCl.js';
3
- import '../../ir-DAUBaPhd.js';
2
+ import { a as TraceDetail } from '../../types-B6z-8phQ.js';
3
+ import '../../ir-D3n-pBYI.js';
4
4
  import '../../dialect.js';
5
5
 
6
6
  /**
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
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-DARjQnvZ.mjs';
2
- export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, T as ToolCall, x as ToolDefinition } from './ir-DARjQnvZ.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, 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-BBKgsUX7.mjs';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-BBKgsUX7.mjs';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.mjs';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, profilesByProvider, tryGetProfile } from './profiles.mjs';
5
5
  import { IntentArchetypeName } from './dialect.mjs';
@@ -335,6 +335,82 @@ interface OutcomePayload {
335
335
  * failure. Never throws.
336
336
  */
337
337
  declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
338
+ /**
339
+ * True when the active brain config requests synchronous (awaited) writes.
340
+ * call()'s shadow-probe path reads this to decide whether to await the probe
341
+ * (Edge/Worker/Lambda — L-086) or fire-and-forget (Node). False when no brain
342
+ * is configured.
343
+ */
344
+ declare function isBrainSync(): boolean;
345
+ /**
346
+ * Full-IR inline shadow-probe record input (Shape B, Phase 1 — s51). Carries
347
+ * ONLY response previews + metadata; the prompt (system/context/payload) is
348
+ * never included — `promptHash` is an irreversible grouping key, not content.
349
+ */
350
+ interface ShadowProbeRecordInput {
351
+ appId: string;
352
+ archetype: string;
353
+ family: string;
354
+ candidateModel: string;
355
+ currentModel: string;
356
+ /** Irreversible grouping hash (NOT the prompt). */
357
+ promptHash: string;
358
+ /** Served model's response, truncated (RESPONSE text only — never the prompt). */
359
+ currentResponsePreview?: string;
360
+ /** Candidate model's response, truncated. */
361
+ candidateResponsePreview?: string;
362
+ tokensCurrentIn?: number;
363
+ tokensCurrentOut?: number;
364
+ tokensCandidateIn?: number;
365
+ tokensCandidateOut?: number;
366
+ /**
367
+ * Wall-clock latency of the served call, ms (alpha.46). The third swap-decision
368
+ * axis alongside quality + cost — a verdict needs to know the candidate is
369
+ * slower, not just better/cheaper. Served latency mirrors
370
+ * `compile_outcomes.latency_ms`; carried here so a probe row is self-contained.
371
+ */
372
+ latencyCurrentMs?: number;
373
+ /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
374
+ latencyCandidateMs?: number;
375
+ }
376
+ /**
377
+ * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
378
+ * Exported so a test can assert the G3 privacy invariant: the row carries NO
379
+ * prompt/system/context text — only response previews + metadata + a hash.
380
+ *
381
+ * Phase 1 (judge: 'off'): `judge_verdict` / `judge_score` are null — the row
382
+ * is an unjudged sample for the Phase-2 offline batch judge. `prompt_fidelity`
383
+ * is 1.0 by construction (the candidate ran the full IR, not a truncated
384
+ * preview), and `replay_source='inline-full-ir'` marks it as a trustworthy row
385
+ * (vs the watchers' lossy `replay-preview`).
386
+ */
387
+ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
388
+ app_id: string;
389
+ intent_archetype: string;
390
+ family: string;
391
+ candidate_model: string;
392
+ current_model: string;
393
+ prompt_hash: string;
394
+ current_response: string | null;
395
+ candidate_response: string | null;
396
+ judge_verdict: null;
397
+ judge_score: null;
398
+ tokens_current_in: number | null;
399
+ tokens_current_out: number | null;
400
+ tokens_candidate_in: number | null;
401
+ tokens_candidate_out: number | null;
402
+ latency_current_ms: number | null;
403
+ latency_candidate_ms: number | null;
404
+ prompt_fidelity: number;
405
+ replay_source: 'inline-full-ir';
406
+ };
407
+ /**
408
+ * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
409
+ * default; honors `BrainConfig.sync` (L-086). Never throws — failures route to
410
+ * onError. Mirrors record()'s POST shape; consumer proxies forward
411
+ * `/probe_outcomes` the same way they forward `/outcomes`.
412
+ */
413
+ declare function recordShadowProbe(input: ShadowProbeRecordInput): Promise<void>;
338
414
 
339
415
  /**
340
416
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -2119,4 +2195,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2119
2195
  */
2120
2196
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2121
2197
 
2122
- export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type 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, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, 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, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
2198
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type 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 ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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-DAUBaPhd.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-DAUBaPhd.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-D3n-pBYI.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, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-D3n-pBYI.js';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.js';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, profilesByProvider, tryGetProfile } from './profiles.js';
5
5
  import { IntentArchetypeName } from './dialect.js';
@@ -335,6 +335,82 @@ interface OutcomePayload {
335
335
  * failure. Never throws.
336
336
  */
337
337
  declare function recordOutcome(input: RecordOutcomeInput): Promise<OutcomeResult>;
338
+ /**
339
+ * True when the active brain config requests synchronous (awaited) writes.
340
+ * call()'s shadow-probe path reads this to decide whether to await the probe
341
+ * (Edge/Worker/Lambda — L-086) or fire-and-forget (Node). False when no brain
342
+ * is configured.
343
+ */
344
+ declare function isBrainSync(): boolean;
345
+ /**
346
+ * Full-IR inline shadow-probe record input (Shape B, Phase 1 — s51). Carries
347
+ * ONLY response previews + metadata; the prompt (system/context/payload) is
348
+ * never included — `promptHash` is an irreversible grouping key, not content.
349
+ */
350
+ interface ShadowProbeRecordInput {
351
+ appId: string;
352
+ archetype: string;
353
+ family: string;
354
+ candidateModel: string;
355
+ currentModel: string;
356
+ /** Irreversible grouping hash (NOT the prompt). */
357
+ promptHash: string;
358
+ /** Served model's response, truncated (RESPONSE text only — never the prompt). */
359
+ currentResponsePreview?: string;
360
+ /** Candidate model's response, truncated. */
361
+ candidateResponsePreview?: string;
362
+ tokensCurrentIn?: number;
363
+ tokensCurrentOut?: number;
364
+ tokensCandidateIn?: number;
365
+ tokensCandidateOut?: number;
366
+ /**
367
+ * Wall-clock latency of the served call, ms (alpha.46). The third swap-decision
368
+ * axis alongside quality + cost — a verdict needs to know the candidate is
369
+ * slower, not just better/cheaper. Served latency mirrors
370
+ * `compile_outcomes.latency_ms`; carried here so a probe row is self-contained.
371
+ */
372
+ latencyCurrentMs?: number;
373
+ /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
374
+ latencyCandidateMs?: number;
375
+ }
376
+ /**
377
+ * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
378
+ * Exported so a test can assert the G3 privacy invariant: the row carries NO
379
+ * prompt/system/context text — only response previews + metadata + a hash.
380
+ *
381
+ * Phase 1 (judge: 'off'): `judge_verdict` / `judge_score` are null — the row
382
+ * is an unjudged sample for the Phase-2 offline batch judge. `prompt_fidelity`
383
+ * is 1.0 by construction (the candidate ran the full IR, not a truncated
384
+ * preview), and `replay_source='inline-full-ir'` marks it as a trustworthy row
385
+ * (vs the watchers' lossy `replay-preview`).
386
+ */
387
+ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
388
+ app_id: string;
389
+ intent_archetype: string;
390
+ family: string;
391
+ candidate_model: string;
392
+ current_model: string;
393
+ prompt_hash: string;
394
+ current_response: string | null;
395
+ candidate_response: string | null;
396
+ judge_verdict: null;
397
+ judge_score: null;
398
+ tokens_current_in: number | null;
399
+ tokens_current_out: number | null;
400
+ tokens_candidate_in: number | null;
401
+ tokens_candidate_out: number | null;
402
+ latency_current_ms: number | null;
403
+ latency_candidate_ms: number | null;
404
+ prompt_fidelity: number;
405
+ replay_source: 'inline-full-ir';
406
+ };
407
+ /**
408
+ * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
409
+ * default; honors `BrainConfig.sync` (L-086). Never throws — failures route to
410
+ * onError. Mirrors record()'s POST shape; consumer proxies forward
411
+ * `/probe_outcomes` the same way they forward `/outcomes`.
412
+ */
413
+ declare function recordShadowProbe(input: ShadowProbeRecordInput): Promise<void>;
338
414
 
339
415
  /**
340
416
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -2119,4 +2195,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2119
2195
  */
2120
2196
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2121
2197
 
2122
- export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type 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, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, 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, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
2198
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type 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 ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
package/dist/index.js CHANGED
@@ -43,6 +43,7 @@ __export(index_exports, {
43
43
  bucketHistory: () => bucketHistory,
44
44
  bucketToolCount: () => bucketToolCount,
45
45
  buildLLMJudge: () => buildLLMJudge,
46
+ buildShadowProbeRow: () => buildShadowProbeRow,
46
47
  call: () => call,
47
48
  clearBrain: () => clearBrain,
48
49
  compile: () => compile2,
@@ -71,6 +72,7 @@ __export(index_exports, {
71
72
  hashShape: () => hashShape,
72
73
  isArchetype: () => isArchetype,
73
74
  isBrainQueryActiveFor: () => isBrainQueryActiveFor,
75
+ isBrainSync: () => isBrainSync,
74
76
  isExclusionFindingsBrainActive: () => isExclusionFindingsBrainActive,
75
77
  isModelReachable: () => isModelReachable,
76
78
  isProviderReachable: () => isProviderReachable,
@@ -89,6 +91,7 @@ __export(index_exports, {
89
91
  readBrainReadEnv: () => readBrainReadEnv,
90
92
  record: () => record,
91
93
  recordOutcome: () => recordOutcome,
94
+ recordShadowProbe: () => recordShadowProbe,
92
95
  resetTokenizer: () => resetTokenizer,
93
96
  resolveConventionsForProfile: () => resolveConventionsForProfile,
94
97
  resolvePricingAt: () => resolvePricingAt,
@@ -4472,6 +4475,63 @@ async function recordOutcome(input) {
4472
4475
  void send();
4473
4476
  return { ok: true };
4474
4477
  }
4478
+ function isBrainSync() {
4479
+ return activeConfig?.sync === true;
4480
+ }
4481
+ function buildShadowProbeRow(input) {
4482
+ return {
4483
+ app_id: input.appId,
4484
+ intent_archetype: input.archetype,
4485
+ family: input.family,
4486
+ candidate_model: input.candidateModel,
4487
+ current_model: input.currentModel,
4488
+ prompt_hash: input.promptHash,
4489
+ current_response: input.currentResponsePreview ?? null,
4490
+ candidate_response: input.candidateResponsePreview ?? null,
4491
+ judge_verdict: null,
4492
+ judge_score: null,
4493
+ tokens_current_in: input.tokensCurrentIn ?? null,
4494
+ tokens_current_out: input.tokensCurrentOut ?? null,
4495
+ tokens_candidate_in: input.tokensCandidateIn ?? null,
4496
+ tokens_candidate_out: input.tokensCandidateOut ?? null,
4497
+ latency_current_ms: input.latencyCurrentMs ?? null,
4498
+ latency_candidate_ms: input.latencyCandidateMs ?? null,
4499
+ // Full IR was replayed (not a truncated preview), so fidelity is 1.0 — the
4500
+ // prompt-fidelity guard never fires on these rows.
4501
+ prompt_fidelity: 1,
4502
+ replay_source: "inline-full-ir"
4503
+ };
4504
+ }
4505
+ async function recordShadowProbe(input) {
4506
+ if (!activeConfig) return;
4507
+ const config = activeConfig;
4508
+ const fetchFn = config.fetchImpl ?? fetch;
4509
+ const row = buildShadowProbeRow(input);
4510
+ const send = async () => {
4511
+ try {
4512
+ const res = await fetchFn(`${config.endpoint}/probe_outcomes`, {
4513
+ method: "POST",
4514
+ headers: {
4515
+ "Content-Type": "application/json",
4516
+ Prefer: "return=minimal",
4517
+ ...config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
4518
+ },
4519
+ body: JSON.stringify(row)
4520
+ });
4521
+ if (!res.ok) {
4522
+ const text = await res.text().catch(() => "<no body>");
4523
+ throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
4524
+ }
4525
+ } catch (err) {
4526
+ (config.onError ?? defaultOnError5)(err);
4527
+ }
4528
+ };
4529
+ if (config.sync) {
4530
+ await send();
4531
+ } else {
4532
+ void send();
4533
+ }
4534
+ }
4475
4535
 
4476
4536
  // src/ir.ts
4477
4537
  var CallError = class extends Error {
@@ -5951,6 +6011,20 @@ async function call(ir, opts = {}) {
5951
6011
  );
5952
6012
  }
5953
6013
  }
6014
+ if (opts.shadowProbe) {
6015
+ const probe = runShadowProbe({
6016
+ ir,
6017
+ opts,
6018
+ servedModel: targetModel,
6019
+ servedResponse: validated.response,
6020
+ servedLatencyMs: latencyMs2
6021
+ });
6022
+ if (isBrainSync()) {
6023
+ await probe;
6024
+ } else {
6025
+ void probe;
6026
+ }
6027
+ }
5954
6028
  return {
5955
6029
  handle: initial.handle,
5956
6030
  actualModel: targetModel,
@@ -6023,6 +6097,72 @@ function extractPromptPreview(ir) {
6023
6097
  if (lastHist) return lastHist.slice(0, 200);
6024
6098
  return void 0;
6025
6099
  }
6100
+ function shouldSampleProbe(sampleRate, rng = Math.random) {
6101
+ if (!(sampleRate > 0)) return false;
6102
+ if (sampleRate >= 1) return true;
6103
+ return rng() < sampleRate;
6104
+ }
6105
+ function normalizeProbeCandidates(candidates) {
6106
+ const arr = Array.isArray(candidates) ? candidates : [candidates];
6107
+ return [...new Set(arr.filter((c) => typeof c === "string" && c.length > 0))];
6108
+ }
6109
+ function hashForProbe(s) {
6110
+ let h = 0;
6111
+ for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i) | 0;
6112
+ return `h${(h >>> 0).toString(16)}`;
6113
+ }
6114
+ async function runShadowProbe(args) {
6115
+ try {
6116
+ const cfg = args.opts.shadowProbe;
6117
+ if (!shouldSampleProbe(cfg.sampleRate ?? 0.05)) return;
6118
+ const candidates = normalizeProbeCandidates(cfg.candidates);
6119
+ const promptHash = hashForProbe(args.ir.currentTurn?.content ?? "");
6120
+ for (const candidate of candidates) {
6121
+ if (candidate === args.servedModel) continue;
6122
+ if (deriveFamilyFromModelId(candidate) === "claude-opus") continue;
6123
+ if (!isModelReachable(candidate, { apiKeys: args.opts.apiKeys })) continue;
6124
+ try {
6125
+ const candCompile = compileAndRegister(
6126
+ {
6127
+ ...args.ir,
6128
+ models: args.ir.models.includes(candidate) ? args.ir.models : [candidate, ...args.ir.models],
6129
+ constraints: { ...args.ir.constraints ?? {}, forceModel: candidate }
6130
+ },
6131
+ args.opts
6132
+ );
6133
+ const candStart = Date.now();
6134
+ const exec = await execute(candCompile.request, {
6135
+ apiKeys: args.opts.apiKeys,
6136
+ fetchImpl: args.opts.fetchImpl,
6137
+ providerOverrides: args.opts.providerOverrides
6138
+ });
6139
+ const candidateLatencyMs = Date.now() - candStart;
6140
+ if (!exec.ok) continue;
6141
+ await recordShadowProbe({
6142
+ appId: args.ir.appId,
6143
+ archetype: args.ir.intent.archetype,
6144
+ family: deriveFamilyFromModelId(candidate) ?? candCompile.provider,
6145
+ candidateModel: candidate,
6146
+ currentModel: args.servedModel,
6147
+ promptHash,
6148
+ currentResponsePreview: args.servedResponse.text.slice(0, 2e3),
6149
+ candidateResponsePreview: exec.response.text.slice(0, 2e3),
6150
+ tokensCurrentIn: args.servedResponse.tokens.input,
6151
+ tokensCurrentOut: args.servedResponse.tokens.output,
6152
+ tokensCandidateIn: exec.response.tokens.input,
6153
+ tokensCandidateOut: exec.response.tokens.output,
6154
+ // alpha.46 — speed is the third swap-decision axis. Served latency
6155
+ // mirrors the user's actual wait; candidate latency is measured only
6156
+ // here and stored nowhere else (irrecoverable if not captured now).
6157
+ latencyCurrentMs: args.servedLatencyMs,
6158
+ latencyCandidateMs: candidateLatencyMs
6159
+ });
6160
+ } catch {
6161
+ }
6162
+ }
6163
+ } catch {
6164
+ }
6165
+ }
6026
6166
  function validateStructuredContract(exec, ir) {
6027
6167
  if (!ir.constraints?.structuredOutput) {
6028
6168
  return { ok: true, response: exec.response };
@@ -6564,6 +6704,7 @@ function compile2(ir, opts) {
6564
6704
  bucketHistory,
6565
6705
  bucketToolCount,
6566
6706
  buildLLMJudge,
6707
+ buildShadowProbeRow,
6567
6708
  call,
6568
6709
  clearBrain,
6569
6710
  compile,
@@ -6592,6 +6733,7 @@ function compile2(ir, opts) {
6592
6733
  hashShape,
6593
6734
  isArchetype,
6594
6735
  isBrainQueryActiveFor,
6736
+ isBrainSync,
6595
6737
  isExclusionFindingsBrainActive,
6596
6738
  isModelReachable,
6597
6739
  isProviderReachable,
@@ -6610,6 +6752,7 @@ function compile2(ir, opts) {
6610
6752
  readBrainReadEnv,
6611
6753
  record,
6612
6754
  recordOutcome,
6755
+ recordShadowProbe,
6613
6756
  resetTokenizer,
6614
6757
  resolveConventionsForProfile,
6615
6758
  resolvePricingAt,
package/dist/index.mjs CHANGED
@@ -2825,6 +2825,63 @@ async function recordOutcome(input) {
2825
2825
  void send();
2826
2826
  return { ok: true };
2827
2827
  }
2828
+ function isBrainSync() {
2829
+ return activeConfig?.sync === true;
2830
+ }
2831
+ function buildShadowProbeRow(input) {
2832
+ return {
2833
+ app_id: input.appId,
2834
+ intent_archetype: input.archetype,
2835
+ family: input.family,
2836
+ candidate_model: input.candidateModel,
2837
+ current_model: input.currentModel,
2838
+ prompt_hash: input.promptHash,
2839
+ current_response: input.currentResponsePreview ?? null,
2840
+ candidate_response: input.candidateResponsePreview ?? null,
2841
+ judge_verdict: null,
2842
+ judge_score: null,
2843
+ tokens_current_in: input.tokensCurrentIn ?? null,
2844
+ tokens_current_out: input.tokensCurrentOut ?? null,
2845
+ tokens_candidate_in: input.tokensCandidateIn ?? null,
2846
+ tokens_candidate_out: input.tokensCandidateOut ?? null,
2847
+ latency_current_ms: input.latencyCurrentMs ?? null,
2848
+ latency_candidate_ms: input.latencyCandidateMs ?? null,
2849
+ // Full IR was replayed (not a truncated preview), so fidelity is 1.0 — the
2850
+ // prompt-fidelity guard never fires on these rows.
2851
+ prompt_fidelity: 1,
2852
+ replay_source: "inline-full-ir"
2853
+ };
2854
+ }
2855
+ async function recordShadowProbe(input) {
2856
+ if (!activeConfig) return;
2857
+ const config = activeConfig;
2858
+ const fetchFn = config.fetchImpl ?? fetch;
2859
+ const row = buildShadowProbeRow(input);
2860
+ const send = async () => {
2861
+ try {
2862
+ const res = await fetchFn(`${config.endpoint}/probe_outcomes`, {
2863
+ method: "POST",
2864
+ headers: {
2865
+ "Content-Type": "application/json",
2866
+ Prefer: "return=minimal",
2867
+ ...config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
2868
+ },
2869
+ body: JSON.stringify(row)
2870
+ });
2871
+ if (!res.ok) {
2872
+ const text = await res.text().catch(() => "<no body>");
2873
+ throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
2874
+ }
2875
+ } catch (err) {
2876
+ (config.onError ?? defaultOnError4)(err);
2877
+ }
2878
+ };
2879
+ if (config.sync) {
2880
+ await send();
2881
+ } else {
2882
+ void send();
2883
+ }
2884
+ }
2828
2885
 
2829
2886
  // src/ir.ts
2830
2887
  var CallError = class extends Error {
@@ -3589,6 +3646,20 @@ async function call(ir, opts = {}) {
3589
3646
  );
3590
3647
  }
3591
3648
  }
3649
+ if (opts.shadowProbe) {
3650
+ const probe = runShadowProbe({
3651
+ ir,
3652
+ opts,
3653
+ servedModel: targetModel,
3654
+ servedResponse: validated.response,
3655
+ servedLatencyMs: latencyMs2
3656
+ });
3657
+ if (isBrainSync()) {
3658
+ await probe;
3659
+ } else {
3660
+ void probe;
3661
+ }
3662
+ }
3592
3663
  return {
3593
3664
  handle: initial.handle,
3594
3665
  actualModel: targetModel,
@@ -3661,6 +3732,72 @@ function extractPromptPreview(ir) {
3661
3732
  if (lastHist) return lastHist.slice(0, 200);
3662
3733
  return void 0;
3663
3734
  }
3735
+ function shouldSampleProbe(sampleRate, rng = Math.random) {
3736
+ if (!(sampleRate > 0)) return false;
3737
+ if (sampleRate >= 1) return true;
3738
+ return rng() < sampleRate;
3739
+ }
3740
+ function normalizeProbeCandidates(candidates) {
3741
+ const arr = Array.isArray(candidates) ? candidates : [candidates];
3742
+ return [...new Set(arr.filter((c) => typeof c === "string" && c.length > 0))];
3743
+ }
3744
+ function hashForProbe(s) {
3745
+ let h = 0;
3746
+ for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i) | 0;
3747
+ return `h${(h >>> 0).toString(16)}`;
3748
+ }
3749
+ async function runShadowProbe(args) {
3750
+ try {
3751
+ const cfg = args.opts.shadowProbe;
3752
+ if (!shouldSampleProbe(cfg.sampleRate ?? 0.05)) return;
3753
+ const candidates = normalizeProbeCandidates(cfg.candidates);
3754
+ const promptHash = hashForProbe(args.ir.currentTurn?.content ?? "");
3755
+ for (const candidate of candidates) {
3756
+ if (candidate === args.servedModel) continue;
3757
+ if (deriveFamilyFromModelId(candidate) === "claude-opus") continue;
3758
+ if (!isModelReachable(candidate, { apiKeys: args.opts.apiKeys })) continue;
3759
+ try {
3760
+ const candCompile = compileAndRegister(
3761
+ {
3762
+ ...args.ir,
3763
+ models: args.ir.models.includes(candidate) ? args.ir.models : [candidate, ...args.ir.models],
3764
+ constraints: { ...args.ir.constraints ?? {}, forceModel: candidate }
3765
+ },
3766
+ args.opts
3767
+ );
3768
+ const candStart = Date.now();
3769
+ const exec = await execute(candCompile.request, {
3770
+ apiKeys: args.opts.apiKeys,
3771
+ fetchImpl: args.opts.fetchImpl,
3772
+ providerOverrides: args.opts.providerOverrides
3773
+ });
3774
+ const candidateLatencyMs = Date.now() - candStart;
3775
+ if (!exec.ok) continue;
3776
+ await recordShadowProbe({
3777
+ appId: args.ir.appId,
3778
+ archetype: args.ir.intent.archetype,
3779
+ family: deriveFamilyFromModelId(candidate) ?? candCompile.provider,
3780
+ candidateModel: candidate,
3781
+ currentModel: args.servedModel,
3782
+ promptHash,
3783
+ currentResponsePreview: args.servedResponse.text.slice(0, 2e3),
3784
+ candidateResponsePreview: exec.response.text.slice(0, 2e3),
3785
+ tokensCurrentIn: args.servedResponse.tokens.input,
3786
+ tokensCurrentOut: args.servedResponse.tokens.output,
3787
+ tokensCandidateIn: exec.response.tokens.input,
3788
+ tokensCandidateOut: exec.response.tokens.output,
3789
+ // alpha.46 — speed is the third swap-decision axis. Served latency
3790
+ // mirrors the user's actual wait; candidate latency is measured only
3791
+ // here and stored nowhere else (irrecoverable if not captured now).
3792
+ latencyCurrentMs: args.servedLatencyMs,
3793
+ latencyCandidateMs: candidateLatencyMs
3794
+ });
3795
+ } catch {
3796
+ }
3797
+ }
3798
+ } catch {
3799
+ }
3800
+ }
3664
3801
  function validateStructuredContract(exec, ir) {
3665
3802
  if (!ir.constraints?.structuredOutput) {
3666
3803
  return { ok: true, response: exec.response };
@@ -4201,6 +4338,7 @@ export {
4201
4338
  bucketHistory,
4202
4339
  bucketToolCount,
4203
4340
  buildLLMJudge,
4341
+ buildShadowProbeRow,
4204
4342
  call,
4205
4343
  clearBrain,
4206
4344
  compile2 as compile,
@@ -4229,6 +4367,7 @@ export {
4229
4367
  hashShape,
4230
4368
  isArchetype,
4231
4369
  isBrainQueryActiveFor,
4370
+ isBrainSync,
4232
4371
  isExclusionFindingsBrainActive,
4233
4372
  isModelReachable,
4234
4373
  isProviderReachable,
@@ -4247,6 +4386,7 @@ export {
4247
4386
  readBrainReadEnv,
4248
4387
  record,
4249
4388
  recordOutcome,
4389
+ recordShadowProbe,
4250
4390
  resetTokenizer,
4251
4391
  resolveConventionsForProfile,
4252
4392
  resolvePricingAt,
@@ -799,9 +799,47 @@ interface ProviderOverrides {
799
799
  openai?: Record<string, unknown>;
800
800
  deepseek?: Record<string, unknown>;
801
801
  }
802
+ /**
803
+ * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
804
+ *
805
+ * When set on `call()`, after the primary response is served kgauto re-lowers
806
+ * the SAME in-memory PromptIR to each candidate and runs it, persisting a
807
+ * `probe_outcomes` row with `replay_source='inline-full-ir'` and
808
+ * `prompt_fidelity=1.0` — a fair, full-prompt measurement (vs the watchers'
809
+ * lossy `prompt_preview` replay). The probe NEVER blocks the user response and
810
+ * NEVER persists the raw prompt (system/context/payload) — only response
811
+ * previews + metadata, same policy the brain already holds.
812
+ *
813
+ * This is the trustworthy path that earns the right to a quality verdict;
814
+ * `prompt_preview` replay is retired for verdicts (see CLAUDE.md).
815
+ *
816
+ * Phase 1 enforces `sampleRate` and runs the candidate with `judge: 'off'`
817
+ * (responses stored for an offline batch judge). `judge: 'opus'` (inline
818
+ * verdict) and `maxPerDay` (per-tuple daily cap, needs a brain-count read)
819
+ * are accepted by the type but ENFORCED IN PHASE 2.
820
+ */
821
+ interface ShadowProbeConfig {
822
+ /** Model id(s) or family alias(es) to shadow-test against the served model, on the same IR. */
823
+ candidates: string | string[];
824
+ /** Probability [0,1] that any given call fires a probe. Default 0.05. */
825
+ sampleRate?: number;
826
+ /**
827
+ * 'off' (Phase 1 default): run candidate + store both responses for an
828
+ * offline batch judge. 'opus': judge candidate-vs-served inline (Phase 2).
829
+ */
830
+ judge?: 'opus' | 'off';
831
+ /** Per-(appId, archetype, candidate) daily cap. Phase 2 (needs brain-count read). Default 20. */
832
+ maxPerDay?: number;
833
+ }
802
834
  interface CallOptions {
803
835
  /** Forwarded to compile(). */
804
836
  policy?: CompilePolicy;
837
+ /**
838
+ * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
839
+ * measures the candidate(s) on the same IR after serving the primary,
840
+ * fire-and-forget. See {@link ShadowProbeConfig}.
841
+ */
842
+ shadowProbe?: ShadowProbeConfig;
805
843
  toolRelevanceThreshold?: number;
806
844
  compressHistoryAfter?: number;
807
845
  /** Override API keys (defaults: process.env). */
@@ -1253,4 +1291,4 @@ interface PerAxisMetrics {
1253
1291
  /** Per-axis metrics keyed by model — used for chain-comparison views. */
1254
1292
  type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1255
1293
 
1256
- export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, 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 MutationApplied as r, type NormalizedTokens as s, type OutcomeKind as t, type PerAxisMetricsByModel as u, type PromptSection as v, type SectionKind as w, type ToolDefinition as x };
1294
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, 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 MutationApplied as r, type NormalizedTokens as s, type OutcomeKind as t, type PerAxisMetricsByModel as u, type PromptSection as v, type SectionKind as w, type ShadowProbeConfig as x, type ToolDefinition as y };
@@ -799,9 +799,47 @@ interface ProviderOverrides {
799
799
  openai?: Record<string, unknown>;
800
800
  deepseek?: Record<string, unknown>;
801
801
  }
802
+ /**
803
+ * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
804
+ *
805
+ * When set on `call()`, after the primary response is served kgauto re-lowers
806
+ * the SAME in-memory PromptIR to each candidate and runs it, persisting a
807
+ * `probe_outcomes` row with `replay_source='inline-full-ir'` and
808
+ * `prompt_fidelity=1.0` — a fair, full-prompt measurement (vs the watchers'
809
+ * lossy `prompt_preview` replay). The probe NEVER blocks the user response and
810
+ * NEVER persists the raw prompt (system/context/payload) — only response
811
+ * previews + metadata, same policy the brain already holds.
812
+ *
813
+ * This is the trustworthy path that earns the right to a quality verdict;
814
+ * `prompt_preview` replay is retired for verdicts (see CLAUDE.md).
815
+ *
816
+ * Phase 1 enforces `sampleRate` and runs the candidate with `judge: 'off'`
817
+ * (responses stored for an offline batch judge). `judge: 'opus'` (inline
818
+ * verdict) and `maxPerDay` (per-tuple daily cap, needs a brain-count read)
819
+ * are accepted by the type but ENFORCED IN PHASE 2.
820
+ */
821
+ interface ShadowProbeConfig {
822
+ /** Model id(s) or family alias(es) to shadow-test against the served model, on the same IR. */
823
+ candidates: string | string[];
824
+ /** Probability [0,1] that any given call fires a probe. Default 0.05. */
825
+ sampleRate?: number;
826
+ /**
827
+ * 'off' (Phase 1 default): run candidate + store both responses for an
828
+ * offline batch judge. 'opus': judge candidate-vs-served inline (Phase 2).
829
+ */
830
+ judge?: 'opus' | 'off';
831
+ /** Per-(appId, archetype, candidate) daily cap. Phase 2 (needs brain-count read). Default 20. */
832
+ maxPerDay?: number;
833
+ }
802
834
  interface CallOptions {
803
835
  /** Forwarded to compile(). */
804
836
  policy?: CompilePolicy;
837
+ /**
838
+ * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
839
+ * measures the candidate(s) on the same IR after serving the primary,
840
+ * fire-and-forget. See {@link ShadowProbeConfig}.
841
+ */
842
+ shadowProbe?: ShadowProbeConfig;
805
843
  toolRelevanceThreshold?: number;
806
844
  compressHistoryAfter?: number;
807
845
  /** Override API keys (defaults: process.env). */
@@ -1253,4 +1291,4 @@ interface PerAxisMetrics {
1253
1291
  /** Per-axis metrics keyed by model — used for chain-comparison views. */
1254
1292
  type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1255
1293
 
1256
- export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, 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 MutationApplied as r, type NormalizedTokens as s, type OutcomeKind as t, type PerAxisMetricsByModel as u, type PromptSection as v, type SectionKind as w, type ToolDefinition as x };
1294
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, 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 MutationApplied as r, type NormalizedTokens as s, type OutcomeKind as t, type PerAxisMetricsByModel as u, type PromptSection as v, type SectionKind as w, type ShadowProbeConfig as x, type ToolDefinition as y };
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-DARjQnvZ.mjs';
1
+ import { k as Provider } from './ir-BBKgsUX7.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-DAUBaPhd.js';
1
+ import { k as Provider } from './ir-D3n-pBYI.js';
2
2
  import { IntentArchetypeName } from './dialect.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { i as Adapter, w as SectionKind } from './ir-DAUBaPhd.js';
1
+ import { i as Adapter, w as SectionKind } from './ir-D3n-pBYI.js';
2
2
 
3
3
  /**
4
4
  * Internal config + hook types for createGlassboxRoutes().
@@ -1,4 +1,4 @@
1
- import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-DAUBaPhd.js';
1
+ import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-D3n-pBYI.js';
2
2
 
3
3
  /**
4
4
  * Glass-Box observability types (alpha.17).
@@ -1,4 +1,4 @@
1
- import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-DARjQnvZ.mjs';
1
+ import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-BBKgsUX7.mjs';
2
2
 
3
3
  /**
4
4
  * Glass-Box observability types (alpha.17).
@@ -1,4 +1,4 @@
1
- import { i as Adapter, w as SectionKind } from './ir-DARjQnvZ.mjs';
1
+ import { i as Adapter, w as SectionKind } from './ir-BBKgsUX7.mjs';
2
2
 
3
3
  /**
4
4
  * Internal config + hook types for createGlassboxRoutes().
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.44",
3
+ "version": "2.0.0-alpha.46",
4
4
  "description": "Prompt compiler + central learning brain for multi-model AI apps. Swap models without rewriting prompts.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",