@warmdrift/kgauto-compiler 2.0.0-alpha.67 → 2.0.0-alpha.69

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.
@@ -56,6 +56,11 @@ var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
56
56
  function isArchetype(name) {
57
57
  return name in INTENT_ARCHETYPES;
58
58
  }
59
+ function resolveOutputMode(args) {
60
+ if (args.declared) return args.declared;
61
+ if (args.structuredOutput === true) return "json";
62
+ return args.toolCount > 0 ? "tool_call" : "text";
63
+ }
59
64
  function bucketContext(tokens) {
60
65
  if (tokens < 1e3) return "tiny";
61
66
  if (tokens < 4e3) return "small";
@@ -92,6 +97,7 @@ export {
92
97
  INTENT_ARCHETYPES,
93
98
  ALL_ARCHETYPES,
94
99
  isArchetype,
100
+ resolveOutputMode,
95
101
  bucketContext,
96
102
  bucketToolCount,
97
103
  bucketHistory,
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var LIBRARY_VERSION = "2.0.0-alpha.67";
2
+ var LIBRARY_VERSION = "2.0.0-alpha.69";
3
3
 
4
4
  // src/key-health.ts
5
5
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -94,6 +94,32 @@ interface ShapeSignature {
94
94
  /** Whether the prompt includes few-shot examples. */
95
95
  hasExamples: boolean;
96
96
  }
97
+ /**
98
+ * SINGLE source of truth for a call's output shape.
99
+ *
100
+ * Two independent expressions of this concept used to exist — `computeShape`
101
+ * (three-valued, feeding `compile_outcomes.shape_key`) and compile()'s Factor C
102
+ * screen (two-valued). They disagreed on exactly one case: tools present with
103
+ * no `structuredOutput`, which the shape signature calls `tool_call` and the
104
+ * screen called `text`. That gap let alpha.68's shape-altering discipline gates
105
+ * fire on tool-call surfaces — the surface class the design contract names as
106
+ * forbidden, because labelling claims inside a tool-call envelope manufactures
107
+ * the structured-output violations alpha.66 ships a retry for.
108
+ *
109
+ * A consumer `declared` value WINS over inference. The inference cannot see
110
+ * that an agentic surface carrying tools ultimately emits prose, so it is
111
+ * deliberately conservative — wrongly firing a shape-altering rule breaks a
112
+ * parser, wrongly withholding one only forgoes a lift. `constraints.outputMode`
113
+ * is the escape hatch for surfaces that know better.
114
+ *
115
+ * Takes the facts rather than a `PromptIR` so `dialect.ts` stays
116
+ * dependency-free (`ir.ts` imports THIS module, not the reverse).
117
+ */
118
+ declare function resolveOutputMode(args: {
119
+ declared?: OutputMode;
120
+ structuredOutput?: boolean;
121
+ toolCount: number;
122
+ }): OutputMode;
97
123
  declare function bucketContext(tokens: number): ContextBucket;
98
124
  declare function bucketToolCount(count: number): ToolCountBucket;
99
125
  declare function bucketHistory(turnCount: number): HistoryDepth;
@@ -108,4 +134,4 @@ declare function hashShape(s: ShapeSignature): string;
108
134
  */
109
135
  declare function learningKey(archetype: IntentArchetypeName, model: string, shape: ShapeSignature): string;
110
136
 
111
- export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey };
137
+ export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey, resolveOutputMode };
package/dist/dialect.d.ts CHANGED
@@ -94,6 +94,32 @@ interface ShapeSignature {
94
94
  /** Whether the prompt includes few-shot examples. */
95
95
  hasExamples: boolean;
96
96
  }
97
+ /**
98
+ * SINGLE source of truth for a call's output shape.
99
+ *
100
+ * Two independent expressions of this concept used to exist — `computeShape`
101
+ * (three-valued, feeding `compile_outcomes.shape_key`) and compile()'s Factor C
102
+ * screen (two-valued). They disagreed on exactly one case: tools present with
103
+ * no `structuredOutput`, which the shape signature calls `tool_call` and the
104
+ * screen called `text`. That gap let alpha.68's shape-altering discipline gates
105
+ * fire on tool-call surfaces — the surface class the design contract names as
106
+ * forbidden, because labelling claims inside a tool-call envelope manufactures
107
+ * the structured-output violations alpha.66 ships a retry for.
108
+ *
109
+ * A consumer `declared` value WINS over inference. The inference cannot see
110
+ * that an agentic surface carrying tools ultimately emits prose, so it is
111
+ * deliberately conservative — wrongly firing a shape-altering rule breaks a
112
+ * parser, wrongly withholding one only forgoes a lift. `constraints.outputMode`
113
+ * is the escape hatch for surfaces that know better.
114
+ *
115
+ * Takes the facts rather than a `PromptIR` so `dialect.ts` stays
116
+ * dependency-free (`ir.ts` imports THIS module, not the reverse).
117
+ */
118
+ declare function resolveOutputMode(args: {
119
+ declared?: OutputMode;
120
+ structuredOutput?: boolean;
121
+ toolCount: number;
122
+ }): OutputMode;
97
123
  declare function bucketContext(tokens: number): ContextBucket;
98
124
  declare function bucketToolCount(count: number): ToolCountBucket;
99
125
  declare function bucketHistory(turnCount: number): HistoryDepth;
@@ -108,4 +134,4 @@ declare function hashShape(s: ShapeSignature): string;
108
134
  */
109
135
  declare function learningKey(archetype: IntentArchetypeName, model: string, shape: ShapeSignature): string;
110
136
 
111
- export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey };
137
+ export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey, resolveOutputMode };
package/dist/dialect.js CHANGED
@@ -28,7 +28,8 @@ __export(dialect_exports, {
28
28
  bucketToolCount: () => bucketToolCount,
29
29
  hashShape: () => hashShape,
30
30
  isArchetype: () => isArchetype,
31
- learningKey: () => learningKey
31
+ learningKey: () => learningKey,
32
+ resolveOutputMode: () => resolveOutputMode
32
33
  });
33
34
  module.exports = __toCommonJS(dialect_exports);
34
35
  var DIALECT_VERSION = "v1";
@@ -88,6 +89,11 @@ var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
88
89
  function isArchetype(name) {
89
90
  return name in INTENT_ARCHETYPES;
90
91
  }
92
+ function resolveOutputMode(args) {
93
+ if (args.declared) return args.declared;
94
+ if (args.structuredOutput === true) return "json";
95
+ return args.toolCount > 0 ? "tool_call" : "text";
96
+ }
91
97
  function bucketContext(tokens) {
92
98
  if (tokens < 1e3) return "tiny";
93
99
  if (tokens < 4e3) return "small";
@@ -128,5 +134,6 @@ function learningKey(archetype, model, shape) {
128
134
  bucketToolCount,
129
135
  hashShape,
130
136
  isArchetype,
131
- learningKey
137
+ learningKey,
138
+ resolveOutputMode
132
139
  });
