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

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.
package/dist/index.d.mts CHANGED
@@ -1,7 +1,8 @@
1
- import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-dDcG8Pvu.mjs';
2
- export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-dDcG8Pvu.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-CAlLBu5d.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-CAlLBu5d.mjs';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.mjs';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.mjs';
5
+ export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.mjs';
5
6
  import { IntentArchetypeName } from './dialect.mjs';
6
7
  export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
7
8
 
@@ -536,13 +537,26 @@ interface ShadowProbeRecordInput {
536
537
  /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
537
538
  latencyCandidateMs?: number;
538
539
  /**
539
- * alpha — probe-row class (migration 029). Defaults to `'completed'` (the
540
- * pre-029 row shape: candidate ran, columns populated). `'aborted_latency_budget'`
541
- * and `'skipped_slow_tier_sync'` are DIAGNOSTIC rows from sync-mode latency
542
- * protection no candidate response, no verdict, no false quality signal. A
543
- * verdict rollup MUST filter to `outcome='completed'`.
540
+ * alpha — probe-row class (migration 029; `candidate_error` added by 032).
541
+ * Defaults to `'completed'` (the pre-029 row shape: candidate ran, columns
542
+ * populated). `'aborted_latency_budget'` and `'skipped_slow_tier_sync'` are
543
+ * DIAGNOSTIC rows from sync-mode latency protection; `'candidate_error'`
544
+ * (alpha.53) is the failed-candidate diagnostic — the candidate call
545
+ * errored, with the error class + latency-at-death recorded instead of
546
+ * silence (the IC demo-night probe deaths were invisible for ~90 min under
547
+ * the old record-no-row rule). Diagnostic rows carry no candidate response
548
+ * and no verdict — no false quality signal. A verdict rollup MUST filter to
549
+ * `outcome='completed'`.
544
550
  */
545
- outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync';
551
+ outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
552
+ /**
553
+ * alpha.53 (migration 032) — error class for `outcome='candidate_error'`
554
+ * rows. Values follow execute()'s taxonomy (`rate_limit`, `timeout`,
555
+ * `server_error`, `model_not_found`, `auth`, `invalid_request`, `unknown`)
556
+ * plus `execute_rejected` (the execute promise rejected outright). NULL /
557
+ * omitted on all other row classes.
558
+ */
559
+ errorClass?: string;
546
560
  }
547
561
  /**
548
562
  * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
@@ -574,7 +588,8 @@ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
574
588
  latency_candidate_ms: number | null;
575
589
  prompt_fidelity: number;
576
590
  replay_source: 'inline-full-ir';
577
- outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync';
591
+ outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
592
+ error_class: string | null;
578
593
  };
579
594
  /**
580
595
  * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-rUUojj0s.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-rUUojj0s.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, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-BiXAMyji.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-BiXAMyji.js';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.js';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.js';
5
+ export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.js';
5
6
  import { IntentArchetypeName } from './dialect.js';
6
7
  export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
7
8
 
@@ -536,13 +537,26 @@ interface ShadowProbeRecordInput {
536
537
  /** Wall-clock latency of the candidate replay call, ms (alpha.46). */
537
538
  latencyCandidateMs?: number;
538
539
  /**
539
- * alpha — probe-row class (migration 029). Defaults to `'completed'` (the
540
- * pre-029 row shape: candidate ran, columns populated). `'aborted_latency_budget'`
541
- * and `'skipped_slow_tier_sync'` are DIAGNOSTIC rows from sync-mode latency
542
- * protection no candidate response, no verdict, no false quality signal. A
543
- * verdict rollup MUST filter to `outcome='completed'`.
540
+ * alpha — probe-row class (migration 029; `candidate_error` added by 032).
541
+ * Defaults to `'completed'` (the pre-029 row shape: candidate ran, columns
542
+ * populated). `'aborted_latency_budget'` and `'skipped_slow_tier_sync'` are
543
+ * DIAGNOSTIC rows from sync-mode latency protection; `'candidate_error'`
544
+ * (alpha.53) is the failed-candidate diagnostic — the candidate call
545
+ * errored, with the error class + latency-at-death recorded instead of
546
+ * silence (the IC demo-night probe deaths were invisible for ~90 min under
547
+ * the old record-no-row rule). Diagnostic rows carry no candidate response
548
+ * and no verdict — no false quality signal. A verdict rollup MUST filter to
549
+ * `outcome='completed'`.
544
550
  */
