@tangle-network/agent-runtime 10.0.22 → 10.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 10.0.23
2
+
3
+ Code improvement uses `budget.candidateConcurrency` to generate candidates in parallel in isolated worktrees, joins started generators on failure, and keeps proposal order stable.
4
+
5
+ Reflective profile search can produce several distinct candidate surfaces per priced proposal when `childrenPerProposal` requests it.
6
+
7
+ Native profile searches can reuse verified proposal and training records from earlier searches without exposing their final evaluations.
8
+
1
9
  ## 10.0.22
2
10
 
3
11
  `report_blocked` on a name that is not one of the caller's coordination tools now says the coordinator cannot run it for the caller. If the name is a tool of the caller's own harness (`bash`, `read`, `edit` and the like), the reply tells the caller to run it again itself and to keep the exact command and its output in its pages or its turn's text. Before, the reply said no tool by that name was served to the caller, which told a worker that had just run its own `bash` that the tool did not exist.
@@ -1,4 +1,4 @@
1
- import { By as OtelExportConfig, Lh as ExecutorConfig, is as CollectedAgentTurn, og as SharedBoxPlacement, qp as BudgetPool, rs as AgentTurnUsage, sg as SharedBoxPlacementOptions, si as ReadonlyAgentProfile, yf as WorkerSlots } from "./types-3p2eAICm.js";
1
+ import { By as OtelExportConfig, Lh as ExecutorConfig, Sf as WorkerSlots, Xp as BudgetPool, og as SharedBoxPlacement, os as AgentTurnUsage, sg as SharedBoxPlacementOptions, ss as CollectedAgentTurn, ui as ReadonlyAgentProfile } from "./types-Pi5uCS88.js";
2
2
  import { AgentCandidateBundle, AgentCandidateExperiment, AgentImprovementActivation, AgentImprovementActivationIntent, AgentImprovementActivationOutcome, AgentImprovementActivationResult, AgentImprovementActivationTarget, AgentImprovementEvaluation, AgentImprovementProposal, AgentImprovementReview, AgentImprovementReviewDecision, AgentImprovementSurface, AgentProfile, AgentProfileDiff, AgentProfileImprovementChange, AgentProfileImprovementExecutionRef, AgentProfileImprovementExperiment, AgentTrainingReceipt, HarnessType, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
3
3
  import { CostLedgerHandle, CostReceiptInput, MaximumCharge, PairedPromotionDecision, PendingCostCallView, ProposalFinding, RunRecord } from "@tangle-network/agent-eval";
4
4
  import { ProposalFinding as ProposalFinding$1 } from "@tangle-network/agent-eval/analyst";
@@ -19,6 +19,7 @@ interface CandidateGenerator {
19
19
  * patch to draft, so the driver short-circuits rather than spin up worktrees
20
20
  * for a guaranteed no-op. Default `false`. */
21
21
  proposesWithoutFindings?: boolean;
22
+ /** Parallel calls receive distinct worktrees and share the campaign cost account. */
22
23
  generate(args: {
23
24
  /** The candidate worktree — a clean checkout of the current incumbent. */
24
25
  worktreePath: string;
@@ -302,6 +303,16 @@ interface SearchCellContext {
302
303
  type SearchTraceOptions = 'off' | {
303
304
  readonly otlp: OtelExportConfig;
304
305
  };
306
+ /** Earlier searches this proposer may learn from, ordered from oldest to newest. */
307
+ interface SearchImprovementMemoryOptions {
308
+ readonly receipts: readonly SearchHistoryReceipt[];
309
+ /** Maximum number of earlier attempts in the proposal prompt. Default 8. */
310
+ readonly maxAttempts?: number;
311
+ /** Only accept searches closed by this campaign's start, as epoch milliseconds. */
312
+ readonly notAfter?: number;
313
+ /** Storage holding earlier ledgers and blobs. Defaults to the current campaign's storage. */
314
+ readonly storage?: Pick<CampaignStorage, 'read'>;
315
+ }
305
316
  /** The executable agent lever `improve` optimizes — every surface a proposal can name
306
317
  * (`AgentImprovementSurface`) except `knowledge`, which the corpus lane owns and `improve`
307
318
  * does not produce. Deriving it means every surface `improve` produces can also be reported, which
@@ -397,6 +408,10 @@ interface ImproveSearchMethod {
397
408
  readonly policy: SearchPolicy;
398
409
  readonly allocation: SearchAllocator;
399
410
  readonly proposer: SurfaceProposer<ProposalFinding>;
411
+ /** Verified prior searches that can supply train evidence for proposals. */
412
+ readonly memory?: SearchImprovementMemoryOptions & {
413
+ readonly maxAttempts: number;
414
+ };
400
415
  /** Proposals the search may make. */
401
416
  readonly maxExpansions: number;
402
417
  /** Children one proposal asks for. */
@@ -457,7 +472,8 @@ type ImproveSearchAgent<TScenario extends Scenario$1, TArtifact> = (profile: Rea
457
472
  /** Runtime-owned code search in isolated git worktrees. */
458
473
  type ImproveCodeRunOptions<TScenario extends Scenario$1, TArtifact> = Omit<SelfImproveOptions<TScenario, TArtifact>, 'analyzeGeneration' | 'baselineSurface' | 'budget' | 'findings' | 'gate' | 'llm' | 'method' | 'mutationPrimitives' | 'proposer' | 'proposerTarget' | 'selectionScenarios'> & {
459
474
  surface: 'code';
460
- /** Local code-search budget. Method-only selection controls do not apply. */
475
+ /** Local code-search budget. `candidateConcurrency` also bounds parallel
476
+ * worktree generation. Method-only selection controls do not apply. */
461
477
  budget?: Omit<SelfImproveBudget, 'selectionFraction'>;
462
478
  /** Findings supplied to Runtime's code candidate driver. */
463
479
  findings?: ReadonlyArray<ProposalFinding>;
@@ -836,6 +852,8 @@ interface SearchMethodOptions {
836
852
  /** Writes each child surface from the parents the policy chose. It reads the
837
853
  * train split only (`ProposeContext.train` and `summary`); `history` is empty. */
838
854
  proposer: SurfaceProposer<ProposalFinding>;
855
+ /** Earlier closed searches the proposer may learn from. Optional. */
856
+ memory?: SearchImprovementMemoryOptions;
839
857
  /** Proposals the search may make. */
840
858
  maxExpansions: number;
841
859
  /** Which node each proposal extends, and which node the search keeps.
@@ -1065,5 +1083,5 @@ declare function verifyAgentImprovementActivation(input: {
1065
1083
  review: unknown;
1066
1084
  activation: unknown;
1067
1085
  }): AgentImprovementActivation;
1068
- export { ImproveCodeBaseOptions as $, AgentProfileMeasuredSurface as A, SearchPromotion as At, DecideSearchImprovementOptions as B, sharedBoxLane as Bt, verifyAgentImprovementProposal as C, ImproveSearchOptions as Ct, AgentImprovementActivationTargetIdentity as D, ImprovementCodeCandidate as Dt, AGENT_PROFILE_MEASURED_SURFACES as E, ImproveSurface as Et, isAgentImprovementProfileSurface as F, SearchLaneOptions as Ft, ImproveTrainingOptions as G, AgenticGeneratorShotExecution as Gt, decideSearchImprovement as H, AgenticGeneratorExecutorForWorktree as Ht, isAgentProfileMeasuredSurface as I, SearchTraceOptions as It, ProfileTrainerRequest as J, VerifyResult as Jt, ImproveTrainingResult as K, AgenticGeneratorShotReceipt as Kt, improve as L, SharedBoxSearchLane as Lt, agentImprovementProfileSurfaceDigest as M, SearchEnvironmentFault as Mt, agentImprovementProfileSurfaceInput as N, SearchLane$1 as Nt, AgentImprovementProfileSurface as O, ImprovementProfileCandidate as Ot, agentImprovementTargetProfileDiffs as P, SearchLaneKind as Pt, ImproveCandidateValidator as Q, SearchMethodOptions as R, dedicatedLane as Rt, verifyAgentImprovementActivationResult as S, ImproveSearchMethod as St, AGENT_IMPROVEMENT_PROFILE_SURFACES as T, ImproveSkillsOptions as Tt, CheckpointServingPort as U, AgenticGeneratorOptions as Ut, SearchImprovementDecision as V, subscriptionLane as Vt, ControlledTrainingCommand as W, AgenticGeneratorShotDisposition as Wt, createCommandProfileTrainer as X, commandVerifier as Xt, TrainingBoundaryResult as Y, agenticGenerator as Yt, ImproveCandidateValidationInput as Z, CandidateGenerator as Zt, createAgentImprovementActivationResult as _, ImproveResult as _t, AgentImprovementActivationTransitionInput as a, ImproveLineage as at, reviewAgentImprovementProposal as b, ImproveSearchAgent as bt, CreateAgentImprovementActivationOptions as c, ImproveMethodLineage as ct, ExecuteAgentImprovementActivationInput as d, ImproveMethodSource as dt, ImproveCodeOptions as et, ExecuteAgentImprovementActivationOptions as f, ImproveOptimizationRunOptions as ft, createAgentImprovementActivation as g, ImproveProfileSurface as gt, SealedCandidateActivationTransitionInput as h, ImproveProfileComponents as ht, AgentImprovementActivationTransition as i, ImproveCustomCodeGeneratorOptions as it, agentImprovementProfileDiffs as j, SearchCellContext as jt, AgentImprovementTargetProfileDiffOptions as k, SearchDispatchContext as kt, CreateAgentImprovementActivationResultOptions as l, ImproveMethodOptions as lt, ReviewAgentImprovementInput as m, ImproveProfileAgent as mt, AgentImprovementActivationResultStore as n, ImproveCodeRunOptions as nt, AgentProfileImprovementActivationOperation as o, ImproveMethodContext as ot, ProfileImprovementActivationTransitionInput as p, ImproveOptions as pt, ProfileTrainer as q, Verifier as qt, AgentImprovementActivationTargetPlan as r, ImproveCost as rt, AgentProfileImprovementActivationTargetPlan as s, ImproveMethodFactory as st, AgentImprovementActivationReconciliation as t, ImproveCodeResult as tt, CreateAgentImprovementProposalOptions as u, ImproveMethodResult as ut, createAgentImprovementProposal as v, ImproveRuntimeCodeGeneratorOptions as vt, verifyAgentImprovementReview as w, ImproveSearchResult as wt, verifyAgentImprovementActivation as x, ImproveSearchIdentity as xt, executeAgentImprovementActivation as y, ImproveScenarioPartitions as yt, searchMethod as z, routerLane as zt };
1069
- //# sourceMappingURL=activation-BSRRW51N.d.ts.map
1086
+ export { ImproveCodeBaseOptions as $, AgentProfileMeasuredSurface as A, SearchPromotion as At, DecideSearchImprovementOptions as B, routerLane as Bt, verifyAgentImprovementProposal as C, ImproveSearchOptions as Ct, AgentImprovementActivationTargetIdentity as D, ImprovementCodeCandidate as Dt, AGENT_PROFILE_MEASURED_SURFACES as E, ImproveSurface as Et, isAgentImprovementProfileSurface as F, SearchLaneKind as Ft, ImproveTrainingOptions as G, AgenticGeneratorShotDisposition as Gt, decideSearchImprovement as H, subscriptionLane as Ht, isAgentProfileMeasuredSurface as I, SearchLaneOptions as It, ProfileTrainerRequest as J, Verifier as Jt, ImproveTrainingResult as K, AgenticGeneratorShotExecution as Kt, improve as L, SearchTraceOptions as Lt, agentImprovementProfileSurfaceDigest as M, SearchCellContext as Mt, agentImprovementProfileSurfaceInput as N, SearchEnvironmentFault as Nt, AgentImprovementProfileSurface as O, ImprovementProfileCandidate as Ot, agentImprovementTargetProfileDiffs as P, SearchLane$1 as Pt, ImproveCandidateValidator as Q, CandidateGenerator as Qt, SearchMethodOptions as R, SharedBoxSearchLane as Rt, verifyAgentImprovementActivationResult as S, ImproveSearchMethod as St, AGENT_IMPROVEMENT_PROFILE_SURFACES as T, ImproveSkillsOptions as Tt, CheckpointServingPort as U, AgenticGeneratorExecutorForWorktree as Ut, SearchImprovementDecision as V, sharedBoxLane as Vt, ControlledTrainingCommand as W, AgenticGeneratorOptions as Wt, createCommandProfileTrainer as X, agenticGenerator as Xt, TrainingBoundaryResult as Y, VerifyResult as Yt, ImproveCandidateValidationInput as Z, commandVerifier as Zt, createAgentImprovementActivationResult as _, ImproveResult as _t, AgentImprovementActivationTransitionInput as a, ImproveLineage as at, reviewAgentImprovementProposal as b, ImproveSearchAgent as bt, CreateAgentImprovementActivationOptions as c, ImproveMethodLineage as ct, ExecuteAgentImprovementActivationInput as d, ImproveMethodSource as dt, ImproveCodeOptions as et, ExecuteAgentImprovementActivationOptions as f, ImproveOptimizationRunOptions as ft, createAgentImprovementActivation as g, ImproveProfileSurface as gt, SealedCandidateActivationTransitionInput as h, ImproveProfileComponents as ht, AgentImprovementActivationTransition as i, ImproveCustomCodeGeneratorOptions as it, agentImprovementProfileDiffs as j, SearchImprovementMemoryOptions as jt, AgentImprovementTargetProfileDiffOptions as k, SearchDispatchContext as kt, CreateAgentImprovementActivationResultOptions as l, ImproveMethodOptions as lt, ReviewAgentImprovementInput as m, ImproveProfileAgent as mt, AgentImprovementActivationResultStore as n, ImproveCodeRunOptions as nt, AgentProfileImprovementActivationOperation as o, ImproveMethodContext as ot, ProfileImprovementActivationTransitionInput as p, ImproveOptions as pt, ProfileTrainer as q, AgenticGeneratorShotReceipt as qt, AgentImprovementActivationTargetPlan as r, ImproveCost as rt, AgentProfileImprovementActivationTargetPlan as s, ImproveMethodFactory as st, AgentImprovementActivationReconciliation as t, ImproveCodeResult as tt, CreateAgentImprovementProposalOptions as u, ImproveMethodResult as ut, createAgentImprovementProposal as v, ImproveRuntimeCodeGeneratorOptions as vt, verifyAgentImprovementReview as w, ImproveSearchResult as wt, verifyAgentImprovementActivation as x, ImproveSearchIdentity as xt, executeAgentImprovementActivation as y, ImproveScenarioPartitions as yt, searchMethod as z, dedicatedLane as zt };
1087
+ //# sourceMappingURL=activation-DOzkzTrl.d.ts.map
package/dist/agent.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as RuntimeStreamEvent, UC as AgentRunSpec, fw as OutputAdapter, mw as SandboxClient } from "./types-3p2eAICm.js";
1
+ import { S as RuntimeStreamEvent, UC as AgentRunSpec, fw as OutputAdapter, mw as SandboxClient } from "./types-Pi5uCS88.js";
2
2
  import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as validateSurfaces } from "./improvement-adapter-D5GRU1eY.js";
3
3
  import { a as ProfileMaterializationContract, c as assertProfileMaterializes, n as AssertProfileMaterializationOptions, o as ProfileMaterializationIssue, r as DefineProfileMaterializationContractOptions, s as ValidateProfileMaterializationOptions, t as AgentProfileMaterializationAxis } from "./profile-materialization-BRY22Oh8.js";
4
4
  import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
package/dist/durable.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $d as PursuitProjection, $m as CoordinationRejectReason, Ab as QuestionEscalationOutcome, Ad as NextPursuitVersion, Bb as AuthorizedDownMessage, Bd as SupervisePursuitError, Ca as RootStreamReceipt, Db as EscalateQuestion, F as NodeId, Fd as SettledPursuitVersion, Gd as RunReopen, Gm as CoordinationAuthentication, Gp as RunParkingRecord, Hb as ContinuityMode, Hd as SupervisedPursuitResult, Hp as ParkedRun, Id as VersionJudge, Jd as PursuitNodeCost, Jm as CoordinationPublicAddress, Kd as PursuitObserverDelivery, Kp as readRunParking, Ld as VersionVerdict, Md as PursuitVersionChain, Nd as PursuitVersionStop, Pd as PursuitVersions, Qd as PursuitNodeUsage, Qm as CoordinationHttpAudit, Rd as assertPursuitVersions, Ub as DownMessageAuthorizationInput, Ud as superviseGraphPursuit, Up as RunParkedError, Vd as SupervisePursuitOptions, Vp as DeadlineCheckIn, Wd as supervisePursuit, Wp as RunParkingPolicy, Xd as PursuitNodeProjection, Xm as CoordinationTransportOptions, Yb as MapOnSettleRoute, Yd as PursuitNodePlatform, Ym as CoordinationReadAccess, Zd as PursuitNodeTiming, _S as readRunState, af as ObserverJournal, am as RootStreamRecord, cf as observerRecordDigest, dS as SpawnJournalReadOptions, dp as SeatSelection, ef as PursuitRunProjection, fS as SpawnJournalReadRecord, fp as SeatSelectionInput, gS as RunState, gb as WorkerWatchOptions, gf as AuthorizedSpawnContext, gm as ResolveDriveHarness, hf as AuthorizedSpawn, if as FileObserverJournal, jd as NextPursuitVersionInput, kd as JudgedPursuitVersion, lf as PursuitFork, mS as readSpawnJournal, mm as DriveHarnessOwnerContext, mp as SelectSeat, nf as PursuitStatus, o_ as ToolLoopCompactionOptions, of as ObserverRecord, om as readRootStream, ow as LoopTokenUsage, pS as SpawnJournalReadResult, q as RetainedPendingCause, qd as PursuitCostProvenance, rf as projectPursuit, sf as ObserverRecordKind, sm as readRootStreamReceipt, tf as PursuitRunTotals, uS as SpawnJournalCursor, uf as RUN_FORK_CORRELATION_KEYS, wa as SupervisedResult, wm as ManagerWakePolicy, yf as WorkerSlots, zd as SuperviseGraphPursuitOptions, zx as AnalyzeOnSettleRoute } from "./types-3p2eAICm.js";
1
+ import { $d as PursuitNodeProjection, $m as CoordinationRejectReason, Ab as QuestionEscalationOutcome, Bb as AuthorizedDownMessage, Bd as VersionVerdict, Da as SupervisedResult, Db as EscalateQuestion, Ea as RootStreamReceipt, F as NodeId, Fd as PursuitVersionChain, Gd as SupervisedPursuitResult, Gm as CoordinationAuthentication, Gp as ParkedRun, Hb as ContinuityMode, Hd as SuperviseGraphPursuitOptions, Id as PursuitVersionStop, Jd as RunReopen, Jm as CoordinationPublicAddress, Jp as RunParkingRecord, Kd as superviseGraphPursuit, Kp as RunParkedError, Ld as PursuitVersions, Md as JudgedPursuitVersion, Nd as NextPursuitVersion, Pd as NextPursuitVersionInput, Qd as PursuitNodePlatform, Qm as CoordinationHttpAudit, Rd as SettledPursuitVersion, Sf as WorkerSlots, Ub as DownMessageAuthorizationInput, Ud as SupervisePursuitError, Vd as assertPursuitVersions, Wd as SupervisePursuitOptions, Wp as DeadlineCheckIn, Xd as PursuitCostProvenance, Xm as CoordinationTransportOptions, Yb as MapOnSettleRoute, Yd as PursuitObserverDelivery, Ym as CoordinationReadAccess, Yp as readRunParking, Zd as PursuitNodeCost, _S as readRunState, _p as SelectSeat, af as PursuitStatus, cf as ObserverJournal, dS as SpawnJournalReadOptions, df as observerRecordDigest, dr as readRootStream, ef as PursuitNodeTiming, fS as SpawnJournalReadRecord, ff as PursuitFork, fr as readRootStreamReceipt, gS as RunState, gb as WorkerWatchOptions, gm as ResolveDriveHarness, hp as SeatSelectionInput, if as PursuitRunTotals, lf as ObserverRecord, mS as readSpawnJournal, mm as DriveHarnessOwnerContext, mp as SeatSelection, nf as PursuitProjection, o_ as ToolLoopCompactionOptions, of as projectPursuit, ow as LoopTokenUsage, pS as SpawnJournalReadResult, pf as RUN_FORK_CORRELATION_KEYS, q as RetainedPendingCause, qd as supervisePursuit, qp as RunParkingPolicy, rf as PursuitRunProjection, sf as FileObserverJournal, tf as PursuitNodeUsage, uS as SpawnJournalCursor, uf as ObserverRecordKind, ur as RootStreamRecord, vf as AuthorizedSpawn, wm as ManagerWakePolicy, yf as AuthorizedSpawnContext, zd as VersionJudge, zx as AnalyzeOnSettleRoute } from "./types-Pi5uCS88.js";
2
2
  import { n as RuntimeDecisionKind, r as RuntimeDecisionPoint, t as RuntimeDecisionEvidenceRef } from "./runtime-hooks-DPghSHV7.js";
3
3
  import { a as ChatTurnProducer, c as handleChatTurn, i as ChatTurnIdentity, n as ChatStreamEvent, o as ChatTurnResult, r as ChatTurnHooks, s as RunChatTurnInput, t as deriveExecutionId } from "./execution-handle-CujvqgCn.js";
4
4
  import { AgentProfile } from "@tangle-network/agent-interface";
@@ -2,6 +2,7 @@ import { i as ConfigError } from "./errors-DG8yufqX.js";
2
2
  import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-BLflx9cs.js";
3
3
  import { C as linkAbort, w as runAbortable, y as sha256 } from "./jsonl-file-B2ESMrTh.js";
4
4
  import { o as armDeadlineTimer } from "./deadline-CySmJ_0S.js";
5
+ import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
5
6
  import { n as detachedSnapshot } from "./snapshot-BKLziJ5K.js";
6
7
  import { Et as terminateProcessTreeAndConfirm, St as runSettledCommand, w as createExecutor } from "./supervisor-DL4hO7UW.js";
7
8
  import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-DFuhCC0-.js";
@@ -18,8 +19,9 @@ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
18
19
  import { spawn, spawnSync } from "node:child_process";
19
20
  import { chmod, mkdir, mkdtemp, open, realpath, rm, writeFile } from "node:fs/promises";
20
21
  import { tmpdir } from "node:os";
22
+ import { fileURLToPath } from "node:url";
21
23
  import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
22
- import { SearchRecorder, aide, asha, campaignCellSearchResult, campaignScenarioIdentity, campaignSplitDigestFromIdentities, captureFinalEvidencePolicy, compareOptimizationMethods, createRunCostLedger, fsCampaignStorage, gitWorktreeAdapter, isProposedCandidate, openSearchLedger, prepareSearchFinalEvidence, renderSearchSummary, resolveRunDir, runCampaign, runSearch, searchClaimReserveUsd, searchNodeId, searchProposalExecution, searchProposerView, searchReceiptAccounting, verifyCodeSurface, verifySearchHistoryArtifact } from "@tangle-network/agent-eval/campaign";
24
+ import { SearchRecorder, aide, asha, campaignCellSearchResult, campaignScenarioIdentity, campaignSplitDigestFromIdentities, captureFinalEvidencePolicy, compareOptimizationMethods, createRunCostLedger, estimateNode, fsCampaignStorage, gitWorktreeAdapter, isProposedCandidate, openSearchLedger, prepareSearchFinalEvidence, renderSearchSummary, replaySearchLedgerText, resolveRunDir, runCampaign, runSearch, searchClaimReserveUsd, searchNodeId, searchProposalExecution, searchProposerView, searchReceiptAccounting, verifyCodeSurface, verifySearchHistoryArtifact, verifySearchHistoryReceipt } from "@tangle-network/agent-eval/campaign";
23
25
  import { selfImprove } from "@tangle-network/agent-eval/contract";
24
26
  import { defineEvaluationClaim, summarizeEvaluationUnits } from "@tangle-network/agent-eval/experiment";
25
27
  // src/runtime-usage.ts
@@ -724,69 +726,95 @@ function copyImproveCost(cost) {
724
726
  /** Build the code-only proposer used internally by `improve({ surface: 'code' })`. */
725
727
  function improvementDriver(opts) {
726
728
  const baseRef = opts.baseRef ?? "main";
729
+ const concurrency = opts.candidateConcurrency ?? 1;
730
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new ConfigError("improve(): candidateConcurrency must be a positive safe integer");
727
731
  const owned = /* @__PURE__ */ new Map();
732
+ async function discardWhere(predicate) {
733
+ const errors = [];
734
+ for (const [worktree, ref] of owned) {
735
+ if (!predicate(worktree, ref)) continue;
736
+ try {
737
+ await opts.worktree.discard(worktree);
738
+ owned.delete(worktree);
739
+ } catch (cause) {
740
+ errors.push(cause);
741
+ }
742
+ }
743
+ if (errors.length > 0) throw new AggregateError(errors, "improvementDriver: failed to discard candidate worktrees");
744
+ }
728
745
  return {
729
746
  kind: `improvement:${opts.generator.kind}`,
730
747
  async propose(ctx) {
731
748
  const findings = ctx.findings;
732
- if (findings.length === 0 && !opts.generator.proposesWithoutFindings) return [];
749
+ if (ctx.signal.aborted || findings.length === 0 && !opts.generator.proposesWithoutFindings) return [];
733
750
  const surfaces = [];
734
751
  const incumbent = verifiedCodeIncumbent(ctx.currentSurface);
735
752
  const proposalBaseRef = incumbent?.baseCommit ?? baseRef;
736
- for (let i = 0; i < ctx.populationSize; i++) {
737
- if (ctx.signal.aborted) break;
738
- const wt = await opts.worktree.create({
739
- baseRef: proposalBaseRef,
740
- label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`
741
- });
742
- owned.set(wt.path, wt);
743
- try {
744
- if (incumbent) advanceToIncumbent(wt, incumbent);
745
- const { applied, summary, label, rationale } = await opts.generator.generate({
746
- worktreePath: wt.path,
747
- findings,
748
- maxShots: ctx.maxImprovementShots ?? 1,
749
- signal: ctx.signal,
750
- generation: ctx.generation,
751
- candidateIndex: i,
752
- ...ctx.costLedger ? { costLedger: ctx.costLedger } : {},
753
- ...ctx.costPhase ? { costPhase: ctx.costPhase } : {}
754
- });
755
- if (!applied) {
756
- await opts.worktree.discard(wt);
757
- owned.delete(wt.path);
758
- continue;
753
+ const batch = /* @__PURE__ */ new Set();
754
+ const stop = new AbortController();
755
+ const signal = AbortSignal.any([ctx.signal, stop.signal]);
756
+ let next = 0;
757
+ try {
758
+ for await (const result of runTaskQueue({
759
+ concurrency,
760
+ take() {
761
+ if (signal.aborted || next >= ctx.populationSize) return void 0;
762
+ const index = next++;
763
+ return {
764
+ id: String(index),
765
+ value: index
766
+ };
767
+ },
768
+ async execute({ value: index }) {
769
+ signal.throwIfAborted();
770
+ const worktree = await opts.worktree.create({
771
+ baseRef: proposalBaseRef,
772
+ label: `${opts.generator.kind}-gen${ctx.generation}-cand${index}`
773
+ });
774
+ batch.add(worktree);
775
+ owned.set(worktree, worktree.path);
776
+ signal.throwIfAborted();
777
+ if (incumbent) advanceToIncumbent(worktree, incumbent);
778
+ const { applied, summary, label, rationale } = await opts.generator.generate({
779
+ worktreePath: worktree.path,
780
+ findings,
781
+ maxShots: ctx.maxImprovementShots ?? 1,
782
+ signal,
783
+ generation: ctx.generation,
784
+ candidateIndex: index,
785
+ ...ctx.costLedger ? { costLedger: ctx.costLedger } : {},
786
+ ...ctx.costPhase ? { costPhase: ctx.costPhase } : {}
787
+ });
788
+ signal.throwIfAborted();
789
+ if (!applied) {
790
+ await opts.worktree.discard(worktree);
791
+ owned.delete(worktree);
792
+ return;
793
+ }
794
+ const surface = await opts.worktree.finalize(worktree, summary);
795
+ owned.set(worktree, surface.worktreeRef);
796
+ return label || rationale ? {
797
+ surface,
798
+ label: label ?? "",
799
+ rationale: rationale ?? ""
800
+ } : surface;
801
+ }
802
+ })) {
803
+ if (result.status === "rejected") {
804
+ stop.abort(result.reason);
805
+ throw result.reason;
759
806
  }
760
- const surface = await opts.worktree.finalize(wt, summary);
761
- surfaces.push(label || rationale ? {
762
- surface,
763
- label: label ?? "",
764
- rationale: rationale ?? ""
765
- } : surface);
766
- owned.delete(wt.path);
767
- owned.set(surface.worktreeRef, wt);
768
- } catch (err) {
769
- return rethrowAfterCleanup(err, async () => {
770
- await opts.worktree.discard(wt);
771
- owned.delete(wt.path);
772
- }, `improvementDriver: ${err instanceof Error ? err.message : String(err)}`);
807
+ if (result.value) surfaces[result.task.value] = result.value;
773
808
  }
809
+ ctx.signal.throwIfAborted();
810
+ return surfaces.filter(Boolean);
811
+ } catch (cause) {
812
+ return rethrowAfterCleanup(cause, () => discardWhere((worktree) => batch.has(worktree)), `improvementDriver: ${cause instanceof Error ? cause.message : String(cause)}`);
774
813
  }
775
- return surfaces;
776
814
  },
777
815
  async cleanup(retainWorktreeRefs = []) {
778
816
  const retained = new Set(retainWorktreeRefs);
779
- const errors = [];
780
- for (const [worktreeRef, worktree] of owned) {
781
- if (retained.has(worktreeRef)) continue;
782
- try {
783
- await opts.worktree.discard(worktree);
784
- owned.delete(worktreeRef);
785
- } catch (cause) {
786
- errors.push(cause);
787
- }
788
- }
789
- if (errors.length > 0) throw new AggregateError(errors, "improvementDriver: failed to discard candidate worktrees");
817
+ await discardWhere((_worktree, ref) => !retained.has(ref));
790
818
  }
791
819
  };
792
820
  }
@@ -1405,7 +1433,7 @@ async function realRoot(path) {
1405
1433
  }
1406
1434
  }
1407
1435
  /** Create a clean incumbent checkout and the candidate producer for a code run. */
1408
- async function prepareCodeRun(code) {
1436
+ async function prepareCodeRun(code, candidateConcurrency) {
1409
1437
  const authorProfile = agentProfileSchema.parse(code.profile);
1410
1438
  assertExecutableAgentProfile(authorProfile, "improve(code) author");
1411
1439
  const baseRef = code.baseRef ?? "main";
@@ -1430,7 +1458,8 @@ async function prepareCodeRun(code) {
1430
1458
  ...code.timeoutMs !== void 0 ? { timeoutMs: code.timeoutMs } : {},
1431
1459
  ...code.maximumCharge ? { maximumCharge: code.maximumCharge } : {}
1432
1460
  }),
1433
- baseRef
1461
+ baseRef,
1462
+ ...candidateConcurrency === void 0 ? {} : { candidateConcurrency }
1434
1463
  });
1435
1464
  return {
1436
1465
  baseline,
@@ -1476,7 +1505,7 @@ function idempotentDispose(dispose) {
1476
1505
  async function runCodeImprovement(opts) {
1477
1506
  const { gate = "holdout", findings: inputFindings = [], rawTraceContext: _rawTraceContext, code, promotionGate, analyzeGeneration, surface: _surface, ...sharedOptions } = opts;
1478
1507
  const findings = immutableCandidateValue([...assertProposalFindings(inputFindings, "improve() code findings")]);
1479
- const preparedCode = await prepareCodeRun(code);
1508
+ const preparedCode = await prepareCodeRun(code, sharedOptions.budget?.candidateConcurrency);
1480
1509
  const budget = gate === "none" ? {
1481
1510
  ...sharedOptions.budget,
1482
1511
  generations: 0
@@ -2020,6 +2049,86 @@ async function runMethodImprovement(profile, opts) {
2020
2049
  async dispose() {}
2021
2050
  };
2022
2051
  }
2052
+ // src/improvement/search-improvement-memory.ts
2053
+ function captureSearchImprovementMemory(options) {
2054
+ const maxAttempts = options.maxAttempts ?? 8;
2055
+ if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) throw new ConfigError("searchMethod(): memory.maxAttempts must be a positive safe integer");
2056
+ if (options.notAfter !== void 0 && !Number.isSafeInteger(options.notAfter)) throw new ConfigError("searchMethod(): memory.notAfter must be integer epoch milliseconds");
2057
+ const receipts = immutableCandidateValue(options.receipts);
2058
+ for (const receipt of receipts) {
2059
+ verifySearchHistoryReceipt(receipt);
2060
+ if (!receipt.complete) throw new ConfigError("searchMethod(): memory requires closed search history receipts");
2061
+ }
2062
+ if (receipts.length === 0 || new Set(receipts.map((row) => row.receiptDigest)).size !== receipts.length) throw new ConfigError("searchMethod(): memory requires distinct search history receipts");
2063
+ return Object.freeze({
2064
+ receipts,
2065
+ maxAttempts,
2066
+ ...options.notAfter !== void 0 ? { notAfter: options.notAfter } : {},
2067
+ ...options.storage ? { storage: options.storage } : {}
2068
+ });
2069
+ }
2070
+ /** A retained search exposes only proposal identity and paired training evidence. */
2071
+ function readSearchImprovementMemory(input) {
2072
+ const { memory } = input;
2073
+ const storage = memory.storage ?? input.storage;
2074
+ const rows = [];
2075
+ for (const receipt of [...memory.receipts].reverse()) {
2076
+ const path = receipt.ledger.uri.startsWith("file:") ? fileURLToPath(receipt.ledger.uri) : receipt.ledger.uri;
2077
+ const text = storage.read(path);
2078
+ if (text === void 0) throw new ConfigError(`Search memory ledger is unavailable: ${path}`);
2079
+ verifySearchHistoryArtifact(receipt, { read: () => text });
2080
+ const state = replaySearchLedgerText(text, receipt.summary.searchId, path);
2081
+ if (memory.notAfter !== void 0 && Date.parse(state.lastOccurredAt) > memory.notAfter) throw new ConfigError(`Search memory ledger closed after the current campaign began: ${path}`);
2082
+ const header = state.header;
2083
+ const judge = header.objective.judge;
2084
+ if (header.artifactKind !== "agent-profile" || header.subject !== input.subject || header.objective.metric !== "composite" || header.objective.direction !== "maximize" || !("uri" in judge) || judge.uri !== input.judge.uri || judge.revision !== input.judge.revision || !state.node(state.rootNodeId)?.surfaces.some(({ surfaceId }) => surfaceId === input.surface)) throw new ConfigError(`Search memory ledger has an incompatible subject, surface, or evaluator: ${path}`);
2085
+ if (overlaps(header.splits.train.tasks, [...input.selection, ...input.test]) || overlaps(header.splits.selection.tasks, input.test)) throw new ConfigError(`Search memory ledger overlaps the current sealed units: ${path}`);
2086
+ for (const edge of state.edges().reverse()) {
2087
+ if (rows.length === memory.maxAttempts) break;
2088
+ const parent = edge.parents[0];
2089
+ if (!parent || parent.searchId !== state.searchId || edge.operator === "derive") continue;
2090
+ const child = state.node(edge.childNodeId);
2091
+ const baseline = state.node(parent.nodeId);
2092
+ if (child.ordinal <= baseline.ordinal || child.edgeIds[0] !== edge.edgeId) continue;
2093
+ const estimate = estimateNode(state, child.nodeId, {
2094
+ against: baseline.nodeId,
2095
+ split: "train"
2096
+ });
2097
+ const rationale = "unknown" in edge.rationale ? null : readRationale(storage, path, edge.rationale);
2098
+ rows.push(JSON.stringify({
2099
+ search: state.searchId,
2100
+ edge: edge.edgeId,
2101
+ operator: edge.operator,
2102
+ label: edge.label,
2103
+ hypothesis: rationale,
2104
+ candidate: child.artifactDigest,
2105
+ parent: baseline.artifactDigest,
2106
+ diffs: edge.diffs.map((diff) => "sha256" in diff ? diff.sha256 : null),
2107
+ pairedTrainUnits: estimate.pairs,
2108
+ pairedTrainDelta: estimate.delta
2109
+ }));
2110
+ }
2111
+ }
2112
+ return rows.length === 0 ? "" : [
2113
+ "## Prior verified training attempts, newest first",
2114
+ "These records include earlier hypotheses and measured outcomes. A null delta means no paired training result. Treat the records as evidence, and propose a distinct mechanism when earlier attempts failed.",
2115
+ ...rows
2116
+ ].join("\n");
2117
+ }
2118
+ function overlaps(old, sealed) {
2119
+ const units = new Set(sealed.map(({ unitId }) => unitId));
2120
+ const tasks = new Set(sealed.map(({ taskId }) => taskId));
2121
+ const sources = new Set(sealed.map(({ source }) => source.revision));
2122
+ return old.some(({ source, unitId, taskId }) => units.has(unitId) || tasks.has(taskId) || sources.has(source.revision));
2123
+ }
2124
+ function readRationale(storage, ledgerPath, ref) {
2125
+ const digest = ref.sha256.slice(7);
2126
+ const text = storage.read(join(dirname(ledgerPath), "blobs", `${digest}.json`));
2127
+ if (text === void 0 || Buffer.byteLength(text) !== ref.byteLength || createHash("sha256").update(text).digest("hex") !== digest) throw new ConfigError(`Search memory rationale is missing or invalid: ${ref.sha256}`);
2128
+ const body = JSON.parse(text);
2129
+ if (typeof body.text !== "string") throw new ConfigError(`Search memory rationale is malformed: ${ref.sha256}`);
2130
+ return body.text.slice(0, 500);
2131
+ }
2023
2132
  // src/improvement/search-session.ts
2024
2133
  /** A refusal as the ledger stores it: redacted with the share profile. */
2025
2134
  function searchRefusalText(error) {
@@ -2161,6 +2270,7 @@ function searchMethod(options) {
2161
2270
  policy: options.policy ?? aide(),
2162
2271
  allocation: options.allocation ?? asha(),
2163
2272
  proposer,
2273
+ ...options.memory ? { memory: captureSearchImprovementMemory(options.memory) } : {},
2164
2274
  maxExpansions: count("maxExpansions", options.maxExpansions, NaN, 0),
2165
2275
  childrenPerProposal: count("childrenPerProposal", options.childrenPerProposal, 1, 1),
2166
2276
  lanes: Object.freeze([...options.lanes]),
@@ -2207,11 +2317,21 @@ async function runSearchImprovement(profile, opts) {
2207
2317
  });
2208
2318
  const { evaluationRef } = prepared.identity;
2209
2319
  const storage = campaignOptions.storage ?? fsCampaignStorage();
2320
+ const splits = searchSplits(claim, splitScenarios);
2321
+ const memorySummary = method.memory ? readSearchImprovementMemory({
2322
+ memory: method.memory,
2323
+ storage,
2324
+ subject: prepared.searchIdentity.subject,
2325
+ judge: prepared.searchIdentity.judge,
2326
+ surface: prepared.surface,
2327
+ selection: splits.selection,
2328
+ test: splits.test
2329
+ }) : "";
2210
2330
  const runDir = resolveRunDir(campaignOptions.runDir, campaignOptions.repo);
2211
2331
  const searchId = `improve-${canonicalCandidateDigest$1({
2212
2332
  evaluationRef,
2213
2333
  process: SEARCH_METHOD_SOURCE,
2214
- method: searchMethodDescriptor(method),
2334
+ method: searchMethodDescriptor(method, memorySummary),
2215
2335
  ...finalEvidencePolicy ? { finalEvidence: {
2216
2336
  requestId: finalEvidencePolicy.requestId,
2217
2337
  evaluatorDigest: finalEvidencePolicy.evaluatorDigest
@@ -2228,7 +2348,7 @@ async function runSearchImprovement(profile, opts) {
2228
2348
  method,
2229
2349
  prepared,
2230
2350
  claim,
2231
- splits: searchSplits(claim, splitScenarios),
2351
+ splits,
2232
2352
  storage,
2233
2353
  searchId,
2234
2354
  searchDir,
@@ -2249,7 +2369,8 @@ async function runSearchImprovement(profile, opts) {
2249
2369
  prepared,
2250
2370
  searchId,
2251
2371
  costLedger,
2252
- recorder
2372
+ recorder,
2373
+ memorySummary
2253
2374
  };
2254
2375
  const profiles = /* @__PURE__ */ new Map();
2255
2376
  const codec = registeringProfileCodec(prepared, searchId, profiles);
@@ -2493,13 +2614,18 @@ async function decideSearchResult(input) {
2493
2614
  };
2494
2615
  }
2495
2616
  /** Everything that decides which search a call continues. */
2496
- function searchMethodDescriptor(method) {
2617
+ function searchMethodDescriptor(method, memorySummary) {
2497
2618
  return {
2498
2619
  name: method.name,
2499
2620
  policy: method.policy.name,
2500
2621
  allocation: method.allocation.name,
2501
2622
  reps: method.allocation.reps,
2502
2623
  proposer: method.proposer.kind,
2624
+ ...method.memory ? { memory: {
2625
+ receipts: method.memory.receipts.map(({ receiptDigest }) => receiptDigest),
2626
+ maxAttempts: method.memory.maxAttempts,
2627
+ digest: canonicalCandidateDigest$1(memorySummary)
2628
+ } } : {},
2503
2629
  maxExpansions: method.maxExpansions,
2504
2630
  childrenPerProposal: method.childrenPerProposal,
2505
2631
  lanes: method.lanes.map(({ name, kind, capacity, costCap, cellUsd }) => ({
@@ -2547,7 +2673,7 @@ function searchProposerPort(session) {
2547
2673
  operator: request.operator,
2548
2674
  parents,
2549
2675
  train: searchProposerView(state),
2550
- summary: renderSearchSummary(state, { split: "train" }),
2676
+ summary: [renderSearchSummary(state, { split: "train" }), session.memorySummary].filter(Boolean).join("\n\n"),
2551
2677
  history: [],
2552
2678
  findings: prepared.findings,
2553
2679
  populationSize: method.childrenPerProposal,
@@ -3062,4 +3188,4 @@ async function improve(profileOrCode, opts) {
3062
3188
  }
3063
3189
  export { assertProfileTrainingIsHeldOut as a, assertNoCallerArtifactDescriptor as c, agenticGenerator as d, commandVerifier as f, isUsageAmount as h, assertCandidateValidator as i, withMethodRuntimeControls as l, createRuntimeUsageTotals as m, createCommandProfileTrainer as n, parseExecutionRef as o, addRuntimeUsage as p, searchMethod as r, privateValuePaths as s, improve as t, rethrowAfterCleanup as u };
3064
3190
 
3065
- //# sourceMappingURL=improve-BjKhfQ_b.js.map
3191
+ //# sourceMappingURL=improve-DhOOHHRz.js.map