package/dist/dialect.mjs CHANGED
@@ -7,8 +7,9 @@ import {
7
7
  bucketToolCount,
8
8
  hashShape,
9
9
  isArchetype,
10
- learningKey
11
- } from "./chunk-3KQAID63.mjs";
10
+ learningKey,
11
+ resolveOutputMode
12
+ } from "./chunk-BVEXV5KC.mjs";
12
13
  export {
13
14
  ALL_ARCHETYPES,
14
15
  DIALECT_VERSION,
@@ -18,5 +19,6 @@ export {
18
19
  bucketToolCount,
19
20
  hashShape,
20
21
  isArchetype,
21
- learningKey
22
+ learningKey,
23
+ resolveOutputMode
22
24
  };
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-8pWRDbUg.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-8pWRDbUg.mjs';
3
- import '../ir-BTvyl8-w.mjs';
1
+ import { G as GlassboxEvent } from '../types-DsEq35WY.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-DsEq35WY.mjs';
3
+ import '../ir-Bqn1RVdV.mjs';
4
4
  import '../dialect.mjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { G as GlassboxEvent } from '../types-BdYlJz0Z.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-BdYlJz0Z.js';
3
- import '../ir-Qnw6L265.js';
1
+ import { G as GlassboxEvent } from '../types-Bon96eyc.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-Bon96eyc.js';
3
+ import '../ir-Bvlkw5ja.js';
4
4
  import '../dialect.js';
5
5
 
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-Cya0jPAF.mjs';
2
- import '../ir-BTvyl8-w.mjs';
1
+ import { T as TraceHealth } from '../types-CwGhacGT.mjs';
2
+ import '../ir-Bqn1RVdV.mjs';
3
3
  import '../dialect.mjs';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { T as TraceHealth } from '../types-DxYXuFxj.js';
2
- import '../ir-Qnw6L265.js';
1
+ import { T as TraceHealth } from '../types-DIxRZ3Dj.js';
2
+ import '../ir-Bvlkw5ja.js';
3
3
  import '../dialect.js';
4
4
 
5
5
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-8pWRDbUg.mjs';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-Cya0jPAF.mjs';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-Cya0jPAF.mjs';
4
- import '../ir-BTvyl8-w.mjs';
1
+ import { G as GlassboxEvent } from '../types-DsEq35WY.mjs';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-CwGhacGT.mjs';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-CwGhacGT.mjs';
4
+ import '../ir-Bqn1RVdV.mjs';
5
5
  import '../dialect.mjs';
6
6
 
7
7
  /**
@@ -1,7 +1,7 @@
1
- import { G as GlassboxEvent } from '../types-BdYlJz0Z.js';
2
- import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-DxYXuFxj.js';
3
- export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-DxYXuFxj.js';
4
- import '../ir-Qnw6L265.js';
1
+ import { G as GlassboxEvent } from '../types-Bon96eyc.js';
2
+ import { a as TraceDetail, b as TraceSummary, c as TraceCounterfactual } from '../types-DIxRZ3Dj.js';
3
+ export { A as AdvisoryRecord, T as TraceHealth, d as TraceSectionRewrite } from '../types-DIxRZ3Dj.js';
4
+ import '../ir-Bvlkw5ja.js';
5
5
  import '../dialect.js';
6
6
 
7
7
  /**
@@ -2228,6 +2228,7 @@ var SECTION_KINDS = /* @__PURE__ */ new Set([
2228
2228
  "role_intro",
2229
2229
  "tool_call_contract",
2230
2230
  "narration_contract",
2231
+ "discipline_contract",
2231
2232
  "user_turn",
2232
2233
  "reference",
2233
2234
  "arbitrary"
@@ -2242,6 +2243,9 @@ function summarizeSectionRewrite(kind, rule) {
2242
2243
  if (kind === "narration_contract" && rule === "narration-thinking-leak-deepseek") {
2243
2244
  return "Thinking-block suppression applied (DeepSeek V4 internal reasoning kept off-wire).";
2244
2245
  }
2246
+ if (kind === "discipline_contract" && rule === "discipline-gates-v1") {
2247
+ return "Discipline gates applied (surface-scaffolding: evidence-before-reasoning, one-extra-signal, source-labeling).";
2248
+ }
2245
2249
  return `Translator applied rule "${rule}" to ${kind} section.`;
2246
2250
  }
2247
2251
  function rowToSectionRewrite(raw) {
@@ -287,6 +287,7 @@ var SECTION_KINDS = /* @__PURE__ */ new Set([
287
287
  "role_intro",
288
288
  "tool_call_contract",
289
289
  "narration_contract",
290
+ "discipline_contract",
290
291
  "user_turn",
291
292
  "reference",
292
293
  "arbitrary"
@@ -301,6 +302,9 @@ function summarizeSectionRewrite(kind, rule) {
301
302
  if (kind === "narration_contract" && rule === "narration-thinking-leak-deepseek") {
302
303
  return "Thinking-block suppression applied (DeepSeek V4 internal reasoning kept off-wire).";
303
304
  }
305
+ if (kind === "discipline_contract" && rule === "discipline-gates-v1") {
306
+ return "Discipline gates applied (surface-scaffolding: evidence-before-reasoning, one-extra-signal, source-labeling).";
307
+ }
304
308
  return `Translator applied rule "${rule}" to ${kind} section.`;
305
309
  }
306
310
  function rowToSectionRewrite(raw) {
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { a as TraceDetail } from '../../types-Cya0jPAF.mjs';
3
- import '../../ir-BTvyl8-w.mjs';
2
+ import { a as TraceDetail } from '../../types-CwGhacGT.mjs';
3
+ import '../../ir-Bqn1RVdV.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-DxYXuFxj.js';
3
- import '../../ir-Qnw6L265.js';
2
+ import { a as TraceDetail } from '../../types-DIxRZ3Dj.js';
3
+ import '../../ir-Bvlkw5ja.js';
4
4
  import '../../dialect.js';
5
5
 
6
6
  /**
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
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-BTvyl8-w.mjs';
2
- export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as parseGoldenCaptureRate, K as resolveGoldenCaptureRate, L as shouldCaptureGolden } from './ir-BTvyl8-w.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-Bqn1RVdV.mjs';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as parseGoldenCaptureRate, K as resolveGoldenCaptureRate, L as shouldCaptureGolden } from './ir-Bqn1RVdV.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
5
  export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.mjs';
6
6
  export { KeyHealthConfig, KeyHealthProvider, KeyHealthResponseBody, KeyHealthResult, KeyHealthRoute, createKeyHealthRoute } from './key-health.mjs';
7
- import { IntentArchetypeName } from './dialect.mjs';
8
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
7
+ import { IntentArchetypeName, OutputMode } from './dialect.mjs';
8
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
9
9
 
10
10
  /**
11
11
  * compile() — the main orchestrator.
@@ -38,6 +38,15 @@ interface CompileOptions {
38
38
  * ceiling, boosts preferred. See CompilePolicy in ir.ts.
39
39
  */
40
40
  policy?: CompilePolicy;
41
+ /**
42
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage) —
43
+ * transport for the fan-out parent handle. Threaded from
44
+ * `CallOptions.parentHandle` on the call() path (and settable directly on the
45
+ * public compile() path). Release A does NOT route on it — it only labels the
46
+ * outcome row (fanout_role / trace_id / parent_handle) at record-registration
47
+ * time. `registerCompile` reads it to derive the linkage. Absent ⇒ root call.
48
+ */
49
+ parentHandle?: string;
41
50
  }
42
51
 
43
52
  /**
@@ -623,6 +632,28 @@ interface OutcomePayload {
623
632
  * downstream outcome quality lifted by M points").
624
633
  */
625
634
  section_rewrites_applied?: SectionRewrite[] | null;
635
+ /**
636
+ * R0 linkage (§5.0). Parent call's handle when this row is a fan-out branch;
637
+ * key OMITTED (undefined → dropped by JSON.stringify → stored NULL) for a
638
+ * root, safe against pre-042 brains.
639
+ */
640
+ parent_handle?: string;
641
+ /**
642
+ * R0 linkage (§5.0). Root handle of the fan-out trace (= parent_handle when a
643
+ * branch, else this row's own handle). Emitted for every registered compile.
644
+ */
645
+ trace_id?: string;
646
+ /**
647
+ * R0 linkage (§5.0). root | branch | composer. Emitted for every registered
648
+ * compile; surface baselines filter to root/NULL so branch traffic never
649
+ * contaminates a promotion/eval baseline. Release A emits only root/branch.
650
+ */
651
+ fanout_role?: 'root' | 'branch' | 'composer';
652
+ /**
653
+ * RD discipline gate-token accounting (§5.D). Measured token tax of the
654
+ * discipline_contract gate block; 0 when the gate didn't fire.
655
+ */
656
+ discipline_gate_tokens?: number;
626
657
  }
627
658
  /**
628
659
  * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
@@ -942,7 +973,7 @@ declare function runGoldenEval(opts: GoldenEvalOptions): Promise<GoldenEvalRunRe
942
973
  * guard in `tests/version.test.ts` fails the suite (and therefore
943
974
  * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
944
975
  */
945
- declare const LIBRARY_VERSION = "2.0.0-alpha.67";
976
+ declare const LIBRARY_VERSION = "2.0.0-alpha.69";
946
977
 
947
978
  /**
948
979
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -1280,6 +1311,15 @@ interface ApplySectionRewritesArgs {
1280
1311
  ir: PromptIR;
1281
1312
  profile: ModelProfile;
1282
1313
  archetype: IntentArchetypeName;
1314
+ /**
1315
+ * alpha.68 / Release A — resolved output shape for Factor C (§5.D). `'json'`
1316
+ * ⇒ structured surface (the discipline gate MUST NOT fire — gates 5+6 are
1317
+ * shape-altering and would break the consumer's parser). `'text'` ⇒ free-form
1318
+ * surface (the gate may fire). Optional: when omitted, derived from
1319
+ * `ir.constraints?.structuredOutput` (true ⇒ 'json', else 'text') so callers
1320
+ * / tests need not pass it. compile() passes it explicitly.
1321
+ */
1322
+ outputMode?: OutputMode;
1283
1323
  }
1284
1324
  interface ApplySectionRewritesResult {
1285
1325
  /**
@@ -2839,4 +2879,4 @@ declare function _testWaitForPromotionsRefresh(): Promise<void>;
2839
2879
  */
2840
2880
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2841
2881
 
2842
- 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 BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, 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 ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, _testResetPromotions, _testWaitForPromotionsRefresh, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isPromotionsBrainActive, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, setTokenizer };
2882
+ 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 BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, _testResetPromotions, _testWaitForPromotionsRefresh, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isPromotionsBrainActive, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, setTokenizer };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
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-Qnw6L265.js';
2
- export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as parseGoldenCaptureRate, K as resolveGoldenCaptureRate, L as shouldCaptureGolden } from './ir-Qnw6L265.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-Bvlkw5ja.js';
2
+ export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, E as EffortLevel, F as FallbackReason, r as GoldenCaptureOptions, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, s as MutationApplied, t as NormalizedTokens, u as OutcomeKind, v as PerAxisMetricsByModel, w as PromptSection, x as SectionKind, y as ShadowProbeConfig, T as ToolCall, z as ToolDefinition, D as captureGoldenIr, J as parseGoldenCaptureRate, K as resolveGoldenCaptureRate, L as shouldCaptureGolden } from './ir-Bvlkw5ja.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
5
  export { BrainForwardConfig, BrainForwardRoutes, createBrainForwardRoutes } from './brain-proxy.js';
6
6
  export { KeyHealthConfig, KeyHealthProvider, KeyHealthResponseBody, KeyHealthResult, KeyHealthRoute, createKeyHealthRoute } from './key-health.js';
7
- import { IntentArchetypeName } from './dialect.js';
8
- export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
7
+ import { IntentArchetypeName, OutputMode } from './dialect.js';
8
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
9
9
 
10
10
  /**
11
11
  * compile() — the main orchestrator.
@@ -38,6 +38,15 @@ interface CompileOptions {
38
38
  * ceiling, boosts preferred. See CompilePolicy in ir.ts.
39
39
  */
40
40
  policy?: CompilePolicy;
41
+ /**
42
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage) —
43
+ * transport for the fan-out parent handle. Threaded from
44
+ * `CallOptions.parentHandle` on the call() path (and settable directly on the
45
+ * public compile() path). Release A does NOT route on it — it only labels the
46
+ * outcome row (fanout_role / trace_id / parent_handle) at record-registration
47
+ * time. `registerCompile` reads it to derive the linkage. Absent ⇒ root call.
48
+ */
49
+ parentHandle?: string;
41
50
  }
