@tangle-network/agent-eval 0.118.1 → 0.118.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/analyst/index.d.ts +10 -3
  3. package/dist/analyst/index.js +6 -6
  4. package/dist/benchmarks/index.js +9 -9
  5. package/dist/campaign/index.d.ts +22 -15
  6. package/dist/campaign/index.js +8 -8
  7. package/dist/{chunk-33JA4TFA.js → chunk-267UCQWI.js} +10 -5
  8. package/dist/chunk-267UCQWI.js.map +1 -0
  9. package/dist/{chunk-QKEGNI5B.js → chunk-6QIM2EAP.js} +6 -116
  10. package/dist/chunk-6QIM2EAP.js.map +1 -0
  11. package/dist/{chunk-SVH2ANFD.js → chunk-7V3QDWNL.js} +2 -2
  12. package/dist/{chunk-IDZTTFRR.js → chunk-EGNRE7VA.js} +2 -2
  13. package/dist/chunk-EGNRE7VA.js.map +1 -0
  14. package/dist/{chunk-Q442S5AS.js → chunk-EKHHBKS6.js} +7 -7
  15. package/dist/chunk-EKHHBKS6.js.map +1 -0
  16. package/dist/{chunk-BFW56GTT.js → chunk-F5A4GDQW.js} +3 -3
  17. package/dist/{chunk-BFW56GTT.js.map → chunk-F5A4GDQW.js.map} +1 -1
  18. package/dist/{chunk-3EHHMC6E.js → chunk-FIUFRXP3.js} +2 -2
  19. package/dist/{chunk-KSDQVPLR.js → chunk-H5UD2323.js} +2 -2
  20. package/dist/{chunk-LTVG32KX.js → chunk-JTMFT5QZ.js} +2 -2
  21. package/dist/chunk-JTMFT5QZ.js.map +1 -0
  22. package/dist/chunk-K4DBDHLK.js +158 -0
  23. package/dist/chunk-K4DBDHLK.js.map +1 -0
  24. package/dist/{chunk-JSDVRFAP.js → chunk-KK2O4VWA.js} +2 -2
  25. package/dist/{chunk-VCTY3W6J.js → chunk-MLHRFWQK.js} +1 -1
  26. package/dist/chunk-MLHRFWQK.js.map +1 -0
  27. package/dist/{chunk-YLMUS4MM.js → chunk-QWRLW4CT.js} +5 -5
  28. package/dist/chunk-QWRLW4CT.js.map +1 -0
  29. package/dist/{chunk-OIIMMLRB.js → chunk-VNLWDTDA.js} +3 -3
  30. package/dist/chunk-VNLWDTDA.js.map +1 -0
  31. package/dist/{chunk-FTUMG2U7.js → chunk-ZYHJNKI3.js} +11 -40
  32. package/dist/chunk-ZYHJNKI3.js.map +1 -0
  33. package/dist/cli.js +2 -2
  34. package/dist/contract/index.d.ts +17 -10
  35. package/dist/contract/index.js +11 -11
  36. package/dist/contract/index.js.map +1 -1
  37. package/dist/fuzz.d.ts +8 -1
  38. package/dist/fuzz.js +1 -1
  39. package/dist/fuzz.js.map +1 -1
  40. package/dist/index.d.ts +51 -24
  41. package/dist/index.js +33 -27
  42. package/dist/index.js.map +1 -1
  43. package/dist/openapi.json +1 -1
  44. package/dist/{run-campaign-IM26A6PD.js → run-campaign-DWC67KJP.js} +3 -3
  45. package/dist/trace-attributes.d.ts +37 -1
  46. package/dist/trace-attributes.js +33 -3
  47. package/dist/traces.d.ts +28 -8
  48. package/dist/traces.js +24 -18
  49. package/dist/wire/index.d.ts +8 -1
  50. package/dist/wire/index.js +2 -2
  51. package/package.json +1 -1
  52. package/dist/chunk-33JA4TFA.js.map +0 -1
  53. package/dist/chunk-FTUMG2U7.js.map +0 -1
  54. package/dist/chunk-IDZTTFRR.js.map +0 -1
  55. package/dist/chunk-LTVG32KX.js.map +0 -1
  56. package/dist/chunk-OIIMMLRB.js.map +0 -1
  57. package/dist/chunk-Q442S5AS.js.map +0 -1
  58. package/dist/chunk-QKEGNI5B.js.map +0 -1
  59. package/dist/chunk-VCTY3W6J.js.map +0 -1
  60. package/dist/chunk-WDHBCA3M.js +0 -31
  61. package/dist/chunk-WDHBCA3M.js.map +0 -1
  62. package/dist/chunk-YLMUS4MM.js.map +0 -1
  63. /package/dist/{chunk-SVH2ANFD.js.map → chunk-7V3QDWNL.js.map} +0 -0
  64. /package/dist/{chunk-3EHHMC6E.js.map → chunk-FIUFRXP3.js.map} +0 -0
  65. /package/dist/{chunk-KSDQVPLR.js.map → chunk-H5UD2323.js.map} +0 -0
  66. /package/dist/{chunk-JSDVRFAP.js.map → chunk-KK2O4VWA.js.map} +0 -0
  67. /package/dist/{run-campaign-IM26A6PD.js.map → run-campaign-DWC67KJP.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,13 @@ All notable changes to `@tangle-network/agent-eval` and its sibling `agent-eval-
4
4
 
5
5
  ---
6
6
 
7
+ ## [0.118.2] — 2026-07-13 — interoperable contracts and trace accounting
8
+
9
+ ### Fixed
10
+
11
+ - Every caller-supplied cost-ledger API now uses the public structural `CostLedgerHandle`, so types remain assignable when TypeScript resolves them through separate package entrypoints.
12
+ - Trace writers emit an exact context-input total from known non-overlapping input and cache categories; behavioral analysis uses that value and leaves ambiguous third-party prompt totals unchanged.
13
+
7
14
  ## [0.118.1] — 2026-07-13 — parsed OTLP intake
8
15
 
9
16
  ### Added
@@ -939,6 +939,13 @@ declare class CostLedger {
939
939
  private ensureCostLimitPersisted;
940
940
  private appendEvent;
941
941
  }
942
+ /** Public callback surface for a shared cost ledger.
943
+ *
944
+ * Declaration bundles may expose this type through multiple package subpaths.
945
+ * Keeping callback contracts structural lets those subpaths compose while the
946
+ * concrete {@link CostLedger} retains its private durable state.
947
+ */
948
+ type CostLedgerHandle = Pick<CostLedger, keyof CostLedger>;
942
949
 
943
950
  /**
944
951
  * LLM client with graceful degrade.
@@ -1181,7 +1188,7 @@ interface SemanticConceptJudgeOptions {
1181
1188
  maxHtmlChars?: number;
1182
1189
  /** LlmClient config (baseUrl, apiKey, authHeader, …). */
1183
1190
  llm?: LlmClientOptions;
1184
- costLedger?: CostLedger;
1191
+ costLedger?: CostLedgerHandle;
1185
1192
  costPhase?: string;
1186
1193
  signal?: AbortSignal;
1187
1194
  /**
@@ -1256,7 +1263,7 @@ interface JudgeInput {
1256
1263
  turns: TurnResult[];
1257
1264
  artifacts: CollectedArtifacts;
1258
1265
  /** Shared ledger for paid built-in judges. Direct calls default to an uncapped ledger. */
1259
- costLedger?: CostLedger;
1266
+ costLedger?: CostLedgerHandle;
1260
1267
  costPhase?: string;
1261
1268
  costTags?: Record<string, string>;
1262
1269
  signal?: AbortSignal;
@@ -2941,7 +2948,7 @@ interface StructureFindingsOptions {
2941
2948
  baseUrl: string;
2942
2949
  apiKey?: string;
2943
2950
  /** Optional ledger for direct use. */
2944
- costLedger?: CostLedger;
2951
+ costLedger?: CostLedgerHandle;
2945
2952
  costPhase?: string;
2946
2953
  maxTokens?: number;
2947
2954
  /** Max reask attempts after a zero/invalid extraction. Default 1. */
@@ -10,13 +10,13 @@ import {
10
10
  diffFindings,
11
11
  emitSkillUsageFindings,
12
12
  runSemanticConceptJudge
13
- } from "../chunk-BFW56GTT.js";
13
+ } from "../chunk-F5A4GDQW.js";
14
14
  import {
15
15
  behavioralAnalyst,
16
16
  buildDefaultAnalystRegistry,
17
17
  createChatClient,
18
18
  deriveEfficiencyFindings
19
- } from "../chunk-33JA4TFA.js";
19
+ } from "../chunk-267UCQWI.js";
20
20
  import "../chunk-HHWE3POT.js";
21
21
  import "../chunk-3YYRZDON.js";
22
22
  import {
@@ -65,16 +65,16 @@ import {
65
65
  structureFindings,
66
66
  validatePolicyEdit,
67
67
  validatePolicyEditCandidateRecord
68
- } from "../chunk-OIIMMLRB.js";
68
+ } from "../chunk-VNLWDTDA.js";
69
69
  import "../chunk-NJC7U437.js";
70
- import "../chunk-VCTY3W6J.js";
70
+ import "../chunk-MLHRFWQK.js";
71
71
  import "../chunk-VI2UW6B6.js";
72
- import "../chunk-QKEGNI5B.js";
72
+ import "../chunk-6QIM2EAP.js";
73
73
  import "../chunk-PC4UYEBM.js";
74
74
  import "../chunk-XJYR7XFV.js";
75
75
  import "../chunk-VSMTAMNK.js";
76
76
  import "../chunk-ONWEPEDO.js";
77
- import "../chunk-WDHBCA3M.js";
77
+ import "../chunk-K4DBDHLK.js";
78
78
  import "../chunk-PZ5AY32C.js";
79
79
 
80
80
  // src/analyst/adapters.ts
@@ -16,27 +16,27 @@ import {
16
16
  routing_exports,
17
17
  runBenchmarkAdapter,
18
18
  summarizeBenchmarkCampaign
19
- } from "../chunk-JSDVRFAP.js";
20
- import "../chunk-Q442S5AS.js";
21
- import "../chunk-YLMUS4MM.js";
22
- import "../chunk-IDZTTFRR.js";
19
+ } from "../chunk-KK2O4VWA.js";
20
+ import "../chunk-EKHHBKS6.js";
21
+ import "../chunk-QWRLW4CT.js";
22
+ import "../chunk-EGNRE7VA.js";
23
23
  import "../chunk-3YYRZDON.js";
24
- import "../chunk-OIIMMLRB.js";
24
+ import "../chunk-VNLWDTDA.js";
25
25
  import "../chunk-ARU2PZFM.js";
26
26
  import "../chunk-NJC7U437.js";
27
27
  import "../chunk-PJQFMIOX.js";
28
- import "../chunk-VCTY3W6J.js";
28
+ import "../chunk-MLHRFWQK.js";
29
29
  import "../chunk-VI2UW6B6.js";
30
- import "../chunk-3EHHMC6E.js";
30
+ import "../chunk-FIUFRXP3.js";
31
31
  import "../chunk-GGE4NNQT.js";
32
- import "../chunk-QKEGNI5B.js";
32
+ import "../chunk-6QIM2EAP.js";
33
33
  import "../chunk-PC4UYEBM.js";
34
34
  import "../chunk-S3UZOQ5Y.js";
35
35
  import "../chunk-MA6HLL3S.js";
36
36
  import "../chunk-XJYR7XFV.js";
37
37
  import "../chunk-VSMTAMNK.js";
38
38
  import "../chunk-ONWEPEDO.js";
39
- import "../chunk-WDHBCA3M.js";
39
+ import "../chunk-K4DBDHLK.js";
40
40
  import "../chunk-PZ5AY32C.js";
41
41
  export {
42
42
  BENCHMARK_SPLIT_SEED,
@@ -888,6 +888,13 @@ declare class CostLedger {
888
888
  private ensureCostLimitPersisted;
889
889
  private appendEvent;
890
890
  }
891
+ /** Public callback surface for a shared cost ledger.
892
+ *
893
+ * Declaration bundles may expose this type through multiple package subpaths.
894
+ * Keeping callback contracts structural lets those subpaths compose while the
895
+ * concrete {@link CostLedger} retains its private durable state.
896
+ */
897
+ type CostLedgerHandle = Pick<CostLedger, keyof CostLedger>;
891
898
 
892
899
  /**
893
900
  * RawProviderSink — first-class persistence for the actual HTTP-level
@@ -1469,7 +1476,7 @@ interface JudgeConfig<TArtifact, TScenario extends Scenario = Scenario> {
1469
1476
  scenario: TScenario;
1470
1477
  signal: AbortSignal;
1471
1478
  /** Shared run spend account and receipt attribution phase. */
1472
- costLedger?: CostLedger;
1479
+ costLedger?: CostLedgerHandle;
1473
1480
  costPhase?: string;
1474
1481
  costTags?: Record<string, string>;
1475
1482
  }): JudgeScore | Promise<JudgeScore>;
@@ -1656,7 +1663,7 @@ interface ProposeContext<TFindings = unknown> {
1656
1663
  * reflection may ignore it. See {@link ParetoParent}. */
1657
1664
  paretoParents?: ParetoParent[];
1658
1665
  /** Shared run spend account and receipt attribution phase. */
1659
- costLedger?: CostLedger;
1666
+ costLedger?: CostLedgerHandle;
1660
1667
  costPhase?: string;
1661
1668
  /** FIREWALL (non-negotiable): the held-out judge is write-only — its verdicts
1662
1669
  * score the chosen output and gate promotion, and are NEVER an input to
@@ -1740,7 +1747,7 @@ interface GateContext<TArtifact, TScenario extends Scenario> {
1740
1747
  baseline: number;
1741
1748
  };
1742
1749
  /** Shared run spend account and receipt attribution phase. */
1743
- costLedger?: CostLedger;
1750
+ costLedger?: CostLedgerHandle;
1744
1751
  costPhase?: string;
1745
1752
  signal: AbortSignal;
1746
1753
  }
@@ -2064,7 +2071,7 @@ interface LlmJudgeOptions<TArtifact, TScenario extends Scenario = Scenario> {
2064
2071
  scenario: TScenario;
2065
2072
  }) => string;
2066
2073
  /** Strict runtime contract; its JSON Schema is sent to the provider. */
2067
- costLedger?: CostLedger;
2074
+ costLedger?: CostLedgerHandle;
2068
2075
  responseSchema?: {
2069
2076
  name: string;
2070
2077
  schema: z.ZodObject;
@@ -2094,7 +2101,7 @@ interface ReferenceEquivalenceJudgeOptions {
2094
2101
  /** Used only by the direct-call adapter. */
2095
2102
  signal?: AbortSignal;
2096
2103
  /** Optional receipt destination for direct calls; campaigns supply their own. */
2097
- costLedger?: CostLedger;
2104
+ costLedger?: CostLedgerHandle;
2098
2105
  }
2099
2106
  /** Build the campaign-native expected-answer judge. */
2100
2107
  declare function createReferenceEquivalenceJudge(options: ReferenceEquivalenceJudgeOptions): JudgeConfig<string, ReferenceEquivalenceScenario>;
@@ -2844,7 +2851,7 @@ interface RunCampaignOptions<TScenario extends Scenario, TArtifact> {
2844
2851
  costCeiling?: number;
2845
2852
  /** Shared spend account. Improvement loops pass one ledger through every
2846
2853
  * campaign so the ceiling and returned total are run-wide. */
2847
- costLedger?: CostLedger;
2854
+ costLedger?: CostLedgerHandle;
2848
2855
  /** Attribution label for receipts recorded by this campaign. */
2849
2856
  costPhase?: string;
2850
2857
  /** Max concurrent cells. Default 2. */
@@ -4106,7 +4113,7 @@ interface RunOptimizationBaseOptions<TScenario extends Scenario, TArtifact> exte
4106
4113
  }>;
4107
4114
  history: GenerationRecord[];
4108
4115
  /** Shared run spend account and receipt attribution phase. */
4109
- costLedger?: CostLedger;
4116
+ costLedger?: CostLedgerHandle;
4110
4117
  costPhase?: string;
4111
4118
  }) => Promise<unknown[]>;
4112
4119
  }
@@ -5148,14 +5155,14 @@ interface ProposePatchesArgs {
5148
5155
  /** How many candidate patches to propose. */
5149
5156
  count: number;
5150
5157
  signal: AbortSignal;
5151
- costLedger?: CostLedger;
5158
+ costLedger?: CostLedgerHandle;
5152
5159
  costPhase?: string;
5153
5160
  }
5154
5161
  interface SkillOptProposerOptions {
5155
5162
  llm: LlmClientOptions;
5156
5163
  model: string;
5157
5164
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5158
- costLedger?: CostLedger;
5165
+ costLedger?: CostLedgerHandle;
5159
5166
  /** What the skill document governs — orients the prompt. */
5160
5167
  target: string;
5161
5168
  /** Default ops-per-patch cap when used as a bare `SurfaceProposer`. The
@@ -5444,7 +5451,7 @@ interface GepaProposerOptions {
5444
5451
  /** Model that performs the reflection. */
5445
5452
  model: string;
5446
5453
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5447
- costLedger?: CostLedger;
5454
+ costLedger?: CostLedgerHandle;
5448
5455
  /** What is being optimized — appears in the reflection prompt for orientation. */
5449
5456
  target: string;
5450
5457
  /** Surface-specific mutation levers offered to the model. */
@@ -5509,7 +5516,7 @@ interface HaloProposerOptions {
5509
5516
  /** Model used to APPLY halo's findings to the prompt surface. Default = `model`. */
5510
5517
  applyModel?: string;
5511
5518
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5512
- costLedger?: CostLedger;
5519
+ costLedger?: CostLedgerHandle;
5513
5520
  analysisMaximumCharge?: MaximumCharge;
5514
5521
  analysisReceipt?: (report: string) => CostReceiptInput;
5515
5522
  applyMaxTokens?: number;
@@ -5646,7 +5653,7 @@ interface LlmPolicyEditProposerOptions {
5646
5653
  llm: LlmClientOptions;
5647
5654
  model: string;
5648
5655
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5649
- costLedger?: CostLedger;
5656
+ costLedger?: CostLedgerHandle;
5650
5657
  /** Plain-language description of the JSON surface being improved. */
5651
5658
  target: string;
5652
5659
  /** PolicyEdit target surface every authored edit must retain. */
@@ -5721,7 +5728,7 @@ declare function projectPolicyEditHistory(history: readonly GenerationRecord[],
5721
5728
 
5722
5729
  interface MemoryCurationProposerOptions {
5723
5730
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5724
- costLedger?: CostLedger;
5731
+ costLedger?: CostLedgerHandle;
5725
5732
  /** Top-K lessons retained in the surface memory block. Default 12. */
5726
5733
  maxEntries?: number;
5727
5734
  /** Heading rendered above the lessons inside the block. Default below. */
@@ -5931,7 +5938,7 @@ interface TraceAnalystProposerOptions {
5931
5938
  * Keep this EQUAL to haloProposer's `applyModel` for an apples-to-apples run. */
5932
5939
  applyModel?: string;
5933
5940
  /** Optional ledger for direct proposer use. Campaign context takes precedence. */
5934
- costLedger?: CostLedger;
5941
+ costLedger?: CostLedgerHandle;
5935
5942
  analysisMaximumCharge?: MaximumCharge;
5936
5943
  analysisReceipt?: (report: string) => CostReceiptInput;
5937
5944
  applyMaxTokens?: number;
@@ -7314,4 +7321,4 @@ declare function verifyCodeSurface(surface: CodeSurface, worktreeDir?: string):
7314
7321
  * identity against the checkout at `worktreeRef`. */
7315
7322
  declare function resolveWorktreePath(surface: CodeSurface, worktreeDir?: string): string;
7316
7323
 
7317
- export { type AcceptedEdit, type AceProposerOptions, type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type ApplySkillPatchResult, type AxisEvidence, type AxisVerdict, type BuildAnalystSurfaceDispatchOptions, type BuildEvidenceVectorOptions, type BuildLoopProvenanceArgs, type CampaignAggregates, type CampaignArtifactWriter, type CampaignBreakdown, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignRunPlan, type CampaignRunPlanCell, type CampaignStorage, type CampaignTokenUsage, type CampaignTraceWriter, type CodeSurface, type CodeSurfaceVerification, type CompareProposersOptions, type CompositeProposerOptions, type CrossSurfaceAdditionDecision, type CrossSurfaceAdditionRejectionReason, type CrossSurfaceAttemptCompleteness, type CrossSurfaceBestSingleSelection, type CrossSurfaceBootstrapPolicy, type CrossSurfaceCandidate, type CrossSurfaceCandidateComparison, type CrossSurfaceCandidateEvidence, type CrossSurfaceCandidateOutcome, type CrossSurfaceCandidateSummary, type CrossSurfaceComponent, type CrossSurfaceComponentEvidence, type CrossSurfaceCompositionStep, type CrossSurfaceDistribution, type CrossSurfaceEligibility, type CrossSurfaceEvidenceBreakdown, type CrossSurfaceIneligibilityReason, type CrossSurfaceInteractionAwareSelection, type CrossSurfaceInteractionEffect, type CrossSurfaceInteractionPath, type CrossSurfaceInteractionReport, type CrossSurfaceInteractionTask, type CrossSurfaceNaiveStackSelection, type CrossSurfacePairCompatibility, type CrossSurfacePairEvidence, type CrossSurfacePairIncompatibilityReason, type CrossSurfacePairwiseEntry, type CrossSurfaceRankedSingle, type CrossSurfaceRelativeCost, type CrossSurfaceSelectionPolicy, type CrossSurfaceSelections, type CrossSurfaceTaskRow, DEFAULT_POLICY_EDIT_HISTORY_LIMITS, type DefaultProductionGateOptions, type DimensionRegression, type DiscriminationScore, type DispatchContext, type DispatchFn, type EmitLoopProvenanceArgs, type EmitLoopProvenanceResult, type EvalFixture, type EvalFixtureFile, type EvalFixtureLoadOptions, type EvalFixtureRunPlan, type EvalFixtureScenario, type EvalFixtureValidationMode, type EvidenceVector, type EvolutionaryProposerOptions, type FailureModeRecallJudgeOptions, type FapoAttributionSignals, type FapoEntryConfig, type FapoFailureCluster, type FapoOptimizationLevel, type FapoProposerOptions, type FapoReviewInput, type FapoReviewIssue, type FapoReviewResult, type FapoScopeContract, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaProposerConstraints, type GepaProposerOptions, type GitWorktreeAdapterOptions, type Governor, type GovernorContext, type GovernorOp, type HaloProposerOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type HeuristicGovernorOptions, type JsonPolicyEditTargetSurface, type JsonPrimitive, type JsonValue, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, Lineage, type LineageEdge, type LineageGraph, type LineageNode, type LineageNodeInput, type LineageStore, type LlmJudgeDimension, type LlmJudgeOptions, type LlmPolicyEditProposerOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceRecord, type MemoryCurationProposerOptions, type MutableSurface, type Mutator, type NeutralizationGateOptions, type ObjectiveSource, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationProposer, type OptimizerConfig, type OptimizerEntryConfig, POLICY_EDIT_CANDIDATE_RECORD_SCHEMA, type PairedHoldout, type ParameterCandidate, type ParameterChange, type ParameterSweepProposerOptions, type ParetoParent, type ParetoSignificanceGateOptions, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PolicyEditAuthorScenarioRow, type PolicyEditCandidateRecord, type PolicyEditCandidateSummary, type PolicyEditFindingInput, type PolicyEditFindingSource, type PolicyEditHistoryCandidateContext, type PolicyEditHistoryGenerationContext, type PolicyEditHistoryProjectionOptions, type PolicyEditObjective, type PolicyEditOutcomeContext, type PolicyEditProposerOptions, type PowerPreflight, type PowerPreflightOptions, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposeContext, type ProposePatchesArgs, type ProposedCandidate, type ProposerComparison, type ProposerEntry, type ProposerPairwise, type ProposerScore, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RejectedEdit, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunLineageLoopOptions, type RunLineageLoopResult, type RunLineageLoopSeed, type RunLineageOptions, type RunLineageResult, type RunLineageSeed, type RunLineageStepResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, type RunSkillOptOptions, type RunSkillOptResult, SEARCH_LEDGER_SCHEMA, type Scenario, type ScenarioAggregate, type ScenarioRollup, type ScenarioSignal, type ScoreboardRenderOptions, type ScoreboardRow, type ScoreboardSummary, type ScoredRollout, type ScoredSurfaceOutcome, type SearchAccountingAudit, type SearchArtifactRef, type SearchAttemptAccounting, type SearchCandidateDecidedEvent, type SearchCandidateLineage, type SearchCandidateRegisteredEvent, type SearchCandidateSlot, type SearchCandidateSlotClosedEvent, type SearchCandidateSurface, type SearchCompletedEvent, type SearchCostAccounting, type SearchFailureReason, type SearchLedger, type SearchLedgerAppendResult, SearchLedgerConflictError, type SearchLedgerEntry, SearchLedgerError, type SearchLedgerEvent, type SearchLedgerHash, SearchLedgerIntegrityError, type SearchLedgerReplay, type SearchModelIdentity, type SearchOperationKind, type SearchOperationRecordedEvent, type SearchPlan, type SearchPlannedEvent, type SearchPlannedOperation, type SearchPlannedTask, type SearchSourceRef, type SearchSurfaceEffect, type SearchSurfaceEvidence, type SearchSurfaceKind, type SearchTaskAttemptedEvent, type SearchTaskOutcome, type SearchTokenAccounting, type SelectPolicyEditAuthorRowsOptions, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SerializedJsonBudget, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptEpochRecord, type SkillOptEvidence, type SkillOptProposer, type SkillOptProposerOptions, type SkillPatch, type SkillPatchOp, SkillPatchParseError, type SkillPatchRejection, type SurfaceProposer, type SurfaceScore, type TraceAnalystProposerOptions, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, aceProposer, acquireSingleRunLock, analyzeCrossSurfaceInteractions, applySkillPatch, assertCodeSurfaceIdentity, assertPolicyEditAuthorContextBudget, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, callbackGovernor, campaignBreakdown, campaignMeanComposite, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareProposers, composeGate, compositeProposer, countSentenceEdits, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, defaultRenderDiff, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, evolutionaryProposer, extractFapoAttributionSignals, extractH2Sections, failureModeRecallJudge, fapoEscalationEntry, fapoProposer, fsCampaignStorage, fsLineageStore, gepaParetoEntry, gepaProposer, gepaReflectionEntry, gitWorktreeAdapter, haloProposer, heldOutGate, heldoutSignificance, heuristicGovernor, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, lineageNodeId, llmJudge, llmPolicyEditProposer, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceSpans, makePlaybackDispatch, memLineageStore, memoryCurationProposer, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, pairHoldout, parameterSweepProposer, paretoPolicy, paretoSignificanceGate, parseSkillPatchResponse, patchEditCount, planCampaignRun, planEvalFixtureRun, policyEditProposer, powerPreflight, projectPolicyEditHistory, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runLineage, runLineageLoop, runOptimization, runProfileMatrix, runSkillOpt, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, selectPolicyEditAuthorRows, sequentialDecide, sequentialPairedGate, skillOptEntry, skillOptProposer, surfaceContentHash, surfaceHash, tangleTracesRoot, traceAnalystProposer, userStoryScoreboard, validatePolicyEditCandidateRecord, validateSearchLedgerEvent, verifyCodeSurface };
7324
+ export { type AcceptedEdit, type AceProposerOptions, type AnalystArtifact, type AnalystScenario, type AnalyzeCrossSurfaceInteractionsInput, type ApplySkillPatchResult, type AxisEvidence, type AxisVerdict, type BuildAnalystSurfaceDispatchOptions, type BuildEvidenceVectorOptions, type BuildLoopProvenanceArgs, type CampaignAggregates, type CampaignArtifactWriter, type CampaignBreakdown, type CampaignCellResult, type CampaignCostMeter, type CampaignResult, type CampaignRunPlan, type CampaignRunPlanCell, type CampaignStorage, type CampaignTokenUsage, type CampaignTraceWriter, type CodeSurface, type CodeSurfaceVerification, type CompareProposersOptions, type CompositeProposerOptions, type CostLedgerHandle, type CrossSurfaceAdditionDecision, type CrossSurfaceAdditionRejectionReason, type CrossSurfaceAttemptCompleteness, type CrossSurfaceBestSingleSelection, type CrossSurfaceBootstrapPolicy, type CrossSurfaceCandidate, type CrossSurfaceCandidateComparison, type CrossSurfaceCandidateEvidence, type CrossSurfaceCandidateOutcome, type CrossSurfaceCandidateSummary, type CrossSurfaceComponent, type CrossSurfaceComponentEvidence, type CrossSurfaceCompositionStep, type CrossSurfaceDistribution, type CrossSurfaceEligibility, type CrossSurfaceEvidenceBreakdown, type CrossSurfaceIneligibilityReason, type CrossSurfaceInteractionAwareSelection, type CrossSurfaceInteractionEffect, type CrossSurfaceInteractionPath, type CrossSurfaceInteractionReport, type CrossSurfaceInteractionTask, type CrossSurfaceNaiveStackSelection, type CrossSurfacePairCompatibility, type CrossSurfacePairEvidence, type CrossSurfacePairIncompatibilityReason, type CrossSurfacePairwiseEntry, type CrossSurfaceRankedSingle, type CrossSurfaceRelativeCost, type CrossSurfaceSelectionPolicy, type CrossSurfaceSelections, type CrossSurfaceTaskRow, DEFAULT_POLICY_EDIT_HISTORY_LIMITS, type DefaultProductionGateOptions, type DimensionRegression, type DiscriminationScore, type DispatchContext, type DispatchFn, type EmitLoopProvenanceArgs, type EmitLoopProvenanceResult, type EvalFixture, type EvalFixtureFile, type EvalFixtureLoadOptions, type EvalFixtureRunPlan, type EvalFixtureScenario, type EvalFixtureValidationMode, type EvidenceVector, type EvolutionaryProposerOptions, type FailureModeRecallJudgeOptions, type FapoAttributionSignals, type FapoEntryConfig, type FapoFailureCluster, type FapoOptimizationLevel, type FapoProposerOptions, type FapoReviewInput, type FapoReviewIssue, type FapoReviewResult, type FapoScopeContract, FileSearchLedger, FsLabeledScenarioStore, type FsLabeledScenarioStoreOptions, type Gate, type GateContext, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaProposerConstraints, type GepaProposerOptions, type GitWorktreeAdapterOptions, type Governor, type GovernorContext, type GovernorOp, type HaloProposerOptions, type HeldOutGateOptions, type HeldoutSignificance, type HeldoutSignificanceOptions, type HeuristicGovernorOptions, type JsonPolicyEditTargetSurface, type JsonPrimitive, type JsonValue, type JudgeAggregate, type JudgeConfig, type JudgeDimension, type JudgeScore, type LabelTrust, type LabeledScenarioRecord, type LabeledScenarioSampleArgs, type LabeledScenarioSource, type LabeledScenarioStore, LabeledScenarioStoreError, type LabeledScenarioWrite, Lineage, type LineageEdge, type LineageGraph, type LineageNode, type LineageNodeInput, type LineageStore, type LlmJudgeDimension, type LlmJudgeOptions, type LlmPolicyEditProposerOptions, type LoadEvalFixtureScenariosOptions, type LoopProvenanceBackend, type LoopProvenanceCandidate, type LoopProvenanceRecord, type MemoryCurationProposerOptions, type MutableSurface, type Mutator, type NeutralizationGateOptions, type ObjectiveSource, type OpenAutoPrOptions, type OpenAutoPrResult, type OpenSearchLedgerOptions, type OptimizationProposer, type OptimizerConfig, type OptimizerEntryConfig, POLICY_EDIT_CANDIDATE_RECORD_SCHEMA, type PairedHoldout, type ParameterCandidate, type ParameterChange, type ParameterSweepProposerOptions, type ParetoParent, type ParetoSignificanceGateOptions, type PlanCampaignRunOptions, type PlanEvalFixtureRunOptions, type PlaybackContext, type PlaybackDriver, type PlaybackStep, type PolicyEditAuthorScenarioRow, type PolicyEditCandidateRecord, type PolicyEditCandidateSummary, type PolicyEditFindingInput, type PolicyEditFindingSource, type PolicyEditHistoryCandidateContext, type PolicyEditHistoryGenerationContext, type PolicyEditHistoryProjectionOptions, type PolicyEditObjective, type PolicyEditOutcomeContext, type PolicyEditProposerOptions, type PowerPreflight, type PowerPreflightOptions, type ProfileDispatchFn, ProfileMatrixError, type ProfileSummary, type PromotionObjective, type PromotionPolicy, type ProposeContext, type ProposePatchesArgs, type ProposedCandidate, type ProposerComparison, type ProposerEntry, type ProposerPairwise, type ProposerScore, type RedactionStatus, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceScenario, type RejectedEdit, type RolloutArgumentDiff, type RolloutArgumentDiffOptions, type RolloutCall, type RunCampaignOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunLineageLoopOptions, type RunLineageLoopResult, type RunLineageLoopSeed, type RunLineageOptions, type RunLineageResult, type RunLineageSeed, type RunLineageStepResult, type RunOptimizationOptions, type RunOptimizationResult, type RunProfileMatrixOptions, type RunProfileMatrixResult, type RunSkillOptOptions, type RunSkillOptResult, SEARCH_LEDGER_SCHEMA, type Scenario, type ScenarioAggregate, type ScenarioRollup, type ScenarioSignal, type ScoreboardRenderOptions, type ScoreboardRow, type ScoreboardSummary, type ScoredRollout, type ScoredSurfaceOutcome, type SearchAccountingAudit, type SearchArtifactRef, type SearchAttemptAccounting, type SearchCandidateDecidedEvent, type SearchCandidateLineage, type SearchCandidateRegisteredEvent, type SearchCandidateSlot, type SearchCandidateSlotClosedEvent, type SearchCandidateSurface, type SearchCompletedEvent, type SearchCostAccounting, type SearchFailureReason, type SearchLedger, type SearchLedgerAppendResult, SearchLedgerConflictError, type SearchLedgerEntry, SearchLedgerError, type SearchLedgerEvent, type SearchLedgerHash, SearchLedgerIntegrityError, type SearchLedgerReplay, type SearchModelIdentity, type SearchOperationKind, type SearchOperationRecordedEvent, type SearchPlan, type SearchPlannedEvent, type SearchPlannedOperation, type SearchPlannedTask, type SearchSourceRef, type SearchSurfaceEffect, type SearchSurfaceEvidence, type SearchSurfaceKind, type SearchTaskAttemptedEvent, type SearchTaskOutcome, type SearchTokenAccounting, type SelectPolicyEditAuthorRowsOptions, type SequentialDecideFn, type SequentialDecideOptions, type SequentialDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SerializedJsonBudget, type SessionScript, type SingleRunLock, type SingleRunLockOptions, type SkillOptEpochRecord, type SkillOptEvidence, type SkillOptProposer, type SkillOptProposerOptions, type SkillPatch, type SkillPatchOp, SkillPatchParseError, type SkillPatchRejection, type SurfaceProposer, type SurfaceScore, type TraceAnalystProposerOptions, type TraceSpan, type TransientFailureOptions, type UngroundedLiteralReport, type UserStory, type UserStoryVerdict, type Worktree, type WorktreeAdapter, WorktreeAdapterError, aceProposer, acquireSingleRunLock, analyzeCrossSurfaceInteractions, applySkillPatch, assertCodeSurfaceIdentity, assertPolicyEditAuthorContextBudget, buildAnalystSurfaceDispatch, buildEvidenceVector, buildLoopProvenanceRecord, callbackGovernor, campaignBreakdown, campaignMeanComposite, classifyUngroundedLiterals, codeSurfaceIdentityMaterial, compareProposers, composeGate, compositeProposer, countSentenceEdits, createReferenceEquivalenceJudge, createRunCostLedger, defaultProductionGate, defaultRenderDiff, detectScale, dimensionRegressions, discoverEvalFixtures, emitLoopProvenance, evolutionaryProposer, extractFapoAttributionSignals, extractH2Sections, failureModeRecallJudge, fapoEscalationEntry, fapoProposer, fsCampaignStorage, fsLineageStore, gepaParetoEntry, gepaProposer, gepaReflectionEntry, gitWorktreeAdapter, haloProposer, heldOutGate, heldoutSignificance, heuristicGovernor, inMemoryCampaignStorage, isProposedCandidate, isTransientTransportFailure, labelTrustRank, lineageNodeId, llmJudge, llmPolicyEditProposer, loadEvalFixture, loadEvalFixtureScenarios, loopProvenanceSpans, makePlaybackDispatch, memLineageStore, memoryCurationProposer, neutralizationGate, neutralizeText, openAutoPr, openSearchLedger, pairHoldout, parameterSweepProposer, paretoPolicy, paretoSignificanceGate, parseSkillPatchResponse, patchEditCount, planCampaignRun, planEvalFixtureRun, policyEditProposer, powerPreflight, projectPolicyEditHistory, provenanceRecordPath, provenanceSpansPath, renderScoreboardMarkdown, resolveRunDir, resolveWorktreePath, rolloutArgumentDiff, runCampaign, runEval, runImprovementLoop, runLineage, runLineageLoop, runOptimization, runProfileMatrix, runSkillOpt, scoreDiscrimination, scoreUserStory, scoreboardSummary, selectDiscriminative, selectPolicyEditAuthorRows, sequentialDecide, sequentialPairedGate, skillOptEntry, skillOptProposer, surfaceContentHash, surfaceHash, tangleTracesRoot, traceAnalystProposer, userStoryScoreboard, validatePolicyEditCandidateRecord, validateSearchLedgerEvent, verifyCodeSurface };
@@ -66,7 +66,7 @@ import {
66
66
  userStoryScoreboard,
67
67
  validateSearchLedgerEvent,
68
68
  verifyCodeSurface
69
- } from "../chunk-Q442S5AS.js";
69
+ } from "../chunk-EKHHBKS6.js";
70
70
  import {
71
71
  assertCodeSurfaceIdentity,
72
72
  buildEvidenceVector,
@@ -103,7 +103,7 @@ import {
103
103
  runOptimization,
104
104
  surfaceContentHash,
105
105
  surfaceHash
106
- } from "../chunk-YLMUS4MM.js";
106
+ } from "../chunk-QWRLW4CT.js";
107
107
  import {
108
108
  SearchLedgerConflictError,
109
109
  SearchLedgerError,
@@ -115,27 +115,27 @@ import {
115
115
  resolveRunDir,
116
116
  runCampaign,
117
117
  tangleTracesRoot
118
- } from "../chunk-IDZTTFRR.js";
118
+ } from "../chunk-EGNRE7VA.js";
119
119
  import "../chunk-3YYRZDON.js";
120
120
  import {
121
121
  POLICY_EDIT_CANDIDATE_RECORD_SCHEMA,
122
122
  validatePolicyEditCandidateRecord
123
- } from "../chunk-OIIMMLRB.js";
123
+ } from "../chunk-VNLWDTDA.js";
124
124
  import "../chunk-ARU2PZFM.js";
125
125
  import "../chunk-NJC7U437.js";
126
126
  import "../chunk-PJQFMIOX.js";
127
- import "../chunk-VCTY3W6J.js";
127
+ import "../chunk-MLHRFWQK.js";
128
128
  import "../chunk-VI2UW6B6.js";
129
- import "../chunk-3EHHMC6E.js";
129
+ import "../chunk-FIUFRXP3.js";
130
130
  import "../chunk-GGE4NNQT.js";
131
- import "../chunk-QKEGNI5B.js";
131
+ import "../chunk-6QIM2EAP.js";
132
132
  import "../chunk-PC4UYEBM.js";
133
133
  import "../chunk-S3UZOQ5Y.js";
134
134
  import "../chunk-MA6HLL3S.js";
135
135
  import "../chunk-XJYR7XFV.js";
136
136
  import "../chunk-VSMTAMNK.js";
137
137
  import "../chunk-ONWEPEDO.js";
138
- import "../chunk-WDHBCA3M.js";
138
+ import "../chunk-K4DBDHLK.js";
139
139
  import "../chunk-PZ5AY32C.js";
140
140
  export {
141
141
  DEFAULT_POLICY_EDIT_HISTORY_LIMITS,
@@ -6,16 +6,19 @@ import {
6
6
  DEFAULT_TRACE_ANALYST_KINDS,
7
7
  createTraceAnalystKind,
8
8
  makeFinding
9
- } from "./chunk-OIIMMLRB.js";
9
+ } from "./chunk-VNLWDTDA.js";
10
10
  import {
11
11
  LlmClient
12
12
  } from "./chunk-NJC7U437.js";
13
13
  import {
14
+ spanEpochMillis
15
+ } from "./chunk-6QIM2EAP.js";
16
+ import {
17
+ LLM_CONTEXT_TOKENS,
14
18
  LLM_INPUT_TOKEN_ATTR_KEYS,
15
19
  LLM_OUTPUT_TOKEN_ATTR_KEYS,
16
- TOOL_NAME_ATTR_KEYS,
17
- spanEpochMillis
18
- } from "./chunk-QKEGNI5B.js";
20
+ TOOL_NAME_ATTR_KEYS
21
+ } from "./chunk-K4DBDHLK.js";
19
22
 
20
23
  // src/analyst/chat-client.ts
21
24
  function createChatClient(opts) {
@@ -114,6 +117,8 @@ function numAttr(attrs, keys) {
114
117
  return null;
115
118
  }
116
119
  function inputTokensOf(s) {
120
+ const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS]);
121
+ if (exactContext !== null) return exactContext;
117
122
  return numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes["llm.usage.input_tokens"]);
118
123
  }
119
124
  function outputTokensOf(s) {
@@ -542,4 +547,4 @@ export {
542
547
  behavioralAnalyst,
543
548
  buildDefaultAnalystRegistry
544
549
  };
545
- //# sourceMappingURL=chunk-33JA4TFA.js.map
550
+ //# sourceMappingURL=chunk-267UCQWI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/analyst/chat-client.ts","../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/default-registry.ts"],"sourcesContent":["/**\n * ChatClient — the single LLM abstraction analysts call.\n *\n * agent-eval already ships an `LlmClient` (OpenAI-compatible, retry,\n * graceful JSON-schema degrade) and judges that talk to `TCloud`. Two\n * mixed patterns force every analyst author to pick a transport, which\n * couples analyst code to runtime concerns (cli-bridge vs router vs\n * sandbox-sdk) it shouldn't know about.\n *\n * `ChatClient` is one interface every analyst takes via `AnalystContext.chat`.\n * The operator decides at the registry boundary which transport binds\n * to it. Analyst code stays transport-agnostic; swapping production\n * (sandbox-sdk) for local dev (cli-bridge) or tests (mock) is a one-\n * line factory call.\n *\n * Designed to coexist: existing `LlmClient` callers and existing\n * `TCloud`-based judges keep working untouched. New analyst code uses\n * `ChatClient`. When old call sites migrate, they pick up budgeting,\n * cancellation, and unified telemetry for free.\n */\n\nimport {\n type LlmCallRequest,\n type LlmCallResult,\n LlmClient,\n type LlmClientOptions,\n} from '../llm-client'\n\n/**\n * Unified chat interface. Mirrors LlmCallRequest/Result so the OpenAI-\n * compatible mental model stays. Two methods: a one-shot `chat()` and\n * an `streamChat()` for future agentic loops (not yet exposed).\n */\nexport interface ChatClient {\n /** Display name of the bound transport — included in telemetry. */\n readonly transport: ChatTransport\n /** Default model when caller omits — operators bind this per environment. */\n readonly defaultModel?: string\n /** Total provider attempts this transport can make for one chat call. */\n readonly maximumAttempts?: number\n\n /** Implementations must enforce `req.maxTokens` when it is present. */\n chat(req: ChatRequest, opts?: ChatCallOpts): Promise<ChatResponse>\n}\n\nexport type ChatTransport =\n | 'router' // router.tangle.tools — production paid models\n | 'sandbox-sdk' // box.streamPrompt() — chat completion via sandbox SDK\n | 'cli-bridge' // local cli-bridge for dev / local-only runs\n | 'direct-provider' // direct OpenAI / Anthropic / etc. — bypass router\n | 'mock' // test-time injection\n\nexport interface ChatRequest extends Omit<LlmCallRequest, 'model'> {\n /** Optional — falls back to ChatClient.defaultModel. */\n model?: string\n}\n\nexport type ChatResponse = LlmCallResult\n\nexport interface ChatCallOpts {\n /** Cancel the in-flight request. */\n signal?: AbortSignal\n /** Hard USD ceiling for this single call (informational; the underlying transport may not enforce). */\n maxCostUsd?: number\n /** Correlation tag carried into request headers when the transport allows. */\n correlationId?: string\n /** Stable provider idempotency key for retries/redrives of one paid call. */\n idempotencyKey?: string\n}\n\n// ── Factory ─────────────────────────────────────────────────────────\n\nexport type CreateChatClientOpts =\n | RouterTransportOpts\n | CliBridgeTransportOpts\n | DirectProviderTransportOpts\n | SandboxSdkTransportOpts\n | MockTransportOpts\n\ninterface BaseTransportOpts {\n defaultModel?: string\n /** Total provider attempts. Required for opaque transports used in capped runs. */\n maximumAttempts?: number\n}\n\nexport interface RouterTransportOpts extends BaseTransportOpts {\n transport: 'router'\n baseUrl?: string\n apiKey: string\n}\n\nexport interface CliBridgeTransportOpts extends BaseTransportOpts {\n transport: 'cli-bridge'\n baseUrl?: string\n bearer?: string\n}\n\nexport interface DirectProviderTransportOpts extends BaseTransportOpts {\n transport: 'direct-provider'\n baseUrl: string\n apiKey: string\n}\n\n/**\n * Sandbox-SDK transport. Provided as a thin pass-through: the caller\n * supplies a callable that mimics LlmClient.chat() against an already-\n * configured Sandbox handle. We don't import the SDK here to keep\n * agent-eval dep-free of @tangle-network/sandbox.\n */\nexport interface SandboxSdkTransportOpts extends BaseTransportOpts {\n transport: 'sandbox-sdk'\n chat: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Mock transport for tests. The handler receives the request and returns\n * whatever the test wants. No retries, no JSON-schema degrade.\n */\nexport interface MockTransportOpts extends BaseTransportOpts {\n transport: 'mock'\n handler: (req: ChatRequest, opts?: ChatCallOpts) => Promise<ChatResponse>\n}\n\n/**\n * Build a ChatClient bound to a specific transport. The returned client\n * is safe to share across analysts in a single registry run.\n */\nexport function createChatClient(opts: CreateChatClientOpts): ChatClient {\n switch (opts.transport) {\n case 'router':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl ?? 'https://router.tangle.tools/v1',\n apiKey: opts.apiKey,\n maxRetries: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'cli-bridge':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl ?? 'http://127.0.0.1:3344/v1',\n apiKey: opts.bearer ?? '',\n maxRetries: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'direct-provider':\n return wrapLlmClient(\n opts.transport,\n opts.defaultModel,\n new LlmClient({\n baseUrl: opts.baseUrl,\n apiKey: opts.apiKey,\n maxRetries: opts.maximumAttempts,\n } as LlmClientOptions),\n )\n case 'sandbox-sdk':\n return {\n transport: 'sandbox-sdk',\n defaultModel: opts.defaultModel,\n maximumAttempts: opts.maximumAttempts,\n chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts),\n }\n case 'mock':\n return {\n transport: 'mock',\n defaultModel: opts.defaultModel,\n maximumAttempts: 1,\n chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts),\n }\n }\n}\n\nfunction wrapLlmClient(\n transport: ChatTransport,\n defaultModel: string | undefined,\n inner: LlmClient,\n): ChatClient {\n return {\n transport,\n defaultModel,\n maximumAttempts: inner.maximumAttempts,\n chat: (req, callOpts) => {\n const resolved = resolveModel(req, defaultModel)\n const request: LlmCallRequest = {\n model: resolved.model!,\n messages: req.messages,\n jsonMode: req.jsonMode,\n jsonSchema: req.jsonSchema,\n temperature: req.temperature,\n maxTokens: req.maxTokens,\n timeoutMs: req.timeoutMs,\n }\n return inner.call(request, {\n signal: callOpts?.signal,\n idempotencyKey: callOpts?.idempotencyKey,\n })\n },\n }\n}\n\nfunction resolveModel(req: ChatRequest, defaultModel: string | undefined): ChatRequest {\n if (req.model) return req\n if (!defaultModel) {\n throw new Error(\n 'ChatClient.chat: no model on request and no defaultModel on the client. ' +\n 'Either pass req.model or bind defaultModel at createChatClient().',\n )\n }\n return { ...req, model: defaultModel }\n}\n","/**\n * Deterministic behavioral metrics over OTLP spans — pure arithmetic, no LLM.\n *\n * These are the model-independent multiplier: the four trace-quality signals a\n * tolerant analyzer (e.g. HALO) re-derives per run inside the model — token\n * growth, output decay, tool monoculture, missing self-verification — computed\n * here once, in TypeScript, with zero model judgment. A finding that falls out\n * of arithmetic is trivially model-agnostic and cannot hallucinate the trend.\n *\n * General, not trace-specific: the detectors key off token trajectories and\n * tool usage present in any agentic OTLP trace, not any one benchmark.\n */\n\nimport { LLM_CONTEXT_TOKENS } from '../trace/attribute-vocabulary'\nimport { executionTrackByLane } from '../trace/execution-tracks'\nimport {\n LLM_INPUT_TOKEN_ATTR_KEYS,\n LLM_OUTPUT_TOKEN_ATTR_KEYS,\n TOOL_NAME_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { spanEpochMillis } from './otlp-span'\nimport type { TraceAnalystSpan } from './types'\n\nexport type SuboptimalCode =\n | 'monotonic-input-growth'\n | 'output-length-decay'\n | 'single-tool-dependency'\n | 'no-self-verification'\n\nexport interface SuboptimalSignal {\n code: SuboptimalCode\n severity: 'high' | 'medium' | 'low'\n /** Human-readable claim, with the backing numbers inlined. */\n detail: string\n /** The exact figures the detector fired on — auditable, no model in the loop. */\n evidence: Record<string, number | string | boolean>\n}\n\nexport interface BehavioralMetrics {\n /** The only trace represented by these metrics; null when spans are empty. */\n traceId: string | null\n llmCallCount: number\n /** Causally serial LLM timelines. Parallel branches are never joined. */\n tokenSequences: BehavioralTokenSequence[]\n /** Token values from the longest serial timeline, retained for convenience. */\n inputTokenTrajectory: number[]\n outputTokenTrajectory: number[]\n toolHistogram: Record<string, number>\n totalToolCalls: number\n distinctTools: number\n /** distinct/total tool calls; 1.0 when there are no tool calls. */\n toolDiversityRatio: number\n hasSelfVerification: boolean\n signals: SuboptimalSignal[]\n}\n\nexport interface BehavioralTokenSequence {\n scopeId: string\n spanIds: string[]\n inputTokenTrajectory: Array<number | null>\n outputTokenTrajectory: Array<number | null>\n}\n\ninterface TokenSample {\n span: TraceAnalystSpan\n input: number | null\n output: number | null\n step: number | null\n}\n\n/** ≥ this input-token growth ratio across a run, with no compression, fires. */\nconst INPUT_GROWTH_FACTOR = 3\n/** Tool-usage signals need at least this many calls to be meaningful. */\nconst MIN_TOOL_CALLS = 3\n/** Tool names that read or check state count as self-verification, not mutation.\n * Covers the inspect verbs plus the read/search tools real harnesses use to\n * verify (Claude Code Read/Grep/Glob, codex read_file/ls/cat, git status/diff,\n * test/lint). A pure shell tool (Bash/exec_command) is intentionally NOT matched\n * — its name can't tell a `pytest` from an `rm`. */\nconst VERIFY_RE =\n /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\\blist\\b|\\bls\\b|\\bcat\\b|\\bfind\\b|diff|status|\\btest|lint|typecheck/i\n\nfunction num(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null\n}\nfunction numAttr(attrs: Record<string, unknown>, keys: readonly string[]): number | null {\n for (const key of keys) {\n const value = num(attrs[key])\n if (value !== null) return value\n }\n return null\n}\nfunction inputTokensOf(s: TraceAnalystSpan): number | null {\n const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS])\n if (exactContext !== null) return exactContext\n // Foreign producers disagree on whether prompt includes cached tokens.\n // Without an exact total, retain the reported prompt instead of guessing.\n return (\n numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes['llm.usage.input_tokens'])\n )\n}\nfunction outputTokensOf(s: TraceAnalystSpan): number | null {\n return (\n numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ??\n num(s.attributes['llm.usage.output_tokens'])\n )\n}\nfunction stepOf(s: TraceAnalystSpan): number | null {\n return num(s.attributes.step)\n}\nfunction toolNameOf(s: TraceAnalystSpan): string | null {\n if (s.tool_name) return s.tool_name\n for (const key of TOOL_NAME_ATTR_KEYS) {\n const t = s.attributes[key]\n if (typeof t === 'string' && t.length > 0) return t\n }\n return null\n}\n\n/**\n * Reduce a span list to behavioral metrics + fired suboptimality signals.\n * Pure + deterministic: same spans → same output, on any machine, no model.\n */\nexport function computeTraceMetrics(spans: readonly TraceAnalystSpan[]): BehavioralMetrics {\n const traceIds = new Set(spans.map((span) => span.trace_id))\n if (traceIds.size > 1) {\n throw new Error(\n `computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`,\n )\n }\n const traceId = traceIds.values().next().value ?? null\n\n const samples: TokenSample[] = spans.map((span) => ({\n span,\n input: inputTokensOf(span),\n output: outputTokensOf(span),\n step: stepOf(span),\n }))\n const llmSamples = samples.filter((sample) => sample.span.kind === 'LLM')\n const tokenSamples =\n llmSamples.length > 0\n ? llmSamples\n : samples.filter((sample) => sample.input !== null || sample.output !== null)\n const tokenSequences = buildTokenSequences(tokenSamples, spans)\n const primarySequence = tokenSequences[0]\n const inputTokenTrajectory =\n primarySequence?.inputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const outputTokenTrajectory =\n primarySequence?.outputTokenTrajectory.filter((value): value is number => value !== null) ?? []\n const toolHistogram: Record<string, number> = {}\n let hasSelfVerification = false\n\n for (const s of spans) {\n const tool = toolNameOf(s)\n if (tool) {\n toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1\n if (VERIFY_RE.test(tool)) hasSelfVerification = true\n }\n }\n\n const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0)\n const distinctTools = Object.keys(toolHistogram).length\n const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls\n\n const signals: SuboptimalSignal[] = []\n const seenTokenSignals = new Set<SuboptimalCode>()\n for (const sequence of tokenSequences) {\n for (const signal of tokenSignals(sequence)) {\n if (seenTokenSignals.has(signal.code)) continue\n seenTokenSignals.add(signal.code)\n signals.push(signal)\n }\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {\n const only = Object.keys(toolHistogram)[0]!\n signals.push({\n code: 'single-tool-dependency',\n severity: 'medium',\n detail: `All ${totalToolCalls} observed tool calls are \\`${only}\\`; no alternate tool call was observed.`,\n evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 },\n })\n }\n\n if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {\n signals.push({\n code: 'no-self-verification',\n severity: 'medium',\n detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,\n evidence: { tool_calls: totalToolCalls, verification_calls: 0 },\n })\n }\n\n return {\n traceId,\n llmCallCount: tokenSamples.length,\n tokenSequences,\n inputTokenTrajectory,\n outputTokenTrajectory,\n toolHistogram,\n totalToolCalls,\n distinctTools,\n toolDiversityRatio,\n hasSelfVerification,\n signals,\n }\n}\n\nfunction buildTokenSequences(\n samples: readonly TokenSample[],\n spans: readonly TraceAnalystSpan[],\n): BehavioralTokenSequence[] {\n const spansById = new Map(spans.map((span) => [span.span_id, span]))\n const executionScopeFor = createTokenExecutionScopeResolver(spansById)\n const scopedSamples = samples.map((sample) => ({\n sample,\n ...executionScopeFor(sample.span),\n }))\n const trackByLane = executionTrackByLane(scopedSamples)\n const byTrack = new Map<string, { scopeId: string; samples: TokenSample[] }>()\n for (const scoped of scopedSamples) {\n const trackId = trackByLane.get(scoped.key)!\n const track = byTrack.get(trackId) ?? { scopeId: scoped.scopeId, samples: [] }\n track.samples.push(scoped.sample)\n byTrack.set(trackId, track)\n }\n\n const sequences: BehavioralTokenSequence[] = []\n for (const { scopeId, samples: tracked } of byTrack.values()) {\n const runs = serialTokenRuns([...tracked].sort(compareTokenSamples))\n runs.forEach((run, index) => {\n sequences.push({\n scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,\n spanIds: run.map((sample) => sample.span.span_id),\n inputTokenTrajectory: run.map((sample) => sample.input),\n outputTokenTrajectory: run.map((sample) => sample.output),\n })\n })\n }\n\n return sequences.sort(\n (a, b) =>\n b.spanIds.length - a.spanIds.length ||\n a.scopeId.localeCompare(b.scopeId) ||\n a.spanIds[0]!.localeCompare(b.spanIds[0]!),\n )\n}\n\ninterface AncestorScope {\n agentId: string | null\n rootId: string | null\n missingParentId: string | null\n laneSpanId: string | null\n}\n\nfunction createTokenExecutionScopeResolver(spansById: ReadonlyMap<string, TraceAnalystSpan>): (\n span: TraceAnalystSpan,\n) => {\n key: string\n scopeKey: string\n scopeId: string\n start: number | null\n end: number | null\n} {\n const cache = new Map<string, AncestorScope>()\n return (span) => {\n const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache)\n const rootId = ancestry.rootId\n const scopeId = ancestry.agentId\n ? `span:${ancestry.agentId}`\n : ancestry.missingParentId\n ? `parent:${ancestry.missingParentId}`\n : rootId\n ? `root:${rootId}`\n : span.agent_name\n ? `agent:${span.agent_name}`\n : `trace:${span.trace_id}`\n const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId\n const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : undefined\n const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId\n const timedSpan = direct ? span : laneSpan\n return {\n key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),\n scopeKey: scopeId,\n scopeId,\n start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,\n end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null,\n }\n }\n}\n\nfunction resolveAncestorScope(\n startId: string | null,\n spansById: ReadonlyMap<string, TraceAnalystSpan>,\n cache: Map<string, AncestorScope>,\n): AncestorScope {\n const empty: AncestorScope = {\n agentId: null,\n rootId: null,\n missingParentId: null,\n laneSpanId: null,\n }\n if (!startId) return empty\n\n const path: string[] = []\n const pathIndex = new Map<string, number>()\n let currentId: string | null = startId\n let resolved = empty\n while (currentId) {\n const cached = cache.get(currentId)\n if (cached) {\n resolved = cached\n break\n }\n const cycleStart = pathIndex.get(currentId)\n if (cycleStart !== undefined) {\n resolved = {\n agentId: null,\n rootId: [...path.slice(cycleStart)].sort()[0]!,\n missingParentId: null,\n laneSpanId: [...path.slice(cycleStart)].sort()[0]!,\n }\n break\n }\n const current = spansById.get(currentId)\n if (!current) {\n resolved = {\n agentId: null,\n rootId: null,\n missingParentId: currentId,\n laneSpanId: currentId,\n }\n break\n }\n if (current.kind === 'AGENT') {\n resolved = {\n agentId: current.span_id,\n rootId: null,\n missingParentId: null,\n laneSpanId: current.span_id,\n }\n break\n }\n pathIndex.set(currentId, path.length)\n path.push(currentId)\n currentId = current.parent_span_id\n }\n\n for (let index = path.length - 1; index >= 0; index -= 1) {\n if (resolved.agentId === null && resolved.rootId === null) {\n resolved = { ...resolved, rootId: path[index]!, laneSpanId: path[index]! }\n } else if (\n resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)\n ) {\n resolved = { ...resolved, laneSpanId: path[index]! }\n }\n cache.set(path[index]!, resolved)\n }\n return resolved\n}\n\nfunction compareTokenSamples(a: TokenSample, b: TokenSample): number {\n const aStart = spanEpochMillis(a.span.start_time)\n const bStart = spanEpochMillis(b.span.start_time)\n if (aStart === null && bStart !== null) return 1\n if (aStart !== null && bStart === null) return -1\n if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart\n if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step\n return a.span.span_id.localeCompare(b.span.span_id)\n}\n\nfunction serialTokenRuns(ordered: readonly TokenSample[]): TokenSample[][] {\n const runs: TokenSample[][] = []\n let serial: TokenSample[] = []\n let overlap: TokenSample[] = []\n let overlapEnd = Number.NEGATIVE_INFINITY\n\n const flushSerial = () => {\n if (serial.length > 0) runs.push(serial)\n serial = []\n }\n const flushOverlap = () => {\n if (overlap.length === 1) {\n serial.push(overlap[0]!)\n } else if (overlap.length > 1) {\n flushSerial()\n for (const sample of overlap) runs.push([sample])\n }\n overlap = []\n overlapEnd = Number.NEGATIVE_INFINITY\n }\n\n for (const sample of ordered) {\n const start = spanEpochMillis(sample.span.start_time)\n const end = spanEpochMillis(sample.span.end_time)\n if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {\n flushOverlap()\n flushSerial()\n runs.push([sample])\n continue\n }\n if (overlap.length > 0 && start >= overlapEnd) flushOverlap()\n overlap.push(sample)\n overlapEnd = Math.max(overlapEnd, end)\n }\n flushOverlap()\n flushSerial()\n return runs\n}\n\nfunction tokenSignals(sequence: BehavioralTokenSequence): SuboptimalSignal[] {\n const signals: SuboptimalSignal[] = []\n const inputs = sequence.inputTokenTrajectory\n const outputs = sequence.outputTokenTrajectory\n if (inputs.length >= 3 && inputs.every((value): value is number => value !== null)) {\n const first = inputs[0]!\n const last = inputs[inputs.length - 1]!\n const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const growthFromZero = first === 0 && last > 0\n const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0\n if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {\n const growthLabel = growthFromZero ? '0→nonzero (unbounded)' : `${growth.toFixed(1)}x`\n signals.push({\n code: 'monotonic-input-growth',\n severity: 'high',\n detail: `LLM input tokens grew ${growthLabel} (${first}→${last}) across ${inputs.length} serial calls without an intervening decrease.`,\n evidence: {\n first,\n last,\n growth_x: growthFromZero ? 'unbounded' : Number(growth.toFixed(2)),\n calls: inputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n\n if (\n inputs.length >= 3 &&\n inputs.length === outputs.length &&\n inputs.every((value): value is number => value !== null) &&\n outputs.every((value): value is number => value !== null)\n ) {\n const first = outputs[0]!\n const last = outputs[outputs.length - 1]!\n const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous)\n const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous)\n const inputGrew = inputs[inputs.length - 1]! > inputs[0]!\n if (inputIsMonotonic && inputGrew && outputIsMonotonic && last < first) {\n signals.push({\n code: 'output-length-decay',\n severity: 'medium',\n detail: `LLM output tokens shrank ${first}→${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,\n evidence: {\n first,\n last,\n calls: outputs.length,\n scope: sequence.scopeId,\n first_span_id: sequence.spanIds[0]!,\n last_span_id: sequence.spanIds[sequence.spanIds.length - 1]!,\n },\n })\n }\n }\n return signals\n}\n\nfunction everyAdjacent(\n values: readonly number[],\n predicate: (previous: number, current: number) => boolean,\n): boolean {\n return values.slice(1).every((current, index) => predicate(values[index]!, current))\n}\n","/**\n * `behavioralAnalyst` — a DETERMINISTIC analyst (cost.kind = 'deterministic',\n * never calls the LLM). It produces the efficiency/behavioral findings a\n * tolerant agentic analyzer (HALO) re-derives per run inside the model —\n * context bloat, output decay, tool monoculture, missing self-verification —\n * directly from arithmetic over spans (`computeTraceMetrics`).\n *\n * Why it matters: these findings are model-agnostic BY CONSTRUCTION (no model\n * in the loop), so they cannot return 0 on a weak model the way the Ax-RLM\n * does — and they are strictly more reliable than HALO, which spends tokens\n * re-deriving the same numbers and can hallucinate the trend. The agentic\n * RLM kinds remain for SEMANTIC findings that genuinely need a model; this\n * analyst owns the behavioral class.\n */\n\nimport {\n type BehavioralMetrics,\n computeTraceMetrics,\n type SuboptimalCode,\n} from '../trace-analyst/behavioral-metrics'\nimport type { TraceAnalysisStore } from '../trace-analyst/store'\nimport { type Analyst, type AnalystFinding, makeFinding } from './types'\n\nconst RECOMMENDED_ACTION: Record<SuboptimalCode, string> = {\n 'monotonic-input-growth':\n 'Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.',\n 'output-length-decay':\n 'Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.',\n 'single-tool-dependency':\n 'Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.',\n 'no-self-verification':\n 'After state-changing actions, require an observable check before the agent proceeds.',\n}\n\nconst ANALYST_ID = 'efficiency-behavioral'\n\nconst AGGREGATE_CLAIM: Record<SuboptimalCode, (observed: number, analyzed: number) => string> = {\n 'monotonic-input-growth': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,\n 'output-length-decay': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,\n 'single-tool-dependency': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,\n 'no-self-verification': (observed, analyzed) =>\n `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`,\n}\n\n/**\n * Map computed signals → structured AnalystFindings. Pure: no LLM, no clock\n * dependence beyond `produced_at` (overridable for deterministic tests).\n */\nexport function deriveEfficiencyFindings(\n metrics: BehavioralMetrics,\n opts: { analystId?: string; producedAt?: string } = {},\n): AnalystFinding[] {\n const analystId = opts.analystId ?? ANALYST_ID\n const traceId = metrics.traceId\n return metrics.signals.map((sig) =>\n makeFinding({\n analyst_id: analystId,\n area: 'efficiency',\n subject: sig.code,\n claim: sig.detail,\n severity: sig.severity,\n // Deterministic arithmetic over spans, not a model judgment → certain.\n confidence: 1,\n evidence_refs: [\n {\n kind: 'metric',\n uri: traceId\n ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}`\n : `metric://efficiency/${sig.code}`,\n excerpt: JSON.stringify(sig.evidence),\n },\n ],\n recommended_action: RECOMMENDED_ACTION[sig.code],\n metadata: {\n deterministic: true,\n evidence: sig.evidence,\n ...(traceId ? { trace_id: traceId } : {}),\n },\n id_basis: sig.code,\n ...(opts.producedAt ? { produced_at: opts.producedAt } : {}),\n }),\n )\n}\n\n/** The deterministic behavioral/efficiency analyst (no LLM, any-model). */\nexport function behavioralAnalyst(): Analyst<TraceAnalysisStore> {\n return {\n id: ANALYST_ID,\n description:\n 'Deterministic behavioral/efficiency findings over OTLP spans — token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.',\n inputKind: 'trace-store',\n cost: { kind: 'deterministic' },\n version: '2.0.0',\n async analyze(store) {\n const overview = await store.getOverview()\n const analyzedTraceIds = [...new Set(overview.sample_trace_ids)].sort()\n const findingsById = new Map<\n string,\n { finding: AnalystFinding; traceIds: string[]; evidence: AnalystFinding['evidence_refs'] }\n >()\n for (const traceId of analyzedTraceIds) {\n const viewed = await store.viewTrace({ trace_id: traceId })\n if (viewed.trace_id !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`,\n )\n }\n if (!viewed.spans) {\n throw new Error(\n `behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`,\n )\n }\n const metrics = computeTraceMetrics(viewed.spans)\n if (metrics.traceId !== null && metrics.traceId !== traceId) {\n throw new Error(\n `behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`,\n )\n }\n for (const finding of deriveEfficiencyFindings(metrics)) {\n const current = findingsById.get(finding.finding_id)\n if (!current) {\n findingsById.set(finding.finding_id, {\n finding,\n traceIds: [traceId],\n evidence: [...finding.evidence_refs],\n })\n continue\n }\n current.traceIds.push(traceId)\n current.evidence.push(...finding.evidence_refs)\n }\n }\n return [...findingsById.values()].map(({ finding, traceIds, evidence }) => ({\n ...finding,\n claim: AGGREGATE_CLAIM[finding.subject as SuboptimalCode](\n traceIds.length,\n analyzedTraceIds.length,\n ),\n rationale: `${traceIds.length}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,\n evidence_refs: evidence,\n metadata: {\n deterministic: true,\n trace_ids: traceIds,\n observed_trace_count: traceIds.length,\n analyzed_trace_count: analyzedTraceIds.length,\n },\n }))\n },\n }\n}\n","/**\n * `buildDefaultAnalystRegistry` — the canonical analyst suite, so consumers\n * stop hand-wiring `new AnalystRegistry()` + per-kind `createTraceAnalystKind`.\n *\n * The deterministic `behavioralAnalyst` is ALWAYS registered (it needs no\n * model and is model-agnostic by construction). The agentic RLM kinds are\n * registered only when an `ai` service is supplied — so a caller with no LLM\n * still gets the full behavioral/efficiency diagnosis, and the substrate's\n * \"any model (including no model)\" guarantee holds at the suite level.\n */\n\nimport type { AxAIService } from '@ax-llm/ax'\nimport { behavioralAnalyst } from './behavioral-analyst'\nimport { createTraceAnalystKind, type TraceAnalystKindSpec } from './kind-factory'\nimport { DEFAULT_TRACE_ANALYST_KINDS } from './kinds'\nimport { AnalystRegistry, type AnalystRegistryOptions } from './registry'\n\nexport interface DefaultAnalystRegistryOptions {\n /** Ax service for the agentic RLM kinds. Omit → only the deterministic analyst. */\n ai?: AxAIService\n /** Model for the agentic kinds (falls back to the ai service default). */\n model?: string\n /** Which agentic kinds to register when `ai` is present. Default = the shipped suite. */\n kinds?: readonly TraceAnalystKindSpec[]\n /** Set false to omit the deterministic behavioral analyst (default: include). */\n includeBehavioral?: boolean\n /** Forwarded to the AnalystRegistry constructor (signal, tags, priorFindings). */\n registry?: AnalystRegistryOptions\n}\n\nexport function buildDefaultAnalystRegistry(\n opts: DefaultAnalystRegistryOptions = {},\n): AnalystRegistry {\n const registry = new AnalystRegistry(opts.registry)\n if (opts.includeBehavioral !== false) {\n registry.register(behavioralAnalyst())\n }\n if (opts.ai) {\n const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS\n for (const spec of kinds) {\n registry.register(createTraceAnalystKind(spec, { ai: opts.ai, model: opts.model }))\n }\n }\n return registry\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+HO,SAAS,iBAAiB,MAAwC;AACvE,UAAQ,KAAK,WAAW;AAAA,IACtB,KAAK;AACH,aAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,IAAI,UAAU;AAAA,UACZ,SAAS,KAAK,WAAW;AAAA,UACzB,QAAQ,KAAK;AAAA,UACb,YAAY,KAAK;AAAA,QACnB,CAAqB;AAAA,MACvB;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,IAAI,UAAU;AAAA,UACZ,SAAS,KAAK,WAAW;AAAA,UACzB,QAAQ,KAAK,UAAU;AAAA,UACvB,YAAY,KAAK;AAAA,QACnB,CAAqB;AAAA,MACvB;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,IAAI,UAAU;AAAA,UACZ,SAAS,KAAK;AAAA,UACd,QAAQ,KAAK;AAAA,UACb,YAAY,KAAK;AAAA,QACnB,CAAqB;AAAA,MACvB;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,WAAW;AAAA,QACX,cAAc,KAAK;AAAA,QACnB,iBAAiB,KAAK;AAAA,QACtB,MAAM,OAAO,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,KAAK,YAAY,GAAG,QAAQ;AAAA,MACzF;AAAA,IACF,KAAK;AACH,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