@tangle-network/agent-runtime 0.337.2 → 0.339.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.
- package/dist/{activation-DRHM55Oo.d.ts → activation-CJIIl_Ey.d.ts} +90 -22
- package/dist/activation-CVSFxis9.js +876 -0
- package/dist/activation-CVSFxis9.js.map +1 -0
- package/dist/agent.d.ts +4 -4
- package/dist/agent.js +4 -7
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-BPGjESee.js → bundle-DVOhBTic.js} +2 -2
- package/dist/{bundle-BPGjESee.js.map → bundle-DVOhBTic.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +4 -63
- package/dist/candidate-execution/index.js +6 -146
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/content-digest-sBTLujlK.js +9 -0
- package/dist/content-digest-sBTLujlK.js.map +1 -0
- package/dist/{delegate-B-T_ZB50.js → delegate-CCWE_AkU.js} +2 -2
- package/dist/{delegate-B-T_ZB50.js.map → delegate-CCWE_AkU.js.map} +1 -1
- package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-C53ggdJ6.js} +4520 -4442
- package/dist/driver-control-acknowledgers-C53ggdJ6.js.map +1 -0
- package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
- package/dist/durable-file-gNI9ILAn.js.map +1 -0
- package/dist/durable.d.ts +3 -35
- package/dist/durable.js +225 -229
- package/dist/durable.js.map +1 -1
- package/dist/{graph-C4RFlWAJ.js → graph-CI9JXKqO.js} +65 -18
- package/dist/graph-CI9JXKqO.js.map +1 -0
- package/dist/{graph-registry-DAI6KNXB.js → graph-registry-BnO64cn8.js} +18 -17
- package/dist/graph-registry-BnO64cn8.js.map +1 -0
- package/dist/{improvement-cycle-D1I4hQvf.js → improve-BOXTLWJ3.js} +76 -1248
- package/dist/improve-BOXTLWJ3.js.map +1 -0
- package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-HUt_-cWA.d.ts} +2 -20
- package/dist/index.d.ts +10 -207
- package/dist/index.js +91 -305
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +10 -229
- package/dist/intelligence.js +506 -88
- package/dist/intelligence.js.map +1 -1
- package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
- package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
- package/dist/kernel.d.ts +4 -3
- package/dist/kernel.js +12 -13
- package/dist/loop-runner-CWzG1bH4.d.ts +32 -0
- package/dist/loop-runner-bin.d.ts +32 -2
- package/dist/loop-runner-bin.js +93 -1
- package/dist/loop-runner-bin.js.map +1 -0
- package/dist/loop-runner-pmPIHFVY.js +59 -0
- package/dist/loop-runner-pmPIHFVY.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +101 -416
- package/dist/mcp/index.js +122 -206
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +231 -1
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/model-policy-CyCUwHed.js.map +1 -1
- package/dist/placement.d.ts +2 -9
- package/dist/placement.js +1 -1
- package/dist/placement.js.map +1 -1
- package/dist/platform.d.ts +194 -2
- package/dist/platform.js +145 -9
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-CER-ZkPp.js → prepare-bXkvPMJA.js} +1213 -710
- package/dist/prepare-bXkvPMJA.js.map +1 -0
- package/dist/{profile-gNUsHNIJ.js → profile-Dpei_Sq0.js} +89 -3
- package/dist/profile-Dpei_Sq0.js.map +1 -0
- package/dist/{profile-materialization-BnoEf1co.d.ts → profile-materialization-B1wm2SPT.d.ts} +3 -5
- package/dist/profiles.d.ts +2 -2
- package/dist/profiles.js +4 -43
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-BGgpy2r9.d.ts} +4 -30
- package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
- package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-CJ6Zz6dz.js} +13 -10
- package/dist/provision-supervisor-CJ6Zz6dz.js.map +1 -0
- package/dist/record-value-B6bwJxLa.js +12 -0
- package/dist/record-value-B6bwJxLa.js.map +1 -0
- package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-C9oL62sW.js} +175 -100
- package/dist/run-cancellation-C9oL62sW.js.map +1 -0
- package/dist/{runtime-BOGpotnH.js → runtime-B2fjL9Oi.js} +2639 -3187
- package/dist/runtime-B2fjL9Oi.js.map +1 -0
- package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
- package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-BzVBFqrz.js} +690 -699
- package/dist/sandbox-profile-compat-BzVBFqrz.js.map +1 -0
- package/dist/search-executor-zMumiak_.js +1916 -0
- package/dist/search-executor-zMumiak_.js.map +1 -0
- package/dist/{server-hZWM-G8w.js → server-_4voDNrl.js} +362 -67
- package/dist/server-_4voDNrl.js.map +1 -0
- package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DpLCXzaL.js} +1680 -3403
- package/dist/structural-rollout-DpLCXzaL.js.map +1 -0
- package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
- package/dist/substrate-CGDFTSRh.js.map +1 -0
- package/dist/{supervise-CvAKVfue.js → supervise-qAwXmPtD.js} +7768 -5360
- package/dist/supervise-qAwXmPtD.js.map +1 -0
- package/dist/{supervisor-Rz8AGpYb.js → supervisor-DHrUJhEZ.js} +26301 -26964
- package/dist/supervisor-DHrUJhEZ.js.map +1 -0
- package/dist/testing.d.ts +227 -2
- package/dist/testing.js +13 -14
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +1 -1
- package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
- package/dist/tool-server-XV4aJwoQ.js.map +1 -0
- package/dist/top-snapshot-CbZE1JsU.js +502 -0
- package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
- package/dist/tui/bin.js +711 -1
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +5 -71
- package/dist/tui/index.js +3 -3
- package/dist/{types-Dl5L4r8Z.d.ts → types-CaOXqRTq.d.ts} +16230 -17376
- package/dist/workspace-store/index.d.ts +2 -27
- package/dist/workspace-store/index.js +2 -2
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BiS4ABah.d.ts} +19 -32
- package/package.json +2 -2
- package/skills/agent-graphs/SKILL.md +10 -3
- package/skills/agent-graphs/references/authoring.md +18 -0
- package/skills/profile-authoring/SKILL.md +3 -3
- package/skills/supervise/SKILL.md +2 -2
- package/dist/activation-BDP6Eivv.js +0 -234
- package/dist/activation-BDP6Eivv.js.map +0 -1
- package/dist/coder-yhVWbdWc.js +0 -40
- package/dist/coder-yhVWbdWc.js.map +0 -1
- package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
- package/dist/delegation-status-CF4D0NZ_.js +0 -358
- package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
- package/dist/durable-file-B_eJr6Mb.js.map +0 -1
- package/dist/graph-C4RFlWAJ.js.map +0 -1
- package/dist/graph-registry-DAI6KNXB.js.map +0 -1
- package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
- package/dist/integrations-DopfCC2a.d.ts +0 -190
- package/dist/integrations-dFi-ALk7.js +0 -132
- package/dist/integrations-dFi-ALk7.js.map +0 -1
- package/dist/kb-gate-C8z2juK8.d.ts +0 -80
- package/dist/kb-gate-DpaSwXVx.js +0 -80
- package/dist/kb-gate-DpaSwXVx.js.map +0 -1
- package/dist/loop-runner-bin-DOuBIJ2O.d.ts +0 -164
- package/dist/loop-runner-bin-Dv5QvYDH.js +0 -246
- package/dist/loop-runner-bin-Dv5QvYDH.js.map +0 -1
- package/dist/memory-server-DXQ8IxGR.js +0 -234
- package/dist/memory-server-DXQ8IxGR.js.map +0 -1
- package/dist/openai-tools-DoQ32vpe.js +0 -44
- package/dist/openai-tools-DoQ32vpe.js.map +0 -1
- package/dist/openai-tools-Oxk4KQrY.d.ts +0 -24
- package/dist/prepare-CER-ZkPp.js.map +0 -1
- package/dist/profile-gNUsHNIJ.js.map +0 -1
- package/dist/protected-model-port-BuRsviSL.js +0 -766
- package/dist/protected-model-port-BuRsviSL.js.map +0 -1
- package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
- package/dist/run-layout-Cu8H7aeh.js.map +0 -1
- package/dist/runtime-BOGpotnH.js.map +0 -1
- package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
- package/dist/search-executor-Cm1WZmL-.js.map +0 -1
- package/dist/server-hZWM-G8w.js.map +0 -1
- package/dist/substrate-B0TYNrXn.js.map +0 -1
- package/dist/supervise-CvAKVfue.js.map +0 -1
- package/dist/supervisor-Rz8AGpYb.js.map +0 -1
- package/dist/tool-server-Dqer2M4_.js.map +0 -1
- package/dist/top-app-BaMw1W2z.js +0 -1212
- package/dist/top-app-BaMw1W2z.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"activation-CVSFxis9.js","names":["canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateDigest"],"sources":["../src/improvement/rollout-policy.ts","../src/intelligence/improvement-surfaces.ts","../src/intelligence/optimization-receipt.ts","../src/intelligence/activation.ts"],"sourcesContent":["/** Serialize and apply Runtime's structural rollout profile coordinate. */\n\nimport type { MutableSurface } from '@tangle-network/agent-eval/contract'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport {\n defaultStructuralRolloutPolicy,\n type StructuralRolloutPolicy,\n} from '../runtime/structural-rollout'\nimport type { ReadonlyAgentProfile } from './profile-types'\n\n/** The profile extensions namespace the policy persists under. */\nexport const ROLLOUT_POLICY_EXTENSION = 'structural-rollout'\n\nconst isBoundedInt = (v: unknown, min: number): v is number =>\n typeof v === 'number' && Number.isInteger(v) && v >= min\n\n/** Parse a serialized policy surface. Returns `undefined` for non-strings,\n * malformed JSON, or values outside the policy invariants. Unknown fields are\n * dropped; supported optional fields are preserved. */\nexport function parseRolloutPolicy(surface: MutableSurface): StructuralRolloutPolicy | undefined {\n if (typeof surface !== 'string' || surface.trim().length === 0) return undefined\n let raw: unknown\n try {\n raw = JSON.parse(surface)\n } catch {\n return undefined\n }\n return normalizeRolloutPolicy(raw)\n}\n\n/** Normalize an untyped policy bag (a parsed surface or a profile extension) into\n * a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any\n * present dial violates the policy invariants (mirrors `resolvePolicy`: integer\n * k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as \"not\n * configured\", never as a fabricated recipe. */\nexport function normalizeRolloutPolicy(raw: unknown): StructuralRolloutPolicy | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const bag = raw as Record<string, unknown>\n const k = bag.k ?? defaultStructuralRolloutPolicy.k\n const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds\n const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen\n if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {\n return undefined\n }\n return {\n k,\n repairRounds,\n testgen,\n ...(typeof bag.diverse === 'boolean' ? { diverse: bag.diverse } : {}),\n }\n}\n\n/** Stable serialization with fixed field order. */\nexport function serializeRolloutPolicy(policy: StructuralRolloutPolicy): string {\n return JSON.stringify({\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n })\n}\n\n/** Read the persisted policy off the profile. `undefined` when the profile does\n * not opt into structural rollout. */\nexport function structuralRolloutPolicyFromProfile(\n profile: ReadonlyAgentProfile,\n): StructuralRolloutPolicy | undefined {\n const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION]\n if (bag === undefined) return undefined\n return normalizeRolloutPolicy(bag)\n}\n\n/** Persist a detached policy under the profile extension without mutating the input. */\nexport function applyRolloutPolicyToProfile(\n profile: ReadonlyAgentProfile,\n policy: StructuralRolloutPolicy,\n): AgentProfile {\n const candidate = structuredClone(profile) as AgentProfile\n const bag: Record<string, unknown> = {\n k: policy.k,\n repairRounds: policy.repairRounds,\n testgen: policy.testgen,\n ...(policy.diverse !== undefined ? { diverse: policy.diverse } : {}),\n }\n return {\n ...candidate,\n extensions: { ...candidate.extensions, [ROLLOUT_POLICY_EXTENSION]: bag },\n }\n}\n","import {\n type AgentCandidateBundle,\n type AgentCandidateExperiment,\n type AgentImprovementActivationIntent,\n type AgentImprovementActivationTarget,\n type AgentImprovementEvaluation,\n type AgentImprovementSurface,\n type AgentProfile,\n type AgentProfileDiff,\n type AgentProfileDiffRemoval,\n type AgentProfileImprovementChange,\n type AgentProfileImprovementExperiment,\n agentProfileDiffSchema,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n changedProfileImprovementSurfaces,\n defineAgentProfileDiff,\n diffAgentProfiles,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n agentCandidateProfileAsAgentProfile,\n applyExactAgentProfileDiff,\n omitUndefinedObjectFields,\n parseExactAgentProfile,\n} from '../candidate-execution/profile'\nimport {\n ROLLOUT_POLICY_EXTENSION,\n structuralRolloutPolicyFromProfile,\n} from '../improvement/rollout-policy'\n\nconst changedSurfaceOrder: readonly AgentImprovementSurface[] = [\n 'prompt',\n 'skills',\n 'tools',\n 'mcp',\n 'hooks',\n 'subagents',\n 'agent-profile',\n 'memory',\n 'code',\n 'knowledge',\n 'rollout-policy',\n]\n\n/** Agent improvement surfaces delivered as exact `AgentProfileDiff` replacements. */\nexport const AGENT_IMPROVEMENT_PROFILE_SURFACES = [\n 'prompt',\n 'skills',\n 'tools',\n 'mcp',\n 'hooks',\n 'subagents',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentImprovementProfileSurface = (typeof AGENT_IMPROVEMENT_PROFILE_SURFACES)[number]\n\n/**\n * Profile changes eligible for the product-owned measured comparison path.\n * The six directly deliverable profile surfaces retain their granular labels;\n * any residual profile axis also adds the complete `agent-profile` surface.\n */\nexport const AGENT_PROFILE_MEASURED_SURFACES = [\n ...AGENT_IMPROVEMENT_PROFILE_SURFACES,\n 'agent-profile',\n] as const satisfies readonly AgentImprovementSurface[]\n\nexport type AgentProfileMeasuredSurface = (typeof AGENT_PROFILE_MEASURED_SURFACES)[number]\n\nexport interface AgentImprovementTargetProfileDiffOptions {\n id: string\n source?: AgentProfileDiff['source']\n metadata?: Record<string, unknown>\n}\n\nexport type AgentImprovementActivationTargetIdentity = Pick<\n AgentImprovementActivationTarget,\n 'surface' | 'identity'\n>\n\nexport function deriveChangedSurfaces(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (baselineBundle.knowledge || candidateBundle.knowledge) {\n assertKnowledgeCandidatePair(baselineBundle, candidateBundle)\n }\n assertCodeCandidatePair(baselineBundle, candidateBundle)\n const baseline = improvementSurfaceValues(baselineBundle)\n const candidate = improvementSurfaceValues(candidateBundle)\n const changed = changedSurfaceOrder.filter(\n (surface) =>\n canonicalCandidateDigest(baseline[surface]) !== canonicalCandidateDigest(candidate[surface]),\n )\n if (changed.length === 0) throw new Error('candidate experiment does not change an agent surface')\n return changed as [AgentImprovementSurface, ...AgentImprovementSurface[]]\n}\n\nexport function assertAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n targets: readonly AgentImprovementActivationTarget[],\n): void {\n if (isProfileImprovementExperiment(experiment)) {\n assertProfileImprovementTargetsShareIdentity(targets)\n }\n const expected = new Set(surfaces)\n const actual = new Set(targets.map((target) => target.surface))\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n if (\n !(isProfileImprovementExperiment(experiment)\n ? sameAgentImprovementSurfaceSet(surfaces, activationExperimentChangedSurfaces(experiment))\n : sameOrderedSurfaces(surfaces, activationExperimentChangedSurfaces(experiment))) ||\n targets.some((target) => !target.identity.trim()) ||\n targets.some(\n (target) =>\n target.expectedBaseDigest !== activationTargetDigest(experiment, sourceArm, target.surface),\n ) ||\n targets.length !== surfaces.length ||\n expected.size !== actual.size ||\n [...expected].some((surface) => !actual.has(surface))\n ) {\n throw new Error('agent improvement activation targets must cover exactly the changed surfaces')\n }\n}\n\n/** One opaque profile-state transition can change only one complete profile record. */\nexport function assertProfileImprovementTargetsShareIdentity(\n targets: readonly Pick<AgentImprovementActivationTarget, 'identity'>[],\n): void {\n if (new Set(targets.map((target) => target.identity)).size !== 1) {\n throw new Error('profile improvement activation targets must name one profile identity')\n }\n}\n\n/** Bind caller-owned target identities to the exact source state Runtime measured. */\nexport function buildAgentImprovementActivationTargets(\n surfaces: readonly AgentImprovementSurface[],\n experiment: AgentImprovementEvaluation['experiment'],\n intent: AgentImprovementActivationIntent,\n identities: readonly AgentImprovementActivationTargetIdentity[],\n): [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]] {\n const sourceArm = intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targets = identities.map((target) => ({\n ...target,\n expectedBaseDigest: activationTargetDigest(experiment, sourceArm, target.surface),\n }))\n assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets)\n return targets as [AgentImprovementActivationTarget, ...AgentImprovementActivationTarget[]]\n}\n\n/** Exact host-owned profile state for every changed profile surface. */\nexport function agentProfileImprovementStateDigest(\n experiment: AgentProfileImprovementExperiment,\n arm: 'baseline' | 'candidate',\n): Sha256Digest {\n return experiment[arm].stateDigest\n}\n\n/** Map Interface's current profile-improvement contract to Runtime-deliverable surfaces. */\nexport function profileImprovementChangedSurfaces(\n change: AgentProfileImprovementChange,\n): [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]] {\n const surfaces = changedProfileImprovementSurfaces(change)\n if (\n surfaces.length === 0 ||\n !surfaces.every((surface): surface is AgentProfileMeasuredSurface =>\n isAgentProfileMeasuredSurface(surface),\n )\n ) {\n throw new Error('profile improvement experiment does not change a supported surface')\n }\n return surfaces as [AgentProfileMeasuredSurface, ...AgentProfileMeasuredSurface[]]\n}\n\nexport function agentImprovementTargetDigest(\n experiment: AgentCandidateExperiment,\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (surface === 'knowledge') {\n const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate)\n return arm === 'baseline' ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash\n }\n if (surface === 'code') assertCodeCandidatePair(experiment.baseline, experiment.candidate)\n return canonicalCandidateDigest(improvementSurfaceValues(experiment[arm])[surface])\n}\n\nexport function agentImprovementTargetInput(\n bundle: AgentCandidateBundle,\n surface: AgentImprovementSurface,\n): unknown {\n return improvementSurfaceValues(bundle)[surface]\n}\n\nfunction activationTargetDigest(\n experiment: AgentImprovementEvaluation['experiment'],\n arm: 'baseline' | 'candidate',\n surface: AgentImprovementSurface,\n): Sha256Digest {\n if (isProfileImprovementExperiment(experiment)) {\n if (!activationExperimentChangedSurfaces(experiment).includes(surface)) {\n throw new Error('profile improvement activation targets an unchanged surface')\n }\n return agentProfileImprovementStateDigest(experiment, arm)\n }\n return agentImprovementTargetDigest(experiment, arm, surface)\n}\n\nfunction activationExperimentChangedSurfaces(\n experiment: AgentImprovementEvaluation['experiment'],\n): [AgentImprovementSurface, ...AgentImprovementSurface[]] {\n if (!isProfileImprovementExperiment(experiment)) {\n return deriveChangedSurfaces(experiment.baseline, experiment.candidate)\n }\n return profileImprovementChangedSurfaces(experiment.change)\n}\n\nfunction isProfileImprovementExperiment(\n experiment: AgentImprovementEvaluation['experiment'],\n): experiment is AgentProfileImprovementExperiment {\n return experiment.kind === 'agent-profile-improvement-experiment'\n}\n\nfunction sameOrderedSurfaces(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface, index) => surface === right[index])\n}\n\n/** Profile-change surface order is presentation only; its measured contract is set-based. */\nexport function sameAgentImprovementSurfaceSet(\n left: readonly AgentImprovementSurface[],\n right: readonly AgentImprovementSurface[],\n): boolean {\n return left.length === right.length && left.every((surface) => right.includes(surface))\n}\n\n/** Return whether a measured surface can be delivered through an agent profile. */\nexport function isAgentImprovementProfileSurface(\n surface: AgentImprovementSurface,\n): surface is AgentImprovementProfileSurface {\n return (AGENT_IMPROVEMENT_PROFILE_SURFACES as readonly string[]).includes(surface)\n}\n\n/** Return whether a surface is eligible for shared profile measurement. */\nexport function isAgentProfileMeasuredSurface(\n surface: string,\n): surface is AgentProfileMeasuredSurface {\n return (AGENT_PROFILE_MEASURED_SURFACES as readonly string[]).includes(surface)\n}\n\n/**\n * Return the canonical current-state input for one profile-deliverable improvement target.\n * Missing slots become `null`; tools and subagents include both their direct and resource slots.\n * Unrelated profile fields are excluded. The result matches `agentImprovementTargetInput` for the\n * same profile inside a candidate bundle.\n */\nexport function agentImprovementProfileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n const parsed = parseExactAgentProfile(\n omitUndefinedObjectFields(profile, 'agent improvement profile'),\n 'agent improvement profile',\n )\n return immutableCandidateValue(profileSurfaceInput(parsed, surface))\n}\n\nfunction profileSurfaceInput(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): unknown {\n switch (surface) {\n case 'prompt':\n return { prompt: profile.prompt ?? null }\n case 'skills':\n return profile.resources?.skills ?? null\n case 'tools':\n return {\n tools: profile.tools ?? null,\n resources: profile.resources?.tools ?? null,\n }\n case 'mcp':\n return profile.mcp ?? null\n case 'hooks':\n return profile.hooks ?? null\n case 'subagents':\n return {\n subagents: profile.subagents ?? null,\n resources: profile.resources?.agents ?? null,\n }\n }\n}\n\n/** Return the `Sha256Digest` of one profile surface using Runtime's canonical candidate digest. */\nexport function agentImprovementProfileSurfaceDigest(\n profile: AgentProfile,\n surface: AgentImprovementProfileSurface,\n): Sha256Digest {\n return canonicalCandidateDigest(agentImprovementProfileSurfaceInput(profile, surface))\n}\n\n/**\n * Replace one measured profile surface exactly, including array-valued resources.\n * Apply the returned diffs in order: a diff applies its set before its removal,\n * so exact replacement requires a reset record followed by a set record.\n */\nexport function agentImprovementTargetProfileDiffs(\n target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n },\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const { remove, set } = improvementSurfaceReplacement(target)\n const common = {\n kind: 'agent-profile-diff' as const,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: target.surface,\n },\n }\n const reset = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:reset`,\n title: `Replace active ${target.surface}`,\n remove,\n }),\n ) as AgentProfileDiff\n if (!set) return [reset]\n const replacement = agentProfileDiffSchema.parse(\n defineAgentProfileDiff({\n ...common,\n id: `${options.id}:${target.surface}:set`,\n title: `Activate measured ${target.surface}`,\n set,\n }),\n ) as AgentProfileDiff\n return [reset, replacement]\n}\n\n/**\n * Derive the ordered profile patch that changes one executable profile into\n * another, then prove the patch preserves the complete candidate state.\n */\nexport function agentImprovementProfileDiffs(\n baselineInput: AgentProfile,\n candidateInput: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const baseline = parseExactAgentProfile(\n omitUndefinedObjectFields(baselineInput, 'profile improvement baseline'),\n 'profile improvement baseline',\n )\n const candidate = parseExactAgentProfile(\n omitUndefinedObjectFields(candidateInput, 'profile improvement candidate'),\n 'profile improvement candidate',\n )\n if (canonicalAgentProfileDigest(baseline) === canonicalAgentProfileDigest(candidate)) {\n throw new Error('profile improvement candidate does not change the profile')\n }\n const completeChanges = completeAgentProfileReplacementDiffs(baseline, candidate, options)\n const applied = completeChanges.reduce(\n (profile, change) =>\n applyExactAgentProfileDiff(profile, change, 'complete profile improvement candidate change'),\n baseline,\n )\n if (canonicalAgentProfileDigest(applied) !== canonicalAgentProfileDigest(candidate)) {\n throw new Error('complete profile improvement change did not reproduce the candidate')\n }\n return completeChanges\n}\n\nfunction completeAgentProfileReplacementDiffs(\n baseline: AgentProfile,\n candidate: AgentProfile,\n options: AgentImprovementTargetProfileDiffOptions,\n): [AgentProfileDiff, ...AgentProfileDiff[]] {\n const [first, ...rest] = diffAgentProfiles(baseline, candidate).map((change) => {\n const reset = change.remove !== undefined\n return agentProfileDiffSchema.parse({\n ...change,\n ...(options.source ? { source: options.source } : {}),\n metadata: {\n ...(options.metadata ?? {}),\n surface: 'agent-profile',\n },\n id: `${options.id}:agent-profile:${reset ? 'reset' : 'set'}`,\n title: reset ? 'Reset changed agent profile fields' : 'Set changed agent profile fields',\n }) as AgentProfileDiff\n })\n if (!first) throw new Error('complete profile differ found no changed fields')\n return [first, ...rest]\n}\n\nfunction improvementSurfaceReplacement(target: {\n surface: AgentImprovementProfileSurface\n desiredInput: unknown\n}): { remove: AgentProfileDiffRemoval; set?: AgentProfile } {\n const value = target.desiredInput\n switch (target.surface) {\n case 'prompt': {\n const prompt = exactObject(value, ['prompt'], 'prompt activation input').prompt\n assertDefined(prompt, 'prompt activation input.prompt')\n return {\n remove: { prompt: true },\n ...(prompt === null ? {} : { set: parseProfileSet({ prompt }) }),\n }\n }\n case 'skills':\n assertDefined(value, 'skills activation input')\n return {\n remove: { resources: { skills: true } },\n ...(value === null ? {} : { set: parseProfileSet({ resources: { skills: value } }) }),\n }\n case 'tools': {\n const parsed = exactObject(value, ['tools', 'resources'], 'tools activation input')\n assertDefined(parsed.tools, 'tools activation input.tools')\n assertDefined(parsed.resources, 'tools activation input.resources')\n const set = {\n ...(parsed.tools === null ? {} : { tools: parsed.tools }),\n ...(parsed.resources === null ? {} : { resources: { tools: parsed.resources } }),\n }\n return {\n remove: { tools: true, resources: { tools: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n case 'mcp':\n assertDefined(value, 'mcp activation input')\n return {\n remove: { mcp: true },\n ...(value === null ? {} : { set: parseProfileSet({ mcp: value }) }),\n }\n case 'hooks':\n assertDefined(value, 'hooks activation input')\n return {\n remove: { hooks: true },\n ...(value === null ? {} : { set: parseProfileSet({ hooks: value }) }),\n }\n case 'subagents': {\n const parsed = exactObject(value, ['subagents', 'resources'], 'subagents activation input')\n assertDefined(parsed.subagents, 'subagents activation input.subagents')\n assertDefined(parsed.resources, 'subagents activation input.resources')\n const set = {\n ...(parsed.subagents === null ? {} : { subagents: parsed.subagents }),\n ...(parsed.resources === null ? {} : { resources: { agents: parsed.resources } }),\n }\n return {\n remove: { subagents: true, resources: { agents: true } },\n ...(Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }),\n }\n }\n }\n}\n\nfunction assertDefined(value: unknown, label: string): void {\n if (value === undefined) throw new Error(`${label} must not be undefined`)\n}\n\nfunction exactObject(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const record = value as Record<string, unknown>\n const actual = Object.keys(record).sort()\n const expected = [...keys].sort()\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {\n throw new Error(`${label} must contain exactly: ${expected.join(', ')}`)\n }\n return record\n}\n\nfunction parseProfileSet(value: unknown): AgentProfile {\n return agentProfileSchema.parse(value) as AgentProfile\n}\n\nfunction assertKnowledgeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): NonNullable<AgentCandidateBundle['knowledge']> {\n const baseline = baselineBundle.knowledge\n const candidate = candidateBundle.knowledge\n if (!baseline && !candidate) {\n throw new Error('knowledge candidate pair is not present')\n }\n if (\n !baseline ||\n !candidate ||\n canonicalCandidateDigest({ candidate: baseline.candidate, evaluation: baseline.evaluation }) !==\n canonicalCandidateDigest({ candidate: candidate.candidate, evaluation: candidate.evaluation })\n ) {\n throw new Error(\n 'knowledge experiment arms must share one measured candidate and evaluation identity',\n )\n }\n return candidate\n}\n\nfunction assertCodeCandidatePair(\n baselineBundle: AgentCandidateBundle,\n candidateBundle: AgentCandidateBundle,\n): void {\n const baseline = baselineBundle.code\n const candidate = candidateBundle.code\n if (\n canonicalCandidateDigest(baseline) === canonicalCandidateDigest(candidate) ||\n candidate.kind !== 'git-patch'\n ) {\n return\n }\n const baselineTree =\n baseline.kind === 'no-op'\n ? baseline.baseTree\n : baseline.kind === 'git-patch'\n ? baseline.candidateTree\n : undefined\n const baselineRepository = baseline.kind === 'disabled' ? undefined : baseline.repository\n if (\n baselineTree !== candidate.baseTree ||\n !baselineRepository ||\n canonicalCandidateDigest(baselineRepository) !== canonicalCandidateDigest(candidate.repository)\n ) {\n throw new Error(\n 'code candidate must be based on the exact repository tree measured by the baseline arm',\n )\n }\n}\n\nfunction improvementSurfaceValues(\n bundle: AgentCandidateBundle,\n): Record<AgentImprovementSurface, unknown> {\n const profile = agentCandidateProfileAsAgentProfile(bundle.profile)\n return {\n prompt: agentImprovementProfileSurfaceInput(profile, 'prompt'),\n skills: agentImprovementProfileSurfaceInput(profile, 'skills'),\n tools: agentImprovementProfileSurfaceInput(profile, 'tools'),\n mcp: agentImprovementProfileSurfaceInput(profile, 'mcp'),\n hooks: agentImprovementProfileSurfaceInput(profile, 'hooks'),\n subagents: agentImprovementProfileSurfaceInput(profile, 'subagents'),\n 'agent-profile': { profile: opaqueProfileSlice(profile), execution: bundle.execution },\n memory: {\n instructions: profile.resources?.instructions ?? null,\n executionPolicy: bundle.memory,\n },\n code: bundle.code,\n knowledge: bundle.knowledge ?? null,\n 'rollout-policy': structuralRolloutPolicyFromProfile(profile) ?? null,\n }\n}\n\nfunction opaqueProfileSlice(profile: AgentProfile): unknown {\n const {\n prompt: _prompt,\n tools: _tools,\n mcp: _mcp,\n hooks: _hooks,\n subagents: _subagents,\n extensions,\n resources,\n ...opaqueProfile\n } = profile\n // The rollout policy is its own surface, so it must not also ride in this slice: one edit to it\n // would otherwise report two changed surfaces.\n const { [ROLLOUT_POLICY_EXTENSION]: _rolloutPolicy, ...opaqueExtensions } = extensions ?? {}\n const {\n instructions: _instructions,\n skills: _skills,\n tools: _resourceTools,\n agents: _agents,\n ...opaqueResources\n } = resources ?? {}\n return {\n ...opaqueProfile,\n ...(Object.keys(opaqueExtensions).length > 0 ? { extensions: opaqueExtensions } : {}),\n ...(Object.keys(opaqueResources).length > 0 ? { resources: opaqueResources } : {}),\n }\n}\n","import type {\n CampaignScenarioIdentity,\n OptimizationMethodComparison,\n OptimizationPackageSource,\n OptimizationTokenUsage,\n} from '@tangle-network/agent-eval/campaign'\nimport { campaignSplitDigestFromIdentities } from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentCandidateJsonValue,\n type AgentImprovementMeasuredComparison,\n type AgentProfile,\n agentProfileModelHintsSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport type { ImproveMethodResult, ImproveScenarioPartitions } from '../improvement/improve'\n\ntype OptimizationProvenance = NonNullable<OptimizationMethodComparison['best']['provenance']>\n\nexport interface OptimizationActivationReceipt {\n kind: 'optimization-activation-receipt'\n method: string\n source: OptimizationPackageSource\n bridge?: OptimizationPackageSource\n modules?: OptimizationProvenance['modules']\n python?: OptimizationProvenance['python']\n models?: {\n candidate?: NonNullable<AgentProfile['model']>\n optimizer?: string\n }\n usage: {\n optimizerEvaluations: number\n optimizerTokens?: OptimizationTokenUsage\n }\n cost: {\n optimization: OptimizationReceiptCost\n finalTest: OptimizationReceiptCost\n total: OptimizationReceiptCost\n }\n invocation: {\n runtimeInvocationId: string\n optimizerRunId: string\n compatibleOptimizerRunId?: string\n resumed: boolean\n artifactDir: string\n }\n developmentDataDigest: Sha256Digest\n finalTestDataDigest: Sha256Digest\n scenarioPartitions: ImproveScenarioPartitions\n digest: Sha256Digest\n}\n\nexport interface OptimizationReceiptCost {\n totalUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport const optimizationReceiptMetadataKey = 'optimizationReceipt'\n\n/** Build a detached receipt only for methods backed by an identified external optimizer. */\nexport function createOptimizationActivationReceipt(\n improvement: ImproveMethodResult,\n): OptimizationActivationReceipt | undefined {\n const provenance = improvement.provenance\n if (!provenance) return undefined\n const finalTestDataDigest = improvement.lineage.finalTestSplitDigest\n if (!finalTestDataDigest) {\n throw new Error('method improvement does not retain its final-test split digest')\n }\n const optimizerModel = provenance.optimizerModel\n const candidateModel = improvement.candidate.profile.model\n\n return canonicalCandidateDocument<OptimizationActivationReceipt>({\n kind: 'optimization-activation-receipt',\n method: improvement.method,\n source: provenance.source,\n ...(provenance.bridge ? { bridge: provenance.bridge } : {}),\n ...(provenance.modules ? { modules: provenance.modules } : {}),\n ...(provenance.python ? { python: provenance.python } : {}),\n ...(candidateModel || optimizerModel\n ? {\n models: {\n ...(candidateModel ? { candidate: candidateModel } : {}),\n ...(optimizerModel ? { optimizer: optimizerModel } : {}),\n },\n }\n : {}),\n usage: {\n optimizerEvaluations: provenance.evaluationCount,\n ...(provenance.tokenUsage ? { optimizerTokens: provenance.tokenUsage } : {}),\n },\n cost: {\n optimization: receiptCost(improvement.raw.optimizationCost),\n finalTest: receiptCost(improvement.raw.testCost),\n total: receiptCost(improvement.raw.totalCost),\n },\n invocation: {\n runtimeInvocationId: improvement.lineage.invocationId,\n optimizerRunId: provenance.runId,\n ...(provenance.compatibleRunId\n ? { compatibleOptimizerRunId: provenance.compatibleRunId }\n : {}),\n resumed: provenance.resumed,\n artifactDir: provenance.artifactDir,\n },\n developmentDataDigest: improvement.lineage.developmentSplitDigest,\n finalTestDataDigest,\n scenarioPartitions: improvement.lineage.scenarioPartitions,\n }).value\n}\n\n/** Add Runtime-owned optimizer evidence without aliasing caller metadata. */\nexport function attachOptimizationActivationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n receipt: OptimizationActivationReceipt,\n): NonNullable<AgentImprovementMeasuredComparison['metadata']> {\n assertNoCallerOptimizationReceipt(metadata)\n return immutableCandidateValue({\n ...(metadata ?? {}),\n [optimizationReceiptMetadataKey]: receipt as unknown as AgentCandidateJsonValue,\n })\n}\n\nexport function assertNoCallerOptimizationReceipt(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): void {\n if (metadata && Object.hasOwn(metadata, optimizationReceiptMetadataKey)) {\n throw new Error(`candidate metadata reserves '${optimizationReceiptMetadataKey}' for Runtime`)\n }\n}\n\n/** Read and verify the optimizer evidence carried by a measured proposal. */\nexport function optimizationActivationReceiptFromMetadata(\n metadata: AgentImprovementMeasuredComparison['metadata'],\n): OptimizationActivationReceipt | undefined {\n const value = metadata?.[optimizationReceiptMetadataKey]\n if (value === undefined) return undefined\n return immutableCandidateValue(parseOptimizationActivationReceipt(value))\n}\n\nfunction parseOptimizationActivationReceipt(\n value: AgentCandidateJsonValue,\n): OptimizationActivationReceipt {\n if (!isRecord(value) || value.kind !== 'optimization-activation-receipt') {\n throw new Error('optimization receipt must be an optimization-activation-receipt')\n }\n if (\n !isNonEmptyString(value.method) ||\n !isPackageSource(value.source) ||\n (value.bridge !== undefined && !isPackageSource(value.bridge)) ||\n !isModules(value.modules) ||\n !isPythonRuntime(value.python) ||\n !isModels(value.models) ||\n !isUsage(value.usage) ||\n !isCost(value.cost) ||\n !isInvocation(value.invocation) ||\n !isSha256Digest(value.developmentDataDigest) ||\n !isSha256Digest(value.finalTestDataDigest) ||\n !isScenarioPartitions(value.scenarioPartitions) ||\n !isSha256Digest(value.digest)\n ) {\n throw new Error('optimization receipt contains invalid evidence')\n }\n const receipt = value as unknown as OptimizationActivationReceipt\n if (!hasMatchingScenarioPartitionDigests(receipt)) {\n throw new Error('optimization receipt task identities do not match its split digests')\n }\n if (canonicalCandidateDigest(omitTopLevelDigest(receipt)) !== receipt.digest) {\n throw new Error('optimization receipt digest does not match its evidence')\n }\n return receipt\n}\n\nfunction isScenarioPartitions(value: unknown): value is ImproveScenarioPartitions {\n if (!isRecord(value)) return false\n return (\n isScenarioIdentityList(value.train) &&\n isScenarioIdentityList(value.selection) &&\n isScenarioIdentityList(value.finalTest) &&\n isPositiveSafeInteger(value.optimizationReps) &&\n isPositiveSafeInteger(value.finalTestReps)\n )\n}\n\nfunction isScenarioIdentityList(value: unknown): value is CampaignScenarioIdentity[] {\n return (\n Array.isArray(value) &&\n value.every(\n (scenario) =>\n isRecord(scenario) &&\n isNonEmptyString(scenario.id) &&\n isNonEmptyString(scenario.kind) &&\n isSha256Digest(scenario.scenarioDigest),\n )\n )\n}\n\nfunction hasMatchingScenarioPartitionDigests(receipt: OptimizationActivationReceipt): boolean {\n try {\n const { scenarioPartitions } = receipt\n const developmentDataDigest = canonicalCandidateDigest({\n train: campaignSplitDigestFromIdentities(\n scenarioPartitions.train,\n scenarioPartitions.optimizationReps,\n ),\n selection: campaignSplitDigestFromIdentities(\n scenarioPartitions.selection,\n scenarioPartitions.optimizationReps,\n ),\n })\n const finalTestDataDigest = campaignSplitDigestFromIdentities(\n scenarioPartitions.finalTest,\n scenarioPartitions.finalTestReps,\n )\n return (\n receipt.developmentDataDigest === developmentDataDigest &&\n receipt.finalTestDataDigest === finalTestDataDigest\n )\n } catch {\n return false\n }\n}\n\nfunction isPackageSource(value: unknown): value is OptimizationPackageSource {\n if (\n !isRecord(value) ||\n value.kind !== 'package' ||\n (value.evidence !== 'observed' && value.evidence !== 'declared') ||\n !isNonEmptyString(value.package) ||\n !isNonEmptyString(value.version)\n ) {\n return false\n }\n return (\n isOptionalNonEmptyString(value.sourceUrl) &&\n isOptionalNonEmptyString(value.revision) &&\n (value.sourceSha256 === undefined ||\n (typeof value.sourceSha256 === 'string' && /^[0-9a-f]{64}$/.test(value.sourceSha256)))\n )\n}\n\nfunction isModules(value: unknown): boolean {\n return (\n value === undefined ||\n (Array.isArray(value) &&\n value.every(\n (module) =>\n isRecord(module) &&\n isNonEmptyString(module.module) &&\n typeof module.sourceSha256 === 'string' &&\n /^[0-9a-f]{64}$/.test(module.sourceSha256),\n ))\n )\n}\n\nfunction isPythonRuntime(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) && isNonEmptyString(value.implementation) && isNonEmptyString(value.version))\n )\n}\n\nfunction isModels(value: unknown): boolean {\n return (\n value === undefined ||\n (isRecord(value) &&\n (value.candidate === undefined ||\n agentProfileModelHintsSchema.safeParse(value.candidate).success) &&\n isOptionalNonEmptyString(value.optimizer) &&\n (value.candidate !== undefined || value.optimizer !== undefined))\n )\n}\n\nfunction isUsage(value: unknown): boolean {\n if (!isRecord(value) || !isNonNegativeInteger(value.optimizerEvaluations)) return false\n if (value.optimizerTokens === undefined) return true\n const tokens = value.optimizerTokens\n if (!isRecord(tokens)) return false\n const inputTokens = tokens.inputTokens\n const outputTokens = tokens.outputTokens\n const totalTokens = tokens.totalTokens\n const calls = tokens.calls\n if (\n !isNonNegativeInteger(inputTokens) ||\n !isNonNegativeInteger(outputTokens) ||\n !isNonNegativeInteger(totalTokens) ||\n !isNonNegativeInteger(calls)\n ) {\n return false\n }\n if (\n !isOptionalNonNegativeInteger(tokens.cachedInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.cacheWriteInputTokens) ||\n !isOptionalNonNegativeInteger(tokens.reasoningTokens)\n ) {\n return false\n }\n const cachedInputTokens =\n typeof tokens.cachedInputTokens === 'number' ? tokens.cachedInputTokens : 0\n const cacheWriteInputTokens =\n typeof tokens.cacheWriteInputTokens === 'number' ? tokens.cacheWriteInputTokens : 0\n const reasoningTokens = typeof tokens.reasoningTokens === 'number' ? tokens.reasoningTokens : 0\n return (\n totalTokens === inputTokens + outputTokens &&\n cachedInputTokens + cacheWriteInputTokens <= inputTokens &&\n reasoningTokens <= outputTokens &&\n (totalTokens === 0 || calls > 0)\n )\n}\n\nfunction isCost(value: unknown): boolean {\n if (\n !isRecord(value) ||\n !isCostPart(value.optimization) ||\n !isCostPart(value.finalTest) ||\n !isCostPart(value.total)\n ) {\n return false\n }\n const optimization = value.optimization as unknown as OptimizationReceiptCost\n const finalTest = value.finalTest as unknown as OptimizationReceiptCost\n const total = value.total as unknown as OptimizationReceiptCost\n return (\n approximatelyEqual(total.totalUsd, optimization.totalUsd + finalTest.totalUsd) &&\n total.accountingComplete === (optimization.accountingComplete && finalTest.accountingComplete)\n )\n}\n\nfunction isCostPart(value: unknown): boolean {\n return (\n isRecord(value) &&\n typeof value.totalUsd === 'number' &&\n Number.isFinite(value.totalUsd) &&\n value.totalUsd >= 0 &&\n typeof value.accountingComplete === 'boolean' &&\n Array.isArray(value.incompleteReasons) &&\n value.incompleteReasons.every((reason) => typeof reason === 'string')\n )\n}\n\nfunction receiptCost(value: {\n totalCostUsd: number\n accountingComplete: boolean\n incompleteReasons: string[]\n}): OptimizationReceiptCost {\n return {\n totalUsd: value.totalCostUsd,\n accountingComplete: value.accountingComplete,\n incompleteReasons: [...value.incompleteReasons],\n }\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8\n return Math.abs(left - right) <= tolerance\n}\n\nfunction isInvocation(value: unknown): boolean {\n return (\n isRecord(value) &&\n isNonEmptyString(value.runtimeInvocationId) &&\n isNonEmptyString(value.optimizerRunId) &&\n isOptionalNonEmptyString(value.compatibleOptimizerRunId) &&\n typeof value.resumed === 'boolean' &&\n isNonEmptyString(value.artifactDir)\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, AgentCandidateJsonValue> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction isOptionalNonEmptyString(value: unknown): boolean {\n return value === undefined || isNonEmptyString(value)\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\nfunction isOptionalNonNegativeInteger(value: unknown): boolean {\n return value === undefined || isNonNegativeInteger(value)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value)\n}\n","import { assertProposalFindings, type ProposalFinding } from '@tangle-network/agent-eval/analyst'\nimport {\n verifyAgentProfileImprovementExperimentComparison,\n verifyCandidateExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementEvaluation,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExecutionRef,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentImprovementProposalSchema,\n agentImprovementReviewSchema,\n agentProfileImprovementExecutionRefSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n type AgentImprovementActivationTargetIdentity,\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n assertAgentImprovementActivationTargets,\n buildAgentImprovementActivationTargets,\n deriveChangedSurfaces,\n profileImprovementChangedSurfaces,\n sameAgentImprovementSurfaceSet,\n} from './improvement-surfaces'\nimport { optimizationActivationReceiptFromMetadata } from './optimization-receipt'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n\nexport interface CreateAgentImprovementProposalOptions {\n runId: string\n findings: readonly ProposalFinding[]\n evaluation: AgentImprovementEvaluation\n now?: () => Date\n}\n\nexport interface ReviewAgentImprovementInput {\n decision: AgentImprovementReviewDecision\n reviewedBy: string\n reason: string\n feedback?: string\n now?: () => Date\n}\n\nexport interface CreateAgentImprovementActivationOptions {\n intent: AgentImprovementActivationIntent\n /** Runtime derives each exact source digest; callers identify only the records to change. */\n targets: [AgentImprovementActivationTargetIdentity, ...AgentImprovementActivationTargetIdentity[]]\n fundingOwner: string\n authorizedBy: string\n expiresAt: string\n /** Required only when an activation targets the complete `agent-profile` surface. */\n executionRef?: AgentProfileImprovementExecutionRef\n now?: () => Date\n}\n\ntype ProposalFindingImprovementProposal = Omit<AgentImprovementProposal, 'findings'> & {\n findings: ProposalFinding[]\n}\n\n/** Create the reviewable record only from a complete, recomputable experiment result. */\nexport function createAgentImprovementProposal(\n options: CreateAgentImprovementProposalOptions,\n): AgentImprovementProposal {\n const findings = assertProposalFindings(\n options.findings,\n 'createAgentImprovementProposal findings',\n )\n const { evaluation, changedSurfaces } = validateShippableAgentImprovementEvaluation(\n options.evaluation,\n options.runId,\n 'agent improvement proposal',\n )\n return agentImprovementProposalSchema.parse(\n canonicalCandidateDocument<ProposalFindingImprovementProposal>({\n kind: 'agent-improvement-proposal',\n runId: options.runId,\n changedSurfaces,\n proposedAt: (options.now ?? (() => new Date()))().toISOString(),\n findings: [...findings],\n evaluation,\n }).value,\n )\n}\n\n/** Persist a human or tenant-policy decision bound to one exact proposal. */\nexport function reviewAgentImprovementProposal(\n inputProposal: AgentImprovementProposal,\n input: ReviewAgentImprovementInput,\n): AgentImprovementReview {\n const proposal = verifyAgentImprovementProposal(inputProposal)\n if (!input.reviewedBy.trim()) throw new Error('candidate review requires reviewedBy')\n if (!input.reason.trim()) throw new Error('candidate review requires a reason')\n if (input.decision === 'approve' && proposal.evaluation.decision.outcome !== 'ship') {\n throw new Error('candidate cannot be approved without a passing experiment')\n }\n const reviewedAt = (input.now ?? (() => new Date()))().toISOString()\n if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) {\n throw new Error('candidate review cannot predate its proposal')\n }\n return agentImprovementReviewSchema.parse(\n canonicalCandidateDocument<AgentImprovementReview>({\n kind: 'agent-improvement-review',\n proposalDigest: proposal.digest,\n decision: input.decision,\n reviewedBy: input.reviewedBy,\n reviewedAt,\n reason: input.reason,\n ...(input.feedback === undefined ? {} : { feedback: input.feedback }),\n }).value,\n )\n}\n\n/** Authorize product-owned writes only after the exact candidate was measured and approved. */\nexport function createAgentImprovementActivation(\n inputProposal: AgentImprovementProposal,\n inputReview: AgentImprovementReview,\n options: CreateAgentImprovementActivationOptions,\n): AgentImprovementActivation {\n const proposal = verifyAgentImprovementProposal(inputProposal)\n const review = verifyAgentImprovementReview(inputReview)\n if (review.decision !== 'approve' || review.proposalDigest !== proposal.digest) {\n throw new Error('candidate activation requires an approval for the exact proposal')\n }\n if (!options.fundingOwner.trim() || !options.authorizedBy.trim()) {\n throw new Error('candidate activation authority must be non-empty')\n }\n const experiment = proposal.evaluation.experiment\n const authorizedAt = (options.now ?? (() => new Date()))().toISOString()\n if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) {\n throw new Error('candidate activation cannot predate its approval')\n }\n const targets = buildAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n options.intent,\n options.targets,\n )\n const executionRef = profileActivationExecutionRef(experiment, targets, options.executionRef)\n return agentImprovementActivationSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivation>({\n kind: 'agent-improvement-activation',\n proposalDigest: proposal.digest,\n reviewDigest: review.digest,\n experimentDigest: experiment.digest,\n candidateDigest: measuredCandidateDigest(proposal),\n ...(executionRef ? { executionRef } : {}),\n intent: options.intent,\n targets,\n fundingOwner: options.fundingOwner,\n authorizedBy: options.authorizedBy,\n authorizedAt,\n expiresAt: options.expiresAt,\n }).value,\n )\n}\n\n/** Validate a proposal and recompute every binding to its measured experiment. */\nexport function verifyAgentImprovementProposal(input: unknown): AgentImprovementProposal {\n const proposal = verifyCanonicalCandidateDocument(\n agentImprovementProposalSchema.parse(input),\n 'agent improvement proposal',\n )\n const { changedSurfaces } = validateShippableAgentImprovementEvaluation(\n proposal.evaluation,\n proposal.runId,\n 'agent improvement proposal',\n )\n const changedSurfacesMatch =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? sameAgentImprovementSurfaceSet(proposal.changedSurfaces, changedSurfaces)\n : sameOrderedValues(proposal.changedSurfaces, changedSurfaces)\n if (!changedSurfacesMatch) {\n throw new Error('proposal changed surfaces do not match its exact experiment')\n }\n assertProposalFindings(proposal.findings, 'agent improvement proposal findings')\n return proposal\n}\n\n/** Return a sealed bundle experiment; ordinary profile changes need a product-owned executor. */\nfunction requireSealedCandidateExperiment(\n proposal: AgentImprovementProposal,\n): AgentCandidateExperiment {\n if (proposal.evaluation.kind !== 'agent-improvement-measured-comparison') {\n throw new Error(\n 'agent profile improvement activation requires a product profile-diff executor, not a sealed candidate bundle',\n )\n }\n return proposal.evaluation.experiment\n}\n\nfunction measuredCandidateDigest(proposal: AgentImprovementProposal): Sha256Digest {\n return proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? proposal.evaluation.experiment.candidate.stateDigest\n : proposal.evaluation.experiment.candidate.digest\n}\n\nfunction profileActivationExecutionRef(\n experiment: AgentImprovementEvaluation['experiment'],\n targets: AgentImprovementActivation['targets'],\n executionRef: AgentProfileImprovementExecutionRef | undefined,\n): AgentProfileImprovementExecutionRef | undefined {\n const targetsAgentProfile = targets.some((target) => target.surface === 'agent-profile')\n if (!targetsAgentProfile) {\n if (executionRef !== undefined) {\n throw new Error('profile activation executionRef is valid only for agent-profile targets')\n }\n return undefined\n }\n if (experiment.kind !== 'agent-profile-improvement-experiment') {\n throw new Error('agent-profile activation requires a measured profile experiment')\n }\n if (executionRef === undefined) {\n throw new Error('profile improvement activation requires the measured executor')\n }\n const parsed = agentProfileImprovementExecutionRefSchema.parse(executionRef)\n if (canonicalCandidateDigest(parsed) !== canonicalCandidateDigest(experiment.executionRef)) {\n throw new Error('profile improvement activation executor does not match the measurement')\n }\n return parsed\n}\n\nfunction validateShippableAgentImprovementEvaluation(\n input: unknown,\n runId: string,\n subject: string,\n): {\n evaluation: AgentImprovementEvaluation\n changedSurfaces: AgentImprovementProposal['changedSurfaces']\n} {\n const evaluation = verifyAgentImprovementEvaluation(input)\n if (evaluation.decision.outcome !== 'ship') {\n throw new Error(`${subject} requires a passing experiment`)\n }\n if (runId !== evaluation.provenance.runId) {\n throw new Error('proposal runId does not match its measured experiment')\n }\n const changedSurfaces =\n evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? profileImprovementChangedSurfaces(evaluation.experiment.change)\n : deriveChangedSurfaces(evaluation.experiment.baseline, evaluation.experiment.candidate)\n return { evaluation, changedSurfaces }\n}\n\n/** Use each owning package's complete measurement validator before a proposal is persisted. */\nfunction verifyAgentImprovementEvaluation(input: unknown): AgentImprovementEvaluation {\n if (\n typeof input === 'object' &&\n input !== null &&\n 'kind' in input &&\n input.kind === 'agent-profile-improvement-measured-comparison'\n ) {\n const evaluation = verifyAgentProfileImprovementExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\n }\n const evaluation = verifyCandidateExperimentComparison(input)\n optimizationActivationReceiptFromMetadata(evaluation.metadata)\n return evaluation\n}\n\n/** Validate the canonical identity and wire shape of an improvement review. */\nexport function verifyAgentImprovementReview(input: unknown): AgentImprovementReview {\n return verifyCanonicalCandidateDocument(\n agentImprovementReviewSchema.parse(input),\n 'agent improvement review',\n )\n}\n\n/** Validate activation authority against the exact proposal, review, experiment, and base state. */\nexport function verifyAgentImprovementActivation(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n}): AgentImprovementActivation {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const review = verifyAgentImprovementReview(input.review)\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(input.activation),\n 'agent improvement activation',\n )\n const experiment = proposal.evaluation.experiment\n if (\n review.decision !== 'approve' ||\n review.proposalDigest !== proposal.digest ||\n activation.proposalDigest !== proposal.digest ||\n activation.reviewDigest !== review.digest ||\n activation.experimentDigest !== experiment.digest ||\n activation.candidateDigest !== measuredCandidateDigest(proposal) ||\n Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) ||\n Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)\n ) {\n throw new Error('candidate activation does not bind the measured and approved candidate')\n }\n if (\n activation.targets.some((target) => target.surface === 'agent-profile') &&\n (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison' ||\n activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(proposal.evaluation.experiment.executionRef))\n ) {\n throw new Error('profile activation does not bind the measured executor')\n }\n assertAgentImprovementActivationTargets(\n proposal.changedSurfaces,\n experiment,\n activation.intent,\n activation.targets,\n )\n return activation\n}\n\nfunction sameOrderedValues<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,2BAA2B;AAExC,MAAM,gBAAgB,GAAY,QAChC,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,KAAK;;;;;;AAqBvD,SAAgB,uBAAuB,KAAmD;CACxF,IAAI,OAAO,QAAQ,YAAY,QAAQ,QAAQ,MAAM,QAAQ,GAAG,GAAG,OAAO,KAAA;CAC1E,MAAM,MAAM;CACZ,MAAM,IAAI,IAAI,KAAK,+BAA+B;CAClD,MAAM,eAAe,IAAI,gBAAgB,+BAA+B;CACxE,MAAM,UAAU,IAAI,WAAW,+BAA+B;CAC9D,IAAI,CAAC,aAAa,GAAG,CAAC,KAAK,CAAC,aAAa,cAAc,CAAC,KAAK,CAAC,aAAa,SAAS,CAAC,GACnF;CAEF,OAAO;EACL;EACA;EACA;EACA,GAAI,OAAO,IAAI,YAAY,YAAY,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CACrE;AACF;;AAGA,SA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MAAM,MAAM;CACxD,MAAM,aAAa,iCACjB,iCAAiC,MAAM,MAAM,UAAU,GACvD,8BACF;CACA,MAAM,aAAa,SAAS,WAAW;CACvC,IACE,OAAO,aAAa,aACpB,OAAO,mBAAmB,SAAS,UACnC,WAAW,mBAAmB,SAAS,UACvC,WAAW,iBAAiB,OAAO,UACnC,WAAW,qBAAqB,WAAW,UAC3C,WAAW,oBAAoB,wBAAwB,QAAQ,KAC/D,KAAK,MAAM,OAAO,UAAU,IAAI,KAAK,MAAM,SAAS,UAAU,KAC9D,KAAK,MAAM,WAAW,YAAY,IAAI,KAAK,MAAM,OAAO,UAAU,GAElE,MAAM,IAAI,MAAM,wEAAwE;CAE1F,IACE,WAAW,QAAQ,MAAM,WAAW,OAAO,YAAY,eAAe,MACrE,SAAS,WAAW,SAAS,mDAC5B,WAAW,iBAAiB,KAAA,KAC5BA,2BAAyB,WAAW,YAAY,MAC9CA,2BAAyB,SAAS,WAAW,WAAW,YAAY,IAExE,MAAM,IAAI,MAAM,wDAAwD;CAE1E,wCACE,SAAS,iBACT,YACA,WAAW,QACX,WAAW,OACb;CACA,OAAO;AACT;AAEA,SAAS,kBAAqB,MAAoB,OAA8B;CAC9E,OAAO,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,OAAO,UAAU,UAAU,MAAM,MAAM;AAC5F"}
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue,
|
|
1
|
+
import { S as RuntimeStreamEvent, Vx as AgentRunSpec, fS as SandboxClient, uS as OutputAdapter } from "./types-CaOXqRTq.js";
|
|
2
|
+
import { _ as promptResourceProfileMaterialization, a as ProfileMaterializationContract, b as worktreeCliProfileMaterialization, c as assertProfileMaterialization, d as defineProfileMaterializationContract, f as fullProfileMaterialization, g as promptOnlyProfileMaterialization, h as promptModelProfileMaterialization, l as assertProfileMaterializes, m as promptControlProfileMaterialization, n as AssertProfileMaterializationOptions, o as ProfileMaterializationIssue, p as profileMaterializationAxes, r as DefineProfileMaterializationContractOptions, s as ValidateProfileMaterializationOptions, t as AgentProfileMaterializationAxis, u as controlProfileMaterialization, v as sandboxActProfileMaterialization, y as validateProfileMaterialization } from "./profile-materialization-B1wm2SPT.js";
|
|
3
|
+
import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as validateSurfaces } from "./improvement-adapter-HUt_-cWA.js";
|
|
4
4
|
import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
|
|
5
5
|
import { TraceAnalystDefinition } from "@tangle-network/agent-eval";
|
|
6
6
|
import { SandboxEvent } from "@tangle-network/sandbox";
|
|
@@ -274,5 +274,5 @@ interface CreateSandboxActOptions<TPersona, TRunOutput> {
|
|
|
274
274
|
*/
|
|
275
275
|
declare function createSandboxAct<TPersona, TRunOutput>(options: CreateSandboxActOptions<TPersona, TRunOutput>): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>;
|
|
276
276
|
//#endregion
|
|
277
|
-
export {
|
|
277
|
+
export { type AgentManifest, AgentManifestError, type AgentRubric, type AgentRunContext, type AgentRunInvocation, type AgentRuntime, type AgentSurfaces, type AnalystConfig, type AssertProfileMaterializationOptions, type CreateSandboxActOptions, type CreateSurfaceImprovementProposerOptions, type DefineProfileMaterializationContractOptions, type DraftPatchInput, type DraftPatchOutput, type JudgeConfig, type ProfileMaterializationContract, type ProfileMaterializationIssue, type ResolvedSurface, type RubricDimension, type SandboxActComposeOverrides, type SurfaceImprovementEdit, type SurfaceValidationIssue, type ValidateProfileMaterializationOptions, assertProfileMaterialization, assertProfileMaterializes, collectAgentRun, controlProfileMaterialization, createSandboxAct, createSurfaceImprovementProposer, defineAgent, defineProfileMaterializationContract, fullProfileMaterialization, profileMaterializationAxes, promptControlProfileMaterialization, promptModelProfileMaterialization, promptOnlyProfileMaterialization, promptResourceProfileMaterialization, renderSurfaceIssues, sandboxActProfileMaterialization, unimplementedAgentRun, validateProfileMaterialization, validateSurfaces, worktreeCliProfileMaterialization };
|
|
278
278
|
//# sourceMappingURL=agent.d.ts.map
|
package/dist/agent.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import "./
|
|
3
|
-
import
|
|
1
|
+
import { Ar as controlProfileMaterialization, Bi as mapSandboxEvent, Fr as promptModelProfileMaterialization, Hr as validateProfileMaterialization, Ir as promptOnlyProfileMaterialization, Lr as promptResourceProfileMaterialization, Mr as fullProfileMaterialization, Nr as profileMaterializationAxes, Or as assertProfileMaterialization, Pr as promptControlProfileMaterialization, Ur as worktreeCliProfileMaterialization, bt as createSandboxForSpec, jr as defineProfileMaterializationContract, kr as assertProfileMaterializes, zr as sandboxActProfileMaterialization } from "./supervisor-DHrUJhEZ.js";
|
|
2
|
+
import { t as sha256 } from "./content-digest-sBTLujlK.js";
|
|
3
|
+
import "./runtime-B2fjL9Oi.js";
|
|
4
4
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
6
|
import { parseFindingSubject } from "@tangle-network/agent-eval/analyst";
|
|
@@ -428,9 +428,6 @@ function createSurfaceImprovementProposer(opts) {
|
|
|
428
428
|
};
|
|
429
429
|
} };
|
|
430
430
|
}
|
|
431
|
-
function sha256(s) {
|
|
432
|
-
return createHash("sha256").update(s, "utf-8").digest("hex");
|
|
433
|
-
}
|
|
434
431
|
//#endregion
|
|
435
432
|
//#region src/agent/sandbox-act.ts
|
|
436
433
|
/**
|
|
@@ -516,6 +513,6 @@ function applyComposeOverrides(base, overrides) {
|
|
|
516
513
|
};
|
|
517
514
|
}
|
|
518
515
|
//#endregion
|
|
519
|
-
export {
|
|
516
|
+
export { AgentManifestError, assertProfileMaterialization, assertProfileMaterializes, collectAgentRun, controlProfileMaterialization, createSandboxAct, createSurfaceImprovementProposer, defineAgent, defineProfileMaterializationContract, fullProfileMaterialization, profileMaterializationAxes, promptControlProfileMaterialization, promptModelProfileMaterialization, promptOnlyProfileMaterialization, promptResourceProfileMaterialization, renderSurfaceIssues, sandboxActProfileMaterialization, unimplementedAgentRun, validateProfileMaterialization, validateSurfaces, worktreeCliProfileMaterialization };
|
|
520
517
|
|
|
521
518
|
//# sourceMappingURL=agent.js.map
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":[],"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n /** Optional: directory containing Agent Skill packages. */\n skills?: string\n /** Optional: directory containing MCP server/tool configuration. */\n mcp?: string\n /** Optional: directory containing hook definitions. */\n hooks?: string\n /** Optional: directory containing subagent definitions. */\n subagents?: string\n /** Optional: directory containing orchestration/workflow policies. */\n workflows?: string\n /** Optional: single file containing rollout-policy settings. */\n rolloutPolicy?: string\n /** Optional: single canonical AgentProfile file. */\n agentProfile?: string\n /** Optional: source root for code findings. */\n code?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return optionalPath(safeJoin(surfaces.knowledge, `${subject.slug}.md`))\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return optionalPath(safeJoin(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`))\n case 'knowledge.raw':\n return optionalPath(safeJoin(surfaces.knowledge, 'raw', `${subject.sourceId}.md`))\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n safeJoin(surfaces.systemPrompt, `${slug}.md`),\n safeJoin(surfaces.systemPrompt, slug, 'SKILL.md'),\n safeJoin(surfaces.systemPrompt, slug, 'index.md'),\n ].filter((path): path is string => path !== null)\n }\n case 'skill': {\n if (!surfaces.skills) return []\n return [\n safeJoin(surfaces.skills, subject.name, 'SKILL.md'),\n safeJoin(surfaces.skills, `${subject.name}.md`),\n ].filter((path): path is string => path !== null)\n }\n case 'tool-doc':\n if (subject.aspect) {\n return optionalPath(safeJoin(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`))\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n safeJoin(surfaces.tools, subject.tool, 'README.md'),\n safeJoin(surfaces.tools, `${subject.tool}.md`),\n ].filter((path): path is string => path !== null)\n case 'new-tool':\n return optionalPath(safeJoin(surfaces.tools, subject.name, 'README.md'))\n case 'mcp':\n if (!surfaces.mcp) return []\n return subject.tool\n ? optionalPath(safeJoin(surfaces.mcp, subject.server, `${subject.tool}.md`))\n : [\n safeJoin(surfaces.mcp, `${subject.server}.json`),\n safeJoin(surfaces.mcp, subject.server, 'README.md'),\n ].filter((path): path is string => path !== null)\n case 'hook':\n if (!surfaces.hooks) return []\n return [\n safeJoin(surfaces.hooks, `${subject.name}.md`),\n safeJoin(surfaces.hooks, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'subagent':\n if (!surfaces.subagents) return []\n return [\n safeJoin(surfaces.subagents, `${subject.name}.md`),\n safeJoin(surfaces.subagents, `${subject.name}.yaml`),\n safeJoin(surfaces.subagents, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'workflow':\n if (!surfaces.workflows) return []\n return [\n safeJoin(surfaces.workflows, `${subject.name}.md`),\n safeJoin(surfaces.workflows, `${subject.name}.yaml`),\n safeJoin(surfaces.workflows, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'rollout-policy':\n return surfaces.rolloutPolicy ? [surfaces.rolloutPolicy] : []\n case 'agent-profile':\n return surfaces.agentProfile ? [surfaces.agentProfile] : []\n case 'code': {\n if (!surfaces.code) return []\n const path = safeJoin(surfaces.code, subject.path)\n return path ? [path] : []\n }\n case 'rag':\n if (!surfaces.rag) return []\n return optionalPath(safeJoin(surfaces.rag, subject.corpus, `${subject.docId}.md`))\n case 'memory':\n if (!surfaces.memory) return []\n return optionalPath(safeJoin(surfaces.memory, `${slugify(subject.key)}.json`))\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return optionalPath(safeJoin(surfaces.scaffolding, `${slugify(subject.concern)}.md`))\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction safeJoin(root: string, ...children: string[]): string | null {\n if (children.some((child) => child.includes('\\0') || isAbsolute(child))) return null\n const rootAbsolute = resolve(root)\n const targetAbsolute = resolve(rootAbsolute, ...children)\n const escaped = relative(rootAbsolute, targetAbsolute)\n if (escaped === '..' || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) return null\n return join(root, ...children)\n}\n\nfunction optionalPath(path: string | null): string[] {\n return path ? [path] : []\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\n/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'scaffolding',\n 'memory',\n 'rag',\n 'skills',\n 'mcp',\n 'hooks',\n 'subagents',\n 'workflows',\n 'code',\n ]\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'outputSchema',\n 'rolloutPolicy',\n 'agentProfile',\n ]\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n continue\n }\n const expectedDirectory = optionalDirSurfaces.includes(key)\n if (expectedDirectory && !statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n } else if (!expectedDirectory && !statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n return issues\n}\n\n/** Format a list of surface validation issues into a human-readable error string. */\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementProposalSource`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n *\n * @experimental Manifests validate and load, but `runtime.act` is not yet wired\n * end-to-end into the substrate's eval path (`unimplementedAgentRun` is the\n * shipped default).\n */\n\nimport type { TraceAnalystDefinition } from '@tangle-network/agent-eval'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystDefinition>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\n/** Thrown when `defineAgent` finds a required surface missing on disk. */\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Surface improvement proposer — resolves analyst findings into LLM-drafted\n * candidate patches without changing the caller's repository.\n *\n * The proposer parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { createHash } from 'node:crypto'\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementProposalSource } from '../analyst-loop/types'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementProposerOptions {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\n/** Resolve each finding to a real surface and draft a detached patch candidate. */\nexport function createSurfaceImprovementProposer(\n opts: CreateSurfaceImprovementProposerOptions,\n): ImprovementProposalSource<SurfaceImprovementEdit> {\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // Knowledge findings flow to the knowledge proposal source so they do not double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n }\n}\n\nfunction sha256(s: string): string {\n return createHash('sha256').update(s, 'utf-8').digest('hex')\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/run-loop'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\nimport {\n type AgentProfileMaterializationAxis,\n assertProfileMaterialization,\n sandboxActProfileMaterialization,\n} from './profile-materialization'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Optional changed axes the caller expects this path to carry. */\n requiredProfileAxes?: readonly AgentProfileMaterializationAxis[]\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n assertProfileMaterialization({\n contract: sandboxActProfileMaterialization,\n changedAxes: options.requiredProfileAxes ?? [],\n context: 'createSandboxAct',\n })\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools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QAAQ,eAAe,MAAM,MAAM;IAC1E,WAAW,MAAM,SAAS,IAAI,aAAa,SAAS,EAAE,OAAO,CAAC,GAAG;KAC/D,IAAI,KAAK,KAAK;KACd,MAAM,SAAS,SAAS,OAAO,EAAE,aAAa,CAAC;KAC/C,IAAI,QAAQ,MAAM;IACpB;IACA,OAAO,QAAQ,OAAO,MAAM,GAAG,CAAC;GAClC,SAAS,KAAK;IACZ,KAAK,GAAG;IACR,MAAM;GACR;EACF;EAEA,OAAO;GAAE,QAAQ,OAAO;GAAG;EAAO;CACpC;AACF;;;AAIA,SAAS,sBACP,MACA,WACc;CACd,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,SAAS,UAAU,eACrB;EAAE,GAAG,KAAK;EAAQ,cAAc,UAAU;CAAa,IACvD,KAAK;CACT,MAAM,cAAc,UAAU,QAAQ;EAAE,GAAI,KAAK,SAAS,CAAC;EAAI,GAAG,UAAU;CAAM,IAAI,KAAK;CAC3F,MAAM,YAAY,UAAU,iBACxB;EAAE,GAAI,KAAK,OAAO,CAAC;EAAI,GAAG,UAAU;CAAe,IACnD,KAAK;CACT,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;CAC5C,MAAM,cAAuC,UAAU,YAAY,SAC/D,CAAC,GAAG,WAAW,GAAG,UAAU,UAAU,IACtC,CAAC,GAAG,SAAS;CACjB,OAAO;EACL,GAAG;EACH,MAAM,UAAU,QAAQ,KAAK;EAC7B;EACA,GAAI,cAAc,EAAE,OAAO,YAAY,IAAI,CAAC;EAC5C,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;EACtC,WAAW;GAAE,GAAG,KAAK;GAAW,OAAO;EAAY;CACrD;AACF"}
|
|
1
|
+
{"version":3,"file":"agent.js","names":[],"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n /** Optional: directory containing Agent Skill packages. */\n skills?: string\n /** Optional: directory containing MCP server/tool configuration. */\n mcp?: string\n /** Optional: directory containing hook definitions. */\n hooks?: string\n /** Optional: directory containing subagent definitions. */\n subagents?: string\n /** Optional: directory containing orchestration/workflow policies. */\n workflows?: string\n /** Optional: single file containing rollout-policy settings. */\n rolloutPolicy?: string\n /** Optional: single canonical AgentProfile file. */\n agentProfile?: string\n /** Optional: source root for code findings. */\n code?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return optionalPath(safeJoin(surfaces.knowledge, `${subject.slug}.md`))\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return optionalPath(safeJoin(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`))\n case 'knowledge.raw':\n return optionalPath(safeJoin(surfaces.knowledge, 'raw', `${subject.sourceId}.md`))\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n safeJoin(surfaces.systemPrompt, `${slug}.md`),\n safeJoin(surfaces.systemPrompt, slug, 'SKILL.md'),\n safeJoin(surfaces.systemPrompt, slug, 'index.md'),\n ].filter((path): path is string => path !== null)\n }\n case 'skill': {\n if (!surfaces.skills) return []\n return [\n safeJoin(surfaces.skills, subject.name, 'SKILL.md'),\n safeJoin(surfaces.skills, `${subject.name}.md`),\n ].filter((path): path is string => path !== null)\n }\n case 'tool-doc':\n if (subject.aspect) {\n return optionalPath(safeJoin(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`))\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n safeJoin(surfaces.tools, subject.tool, 'README.md'),\n safeJoin(surfaces.tools, `${subject.tool}.md`),\n ].filter((path): path is string => path !== null)\n case 'new-tool':\n return optionalPath(safeJoin(surfaces.tools, subject.name, 'README.md'))\n case 'mcp':\n if (!surfaces.mcp) return []\n return subject.tool\n ? optionalPath(safeJoin(surfaces.mcp, subject.server, `${subject.tool}.md`))\n : [\n safeJoin(surfaces.mcp, `${subject.server}.json`),\n safeJoin(surfaces.mcp, subject.server, 'README.md'),\n ].filter((path): path is string => path !== null)\n case 'hook':\n if (!surfaces.hooks) return []\n return [\n safeJoin(surfaces.hooks, `${subject.name}.md`),\n safeJoin(surfaces.hooks, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'subagent':\n if (!surfaces.subagents) return []\n return [\n safeJoin(surfaces.subagents, `${subject.name}.md`),\n safeJoin(surfaces.subagents, `${subject.name}.yaml`),\n safeJoin(surfaces.subagents, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'workflow':\n if (!surfaces.workflows) return []\n return [\n safeJoin(surfaces.workflows, `${subject.name}.md`),\n safeJoin(surfaces.workflows, `${subject.name}.yaml`),\n safeJoin(surfaces.workflows, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'rollout-policy':\n return surfaces.rolloutPolicy ? [surfaces.rolloutPolicy] : []\n case 'agent-profile':\n return surfaces.agentProfile ? [surfaces.agentProfile] : []\n case 'code': {\n if (!surfaces.code) return []\n const path = safeJoin(surfaces.code, subject.path)\n return path ? [path] : []\n }\n case 'rag':\n if (!surfaces.rag) return []\n return optionalPath(safeJoin(surfaces.rag, subject.corpus, `${subject.docId}.md`))\n case 'memory':\n if (!surfaces.memory) return []\n return optionalPath(safeJoin(surfaces.memory, `${slugify(subject.key)}.json`))\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return optionalPath(safeJoin(surfaces.scaffolding, `${slugify(subject.concern)}.md`))\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction safeJoin(root: string, ...children: string[]): string | null {\n if (children.some((child) => child.includes('\\0') || isAbsolute(child))) return null\n const rootAbsolute = resolve(root)\n const targetAbsolute = resolve(rootAbsolute, ...children)\n const escaped = relative(rootAbsolute, targetAbsolute)\n if (escaped === '..' || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) return null\n return join(root, ...children)\n}\n\nfunction optionalPath(path: string | null): string[] {\n return path ? [path] : []\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\n/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'scaffolding',\n 'memory',\n 'rag',\n 'skills',\n 'mcp',\n 'hooks',\n 'subagents',\n 'workflows',\n 'code',\n ]\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'outputSchema',\n 'rolloutPolicy',\n 'agentProfile',\n ]\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n continue\n }\n const expectedDirectory = optionalDirSurfaces.includes(key)\n if (expectedDirectory && !statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n } else if (!expectedDirectory && !statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n return issues\n}\n\n/** Format a list of surface validation issues into a human-readable error string. */\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementProposalSource`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n *\n * @experimental Manifests validate and load, but `runtime.act` is not yet wired\n * end-to-end into the substrate's eval path (`unimplementedAgentRun` is the\n * shipped default).\n */\n\nimport type { TraceAnalystDefinition } from '@tangle-network/agent-eval'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystDefinition>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\n/** Thrown when `defineAgent` finds a required surface missing on disk. */\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Surface improvement proposer — resolves analyst findings into LLM-drafted\n * candidate patches without changing the caller's repository.\n *\n * The proposer parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementProposalSource } from '../analyst-loop/types'\nimport { sha256 } from '../content-digest'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementProposerOptions {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\n/** Resolve each finding to a real surface and draft a detached patch candidate. */\nexport function createSurfaceImprovementProposer(\n opts: CreateSurfaceImprovementProposerOptions,\n): ImprovementProposalSource<SurfaceImprovementEdit> {\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // Knowledge findings flow to the knowledge proposal source so they do not double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n }\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/iteration-sandboxes'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\nimport {\n type AgentProfileMaterializationAxis,\n assertProfileMaterialization,\n sandboxActProfileMaterialization,\n} from './profile-materialization'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Optional changed axes the caller expects this path to carry. */\n requiredProfileAxes?: readonly AgentProfileMaterializationAxis[]\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n assertProfileMaterialization({\n contract: sandboxActProfileMaterialization,\n changedAxes: options.requiredProfileAxes ?? [],\n context: 'createSandboxAct',\n })\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools: mergedTools } : {}),\n ...(mergedMcp ? { mcp: mergedMcp } : {}),\n resources: { ...base.resources, files: mergedFiles },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,mBACd,SACA,UACA,UACwB;CACxB,MAAM,aAAa,yBAAyB,SAAS,QAAQ;CAC7D,IAAI,WAAW,WAAW,GAAG,OAAO;CAMpC,KAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,MAAM,WAAW,GAAG,IAAI,MAAM,KAAK,UAAU,GAAG;EACtD,IAAI,WAAW,GAAG,GAChB,OAAO;GAAE,cAAc;GAAK,kBAAkB;GAAK,QAAQ;GAAM,QAAQ;EAAgB;CAE7F;CACA,MAAM,WAAW,WAAW;CAE5B,OAAO;EACL,cAFkB,WAAW,QAAQ,IAAI,WAAW,KAAK,UAAU,QAAQ;EAG3E,kBAAkB;EAClB,QAAQ;EACR,QAAQ;CACV;AACF;AAEA,SAAS,yBACP,SACA,UACuB;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AC5C,MAAM,cAAuC,UAAU,YAAY,SAC/D,CAAC,GAAG,WAAW,GAAG,UAAU,UAAU,IACtC,CAAC,GAAG,SAAS;CACjB,OAAO;EACL,GAAG;EACH,MAAM,UAAU,QAAQ,KAAK;EAC7B;EACA,GAAI,cAAc,EAAE,OAAO,YAAY,IAAI,CAAC;EAC5C,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;EACtC,WAAW;GAAE,GAAG,KAAK;GAAW,OAAO;EAAY;CACrD;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, z as immutableCandidateValue } from "./sandbox-profile-compat-
|
|
1
|
+
import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, z as immutableCandidateValue } from "./sandbox-profile-compat-BzVBFqrz.js";
|
|
2
2
|
import { agentCandidateBundleSchema } from "@tangle-network/agent-interface";
|
|
3
3
|
//#region src/candidate-execution/bundle.ts
|
|
4
4
|
/** Validate and content-address a candidate bundle before it crosses an approval boundary. */
|
|
@@ -14,4 +14,4 @@ function sealAgentCandidateBundle(input) {
|
|
|
14
14
|
//#endregion
|
|
15
15
|
export { sealAgentCandidateBundle as t };
|
|
16
16
|
|
|
17
|
-
//# sourceMappingURL=bundle-
|
|
17
|
+
//# sourceMappingURL=bundle-DVOhBTic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle-
|
|
1
|
+
{"version":3,"file":"bundle-DVOhBTic.js","names":["canonicalCandidateDigest"],"sources":["../src/candidate-execution/bundle.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\n}\n"],"mappings":";;;;AASA,SAAgB,yBAAyB,OAAwD;CAC/F,MAAM,SAASA,2BAAyB,KAAK;CAC7C,MAAM,SAAS,2BAA2B,MAAM;EAAE,GAAG;EAAO;CAAO,CAAC;CAEpE,IADqBA,2BAAyB,mBAAmB,MAAM,CACxD,MAAM,QACnB,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO,wBAAwB,MAAM;AACvC"}
|