42
51
 
43
52
  /**
@@ -623,6 +632,28 @@ interface OutcomePayload {
623
632
  * downstream outcome quality lifted by M points").
624
633
  */
625
634
  section_rewrites_applied?: SectionRewrite[] | null;
635
+ /**
636
+ * R0 linkage (§5.0). Parent call's handle when this row is a fan-out branch;
637
+ * key OMITTED (undefined → dropped by JSON.stringify → stored NULL) for a
638
+ * root, safe against pre-042 brains.
639
+ */
640
+ parent_handle?: string;
641
+ /**
642
+ * R0 linkage (§5.0). Root handle of the fan-out trace (= parent_handle when a
643
+ * branch, else this row's own handle). Emitted for every registered compile.
644
+ */
645
+ trace_id?: string;
646
+ /**
647
+ * R0 linkage (§5.0). root | branch | composer. Emitted for every registered
648
+ * compile; surface baselines filter to root/NULL so branch traffic never
649
+ * contaminates a promotion/eval baseline. Release A emits only root/branch.
650
+ */
651
+ fanout_role?: 'root' | 'branch' | 'composer';
652
+ /**
653
+ * RD discipline gate-token accounting (§5.D). Measured token tax of the
654
+ * discipline_contract gate block; 0 when the gate didn't fire.
655
+ */
656
+ discipline_gate_tokens?: number;
626
657
  }
627
658
  /**
628
659
  * alpha.20 Entry 4: record a quality outcome for a previously-compiled call.
@@ -942,7 +973,7 @@ declare function runGoldenEval(opts: GoldenEvalOptions): Promise<GoldenEvalRunRe
942
973
  * guard in `tests/version.test.ts` fails the suite (and therefore
943
974
  * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
944
975
  */
945
- declare const LIBRARY_VERSION = "2.0.0-alpha.67";
976
+ declare const LIBRARY_VERSION = "2.0.0-alpha.69";
946
977
 
947
978
  /**
948
979
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -1280,6 +1311,15 @@ interface ApplySectionRewritesArgs {
1280
1311
  ir: PromptIR;
1281
1312
  profile: ModelProfile;
1282
1313
  archetype: IntentArchetypeName;
1314
+ /**
1315
+ * alpha.68 / Release A — resolved output shape for Factor C (§5.D). `'json'`
1316
+ * ⇒ structured surface (the discipline gate MUST NOT fire — gates 5+6 are
1317
+ * shape-altering and would break the consumer's parser). `'text'` ⇒ free-form
1318
+ * surface (the gate may fire). Optional: when omitted, derived from
1319
+ * `ir.constraints?.structuredOutput` (true ⇒ 'json', else 'text') so callers
1320
+ * / tests need not pass it. compile() passes it explicitly.
1321
+ */
1322
+ outputMode?: OutputMode;
1283
1323
  }
1284
1324
  interface ApplySectionRewritesResult {
1285
1325
  /**
@@ -2839,4 +2879,4 @@ declare function _testWaitForPromotionsRefresh(): Promise<void>;
2839
2879
  */
2840
2880
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2841
2881
 
2842
- 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 BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, 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 ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, _testResetPromotions, _testWaitForPromotionsRefresh, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isPromotionsBrainActive, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, setTokenizer };
2882
+ 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 BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, _testResetPromotions, _testWaitForPromotionsRefresh, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isPromotionsBrainActive, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, setTokenizer };
package/dist/index.js CHANGED
@@ -2476,6 +2476,11 @@ var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
2476
2476
  function isArchetype(name) {
2477
2477
  return name in INTENT_ARCHETYPES;
2478
2478
  }
