@warmdrift/kgauto-compiler 2.0.0-alpha.85 → 2.0.0-alpha.87

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.js CHANGED
@@ -61,7 +61,9 @@ __export(index_exports, {
61
61
  STRATEGY_AUTHORSHIP_INDEPENDENT: () => STRATEGY_AUTHORSHIP_INDEPENDENT,
62
62
  STRATEGY_AUTHORSHIP_LIMITATION: () => STRATEGY_AUTHORSHIP_LIMITATION,
63
63
  TRANSLATOR_FLOOR: () => TRANSLATOR_FLOOR,
64
+ _testClearConsumerProfiles: () => _testClearConsumerProfiles,
64
65
  _testResetMeasuredFailure: () => _testResetMeasuredFailure,
66
+ _testResetOutcomeSourceWarning: () => _testResetOutcomeSourceWarning,
65
67
  _testResetPromotions: () => _testResetPromotions,
66
68
  _testWaitForMeasuredFailureRefresh: () => _testWaitForMeasuredFailureRefresh,
67
69
  _testWaitForPromotionsRefresh: () => _testWaitForPromotionsRefresh,
@@ -72,6 +74,8 @@ __export(index_exports, {
72
74
  applySectionRewrites: () => applySectionRewrites,
73
75
  attachCacheControlToStreamTextInput: () => attachCacheControlToStreamTextInput,
74
76
  awaitMeasuredFailureReady: () => awaitMeasuredFailureReady,
77
+ awaitPromotionsReady: () => awaitPromotionsReady,
78
+ bestEffortProfile: () => bestEffortProfile,
75
79
  brainHealth: () => brainHealth,
76
80
  bucketContext: () => bucketContext,
77
81
  bucketHistory: () => bucketHistory,
@@ -126,6 +130,7 @@ __export(index_exports, {
126
130
  getStarterChainWithGrounding: () => getStarterChainWithGrounding,
127
131
  hasMutation: () => hasMutation,
128
132
  hashShape: () => hashShape,
133
+ inferProviderFromId: () => inferProviderFromId,
129
134
  isAltStrategy: () => isAltStrategy,
130
135
  isArchetype: () => isArchetype,
131
136
  isAutoPromoteEnabledFromEnv: () => isAutoPromoteEnabledFromEnv,
@@ -158,6 +163,7 @@ __export(index_exports, {
158
163
  peekBrainDeadLetter: () => peekBrainDeadLetter,
159
164
  planDecomposition: () => planDecomposition,
160
165
  prefetchMeasuredFailure: () => prefetchMeasuredFailure,
166
+ prefetchPromotions: () => prefetchPromotions,
161
167
  probeShadow: () => probeShadow,
162
168
  profileToRow: () => profileToRow,
163
169
  profilesByProvider: () => profilesByProvider,
@@ -166,11 +172,13 @@ __export(index_exports, {
166
172
  recordGoldenIr: () => recordGoldenIr,
167
173
  recordOutcome: () => recordOutcome,
168
174
  recordShadowProbe: () => recordShadowProbe,
175
+ registerProfiles: () => registerProfiles,
169
176
  renderIrForJudge: () => renderIrForJudge,
170
177
  resetTokenizer: () => resetTokenizer,
171
178
  resolveConventionsForProfile: () => resolveConventionsForProfile,
172
179
  resolveGoldenCaptureRate: () => resolveGoldenCaptureRate,
173
180
  resolveModelAlias: () => resolveModelAlias,
181
+ resolveOutcomeSource: () => resolveOutcomeSource,
174
182
  resolvePricingAt: () => resolvePricingAt,
175
183
  resolveProviderKey: () => resolveProviderKey,
176
184
  rowToAdvisory: () => rowToAdvisory,
@@ -197,6 +205,9 @@ var FRESH_SNAPSHOT = {
197
205
  };
198
206
  var snapshot = { ...FRESH_SNAPSHOT };
199
207
  var runtime;
208
+ function configFreshness() {
209
+ return runtime && snapshot.data ? "brain" : "bundled";
210
+ }
200
211
  function configureBrainQuery(rt) {
201
212
  runtime = rt;
202
213
  snapshot = { ...FRESH_SNAPSHOT };
@@ -572,7 +583,7 @@ var PROFILES_RAW = [
572
583
  },
573
584
  {
574
585
  id: "claude-opus-4-7",
575
- verifiedAgainstDocs: "2026-05-08",
586
+ verifiedAgainstDocs: "2026-08-14",
576
587
  provider: "anthropic",
577
588
  status: "legacy",
578
589
  // s76 2026-07-25: docs list as LEGACY (Opus 5 is current). Bundle said current while the brain already said legacy — the two disagreed.
@@ -622,7 +633,7 @@ var PROFILES_RAW = [
622
633
  },
623
634
  {
624
635
  id: "claude-opus-4-6",
625
- verifiedAgainstDocs: "2026-05-08",
636
+ verifiedAgainstDocs: "2026-08-14",
626
637
  provider: "anthropic",
627
638
  status: "legacy",
628
639
  maxContextTokens: 1e6,
@@ -667,7 +678,7 @@ var PROFILES_RAW = [
667
678
  },
668
679
  {
669
680
  id: "claude-sonnet-4-6",
670
- verifiedAgainstDocs: "2026-05-08",
681
+ verifiedAgainstDocs: "2026-08-14",
671
682
  provider: "anthropic",
672
683
  status: "legacy",
673
684
  // s76 2026-07-25: docs list as LEGACY (Sonnet 5 is current).
@@ -708,7 +719,7 @@ var PROFILES_RAW = [
708
719
  },
709
720
  {
710
721
  id: "claude-haiku-4-5",
711
- verifiedAgainstDocs: "2026-05-08",
722
+ verifiedAgainstDocs: "2026-08-14",
712
723
  provider: "anthropic",
713
724
  status: "current",
714
725
  maxContextTokens: 2e5,
@@ -771,7 +782,7 @@ var PROFILES_RAW = [
771
782
  // ── Google ──
772
783
  {
773
784
  id: "gemini-2.5-flash",
774
- verifiedAgainstDocs: "2026-05-08",
785
+ verifiedAgainstDocs: "2026-08-14",
775
786
  provider: "google",
776
787
  status: "current",
777
788
  maxContextTokens: 1048576,
@@ -877,7 +888,7 @@ var PROFILES_RAW = [
877
888
  // thresholds. The brain will validate/relax these as evidence accumulates
878
889
  // per (archetype, model) tuple. Currently ZERO brain rows for this model.
879
890
  id: "gemini-2.5-flash-lite",
880
- verifiedAgainstDocs: "2026-05-13",
891
+ verifiedAgainstDocs: "2026-08-14",
881
892
  provider: "google",
882
893
  status: "current",
883
894
  maxContextTokens: 1048576,
@@ -972,9 +983,21 @@ var PROFILES_RAW = [
972
983
  },
973
984
  {
974
985
  id: "gemini-2.5-pro",
975
- verifiedAgainstDocs: "2026-05-08",
986
+ verifiedAgainstDocs: "2026-08-08",
976
987
  provider: "google",
977
- status: "current",
988
+ // alpha.86 — AVAILABILITY demotion, not a provider-lifecycle mirror.
989
+ // Google's docs still list 2.5-pro as Stable, but the serving layer
990
+ // disagrees per account cohort: tt-intel measured 4/4 refusals
991
+ // ("no longer available to new users", 2026-08-02, their bench), and
992
+ // kgauto's own key 429s on a FreeTier per-day quota (probed
993
+ // 2026-08-08). A chain anchor that hard-fails for whole account
994
+ // cohorts is not an anchor; `legacy` removes it from cost-ordered
995
+ // chains and new selection while keeping the profile resolvable for
996
+ // consumers who pass it explicitly. Re-promotion is one status flip
997
+ // if Google restores availability. The registry cannot yet express
998
+ // account-cohort availability as data — see interfaces/kgauto.md
999
+ // ## Requested 2026-08-02.
1000
+ status: "legacy",
978
1001
  maxContextTokens: 1048576,
979
1002
  maxOutputTokens: 65535,
980
1003
  maxTools: 128,
@@ -1004,7 +1027,7 @@ var PROFILES_RAW = [
1004
1027
  }
1005
1028
  ],
1006
1029
  strengths: ["reasoning", "1m_context", "structured_output", "tool_use"],
1007
- weaknesses: ["pricing_above_200k"],
1030
+ weaknesses: ["pricing_above_200k", "availability_restricted_by_account_cohort"],
1008
1031
  // Master plan §3.3 anchor: tier-2 cross-provider in almost every chain.
1009
1032
  // Sits on the frontier at perf-9 — close to Sonnet but cheaper input.
1010
1033
  archetypePerf: {
@@ -1022,7 +1045,7 @@ var PROFILES_RAW = [
1022
1045
  },
1023
1046
  {
1024
1047
  id: "gemini-3.1-pro-preview",
1025
- verifiedAgainstDocs: "2026-05-08",
1048
+ verifiedAgainstDocs: "2026-08-14",
1026
1049
  provider: "google",
1027
1050
  status: "preview",
1028
1051
  maxContextTokens: 1048576,
@@ -1082,7 +1105,7 @@ var PROFILES_RAW = [
1082
1105
  // deepseek-reasoner registered as aliases (see ALIASES below).
1083
1106
  {
1084
1107
  id: "deepseek-v4-flash",
1085
- verifiedAgainstDocs: "2026-05-08",
1108
+ verifiedAgainstDocs: "2026-08-14",
1086
1109
  provider: "deepseek",
1087
1110
  status: "current",
1088
1111
  maxContextTokens: 1e6,
@@ -1120,7 +1143,7 @@ var PROFILES_RAW = [
1120
1143
  // baseQuality (it carries 'reasoning') with no latency counterweight,
1121
1144
  // leapfrogged gemini-2.5-flash as PB's summarize leader once reachable.
1122
1145
  latencyTier: "slow",
1123
- notes: "Cheap workhorse. 1M context, 384k max output. Cache-hit input $0.0028/M (1/50\xD7 of miss). Aliased as `deepseek-chat` (non-thinking) and `deepseek-reasoner` (thinking) \u2014 see ALIASES.",
1146
+ notes: "Cheap workhorse. 1M context, 384k max output. Cache-hit input $0.0028/M (1/50\xD7 of miss). Aliased as `deepseek-chat` (non-thinking) and `deepseek-reasoner` (thinking) \u2014 see ALIASES. PRICING MODEL CHANGE effective 2026-08-16: DeepSeek moves to peak/off-peak billing, off-peak at HALF the peak rate (docs, fetched 2026-08-14). Encoded prices are peak; cost math for off-peak traffic will overstate by up to 2x until time-of-day pricing is modeled.",
1124
1147
  // Master plan §6.2 anchor. Brain-validated tier 1 cross-provider for
1125
1148
  // classify (169 rows, 0% empty). Tier 0 for summarize-with-no-tools.
1126
1149
  // Falls off on hunt (sequential tools — L-040) and reasoning depth.
@@ -1155,7 +1178,7 @@ var PROFILES_RAW = [
1155
1178
  },
1156
1179
  {
1157
1180
  id: "deepseek-v4-pro",
1158
- verifiedAgainstDocs: "2026-06-22",
1181
+ verifiedAgainstDocs: "2026-08-14",
1159
1182
  provider: "deepseek",
1160
1183
  status: "current",
1161
1184
  maxContextTokens: 1e6,
@@ -1196,7 +1219,7 @@ var PROFILES_RAW = [
1196
1219
  // of the served set. Tag derivation would say 'medium'; the measurement says
1197
1220
  // otherwise.
1198
1221
  latencyTier: "slow",
1199
- notes: "Pro tier. 1M context, 384k max output. $0.435/$0.87 per 1M (cache-hit in $0.003625) \u2014 verified live 2026-06-22; the launch promo became the standing price (no revert). Default mode = thinking.",
1222
+ notes: "Pro tier. 1M context, 384k max output. $0.435/$0.87 per 1M (cache-hit in $0.003625) \u2014 verified live 2026-06-22; the launch promo became the standing price (no revert). Default mode = thinking. PRICING MODEL CHANGE effective 2026-08-16: DeepSeek moves to peak/off-peak billing, off-peak at HALF the peak rate (docs, fetched 2026-08-14). Encoded prices are peak; cost math for off-peak traffic will overstate by up to 2x until time-of-day pricing is modeled.",
1200
1223
  // Master plan §3.3: tier 3 cross-provider for plan chain. Reasoning
1201
1224
  // bumped one notch over V4-Flash; same parallel-tool ceiling.
1202
1225
  archetypePerf: {
@@ -1804,13 +1827,109 @@ var PROFILES_RAW = [
1804
1827
  // +1 vs 2.5-flash — but still below Sonnet/Opus reasoning floor
1805
1828
  }
1806
1829
  },
1830
+ // ─────────────────────────────────────────────────────────────────────────
1831
+ // gemini-3.6-flash — hand-onboarded s86 (2026-08-14), step-zero against
1832
+ // Google docs (models/gemini-3.6-flash page + pricing via catalog-sync's
1833
+ // two-agreeing-extraction the same day). Docs list it as Stable and call
1834
+ // it "previous-generation Flash" (3.5-flash is now "legacy" in Google's
1835
+ // wording) — but kgauto status is 'preview' per the standing entry rule:
1836
+ // a new model enters on capability data verified only at the docs level,
1837
+ // preview is unreachable by starter chains, and promotion to routing
1838
+ // happens through brain evidence, not through Google's marketing tier.
1839
+ // This also means NO family-primary retarget rides this release.
1840
+ // ─────────────────────────────────────────────────────────────────────────
1841
+ {
1842
+ id: "gemini-3.6-flash",
1843
+ verifiedAgainstDocs: "2026-08-14",
1844
+ versionAdded: "2.0.0-alpha.87",
1845
+ provider: "google",
1846
+ status: "preview",
1847
+ maxContextTokens: 1048576,
1848
+ maxOutputTokens: 65536,
1849
+ maxTools: 128,
1850
+ parallelToolCalls: true,
1851
+ structuredOutput: "native",
1852
+ systemPromptMode: "separate",
1853
+ streaming: true,
1854
+ cliffs: [
1855
+ {
1856
+ metric: "input_tokens",
1857
+ threshold: 8e3,
1858
+ action: "downgrade_quality_warning",
1859
+ reason: "Inherited Flash-family guard (2.5\u21923.5 lineage); no 3.6 brain evidence yet"
1860
+ },
1861
+ {
1862
+ metric: "tool_count",
1863
+ threshold: 20,
1864
+ action: "drop_to_top_relevant",
1865
+ reason: "Inherited from Flash family: tool reliability drops above ~20 (despite 128 hard limit). Validate per (archetype, model) after n\u226520."
1866
+ },
1867
+ {
1868
+ metric: "thinking_with_short_output",
1869
+ threshold: 1,
1870
+ action: "force_thinking_budget_zero",
1871
+ reason: "Thinking supported per Google docs; same drain risk as 2.5/3.5-flash \u2014 thinking tokens consume maxOutputTokens"
1872
+ },
1873
+ {
1874
+ metric: "tool_count",
1875
+ threshold: 1,
1876
+ whenIntent: "summarize",
1877
+ action: "strip_tools",
1878
+ reason: "Inherited from 2.5-flash s11 cliff: summarize+tools \u2192 empty response. Preemptive family guard until brain evidence on 3.6-flash specifically."
1879
+ }
1880
+ ],
1881
+ costInputPer1m: 1.5,
1882
+ costOutputPer1m: 7.5,
1883
+ lowering: {
1884
+ ...GOOGLE_LOWERING_BASE,
1885
+ cache: { ...GOOGLE_LOWERING_BASE.cache, discount: 0.1 },
1886
+ thinking: { field: "generationConfig.thinkingConfig.thinkingBudget", default: "auto" }
1887
+ },
1888
+ recovery: [
1889
+ {
1890
+ signal: "empty_response_after_tool",
1891
+ action: "retry_with_params",
1892
+ retryParams: { "generationConfig.thinkingConfig.thinkingBudget": 0 },
1893
+ maxRetries: 1,
1894
+ reason: "Inherited Flash-family pattern: empty after tool result \u2014 retry with thinking off"
1895
+ },
1896
+ {
1897
+ signal: "empty_response",
1898
+ action: "retry_with_params",
1899
+ retryParams: { "generationConfig.thinkingConfig.thinkingBudget": 0 },
1900
+ maxRetries: 1,
1901
+ reason: "Empty response \u2014 try with thinking off"
1902
+ },
1903
+ {
1904
+ signal: "malformed_function_call",
1905
+ action: "escalate",
1906
+ reason: "MALFORMED_FUNCTION_CALL maps to stop \u2014 escalate to next target"
1907
+ }
1908
+ ],
1909
+ strengths: ["agentic_loops", "coding", "1m_context", "parallel_tools", "thinking_mode"],
1910
+ weaknesses: ["no_brain_evidence_yet"],
1911
+ notes: "Hand-onboarded s86 (2026-08-14), step-zero verified: 1,048,576 ctx / 65,536 out (Google model page), $1.50/$7.50 per 1M (catalog-sync two-agreeing-extraction same day \u2014 CHEAPER output than 3.5-flash at $9.00). Docs status Stable; enters kgauto as preview per standing rule (availability != lifecycle, promotion via brain evidence). Function calling + structured outputs + thinking per docs; parallel tools assumed per Flash family (docs silent). First flagged by the release watcher s73; sat in the onboarding queue 18 days \u2014 drained by the s86 catalog-sync run.",
1912
+ archetypePerf: {
1913
+ hunt: 9,
1914
+ // Flash-family parallel-tool tier (L-040); inherited from 3.5-flash
1915
+ classify: 7,
1916
+ summarize: 7,
1917
+ transform: 7,
1918
+ ask: 8,
1919
+ generate: 8,
1920
+ plan: 7,
1921
+ extract: 7,
1922
+ critique: 5
1923
+ }
1924
+ },
1807
1925
  {
1808
1926
  // Auto-onboarded 2026-07-01 from `claude-sonnet-4-6`; VERIFIED 2026-07-02
1809
1927
  // against the claude-api reference (cc-portfolio ratification pass). The
1810
- // clone got context right (1M) and pricing right at sticker ($3/$15
1811
- // NOTE an introductory $2/$10 per MTok runs through 2026-08-31; sticker
1812
- // encoded here per the time-bounded-pricing convention, intro belongs in
1813
- // brain kgauto_pricing if worth capturing). The clone got max output WRONG:
1928
+ // clone got context right (1M). PRICING RE-BASED 2026-08-14 (s86): the
1929
+ // introductory $2/$10 was made PERMANENT Anthropic's pricing page now
1930
+ // states the scheduled Sept-1 increase to $3/$15 "will not occur", so
1931
+ // $2/$10 IS the sticker. (The $3/$15 encoded 07-02 was correct under the
1932
+ // time-bounded-pricing convention at the time; the bound was cancelled.) The clone got max output WRONG:
1814
1933
  // Sonnet 5 is 128k, not 4-6's 64k — corrected. New tokenizer (~30% more
1815
1934
  // tokens for the same text vs 4-6): byte-budget consumers should re-baseline.
1816
1935
  // API quirks (claude-api ref): (a) NON-DEFAULT temperature/top_p/top_k
@@ -1823,7 +1942,7 @@ var PROFILES_RAW = [
1823
1942
  // 'preview' per the Fable precedent — no brain evidence yet; promotion to
1824
1943
  // 'current' is an explicit call. (L-049/L-081.)
1825
1944
  id: "claude-sonnet-5",
1826
- verifiedAgainstDocs: "2026-07-02",
1945
+ verifiedAgainstDocs: "2026-08-14",
1827
1946
  provider: "anthropic",
1828
1947
  status: "current",
1829
1948
  // s76 2026-07-25: GA per docs; was preview.
@@ -1835,8 +1954,9 @@ var PROFILES_RAW = [
1835
1954
  systemPromptMode: "inline",
1836
1955
  streaming: true,
1837
1956
  cliffs: [],
1838
- costInputPer1m: 3,
1839
- costOutputPer1m: 15,
1957
+ costInputPer1m: 2,
1958
+ // 2026-08-14: intro price made PERMANENT (docs: "the previously scheduled increase to $3/$15 on September 1, 2026 will not occur")
1959
+ costOutputPer1m: 10,
1840
1960
  lowering: ANTHROPIC_LOWERING_BASE,
1841
1961
  recovery: [
1842
1962
  { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
@@ -2027,6 +2147,55 @@ function _setProfileBrainHook(hook) {
2027
2147
  function canonicalId(id) {
2028
2148
  return brainHook.resolveAlias?.(id) ?? ALIASES[id] ?? id;
2029
2149
  }
2150
+ var CONSUMER_INDEX = /* @__PURE__ */ new Map();
2151
+ function registerProfiles(profiles) {
2152
+ for (const p of profiles) CONSUMER_INDEX.set(p.id, p);
2153
+ }
2154
+ function _testClearConsumerProfiles() {
2155
+ CONSUMER_INDEX.clear();
2156
+ }
2157
+ function inferProviderFromId(id) {
2158
+ const lower2 = id.toLowerCase();
2159
+ if (lower2.startsWith("claude")) return "anthropic";
2160
+ if (lower2.startsWith("gemini") || lower2.startsWith("palm")) return "google";
2161
+ if (lower2.startsWith("gpt") || /^o[0-9]/.test(lower2) || lower2.startsWith("chatgpt")) return "openai";
2162
+ if (lower2.startsWith("deepseek")) return "deepseek";
2163
+ if (lower2.startsWith("glm")) return "zai";
2164
+ if (lower2.startsWith("kimi") || lower2.startsWith("moonshot")) return "moonshot";
2165
+ return void 0;
2166
+ }
2167
+ function bestEffortProfile(id) {
2168
+ const canonical = canonicalId(id);
2169
+ const existing = tryGetProfile(canonical);
2170
+ if (existing) return existing;
2171
+ const provider = inferProviderFromId(canonical);
2172
+ if (!provider) return void 0;
2173
+ const donor = PROFILES_RAW.find((p) => p.provider === provider && p.status === "current") ?? PROFILES_RAW.find((p) => p.provider === provider);
2174
+ if (!donor) return void 0;
2175
+ const synth = {
2176
+ id: canonical,
2177
+ provider,
2178
+ bestEffort: true,
2179
+ status: "preview",
2180
+ maxContextTokens: 128e3,
2181
+ maxOutputTokens: 4096,
2182
+ maxTools: donor.maxTools,
2183
+ parallelToolCalls: false,
2184
+ structuredOutput: "none",
2185
+ systemPromptMode: donor.systemPromptMode,
2186
+ streaming: donor.streaming,
2187
+ cliffs: [],
2188
+ costInputPer1m: 0,
2189
+ costOutputPer1m: 0,
2190
+ lowering: donor.lowering,
2191
+ recovery: [],
2192
+ strengths: [],
2193
+ weaknesses: ["best-effort synthesized profile \u2014 no verified capability data"],
2194
+ notes: `Synthesized by onUnprofiledModel:'best-effort' (provider ${provider} inferred from id; wire mechanics borrowed from ${donor.id}). No cliffs, no measured knowledge, cost UNKNOWN (recorded as 0). Replace via registerProfiles() for real guards.`
2195
+ };
2196
+ CONSUMER_INDEX.set(canonical, synth);
2197
+ return synth;
2198
+ }
2030
2199
  function resolveModelAlias(id) {
2031
2200
  return canonicalId(id);
2032
2201
  }
@@ -2035,18 +2204,22 @@ var PROFILE_INDEX = new Map(
2035
2204
  );
2036
2205
  function getProfile(id) {
2037
2206
  const canonical = canonicalId(id);
2207
+ const fromConsumer = CONSUMER_INDEX.get(canonical);
2208
+ if (fromConsumer) return fromConsumer;
2038
2209
  const fromBrain = brainHook.getProfile?.(canonical);
2039
2210
  if (fromBrain) return fromBrain;
2040
2211
  const p = PROFILE_INDEX.get(canonical);
2041
2212
  if (!p) {
2042
2213
  const known = [...PROFILE_INDEX.keys(), ...Object.keys(ALIASES)].join(", ");
2043
- throw new Error(`Unknown model id: "${id}". Known: ${known}`);
2214
+ throw new Error(
2215
+ `Unknown model id: "${id}". Known: ${known}. For a model kgauto has not onboarded: registerProfiles([...]) supplies a full profile, or policy.onUnprofiledModel:'best-effort' compiles with guards skipped (alpha.87).`
2216
+ );
2044
2217
  }
2045
2218
  return p;
2046
2219
  }
2047
2220
  function tryGetProfile(id) {
2048
2221
  const canonical = canonicalId(id);
2049
- return brainHook.getProfile?.(canonical) ?? PROFILE_INDEX.get(canonical);
2222
+ return CONSUMER_INDEX.get(canonical) ?? brainHook.getProfile?.(canonical) ?? PROFILE_INDEX.get(canonical);
2050
2223
  }
2051
2224
  function allProfiles() {
2052
2225
  return PROFILES_RAW;
@@ -2325,6 +2498,9 @@ function mapRowsToFindings(rows) {
2325
2498
  return out;
2326
2499
  }
2327
2500
  var snapshots = /* @__PURE__ */ new Map();
2501
+ function exclusionFindingsFreshness(appId) {
2502
+ return snapshots.get(appId)?.loaded ? "warm" : "cold";
2503
+ }
2328
2504
  var runtime2;
2329
2505
  var warnedOnce = false;
2330
2506
  var DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
@@ -2385,6 +2561,7 @@ async function doRefresh2(rt, appId) {
2385
2561
  if (runtime2 !== rt) return;
2386
2562
  const rows = Array.isArray(body) ? mapRowsToFindings(body) : [];
2387
2563
  snap.data = rows;
2564
+ snap.loaded = true;
2388
2565
  snap.expiresAt = Date.now() + rt.ttlMs;
2389
2566
  snap.refreshing = false;
2390
2567
  } catch (err) {
@@ -2848,9 +3025,12 @@ function passApplyCliffs(ir, profile, estimatedInputTokens) {
2848
3025
  if (!triggered) continue;
2849
3026
  switch (cliff.action) {
2850
3027
  case "drop_to_top_relevant": {
2851
- const targetCount = Math.min(
2852
- Math.floor(cliff.threshold * 0.75),
2853
- Math.max(1, Math.floor((nextIR.tools?.length ?? 0) / 2))
3028
+ const targetCount = Math.max(
3029
+ 1,
3030
+ Math.min(
3031
+ Math.floor(cliff.threshold * 0.75),
3032
+ Math.floor((nextIR.tools?.length ?? 0) / 2)
3033
+ )
2854
3034
  );
2855
3035
  if (nextIR.tools && nextIR.tools.length > targetCount) {
2856
3036
  const intent = nextIR.intent.archetype;
@@ -3928,8 +4108,14 @@ var STARTER_CHAINS_GROUNDED = {
3928
4108
  critique: [
3929
4109
  { id: "claude-opus-4-7", grounding: "judgment", reason: "Highest reasoning bar, no degradation tier \u2014 engineer pick, awaiting measured backing" },
3930
4110
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Same-provider walk-down from Opus on 429" },
3931
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor in similar quality bracket" },
3932
- { id: "gpt-5.5", grounding: "judgment", reason: "alpha.16: third-provider frontier-tier floor (archetypePerf=9)" }
4111
+ // alpha.86: gemini-2.5-pro dropped availability-restricted (tt-intel
4112
+ // measured 4/4 cohort refusal 2026-08-02; kgauto key free-tier-quota
4113
+ // 429 2026-08-08). No current Google model clears the critique floor
4114
+ // (3.5-flash critique=5; 3.1-pro-preview scores 10 but is preview —
4115
+ // default chains carry promoted models only). deepseek-v4-pro takes the
4116
+ // third-provider tail instead.
4117
+ { id: "gpt-5.5", grounding: "judgment", reason: "alpha.16: third-provider frontier-tier floor (archetypePerf=9)" },
4118
+ { id: "deepseek-v4-pro", grounding: "judgment", reason: "alpha.86: third-provider tail replacing availability-restricted gemini-2.5-pro \u2014 critique=6 clears the floor exactly; last-resort when Anthropic AND OpenAI are down, not a quality peer of the tiers above" }
3933
4119
  ],
3934
4120
  // alpha.62 (eval spine) — pairwise output comparison. Same reasoning-floor
3935
4121
  // posture as critique (a verdict from a weak judge is worse than no
@@ -3938,14 +4124,16 @@ var STARTER_CHAINS_GROUNDED = {
3938
4124
  judge: [
3939
4125
  { id: "claude-opus-4-8", grounding: "judgment", reason: "Highest reasoning bar for pairwise verdicts \u2014 current opus (s64 roster)" },
3940
4126
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Same-provider walk-down on 429" },
3941
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor in similar quality bracket" },
3942
- { id: "gpt-5.5", grounding: "judgment", reason: "Third-provider frontier-tier floor" }
4127
+ // alpha.86: gemini-2.5-pro dropped (availability-restricted; see critique
4128
+ // note). gpt-5.5 remains the cross-provider frontier floor for verdicts.
4129
+ { id: "gpt-5.5", grounding: "judgment", reason: "Third-provider frontier-tier floor" },
4130
+ { id: "deepseek-v4-pro", grounding: "judgment", reason: "alpha.86: third-provider tail replacing availability-restricted gemini-2.5-pro \u2014 native structured output per the judge contract; last-resort tier" }
3943
4131
  ],
3944
4132
  // Reasoning matters — Sonnet primary; walk UP to Opus on 429.
3945
4133
  plan: [
3946
4134
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Reasoning + cost balance \u2014 engineer pick" },
3947
4135
  { id: "claude-opus-4-7", grounding: "judgment", reason: 'Same-provider walk-UP on 429 (rare exception to "always cheaper")' },
3948
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor" },
4136
+ { id: "gemini-3.5-flash", grounding: "judgment", reason: "alpha.86: cross-provider anchor \u2014 replaces availability-restricted gemini-2.5-pro (tt-intel 4/4 cohort refusal 2026-08-02; probed serving 200 on kgauto key 2026-08-08)" },
3949
4137
  { id: "deepseek-v4-pro", grounding: "judgment", reason: "Tier 3 cost floor \u2014 no brain evidence yet" },
3950
4138
  { id: "gpt-5.4", grounding: "judgment", reason: "alpha.33: third-provider tail (archetypePerf=7) \u2014 closes openai-in-default-fallback-chains" }
3951
4139
  ],
@@ -3953,7 +4141,7 @@ var STARTER_CHAINS_GROUNDED = {
3953
4141
  generate: [
3954
4142
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Quality + cost match \u2014 engineer pick" },
3955
4143
  { id: "claude-haiku-4-5", grounding: "judgment", reason: "Same-provider step-down" },
3956
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor" },
4144
+ { id: "gemini-3.5-flash", grounding: "judgment", reason: "alpha.86: cross-provider anchor \u2014 replaces availability-restricted gemini-2.5-pro (tt-intel 4/4 cohort refusal 2026-08-02; probed serving 200 on kgauto key 2026-08-08)" },
3957
4145
  { id: "gpt-5.4-mini", grounding: "judgment", reason: "alpha.16: third-provider tail (archetypePerf=7) \u2014 closes mono-Anthropic gap" }
3958
4146
  ],
3959
4147
  // ask::sonnet — STARTER_CHAINS calls this "Quality + cost match" but
@@ -3962,7 +4150,7 @@ var STARTER_CHAINS_GROUNDED = {
3962
4150
  ask: [
3963
4151
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Quality + cost match \u2014 engineer pick. NOTE: tt-intel s78 prod showed 27% empty rate; placement awaits measurement validation" },
3964
4152
  { id: "claude-haiku-4-5", grounding: "judgment", reason: "Same-provider step-down" },
3965
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor" },
4153
+ { id: "gemini-3.5-flash", grounding: "judgment", reason: "alpha.86: cross-provider anchor \u2014 replaces availability-restricted gemini-2.5-pro (tt-intel 4/4 cohort refusal 2026-08-02; probed serving 200 on kgauto key 2026-08-08)" },
3966
4154
  { id: "gpt-5.4-mini", grounding: "judgment", reason: "alpha.16: third-provider tail (archetypePerf=7)" }
3967
4155
  ],
3968
4156
  // Structured-output archetype — Flash skipped (alpha.8 MAX_TOKENS cliff,
@@ -3970,14 +4158,14 @@ var STARTER_CHAINS_GROUNDED = {
3970
4158
  extract: [
3971
4159
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Reliable structured-output anchor \u2014 engineer pick" },
3972
4160
  { id: "claude-haiku-4-5", grounding: "judgment", reason: "Same-provider step-down with native structured output" },
3973
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor with structured-output support" },
4161
+ { id: "gemini-3.5-flash", grounding: "judgment", reason: "alpha.86: cross-provider anchor with native structured output \u2014 replaces availability-restricted gemini-2.5-pro" },
3974
4162
  { id: "gpt-5.4", grounding: "capability-fact", reason: "alpha.16: third-provider floor \u2014 native structured-output capability (archetypePerf=8)" }
3975
4163
  ],
3976
4164
  // Forgiving archetype — Sonnet primary but Flash safely floors it.
3977
4165
  transform: [
3978
4166
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Quality anchor \u2014 engineer pick" },
3979
4167
  { id: "claude-haiku-4-5", grounding: "judgment", reason: "Same-provider step-down" },
3980
- { id: "gemini-2.5-pro", grounding: "judgment", reason: "Cross-provider anchor" },
4168
+ { id: "gemini-3.5-flash", grounding: "judgment", reason: "alpha.86: cross-provider anchor \u2014 replaces availability-restricted gemini-2.5-pro (tt-intel 4/4 cohort refusal 2026-08-02; probed serving 200 on kgauto key 2026-08-08)" },
3981
4169
  { id: "gemini-2.5-flash", grounding: "judgment", reason: "Cost floor \u2014 forgiving archetype tolerates Flash" },
3982
4170
  { id: "gpt-5.4-mini", grounding: "judgment", reason: "alpha.33: third-provider tail (archetypePerf=7) \u2014 closes openai-in-default-fallback-chains" }
3983
4171
  ],
@@ -3985,7 +4173,7 @@ var STARTER_CHAINS_GROUNDED = {
3985
4173
  // (capability-fact: Flash 15-75 parallel calls/step vs DeepSeek 7-8).
3986
4174
  hunt: [
3987
4175
  { id: "gemini-2.5-flash", grounding: "capability-fact", reason: "L-040 parallel-tool throughput champion (15-75 calls/step)" },
3988
- { id: "gemini-2.5-pro", grounding: "capability-fact", reason: "Cross-provider tier 1 with strong parallel-tool support" },
4176
+ { id: "gemini-3.5-flash", grounding: "capability-fact", reason: "alpha.86: parallel-tool agentic tier (hunt archetypePerf 9, L-040 family) \u2014 replaces availability-restricted gemini-2.5-pro" },
3989
4177
  { id: "claude-sonnet-4-6", grounding: "judgment", reason: "Quality safety net for blocked-Flash case" },
3990
4178
  { id: "claude-haiku-4-5", grounding: "judgment", reason: "Reduced tool budget \u2014 cliff at 16 fires" },
3991
4179
  { id: "gpt-5.4-mini", grounding: "judgment", reason: "alpha.33: third-provider tail \u2014 OpenAI parallel-tool capable archetype" }
@@ -4033,9 +4221,9 @@ var STARTER_CHAINS_BY_MODE_GROUNDED = {
4033
4221
  reason: "Cross-provider safety net \u2014 Sonnet handles sequential agentic loops cleanly"
4034
4222
  },
4035
4223
  {
4036
- id: "gemini-2.5-pro",
4224
+ id: "gemini-3.5-flash",
4037
4225
  grounding: "judgment",
4038
- reason: "Third-provider tail when no DeepSeek key reachable"
4226
+ reason: "alpha.86: third-provider tail when no DeepSeek key reachable \u2014 replaces availability-restricted gemini-2.5-pro"
4039
4227
  }
4040
4228
  ]
4041
4229
  }
@@ -4331,6 +4519,9 @@ function judgeMeasuredFailure(row, cfg = MEASURED_FAILURE_CFG) {
4331
4519
  };
4332
4520
  }
4333
4521
  var snapshots2 = /* @__PURE__ */ new Map();
4522
+ function measuredFailureFreshness(appId) {
4523
+ return snapshots2.get(appId)?.loaded ? "warm" : "cold";
4524
+ }
4334
4525
  var runtime3;
4335
4526
  var warnedOnce2 = false;
4336
4527
  var DEFAULT_MEASURED_FAILURE_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure";
@@ -4428,6 +4619,7 @@ async function doRefresh3(rt, appId) {
4428
4619
  const body = await res.json();
4429
4620
  if (runtime3 !== rt) return;
4430
4621
  snap.data = Array.isArray(body) ? mapRows(body) : [];
4622
+ snap.loaded = true;
4431
4623
  snap.expiresAt = Date.now() + rt.ttlMs;
4432
4624
  snap.refreshing = false;
4433
4625
  } catch (err) {
@@ -4499,6 +4691,9 @@ function mapRowsToPromotions(rows) {
4499
4691
  return out;
4500
4692
  }
4501
4693
  var snapshots3 = /* @__PURE__ */ new Map();
4694
+ function promotionsFreshness(appId) {
4695
+ return snapshots3.get(appId)?.loaded ? "warm" : "cold";
4696
+ }
4502
4697
  var runtime4;
4503
4698
  var warnedOnce3 = false;
4504
4699
  var DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
@@ -4583,6 +4778,7 @@ async function doRefresh4(rt, appId) {
4583
4778
  if (runtime4 !== rt) return;
4584
4779
  const rows = Array.isArray(body) ? mapRowsToPromotions(body) : [];
4585
4780
  snap.data = rows;
4781
+ snap.loaded = true;
4586
4782
  snap.expiresAt = Date.now() + rt.ttlMs;
4587
4783
  snap.refreshing = false;
4588
4784
  } catch (err) {
@@ -4601,6 +4797,40 @@ function defaultOnError4(err) {
4601
4797
  err
4602
4798
  );
4603
4799
  }
4800
+ function prefetchPromotions(appId) {
4801
+ const rt = runtime4;
4802
+ if (!rt || !appId) return void 0;
4803
+ let snap = snapshots3.get(appId);
4804
+ if (!snap) {
4805
+ snap = { data: [], expiresAt: 0, refreshing: false };
4806
+ snapshots3.set(appId, snap);
4807
+ }
4808
+ if (snap.expiresAt > Date.now()) return void 0;
4809
+ const inflight = pendingRefreshes3.get(appId);
4810
+ if (inflight) return inflight;
4811
+ if (snap.refreshing) return void 0;
4812
+ snap.refreshing = true;
4813
+ void asyncRefresh4(rt, appId);
4814
+ return pendingRefreshes3.get(appId);
4815
+ }
4816
+ async function awaitPromotionsReady(appId, timeoutMs) {
4817
+ if (!runtime4 || !appId) return;
4818
+ const pending = prefetchPromotions(appId) ?? pendingRefreshes3.get(appId);
4819
+ if (!(timeoutMs > 0)) return;
4820
+ if (!pending) return;
4821
+ let timer;
4822
+ try {
4823
+ await Promise.race([
4824
+ pending,
4825
+ new Promise((resolve) => {
4826
+ timer = setTimeout(resolve, timeoutMs);
4827
+ })
4828
+ ]);
4829
+ } catch {
4830
+ } finally {
4831
+ if (timer) clearTimeout(timer);
4832
+ }
4833
+ }
4604
4834
  function _testResetPromotions() {
4605
4835
  runtime4 = void 0;
4606
4836
  snapshots3.clear();
@@ -4649,6 +4879,9 @@ function mapRowsToFindings2(rows) {
4649
4879
  return out;
4650
4880
  }
4651
4881
  var snapshots4 = /* @__PURE__ */ new Map();
4882
+ function promoteReadyFreshness(appId) {
4883
+ return snapshots4.get(appId)?.loaded ? "warm" : "cold";
4884
+ }
4652
4885
  var runtime5;
4653
4886
  var warnedOnce4 = false;
4654
4887
  function isPromoteReadyBrainActive() {
@@ -4707,6 +4940,7 @@ async function doRefresh5(rt, appId) {
4707
4940
  if (runtime5 !== rt) return;
4708
4941
  const rows = Array.isArray(body) ? mapRowsToFindings2(body) : [];
4709
4942
  snap.data = rows;
4943
+ snap.loaded = true;
4710
4944
  snap.expiresAt = Date.now() + rt.ttlMs;
4711
4945
  snap.refreshing = false;
4712
4946
  } catch (err) {
@@ -5131,6 +5365,31 @@ function advisorRuleBlockedModelDrift(ctx) {
5131
5365
  return out;
5132
5366
  }
5133
5367
 
5368
+ // src/advisor-rules/preferred-blocked-overlap.ts
5369
+ var PREFERRED_MODEL_BLOCKED_CODE = "preferred-model-blocked";
5370
+ var DOCS_URL2 = "https://github.com/stue/command-center/blob/main/interfaces/kgauto.md#best-practice-advisories";
5371
+ function advisorRulePreferredBlockedOverlap(ctx) {
5372
+ const preferred = ctx.policy?.preferredModels;
5373
+ const blocked = ctx.policy?.blockedModels;
5374
+ if (!preferred?.length || !blocked?.length) return [];
5375
+ const blockedSet = canonicalPolicySet(blocked);
5376
+ const deadPins = [...new Set(preferred)].filter((p) => policySetHas(blockedSet, p)).sort();
5377
+ if (deadPins.length === 0) return [];
5378
+ const list = deadPins.map((p) => `\`${p}\``).join(", ");
5379
+ const one = deadPins.length === 1;
5380
+ const preferredSet = canonicalPolicySet(preferred);
5381
+ const servedIsPinned = policySetHas(preferredSet, ctx.selectedModelId);
5382
+ return [
5383
+ {
5384
+ level: "warn",
5385
+ code: PREFERRED_MODEL_BLOCKED_CODE,
5386
+ message: `CompilePolicy.preferredModels entr${one ? "y" : "ies"} ${list} ${one ? "is" : "are"} also in \`blockedModels\` (matched canonically, aliases included). A blocked model is hard-rejected before preference boosts apply, so ${one ? "this pin" : "these pins"} can never serve. ` + (servedIsPinned ? `This call was served by \`${ctx.selectedModelId}\`, which is itself a live pin \u2014 the dead entr${one ? "y is" : "ies are"} latent, not currently rerouting traffic.` : `Substitution is your steady state: this call landed on \`${ctx.selectedModelId}\`, which you did not pin.`),
5387
+ suggestion: `Two readings, and kgauto cannot tell them apart: (1) intentional \u2014 your spend gate deliberately outranks the pin, in which case nothing needs doing and you can filter this code; (2) misconfiguration \u2014 the pin and the block were written at different times and the overlap is an accident. tt-intel hit reading (2) on 2026-08-01: a summarize site pinned \`claude-sonnet\` while \`KGAUTO_BLOCKED_MODELS\` carried the same family, and every call silently substituted a reasoning model whose reasoning burn exceeded the site's \`maxOutputTokens\` \u2014 100% empty payloads under HTTP 200. If the block should win, remove the pin so the policy says what it does. If the pin should win, remove ${one ? "the blocking entry" : "the blocking entries"} or re-scope the block to the exact ids you mean. Check what the substitute costs at your input shape while you are here \u2014 a spend gate that lands traffic on a pricier model than the one it blocked is a cost inversion, not a saving.`,
5388
+ docsUrl: DOCS_URL2
5389
+ }
5390
+ ];
5391
+ }
5392
+
5134
5393
  // src/advisor.ts
5135
5394
  var QUALITY_FLOOR_FOR_RECOMMENDATION = 6;
5136
5395
  var TIER_DOWN_COST_RATIO = 0.5;
@@ -5155,6 +5414,12 @@ function runAdvisor(ir, result, profile, policy, phase2) {
5155
5414
  selectedModelId: profile.id
5156
5415
  })
5157
5416
  );
5417
+ out.push(
5418
+ ...advisorRulePreferredBlockedOverlap({
5419
+ policy,
5420
+ selectedModelId: profile.id
5421
+ })
5422
+ );
5158
5423
  if (policy?.posture !== "locked") {
5159
5424
  out.push(...detectCostMismatchedArchetype(ir, profile, phase2));
5160
5425
  out.push(...detectModelStaleEvidence(ir, profile));
@@ -5625,7 +5890,16 @@ function makeHandle() {
5625
5890
  return `c${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
5626
5891
  }
5627
5892
  function compile(ir, opts = {}) {
5628
- const resolver = opts.profileResolver ?? getProfile;
5893
+ const baseResolver = opts.profileResolver ?? getProfile;
5894
+ const resolver = opts.policy?.onUnprofiledModel === "best-effort" ? (id) => {
5895
+ try {
5896
+ return baseResolver(id);
5897
+ } catch (err) {
5898
+ const synth = bestEffortProfile(id);
5899
+ if (!synth) throw err;
5900
+ return synth;
5901
+ }
5902
+ } : baseResolver;
5629
5903
  validateIR(ir);
5630
5904
  ir = resolveModelEntries(ir);
5631
5905
  const sliced = passSlice(ir);
@@ -5685,11 +5959,26 @@ function compile(ir, opts = {}) {
5685
5959
  accumulatedMutations.push(...scores.mutations);
5686
5960
  const target = pickTarget(workingIR, scores.value);
5687
5961
  if (!target) {
5962
+ const unknownIds = scores.value.filter((s) => s.rejectReasons?.includes("unknown_model_id")).map((s) => s.modelId);
5963
+ const uninferable = unknownIds.filter((id) => !inferProviderFromId(id));
5964
+ const unknownHint = unknownIds.length > 0 ? ` Unprofiled model id(s): ${unknownIds.join(", ")}. registerProfiles([...]) supplies a full profile; policy.onUnprofiledModel:'best-effort' compiles with guards skipped.` + (uninferable.length > 0 ? ` Note: provider is not inferable from ${uninferable.join(", ")}, so best-effort cannot lower it \u2014 registerProfiles is the only path for those.` : "") : "";
5688
5965
  throw new Error(
5689
- `compile(): no allowed model fits the request. Scores: ${JSON.stringify(scores.value, null, 2)}`
5966
+ `compile(): no allowed model fits the request.${unknownHint} Scores: ${JSON.stringify(scores.value, null, 2)}`
5690
5967
  );
5691
5968
  }
5692
5969
  const profile = resolver(target.modelId);
5970
+ const bestEffortWarnings = [];
5971
+ if (profile.bestEffort) {
5972
+ bestEffortWarnings.push(
5973
+ `best-effort profile in use for "${profile.id}" (provider ${profile.provider} inferred from the id; wire mechanics borrowed). SKIPPED for this model: cliff guards, recovery rules, measured archetype knowledge, structured-output capability (treated as 'none'), parallel tools (treated as sequential). Cost is UNKNOWN and recorded as $0 \u2014 cost gates and cost attribution are meaningless for this model. registerProfiles() restores real guards.`
5974
+ );
5975
+ accumulatedMutations.push({
5976
+ id: `best_effort_profile_${profile.id}`,
5977
+ source: "best_effort",
5978
+ passName: "resolve-profile",
5979
+ description: `Unprofiled model "${profile.id}" compiled under onUnprofiledModel:'best-effort' \u2014 guards skipped, cost unknown. See diagnostics.cliffWarnings for the full list.`
5980
+ });
5981
+ }
5693
5982
  const fallbackChain = scores.value.filter((s) => s.modelId !== target.modelId && s.fits).sort((a, b) => b.rank - a.rank).map((s) => s.modelId);
5694
5983
  const cliffs = passApplyCliffs(workingIR, profile, inputTokens);
5695
5984
  workingIR = cliffs.value.ir;
@@ -5775,6 +6064,23 @@ function compile(ir, opts = {}) {
5775
6064
  const historyCacheMarkIndex = computeHistoryCacheMarkIndex(workingIR);
5776
6065
  const systemMessages = buildSystemMessages(workingIR, profile.provider);
5777
6066
  const systemCacheMarkIndex = lastCacheableSystemIndex(systemMessages);
6067
+ const keptSectionIds = new Set(workingIR.sections.map((s) => s.id));
6068
+ const cachePrefixActive = lowered.diagnostics.cacheableTokens > 0;
6069
+ const cacheReadFraction = profile.lowering.cache.discount ?? 0.25;
6070
+ const sectionAttribution = ir.sections.map((s) => {
6071
+ const tokens = countTokens(s.text);
6072
+ const kept = keptSectionIds.has(s.id);
6073
+ const estCostUsdFirstCall = kept ? tokens / 1e6 * profile.costInputPer1m : 0;
6074
+ const inActiveCachePrefix = kept && s.cacheable === true && cachePrefixActive;
6075
+ return {
6076
+ id: s.id,
6077
+ tokens,
6078
+ kept,
6079
+ cacheable: s.cacheable === true,
6080
+ estCostUsdFirstCall,
6081
+ estCostUsdWarm: inActiveCachePrefix ? estCostUsdFirstCall * cacheReadFraction : estCostUsdFirstCall
6082
+ };
6083
+ });
5778
6084
  const diagnostics = {
5779
6085
  sectionsKept: workingIR.sections.length,
5780
6086
  sectionsDropped: ir.sections.length - workingIR.sections.length,
@@ -5798,11 +6104,25 @@ function compile(ir, opts = {}) {
5798
6104
  // text the consumer can route on without changing behavior).
5799
6105
  cliffWarnings: [
5800
6106
  ...cliffs.value.loweringHints.qualityWarning ?? [],
5801
- ...conventions.value.cliffWarnings
6107
+ ...conventions.value.cliffWarnings,
6108
+ // alpha.87 — best-effort profile in use (loud on EVERY compile).
6109
+ ...bestEffortWarnings
5802
6110
  ],
5803
6111
  // alpha.68 / Release A — measured discipline gate-token tax (§5.D). 0 when
5804
6112
  // the gate didn't fire.
5805
- disciplineGateTokens
6113
+ disciplineGateTokens,
6114
+ // alpha.87 — per-source freshness stamped at the moment the compile's
6115
+ // reads have all happened, from state each source already tracks (the
6116
+ // "one-line stamp at the point where the source is already known and
6117
+ // discarded" this filing reduced to once alpha.73/.86 warmed the caches).
6118
+ freshness: {
6119
+ config: configFreshness(),
6120
+ measuredFailure: measuredFailureFreshness(ir.appId),
6121
+ promotions: promotionsFreshness(ir.appId),
6122
+ exclusions: exclusionFindingsFreshness(ir.appId),
6123
+ promoteReady: promoteReadyFreshness(ir.appId)
6124
+ },
6125
+ sections: sectionAttribution
5806
6126
  };
5807
6127
  if (ir.intent.archetype === "hunt" && ir.constraints?.toolOrchestration === "sequential") {
5808
6128
  accumulatedMutations.push({
@@ -5967,7 +6287,7 @@ function validateFinalFit(ir, profile, tokens) {
5967
6287
  }
5968
6288
 
5969
6289
  // src/version.ts
5970
- var LIBRARY_VERSION = "2.0.0-alpha.85";
6290
+ var LIBRARY_VERSION = "2.0.0-alpha.87";
5971
6291
 
5972
6292
  // src/pricing-brain.ts
5973
6293
  function isPricingRow(x) {
@@ -6078,6 +6398,12 @@ function configureBrain(config) {
6078
6398
  fetchImpl: config.fetchImpl ?? fetch,
6079
6399
  onError: config.onError
6080
6400
  });
6401
+ if (config.appId) {
6402
+ try {
6403
+ void prefetchPromotions(config.appId);
6404
+ } catch {
6405
+ }
6406
+ }
6081
6407
  } else {
6082
6408
  configurePromotionsBrain(void 0);
6083
6409
  }
@@ -6335,6 +6661,26 @@ function maybeWarnDiscardedCompile(reg, handle) {
6335
6661
  `[kgauto] compile-then-discard: compileForAISDKv6() output for handle ${handle} (archetype=${reg.archetype}, model=${reg.model}) was recorded but neither .system, .model, nor .raw was read before record(). The brain row's mutations_applied / estimated_tokens_in / system_prompt_chars describe a compile that did NOT shape the served call. Pass compiled.system + compiled.model into your generateText/streamText (or use call()). Silence via configureBrain({ warnOnDiscardedCompile: false }).`
6336
6662
  );
6337
6663
  }
6664
+ var OUTCOME_SOURCES = ["canary", "smoke", "eval", "probe", "synthetic"];
6665
+ var warnedInvalidEnvSource = false;
6666
+ function resolveOutcomeSource(explicit) {
6667
+ if (explicit) return explicit;
6668
+ const raw = typeof process !== "undefined" ? process.env?.KGAUTO_SOURCE : void 0;
6669
+ if (!raw) return void 0;
6670
+ const trimmed = raw.trim();
6671
+ if (!trimmed) return void 0;
6672
+ if (OUTCOME_SOURCES.includes(trimmed)) return trimmed;
6673
+ if (!warnedInvalidEnvSource) {
6674
+ warnedInvalidEnvSource = true;
6675
+ console.warn(
6676
+ `[kgauto] KGAUTO_SOURCE="${trimmed}" is not one of ${OUTCOME_SOURCES.join("|")} \u2014 recording as 'synthetic' so the row survives the brain's CHECK constraint and stays out of organic-liveness stats.`
6677
+ );
6678
+ }
6679
+ return "synthetic";
6680
+ }
6681
+ function _testResetOutcomeSourceWarning() {
6682
+ warnedInvalidEnvSource = false;
6683
+ }
6338
6684
  async function record(input) {
6339
6685
  const reg = compileRegistry.get(input.handle);
6340
6686
  if (reg) {
@@ -6449,6 +6795,9 @@ function buildPayload(input, reg) {
6449
6795
  latency_ms: input.latencyMs,
6450
6796
  success: input.success,
6451
6797
  empty_response: input.emptyResponse ?? input.tokensOut === 0,
6798
+ // alpha.87 — explicit source wins; KGAUTO_SOURCE env fills the gap (the
6799
+ // zero-code synthetic self-mark for harness/smoke processes).
6800
+ source: resolveOutcomeSource(input.source),
6452
6801
  error_type: input.errorType,
6453
6802
  tools_called: input.toolsCalled,
6454
6803
  oracle_score: input.oracleScore?.score,
@@ -7848,7 +8197,11 @@ async function call(ir, opts = {}) {
7848
8197
  )
7849
8198
  })
7850
8199
  );
7851
- await awaitMeasuredFailureReady(ir.appId, resolveGateWarmupMs(opts));
8200
+ const warmupMs = resolveGateWarmupMs(opts);
8201
+ await Promise.all([
8202
+ awaitMeasuredFailureReady(ir.appId, warmupMs),
8203
+ awaitPromotionsReady(ir.appId, warmupMs)
8204
+ ]);
7852
8205
  const initial = compileAndRegister(ir, opts);
7853
8206
  safeEmit(
7854
8207
  () => emitCompileDone(traceId, ir.appId, {
@@ -7888,6 +8241,7 @@ async function call(ir, opts = {}) {
7888
8241
  const latencyMs2 = Date.now() - start;
7889
8242
  await record({
7890
8243
  handle: initial.handle,
8244
+ source: opts.source,
7891
8245
  tokensIn: 0,
7892
8246
  tokensOut: 0,
7893
8247
  latencyMs: latencyMs2,
@@ -7940,6 +8294,7 @@ async function call(ir, opts = {}) {
7940
8294
  const latencyMs2 = Date.now() - start;
7941
8295
  await record({
7942
8296
  handle: initial.handle,
8297
+ source: opts.source,
7943
8298
  tokensIn: 0,
7944
8299
  tokensOut: 0,
7945
8300
  latencyMs: latencyMs2,
@@ -8081,6 +8436,7 @@ async function call(ir, opts = {}) {
8081
8436
  const goldenShapeKey = goldenRate > 0 ? peekRegisteredShapeKey(initial.handle) : void 0;
8082
8437
  await record({
8083
8438
  handle: initial.handle,
8439
+ source: opts.source,
8084
8440
  tokensIn: validated.response.tokens.input,
8085
8441
  tokensOut: validated.response.tokens.output,
8086
8442
  latencyMs: latencyMs2,
@@ -8203,6 +8559,7 @@ async function call(ir, opts = {}) {
8203
8559
  const latencyMs = Date.now() - start;
8204
8560
  await record({
8205
8561
  handle: initial.handle,
8562
+ source: opts.source,
8206
8563
  tokensIn: lastErr?.tokens?.input ?? 0,
8207
8564
  tokensOut: lastErr?.tokens?.output ?? 0,
8208
8565
  latencyMs,
@@ -10732,7 +11089,9 @@ function compile2(ir, opts) {
10732
11089
  STRATEGY_AUTHORSHIP_INDEPENDENT,
10733
11090
  STRATEGY_AUTHORSHIP_LIMITATION,
10734
11091
  TRANSLATOR_FLOOR,
11092
+ _testClearConsumerProfiles,
10735
11093
  _testResetMeasuredFailure,
11094
+ _testResetOutcomeSourceWarning,
10736
11095
  _testResetPromotions,
10737
11096
  _testWaitForMeasuredFailureRefresh,
10738
11097
  _testWaitForPromotionsRefresh,
@@ -10743,6 +11102,8 @@ function compile2(ir, opts) {
10743
11102
  applySectionRewrites,
10744
11103
  attachCacheControlToStreamTextInput,
10745
11104
  awaitMeasuredFailureReady,
11105
+ awaitPromotionsReady,
11106
+ bestEffortProfile,
10746
11107
  brainHealth,
10747
11108
  bucketContext,
10748
11109
  bucketHistory,
@@ -10797,6 +11158,7 @@ function compile2(ir, opts) {
10797
11158
  getStarterChainWithGrounding,
10798
11159
  hasMutation,
10799
11160
  hashShape,
11161
+ inferProviderFromId,
10800
11162
  isAltStrategy,
10801
11163
  isArchetype,
10802
11164
  isAutoPromoteEnabledFromEnv,
@@ -10829,6 +11191,7 @@ function compile2(ir, opts) {
10829
11191
  peekBrainDeadLetter,
10830
11192
  planDecomposition,
10831
11193
  prefetchMeasuredFailure,
11194
+ prefetchPromotions,
10832
11195
  probeShadow,
10833
11196
  profileToRow,
10834
11197
  profilesByProvider,
@@ -10837,11 +11200,13 @@ function compile2(ir, opts) {
10837
11200
  recordGoldenIr,
10838
11201
  recordOutcome,
10839
11202
  recordShadowProbe,
11203
+ registerProfiles,
10840
11204
  renderIrForJudge,
10841
11205
  resetTokenizer,
10842
11206
  resolveConventionsForProfile,
10843
11207
  resolveGoldenCaptureRate,
10844
11208
  resolveModelAlias,
11209
+ resolveOutcomeSource,
10845
11210
  resolvePricingAt,
10846
11211
  resolveProviderKey,
10847
11212
  rowToAdvisory,