@tangle-network/agent-runtime 0.133.8 → 0.134.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/{activation-CbgOt7bK.js → activation-CY_v6Ia7.js} +3 -3
  2. package/dist/{activation-CbgOt7bK.js.map → activation-CY_v6Ia7.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{analyst-loop-C189F6v8.js → analyst-loop-BKWqQhVI.js} +2 -2
  6. package/dist/{analyst-loop-C189F6v8.js.map → analyst-loop-BKWqQhVI.js.map} +1 -1
  7. package/dist/analyst-loop.js +1 -1
  8. package/dist/{authoring-DI2ZcORJ.js → authoring-BDICoQby.js} +2 -2
  9. package/dist/{authoring-DI2ZcORJ.js.map → authoring-BDICoQby.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{candidate-execution-_u2HIWeX.js → candidate-execution-CWMkOz7g.js} +4 -4
  12. package/dist/{candidate-execution-_u2HIWeX.js.map → candidate-execution-CWMkOz7g.js.map} +1 -1
  13. package/dist/{conversation-kPowfA_A.js → conversation-CrWcNPQg.js} +4 -4
  14. package/dist/{conversation-kPowfA_A.js.map → conversation-CrWcNPQg.js.map} +1 -1
  15. package/dist/conversation.d.ts +1 -1
  16. package/dist/conversation.js +1 -1
  17. package/dist/{environment-provider-DTJA4ZiM.js → environment-provider-CPHwqLLm.js} +2 -2
  18. package/dist/{environment-provider-DTJA4ZiM.js.map → environment-provider-CPHwqLLm.js.map} +1 -1
  19. package/dist/{environment-provider-B-w9VYcF.d.ts → environment-provider-qDOhdE9M.d.ts} +2 -2
  20. package/dist/environment-provider.d.ts +1 -1
  21. package/dist/environment-provider.js +1 -1
  22. package/dist/{errors-DRoXIc7E.js → errors-CVIDr7GQ.js} +9 -1
  23. package/dist/errors-CVIDr7GQ.js.map +1 -0
  24. package/dist/{graph-CnLcp2Tl.js → graph-D5TKFG8R.js} +4 -4
  25. package/dist/{graph-CnLcp2Tl.js.map → graph-D5TKFG8R.js.map} +1 -1
  26. package/dist/{improvement-cycle-ekj_ODWY.js → improvement-cycle-XLPktFtP.js} +9 -9
  27. package/dist/{improvement-cycle-ekj_ODWY.js.map → improvement-cycle-XLPktFtP.js.map} +1 -1
  28. package/dist/{index-DqJa9jGF.d.ts → index-CgBJtAzI.d.ts} +2 -2
  29. package/dist/{index-CP8LBWD1.d.ts → index-DBZTN4ci.d.ts} +4 -4
  30. package/dist/{index-Cgo-tyB8.d.ts → index-DiUDbnk-.d.ts} +29 -6
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +14 -14
  33. package/dist/intelligence.d.ts +4 -4
  34. package/dist/intelligence.js +6 -6
  35. package/dist/kernel.d.ts +6 -6
  36. package/dist/kernel.js +10 -10
  37. package/dist/{knowledge-BdJoVN9q.js → knowledge-Dv2HMnE6.js} +7 -7
  38. package/dist/{knowledge-BdJoVN9q.js.map → knowledge-Dv2HMnE6.js.map} +1 -1
  39. package/dist/knowledge.d.ts +1 -1
  40. package/dist/knowledge.js +1 -1
  41. package/dist/{loop-runner-bin-C1uQcY_O.js → loop-runner-bin-Bieu4QO4.js} +5 -5
  42. package/dist/{loop-runner-bin-C1uQcY_O.js.map → loop-runner-bin-Bieu4QO4.js.map} +1 -1
  43. package/dist/{loop-runner-bin-BX_266wJ.d.ts → loop-runner-bin-D5JXvb_l.d.ts} +3 -3
  44. package/dist/loop-runner-bin.d.ts +1 -1
  45. package/dist/loop-runner-bin.js +1 -1
  46. package/dist/{materialization-D2bdTfkK.js → materialization-BP5zspr2.js} +25 -10
  47. package/dist/materialization-BP5zspr2.js.map +1 -0
  48. package/dist/mcp/bin.js +4 -4
  49. package/dist/mcp/index.d.ts +3 -3
  50. package/dist/mcp/index.js +9 -9
  51. package/dist/mcp/memory-bin.js +1 -1
  52. package/dist/{memory-server-CblxrUKT.js → memory-server-Cdpy7Uu8.js} +3 -3
  53. package/dist/{memory-server-CblxrUKT.js.map → memory-server-Cdpy7Uu8.js.map} +1 -1
  54. package/dist/{model-policy-Bv1DU2fw.js → model-policy-UTTc9Z-A.js} +2 -2
  55. package/dist/{model-policy-Bv1DU2fw.js.map → model-policy-UTTc9Z-A.js.map} +1 -1
  56. package/dist/{openai-tools-BTznyT19.js → openai-tools-D4Rf0Ciu.js} +2 -2
  57. package/dist/{openai-tools-BTznyT19.js.map → openai-tools-D4Rf0Ciu.js.map} +1 -1
  58. package/dist/{prepare-DUbH3GD5.js → prepare-BxP7Hq1l.js} +2 -2
  59. package/dist/{prepare-DUbH3GD5.js.map → prepare-BxP7Hq1l.js.map} +1 -1
  60. package/dist/primeintellect/index.d.ts +1 -1
  61. package/dist/profiles.js +1 -1
  62. package/dist/{protected-model-port-DP7MS63a.js → protected-model-port-B82zDDu5.js} +2 -2
  63. package/dist/{protected-model-port-DP7MS63a.js.map → protected-model-port-B82zDDu5.js.map} +1 -1
  64. package/dist/{redact-BSD-nvTf.d.ts → redact-6UE6pdNi.d.ts} +3 -3
  65. package/dist/{researcher-BiWSFLi6.js → researcher-DBfKdnAz.js} +3 -3
  66. package/dist/{researcher-BiWSFLi6.js.map → researcher-DBfKdnAz.js.map} +1 -1
  67. package/dist/{runtime-D-26vxJt.d.ts → runtime-DlxoqEj2.d.ts} +27 -6
  68. package/dist/{runtime-Br49sl8u.js → runtime-Ox-uvtni.js} +29 -14
  69. package/dist/runtime-Ox-uvtni.js.map +1 -0
  70. package/dist/{snapshot-DY6VGliG.js → snapshot-BOIprwBk.js} +2 -2
  71. package/dist/{snapshot-DY6VGliG.js.map → snapshot-BOIprwBk.js.map} +1 -1
  72. package/dist/{spawn-journal-BX3-4WDm.js → spawn-journal-TJSlDa2J.js} +27 -11
  73. package/dist/spawn-journal-TJSlDa2J.js.map +1 -0
  74. package/dist/{stream-agent-turn-NFWCv1X1.d.ts → stream-agent-turn-CJog3ebs.d.ts} +2 -2
  75. package/dist/{stream-agent-turn-D8YHY0oO.js → stream-agent-turn-CdIcf-bn.js} +4 -4
  76. package/dist/{stream-agent-turn-D8YHY0oO.js.map → stream-agent-turn-CdIcf-bn.js.map} +1 -1
  77. package/dist/{structural-rollout-C4_mifPH.js → structural-rollout-CnHKUCVM.js} +6 -6
  78. package/dist/{structural-rollout-C4_mifPH.js.map → structural-rollout-CnHKUCVM.js.map} +1 -1
  79. package/dist/{supervise-BTwl4Cdi.js → supervise-BNOccEtp.js} +66 -37
  80. package/dist/supervise-BNOccEtp.js.map +1 -0
  81. package/dist/{supervisor-BA87pb7g.js → supervisor-4r4BYSti.js} +75 -22
  82. package/dist/supervisor-4r4BYSti.js.map +1 -0
  83. package/dist/testing.d.ts +2 -2
  84. package/dist/testing.js +12 -12
  85. package/dist/{tool-server-VvSK1K3X.js → tool-server-Dh-NcbHr.js} +2 -2
  86. package/dist/{tool-server-VvSK1K3X.js.map → tool-server-Dh-NcbHr.js.map} +1 -1
  87. package/dist/{types-DJ7k6vHE.d.ts → types-D4BfurNs.d.ts} +9 -2
  88. package/dist/{util-Dr--8wAL.js → util-CG3ghHfb.js} +56 -7
  89. package/dist/util-CG3ghHfb.js.map +1 -0
  90. package/dist/{workspace-archive-WEbaLREb.js → workspace-archive-BwJQSvGi.js} +2 -2
  91. package/dist/{workspace-archive-WEbaLREb.js.map → workspace-archive-BwJQSvGi.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/dist/errors-DRoXIc7E.js.map +0 -1
  94. package/dist/materialization-D2bdTfkK.js.map +0 -1
  95. package/dist/runtime-Br49sl8u.js.map +0 -1
  96. package/dist/spawn-journal-BX3-4WDm.js.map +0 -1
  97. package/dist/supervise-BTwl4Cdi.js.map +0 -1
  98. package/dist/supervisor-BA87pb7g.js.map +0 -1
  99. package/dist/util-Dr--8wAL.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { it as canonicalCandidateDocument, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, ut as verifyCanonicalCandidateDocument } from "./prepare-DUbH3GD5.js";
2
- import { C as agentImprovementTargetInput, S as agentImprovementTargetDigest, T as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal } from "./improvement-cycle-ekj_ODWY.js";
1
+ import { it as canonicalCandidateDocument, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, ut as verifyCanonicalCandidateDocument } from "./prepare-BxP7Hq1l.js";
2
+ import { C as agentImprovementTargetInput, S as agentImprovementTargetDigest, T as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal } from "./improvement-cycle-XLPktFtP.js";
3
3
  import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
4
4
  //#region src/intelligence/activation.ts
5
5
  /** Create the exact result a product stores in the same transaction as its target write. */
@@ -201,4 +201,4 @@ function targetIdentity(target) {
201
201
  //#endregion
202
202
  export { executeAgentImprovementActivation as n, verifyAgentImprovementActivationResult as r, createAgentImprovementActivationResult as t };
203
203
 
204
- //# sourceMappingURL=activation-CbgOt7bK.js.map
204
+ //# sourceMappingURL=activation-CY_v6Ia7.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-CbgOt7bK.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\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 requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\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"],"mappings":";;;;;AA6IA,SAAgB,uCACd,YACA,SACkC;CAClC,MAAM,aAAa,iCACjB,iCAAiC,MAAM,WAAW,UAAU,GAC5D,8BACF;CACA,sBAAsB,YAAY,UAAU;CAC5C,MAAM,SAAS,uCAAuC,MACpD,2BAA6D;EAC3D,MAAM;EACN,gBAAgB,WAAW;EAC3B,aAAa,WAAW;EACxB,aAAa,QAAQ;EACrB,SAAS,QAAQ;CACnB,CAAC,CAAC,CAAC,KACL;CACA,8BAA8B,YAAY,MAAM;CAChD,0BACE,YACA,QACA,IAAI,IAAI,WAAW,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,OAAO,aAAa,CAAC,CAAC,CAC5F;CACA,OAAO,wBAAwB,MAAM;AACvC;;;;;AAMA,SAAgB,uCAAuC,OAKlB;CACnC,MAAM,WAAW,+BAA+B,MAAM,QAAQ;CAC9D,MAAM,aAAa,iCAAiC,KAAK;CACzD,MAAM,SAAS,iCACb,uCAAuC,MAAM,MAAM,MAAM,GACzD,qCACF;CACA,8BAA8B,YAAY,MAAM;CAChD,yBAAyB,UAAU,YAAY,MAAM;CACrD,OAAO;AACT;;AAGA,eAAsB,kCACpB,OACA,SAC2C;CAC3C,MAAM,WAAW,+BAA+B,MAAM,QAAQ;CAC9D,MAAM,aAAa,iCAAiC,KAAK;CACzD,MAAM,cAAc,QAAQ,8BAAc,IAAI,KAAK,GAAA,CAAI,CAAC,CAAC,YAAY;CACrE,MAAM,cACJ,KAAK,MAAM,UAAU,IAAI,KAAK,MAAM,WAAW,YAAY,IACvD,WAAW,eACX;CACN,MAAM,UAAU,KAAK,MAAM,WAAW,KAAK,KAAK,MAAM,WAAW,SAAS;CAC1E,MAAM,aAAa,wBACjB,SAAS,WAAW,SAAS,0CACzB,0BAA0B,SAAS,WAAW,YAAY,YAAY,aAAa,OAAO,IAC1F,6BACE,SAAS,W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,IAAI,MAAM,wDAAwD;EAE1E;CACF;CACA,MAAM,aAAa,OAAO,QAAQ,QAAQ,OACvC,WAAW,OAAO,kBAAkB,QAAQ,IAAI,eAAe,MAAM,CAAC,CACzE;CACA,IAAI,OAAO,QAAQ,WAAW,mBAAmB;EAC/C,IAAI,CAAC,YAAY,MAAM,IAAI,MAAM,0DAA0D;EAC3F;CACF;CACA,MAAM,aAAa,UAAU,WAAW,OAAO;CAC/C,MAAM,iBAAiB,OAAO,QAAQ,QAAQ,MAC3C,WAAW,OAAO,kBAAkB,WAAW,IAAI,eAAe,MAAM,CAAC,CAAC,EAAE,kBAC/E;CACA,IAAI,cAAc,CAAC,gBACjB,MAAM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,UACP,SACgB;CAChB,OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
1
+ {"version":3,"file":"activation-CY_v6Ia7.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\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 requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\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"],"mappings":";;;;;AA6IA,SAAgB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AQ,IAAI,eAAe,MAAM,CAAC,CACzE;CACA,IAAI,OAAO,QAAQ,WAAW,mBAAmB;EAC/C,IAAI,CAAC,YAAY,MAAM,IAAI,MAAM,0DAA0D;EAC3F;CACF;CACA,MAAM,aAAa,UAAU,WAAW,OAAO;CAC/C,MAAM,iBAAiB,OAAO,QAAQ,QAAQ,MAC3C,WAAW,OAAO,kBAAkB,WAAW,IAAI,eAAe,MAAM,CAAC,CAAC,EAAE,kBAC/E;CACA,IAAI,cAAc,CAAC,gBACjB,MAAM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,UACP,SACgB;CAChB,OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { E as SandboxClient, it as RuntimeStreamEvent, t as AgentRunSpec, w as OutputAdapter } from "./types-6zHo67jn.js";
2
2
  import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, d as validateSurfaces, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as resolveSubjectPath } from "./improvement-adapter-D5gwwoXQ.js";
3
- import { $f as KnownAgentProfileMaterializationAxis, Jf as AGENT_PROFILE_MATERIALIZATION_AXES, Qf as DefineProfileMaterializationContractOptions, Xf as AssertProfileMaterializationOptions, Yf as AgentProfileMaterializationAxis, Zf as CanonicalAgentProfileMaterializationAxis, ap as defineProfileMaterializationContract, cp as promptControlProfileMaterialization, dp as promptResourceProfileMaterialization, ep as ProfileMaterializationContract, fp as renderProfileMaterializationIssues, hp as worktreeCliProfileMaterialization, ip as controlProfileMaterialization, lp as promptModelProfileMaterialization, mp as validateProfileMaterialization, np as ValidateProfileMaterializationOptions, op as fullProfileMaterialization, pp as sandboxActProfileMaterialization, rp as assertProfileMaterialization, sp as profileMaterializationAxes, tp as ProfileMaterializationIssue, up as promptOnlyProfileMaterialization } from "./index-Cgo-tyB8.js";
3
+ import { $f as KnownAgentProfileMaterializationAxis, Jf as AGENT_PROFILE_MATERIALIZATION_AXES, Qf as DefineProfileMaterializationContractOptions, Xf as AssertProfileMaterializationOptions, Yf as AgentProfileMaterializationAxis, Zf as CanonicalAgentProfileMaterializationAxis, ap as defineProfileMaterializationContract, cp as promptControlProfileMaterialization, dp as promptResourceProfileMaterialization, ep as ProfileMaterializationContract, fp as renderProfileMaterializationIssues, hp as worktreeCliProfileMaterialization, ip as controlProfileMaterialization, lp as promptModelProfileMaterialization, mp as validateProfileMaterialization, np as ValidateProfileMaterializationOptions, op as fullProfileMaterialization, pp as sandboxActProfileMaterialization, rp as assertProfileMaterialization, sp as profileMaterializationAxes, tp as ProfileMaterializationIssue, up as promptOnlyProfileMaterialization } from "./index-DiUDbnk-.js";
4
4
  import { TraceAnalystDefinition } from "@tangle-network/agent-eval";
5
5
  import { AgentProfile as AgentProfile$1, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
6
6
  import { SandboxEvent } from "@tangle-network/sandbox";
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { r as mapSandboxEvent } from "./sandbox-events-vIwmuPdl.js";
2
- import { $ as createSandboxForSpec, $t as sandboxActProfileMaterialization, Gt as defineProfileMaterializationContract, Ht as AGENT_PROFILE_MATERIALIZATION_AXES, Jt as promptControlProfileMaterialization, Kt as fullProfileMaterialization, Qt as renderProfileMaterializationIssues, Ut as assertProfileMaterialization, Wt as controlProfileMaterialization, Xt as promptOnlyProfileMaterialization, Yt as promptModelProfileMaterialization, Zt as promptResourceProfileMaterialization, en as validateProfileMaterialization, qt as profileMaterializationAxes, tn as worktreeCliProfileMaterialization } from "./supervisor-BA87pb7g.js";
3
- import "./runtime-Br49sl8u.js";
2
+ import { $ as createSandboxForSpec, $t as sandboxActProfileMaterialization, Gt as defineProfileMaterializationContract, Ht as AGENT_PROFILE_MATERIALIZATION_AXES, Jt as promptControlProfileMaterialization, Kt as fullProfileMaterialization, Qt as renderProfileMaterializationIssues, Ut as assertProfileMaterialization, Wt as controlProfileMaterialization, Xt as promptOnlyProfileMaterialization, Yt as promptModelProfileMaterialization, Zt as promptResourceProfileMaterialization, en as validateProfileMaterialization, qt as profileMaterializationAxes, tn as worktreeCliProfileMaterialization } from "./supervisor-4r4BYSti.js";
3
+ import "./runtime-Ox-uvtni.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { existsSync, readFileSync, statSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { n as AnalystError } from "./errors-DRoXIc7E.js";
1
+ import { n as AnalystError } from "./errors-CVIDr7GQ.js";
2
2
  import { n as extractLlmCallEvent } from "./sandbox-events-vIwmuPdl.js";
3
3
  import { DEFAULT_TRACE_ANALYST_BUDGETS, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, diffFindings } from "@tangle-network/agent-eval";
4
4
  //#region src/analyst-loop/iterations-to-trace-store.ts
@@ -543,4 +543,4 @@ function defaultLog(msg, fields) {
543
543
  //#endregion
544
544
  export { iterationsToTraceStore as n, runAnalystLoop as t };
545
545
 
546
- //# sourceMappingURL=analyst-loop-C189F6v8.js.map
546
+ //# sourceMappingURL=analyst-loop-BKWqQhVI.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"analyst-loop-C189F6v8.js","names":[],"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async hasTrace(trace_id: string): Promise<boolean> {\n return byId.has(trace_id)\n },\n\n async hasSpans(opts): Promise<string[]> {\n const t = byId.get(opts.trace_id)\n if (!t) return []\n const present = new Set(t.spans.map((s) => s.span_id))\n return opts.span_ids.filter((id) => present.has(id))\n },\n\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n // Fill the response up to the per-call byte ceiling; requested spans that\n // exist but do not fit become `omitted_span_ids` continuation work. The\n // first span is always included even when it alone exceeds the ceiling —\n // otherwise a caller could never make progress on an oversized span.\n let truncated = 0\n let bytes = 0\n const spans: TraceAnalystSpan[] = []\n const omitted: string[] = []\n for (const s of found) {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n const projected = { ...s, attributes: capped }\n const size = bytesOf(projected)\n if (spans.length > 0 && bytes + size > budgets.perCallByteCeiling) {\n omitted.push(s.span_id)\n continue\n }\n truncated += n\n bytes += size\n spans.push(projected)\n }\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n omitted_span_ids: omitted,\n has_more: omitted.length > 0,\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const all = span ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget) : []\n const hits = all.slice(0, max)\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n has_more: all.length > hits.length,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge proposal source\n * 6. Hand the findings to the agent-surface proposal source\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Proposal sources are optional: the loop also works as a plain\n * \"run + diff + report\" primitive.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\n/** Analyze a run and apply accepted knowledge and agent-surface proposals. */\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before proposal generation so the ledger remains\n // the source of truth if a proposal source throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge proposals. This loop never writes live knowledge.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeProposalSource) {\n knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit)\n }\n\n // 6. Agent-surface proposals. This loop never writes live agent state.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementProposalSource) {\n improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit)\n }\n\n const durationMs = Math.max(0, Date.now() - startedAt)\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n durationMs,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n const registryOptions = {\n ...(priorFindings ? { priorFindings } : {}),\n ...(opts.chainFindings !== undefined ? { chainFindings: opts.chainFindings } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n ...(opts.costPhase ? { costPhase: opts.costPhase } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n }\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, registryOptions)) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, registryOptions)\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeProposalSource<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const source = opts.knowledgeProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n proposals: batch.proposals as TProposal[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nasync function runImprovementProposalSource<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const source = opts.improvementProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n edits: batch.edits as TEdit[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,WAAW,MAAuB,OAAO,WAAW,KAAK,UAAU,CAAC,KAAK,IAAI,MAAM;AACzF,MAAM,OAAO,OAAuB,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;;;AAI7D,SAAS,mBAAmB,SAAyB;CACnD,OAAO,QACJ,QAAQ,mBAAmB,KAAK,CAAC,CACjC,QAAQ,gFAAgF,MAAM,CAAC,CAC/F,QAAQ,oBAAoB,MAAM,CAAC,CACnC,QAAQ,8BAA8B,KAAK,CAAC,CAC5C,QAAQ,YAAY,GAAG,CAAC,CACxB,QAAQ,QAAQ,GAAG,CAAC,CACpB,KAAK,CAAC,CACN,MAAM,GAAG,GAAG;AACjB;AAEA,SAAS,YACP,OACA,cAKA;CACA,MAAM,MAAM,oBAAoB,OAAO,YAAY;CACnD,IAAI,KAAK,OAAO;EAAE,MAAM;EAAO,OAAO,IAAI,SAAS;EAAM,MAAM;CAAK;CACpE,MAAM,OAAO,OAAO,OAAO,QAAQ,EAAE;CACrC,IAAI,QAAQ,KAAK,IAA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AO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,WAAW,MAAM,MAAM;EACvB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,OAAO,MAAM;EACb,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;CACvE,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,OAAO,MAAM;MAClD,QAAQ,IAAI,kBAAkB,KAAK;AAC1C"}
1
+ {"version":3,"file":"analyst-loop-BKWqQhVI.js","names":[],"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async hasTrace(trace_id: string): Promise<boolean> {\n return byId.has(trace_id)\n },\n\n async hasSpans(opts): Promise<string[]> {\n const t = byId.get(opts.trace_id)\n if (!t) return []\n const present = new Set(t.spans.map((s) => s.span_id))\n return opts.span_ids.filter((id) => present.has(id))\n },\n\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n // Fill the response up to the per-call byte ceiling; requested spans that\n // exist but do not fit become `omitted_span_ids` continuation work. The\n // first span is always included even when it alone exceeds the ceiling —\n // otherwise a caller could never make progress on an oversized span.\n let truncated = 0\n let bytes = 0\n const spans: TraceAnalystSpan[] = []\n const omitted: string[] = []\n for (const s of found) {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n const projected = { ...s, attributes: capped }\n const size = bytesOf(projected)\n if (spans.length > 0 && bytes + size > budgets.perCallByteCeiling) {\n omitted.push(s.span_id)\n continue\n }\n truncated += n\n bytes += size\n spans.push(projected)\n }\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n omitted_span_ids: omitted,\n has_more: omitted.length > 0,\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const all = span ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget) : []\n const hits = all.slice(0, max)\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n has_more: all.length > hits.length,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge proposal source\n * 6. Hand the findings to the agent-surface proposal source\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Proposal sources are optional: the loop also works as a plain\n * \"run + diff + report\" primitive.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\n/** Analyze a run and apply accepted knowledge and agent-surface proposals. */\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before proposal generation so the ledger remains\n // the source of truth if a proposal source throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge proposals. This loop never writes live knowledge.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeProposalSource) {\n knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit)\n }\n\n // 6. Agent-surface proposals. This loop never writes live agent state.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementProposalSource) {\n improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit)\n }\n\n const durationMs = Math.max(0, Date.now() - startedAt)\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n durationMs,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n const registryOptions = {\n ...(priorFindings ? { priorFindings } : {}),\n ...(opts.chainFindings !== undefined ? { chainFindings: opts.chainFindings } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n ...(opts.costPhase ? { costPhase: opts.costPhase } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n }\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, registryOptions)) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, registryOptions)\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeProposalSource<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const source = opts.knowledgeProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n proposals: batch.proposals as TProposal[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nasync function runImprovementProposalSource<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const source = opts.improvementProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n edits: batch.edits as TEdit[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,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;CACnF,IAAI,aAAa,YACf,OAAO,EAAE,KAAK,SAAS;CAGzB,OAAO;AACT;AAEA,eAAe,2BACb,MACA,UACA,KACA,MACqC;CAErC,MAAM,QAAQ,MADC,KAAK,wBACO,oBAAoB,QAAQ;CACvD,IAAI,iCAAiC;EACnC,WAAW,MAAM,UAAU;EAC3B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,eAAe,MAAM,UAAU;EAC/B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,eAAe,6BACb,MACA,UACA,KACA,MACmC;CAEnC,MAAM,QAAQ,MADC,KAAK,0BACO,oBAAoB,QAAQ;CACvD,IAAI,mCAAmC;EACrC,OAAO,MAAM,MAAM;EACnB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,WAAW,MAAM,MAAM;EACvB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,OAAO,MAAM;EACb,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;CACvE,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,OAAO,MAAM;MAClD,QAAQ,IAAI,kBAAkB,KAAK;AAC1C"}
@@ -1,2 +1,2 @@
1
- import { n as iterationsToTraceStore, t as runAnalystLoop } from "./analyst-loop-C189F6v8.js";
1
+ import { n as iterationsToTraceStore, t as runAnalystLoop } from "./analyst-loop-BKWqQhVI.js";
2
2
  export { iterationsToTraceStore, runAnalystLoop };
@@ -1,4 +1,4 @@
1
- import { v as supervisorPolicyPrompt } from "./supervise-BTwl4Cdi.js";
1
+ import { v as supervisorPolicyPrompt } from "./supervise-BNOccEtp.js";
2
2
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
3
3
  import { agentProfileSchema } from "@tangle-network/agent-interface";
4
4
  //#region src/runtime/supervise/authoring.ts
@@ -160,4 +160,4 @@ function profileRichnessFinding(richness, opts) {
160
160
  //#endregion
161
161
  export { supervisorInstructions as a, profileRichnessFinding as i, assessAuthoredProfile as n, defaultProfileRichnessThresholds as r, asAuthoredProfile as t };
162
162
 
163
- //# sourceMappingURL=authoring-DI2ZcORJ.js.map
163
+ //# sourceMappingURL=authoring-BDICoQby.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authoring-DI2ZcORJ.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO;CACjF,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ;GAAE,GAAG,OAAO,KAAK;GAAQ;EAAa;CAChD;AACF;;;;;;;;AASA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL,uBAAuB;EACvB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO,CAAC,IAAI,aAAa,KAAK,MAAM,IAAI,CAAC;CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;AAqBA,MAAa,mCAA8D;CACzE,sBAAsB;CACtB,sBAAsB;AACxB;;;AA0BA,SAAS,oBAAoB,SAA+B;CAC1D,MAAM,KAAM,QAAiC;CAC7C,IAAI,OAAO,OAAO,UAAU,OAAO;CACnC,IAAI,MAAM,OAAO,OAAO,UAAU;EAChC,MAAM,IAAI;EACV,IAAI,OAAO,EAAE,iBAAiB,UAAU,OAAO,EAAE;EACjD,IAAI,OAAO,EAAE,WAAW,UAAU,OAAO,EAAE;CAC7C;CACA,OAAO;AACT;;;AAIA,SAAgB,sBACd,SACA,MACiB;CACjB,MAAM,KAAK;EAAE,GAAG;EAAkC,GAAI,MAAM,cAAc,CAAC;CAAG;CAC9E,MAAM,eAAe,oBAAoB,OAA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;CAE1D,MAAM,OAAO,cAAe,CAAC,YAAY,CAAC,aAAa,CAAC;CAExD,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,SAAgB,uBACd,UACA,MACgB;CAChB,MAAM,aAAa,MAAM,aAAa;CACtC,MAAM,UAAU,SAAS;CACzB,MAAM,QAAQ,SAAS,OACnB,WAAW,SAAS,KAAK,oCAAoC,SAAS,QAAQ,KAAK,IAAI,EAAE,KACzF,WAAW,SAAS,KAAK,8CAA8C,SAAS,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE;CAM/G,OAAO,YAAY;EACjB;EACA,UAP2C,SAAS,OAClD,SAAS,WAAW,MAClB,SACA,WACF;EAIF,MAAM;EACN;EACA;EACA,YAAY;EACZ,eAAe,CACb;GACE,MAAM;GACN,KAAK,WAAW;GAChB,SAAS,SAAS,SAAS,kBAAkB,SAAS,SAAS,kBAAkB,SAAS,SAAS,SAAS,UAAU,SAAS,UAAU,OAAO,SAAS,OAAO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"authoring-BDICoQby.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO;CACjF,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ;GAAE,GAAG,OAAO,KAAK;GAAQ;EAAa;CAChD;AACF;;;;;;;;AASA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL,uBAAuB;EACvB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;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AO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
- import { $ as parseExactAgentProfile, G as agentCandidateProfileAsAgentProfile, K as applyExactAgentProfileDiff, S as CANDIDATE_TRACE_TAGS, Y as freezeGenericAgentCandidateProfile, Z as omitUndefinedObjectFields, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, n as executePreparedAgentCandidate, q as assertCandidateProfileBinding, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, t as prepareAgentCandidateExecution, tt as parseExactCandidateProfile, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "../prepare-DUbH3GD5.js";
2
- import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "../workspace-archive-WEbaLREb.js";
3
- import { a as buildAgentCandidateBundle, i as FileAgentCandidateExecutionClaimStore, n as runProtectedAgentCandidateModelGrant, r as disposePreparedAgentCandidateExecution, t as recoverExpiredAgentCandidateExecution } from "../candidate-execution-_u2HIWeX.js";
4
- import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-DP7MS63a.js";
1
+ import { $ as parseExactAgentProfile, G as agentCandidateProfileAsAgentProfile, K as applyExactAgentProfileDiff, S as CANDIDATE_TRACE_TAGS, Y as freezeGenericAgentCandidateProfile, Z as omitUndefinedObjectFields, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, n as executePreparedAgentCandidate, q as assertCandidateProfileBinding, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, t as prepareAgentCandidateExecution, tt as parseExactCandidateProfile, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "../prepare-BxP7Hq1l.js";
2
+ import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "../workspace-archive-BwJQSvGi.js";
3
+ import { a as buildAgentCandidateBundle, i as FileAgentCandidateExecutionClaimStore, n as runProtectedAgentCandidateModelGrant, r as disposePreparedAgentCandidateExecution, t as recoverExpiredAgentCandidateExecution } from "../candidate-execution-CWMkOz7g.js";
4
+ import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-B82zDDu5.js";
5
5
  export { AGENT_CANDIDATE_EXECUTION_SUPPORT, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, FileAgentCandidateExecutionClaimStore, InMemoryAgentCandidateExecutionClaimStore, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateExecutionClaim, candidateKnowledgeExecutionPaths, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, omitUndefinedObjectFields, parseExactAgentProfile, parseExactAgentProfileDiff, parseExactCandidateProfile, persistCandidateOutputArtifact, prepareAgentCandidateExecution, recoverExpiredAgentCandidateExecution, runProtectedAgentCandidateModelGrant, sealAgentCandidateBundle, verifyAgentCandidateBundle };
@@ -1,6 +1,6 @@
1
- import { $ as parseExactAgentProfile, B as rejectedStage, F as assertTerminalAllowedInPhase, H as sealTerminalDigest, I as assertTerminalMatchesClaim, K as applyExactAgentProfileDiff, L as assertTerminalMatchesStaged, M as candidateCleanupTimeout, N as withinCandidateCleanupDeadline, O as readVerifiedArtifact, P as assertRecoveryMatchesStaged, R as recoveredTerminalRecord, U as terminalRecord, V as requireStagedTerminal, Y as freezeGenericAgentCandidateProfile, a as persistCandidateOutputArtifact, b as consumePreparedCandidateExecution, et as parseExactAgentProfileDiff, g as candidateClaimFileInternals, i as persistCandidateModelSettlementEvidence, j as candidateCleanupDeadline, nt as canonicalCandidateBytes, o as sealAgentCandidateExecutorStopAcknowledgement, ot as embeddedCandidateArtifact, p as sealAgentCandidateModelSettlement, r as RecoveryAgentCandidateTraceStore, tt as parseExactCandidateProfile, v as assertPreparedCandidateIntegrity, y as beginPreparedCandidateDisposal, z as rejectedFinish } from "./prepare-DUbH3GD5.js";
2
- import { i as sealAgentCandidateBundle } from "./workspace-archive-WEbaLREb.js";
3
- import "./protected-model-port-DP7MS63a.js";
1
+ import { $ as parseExactAgentProfile, B as rejectedStage, F as assertTerminalAllowedInPhase, H as sealTerminalDigest, I as assertTerminalMatchesClaim, K as applyExactAgentProfileDiff, L as assertTerminalMatchesStaged, M as candidateCleanupTimeout, N as withinCandidateCleanupDeadline, O as readVerifiedArtifact, P as assertRecoveryMatchesStaged, R as recoveredTerminalRecord, U as terminalRecord, V as requireStagedTerminal, Y as freezeGenericAgentCandidateProfile, a as persistCandidateOutputArtifact, b as consumePreparedCandidateExecution, et as parseExactAgentProfileDiff, g as candidateClaimFileInternals, i as persistCandidateModelSettlementEvidence, j as candidateCleanupDeadline, nt as canonicalCandidateBytes, o as sealAgentCandidateExecutorStopAcknowledgement, ot as embeddedCandidateArtifact, p as sealAgentCandidateModelSettlement, r as RecoveryAgentCandidateTraceStore, tt as parseExactCandidateProfile, v as assertPreparedCandidateIntegrity, y as beginPreparedCandidateDisposal, z as rejectedFinish } from "./prepare-BxP7Hq1l.js";
2
+ import { i as sealAgentCandidateBundle } from "./workspace-archive-BwJQSvGi.js";
3
+ import "./protected-model-port-B82zDDu5.js";
4
4
  import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
5
5
  import { agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema } from "@tangle-network/agent-interface";
6
6
  import { randomUUID } from "node:crypto";
@@ -573,4 +573,4 @@ function parseCanonicalBytes(bytes, label) {
573
573
  //#endregion
574
574
  export { buildAgentCandidateBundle as a, FileAgentCandidateExecutionClaimStore as i, runProtectedAgentCandidateModelGrant as n, disposePreparedAgentCandidateExecution as r, recoverExpiredAgentCandidateExecution as t };
575
575
 
576
- //# sourceMappingURL=candidate-execution-_u2HIWeX.js.map
576
+ //# sourceMappingURL=candidate-execution-CWMkOz7g.js.map