2479
+ function resolveOutputMode(args) {
2480
+ if (args.declared) return args.declared;
2481
+ if (args.structuredOutput === true) return "json";
2482
+ return args.toolCount > 0 ? "tool_call" : "text";
2483
+ }
2479
2484
  function bucketContext(tokens) {
2480
2485
  if (tokens < 1e3) return "tiny";
2481
2486
  if (tokens < 4e3) return "small";
@@ -2923,7 +2928,11 @@ function computeShape(ir, estimatedInputTokens) {
2923
2928
  contextBucket: bucketContext(estimatedInputTokens),
2924
2929
  toolCountBucket: bucketToolCount(ir.tools?.length ?? 0),
2925
2930
  historyDepth: bucketHistory(ir.history?.length ?? 0),
2926
- outputMode: ir.constraints?.structuredOutput ? "json" : ir.tools?.length ? "tool_call" : "text",
2931
+ outputMode: resolveOutputMode({
2932
+ declared: ir.constraints?.outputMode,
2933
+ structuredOutput: ir.constraints?.structuredOutput,
2934
+ toolCount: ir.tools?.length ?? 0
2935
+ }),
2927
2936
  hasExamples: ir.sections.some((s) => /\bexample\b/i.test(s.id))
2928
2937
  };
2929
2938
  }
@@ -4308,7 +4317,36 @@ var RULE_NARRATION_THINKING_LEAK_DEEPSEEK = "narration-thinking-leak-deepseek";
4308
4317
  var SEQUENTIAL_TOOL_PREAMBLE = "IMPORTANT: Use one tool call per response. Wait for the tool result before deciding the next tool. Do NOT batch tool calls in parallel.";
4309
4318
  var NARRATION_DRIFT_ANTHROPIC_PREAMBLE = "Output ONLY the requested content. Do not narrate your thought process. Each line \u2264 12 words.";
4310
4319
  var NARRATION_THINKING_LEAK_DEEPSEEK_PREAMBLE = "Reasoning is internal. Output ONLY the requested content; do not emit <thinking> blocks or internal monologue as user-facing text.";
