@tangle-network/agent-runtime 0.173.0 → 0.174.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { at as canonicalCandidateDocument, ct as immutableCandidateValue, dt as verifyCanonicalCandidateDocument, it as canonicalCandidateDigest$1 } from "./prepare-BAyaNoZu.js";
2
- import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-lP-F7B60.js";
2
+ import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-BZH9dewp.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-DkZiIzqK.js.map
204
+ //# sourceMappingURL=activation-DQo7-oIF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-DkZiIzqK.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,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AI,OAAO,QAAQ,WAAW,WAAW;EACvC,IACE,OAAO,QAAQ,QAAQ,MACpB,WAAW,OAAO,gBAAgB,QAAQ,IAAI,eAAe,MAAM,CAAC,CACvE,GAEA,MAAM,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-DQo7-oIF.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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AAe,MAAM,CAAC,CACvE,GAEA,MAAM,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"}
@@ -12,11 +12,78 @@ import { campaignScenarioIdentity, campaignSplitDigestFromIdentities, compareOpt
12
12
  import { createHash, randomUUID } from "node:crypto";
13
13
  import { basename, join, resolve } from "node:path";
14
14
  import { realpath } from "node:fs/promises";
15
- import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
15
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
16
16
  import { spawnSync } from "node:child_process";
17
+ import { tmpdir } from "node:os";
17
18
  import { isDeepStrictEqual } from "node:util";
18
19
  import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
19
20
  import { measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, runAgentProfileImprovementExperiment, runCandidateExperiment, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateExperiment, selfImprove, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison } from "@tangle-network/agent-eval/contract";
21
+ //#region src/improvement/worktree-tree.ts
22
+ /**
23
+ * The exact content of a candidate worktree, as a Git tree object.
24
+ *
25
+ * A multi-shot candidate edits ONE directory in place, so the tree a shot
26
+ * produced is gone as soon as the next shot writes over it. Writing that
27
+ * content into the object store is what makes an earlier tree recoverable:
28
+ * `agenticGenerator` snapshots a tree that verified, and puts it back when a
29
+ * later shot ends the budget on a worse one.
30
+ *
31
+ * The snapshot stages into a PRIVATE index file, so the index the driver later
32
+ * commits from is untouched.
33
+ */
34
+ /** Write the worktree's current content into the object store and return its tree id. */
35
+ function snapshotWorktreeTree(worktreePath) {
36
+ const scratch = mkdtempSync(join(tmpdir(), "agentic-generator-tree-"));
37
+ const indexFile = join(scratch, "index");
38
+ try {
39
+ git(worktreePath, ["read-tree", "HEAD"], indexFile);
40
+ git(worktreePath, ["add", "--all"], indexFile);
41
+ return git(worktreePath, ["write-tree"], indexFile);
42
+ } finally {
43
+ rmSync(scratch, {
44
+ recursive: true,
45
+ force: true
46
+ });
47
+ }
48
+ }
49
+ /**
50
+ * Put a snapshotted tree back into the worktree, then prove the directory
51
+ * holds exactly that tree.
52
+ *
53
+ * The proof is not ceremony: a restore that lands the wrong bytes ships the
54
+ * wrong candidate, and every artifact downstream still reads as though the
55
+ * best tree shipped.
56
+ */
57
+ function restoreWorktreeTree(worktreePath, tree) {
58
+ git(worktreePath, [
59
+ "read-tree",
60
+ "-u",
61
+ "--reset",
62
+ tree
63
+ ]);
64
+ git(worktreePath, [
65
+ "clean",
66
+ "--force",
67
+ "-d",
68
+ "--quiet"
69
+ ]);
70
+ const restored = snapshotWorktreeTree(worktreePath);
71
+ if (restored !== tree) throw new Error(`agenticGenerator: restoring tree ${tree} into ${worktreePath} produced ${restored}`);
72
+ }
73
+ function git(cwd, args, indexFile) {
74
+ const env = { ...process.env };
75
+ if (indexFile) env.GIT_INDEX_FILE = indexFile;
76
+ else delete env.GIT_INDEX_FILE;
77
+ const result = spawnSync("git", args, {
78
+ cwd,
79
+ encoding: "utf-8",
80
+ env
81
+ });
82
+ if (result.error) throw new Error(`agenticGenerator: git ${args[0]} failed to spawn in ${cwd}: ${result.error.message}`);
83
+ if (result.status !== 0) throw new Error(`agenticGenerator: git ${args[0]} exited ${result.status} in ${cwd}: ${result.stderr.trim()}`);
84
+ return result.stdout.trim();
85
+ }
86
+ //#endregion
20
87
  //#region src/improvement/agentic-generator.ts
21
88
  /**
22
89
  *
@@ -43,10 +110,20 @@ import { measuredComparisonFromAgentProfileImprovementExperiment, measuredCompar
43
110
  * (the worktree persists, so the harness RESUMES atop its own failing
44
111
  * edits with the error in hand — no session-specific retry path needed)
45
112
  * - dirty + `verify` ok (or no verifier configured) → return the candidate
113
+ * - dirty + `verify` ok + `keepGoing` → bank the tree and spend the next shot
46
114
  * A candidate that never verifies within `maxShots` is discarded (`applied:
47
115
  * false`), never shipped — if you configured a verifier, a non-passing tree is
48
116
  * not a candidate. With no verifier, the first dirty shot is the candidate.
49
117
  *
118
+ * BEST-OF-N is the `keepGoing` path, and the loop owns it end to end. A
119
+ * verifier that passes a tree and asks for another shot has its tree
120
+ * snapshotted as a Git tree object; when the budget ends, the highest-`score`
121
+ * tree is RESTORED into the worktree and returned as the candidate. So the
122
+ * caller ranks and the loop moves the bytes — a caller never has to write a
123
+ * passing tree back itself. The budget ends on the last shot, or earlier on a
124
+ * `keepGoing`-less pass, and a last shot that broke or reverted the change does
125
+ * not cost the candidate the verified tree an earlier shot produced.
126
+ *
50
127
  * @stable
51
128
  */
52
129
  const RAW_TRACE_ANALYST_ID = "raw-trace-distiller";
@@ -77,8 +154,31 @@ function agenticGenerator(opts) {
77
154
  const needsRawTraceEvidence = requiresRawTraceEvidence(findings);
78
155
  const shots = Math.max(1, maxShots);
79
156
  let attemptNote = "";
157
+ let best = null;
158
+ let scored = null;
159
+ let lastReceipt = null;
160
+ /** Ship the best tree this candidate produced, restoring it when a later
161
+ * shot wrote over it. */
162
+ const shipBankedTree = async (receipt, banked) => {
163
+ const restoredFromShot = banked.onDisk ? null : banked.shot;
164
+ if (!banked.onDisk) {
165
+ if (banked.tree === null) throw new Error(`agenticGenerator: shot ${banked.shot} produced the best tree but it was never snapshotted`);
166
+ restoreWorktreeTree(worktreePath, banked.tree);
167
+ banked.onDisk = true;
168
+ }
169
+ signal.throwIfAborted();
170
+ await emitShotDisposition(opts.onShotDisposition, receipt, {
171
+ kind: "accepted",
172
+ worktreePath,
173
+ verified: true,
174
+ restoredFromShot
175
+ });
176
+ signal.throwIfAborted();
177
+ return acceptedCandidate(findings);
178
+ };
80
179
  for (let shot = 0; shot < shots; shot++) {
81
180
  signal.throwIfAborted();
181
+ if (best) best.onDisk = false;
82
182
  const taskPrompt = attemptNote ? `${basePrompt}\n\n${attemptNote}` : basePrompt;
83
183
  const startedAt = /* @__PURE__ */ new Date();
84
184
  let turn = null;
@@ -144,6 +244,7 @@ function agenticGenerator(opts) {
144
244
  costReceipt,
145
245
  error: shotError
146
246
  });
247
+ lastReceipt = receipt;
147
248
  await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError);
148
249
  signal.throwIfAborted();
149
250
  if (!execution) throw new Error("agenticGenerator: author shot completed without a Runtime turn");
@@ -190,7 +291,8 @@ function agenticGenerator(opts) {
190
291
  await emitShotDisposition(opts.onShotDisposition, receipt, {
191
292
  kind: "accepted",
192
293
  worktreePath,
193
- verified: false
294
+ verified: false,
295
+ restoredFromShot: null
194
296
  });
195
297
  signal.throwIfAborted();
196
298
  return acceptedCandidate(findings);
@@ -205,14 +307,35 @@ function agenticGenerator(opts) {
205
307
  return rethrowShotSetupError(opts.onShotDisposition, receipt, worktreePath, "verification", cause);
206
308
  }
207
309
  if (result.ok) {
310
+ const score = admittedScore(result, scored, shot);
311
+ scored = score !== null;
312
+ const previousBest = best;
313
+ let banked;
314
+ if (previousBest === null || (score ?? 0) >= (previousBest.score ?? 0)) banked = {
315
+ shot: shot + 1,
316
+ score,
317
+ tree: null,
318
+ onDisk: true
319
+ };
320
+ else banked = previousBest;
321
+ const becomesBest = banked !== previousBest;
322
+ best = banked;
323
+ if (result.keepGoing !== true) {
324
+ signal.throwIfAborted();
325
+ return await shipBankedTree(receipt, banked);
326
+ }
327
+ if (becomesBest && shot < shots - 1) banked.tree = snapshotWorktreeTree(worktreePath);
208
328
  signal.throwIfAborted();
209
329
  await emitShotDisposition(opts.onShotDisposition, receipt, {
210
- kind: "accepted",
330
+ kind: "kept",
211
331
  worktreePath,
212
- verified: true
332
+ score,
333
+ best: becomesBest,
334
+ feedback: result.feedback ?? null
213
335
  });
214
336
  signal.throwIfAborted();
215
- return acceptedCandidate(findings);
337
+ attemptNote = keptNote(result.feedback);
338
+ continue;
216
339
  }
217
340
  signal.throwIfAborted();
218
341
  await emitShotDisposition(opts.onShotDisposition, receipt, {
@@ -224,6 +347,10 @@ function agenticGenerator(opts) {
224
347
  signal.throwIfAborted();
225
348
  attemptNote = failureNote(result.feedback);
226
349
  }
350
+ if (best !== null) {
351
+ if (!lastReceipt) throw new Error("agenticGenerator: a tree was banked without a shot receipt");
352
+ return await shipBankedTree(lastReceipt, best);
353
+ }
227
354
  return {
228
355
  applied: false,
229
356
  summary: ""
@@ -231,6 +358,14 @@ function agenticGenerator(opts) {
231
358
  }
232
359
  };
233
360
  }
361
+ /** The rank a passing tree carries, refusing a set of trees that cannot be ordered. */
362
+ function admittedScore(result, scored, shot) {
363
+ const has = result.score !== void 0;
364
+ if (scored !== null && has !== scored) throw new Error(`agenticGenerator: verify ${has ? "scored" : "did not score"} the tree from shot ${shot + 1} and ${scored ? "scored" : "did not score"} an earlier passing tree; a scored tree cannot be ranked against an unscored one`);
365
+ if (!has) return null;
366
+ if (typeof result.score !== "number" || !Number.isFinite(result.score)) throw new Error(`agenticGenerator: verify returned a non-finite score (${String(result.score)}) for shot ${shot + 1}`);
367
+ return result.score;
368
+ }
234
369
  async function emitShotReceipt(callback, receipt, execution, primaryError) {
235
370
  try {
236
371
  await callback?.(receipt, execution);
@@ -373,6 +508,18 @@ function failureNote(feedback) {
373
508
  detail ? `Verifier output:\n${truncate$1(detail, 4e3)}` : "No verifier detail was captured."
374
509
  ].join("\n");
375
510
  }
511
+ /** Next-shot feedback when the worktree PASSED and the verifier asked for
512
+ * another shot. The passing tree is banked, so the author is told to improve
513
+ * it rather than protect it — a worse tree cannot cost it the candidate. */
514
+ function keptNote(feedback) {
515
+ const detail = feedback?.trim();
516
+ return [
517
+ "NOTE: your edits are in the working tree and verification PASSED.",
518
+ "Shots remain in this budget — keep improving the change in place, do not revert it.",
519
+ "The best version you produce is the one that ships.",
520
+ detail ? `Verifier output:\n${truncate$1(detail, 4e3)}` : "No verifier detail was captured."
521
+ ].join("\n");
522
+ }
376
523
  function rawTraceEvidenceProblem(worktreePath, findings) {
377
524
  if (worktreeChangedPaths(worktreePath).filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH).length === 0) return [`NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`, "Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change."].join("\n");
378
525
  const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH);
@@ -3080,4 +3227,4 @@ function sameOrderedValues(left, right) {
3080
3227
  //#endregion
3081
3228
  export { agentImprovementTargetInput as A, ROLLOUT_POLICY_EXTENSION as B, optimizationActivationReceiptFromMetadata as C, agentImprovementProfileSurfaceDigest as D, agentImprovementProfileDiffs as E, isAgentImprovementProfileSurface as F, structuralRolloutPolicyFromProfile as G, normalizeRolloutPolicy as H, isAgentProfileMeasuredSurface as I, defaultBuildPrompt as J, agenticGenerator as K, improve as L, agentProfileImprovementStateDigest as M, assertProfileImprovementTargetsShareIdentity as N, agentImprovementProfileSurfaceInput as O, buildAgentImprovementActivationTargets as P, withMethodRuntimeControls as R, createOptimizationActivationReceipt as S, AGENT_PROFILE_MEASURED_SURFACES as T, parseRolloutPolicy as U, applyRolloutPolicyToProfile as V, serializeRolloutPolicy as W, profilePolicyWithBudget as _, executeAgentCandidateExperimentCell as a, profileTaskScenarioIdentity as b, requireSealedCandidateExperiment as c, verifyAgentImprovementActivation as d, verifyAgentImprovementProposal as f, profileImprovementMetadata as g, createProfileImprovementCostLedger as h, createAgentImprovementProposal as i, agentImprovementTargetProfileDiffs as j, agentImprovementTargetDigest as k, reviewAgentImprovementProposal as l, verifyCandidateExecutionEvidence as m, createAgentImprovementActivation as n, proposeAgentImprovement as o, verifyAgentImprovementReview as p, commandVerifier as q, createAgentImprovementMeasuredComparison as r, proposeAgentProfileImprovement as s, AgentCandidateExperimentCellExecutionError as t, runAgentCandidateExperiment as u, profilePreparationAccounting as v, AGENT_IMPROVEMENT_PROFILE_SURFACES as w, sealProfileImprovementBenchmark as x, profileStateDigest as y, rawTraceDistiller as z };
3082
3229
 
3083
- //# sourceMappingURL=improvement-cycle-lP-F7B60.js.map
3230
+ //# sourceMappingURL=improvement-cycle-BZH9dewp.js.map