@tangle-network/agent-eval 0.111.0 → 0.113.0

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 (42) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/analyst/index.d.ts +3 -3
  3. package/dist/analyst/index.js +8 -4
  4. package/dist/analyst/index.js.map +1 -1
  5. package/dist/benchmarks/index.d.ts +2 -2
  6. package/dist/benchmarks/index.js +4 -4
  7. package/dist/campaign/index.d.ts +55 -22
  8. package/dist/campaign/index.js +12 -6
  9. package/dist/{chunk-XRGOKCMO.js → chunk-4FRTXH2M.js} +3 -3
  10. package/dist/{chunk-D2XDWRFX.js → chunk-CX5RBMPW.js} +512 -21
  11. package/dist/{chunk-D2XDWRFX.js.map → chunk-CX5RBMPW.js.map} +1 -1
  12. package/dist/{chunk-7NX6ZSBG.js → chunk-DWLIGZBX.js} +145 -42
  13. package/dist/chunk-DWLIGZBX.js.map +1 -0
  14. package/dist/{chunk-RCXMWGRY.js → chunk-F2NV5PQ6.js} +65 -21
  15. package/dist/chunk-F2NV5PQ6.js.map +1 -0
  16. package/dist/{chunk-2IY4ILP4.js → chunk-HJWNHCD5.js} +57 -2
  17. package/dist/chunk-HJWNHCD5.js.map +1 -0
  18. package/dist/{chunk-OW47B5WA.js → chunk-LVTGFSHF.js} +2 -2
  19. package/dist/contract/index.d.ts +6 -6
  20. package/dist/contract/index.js +6 -5
  21. package/dist/contract/index.js.map +1 -1
  22. package/dist/{gepa-T8T215nw.d.ts → gepa-DolL_Fko.d.ts} +2 -6
  23. package/dist/hosted/index.d.ts +1 -1
  24. package/dist/{index-Dc3VLGhp.d.ts → index-CWr5SIG-.d.ts} +1 -1
  25. package/dist/index.d.ts +9 -9
  26. package/dist/index.js +6 -6
  27. package/dist/multishot/index.d.ts +1 -1
  28. package/dist/openapi.json +1 -1
  29. package/dist/{policy-edit-D2bBDZDf.d.ts → policy-edit-az2qRmvN.d.ts} +1 -1
  30. package/dist/{pre-registration-BepVVa6P.d.ts → pre-registration-CTQbZbpX.d.ts} +1 -1
  31. package/dist/{provenance-KhY8ESVM.d.ts → provenance-DChJ2oZ4.d.ts} +4 -10
  32. package/dist/rl.d.ts +1 -1
  33. package/dist/{semantic-concept-judge-D7z6JCLZ.d.ts → semantic-concept-judge-CpzbtwD0.d.ts} +29 -1
  34. package/dist/{types-v--ctu-b.d.ts → types-CgSlO6wT.d.ts} +26 -11
  35. package/docs/design/loop-taxonomy.md +7 -1
  36. package/docs/improvement-glossary.md +1 -1
  37. package/package.json +2 -2
  38. package/dist/chunk-2IY4ILP4.js.map +0 -1
  39. package/dist/chunk-7NX6ZSBG.js.map +0 -1
  40. package/dist/chunk-RCXMWGRY.js.map +0 -1
  41. /package/dist/{chunk-XRGOKCMO.js.map → chunk-4FRTXH2M.js.map} +0 -0
  42. /package/dist/{chunk-OW47B5WA.js.map → chunk-LVTGFSHF.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  export { A as ActionExecutionPolicy, a as ActionPolicyDecision, C as ControlRunToRunRecordOptions, L as LlmJsonCall, b as LlmReviewerConfig, P as ProposeFn, c as ProposeInput, d as ProposeOutput, e as ProposeReviewConfig, f as ProposeReviewControlAction, g as ProposeReviewControlConfig, h as ProposeReviewControlResult, i as ProposeReviewControlState, j as ProposeReviewReport, k as ProposeReviewShot, R as Review, l as ReviewFn, m as ReviewInput, n as ReviewMemoryEntry, o as ReviewMemoryStore, p as RunEvidenceMetadata, V as Verification, q as VerifyFn, r as controlFailureClassFromVerification, s as controlRunToRunRecord, t as createLlmReviewer, u as evaluateActionPolicy, v as inMemoryReviewStore, w as jsonlReviewStore, x as runProposeReview, y as runProposeReviewAsControlLoop, z as scoreFromEvals } from './control-U8LBKUES.js';
2
2
  import { R as RunRecord, b as RunSplitTag } from './run-record-DksGsfgv.js';
3
3
  export { f as AGENT_PROFILE_KINDS, g as AgentInterfaceProfileLike, A as AgentProfileCell, e as AgentProfileCellInput, h as AgentProfileCellSchemaVersion, i as AgentProfileCellValidationError, j as AgentProfileDimensionValue, k as AgentProfileHarness, a as AgentProfileJson, l as AgentProfileKind, m as AgentProfileSource, n as AgentProfileSourceInput, J as JudgeScoresRecord, d as RunJudgeMetadata, o as RunOutcome, p as RunRecordValidationError, c as RunTokenUsage, q as agentProfileCellHashMaterial, r as agentProfileCellKey, s as assertRunAgentProfileCell, t as buildAgentInterfaceProfileCell, u as buildAgentProfileCell, v as groupRunsByAgentProfileCell, w as isRunRecord, x as modelHasSnapshot, y as parseRunRecordSafe, z as requireAgentProfileCell, B as roundTripRunRecord, C as toAgentProfileJson, D as validateAgentProfileCell, E as validateRunRecord, F as verifyAgentProfileCell } from './run-record-DksGsfgv.js';
4
- import { B as BehavioralMetrics, y as RunScore, a as RunTrace, z as RunScoreWeights } from './semantic-concept-judge-D7z6JCLZ.js';
5
- export { A as ConceptComplexity, E as ConceptFinding, G as ConceptSpec, H as ConceptWeightStrategy, C as CreateAnalystAiConfig, J as DEFAULT_COMPLEXITY_WEIGHTS, L as DEFAULT_RUN_SCORE_WEIGHTS, D as DEFAULT_TRACE_ANALYST_KINDS, c as DiffPolicy, F as FAILURE_MODE_KIND_SPEC, f as FindingSubject, g as FindingSubjectKind, i as FindingsDiff, j as FindingsStore, I as IMPROVEMENT_KIND_SPEC, k as KNOWLEDGE_GAP_KIND_SPEC, l as KNOWLEDGE_POISONING_KIND_SPEC, P as PersistedFinding, R as RunCritic, M as RunCriticOptions, N as SEMANTIC_CONCEPT_JUDGE_VERSION, m as SKILL_USAGE_ANALYST, b as SemanticConceptJudgeInput, S as SemanticConceptJudgeOptions, O as SemanticConceptJudgeResult, n as SkillUsageAnalyst, Q as SuboptimalCode, T as SuboptimalSignal, U as aggregateRunScore, V as clamp01, W as computeTraceMetrics, s as createAnalystAi, X as createSemanticConceptJudge, t as defaultIsMaterial, u as diffFindings, Y as runSemanticConceptJudge } from './semantic-concept-judge-D7z6JCLZ.js';
4
+ import { B as BehavioralMetrics, A as RunScore, a as RunTrace, E as RunScoreWeights } from './semantic-concept-judge-CpzbtwD0.js';
5
+ export { G as ConceptComplexity, H as ConceptFinding, J as ConceptSpec, L as ConceptWeightStrategy, C as CreateAnalystAiConfig, M as DEFAULT_COMPLEXITY_WEIGHTS, N as DEFAULT_RUN_SCORE_WEIGHTS, D as DEFAULT_TRACE_ANALYST_KINDS, c as DiffPolicy, F as FAILURE_MODE_KIND_SPEC, g as FindingSubject, h as FindingSubjectKind, j as FindingsDiff, k as FindingsStore, I as IMPROVEMENT_KIND_SPEC, l as KNOWLEDGE_GAP_KIND_SPEC, m as KNOWLEDGE_POISONING_KIND_SPEC, P as PersistedFinding, R as RunCritic, O as RunCriticOptions, Q as SEMANTIC_CONCEPT_JUDGE_VERSION, n as SKILL_USAGE_ANALYST, b as SemanticConceptJudgeInput, S as SemanticConceptJudgeOptions, T as SemanticConceptJudgeResult, o as SkillUsageAnalyst, U as SuboptimalCode, V as SuboptimalSignal, W as aggregateRunScore, X as clamp01, Y as computeTraceMetrics, t as createAnalystAi, Z as createSemanticConceptJudge, u as defaultIsMaterial, v as diffFindings, _ as runSemanticConceptJudge } from './semantic-concept-judge-CpzbtwD0.js';
6
6
  import { m as ChatRequest, q as CreateChatClientOpts } from './kind-factory-20hcaYpf.js';
7
7
  export { a as Analyst, b as AnalystContext, i as AnalystCost, A as AnalystFinding, j as AnalystInputKind, k as AnalystRequirements, f as AnalystRunEvent, e as AnalystRunInputs, d as AnalystRunResult, c as AnalystRunSummary, g as AnalystSeverity, l as ChatCallOpts, C as ChatClient, n as ChatResponse, o as ChatTransport, p as CliBridgeTransportOpts, r as CreateTraceAnalystKindOpts, D as DirectProviderTransportOpts, E as EvidenceRef, M as MockTransportOpts, s as RawAnalystFinding, u as RouterTransportOpts, S as SandboxSdkTransportOpts, v as TraceAnalystGolden, T as TraceAnalystKindSpec, w as computeFindingId, x as createChatClient, y as createTraceAnalystKind, z as makeFinding, F as renderPriorFindings } from './kind-factory-20hcaYpf.js';
8
8
  export { a as AnalystHooks, A as AnalystRegistry, b as AnalystRegistryOptions, B as BudgetPolicy, D as DefaultAnalystRegistryOptions, R as RegistryRunOpts, c as buildDefaultAnalystRegistry } from './default-registry-Bcf1uKVI.js';
9
- export { F as FindingToPolicyEditOptions, P as POLICY_EDIT_AXES, a as POLICY_EDIT_TARGET_SURFACES, b as PolicyEdit, c as PolicyEditAdmission, d as PolicyEditAdmissionOptions, e as PolicyEditAxis, f as PolicyEditChange, g as PolicyEditExpectedGain, h as PolicyEditGainDirection, i as PolicyEditGainUnit, j as PolicyEditInit, k as PolicyEditRisk, l as PolicyEditSchemaVersion, m as PolicyEditSource, n as PolicyEditTarget, o as PolicyEditTargetSurface, p as PolicyEditValidationError, q as admitPolicyEdit, r as applyPolicyEditToSurface, s as computePolicyEditId, t as isPolicyEdit, u as makePolicyEdit, v as policyEditFromFinding, w as policyEditsFromFindings, x as scorePolicyEditReadiness, y as validatePolicyEdit } from './policy-edit-D2bBDZDf.js';
9
+ export { F as FindingToPolicyEditOptions, P as POLICY_EDIT_AXES, a as POLICY_EDIT_TARGET_SURFACES, b as PolicyEdit, c as PolicyEditAdmission, d as PolicyEditAdmissionOptions, e as PolicyEditAxis, f as PolicyEditChange, g as PolicyEditExpectedGain, h as PolicyEditGainDirection, i as PolicyEditGainUnit, j as PolicyEditInit, k as PolicyEditRisk, l as PolicyEditSchemaVersion, m as PolicyEditSource, n as PolicyEditTarget, o as PolicyEditTargetSurface, p as PolicyEditValidationError, q as admitPolicyEdit, r as applyPolicyEditToSurface, s as computePolicyEditId, t as isPolicyEdit, u as makePolicyEdit, v as policyEditFromFinding, w as policyEditsFromFindings, x as scorePolicyEditReadiness, y as validatePolicyEdit } from './policy-edit-az2qRmvN.js';
10
10
  import { TCloud } from '@tangle-network/tcloud';
11
11
  import { B as BenchmarkRunnerConfig, S as Scenario, c as BenchmarkReport, P as ProductClientConfig, C as CheckResult, T as TestResult, d as PersonaConfig, D as DriverResult, e as DriverState, b as JudgeFn, f as CollectedArtifacts, g as ScenarioResult, h as TurnMetrics, i as ScenarioFile, j as CompletionCriterion } from './types-C7DGg5ex.js';
12
12
  export { A as ArtifactCheck, k as ArtifactResult, E as EvalResult, F as FeedbackPattern, l as JudgeConfig, a as JudgeInput, m as JudgeRubric, J as JudgeScore, n as PersonaRigor, R as RouteMap, o as RubricDimension, p as Turn, q as TurnResult } from './types-C7DGg5ex.js';
@@ -16,8 +16,8 @@ import { F as FailureClass, T as ToolSpan, h as BudgetSpec, B as BudgetLedgerEnt
16
16
  export { A as Artifact, E as EventKind, i as FAILURE_CLASSES, G as GenericSpan, J as JudgeSpan, M as Message, c as RetrievalSpan, g as RunLayer, f as RunStatus, d as SandboxSpan, j as SpanBase, b as SpanKind, k as SpanStatus, l as TRACE_SCHEMA_VERSION, e as TraceEvent, m as isJudgeSpan, n as isLlmSpan, o as isRetrievalSpan, p as isSandboxSpan, q as isToolSpan } from './schema-SGWcK9wa.js';
17
17
  import { A as AgentEvalError, J as JudgeError, a as ConfigError } from './errors-oeQrLqXC.js';
18
18
  export { b as AgentEvalErrorCode, C as CaptureIntegrityError, N as NotFoundError, R as ReplayError, V as ValidationError, c as VerificationError } from './errors-oeQrLqXC.js';
19
- import { b as CorrectnessChecker } from './pre-registration-BepVVa6P.js';
20
- export { A as ArtifactCheckArtifact, d as ArtifactEventLike, e as ArtifactValidator, f as BackendIntegrityError, B as BackendIntegrityReport, C as CompletionRequirement, a as CompletionVerdict, H as HypothesisManifest, g as HypothesisResult, h as LlmCorrectnessCheckerOpts, L as LlmJudgeDimension, c as LlmJudgeOptions, i as ProducedProposal, P as ProducedState, j as ProposalEventLike, k as RequirementCheck, R as RuntimeEventLike, m as SatisfiedBy, S as SignedManifest, n as SignedManifestAlgo, T as TaskGold, o as ToolCallEventLike, V as ValidationContext, p as ValidationIssue, q as ValidationResult, r as assertRealBackend, s as byteLengthRange, t as canonicalize, u as completionVerdict, v as composeValidators, w as containsAll, x as createLlmCorrectnessChecker, y as createTokenRecallChecker, z as evaluateHypothesis, D as extractProducedState, E as hashJson, F as jsonHasKeys, l as llmJudge, G as parseCorrectnessResponse, I as regexMatch, J as signManifest, K as summarizeBackendIntegrity, M as verifyCompletion, N as verifyManifest } from './pre-registration-BepVVa6P.js';
19
+ import { b as CorrectnessChecker } from './pre-registration-CTQbZbpX.js';
20
+ export { A as ArtifactCheckArtifact, d as ArtifactEventLike, e as ArtifactValidator, f as BackendIntegrityError, B as BackendIntegrityReport, C as CompletionRequirement, a as CompletionVerdict, H as HypothesisManifest, g as HypothesisResult, h as LlmCorrectnessCheckerOpts, L as LlmJudgeDimension, c as LlmJudgeOptions, i as ProducedProposal, P as ProducedState, j as ProposalEventLike, k as RequirementCheck, R as RuntimeEventLike, m as SatisfiedBy, S as SignedManifest, n as SignedManifestAlgo, T as TaskGold, o as ToolCallEventLike, V as ValidationContext, p as ValidationIssue, q as ValidationResult, r as assertRealBackend, s as byteLengthRange, t as canonicalize, u as completionVerdict, v as composeValidators, w as containsAll, x as createLlmCorrectnessChecker, y as createTokenRecallChecker, z as evaluateHypothesis, D as extractProducedState, E as hashJson, F as jsonHasKeys, l as llmJudge, G as parseCorrectnessResponse, I as regexMatch, J as signManifest, K as summarizeBackendIntegrity, M as verifyCompletion, N as verifyManifest } from './pre-registration-CTQbZbpX.js';
21
21
  import { T as TraceEmitter } from './emitter-BRchAAAx.js';
22
22
  export { R as RunCompleteHook, a as RunCompleteHookContext, S as SpanHandle, b as TraceEmitterOptions, l as llmSpanFromProvider } from './emitter-BRchAAAx.js';
23
23
  import { h as ReleaseConfidenceThresholds, f as ReleaseConfidenceScorecard } from './release-report-oBfOz8ku.js';
@@ -30,10 +30,10 @@ import { a as AnalyzeTracesInput, A as AnalyzeTracesOptions, b as AnalyzeTracesR
30
30
  export { c as AnalyzeTracesTurnSnapshot, d as analyzeTraces } from './analyst-C8HHvfJp.js';
31
31
  import { a as TraceAnalystSpan } from './store-C1YxJDEK.js';
32
32
  export { D as DEFAULT_TRACE_ANALYST_BUDGETS, b as DatasetOverview, E as ErrorCluster, Q as QueryTracesPage, S as SearchSpanResult, c as SearchTraceResult, d as SpanMatchRecord, e as TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, T as TraceAnalysisStore, f as TraceAnalystByteBudgets, g as TraceAnalystFilters, h as TraceAnalystSpanKind, i as TraceAnalystSpanStatus, j as TraceAnalystTraceSummary, V as ViewSpansResult, k as ViewTraceOversized, l as ViewTraceResult } from './store-C1YxJDEK.js';
33
- import { b as JudgeConfig, J as JudgeScore, S as Scenario$1, g as Gate } from './types-v--ctu-b.js';
33
+ import { b as JudgeConfig, J as JudgeScore, S as Scenario$1, g as Gate } from './types-CgSlO6wT.js';
34
34
  import { A as AnalyzeRunsOptions } from './analyze-runs-Dmz6LA9e.js';
35
- import { q as Objective, t as ParetoResult, h as GepaProposerConstraints, a as RunImprovementLoopResult } from './gepa-T8T215nw.js';
36
- export { u as DEFAULT_RED_TEAM_CORPUS, D as Direction, e as RedTeamCase, v as RedTeamCategory, w as RedTeamFinding, x as RedTeamPayload, y as RedTeamReport, z as crowdingDistance, A as dominates, B as paretoFrontier, E as paretoFrontierWithCrowding, F as redTeamDataset, H as redTeamReport, I as scalarScore, J as scoreRedTeamOutput, K as toolNamesForRun } from './gepa-T8T215nw.js';
35
+ import { q as Objective, s as ParetoResult, h as GepaProposerConstraints, a as RunImprovementLoopResult } from './gepa-DolL_Fko.js';
36
+ export { t as DEFAULT_RED_TEAM_CORPUS, D as Direction, e as RedTeamCase, u as RedTeamCategory, v as RedTeamFinding, w as RedTeamPayload, x as RedTeamReport, y as crowdingDistance, z as dominates, A as paretoFrontier, B as paretoFrontierWithCrowding, E as redTeamDataset, F as redTeamReport, H as scalarScore, I as scoreRedTeamOutput, J as toolNamesForRun } from './gepa-DolL_Fko.js';
37
37
  import { S as SandboxDriver, H as HarnessConfig, a as SandboxHarnessResult } from './test-graded-scenario-mzYBKspu.js';
38
38
  export { D as DockerSandboxDriver, c as SandboxHarness, d as SandboxResult, e as SubprocessSandboxDriver, f as SubprocessSandboxDriverOptions, g as TestGradedRunOptions, b as TestGradedRunResult, T as TestGradedScenario, h as TestOutputParser, i as composeParsers, j as jestTestParser, p as pytestTestParser, r as runTestGradedScenario, v as vitestTestParser } from './test-graded-scenario-mzYBKspu.js';
39
39
  export { b as RunIntegrityError, R as RunIntegrityExpectations, c as RunIntegrityIssue, d as RunIntegrityIssueCode, a as RunIntegrityReport, e as assertRunCaptured, t as throwIfRunIncomplete } from './integrity-qemeBAyx.js';
@@ -58,7 +58,7 @@ import { L as Layer, S as Severity, b as LayerResult, c as VerifyContext } from
58
58
  export { F as Finding, d as LayerStatus, M as MultiLayerVerifier, a as VerificationReport, V as VerifyOptions, g as gradeSemanticStatus } from './multi-layer-verifier-BsqKuLyN.js';
59
59
  import { L as LlmClientOptions } from './llm-client-DyqEH4jH.js';
60
60
  export { d as LlmCallError, b as LlmCallRequest, c as LlmCallResult, e as LlmClient, f as LlmMessage, g as LlmRouteAssertionError, a as LlmRouteRequirements, h as LlmUsage, i as assertLlmRoute, j as backoffMs, k as callLlm, l as callLlmJson, m as isTransientLlmError, p as probeLlm, s as stripFencedJson } from './llm-client-DyqEH4jH.js';
61
- export { B as BENCHMARK_SPLIT_SEED, a as BenchmarkAdapter, b as BenchmarkDatasetItem, c as BenchmarkEvaluation, d as BenchmarkFamily, e as BenchmarkResponder, f as BenchmarkScenario, g as BenchmarkSource, h as BenchmarkTaskKind, i as benchmarkDeterministicSplit, j as benchmarks } from './index-Dc3VLGhp.js';
61
+ export { B as BENCHMARK_SPLIT_SEED, a as BenchmarkAdapter, b as BenchmarkDatasetItem, c as BenchmarkEvaluation, d as BenchmarkFamily, e as BenchmarkResponder, f as BenchmarkScenario, g as BenchmarkSource, h as BenchmarkTaskKind, i as benchmarkDeterministicSplit, j as benchmarks } from './index-CWr5SIG-.js';
62
62
  export { C as CallbackResearcher, d as CallbackResearcherOptions, e as CampaignFactoryParams, f as CampaignIntegrityPolicy, g as CampaignRunContext, h as CampaignRunOutcome, i as CampaignRunner, j as CampaignScenario, k as CampaignVariant, c as EvalCampaignOptions, b as EvalCampaignResult, E as ExperimentPlan, a as ExperimentResult, l as FailedRun, F as FailureMode, N as NoopResearcher, R as Researcher, S as SteeringChange, r as runEvalCampaign } from './researcher-CaH0CwFC.js';
63
63
  export { G as GainDistributionBin, a as GainDistributionFigureSpec, b as GainDistributionOptions, m as GateDecision, n as GateEvidence, H as HeldOutGate, o as HeldOutGateConfig, q as HeldOutGateRejectionCode, P as ParetoFigureSpec, c as ParetoPoint, R as RESEARCH_REPORT_HARD_PAIR_FLOOR, d as ResearchReport, e as ResearchReportCandidate, f as ResearchReportDecision, g as ResearchReportMethodology, h as ResearchReportOptions, i as ResearchReportRecommendation, S as SummaryTable, j as SummaryTableOptions, k as SummaryTableRow, l as gainHistogram, p as paretoChart, r as researchReport, s as summaryTable } from './summary-report-Bz-0-t8v.js';
64
64
  export { I as InterimReleaseConfidence, a as InterimReleaseConfidenceInput, P as PairedEvalueOptions, b as PairedEvalueSequence, c as PairedEvalueStep, S as SequentialDecision, e as evaluateInterimReleaseConfidence, p as pairedEvalueSequence } from './sequential-5iSVfzl2.js';
package/dist/index.js CHANGED
@@ -59,7 +59,7 @@ import {
59
59
  llmJudge,
60
60
  parseCorrectnessResponse,
61
61
  verifyCompletion
62
- } from "./chunk-D2XDWRFX.js";
62
+ } from "./chunk-CX5RBMPW.js";
63
63
  import {
64
64
  DEFAULT_MUTATION_PRIMITIVES,
65
65
  DEFAULT_RED_TEAM_CORPUS,
@@ -83,7 +83,7 @@ import {
83
83
  scoreRedTeamOutput,
84
84
  surfaceContentHash,
85
85
  toolNamesForRun
86
- } from "./chunk-RCXMWGRY.js";
86
+ } from "./chunk-F2NV5PQ6.js";
87
87
  import {
88
88
  MODEL_PRICING,
89
89
  MetricsCollector,
@@ -118,11 +118,11 @@ import {
118
118
  defaultIsMaterial,
119
119
  diffFindings,
120
120
  runSemanticConceptJudge
121
- } from "./chunk-XRGOKCMO.js";
121
+ } from "./chunk-4FRTXH2M.js";
122
122
  import {
123
123
  buildDefaultAnalystRegistry,
124
124
  computeTraceMetrics
125
- } from "./chunk-OW47B5WA.js";
125
+ } from "./chunk-LVTGFSHF.js";
126
126
  import {
127
127
  DEFAULT_RUN_SCORE_WEIGHTS,
128
128
  POLICY_EDIT_AXES,
@@ -139,7 +139,7 @@ import {
139
139
  policyEditsFromFindings,
140
140
  scorePolicyEditReadiness,
141
141
  validatePolicyEdit
142
- } from "./chunk-2IY4ILP4.js";
142
+ } from "./chunk-HJWNHCD5.js";
143
143
  import {
144
144
  AnalystRegistry,
145
145
  DEFAULT_TRACE_ANALYST_KINDS,
@@ -151,7 +151,7 @@ import {
151
151
  createTraceAnalystKind,
152
152
  makeFinding,
153
153
  renderPriorFindings
154
- } from "./chunk-7NX6ZSBG.js";
154
+ } from "./chunk-DWLIGZBX.js";
155
155
  import {
156
156
  allCriticalPassed,
157
157
  controlFailureClassFromVerification,
@@ -1,4 +1,4 @@
1
- import { J as JudgeScore } from '../types-v--ctu-b.js';
1
+ import { J as JudgeScore } from '../types-CgSlO6wT.js';
2
2
  import { AgentProfile } from '@tangle-network/agent-interface';
3
3
  import { M as MatrixResult } from '../types-BUxNaJ8c.js';
4
4
  import '../run-record-DksGsfgv.js';
package/dist/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "@tangle-network/agent-eval — wire protocol",
5
- "version": "0.111.0",
5
+ "version": "0.113.0",
6
6
  "description": "HTTP and stdio RPC interface to agent-eval. The TypeScript runtime is the source of truth; this spec is the contract that cross-language clients (Python, Rust, Go) generate from.\n\nWire-protocol version: 1.0.0. Bumps on breaking changes to request/response schemas.",
7
7
  "contact": {
8
8
  "name": "Tangle Network",
@@ -5,7 +5,7 @@ import { A as AnalystFinding, E as EvidenceRef } from './kind-factory-20hcaYpf.j
5
5
  type PolicyEditSchemaVersion = 'policy-edit/v1';
6
6
  declare const POLICY_EDIT_AXES: readonly ["carrier", "representation", "budget", "sampling", "output_contract", "tool_contract", "routing", "memory", "agent_profile", "deployment_target"];
7
7
  type PolicyEditAxis = (typeof POLICY_EDIT_AXES)[number];
8
- declare const POLICY_EDIT_TARGET_SURFACES: readonly ["prompt", "tool-contract", "runtime-config", "memory", "agent-profile", "deployment"];
8
+ declare const POLICY_EDIT_TARGET_SURFACES: readonly ["prompt", "tool-contract", "runtime-config", "memory", "agent-profile", "code", "deployment"];
9
9
  type PolicyEditTargetSurface = (typeof POLICY_EDIT_TARGET_SURFACES)[number];
10
10
  type PolicyEditRisk = 'low' | 'medium' | 'high' | 'unknown';
11
11
  type PolicyEditGainDirection = 'increase' | 'decrease';
@@ -1,7 +1,7 @@
1
1
  import { A as AgentEvalError } from './errors-oeQrLqXC.js';
2
2
  import { R as RunRecord } from './run-record-DksGsfgv.js';
3
3
  import { C as ChatClient } from './kind-factory-20hcaYpf.js';
4
- import { a as JudgeDimension, S as Scenario, b as JudgeConfig } from './types-v--ctu-b.js';
4
+ import { a as JudgeDimension, S as Scenario, b as JudgeConfig } from './types-CgSlO6wT.js';
5
5
  import { TCloud } from '@tangle-network/tcloud';
6
6
  import { R as RawProviderSink } from './raw-provider-sink-C46HDghv.js';
7
7
  import { D as DefaultVerdict } from './verdict-C9MlYujm.js';
@@ -1,5 +1,5 @@
1
- import { S as Scenario, g as Gate, G as GateResult, n as GateContext, C as CampaignResult, p as Mutator, f as SurfaceProposer, M as MutableSurface, h as GateDecision } from './types-v--ctu-b.js';
2
- import { e as RedTeamCase, D as Direction, b as RunCampaignOptions } from './gepa-T8T215nw.js';
1
+ import { S as Scenario, g as Gate, G as GateResult, n as GateContext, C as CampaignResult, p as Mutator, f as SurfaceProposer, M as MutableSurface, h as GateDecision } from './types-CgSlO6wT.js';
2
+ import { e as RedTeamCase, D as Direction, b as RunCampaignOptions } from './gepa-DolL_Fko.js';
3
3
  import { R as RunRecord } from './run-record-DksGsfgv.js';
4
4
  import { a as PairedBootstrapResult } from './statistics-CDfpwIdX.js';
5
5
  import { HostedClient, TraceSpanEvent } from './hosted/index.js';
@@ -375,12 +375,6 @@ declare function evolutionaryProposer<TFindings = unknown>(opts: EvolutionaryPro
375
375
  * could drift from what the gate actually saw.
376
376
  */
377
377
 
378
- /** Stable sha256 (full hex) of a surface's effective text. Code surfaces hash
379
- * their worktree+base identity since the content lives in git. Distinct from
380
- * `surfaceHash` (16-char content fingerprint used as a loop identity key);
381
- * this is the byte-identical-verifiable content hash the provenance record +
382
- * `RunRecord.promptHash` carry. */
383
- declare function surfaceContentHash(surface: MutableSurface): string;
384
378
  interface LoopProvenanceCandidate {
385
379
  /** Generation index this candidate was proposed in. */
386
380
  generation: number;
@@ -415,7 +409,7 @@ interface LoopProvenanceBackend {
415
409
  * the bare hosted event) + backend provenance.
416
410
  */
417
411
  interface LoopProvenanceRecord {
418
- schema: 'tangle.loop-provenance.v1';
412
+ schema: 'tangle.loop-provenance.v2';
419
413
  runId: string;
420
414
  runDir: string;
421
415
  timestamp: string;
@@ -532,4 +526,4 @@ interface EmitLoopProvenanceArgs<TArtifact, TScenario extends Scenario> extends
532
526
  */
533
527
  declare function emitLoopProvenance<TArtifact, TScenario extends Scenario>(args: EmitLoopProvenanceArgs<TArtifact, TScenario>): Promise<EmitLoopProvenanceResult>;
534
528
 
535
- export { type AxisEvidence as A, type BuildEvidenceVectorOptions as B, type DefaultProductionGateOptions as D, type EvidenceVector as E, type HeldOutGateOptions as H, type LoopProvenanceRecord as L, type ObjectiveSource as O, type PowerPreflight as P, type RunEvalOptions as R, type AxisVerdict as a, type EvolutionaryProposerOptions as b, type ParetoSignificanceGateOptions as c, type PromotionObjective as d, type PromotionPolicy as e, buildEvidenceVector as f, composeGate as g, defaultProductionGate as h, evolutionaryProposer as i, heldOutGate as j, paretoSignificanceGate as k, type BuildLoopProvenanceArgs as l, type EmitLoopProvenanceArgs as m, type EmitLoopProvenanceResult as n, type LoopProvenanceBackend as o, paretoPolicy as p, type LoopProvenanceCandidate as q, runEval as r, type PowerPreflightOptions as s, buildLoopProvenanceRecord as t, emitLoopProvenance as u, loopProvenanceSpans as v, powerPreflight as w, provenanceRecordPath as x, provenanceSpansPath as y, surfaceContentHash as z };
529
+ export { type AxisEvidence as A, type BuildEvidenceVectorOptions as B, type DefaultProductionGateOptions as D, type EvidenceVector as E, type HeldOutGateOptions as H, type LoopProvenanceRecord as L, type ObjectiveSource as O, type PowerPreflight as P, type RunEvalOptions as R, type AxisVerdict as a, type EvolutionaryProposerOptions as b, type ParetoSignificanceGateOptions as c, type PromotionObjective as d, type PromotionPolicy as e, buildEvidenceVector as f, composeGate as g, defaultProductionGate as h, evolutionaryProposer as i, heldOutGate as j, paretoSignificanceGate as k, type BuildLoopProvenanceArgs as l, type EmitLoopProvenanceArgs as m, type EmitLoopProvenanceResult as n, type LoopProvenanceBackend as o, paretoPolicy as p, type LoopProvenanceCandidate as q, runEval as r, type PowerPreflightOptions as s, buildLoopProvenanceRecord as t, emitLoopProvenance as u, loopProvenanceSpans as v, powerPreflight as w, provenanceRecordPath as x, provenanceSpansPath as y };
package/dist/rl.d.ts CHANGED
@@ -10,7 +10,7 @@ import { R as Researcher, F as FailureMode, S as SteeringChange, E as Experiment
10
10
  export { r as runEvalCampaign } from './researcher-CaH0CwFC.js';
11
11
  import { a as VerificationReport } from './multi-layer-verifier-BsqKuLyN.js';
12
12
  import { I as InterimReleaseConfidence } from './sequential-5iSVfzl2.js';
13
- import { C as CampaignResult } from './types-v--ctu-b.js';
13
+ import { C as CampaignResult } from './types-CgSlO6wT.js';
14
14
  import '@tangle-network/agent-interface';
15
15
  import './errors-oeQrLqXC.js';
16
16
  import './llm-client-DyqEH4jH.js';
@@ -91,6 +91,9 @@ type FindingSubject = {
91
91
  } | {
92
92
  kind: 'system-prompt';
93
93
  section: string;
94
+ } | {
95
+ kind: 'skill';
96
+ name: string;
94
97
  } | {
95
98
  kind: 'tool-doc';
96
99
  tool: string;
@@ -98,6 +101,28 @@ type FindingSubject = {
98
101
  } | {
99
102
  kind: 'new-tool';
100
103
  name: string;
104
+ } | {
105
+ kind: 'mcp';
106
+ server: string;
107
+ tool?: string;
108
+ } | {
109
+ kind: 'hook';
110
+ name: string;
111
+ } | {
112
+ kind: 'subagent';
113
+ name: string;
114
+ } | {
115
+ kind: 'workflow';
116
+ name: string;
117
+ } | {
118
+ kind: 'rollout-policy';
119
+ field: string;
120
+ } | {
121
+ kind: 'agent-profile';
122
+ field: string;
123
+ } | {
124
+ kind: 'code';
125
+ path: string;
101
126
  } | {
102
127
  kind: 'rag';
103
128
  corpus: string;
@@ -156,6 +181,7 @@ declare function renderFindingSubject(s: FindingSubject): string;
156
181
  * this constant + the matching `expects` set, and the unit tests below
157
182
  * lock the table to the parser.
158
183
  */
184
+ declare const FINDING_SUBJECT_SYNTAX: Readonly<Record<FindingSubjectKind, string>>;
159
185
  declare const FINDING_SUBJECT_GRAMMAR_PROMPT: string;
160
186
  /**
161
187
  * The variants each kind is allowed to emit. Used at the kind factory
@@ -166,6 +192,8 @@ declare const FINDING_SUBJECT_GRAMMAR_PROMPT: string;
166
192
  * a non-locus subject.
167
193
  */
168
194
  declare const KIND_EXPECTED_SUBJECTS: Record<string, ReadonlyArray<FindingSubjectKind>>;
195
+ /** Render only the subject forms one analyst kind is permitted to emit. */
196
+ declare function findingSubjectGrammarPromptFor(kindId: string): string;
169
197
  /**
170
198
  * Zod schema that validates a raw subject string and returns the parsed
171
199
  * `FindingSubject`. Embedded in `RawAnalystFindingSchema` via
@@ -674,4 +702,4 @@ declare function runSemanticConceptJudge(input: SemanticConceptJudgeInput, optio
674
702
  */
675
703
  declare function createSemanticConceptJudge(options?: SemanticConceptJudgeOptions): (input: SemanticConceptJudgeInput) => Promise<SemanticConceptJudgeResult>;
676
704
 
677
- export { type ConceptComplexity as A, type BehavioralMetrics as B, type CreateAnalystAiConfig as C, DEFAULT_TRACE_ANALYST_KINDS as D, type ConceptFinding as E, FAILURE_MODE_KIND_SPEC as F, type ConceptSpec as G, type ConceptWeightStrategy as H, IMPROVEMENT_KIND_SPEC as I, DEFAULT_COMPLEXITY_WEIGHTS as J, KIND_EXPECTED_SUBJECTS as K, DEFAULT_RUN_SCORE_WEIGHTS as L, type RunCriticOptions as M, SEMANTIC_CONCEPT_JUDGE_VERSION as N, type SemanticConceptJudgeResult as O, type PersistedFinding as P, type SuboptimalCode as Q, RunCritic as R, type SemanticConceptJudgeOptions as S, type SuboptimalSignal as T, aggregateRunScore as U, clamp01 as V, computeTraceMetrics as W, createSemanticConceptJudge as X, runSemanticConceptJudge as Y, type RunTrace as a, type SemanticConceptJudgeInput as b, type DiffPolicy as c, FINDING_SUBJECT_GRAMMAR_PROMPT as d, FINDING_SUBJECT_KINDS as e, type FindingSubject as f, type FindingSubjectKind as g, FindingSubjectStringSchema as h, type FindingsDiff as i, FindingsStore as j, KNOWLEDGE_GAP_KIND_SPEC as k, KNOWLEDGE_POISONING_KIND_SPEC as l, SKILL_USAGE_ANALYST as m, SkillUsageAnalyst as n, type SkillUsageRecord as o, type SkillUsageReport as p, type SkillUsageScanConfig as q, buildSkillUsageReport as r, createAnalystAi as s, defaultIsMaterial as t, diffFindings as u, emitSkillUsageFindings as v, parseFindingSubject as w, renderFindingSubject as x, type RunScore as y, type RunScoreWeights as z };
705
+ export { type RunScore as A, type BehavioralMetrics as B, type CreateAnalystAiConfig as C, DEFAULT_TRACE_ANALYST_KINDS as D, type RunScoreWeights as E, FAILURE_MODE_KIND_SPEC as F, type ConceptComplexity as G, type ConceptFinding as H, IMPROVEMENT_KIND_SPEC as I, type ConceptSpec as J, KIND_EXPECTED_SUBJECTS as K, type ConceptWeightStrategy as L, DEFAULT_COMPLEXITY_WEIGHTS as M, DEFAULT_RUN_SCORE_WEIGHTS as N, type RunCriticOptions as O, type PersistedFinding as P, SEMANTIC_CONCEPT_JUDGE_VERSION as Q, RunCritic as R, type SemanticConceptJudgeOptions as S, type SemanticConceptJudgeResult as T, type SuboptimalCode as U, type SuboptimalSignal as V, aggregateRunScore as W, clamp01 as X, computeTraceMetrics as Y, createSemanticConceptJudge as Z, runSemanticConceptJudge as _, type RunTrace as a, type SemanticConceptJudgeInput as b, type DiffPolicy as c, FINDING_SUBJECT_GRAMMAR_PROMPT as d, FINDING_SUBJECT_KINDS as e, FINDING_SUBJECT_SYNTAX as f, type FindingSubject as g, type FindingSubjectKind as h, FindingSubjectStringSchema as i, type FindingsDiff as j, FindingsStore as k, KNOWLEDGE_GAP_KIND_SPEC as l, KNOWLEDGE_POISONING_KIND_SPEC as m, SKILL_USAGE_ANALYST as n, SkillUsageAnalyst as o, type SkillUsageRecord as p, type SkillUsageReport as q, type SkillUsageScanConfig as r, buildSkillUsageReport as s, createAnalystAi as t, defaultIsMaterial as u, diffFindings as v, emitSkillUsageFindings as w, findingSubjectGrammarPromptFor as x, parseFindingSubject as y, renderFindingSubject as z };
@@ -116,20 +116,35 @@ interface JudgeScore {
116
116
  /** Ensemble extras: each surviving judge's per-dimension scores. */
117
117
  perJudge?: Record<string, Record<string, number>>;
118
118
  }
119
- /** A tier-4 code surface — a candidate change to the agent's
119
+ /** A tier-4 code surface — a finalized candidate change to the agent's
120
120
  * IMPLEMENTATION, not its prompt. Produced by autoresearch (reads codebase +
121
- * trace findings → opens a worktree). Measured by checking out `worktreeRef`
122
- * and running the worker against the changed code. See the improvement-tier
123
- * table in `docs/design/loop-taxonomy.md`. */
121
+ * trace findings → opens a worktree). `worktreeRef` locates the candidate;
122
+ * the exact commits, tree, and binary-patch digest identify it. See the
123
+ * improvement-tier table in `docs/design/loop-taxonomy.md`. */
124
124
  interface CodeSurface {
125
- kind: 'code';
126
- /** Worktree path or git ref holding the candidate code change. The
127
- * consumer's `dispatchWithSurface` checks this out before running. */
128
- worktreeRef: string;
129
- /** Base ref the change is measured against. Default: the repo's main. */
130
- baseRef?: string;
125
+ readonly kind: 'code';
126
+ /** Worktree path or git ref holding the candidate code change. This is a
127
+ * mutable locator and is deliberately excluded from content hashes. */
128
+ readonly worktreeRef: string;
129
+ /** Human-readable ref the worktree was forked from. Not identity-bearing. */
130
+ readonly baseRef: string;
131
+ /** Exact commit the candidate was forked from. */
132
+ readonly baseCommit: string;
133
+ /** Exact tree object for `baseCommit`. */
134
+ readonly baseTree: string;
135
+ /** Exact finalized candidate commit. */
136
+ readonly candidateCommit: string;
137
+ /** Exact tree object for `candidateCommit`. */
138
+ readonly candidateTree: string;
139
+ /** Identity of the exact patch artifact. The deployable candidate bundle
140
+ * carries the same descriptor plus its base64-encoded content. */
141
+ readonly patch: {
142
+ readonly format: 'git-diff-binary';
143
+ readonly sha256: `sha256:${string}`;
144
+ readonly byteLength: number;
145
+ };
131
146
  /** Human summary of what changed — rendered into the auto-PR body. */
132
- summary?: string;
147
+ readonly summary?: string;
133
148
  }
134
149
  /** The mutable surface a proposer changes. Tiers (see
135
150
  * `docs/design/loop-taxonomy.md`):
@@ -162,7 +162,13 @@ imports agent-eval and implements it.
162
162
 
163
163
  `MutableSurface` is the thing the proposer changes. It has tiers, least → most
164
164
  invasive. `MutableSurface = string | CodeSurface` spans all of them: `string`
165
- for tiers 1–2, `CodeSurface{ worktreeRef }` for tier 4.
165
+ for tiers 1–2, and a finalized `CodeSurface` for tier 4. A code surface's
166
+ worktree path is only its locator; exact base/candidate commits, final tree,
167
+ and binary-patch digest are its portable identity. Call `verifyCodeSurface`
168
+ before executing the checkout so a moved ref or post-finalization mutation
169
+ fails before measurement. Verification hashes raw files and executable modes
170
+ without Git filters and rejects external symlinks or submodules whose bytes are
171
+ not represented by the candidate tree.
166
172
 
167
173
  | Tier | Surface | Generator that changes it | Blast radius |
168
174
  |---|---|---|---|
@@ -30,7 +30,7 @@ Grounded to `agent-eval/src/campaign/types.ts` unless noted.
30
30
 
31
31
  | Term | Plain sentence | If you know DSPy/GEPA |
32
32
  |---|---|---|
33
- | **surface** | The one thing being changed this run — a prompt string, a JSON config string, or a code/worktree ref (`MutableSurface = string \| CodeSurface`, `types.ts:158`). | The optimized artifact: a signature/predictor's instruction text, or the module config. |
33
+ | **surface** | The one thing being changed this run — a prompt string, a JSON config string, or a finalized code candidate (`MutableSurface = string \| CodeSurface`, `types.ts`). | The optimized artifact: a signature/predictor's instruction text, or the module config. |
34
34
  | **proposer** | The strategy that, given the current surface + what failed, proposes the next batch of candidate surfaces to measure — it does **not** run the agent or score anything (`SurfaceProposer.propose`, `types.ts:286`). | The optimizer / teleprompter (MIPRO, BootstrapFewShot, GEPA's reflective proposer). |
35
35
  | **candidate** | One proposed surface plus its human `label` and `rationale`, ready to be measured (`ProposedCandidate`, `types.ts:166`). | One trial instruction/program the optimizer wants to evaluate. |
36
36
  | **generation** | One round of *propose → measure → rank → promote*; the loop runs up to `maxGenerations` of them (`GenerationRecord`, `types.ts:549`). | One GEPA iteration / optimization step. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-eval",
3
- "version": "0.111.0",
3
+ "version": "0.113.0",
4
4
  "description": "Evaluate and improve AI agents from runs, traces, judges, and feedback. Compare candidates, cluster failures, measure lift, and gate releases.",
5
5
  "homepage": "https://github.com/tangle-network/agent-eval#readme",
6
6
  "repository": {
@@ -146,7 +146,7 @@
146
146
  "@asteasolutions/zod-to-openapi": "^8.5.0",
147
147
  "@ax-llm/ax": "^19.0.25",
148
148
  "@hono/node-server": "^2.0.0",
149
- "@tangle-network/agent-interface": "^0.10.0",
149
+ "@tangle-network/agent-interface": "^0.22.0",
150
150
  "@tangle-network/tcloud": "^0.4.14",
151
151
  "hono": "^4.12.16",
152
152
  "zod": "^4.3.6"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/analyst/steer-firewall.ts","../src/analyst/policy-edit.ts","../src/run-score.ts"],"sourcesContent":["// The realness-oracle firewall (docs/learning-flywheel.md, \"The steer is f(trace)\").\n//\n// A realness/authenticity signal has TWO legitimate roles that must stay\n// separated by a firewall:\n// (a) anchor judge J — write-only: scores the chosen output, gates promotion,\n// NEVER seen by the worker/optimizer mid-run (else the loop games it).\n// (b) steer f(trace) — an analyst observes the agent's OWN behavior in the\n// trace (\"imported a stub\", \"used a non-crypto PRNG where encryption was\n// required\") and steers the next attempt. Legitimate, because it is derived\n// from OBSERVABLE BEHAVIOR, not from J's held-out verdict.\n//\n// The correct discriminator is PROVENANCE, not evidence presence. A judge verdict\n// lifted into a finding (createJudgeAdapter → liftJudgeScore) is a verdict even\n// when it cites an artifact; an evidence-less trace-analyst bullet is an\n// observation even though it cites nothing. So the firewall keys on\n// `AnalystFinding.derived_from_judge` (set at the judge lift site), NOT on whether\n// evidence_refs is populated. The instant a verdict steers the next attempt it is\n// a back-channel for J and the loop Goodharts realness exactly as it would\n// Goodhart pass-rate.\n\nimport type { AnalystFinding, EvidenceRef } from './types'\n\n/** Evidence grounded in the agent's OWN execution: OTLP trace elements\n * (`span`/`event`) or the artifact it produced (`artifact`). */\nconst OBSERVABLE_KINDS: ReadonlySet<EvidenceRef['kind']> = new Set<EvidenceRef['kind']>([\n 'span',\n 'event',\n 'artifact',\n])\n\n/** DESCRIPTIVE predicate: does the finding cite at least one observable\n * (span/event/artifact) evidence ref. Useful for ranking evidence quality or\n * rendering — it is NOT the steer gate. Evidence presence is the WRONG\n * discriminator for steering: a legitimate trace-analyst observation may cite\n * nothing (it would be wrongly rejected), and a judge verdict may cite an\n * artifact (it would be wrongly admitted). Use `assertNoJudgeVerdict` to gate\n * steering; use this only where \"is this grounded in observable evidence\" is the\n * literal question. */\nexport function isTraceObservable(finding: AnalystFinding): boolean {\n return finding.evidence_refs.some((ref) => OBSERVABLE_KINDS.has(ref.kind))\n}\n\n/** True iff the finding is a JUDGE VERDICT (an acceptance score lifted into a\n * finding), identified by provenance set at the lift site — independent of\n * whatever evidence it cites. */\nexport function isJudgeVerdict(finding: AnalystFinding): boolean {\n return finding.derived_from_judge === true\n}\n\n/**\n * THE steer firewall. Fail-loud guard for any path that admits analyst findings\n * as STEERING input (the `f(trace)` role): rejects — naming the offenders — any\n * finding whose provenance is a judge verdict, rather than let `J` leak into the\n * loop. Returns the findings unchanged for chaining.\n *\n * Call this at the chokepoint where a detector that ALSO scores/gates has its\n * findings turned into a steer (the judge-and-steer dual-role case). It keys on\n * provenance, so it correctly admits evidence-less trace-analyst observations and\n * correctly rejects an artifact-citing judge verdict — the cases an evidence\n * check gets backwards.\n *\n * It is necessary, not sufficient: it stops PROVENANCE-tagged verdicts. A judge\n * whose output is laundered through a hand-built finding with no provenance flag\n * is out of its reach — provenance must be honestly set at every judge→finding\n * lift (today: createJudgeAdapter). That is why the integrity rule lives at the\n * lift site, and why ProposeContext.judgeScores?: never is the complementary\n * compile-time tripwire on the obvious direct channel.\n */\nexport function assertNoJudgeVerdict(\n findings: ReadonlyArray<AnalystFinding>,\n context = 'steer',\n): ReadonlyArray<AnalystFinding> {\n const leaks = findings.filter(isJudgeVerdict)\n if (leaks.length > 0) {\n throw new Error(\n `${context}: a judge verdict cannot be admitted as steering input — that is the ` +\n `held-out judge leaking into the loop. Offending judge-derived findings: [${leaks\n .map((f) => f.finding_id)\n .join(', ')}]. Steering consumes observations of behavior, never acceptance verdicts.`,\n )\n }\n return findings\n}\n","import { createHash } from 'node:crypto'\nimport type { AgentProfileCell, AgentProfileJson } from '../agent-profile-cell'\nimport { validateAgentProfileCell } from '../agent-profile-cell'\nimport { ValidationError } from '../errors'\nimport { canonicalize } from '../pre-registration'\nimport { type FindingSubject, parseFindingSubject } from './finding-subject'\nimport { assertNoJudgeVerdict } from './steer-firewall'\nimport type { AnalystFinding, EvidenceRef } from './types'\n\nexport type PolicyEditSchemaVersion = 'policy-edit/v1'\n\nexport const POLICY_EDIT_AXES = [\n 'carrier',\n 'representation',\n 'budget',\n 'sampling',\n 'output_contract',\n 'tool_contract',\n 'routing',\n 'memory',\n 'agent_profile',\n 'deployment_target',\n] as const\n\nexport type PolicyEditAxis = (typeof POLICY_EDIT_AXES)[number]\n\nexport const POLICY_EDIT_TARGET_SURFACES = [\n 'prompt',\n 'tool-contract',\n 'runtime-config',\n 'memory',\n 'agent-profile',\n 'deployment',\n] as const\n\nexport type PolicyEditTargetSurface = (typeof POLICY_EDIT_TARGET_SURFACES)[number]\nexport type PolicyEditRisk = 'low' | 'medium' | 'high' | 'unknown'\nexport type PolicyEditGainDirection = 'increase' | 'decrease'\nexport type PolicyEditGainUnit = 'absolute' | 'relative' | 'percent' | 'score'\n\nexport interface PolicyEditTarget {\n surface: PolicyEditTargetSurface\n /** Stable path inside the target surface, for example `system-prompt:tools`\n * or `budget.maxTurns`. */\n path?: string\n /** Optional canonical deployment identity. Store the existing cell, not a\n * local profile shape. */\n agentProfileCell?: AgentProfileCell\n /** Human label when the path is not enough for a readable audit trail. */\n label?: string\n}\n\nexport type PolicyEditChange =\n | {\n kind: 'text'\n mode: 'append' | 'prepend' | 'replace'\n value: string\n /** Required when `mode === 'replace'`; exact match only. */\n find?: string\n }\n | {\n kind: 'json'\n mode: 'set' | 'merge' | 'remove'\n path: string\n value?: AgentProfileJson\n }\n\nexport interface PolicyEditExpectedGain {\n /** Metric this edit is expected to move, e.g. `holdout.composite`. */\n metric: string\n direction: PolicyEditGainDirection\n /** Positive magnitude in the metric's native units. */\n amount: number\n unit?: PolicyEditGainUnit\n rationale?: string\n}\n\nexport interface PolicyEditSource {\n findingIds: string[]\n analystIds: string[]\n evidenceRefs: EvidenceRef[]\n /** Mirrors `AnalystFinding.derived_from_judge`; admission rejects it. */\n derivedFromJudge?: boolean\n}\n\nexport interface PolicyEdit {\n schemaVersion: PolicyEditSchemaVersion\n editId: string\n axis: PolicyEditAxis\n target: PolicyEditTarget\n change: PolicyEditChange\n claim: string\n expectedGain: PolicyEditExpectedGain\n confidence: number\n risk: PolicyEditRisk\n source: PolicyEditSource\n rationale?: string\n validationPlan?: string\n metadata?: Record<string, unknown>\n}\n\nexport type PolicyEditInit = Omit<PolicyEdit, 'schemaVersion' | 'editId'> & {\n schemaVersion?: PolicyEditSchemaVersion\n editId?: string\n}\n\nexport class PolicyEditValidationError extends ValidationError {\n readonly path: string\n constructor(message: string, path = '') {\n super(path ? `${message} (at ${path})` : message)\n this.path = path\n }\n}\n\nexport interface FindingToPolicyEditOptions {\n expectedGain?:\n | PolicyEditExpectedGain\n | ((finding: AnalystFinding) => PolicyEditExpectedGain | null | undefined)\n risk?: PolicyEditRisk | ((finding: AnalystFinding) => PolicyEditRisk)\n defaultAxis?: PolicyEditAxis\n defaultTargetSurface?: PolicyEditTargetSurface\n}\n\nexport interface PolicyEditAdmissionOptions {\n minScore?: number\n minExpectedGain?: number\n allowHighRisk?: boolean\n requireEvidence?: boolean\n}\n\nexport interface PolicyEditAdmission {\n edit: PolicyEdit\n decision: 'admit' | 'reject'\n score: number\n reasons: string[]\n}\n\nconst DEFAULT_MIN_SCORE = 0.7\nconst DEFAULT_MIN_EXPECTED_GAIN = 0.01\nconst POLICY_EDIT_ID = /^policy-edit:sha256:[0-9a-f]{64}$/\n\nexport function makePolicyEdit(init: PolicyEditInit): PolicyEdit {\n const normalized = normalizePolicyEdit({\n schemaVersion: 'policy-edit/v1',\n ...init,\n source: normalizeSource(init.source),\n })\n const edit = {\n ...normalized,\n editId: init.editId ?? computePolicyEditId(normalized),\n }\n return validatePolicyEdit(edit)\n}\n\nexport function computePolicyEditId(edit: Omit<PolicyEdit, 'editId'> | PolicyEdit): string {\n const { editId: _editId, schemaVersion, ...material } = edit as PolicyEdit\n void _editId\n const canonical = JSON.stringify(canonicalize({ schemaVersion, ...material }))\n return `policy-edit:sha256:${createHash('sha256').update(canonical).digest('hex')}`\n}\n\nexport function validatePolicyEdit(input: unknown): PolicyEdit {\n if (input === null || typeof input !== 'object') {\n throw new PolicyEditValidationError('expected object')\n }\n const obj = input as PolicyEdit\n expectLiteral(obj.schemaVersion, 'policy-edit/v1', 'schemaVersion')\n expectString(obj.editId, 'editId')\n if (!POLICY_EDIT_ID.test(obj.editId)) {\n throw new PolicyEditValidationError(\n 'editId must match policy-edit:sha256:<64 lowercase hex chars>',\n 'editId',\n )\n }\n expectOneOf(obj.axis, POLICY_EDIT_AXES, 'axis')\n validateTarget(obj.target)\n validateChange(obj.change)\n expectString(obj.claim, 'claim')\n validateExpectedGain(obj.expectedGain)\n expectConfidence(obj.confidence, 'confidence')\n expectOneOf(obj.risk, ['low', 'medium', 'high', 'unknown'] as const, 'risk')\n validateSource(obj.source)\n if (obj.rationale !== undefined) expectString(obj.rationale, 'rationale')\n if (obj.validationPlan !== undefined) expectString(obj.validationPlan, 'validationPlan')\n if (obj.metadata !== undefined && (obj.metadata === null || typeof obj.metadata !== 'object')) {\n throw new PolicyEditValidationError('expected object', 'metadata')\n }\n const expectedId = computePolicyEditId(obj)\n if (obj.editId !== expectedId) {\n throw new PolicyEditValidationError('editId does not match policy edit content', 'editId')\n }\n return obj\n}\n\nexport function isPolicyEdit(input: unknown): input is PolicyEdit {\n try {\n validatePolicyEdit(input)\n return true\n } catch {\n return false\n }\n}\n\nexport function policyEditsFromFindings(\n findings: ReadonlyArray<AnalystFinding>,\n opts: FindingToPolicyEditOptions = {},\n): PolicyEdit[] {\n assertNoJudgeVerdict(findings, 'policyEditsFromFindings')\n const edits: PolicyEdit[] = []\n for (const finding of findings) {\n const edit = policyEditFromFinding(finding, opts)\n if (edit) edits.push(edit)\n }\n return edits\n}\n\nexport function policyEditFromFinding(\n finding: AnalystFinding,\n opts: FindingToPolicyEditOptions = {},\n): PolicyEdit | null {\n assertNoJudgeVerdict([finding], 'policyEditFromFinding')\n if (!finding.recommended_action?.trim()) return null\n\n const expectedGain = resolveExpectedGain(finding, opts)\n if (!expectedGain) return null\n\n const routed = routeFindingSubject(finding.subject, opts)\n const risk = resolveRisk(finding, opts)\n return makePolicyEdit({\n axis: routed.axis,\n target: routed.target,\n change: { kind: 'text', mode: 'append', value: finding.recommended_action.trim() },\n claim: finding.claim,\n rationale: finding.rationale,\n expectedGain,\n confidence: finding.confidence,\n risk,\n validationPlan: finding.validation_plan,\n source: {\n findingIds: [finding.finding_id],\n analystIds: [finding.analyst_id],\n evidenceRefs: finding.evidence_refs,\n derivedFromJudge: finding.derived_from_judge,\n },\n })\n}\n\nexport function scorePolicyEditReadiness(\n edit: PolicyEdit,\n opts: PolicyEditAdmissionOptions = {},\n): number {\n validatePolicyEdit(edit)\n const minExpectedGain = opts.minExpectedGain ?? DEFAULT_MIN_EXPECTED_GAIN\n const evidenceScore = Math.min(1, edit.source.evidenceRefs.length / 2)\n const confidenceScore = clamp01(edit.confidence)\n const gainScore = clamp01(\n Math.abs(edit.expectedGain.amount) / Math.max(minExpectedGain * 5, 0.001),\n )\n const targetScore = targetSpecificityScore(edit)\n const riskPenalty =\n edit.risk === 'high' && opts.allowHighRisk !== true ? 0.35 : edit.risk === 'unknown' ? 0.2 : 0\n\n return clamp01(\n 0.3 * evidenceScore +\n 0.25 * confidenceScore +\n 0.25 * gainScore +\n 0.2 * targetScore -\n riskPenalty,\n )\n}\n\nexport function admitPolicyEdit(\n edit: PolicyEdit,\n opts: PolicyEditAdmissionOptions = {},\n): PolicyEditAdmission {\n const validated = validatePolicyEdit(edit)\n const score = scorePolicyEditReadiness(validated, opts)\n const reasons: string[] = []\n const minExpectedGain = opts.minExpectedGain ?? DEFAULT_MIN_EXPECTED_GAIN\n const requireEvidence = opts.requireEvidence ?? true\n\n if (validated.source.derivedFromJudge) {\n reasons.push('source is judge-derived; judge verdicts cannot steer policy edits')\n }\n if (requireEvidence && validated.source.evidenceRefs.length === 0) {\n reasons.push('missing evidence refs')\n }\n if (Math.abs(validated.expectedGain.amount) < minExpectedGain) {\n reasons.push(`expected gain below ${minExpectedGain}`)\n }\n if (validated.risk === 'high' && opts.allowHighRisk !== true) {\n reasons.push('high-risk edit requires explicit allowHighRisk')\n }\n if (score < (opts.minScore ?? DEFAULT_MIN_SCORE)) {\n reasons.push(\n `readiness score ${score.toFixed(3)} below ${(opts.minScore ?? DEFAULT_MIN_SCORE).toFixed(3)}`,\n )\n }\n\n return {\n edit: validated,\n decision: reasons.length === 0 ? 'admit' : 'reject',\n score,\n reasons,\n }\n}\n\nexport function applyPolicyEditToSurface(surface: unknown, edit: PolicyEdit): unknown {\n const validated = validatePolicyEdit(edit)\n if (validated.change.kind === 'text') return applyTextChange(surface, validated.change)\n return applyJsonChange(surface, validated.change)\n}\n\nfunction routeFindingSubject(\n subject: string | undefined,\n opts: FindingToPolicyEditOptions,\n): { axis: PolicyEditAxis; target: PolicyEditTarget } {\n const parsed = parseFindingSubject(subject)\n if (!parsed) {\n return {\n axis: opts.defaultAxis ?? 'representation',\n target: { surface: opts.defaultTargetSurface ?? 'prompt' },\n }\n }\n return routeParsedSubject(parsed)\n}\n\nfunction routeParsedSubject(subject: FindingSubject): {\n axis: PolicyEditAxis\n target: PolicyEditTarget\n} {\n switch (subject.kind) {\n case 'system-prompt':\n return {\n axis: 'representation',\n target: { surface: 'prompt', path: `system-prompt:${subject.section}` },\n }\n case 'tool-doc':\n return {\n axis: 'tool_contract',\n target: {\n surface: 'tool-contract',\n path: subject.aspect\n ? `tool-doc:${subject.tool}:${subject.aspect}`\n : `tool-doc:${subject.tool}`,\n },\n }\n case 'new-tool':\n return {\n axis: 'tool_contract',\n target: { surface: 'tool-contract', path: `new-tool:${subject.name}` },\n }\n case 'rag':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `rag:${subject.corpus}:${subject.docId}` },\n }\n case 'memory':\n return { axis: 'memory', target: { surface: 'memory', path: `memory:${subject.key}` } }\n case 'scaffolding':\n return {\n axis: 'routing',\n target: { surface: 'runtime-config', path: `scaffolding:${subject.concern}` },\n }\n case 'output-schema':\n return {\n axis: 'output_contract',\n target: { surface: 'runtime-config', path: `output-schema:${subject.field}` },\n }\n case 'knowledge.wiki':\n return {\n axis: 'memory',\n target: {\n surface: 'memory',\n path: `agent-knowledge:wiki:${subject.slug}${subject.heading ? `#${subject.heading}` : ''}`,\n },\n }\n case 'knowledge.claim':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `agent-knowledge:claim:${subject.topic}` },\n }\n case 'knowledge.raw':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `agent-knowledge:raw:${subject.sourceId}` },\n }\n case 'knowledge.stale':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `agent-knowledge:stale:${subject.slug}` },\n }\n case 'websearch.outdated':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `websearch:outdated:${subject.topic}` },\n }\n case 'prior-run-summary':\n return {\n axis: 'memory',\n target: { surface: 'memory', path: `prior-run-summary:${subject.topic}` },\n }\n case 'cluster':\n return { axis: 'representation', target: { surface: 'prompt', path: subject.label } }\n }\n}\n\nfunction resolveExpectedGain(\n finding: AnalystFinding,\n opts: FindingToPolicyEditOptions,\n): PolicyEditExpectedGain | null {\n if (typeof opts.expectedGain === 'function') return opts.expectedGain(finding) ?? null\n if (opts.expectedGain) return opts.expectedGain\n return readExpectedGainFromMetadata(finding.metadata)\n}\n\nfunction readExpectedGainFromMetadata(\n metadata: Record<string, unknown> | undefined,\n): PolicyEditExpectedGain | null {\n const raw =\n readPolicyEditMetadata(metadata)?.expectedGain ??\n readPolicyEditMetadata(metadata)?.expected_gain\n if (!raw || typeof raw !== 'object') return null\n const obj = raw as Record<string, unknown>\n if (\n typeof obj.metric !== 'string' ||\n (obj.direction !== 'increase' && obj.direction !== 'decrease') ||\n typeof obj.amount !== 'number'\n ) {\n return null\n }\n const out: PolicyEditExpectedGain = {\n metric: obj.metric,\n direction: obj.direction,\n amount: obj.amount,\n }\n if (\n obj.unit === 'absolute' ||\n obj.unit === 'relative' ||\n obj.unit === 'percent' ||\n obj.unit === 'score'\n ) {\n out.unit = obj.unit\n }\n if (typeof obj.rationale === 'string') out.rationale = obj.rationale\n return out\n}\n\nfunction readPolicyEditMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, unknown> | null {\n const raw = metadata?.policyEdit ?? metadata?.policy_edit\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null\n}\n\nfunction resolveRisk(finding: AnalystFinding, opts: FindingToPolicyEditOptions): PolicyEditRisk {\n if (typeof opts.risk === 'function') return opts.risk(finding)\n if (opts.risk) return opts.risk\n const raw = readPolicyEditMetadata(finding.metadata)?.risk\n if (raw === 'low' || raw === 'medium' || raw === 'high' || raw === 'unknown') return raw\n if (finding.severity === 'critical' || finding.severity === 'high') return 'medium'\n return 'low'\n}\n\nfunction applyTextChange(\n surface: unknown,\n change: Extract<PolicyEditChange, { kind: 'text' }>,\n): string {\n if (typeof surface !== 'string') {\n throw new PolicyEditValidationError('text policy edits require a string surface', 'change')\n }\n if (change.mode === 'append') {\n if (hasExactTextBlock(surface, change.value)) return surface\n return `${surface.trimEnd()}\\n\\n${change.value}`.trimStart()\n }\n if (change.mode === 'prepend') {\n if (hasExactTextBlock(surface, change.value)) return surface\n return `${change.value}\\n\\n${surface.trimStart()}`.trimEnd()\n }\n const find = expectNonEmpty(change.find, 'change.find')\n if (!surface.includes(find)) {\n throw new PolicyEditValidationError('replace target not found in surface', 'change.find')\n }\n return surface.replace(find, change.value)\n}\n\nfunction applyJsonChange(\n surface: unknown,\n change: Extract<PolicyEditChange, { kind: 'json' }>,\n): AgentProfileJson {\n const root = parseJsonSurface(surface)\n const path = splitPath(change.path)\n if (change.mode === 'remove') return setJsonAtPath(root, path, undefined, 'remove')\n if (change.mode === 'set') return setJsonAtPath(root, path, change.value ?? null, 'set')\n const prior = readJsonAtPath(root, path)\n const merged =\n prior &&\n typeof prior === 'object' &&\n !Array.isArray(prior) &&\n change.value &&\n typeof change.value === 'object' &&\n !Array.isArray(change.value)\n ? { ...prior, ...change.value }\n : (change.value ?? null)\n return setJsonAtPath(root, path, merged as AgentProfileJson, 'set')\n}\n\nfunction parseJsonSurface(surface: unknown): AgentProfileJson {\n if (typeof surface === 'string') {\n try {\n return JSON.parse(surface) as AgentProfileJson\n } catch {\n throw new PolicyEditValidationError(\n 'json policy edits require a JSON string surface',\n 'change',\n )\n }\n }\n assertJson(surface, 'surface')\n return surface as AgentProfileJson\n}\n\nfunction readJsonAtPath(root: AgentProfileJson, path: string[]): AgentProfileJson | undefined {\n let cursor: AgentProfileJson | undefined = root\n for (const part of path) {\n if (!cursor || typeof cursor !== 'object' || Array.isArray(cursor)) return undefined\n cursor = cursor[part]\n }\n return cursor\n}\n\nfunction setJsonAtPath(\n root: AgentProfileJson,\n path: string[],\n value: AgentProfileJson | undefined,\n mode: 'set' | 'remove',\n): AgentProfileJson {\n if (path.length === 0) {\n if (mode === 'remove') return null\n return value ?? null\n }\n if (root === null || typeof root !== 'object' || Array.isArray(root)) {\n throw new PolicyEditValidationError('json edit root must be an object', 'change.path')\n }\n const out: Record<string, AgentProfileJson> = { ...root }\n let cursor: Record<string, AgentProfileJson> = out\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]!\n const existing = cursor[key]\n if (\n mode === 'remove' &&\n (!existing || typeof existing !== 'object' || Array.isArray(existing))\n ) {\n return out\n }\n const next =\n existing && typeof existing === 'object' && !Array.isArray(existing) ? { ...existing } : {}\n cursor[key] = next\n cursor = next\n }\n const leaf = path[path.length - 1]!\n if (mode === 'remove') delete cursor[leaf]\n else cursor[leaf] = value ?? null\n return out\n}\n\nfunction normalizePolicyEdit(input: Omit<PolicyEdit, 'editId'>): Omit<PolicyEdit, 'editId'> {\n const out: Omit<PolicyEdit, 'editId'> = {\n schemaVersion: 'policy-edit/v1',\n axis: input.axis,\n target: normalizeTarget(input.target),\n change: normalizeChange(input.change),\n claim: input.claim.trim(),\n expectedGain: normalizeExpectedGain(input.expectedGain),\n confidence: input.confidence,\n risk: input.risk,\n source: normalizeSource(input.source),\n }\n if (input.rationale?.trim()) out.rationale = input.rationale.trim()\n if (input.validationPlan?.trim()) out.validationPlan = input.validationPlan.trim()\n if (input.metadata) out.metadata = input.metadata\n return out\n}\n\nfunction normalizeTarget(target: PolicyEditTarget): PolicyEditTarget {\n const out: PolicyEditTarget = { surface: target.surface }\n if (target.path?.trim()) out.path = target.path.trim()\n if (target.agentProfileCell)\n out.agentProfileCell = validateAgentProfileCell(target.agentProfileCell)\n if (target.label?.trim()) out.label = target.label.trim()\n return out\n}\n\nfunction normalizeChange(change: PolicyEditChange): PolicyEditChange {\n if (change.kind === 'text') {\n const out: Extract<PolicyEditChange, { kind: 'text' }> = {\n kind: 'text',\n mode: change.mode,\n value: change.value.trim(),\n }\n if (change.find?.trim()) out.find = change.find.trim()\n return out\n }\n const out: Extract<PolicyEditChange, { kind: 'json' }> = {\n kind: 'json',\n mode: change.mode,\n path: change.path.trim(),\n }\n if (change.value !== undefined) out.value = change.value\n return out\n}\n\nfunction normalizeExpectedGain(gain: PolicyEditExpectedGain): PolicyEditExpectedGain {\n const out: PolicyEditExpectedGain = {\n metric: gain.metric.trim(),\n direction: gain.direction,\n amount: gain.amount,\n }\n if (gain.unit) out.unit = gain.unit\n if (gain.rationale?.trim()) out.rationale = gain.rationale.trim()\n return out\n}\n\nfunction normalizeSource(source: PolicyEditSource): PolicyEditSource {\n const out: PolicyEditSource = {\n findingIds: uniqueSorted(source.findingIds.map((s) => s.trim()).filter(Boolean)),\n analystIds: uniqueSorted(source.analystIds.map((s) => s.trim()).filter(Boolean)),\n evidenceRefs: source.evidenceRefs,\n }\n if (source.derivedFromJudge) out.derivedFromJudge = true\n return out\n}\n\nfunction validateTarget(target: unknown): asserts target is PolicyEditTarget {\n if (!target || typeof target !== 'object')\n throw new PolicyEditValidationError('expected object', 'target')\n const obj = target as PolicyEditTarget\n expectOneOf(obj.surface, POLICY_EDIT_TARGET_SURFACES, 'target.surface')\n if (obj.path !== undefined) expectString(obj.path, 'target.path')\n if (obj.label !== undefined) expectString(obj.label, 'target.label')\n if (obj.agentProfileCell !== undefined) validateAgentProfileCell(obj.agentProfileCell)\n}\n\nfunction validateChange(change: unknown): asserts change is PolicyEditChange {\n if (!change || typeof change !== 'object')\n throw new PolicyEditValidationError('expected object', 'change')\n const obj = change as PolicyEditChange\n if (obj.kind !== 'text' && obj.kind !== 'json') {\n throw new PolicyEditValidationError('kind must be text or json', 'change.kind')\n }\n if (obj.kind === 'text') {\n expectOneOf(obj.mode, ['append', 'prepend', 'replace'] as const, 'change.mode')\n expectString(obj.value, 'change.value')\n if (obj.mode === 'replace') expectString(obj.find, 'change.find')\n return\n }\n expectOneOf(obj.mode, ['set', 'merge', 'remove'] as const, 'change.mode')\n expectString(obj.path, 'change.path')\n if (obj.value !== undefined) assertJson(obj.value, 'change.value')\n}\n\nfunction validateExpectedGain(gain: unknown): asserts gain is PolicyEditExpectedGain {\n if (!gain || typeof gain !== 'object')\n throw new PolicyEditValidationError('expected object', 'expectedGain')\n const obj = gain as PolicyEditExpectedGain\n expectString(obj.metric, 'expectedGain.metric')\n expectOneOf(obj.direction, ['increase', 'decrease'] as const, 'expectedGain.direction')\n if (!Number.isFinite(obj.amount) || obj.amount <= 0) {\n throw new PolicyEditValidationError(\n 'amount must be a positive finite number',\n 'expectedGain.amount',\n )\n }\n if (obj.unit !== undefined) {\n expectOneOf(\n obj.unit,\n ['absolute', 'relative', 'percent', 'score'] as const,\n 'expectedGain.unit',\n )\n }\n if (obj.rationale !== undefined) expectString(obj.rationale, 'expectedGain.rationale')\n}\n\nfunction validateSource(source: unknown): asserts source is PolicyEditSource {\n if (!source || typeof source !== 'object')\n throw new PolicyEditValidationError('expected object', 'source')\n const obj = source as PolicyEditSource\n expectNonEmptyStringArray(obj.findingIds, 'source.findingIds')\n expectNonEmptyStringArray(obj.analystIds, 'source.analystIds')\n if (!Array.isArray(obj.evidenceRefs)) {\n throw new PolicyEditValidationError('expected array', 'source.evidenceRefs')\n }\n for (const [i, ref] of obj.evidenceRefs.entries())\n validateEvidenceRef(ref, `source.evidenceRefs.${i}`)\n if (obj.derivedFromJudge !== undefined && typeof obj.derivedFromJudge !== 'boolean') {\n throw new PolicyEditValidationError('expected boolean', 'source.derivedFromJudge')\n }\n}\n\nfunction validateEvidenceRef(ref: unknown, path: string): asserts ref is EvidenceRef {\n if (!ref || typeof ref !== 'object') throw new PolicyEditValidationError('expected object', path)\n const obj = ref as EvidenceRef\n expectOneOf(obj.kind, ['span', 'event', 'artifact', 'finding', 'metric'] as const, `${path}.kind`)\n expectString(obj.uri, `${path}.uri`)\n if (obj.excerpt !== undefined) expectString(obj.excerpt, `${path}.excerpt`)\n}\n\nfunction assertJson(value: unknown, path: string): asserts value is AgentProfileJson {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean' ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return\n }\n if (Array.isArray(value)) {\n for (const [i, item] of value.entries()) assertJson(item, `${path}.${i}`)\n return\n }\n if (typeof value === 'object') {\n for (const [key, item] of Object.entries(value)) {\n if (!key) throw new PolicyEditValidationError('empty object key', path)\n assertJson(item, `${path}.${key}`)\n }\n return\n }\n throw new PolicyEditValidationError('expected JSON-compatible value', path)\n}\n\nfunction targetSpecificityScore(edit: PolicyEdit): number {\n let score = 0.4\n if (edit.target.path) score += 0.25\n if (edit.target.agentProfileCell) score += 0.15\n if (edit.change.kind === 'json' || edit.change.mode === 'replace') score += 0.2\n else if (edit.change.value.length > 0) score += 0.1\n return clamp01(score)\n}\n\nfunction splitPath(path: string): string[] {\n const parts = path\n .split('.')\n .map((p) => p.trim())\n .filter(Boolean)\n if (parts.length === 0)\n throw new PolicyEditValidationError('path must not be empty', 'change.path')\n return parts\n}\n\nfunction expectLiteral<T extends string>(\n value: unknown,\n expected: T,\n path: string,\n): asserts value is T {\n if (value !== expected) throw new PolicyEditValidationError(`expected ${expected}`, path)\n}\n\nfunction expectString(value: unknown, path: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new PolicyEditValidationError('expected non-empty string', path)\n }\n}\n\nfunction expectNonEmpty(value: unknown, path: string): string {\n expectString(value, path)\n return value\n}\n\nfunction expectConfidence(value: unknown, path: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n throw new PolicyEditValidationError('expected finite number in [0,1]', path)\n }\n}\n\nfunction hasExactTextBlock(surface: string, value: string): boolean {\n const needle = normalizeTextBlock(value)\n const normalizedSurface = surface.replace(/\\r\\n/g, '\\n')\n return [...normalizedSurface.split(/\\n{2,}/), ...normalizedSurface.split('\\n')].some(\n (block) => normalizeTextBlock(block) === needle,\n )\n}\n\nfunction normalizeTextBlock(value: string): string {\n return value.replace(/\\r\\n/g, '\\n').trim()\n}\n\nfunction expectOneOf<const T extends readonly string[]>(\n value: unknown,\n allowed: T,\n path: string,\n): asserts value is T[number] {\n if (typeof value !== 'string' || !allowed.includes(value)) {\n throw new PolicyEditValidationError(`expected one of ${allowed.join(', ')}`, path)\n }\n}\n\nfunction expectStringArray(value: unknown, path: string): asserts value is string[] {\n if (!Array.isArray(value)) throw new PolicyEditValidationError('expected array', path)\n for (const [i, item] of value.entries()) expectString(item, `${path}.${i}`)\n}\n\nfunction expectNonEmptyStringArray(value: unknown, path: string): asserts value is string[] {\n expectStringArray(value, path)\n if (value.length === 0) throw new PolicyEditValidationError('expected non-empty array', path)\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort()\n}\n\nfunction clamp01(n: number): number {\n if (!Number.isFinite(n)) return 0\n if (n < 0) return 0\n if (n > 1) return 1\n return n\n}\n","export interface RunScore {\n success: number\n goalProgress: number\n repoGroundedness: number\n driftPenalty: number\n toolUseQuality: number\n patchQuality: number\n testReality: number\n finalGate: number\n reviewerBlockers: number\n costUsd: number\n wallSeconds: number\n notes?: string[]\n}\n\nexport interface RunScoreWeights {\n success: number\n goalProgress: number\n repoGroundedness: number\n driftPenalty: number\n toolUseQuality: number\n patchQuality: number\n testReality: number\n finalGate: number\n reviewerBlockers: number\n costUsd: number\n wallSeconds: number\n}\n\nexport const DEFAULT_RUN_SCORE_WEIGHTS: RunScoreWeights = {\n success: 4,\n goalProgress: 2,\n repoGroundedness: 1.5,\n driftPenalty: -1.5,\n toolUseQuality: 1,\n patchQuality: 1.25,\n testReality: 1.5,\n finalGate: 3,\n reviewerBlockers: -2,\n costUsd: -0.2,\n wallSeconds: -0.1,\n}\n\nexport function aggregateRunScore(score: RunScore, weights: Partial<RunScoreWeights> = {}): number {\n const w = { ...DEFAULT_RUN_SCORE_WEIGHTS, ...weights }\n return (\n w.success * clamp01(score.success) +\n w.goalProgress * clamp01(score.goalProgress) +\n w.repoGroundedness * clamp01(score.repoGroundedness) +\n w.driftPenalty * clamp01(score.driftPenalty) +\n w.toolUseQuality * clamp01(score.toolUseQuality) +\n w.patchQuality * clamp01(score.patchQuality) +\n w.testReality * clamp01(score.testReality) +\n w.finalGate * clamp01(score.finalGate) +\n w.reviewerBlockers * clamp01(score.reviewerBlockers) +\n w.costUsd * Math.max(0, finiteOrZero(score.costUsd)) +\n w.wallSeconds * Math.max(0, finiteOrZero(score.wallSeconds) / 60)\n )\n}\n\nexport function clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.min(1, value))\n}\n\nfunction finiteOrZero(value: number): number {\n return Number.isFinite(value) ? value : 0\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,IAAM,mBAAqD,oBAAI,IAAyB;AAAA,EACtF;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAUM,SAAS,kBAAkB,SAAkC;AAClE,SAAO,QAAQ,cAAc,KAAK,CAAC,QAAQ,iBAAiB,IAAI,IAAI,IAAI,CAAC;AAC3E;AAKO,SAAS,eAAe,SAAkC;AAC/D,SAAO,QAAQ,uBAAuB;AACxC;AAqBO,SAAS,qBACd,UACA,UAAU,SACqB;AAC/B,QAAM,QAAQ,SAAS,OAAO,cAAc;AAC5C,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,IAAI;AAAA,MACR,GAAG,OAAO,sJACoE,MACzE,IAAI,CAAC,MAAM,EAAE,UAAU,EACvB,KAAK,IAAI,CAAC;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;;;AClFA,SAAS,kBAAkB;AAWpB,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIO,IAAM,8B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