4311
- function matchRule(kind, profile, archetype) {
4320
+ var RULE_DISCIPLINE_GATES_V1 = "discipline-gates-v1";
4321
+ var DISCIPLINE_GATES_V1_WITH_TOOLS = `Work through these gates at every judgment point, explicitly:
4322
+ 1. Evidence before reasoning: cite what you observed before concluding from it.
4323
+ 2. One extra signal: when a finding feels conclusive, check one more adjacent signal before stating it.
4324
+ 3. Expand, don't guess: resolve a compressed or referenced item by looking it up rather than inferring its contents.
4325
+ 4. Innocent explanation first: state the most plausible benign reading before alleging the alarming one.
4326
+ 5. Label each claim: mark it observed, inferred, or assumed.
4327
+ 6. A surfaced gap beats a guessed answer: flag what you cannot determine rather than fabricating past it.`;
4328
+ var DISCIPLINE_GATES_V1_NO_TOOLS = `Work through these gates at every judgment point, explicitly:
4329
+ 1. Evidence before reasoning: cite what you observed before concluding from it.
4330
+ 2. One extra signal: when a finding feels conclusive, check one more adjacent signal before stating it.
4331
+ 3. Innocent explanation first: state the most plausible benign reading before alleging the alarming one.
4332
+ 4. Label each claim: mark it observed, inferred, or assumed.
4333
+ 5. A surfaced gap beats a guessed answer: flag what you cannot determine rather than fabricating past it.`;
4334
+ var DISCIPLINE_ELIGIBLE_ARCHETYPES = /* @__PURE__ */ new Set([
4335
+ "hunt",
4336
+ "summarize",
4337
+ "plan",
4338
+ "critique",
4339
+ "judge"
4340
+ ]);
4341
+ function matchRule(kind, profile, archetype, ctx) {
4342
+ if (kind === "discipline_contract") {
4343
+ if (!DISCIPLINE_ELIGIBLE_ARCHETYPES.has(archetype)) return null;
4344
+ if (ctx.outputMode !== "text") return null;
4345
+ return {
4346
+ id: RULE_DISCIPLINE_GATES_V1,
4347
+ preamble: ctx.hasTools ? DISCIPLINE_GATES_V1_WITH_TOOLS : DISCIPLINE_GATES_V1_NO_TOOLS
4348
+ };
4349
+ }
4312
4350
  if (kind === "tool_call_contract") {
4313
4351
  if (!profile.archetypePerf) return null;
4314
4352
  const archetypeScore = profile.archetypePerf[archetype];
@@ -4343,10 +4381,17 @@ function applySectionRewrites(args) {
4343
4381
  if (!Array.isArray(ir.sections) || ir.sections.length === 0) {
4344
4382
  return { rewrittenIR: ir, rewrites: [] };
4345
4383
  }
4384
+ const outputMode = args.outputMode ?? resolveOutputMode({
4385
+ declared: ir.constraints?.outputMode,
4386
+ structuredOutput: ir.constraints?.structuredOutput,
4387
+ toolCount: ir.tools?.length ?? 0
4388
+ });
4389
+ const hasTools = (ir.tools?.length ?? 0) > 0;
4390
+ const ctx = { outputMode, hasTools };
4346
4391
  const rewrites = [];
4347
4392
  const newSections = ir.sections.map((section) => {
4348
4393
  if (!section.kind || section.kind === "arbitrary") return section;
4349
- const rule = matchRule(section.kind, profile, archetype);
4394
+ const rule = matchRule(section.kind, profile, archetype, ctx);
4350
4395
  if (!rule) return section;
4351
4396
  const originalText = section.text;
4352
4397
  const transformedText = `${rule.preamble}
@@ -4551,13 +4596,28 @@ function compile(ir, opts = {}) {
4551
4596
  const conventions = passApplyConventions(workingIR, profile);
4552
4597
  workingIR = conventions.value.ir;
4553
4598
  accumulatedMutations.push(...conventions.mutations);
4599
+ const outputMode = resolveOutputMode({
4600
+ declared: ir.constraints?.outputMode,
4601
+ structuredOutput: ir.constraints?.structuredOutput,
4602
+ toolCount: ir.tools?.length ?? 0
4603
+ });
4554
4604
  const translated = applySectionRewrites({
4555
4605
  ir: workingIR,
4556
4606
  profile,
4557
- archetype: ir.intent.archetype
4607
+ archetype: ir.intent.archetype,
4608
+ outputMode
4558
4609
  });
4559
4610
  workingIR = translated.rewrittenIR;
4560
4611
  const sectionRewritesApplied = translated.rewrites;
4612
+ const disciplineRewrite = sectionRewritesApplied.find(
4613
+ (rw) => rw.kind === "discipline_contract"
4614
+ );
4615
+ const disciplineGateTokens = disciplineRewrite ? countTokens(
4616
+ disciplineRewrite.transformedText.slice(
4617
+ 0,
4618
+ disciplineRewrite.transformedText.length - disciplineRewrite.originalText.length
4619
+ )
4620
+ ) : 0;
4561
4621
  let wireOverrides;
4562
4622
  for (const rw of sectionRewritesApplied) {
4563
4623
  if (!rw.wireOverrides) continue;
@@ -4610,7 +4670,10 @@ function compile(ir, opts = {}) {
4610
4670
  cliffWarnings: [
4611
4671
  ...cliffs.value.loweringHints.qualityWarning ?? [],
4612
4672
  ...conventions.value.cliffWarnings
4613
- ]
4673
+ ],
4674
+ // alpha.68 / Release A — measured discipline gate-token tax (§5.D). 0 when
4675
+ // the gate didn't fire.
4676
+ disciplineGateTokens
4614
4677
  };
4615
4678
  if (ir.intent.archetype === "hunt" && ir.constraints?.toolOrchestration === "sequential") {
4616
4679
  accumulatedMutations.push({
@@ -5014,7 +5077,7 @@ async function flushBrainDeadLetter() {
5014
5077
  }
5015
5078
  var compileRegistry = /* @__PURE__ */ new Map();
5016
5079
  var REGISTRY_MAX_ENTRIES = 1e4;
5017
- function registerCompile(appId, archetype, ir, result) {
5080
+ function registerCompile(appId, archetype, ir, result, parentHandle) {
5018
5081
  if (compileRegistry.size >= REGISTRY_MAX_ENTRIES) {
5019
5082
  const cutoff = Math.floor(REGISTRY_MAX_ENTRIES * 0.25);
5020
5083
  let evicted = 0;
@@ -5066,7 +5129,15 @@ function registerCompile(appId, archetype, ir, result) {
5066
5129
  // outcome quality lifted to M."
5067
5130
  sectionRewritesApplied: result.sectionRewritesApplied,
5068
5131
  // alpha.57: cache the declared effort tier for record()'s auto-enrich.
5069
- effortFromCompile: ir.constraints?.effort
5132
+ effortFromCompile: ir.constraints?.effort,
5133
+ // alpha.68 / Release A (§5.0, R0 linkage) — derive + cache the fan-out
5134
+ // linkage. Release A is 1-level: a branch's trace_id is its parent handle
5135
+ // (the root); deeper trees await the delegate primitive (Release D).
5136
+ parentHandle,
5137
+ traceId: parentHandle ?? result.handle,
5138
+ fanoutRole: parentHandle ? "branch" : "root",
5139
+ // alpha.68 / Release A (§5.D) — measured gate-token tax from diagnostics.
5140
+ disciplineGateTokens: result.diagnostics.disciplineGateTokens
5070
5141
  });
5071
5142
  }
5072
5143
  function estimateSystemPromptChars(sections) {
@@ -5257,7 +5328,17 @@ function buildPayload(input, reg) {
5257
5328
  // alpha.29 — translator activity (migration 019). Send NULL when no
5258
5329
  // rewrites fired so the brain's "did the translator do anything?"
5259
5330
  // queries can use `IS NOT NULL` cleanly.
5260
- section_rewrites_applied: reg?.sectionRewritesApplied && reg.sectionRewritesApplied.length > 0 ? reg.sectionRewritesApplied : null
5331
+ section_rewrites_applied: reg?.sectionRewritesApplied && reg.sectionRewritesApplied.length > 0 ? reg.sectionRewritesApplied : null,
5332
+ // alpha.68 / Release A (§5.0 + §5.D, migration 042) — auto-enrich the
5333
+ // fan-out linkage + discipline gate tax from the registered compile.
5334
+ // Omit-when-undefined (JSON.stringify drops undefined keys), same posture as
5335
+ // `effort` / `retried_same_model` → safe against pre-042 brains. A registered
5336
+ // compile always carries trace_id + fanout_role + discipline_gate_tokens
5337
+ // (root/0 for ordinary traffic); parent_handle is present only for branches.
5338
+ parent_handle: reg?.parentHandle,
5339
+ trace_id: reg?.traceId,
5340
+ fanout_role: reg?.fanoutRole,
5341
+ discipline_gate_tokens: reg?.disciplineGateTokens
5261
5342
  };
5262
5343
  }
5263
5344
  function computeCostUsd(modelId, tokensIn, tokensOut) {
@@ -7187,9 +7268,11 @@ function compileAndRegister(ir, opts) {
7187
7268
  const result = compile(ir, {
7188
7269
  policy: opts.policy,
7189
7270
  toolRelevanceThreshold: opts.toolRelevanceThreshold,
7190
- compressHistoryAfter: opts.compressHistoryAfter
7271
+ compressHistoryAfter: opts.compressHistoryAfter,
7272
+ // alpha.68 / Release A — carry the fan-out parent handle through to compile.
7273
+ parentHandle: opts.parentHandle
7191
7274
  });
7192
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
7275
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts.parentHandle);
7193
7276
  return result;
7194
7277
  }
7195
7278
  function extractPromptPreview(ir) {
@@ -7540,7 +7623,7 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
7540
7623
  // src/compile-aisdk.ts
7541
7624
  function compileForAISDKv6(ir, opts) {
7542
7625
  const result = compile(ir, opts);
7543
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
7626
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts?.parentHandle);
7544
7627
  armCompileConsumeTracking(result.handle);
7545
7628
  const systemMessages = result.systemMessages;
7546
7629
  const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
@@ -8293,7 +8376,7 @@ function createBrainForwardRoutes(config) {
8293
8376
  }
8294
8377
 
8295
8378
  // src/version.ts
8296
- var LIBRARY_VERSION = "2.0.0-alpha.67";
8379
+ var LIBRARY_VERSION = "2.0.0-alpha.69";
8297
8380
 
8298
8381
  // src/key-health.ts
8299
8382
  var JSON_HEADERS2 = { "Content-Type": "application/json" };
@@ -8914,7 +8997,7 @@ async function markExclusionFindingHandled(opts) {
8914
8997
  // src/index.ts
8915
8998
  function compile2(ir, opts) {
8916
8999
  const result = compile(ir, opts);
8917
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
9000
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts?.parentHandle);
8918
9001
  return result;
8919
9002
  }
8920
9003
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.mjs CHANGED
@@ -10,12 +10,13 @@ import {
10
10
  bucketToolCount,
11
11
  hashShape,
12
12
  isArchetype,
13
- learningKey
14
- } from "./chunk-3KQAID63.mjs";
13
+ learningKey,
14
+ resolveOutputMode
15
+ } from "./chunk-BVEXV5KC.mjs";
15
16
  import {
16
17
  LIBRARY_VERSION,
17
18
  createKeyHealthRoute
18
- } from "./chunk-DTFQIURE.mjs";
19
+ } from "./chunk-EZXVJUK7.mjs";
19
20
  import {
20
21
  ABSOLUTE_FLOOR,
21
22
  ARCHETYPE_FLOOR_DEFAULT,
@@ -904,7 +905,11 @@ function computeShape(ir, estimatedInputTokens) {
904
905
  contextBucket: bucketContext(estimatedInputTokens),
905
906
  toolCountBucket: bucketToolCount(ir.tools?.length ?? 0),
906
907
  historyDepth: bucketHistory(ir.history?.length ?? 0),
907
- outputMode: ir.constraints?.structuredOutput ? "json" : ir.tools?.length ? "tool_call" : "text",
908
+ outputMode: resolveOutputMode({
909
+ declared: ir.constraints?.outputMode,
910
+ structuredOutput: ir.constraints?.structuredOutput,
911
+ toolCount: ir.tools?.length ?? 0
912
+ }),
908
913
  hasExamples: ir.sections.some((s) => /\bexample\b/i.test(s.id))
909
914
  };
910
915
  }
@@ -2289,7 +2294,36 @@ var RULE_NARRATION_THINKING_LEAK_DEEPSEEK = "narration-thinking-leak-deepseek";
2289
2294
  var SEQUENTIAL_TOOL_PREAMBLE = "IMPORTANT: Use one tool call per response. Wait for the tool result before deciding the next tool. Do NOT batch tool calls in parallel.";
2290
2295
  var NARRATION_DRIFT_ANTHROPIC_PREAMBLE = "Output ONLY the requested content. Do not narrate your thought process. Each line \u2264 12 words.";
2291
2296
  var NARRATION_THINKING_LEAK_DEEPSEEK_PREAMBLE = "Reasoning is internal. Output ONLY the requested content; do not emit <thinking> blocks or internal monologue as user-facing text.";
2292
- function matchRule(kind, profile, archetype) {
2297
+ var RULE_DISCIPLINE_GATES_V1 = "discipline-gates-v1";
2298
+ var DISCIPLINE_GATES_V1_WITH_TOOLS = `Work through these gates at every judgment point, explicitly:
2299
+ 1. Evidence before reasoning: cite what you observed before concluding from it.
2300
+ 2. One extra signal: when a finding feels conclusive, check one more adjacent signal before stating it.
2301
+ 3. Expand, don't guess: resolve a compressed or referenced item by looking it up rather than inferring its contents.
2302
+ 4. Innocent explanation first: state the most plausible benign reading before alleging the alarming one.
2303
+ 5. Label each claim: mark it observed, inferred, or assumed.
2304
+ 6. A surfaced gap beats a guessed answer: flag what you cannot determine rather than fabricating past it.`;
2305
+ var DISCIPLINE_GATES_V1_NO_TOOLS = `Work through these gates at every judgment point, explicitly:
2306
+ 1. Evidence before reasoning: cite what you observed before concluding from it.
2307
+ 2. One extra signal: when a finding feels conclusive, check one more adjacent signal before stating it.
2308
+ 3. Innocent explanation first: state the most plausible benign reading before alleging the alarming one.
2309
+ 4. Label each claim: mark it observed, inferred, or assumed.
2310
+ 5. A surfaced gap beats a guessed answer: flag what you cannot determine rather than fabricating past it.`;
2311
+ var DISCIPLINE_ELIGIBLE_ARCHETYPES = /* @__PURE__ */ new Set([
2312
+ "hunt",
2313
+ "summarize",
2314
+ "plan",
2315
+ "critique",
2316
+ "judge"
2317
+ ]);
2318
+ function matchRule(kind, profile, archetype, ctx) {
2319
+ if (kind === "discipline_contract") {
2320
+ if (!DISCIPLINE_ELIGIBLE_ARCHETYPES.has(archetype)) return null;
2321
+ if (ctx.outputMode !== "text") return null;
2322
+ return {
2323
+ id: RULE_DISCIPLINE_GATES_V1,
2324
+ preamble: ctx.hasTools ? DISCIPLINE_GATES_V1_WITH_TOOLS : DISCIPLINE_GATES_V1_NO_TOOLS
2325
+ };
2326
+ }
2293
2327
  if (kind === "tool_call_contract") {
2294
2328
  if (!profile.archetypePerf) return null;
2295
2329
  const archetypeScore = profile.archetypePerf[archetype];
@@ -2324,10 +2358,17 @@ function applySectionRewrites(args) {
2324
2358
  if (!Array.isArray(ir.sections) || ir.sections.length === 0) {
2325
2359
  return { rewrittenIR: ir, rewrites: [] };
2326
2360
  }
2361
+ const outputMode = args.outputMode ?? resolveOutputMode({
2362
+ declared: ir.constraints?.outputMode,
2363
+ structuredOutput: ir.constraints?.structuredOutput,
2364
+ toolCount: ir.tools?.length ?? 0
2365
+ });
2366
+ const hasTools = (ir.tools?.length ?? 0) > 0;
2367
+ const ctx = { outputMode, hasTools };
2327
2368
  const rewrites = [];
2328
2369
  const newSections = ir.sections.map((section) => {
2329
2370
  if (!section.kind || section.kind === "arbitrary") return section;
2330
- const rule = matchRule(section.kind, profile, archetype);
2371
+ const rule = matchRule(section.kind, profile, archetype, ctx);
2331
2372
  if (!rule) return section;
2332
2373
  const originalText = section.text;
2333
2374
  const transformedText = `${rule.preamble}
@@ -2532,13 +2573,28 @@ function compile(ir, opts = {}) {
2532
2573
  const conventions = passApplyConventions(workingIR, profile);
2533
2574
  workingIR = conventions.value.ir;
2534
2575
  accumulatedMutations.push(...conventions.mutations);
2576
+ const outputMode = resolveOutputMode({
2577
+ declared: ir.constraints?.outputMode,
2578
+ structuredOutput: ir.constraints?.structuredOutput,
2579
+ toolCount: ir.tools?.length ?? 0
2580
+ });
2535
2581
  const translated = applySectionRewrites({
2536
2582
  ir: workingIR,
2537
2583
  profile,
2538
- archetype: ir.intent.archetype
2584
+ archetype: ir.intent.archetype,
2585
+ outputMode
2539
2586
  });
2540
2587
  workingIR = translated.rewrittenIR;
2541
2588
  const sectionRewritesApplied = translated.rewrites;
2589
+ const disciplineRewrite = sectionRewritesApplied.find(
2590
+ (rw) => rw.kind === "discipline_contract"
2591
+ );
2592
+ const disciplineGateTokens = disciplineRewrite ? countTokens(
2593
+ disciplineRewrite.transformedText.slice(
2594
+ 0,
2595
+ disciplineRewrite.transformedText.length - disciplineRewrite.originalText.length
2596
+ )
2597
+ ) : 0;
2542
2598
  let wireOverrides;
2543
2599
  for (const rw of sectionRewritesApplied) {
2544
2600
  if (!rw.wireOverrides) continue;
@@ -2591,7 +2647,10 @@ function compile(ir, opts = {}) {
2591
2647
  cliffWarnings: [
2592
2648
  ...cliffs.value.loweringHints.qualityWarning ?? [],
2593
2649
  ...conventions.value.cliffWarnings
2594
- ]
2650
+ ],
2651
+ // alpha.68 / Release A — measured discipline gate-token tax (§5.D). 0 when
2652
+ // the gate didn't fire.
2653
+ disciplineGateTokens
2595
2654
  };
2596
2655
  if (ir.intent.archetype === "hunt" && ir.constraints?.toolOrchestration === "sequential") {
2597
2656
  accumulatedMutations.push({
@@ -2995,7 +3054,7 @@ async function flushBrainDeadLetter() {
2995
3054
  }
2996
3055
  var compileRegistry = /* @__PURE__ */ new Map();
2997
3056
  var REGISTRY_MAX_ENTRIES = 1e4;
2998
- function registerCompile(appId, archetype, ir, result) {
3057
+ function registerCompile(appId, archetype, ir, result, parentHandle) {
2999
3058
  if (compileRegistry.size >= REGISTRY_MAX_ENTRIES) {
3000
3059
  const cutoff = Math.floor(REGISTRY_MAX_ENTRIES * 0.25);
3001
3060
  let evicted = 0;
@@ -3047,7 +3106,15 @@ function registerCompile(appId, archetype, ir, result) {
3047
3106
  // outcome quality lifted to M."
3048
3107
  sectionRewritesApplied: result.sectionRewritesApplied,
3049
3108
  // alpha.57: cache the declared effort tier for record()'s auto-enrich.
3050
- effortFromCompile: ir.constraints?.effort
3109
+ effortFromCompile: ir.constraints?.effort,
3110
+ // alpha.68 / Release A (§5.0, R0 linkage) — derive + cache the fan-out
3111
+ // linkage. Release A is 1-level: a branch's trace_id is its parent handle
3112
+ // (the root); deeper trees await the delegate primitive (Release D).
3113
+ parentHandle,
3114
+ traceId: parentHandle ?? result.handle,
3115
+ fanoutRole: parentHandle ? "branch" : "root",
3116
+ // alpha.68 / Release A (§5.D) — measured gate-token tax from diagnostics.
3117
+ disciplineGateTokens: result.diagnostics.disciplineGateTokens
3051
3118
  });
3052
3119
  }
3053
3120
  function estimateSystemPromptChars(sections) {
@@ -3238,7 +3305,17 @@ function buildPayload(input, reg) {
3238
3305
  // alpha.29 — translator activity (migration 019). Send NULL when no
3239
3306
  // rewrites fired so the brain's "did the translator do anything?"
3240
3307
  // queries can use `IS NOT NULL` cleanly.
3241
- section_rewrites_applied: reg?.sectionRewritesApplied && reg.sectionRewritesApplied.length > 0 ? reg.sectionRewritesApplied : null
3308
+ section_rewrites_applied: reg?.sectionRewritesApplied && reg.sectionRewritesApplied.length > 0 ? reg.sectionRewritesApplied : null,
3309
+ // alpha.68 / Release A (§5.0 + §5.D, migration 042) — auto-enrich the
3310
+ // fan-out linkage + discipline gate tax from the registered compile.
3311
+ // Omit-when-undefined (JSON.stringify drops undefined keys), same posture as
3312
+ // `effort` / `retried_same_model` → safe against pre-042 brains. A registered
3313
+ // compile always carries trace_id + fanout_role + discipline_gate_tokens
3314
+ // (root/0 for ordinary traffic); parent_handle is present only for branches.
3315
+ parent_handle: reg?.parentHandle,
3316
+ trace_id: reg?.traceId,
3317
+ fanout_role: reg?.fanoutRole,
3318
+ discipline_gate_tokens: reg?.disciplineGateTokens
3242
3319
  };
3243
3320
  }
3244
3321
  function computeCostUsd(modelId, tokensIn, tokensOut) {
@@ -4429,9 +4506,11 @@ function compileAndRegister(ir, opts) {
4429
4506
  const result = compile(ir, {
4430
4507
  policy: opts.policy,
4431
4508
  toolRelevanceThreshold: opts.toolRelevanceThreshold,
4432
- compressHistoryAfter: opts.compressHistoryAfter
4509
+ compressHistoryAfter: opts.compressHistoryAfter,
4510
+ // alpha.68 / Release A — carry the fan-out parent handle through to compile.
4511
+ parentHandle: opts.parentHandle
4433
4512
  });
4434
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
4513
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts.parentHandle);
4435
4514
  return result;
4436
4515
  }
4437
4516
  function extractPromptPreview(ir) {
@@ -4782,7 +4861,7 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
4782
4861
  // src/compile-aisdk.ts
4783
4862
  function compileForAISDKv6(ir, opts) {
4784
4863
  const result = compile(ir, opts);
4785
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
4864
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts?.parentHandle);
4786
4865
  armCompileConsumeTracking(result.handle);
4787
4866
  const systemMessages = result.systemMessages;
4788
4867
  const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
@@ -5791,7 +5870,7 @@ async function markExclusionFindingHandled(opts) {
5791
5870
  // src/index.ts
5792
5871
  function compile2(ir, opts) {
5793
5872
  const result = compile(ir, opts);
5794
- registerCompile(ir.appId, ir.intent.archetype, ir, result);
5873
+ registerCompile(ir.appId, ir.intent.archetype, ir, result, opts?.parentHandle);
5795
5874
  return result;
5796
5875
  }
5797
5876
  export {
@@ -1,4 +1,4 @@
1
- import { IntentArchetypeName } from './dialect.js';
1
+ import { IntentArchetypeName, OutputMode } from './dialect.mjs';
2
2
 
3
3
  /**
4
4
  * Golden-set capture (alpha.62, eval spine — design brief 2026-07-17).
@@ -125,12 +125,21 @@ interface PromptSection {
125
125
  * sequential-tool cliff on the active archetype
126
126
  * - `narration_contract` — output-format rules ("don't narrate your steps");
127
127
  * alpha.30+ candidate
128
+ * - `discipline_contract`— alpha.68 / Release A (delegation-fanout-accelerator
129
+ * §5.D): surface-scaffolding gate block. When declared
130
+ * on a role/system section, the translator prepends the
131
+ * frozen `discipline-gates-v1` preamble subject to a
132
+ * two-factor eligibility screen — Factor A (archetype:
133
+ * hunt/summarize/plan/critique/judge) AND Factor C
134
+ * (output-shape: text only, never json/tool_call).
135
+ * Clears no cliff, emits no wireOverrides ⇒ no advisor
136
+ * suppression. See `translator.ts`.
128
137
  * - `user_turn` — when sections carry user content rather than
129
138
  * system context (rare)
130
139
  * - `reference` — supporting reference data the model may consult
131
140
  * - `arbitrary` — explicit pass-through (default when unset)
132
141
  */
133
- type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'user_turn' | 'reference' | 'arbitrary';
142
+ type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'discipline_contract' | 'user_turn' | 'reference' | 'arbitrary';
134
143
  interface ToolDefinition {
135
144
  name: string;
136
145
  description?: string;
@@ -197,6 +206,21 @@ interface Constraints {
197
206
  effort?: EffortLevel;
198
207
  /** Caller wants structured (JSON) output. */
199
208
  structuredOutput?: boolean;
209
+ /**
210
+ * alpha.69 — consumer-declared output shape. Overrides the inference in
211
+ * `resolveOutputMode` (structuredOutput ⇒ json · tools ⇒ tool_call · else
212
+ * text), which is deliberately conservative: it cannot see that an agentic
213
+ * surface carrying tools ultimately emits prose to the user.
214
+ *
215
+ * Declaring `'text'` on a tool-carrying surface is what re-opens the
216
+ * alpha.68 discipline gates for it (Factor C is a hard screen on inferred
217
+ * `tool_call`, because wrongly firing breaks a parser while wrongly
218
+ * withholding only forgoes a lift). Declare it truthfully — it is
219
+ * consumer-reported ground truth about what the model emits, and it feeds
220
+ * `shape_key`, so a false declaration fragments the learning key AND lets
221
+ * shape-altering rules fire on a structured surface.
222
+ */
223
+ outputMode?: OutputMode;
200
224
  /** Hint: caller expects a short response (used to disable thinking on Gemini). */
201
225
  expectedShortOutput?: boolean;
202
226
  /** Hint: max response words. */
@@ -289,6 +313,18 @@ interface CompilePolicy {
289
313
  * on high-volume routes.
290
314
  */
291
315
  maxCostPerCallUsd?: number;
316
+ /**
317
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.1) — trace-level
318
+ * cost ceiling (USD) across a fan-out `trace_id`'s cumulative spend.
319
+ *
320
+ * RECORDED / INERT in Release A: nothing fans out yet, so this field is
321
+ * accepted and carried but the compiler enforces NOTHING from it. It is
322
+ * enforced by the `delegate` primitive against the running trace spend in
323
+ * Release D. Kept distinct from `maxCostPerCallUsd` because that per-call
324
+ * ceiling is trivially evadable N times under fan-out — a fan-out budget
325
+ * has to be trace-scoped, not per-call.
326
+ */
327
+ maxCostPerTraceUsd?: number;
292
328
  /**
293
329
  * Model IDs the consumer prefers. When multiple models fit, preferred
294
330
  * models get a rank boost (large enough to overcome small quality
@@ -800,6 +836,16 @@ interface CompileResult {
800
836
  * advisory text. Both can fire on the same call.
801
837
  */
802
838
  cliffWarnings: string[];
839
+ /**
840
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.D) — tokens added
841
+ * by the `discipline_contract` gate block on this call; 0 when the gate
842
+ * didn't fire (no eligible `discipline_contract` section, or Factor A /
843
+ * Factor C screened it out). Measured, never assumed: counted from the
844
+ * exact frozen preamble the translator prepended. Persisted to
845
+ * `compile_outcomes.discipline_gate_tokens` (migration 042) so the tax is a
846
+ * number the cost-watcher can weigh against the lift.
847
+ */
848
+ disciplineGateTokens: number;
803
849
  };
804
850
  /**
805
851
  * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
@@ -987,6 +1033,18 @@ interface ShadowProbeConfig {
987
1033
  interface CallOptions {
988
1034
  /** Forwarded to compile(). */
989
1035
  policy?: CompilePolicy;
1036
+ /**
1037
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage).
1038
+ * When set, this call is a fan-out BRANCH of the parent trace: the outcome
1039
+ * row records `fanout_role='branch'`, `parent_handle=<this value>`, and
1040
+ * `trace_id` inherits the parent handle (the trace root). Absent ⇒ this is a
1041
+ * root (user-facing) call: `fanout_role='root'`, `trace_id=<own handle>`.
1042
+ * Pass the parent's `CallResult.handle` / `CompileResult.handle`.
1043
+ *
1044
+ * Release A supports 1-level linkage (root → branch); deeper trees await the
1045
+ * `delegate` primitive in Release D. Labelling only — NOT a routing change.
1046
+ */
1047
+ parentHandle?: string;
990
1048
  /**
991
1049
  * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
992
1050
  * measures the candidate(s) on the same IR after serving the primary,
@@ -1,4 +1,4 @@
1
- import { IntentArchetypeName } from './dialect.mjs';
1
+ import { IntentArchetypeName, OutputMode } from './dialect.js';
2
2
 
3
3
  /**
4
4
  * Golden-set capture (alpha.62, eval spine — design brief 2026-07-17).
@@ -125,12 +125,21 @@ interface PromptSection {
125
125
  * sequential-tool cliff on the active archetype
126
126
  * - `narration_contract` — output-format rules ("don't narrate your steps");
127
127
  * alpha.30+ candidate
128
+ * - `discipline_contract`— alpha.68 / Release A (delegation-fanout-accelerator
129
+ * §5.D): surface-scaffolding gate block. When declared
130
+ * on a role/system section, the translator prepends the
131
+ * frozen `discipline-gates-v1` preamble subject to a
132
+ * two-factor eligibility screen — Factor A (archetype:
133
+ * hunt/summarize/plan/critique/judge) AND Factor C
134
+ * (output-shape: text only, never json/tool_call).
135
+ * Clears no cliff, emits no wireOverrides ⇒ no advisor
136
+ * suppression. See `translator.ts`.
128
137
  * - `user_turn` — when sections carry user content rather than
129
138
  * system context (rare)
130
139
  * - `reference` — supporting reference data the model may consult
131
140
  * - `arbitrary` — explicit pass-through (default when unset)
132
141
  */
133
- type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'user_turn' | 'reference' | 'arbitrary';
142
+ type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'discipline_contract' | 'user_turn' | 'reference' | 'arbitrary';
134
143
  interface ToolDefinition {
135
144
  name: string;
136
145
  description?: string;
@@ -197,6 +206,21 @@ interface Constraints {
197
206
  effort?: EffortLevel;
198
207
  /** Caller wants structured (JSON) output. */
199
208
  structuredOutput?: boolean;
209
+ /**
210
+ * alpha.69 — consumer-declared output shape. Overrides the inference in
211
+ * `resolveOutputMode` (structuredOutput ⇒ json · tools ⇒ tool_call · else
212
+ * text), which is deliberately conservative: it cannot see that an agentic
213
+ * surface carrying tools ultimately emits prose to the user.
214
+ *
215
+ * Declaring `'text'` on a tool-carrying surface is what re-opens the
216
+ * alpha.68 discipline gates for it (Factor C is a hard screen on inferred
217
+ * `tool_call`, because wrongly firing breaks a parser while wrongly
218
+ * withholding only forgoes a lift). Declare it truthfully — it is
219
+ * consumer-reported ground truth about what the model emits, and it feeds
220
+ * `shape_key`, so a false declaration fragments the learning key AND lets
221
+ * shape-altering rules fire on a structured surface.
222
+ */
223
+ outputMode?: OutputMode;
200
224
  /** Hint: caller expects a short response (used to disable thinking on Gemini). */
201
225
  expectedShortOutput?: boolean;
202
226
  /** Hint: max response words. */
@@ -289,6 +313,18 @@ interface CompilePolicy {
289
313
  * on high-volume routes.
290
314
  */
291
315
  maxCostPerCallUsd?: number;
316
+ /**
317
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.1) — trace-level
318
+ * cost ceiling (USD) across a fan-out `trace_id`'s cumulative spend.
319
+ *
320
+ * RECORDED / INERT in Release A: nothing fans out yet, so this field is
321
+ * accepted and carried but the compiler enforces NOTHING from it. It is
322
+ * enforced by the `delegate` primitive against the running trace spend in
323
+ * Release D. Kept distinct from `maxCostPerCallUsd` because that per-call
324
+ * ceiling is trivially evadable N times under fan-out — a fan-out budget
325
+ * has to be trace-scoped, not per-call.
326
+ */
327
+ maxCostPerTraceUsd?: number;
292
328
  /**
293
329
  * Model IDs the consumer prefers. When multiple models fit, preferred
294
330
  * models get a rank boost (large enough to overcome small quality
@@ -800,6 +836,16 @@ interface CompileResult {
800
836
  * advisory text. Both can fire on the same call.
801
837
  */
802
838
  cliffWarnings: string[];
839
+ /**
840
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.D) — tokens added
841
+ * by the `discipline_contract` gate block on this call; 0 when the gate
842
+ * didn't fire (no eligible `discipline_contract` section, or Factor A /
843
+ * Factor C screened it out). Measured, never assumed: counted from the
844
+ * exact frozen preamble the translator prepended. Persisted to
845
+ * `compile_outcomes.discipline_gate_tokens` (migration 042) so the tax is a
846
+ * number the cost-watcher can weigh against the lift.
847
+ */
848
+ disciplineGateTokens: number;
803
849
  };
804
850
  /**
805
851
  * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
@@ -987,6 +1033,18 @@ interface ShadowProbeConfig {
987
1033
  interface CallOptions {
988
1034
  /** Forwarded to compile(). */
989
1035
  policy?: CompilePolicy;
1036
+ /**
1037
+ * alpha.68 / Release A (delegation-fanout-accelerator §5.0, R0 linkage).
1038
+ * When set, this call is a fan-out BRANCH of the parent trace: the outcome
1039
+ * row records `fanout_role='branch'`, `parent_handle=<this value>`, and
1040
+ * `trace_id` inherits the parent handle (the trace root). Absent ⇒ this is a
1041
+ * root (user-facing) call: `fanout_role='root'`, `trace_id=<own handle>`.
1042
+ * Pass the parent's `CallResult.handle` / `CompileResult.handle`.
1043
+ *
1044
+ * Release A supports 1-level linkage (root → branch); deeper trees await the
1045
+ * `delegate` primitive in Release D. Labelling only — NOT a routing change.
1046
+ */
1047
+ parentHandle?: string;
990
1048
  /**
991
1049
  * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
992
1050
  * measures the candidate(s) on the same IR after serving the primary,
@@ -25,7 +25,7 @@ __export(key_health_exports, {
25
25
  module.exports = __toCommonJS(key_health_exports);
26
26
 
27
27
  // src/version.ts
28
- var LIBRARY_VERSION = "2.0.0-alpha.67";
28
+ var LIBRARY_VERSION = "2.0.0-alpha.69";
29
29
 
30
30
  // src/key-health.ts
31
31
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createKeyHealthRoute
3
- } from "./chunk-DTFQIURE.mjs";
3
+ } from "./chunk-EZXVJUK7.mjs";
4
4
  export {
5
5
  createKeyHealthRoute
6
6
  };
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-BTvyl8-w.mjs';
1
+ import { k as Provider } from './ir-Bqn1RVdV.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-Qnw6L265.js';
1
+ import { k as Provider } from './ir-Bvlkw5ja.js';
2
2
  import { IntentArchetypeName } from './dialect.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-Qnw6L265.js';
1
+ import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-Bvlkw5ja.js';
2
2
 
3
3
  /**
4
4
  * Glass-Box observability types (alpha.17).
@@ -1,4 +1,4 @@
1
- import { i as Adapter, x as SectionKind } from './ir-BTvyl8-w.mjs';
1
+ import { i as Adapter, x as SectionKind } from './ir-Bqn1RVdV.mjs';
2
2
 
3
3
  /**
4
4
  * Internal config + hook types for createGlassboxRoutes().
@@ -1,4 +1,4 @@
1
- import { i as Adapter, x as SectionKind } from './ir-Qnw6L265.js';
1
+ import { i as Adapter, x as SectionKind } from './ir-Bvlkw5ja.js';
2
2
 
3
3
  /**
4
4
  * Internal config + hook types for createGlassboxRoutes().
@@ -1,4 +1,4 @@
1
- import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-BTvyl8-w.mjs';
1
+ import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-Bqn1RVdV.mjs';
2
2
 
3
3
  /**
4
4
  * Glass-Box observability types (alpha.17).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.67",
3
+ "version": "2.0.0-alpha.69",
4
4
  "description": "Prompt compiler with executable provider knowledge for multi-model AI apps: normalized multi-provider transport with fallback chains, compile-time cliff guards, a curated model registry, and a telemetry flight recorder. Swap models without rewriting prompts.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",