545
- outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync';
551
+ outcome?: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
552
+ /**
553
+ * alpha.53 (migration 032) — error class for `outcome='candidate_error'`
554
+ * rows. Values follow execute()'s taxonomy (`rate_limit`, `timeout`,
555
+ * `server_error`, `model_not_found`, `auth`, `invalid_request`, `unknown`)
556
+ * plus `execute_rejected` (the execute promise rejected outright). NULL /
557
+ * omitted on all other row classes.
558
+ */
559
+ errorClass?: string;
546
560
  }
547
561
  /**
548
562
  * Pure builder for the `probe_outcomes` row written by the inline shadow-probe.
@@ -574,7 +588,8 @@ declare function buildShadowProbeRow(input: ShadowProbeRecordInput): {
574
588
  latency_candidate_ms: number | null;
575
589
  prompt_fidelity: number;
576
590
  replay_source: 'inline-full-ir';
577
- outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync';
591
+ outcome: 'completed' | 'aborted_latency_budget' | 'skipped_slow_tier_sync' | 'candidate_error';
592
+ error_class: string | null;
578
593
  };
579
594
  /**
580
595
  * Persist one inline shadow-probe row to `probe_outcomes`. Fire-and-forget by
package/dist/index.js CHANGED
@@ -51,6 +51,7 @@ __export(index_exports, {
51
51
  compileForAISDKv6: () => compileForAISDKv6,
52
52
  configureBrain: () => configureBrain,
53
53
  countTokens: () => countTokens,
54
+ createBrainForwardRoutes: () => createBrainForwardRoutes,
54
55
  deriveFamilyFromModelId: () => deriveFamilyFromModelId,
55
56
  deriveOwnership: () => deriveOwnership,
56
57
  execute: () => execute,
@@ -1635,6 +1636,63 @@ var PROFILES_RAW = [
1635
1636
  critique: 5
1636
1637
  // +1 vs 2.5-flash — but still below Sonnet/Opus reasoning floor
1637
1638
  }
1639
+ },
1640
+ {
1641
+ // Auto-onboarded 2026-07-01 from `claude-sonnet-4-6`; VERIFIED 2026-07-02
1642
+ // against the claude-api reference (cc-portfolio ratification pass). The
1643
+ // clone got context right (1M) and pricing right at sticker ($3/$15 —
1644
+ // NOTE an introductory $2/$10 per MTok runs through 2026-08-31; sticker
1645
+ // encoded here per the time-bounded-pricing convention, intro belongs in
1646
+ // brain kgauto_pricing if worth capturing). The clone got max output WRONG:
1647
+ // Sonnet 5 is 128k, not 4-6's 64k — corrected. New tokenizer (~30% more
1648
+ // tokens for the same text vs 4-6): byte-budget consumers should re-baseline.
1649
+ // API quirks (claude-api ref): (a) NON-DEFAULT temperature/top_p/top_k
1650
+ // return 400 — moot for kgauto's own call() path (ANTHROPIC_LOWERING_BASE
1651
+ // emits no sampling params) but a REAL hazard for compileForAISDKv6
1652
+ // consumers that pass temperature themselves (tt-intel scoring uses temp:0
1653
+ // for determinism — that 400s on this model; noted to consumers via the
1654
+ // contract). (b) Omitting `thinking` runs ADAPTIVE by default (4-6 ran
1655
+ // thinking-off) — output spend shifts. (c) Supports effort xhigh. status:
1656
+ // 'preview' per the Fable precedent — no brain evidence yet; promotion to
1657
+ // 'current' is an explicit call. (L-049/L-081.)
1658
+ id: "claude-sonnet-5",
1659
+ verifiedAgainstDocs: "2026-07-02",
1660
+ provider: "anthropic",
1661
+ status: "preview",
1662
+ maxContextTokens: 1e6,
1663
+ maxOutputTokens: 128e3,
1664
+ maxTools: 64,
1665
+ parallelToolCalls: true,
1666
+ structuredOutput: "grammar",
1667
+ systemPromptMode: "inline",
1668
+ streaming: true,
1669
+ cliffs: [],
1670
+ costInputPer1m: 3,
1671
+ costOutputPer1m: 15,
1672
+ lowering: ANTHROPIC_LOWERING_BASE,
1673
+ recovery: [
1674
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
1675
+ { signal: "model_not_found", action: "escalate", reason: "Deprecated \u2014 escalate (L-061)" }
1676
+ ],
1677
+ strengths: ["quality", "tool_use", "long_context", "cache_friendly", "extended_thinking"],
1678
+ weaknesses: [],
1679
+ notes: "Sonnet 5 (2026-06): near-Opus quality on coding/agentic work at Sonnet cost. Verified 2026-07-02 against the claude-api reference: 1M ctx, 128k out (clone's 64k corrected), $3/$15 sticker (intro $2/$10 through 2026-08-31). New tokenizer ~30% more tokens vs sonnet-4-6. Consumer hazards: non-default temperature/top_p/top_k 400 (temp:0 rejected \u2014 deterministic-scoring consumers must omit); thinking defaults to adaptive when omitted. status:preview \u2014 no brain evidence yet; earns placement via the machinery.",
1680
+ // Master plan §6.2 anchor. Tier 0 for plan/generate/ask/extract/transform
1681
+ // in starter chains; tier 1 cross-provider for hunt/summarize/classify.
1682
+ archetypePerf: {
1683
+ ask: 9,
1684
+ generate: 9,
1685
+ plan: 9,
1686
+ critique: 9,
1687
+ extract: 9,
1688
+ transform: 9,
1689
+ hunt: 7,
1690
+ // strong but Flash beats on parallel tool throughput
1691
+ summarize: 8,
1692
+ // overkill for tolerant archetype
1693
+ classify: 8
1694
+ // overkill
1695
+ }
1638
1696
  }
1639
1697
  ];
1640
1698
  var ALIASES = {
@@ -4525,7 +4583,7 @@ async function record(input) {
4525
4583
  });
4526
4584
  if (!res.ok) {
4527
4585
  const text = await res.text().catch(() => "<no body>");
4528
- throw new Error(`brain ${res.status}: ${text}`);
4586
+ throw new Error(describeBrainWriteFailure(res.status, "outcomes", text));
4529
4587
  }
4530
4588
  outcomeId = await tryExtractOutcomeId(res);
4531
4589
  } catch (err) {
@@ -4563,6 +4621,11 @@ async function record(input) {
4563
4621
  function defaultOnError5(err) {
4564
4622
  console.warn("[kgauto] brain record failed:", err);
4565
4623
  }
4624
+ function describeBrainWriteFailure(status, route, body) {
4625
+ const base = `brain ${route} ${status}: ${body}`;
4626
+ if (status !== 404 && status !== 405) return base;
4627
+ return `${base} \u2014 likely cause: the brain proxy at your KGAUTO_V2_BRAIN_URL is missing the /${route} forward route. Self-proxying consumers must implement ALL THREE sibling routes (/outcomes, /probe_outcomes, /compile_outcome_quality) \u2014 see interfaces/kgauto.md "Consumer adoption checklist" route-completeness (L-142).`;
4628
+ }
4566
4629
  function buildPayload(input, reg) {
4567
4630
  const compileTarget = reg?.model;
4568
4631
  const actual = input.actualModel ?? compileTarget;
@@ -4691,7 +4754,9 @@ async function recordOutcome(input) {
4691
4754
  });
4692
4755
  if (!res.ok) {
4693
4756
  const text = await res.text().catch(() => "<no body>");
4694
- const err = new Error(`brain ${res.status}: ${text}`);
4757
+ const err = new Error(
4758
+ describeBrainWriteFailure(res.status, "compile_outcome_quality", text)
4759
+ );
4695
4760
  (config.onError ?? defaultOnError5)(err);
4696
4761
  return { ok: false, reason: "persistence_failed" };
4697
4762
  }
@@ -4733,8 +4798,12 @@ function buildShadowProbeRow(input) {
4733
4798
  prompt_fidelity: 1,
4734
4799
  replay_source: "inline-full-ir",
4735
4800
  // alpha — migration 029. 'completed' is the default completed-probe shape;
4736
- // diagnostic rows (aborted/skipped) pass the explicit class.
4737
- outcome: input.outcome ?? "completed"
4801
+ // diagnostic rows (aborted/skipped/errored) pass the explicit class.
4802
+ outcome: input.outcome ?? "completed",
4803
+ // alpha.53 — migration 032. Populated only on candidate_error rows.
4804
+ // Self-proxying consumers must whitelist `error_class` (and `outcome`,
4805
+ // per the alpha.51 PB finding) or diagnostic rows degrade silently.
4806
+ error_class: input.errorClass ?? null
4738
4807
  };
4739
4808
  }
4740
4809
  async function recordShadowProbe(input) {
@@ -4755,7 +4824,7 @@ async function recordShadowProbe(input) {
4755
4824
  });
4756
4825
  if (!res.ok) {
4757
4826
  const text = await res.text().catch(() => "<no body>");
4758
- throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
4827
+ throw new Error(describeBrainWriteFailure(res.status, "probe_outcomes", text));
4759
4828
  }
4760
4829
  } catch (err) {
4761
4830
  (config.onError ?? defaultOnError5)(err);
@@ -6360,7 +6429,7 @@ async function runProbeCandidates(args) {
6360
6429
  const budgetMs = args.cfg.maxLatencyMs ?? DEFAULT_PROBE_MAX_LATENCY_MS;
6361
6430
  const deadline = args.sync ? Date.now() + budgetMs : Number.POSITIVE_INFINITY;
6362
6431
  const skipSlow = args.sync && (args.cfg.skipSlowTierInSync ?? true);
6363
- const recordDiagnostic = async (candidate, outcome) => {
6432
+ const recordDiagnostic = async (candidate, outcome, detail) => {
6364
6433
  await recordShadowProbe({
6365
6434
  appId: args.ir.appId,
6366
6435
  archetype: args.ir.intent.archetype,
@@ -6373,7 +6442,9 @@ async function runProbeCandidates(args) {
6373
6442
  tokensCurrentIn: args.servedResponse.tokens.input,
6374
6443
  tokensCurrentOut: args.servedResponse.tokens.output,
6375
6444
  latencyCurrentMs: args.servedLatencyMs,
6376
- outcome
6445
+ outcome,
6446
+ ...detail?.errorClass ? { errorClass: detail.errorClass } : {},
6447
+ ...detail?.latencyCandidateMs !== void 0 ? { latencyCandidateMs: detail.latencyCandidateMs } : {}
6377
6448
  });
6378
6449
  };
6379
6450
  for (const candidate of candidates) {
@@ -6428,10 +6499,28 @@ async function runProbeCandidates(args) {
6428
6499
  }
6429
6500
  break;
6430
6501
  }
6431
- if (raced.kind === "failed") continue;
6502
+ if (raced.kind === "failed") {
6503
+ try {
6504
+ await recordDiagnostic(candidate, "candidate_error", {
6505
+ errorClass: "execute_rejected",
6506
+ latencyCandidateMs: Date.now() - candStart
6507
+ });
6508
+ } catch {
6509
+ }
6510
+ continue;
6511
+ }
6432
6512
  const exec = raced.exec;
6433
6513
  const candidateLatencyMs = Date.now() - candStart;
6434
- if (!exec.ok) continue;
6514
+ if (!exec.ok) {
6515
+ try {
6516
+ await recordDiagnostic(candidate, "candidate_error", {
6517
+ errorClass: exec.errorCode,
6518
+ latencyCandidateMs: candidateLatencyMs
6519
+ });
6520
+ } catch {
6521
+ }
6522
+ continue;
6523
+ }
6435
6524
  await recordShadowProbe({
6436
6525
  appId: args.ir.appId,
6437
6526
  archetype: args.ir.intent.archetype,
@@ -6673,6 +6762,100 @@ function extractKeptToolNames(result) {
6673
6762
  return names;
6674
6763
  }
6675
6764
 
6765
+ // src/brain-proxy.ts
6766
+ var SEGMENT_TO_TABLE = {
6767
+ outcomes: "compile_outcomes",
6768
+ compile_outcome_advisories: "compile_outcome_advisories",
6769
+ compile_outcome_quality: "compile_outcome_quality",
6770
+ probe_outcomes: "probe_outcomes"
6771
+ };
6772
+ var KNOWN_SEGMENTS = Object.keys(SEGMENT_TO_TABLE);
6773
+ var JSON_HEADERS = { "Content-Type": "application/json" };
6774
+ function jsonResponse(status, body) {
6775
+ return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
6776
+ }
6777
+ function bearerOf(req) {
6778
+ const header = req.headers.get("Authorization") ?? "";
6779
+ const match = /^Bearer\s+(.+)$/i.exec(header);
6780
+ return match?.[1]?.trim() ?? "";
6781
+ }
6782
+ function requireString(name, value) {
6783
+ if (typeof value !== "string" || value.length === 0) {
6784
+ throw new Error(`createBrainForwardRoutes: ${name} is required`);
6785
+ }
6786
+ return value;
6787
+ }
6788
+ function createBrainForwardRoutes(config) {
6789
+ const ingestSecret = requireString("ingestSecret", config.ingestSecret);
6790
+ const brainUrl = requireString("brainUrl", config.brainUrl).replace(/\/+$/, "");
6791
+ const serviceKey = requireString("serviceKey", config.serviceKey);
6792
+ const fetchFn = config.fetchImpl ?? fetch;
6793
+ async function handle(req, segment) {
6794
+ try {
6795
+ if (req.method !== "POST") {
6796
+ return jsonResponse(405, {
6797
+ error: "method-not-allowed",
6798
+ method: req.method,
6799
+ allowed: ["POST"]
6800
+ });
6801
+ }
6802
+ const table = SEGMENT_TO_TABLE[segment];
6803
+ if (!table) {
6804
+ return jsonResponse(404, {
6805
+ error: "unknown-brain-forward-segment",
6806
+ segment,
6807
+ known: KNOWN_SEGMENTS
6808
+ });
6809
+ }
6810
+ if (bearerOf(req) !== ingestSecret) {
6811
+ return jsonResponse(401, { error: "unauthorized" });
6812
+ }
6813
+ let body;
6814
+ try {
6815
+ body = await req.json();
6816
+ } catch {
6817
+ return jsonResponse(400, { error: "invalid-json" });
6818
+ }
6819
+ const row = Array.isArray(body) ? body : { ...body };
6820
+ let brainRes;
6821
+ try {
6822
+ brainRes = await fetchFn(`${brainUrl}/rest/v1/${table}`, {
6823
+ method: "POST",
6824
+ headers: {
6825
+ apikey: serviceKey,
6826
+ Authorization: `Bearer ${serviceKey}`,
6827
+ "Content-Type": "application/json",
6828
+ Prefer: "return=minimal"
6829
+ },
6830
+ body: JSON.stringify(row)
6831
+ });
6832
+ } catch (err) {
6833
+ return jsonResponse(502, {
6834
+ error: "brain-unreachable",
6835
+ table,
6836
+ detail: err instanceof Error ? err.message : String(err)
6837
+ });
6838
+ }
6839
+ if (brainRes.ok) {
6840
+ return jsonResponse(201, { ok: true });
6841
+ }
6842
+ const text = await brainRes.text().catch(() => "<no body>");
6843
+ return jsonResponse(brainRes.status, {
6844
+ error: "brain-write-failed",
6845
+ table,
6846
+ status: brainRes.status,
6847
+ detail: text
6848
+ });
6849
+ } catch (err) {
6850
+ return jsonResponse(500, {
6851
+ error: "brain-forward-internal-error",
6852
+ detail: err instanceof Error ? err.message : String(err)
6853
+ });
6854
+ }
6855
+ }
6856
+ return { handle, segments: KNOWN_SEGMENTS };
6857
+ }
6858
+
6676
6859
  // src/oracle.ts
6677
6860
  var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
6678
6861
  var judgeCallTimes = [];
@@ -7132,6 +7315,7 @@ function compile2(ir, opts) {
7132
7315
  compileForAISDKv6,
7133
7316
  configureBrain,
7134
7317
  countTokens,
7318
+ createBrainForwardRoutes,
7135
7319
  deriveFamilyFromModelId,
7136
7320
  deriveOwnership,
7137
7321
  execute,
package/dist/index.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import {
2
+ createBrainForwardRoutes
3
+ } from "./chunk-NGPB3D53.mjs";
1
4
  import {
2
5
  ALL_ARCHETYPES,
3
6
  DIALECT_VERSION,
@@ -33,7 +36,7 @@ import {
33
36
  loadChainsFromBrain,
34
37
  readBrainReadEnv,
35
38
  resolveProviderKey
36
- } from "./chunk-HHWBB46W.mjs";
39
+ } from "./chunk-IIMPJZNH.mjs";
37
40
  import {
38
41
  ALIASES,
39
42
  LATENCY_TIER_MS,
@@ -44,7 +47,7 @@ import {
44
47
  latencyTierOf,
45
48
  profilesByProvider,
46
49
  tryGetProfile
47
- } from "./chunk-CXH7KC4D.mjs";
50
+ } from "./chunk-QKXTMVCT.mjs";
48
51
  import {
49
52
  emitAdvisoryFired,
50
53
  emitCompileDone,
@@ -2736,7 +2739,7 @@ async function record(input) {
2736
2739
  });
2737
2740
  if (!res.ok) {
2738
2741
  const text = await res.text().catch(() => "<no body>");
2739
- throw new Error(`brain ${res.status}: ${text}`);
2742
+ throw new Error(describeBrainWriteFailure(res.status, "outcomes", text));
2740
2743
  }
2741
2744
  outcomeId = await tryExtractOutcomeId(res);
2742
2745
  } catch (err) {
@@ -2774,6 +2777,11 @@ async function record(input) {
2774
2777
  function defaultOnError4(err) {
2775
2778
  console.warn("[kgauto] brain record failed:", err);
2776
2779
  }
2780
+ function describeBrainWriteFailure(status, route, body) {
2781
+ const base = `brain ${route} ${status}: ${body}`;
2782
+ if (status !== 404 && status !== 405) return base;
2783
+ return `${base} \u2014 likely cause: the brain proxy at your KGAUTO_V2_BRAIN_URL is missing the /${route} forward route. Self-proxying consumers must implement ALL THREE sibling routes (/outcomes, /probe_outcomes, /compile_outcome_quality) \u2014 see interfaces/kgauto.md "Consumer adoption checklist" route-completeness (L-142).`;
2784
+ }
2777
2785
  function buildPayload(input, reg) {
2778
2786
  const compileTarget = reg?.model;
2779
2787
  const actual = input.actualModel ?? compileTarget;
@@ -2902,7 +2910,9 @@ async function recordOutcome(input) {
2902
2910
  });
2903
2911
  if (!res.ok) {
2904
2912
  const text = await res.text().catch(() => "<no body>");
2905
- const err = new Error(`brain ${res.status}: ${text}`);
2913
+ const err = new Error(
2914
+ describeBrainWriteFailure(res.status, "compile_outcome_quality", text)
2915
+ );
2906
2916
  (config.onError ?? defaultOnError4)(err);
2907
2917
  return { ok: false, reason: "persistence_failed" };
2908
2918
  }
@@ -2944,8 +2954,12 @@ function buildShadowProbeRow(input) {
2944
2954
  prompt_fidelity: 1,
2945
2955
  replay_source: "inline-full-ir",
2946
2956
  // alpha — migration 029. 'completed' is the default completed-probe shape;
2947
- // diagnostic rows (aborted/skipped) pass the explicit class.
2948
- outcome: input.outcome ?? "completed"
2957
+ // diagnostic rows (aborted/skipped/errored) pass the explicit class.
2958
+ outcome: input.outcome ?? "completed",
2959
+ // alpha.53 — migration 032. Populated only on candidate_error rows.
2960
+ // Self-proxying consumers must whitelist `error_class` (and `outcome`,
2961
+ // per the alpha.51 PB finding) or diagnostic rows degrade silently.
2962
+ error_class: input.errorClass ?? null
2949
2963
  };
2950
2964
  }
2951
2965
  async function recordShadowProbe(input) {
@@ -2966,7 +2980,7 @@ async function recordShadowProbe(input) {
2966
2980
  });
2967
2981
  if (!res.ok) {
2968
2982
  const text = await res.text().catch(() => "<no body>");
2969
- throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
2983
+ throw new Error(describeBrainWriteFailure(res.status, "probe_outcomes", text));
2970
2984
  }
2971
2985
  } catch (err) {
2972
2986
  (config.onError ?? defaultOnError4)(err);
@@ -3856,7 +3870,7 @@ async function runProbeCandidates(args) {
3856
3870
  const budgetMs = args.cfg.maxLatencyMs ?? DEFAULT_PROBE_MAX_LATENCY_MS;
3857
3871
  const deadline = args.sync ? Date.now() + budgetMs : Number.POSITIVE_INFINITY;
3858
3872
  const skipSlow = args.sync && (args.cfg.skipSlowTierInSync ?? true);
3859
- const recordDiagnostic = async (candidate, outcome) => {
3873
+ const recordDiagnostic = async (candidate, outcome, detail) => {
3860
3874
  await recordShadowProbe({
3861
3875
  appId: args.ir.appId,
3862
3876
  archetype: args.ir.intent.archetype,
@@ -3869,7 +3883,9 @@ async function runProbeCandidates(args) {
3869
3883
  tokensCurrentIn: args.servedResponse.tokens.input,
3870
3884
  tokensCurrentOut: args.servedResponse.tokens.output,
3871
3885
  latencyCurrentMs: args.servedLatencyMs,
3872
- outcome
3886
+ outcome,
3887
+ ...detail?.errorClass ? { errorClass: detail.errorClass } : {},
3888
+ ...detail?.latencyCandidateMs !== void 0 ? { latencyCandidateMs: detail.latencyCandidateMs } : {}
3873
3889
  });
3874
3890
  };
3875
3891
  for (const candidate of candidates) {
@@ -3924,10 +3940,28 @@ async function runProbeCandidates(args) {
3924
3940
  }
3925
3941
  break;
3926
3942
  }
3927
- if (raced.kind === "failed") continue;
3943
+ if (raced.kind === "failed") {
3944
+ try {
3945
+ await recordDiagnostic(candidate, "candidate_error", {
3946
+ errorClass: "execute_rejected",
3947
+ latencyCandidateMs: Date.now() - candStart
3948
+ });
3949
+ } catch {
3950
+ }
3951
+ continue;
3952
+ }
3928
3953
  const exec = raced.exec;
3929
3954
  const candidateLatencyMs = Date.now() - candStart;
3930
- if (!exec.ok) continue;
3955
+ if (!exec.ok) {
3956
+ try {
3957
+ await recordDiagnostic(candidate, "candidate_error", {
3958
+ errorClass: exec.errorCode,
3959
+ latencyCandidateMs: candidateLatencyMs
3960
+ });
3961
+ } catch {
3962
+ }
3963
+ continue;
3964
+ }
3931
3965
  await recordShadowProbe({
3932
3966
  appId: args.ir.appId,
3933
3967
  archetype: args.ir.intent.archetype,
@@ -4627,6 +4661,7 @@ export {
4627
4661
  compileForAISDKv6,
4628
4662
  configureBrain,
4629
4663
  countTokens,
4664
+ createBrainForwardRoutes,
4630
4665
  deriveFamilyFromModelId,
4631
4666
  deriveOwnership,
4632
4667
  execute,
@@ -1216,7 +1216,16 @@ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned'
1216
1216
  * outcomes accumulate.
1217
1217
  */
1218
1218
  interface RecordOutcomeInput {
1219
- /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1219
+ /**
1220
+ * Joins to compile_outcomes.id. Pass the compile `handle` string
1221
+ * (CompileResult.handle / CallResult.handle) — consumer proxies resolve
1222
+ * handle → compile_outcomes.id via the `compile_outcomes.handle` column
1223
+ * (reference implementations: PB `api/kgauto-v2/compile_outcome_quality.js`,
1224
+ * tt-intel/IC `app/api/kgauto/v2/compile_outcome_quality/route.ts`). A
1225
+ * numeric compile_outcomes.id also works if the caller already has it.
1226
+ * (There is no `CompileResult.outcomeId` field — the brain assigns the row
1227
+ * id at insert; `handle` is the consumer-visible correlator.)
1228
+ */
1220
1229
  outcomeId: number | string;
1221
1230
  /** What did the user / system do with this output? */
1222
1231
  outcome: OutcomeKind;
@@ -1216,7 +1216,16 @@ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned'
1216
1216
  * outcomes accumulate.
1217
1217
  */
1218
1218
  interface RecordOutcomeInput {
1219
- /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1219
+ /**
1220
+ * Joins to compile_outcomes.id. Pass the compile `handle` string
1221
+ * (CompileResult.handle / CallResult.handle) — consumer proxies resolve
1222
+ * handle → compile_outcomes.id via the `compile_outcomes.handle` column
1223
+ * (reference implementations: PB `api/kgauto-v2/compile_outcome_quality.js`,
1224
+ * tt-intel/IC `app/api/kgauto/v2/compile_outcome_quality/route.ts`). A
1225
+ * numeric compile_outcomes.id also works if the caller already has it.
1226
+ * (There is no `CompileResult.outcomeId` field — the brain assigns the row
1227
+ * id at insert; `handle` is the consumer-visible correlator.)
1228
+ */
1220
1229
  outcomeId: number | string;
1221
1230
  /** What did the user / system do with this output? */
1222
1231
  outcome: OutcomeKind;
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-dDcG8Pvu.mjs';
1
+ import { k as Provider } from './ir-CAlLBu5d.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-rUUojj0s.js';
1
+ import { k as Provider } from './ir-BiXAMyji.js';
2
2
  import { IntentArchetypeName } from './dialect.js';
3
3
 
4
4
  /**
package/dist/profiles.js CHANGED
@@ -1388,6 +1388,63 @@ var PROFILES_RAW = [
1388
1388
  critique: 5
1389
1389
  // +1 vs 2.5-flash — but still below Sonnet/Opus reasoning floor
1390
1390
  }
1391
+ },
1392
+ {
1393
+ // Auto-onboarded 2026-07-01 from `claude-sonnet-4-6`; VERIFIED 2026-07-02
1394
+ // against the claude-api reference (cc-portfolio ratification pass). The
1395
+ // clone got context right (1M) and pricing right at sticker ($3/$15 —
1396
+ // NOTE an introductory $2/$10 per MTok runs through 2026-08-31; sticker
1397
+ // encoded here per the time-bounded-pricing convention, intro belongs in
1398
+ // brain kgauto_pricing if worth capturing). The clone got max output WRONG:
1399
+ // Sonnet 5 is 128k, not 4-6's 64k — corrected. New tokenizer (~30% more
1400
+ // tokens for the same text vs 4-6): byte-budget consumers should re-baseline.
1401
+ // API quirks (claude-api ref): (a) NON-DEFAULT temperature/top_p/top_k
1402
+ // return 400 — moot for kgauto's own call() path (ANTHROPIC_LOWERING_BASE
1403
+ // emits no sampling params) but a REAL hazard for compileForAISDKv6
1404
+ // consumers that pass temperature themselves (tt-intel scoring uses temp:0
1405
+ // for determinism — that 400s on this model; noted to consumers via the
1406
+ // contract). (b) Omitting `thinking` runs ADAPTIVE by default (4-6 ran
1407
+ // thinking-off) — output spend shifts. (c) Supports effort xhigh. status:
1408
+ // 'preview' per the Fable precedent — no brain evidence yet; promotion to
1409
+ // 'current' is an explicit call. (L-049/L-081.)
1410
+ id: "claude-sonnet-5",
1411
+ verifiedAgainstDocs: "2026-07-02",
1412
+ provider: "anthropic",
1413
+ status: "preview",
1414
+ maxContextTokens: 1e6,
1415
+ maxOutputTokens: 128e3,
1416
+ maxTools: 64,
1417
+ parallelToolCalls: true,
1418
+ structuredOutput: "grammar",
1419
+ systemPromptMode: "inline",
1420
+ streaming: true,
1421
+ cliffs: [],
1422
+ costInputPer1m: 3,
1423
+ costOutputPer1m: 15,
1424
+ lowering: ANTHROPIC_LOWERING_BASE,
1425
+ recovery: [
1426
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
1427
+ { signal: "model_not_found", action: "escalate", reason: "Deprecated \u2014 escalate (L-061)" }
1428
+ ],
1429
+ strengths: ["quality", "tool_use", "long_context", "cache_friendly", "extended_thinking"],
1430
+ weaknesses: [],
1431
+ notes: "Sonnet 5 (2026-06): near-Opus quality on coding/agentic work at Sonnet cost. Verified 2026-07-02 against the claude-api reference: 1M ctx, 128k out (clone's 64k corrected), $3/$15 sticker (intro $2/$10 through 2026-08-31). New tokenizer ~30% more tokens vs sonnet-4-6. Consumer hazards: non-default temperature/top_p/top_k 400 (temp:0 rejected \u2014 deterministic-scoring consumers must omit); thinking defaults to adaptive when omitted. status:preview \u2014 no brain evidence yet; earns placement via the machinery.",
1432
+ // Master plan §6.2 anchor. Tier 0 for plan/generate/ask/extract/transform
1433
+ // in starter chains; tier 1 cross-provider for hunt/summarize/classify.
1434
+ archetypePerf: {
1435
+ ask: 9,
1436
+ generate: 9,
1437
+ plan: 9,
1438
+ critique: 9,
1439
+ extract: 9,
1440
+ transform: 9,
1441
+ hunt: 7,
1442
+ // strong but Flash beats on parallel tool throughput
1443
+ summarize: 8,
1444
+ // overkill for tolerant archetype
1445
+ classify: 8
1446
+ // overkill
1447
+ }
1391
1448
  }
1392
1449
  ];
1393
1450
  var ALIASES = {
package/dist/profiles.mjs CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  latencyTierOf,
9
9
  profilesByProvider,
10
10
  tryGetProfile
11
- } from "./chunk-CXH7KC4D.mjs";
11
+ } from "./chunk-QKXTMVCT.mjs";
12
12
  export {
13
13
  ALIASES,
14
14
  LATENCY_TIER_MS,