@tangle-network/agent-runtime 0.133.0 → 0.133.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/{activation-B4nhh8w3.js → activation-BKeGUWTV.js} +3 -3
  2. package/dist/{activation-B4nhh8w3.js.map → activation-BKeGUWTV.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{authoring-Dt5lGaM7.js → authoring-CoJWo0Ju.js} +2 -2
  6. package/dist/{authoring-Dt5lGaM7.js.map → authoring-CoJWo0Ju.js.map} +1 -1
  7. package/dist/candidate-execution/index.js +4 -4
  8. package/dist/{candidate-execution-BUhnNcyt.js → candidate-execution-gDXl7pGk.js} +4 -4
  9. package/dist/{candidate-execution-BUhnNcyt.js.map → candidate-execution-gDXl7pGk.js.map} +1 -1
  10. package/dist/{conversation-CiO00rgm.js → conversation-kPowfA_A.js} +3 -3
  11. package/dist/{conversation-CiO00rgm.js.map → conversation-kPowfA_A.js.map} +1 -1
  12. package/dist/conversation.d.ts +1 -1
  13. package/dist/conversation.js +1 -1
  14. package/dist/{environment-provider-BnioYoPQ.d.ts → environment-provider-B-w9VYcF.d.ts} +2 -2
  15. package/dist/environment-provider.d.ts +1 -1
  16. package/dist/{graph-CEFPJQRh.js → graph-B2xqnhnF.js} +3 -3
  17. package/dist/{graph-CEFPJQRh.js.map → graph-B2xqnhnF.js.map} +1 -1
  18. package/dist/{improvement-cycle-Bf9V8cj8.js → improvement-cycle-Cq5xHru1.js} +5 -5
  19. package/dist/{improvement-cycle-Bf9V8cj8.js.map → improvement-cycle-Cq5xHru1.js.map} +1 -1
  20. package/dist/{index-BzP_EK1N.d.ts → index-B7qKWyMV.d.ts} +17 -11
  21. package/dist/{index-Cw0RMLao.d.ts → index-BNz-BzLt.d.ts} +4 -4
  22. package/dist/{index-Cdf9NET5.d.ts → index-DqJa9jGF.d.ts} +2 -2
  23. package/dist/index.d.ts +8 -8
  24. package/dist/index.js +13 -13
  25. package/dist/intelligence.d.ts +4 -4
  26. package/dist/intelligence.js +5 -5
  27. package/dist/kernel.d.ts +6 -6
  28. package/dist/kernel.js +8 -8
  29. package/dist/{knowledge-Dj7e4Pg8.js → knowledge-D-ofzi3v.js} +5 -5
  30. package/dist/{knowledge-Dj7e4Pg8.js.map → knowledge-D-ofzi3v.js.map} +1 -1
  31. package/dist/knowledge.d.ts +1 -1
  32. package/dist/knowledge.js +1 -1
  33. package/dist/{loop-runner-bin-DJDMsJus.js → loop-runner-bin-BwF5A_xf.js} +3 -3
  34. package/dist/{loop-runner-bin-DJDMsJus.js.map → loop-runner-bin-BwF5A_xf.js.map} +1 -1
  35. package/dist/{loop-runner-bin-rmUSJ0jy.d.ts → loop-runner-bin-CBW9ri20.d.ts} +3 -3
  36. package/dist/loop-runner-bin.d.ts +1 -1
  37. package/dist/loop-runner-bin.js +1 -1
  38. package/dist/{materialization-BkL7gRP6.js → materialization-D2bdTfkK.js} +75 -14
  39. package/dist/materialization-D2bdTfkK.js.map +1 -0
  40. package/dist/mcp/bin.js +3 -3
  41. package/dist/mcp/index.d.ts +3 -3
  42. package/dist/mcp/index.js +4 -4
  43. package/dist/{openai-tools-MB5xyj1D.js → openai-tools-rpPRFsVG.js} +2 -2
  44. package/dist/{openai-tools-MB5xyj1D.js.map → openai-tools-rpPRFsVG.js.map} +1 -1
  45. package/dist/{prepare-DggAvkbq.js → prepare-DWH0J5z2.js} +2 -2
  46. package/dist/{prepare-DggAvkbq.js.map → prepare-DWH0J5z2.js.map} +1 -1
  47. package/dist/primeintellect/index.d.ts +1 -1
  48. package/dist/{protected-model-port-BpQeW-0j.js → protected-model-port-djV8FMXc.js} +2 -2
  49. package/dist/{protected-model-port-BpQeW-0j.js.map → protected-model-port-djV8FMXc.js.map} +1 -1
  50. package/dist/{redact-BTKr5YLO.d.ts → redact-BSD-nvTf.d.ts} +3 -3
  51. package/dist/{runtime-DtRTgm3B.js → runtime-CmTSbexZ.js} +85 -76
  52. package/dist/runtime-CmTSbexZ.js.map +1 -0
  53. package/dist/{runtime-BRErB7lm.d.ts → runtime-D-26vxJt.d.ts} +3 -3
  54. package/dist/{spawn-journal-CNg5-D9p.js → spawn-journal-BX3-4WDm.js} +183 -5
  55. package/dist/spawn-journal-BX3-4WDm.js.map +1 -0
  56. package/dist/{stream-agent-turn-B4Mvk5G-.js → stream-agent-turn-D8YHY0oO.js} +2 -2
  57. package/dist/{stream-agent-turn-B4Mvk5G-.js.map → stream-agent-turn-D8YHY0oO.js.map} +1 -1
  58. package/dist/{stream-agent-turn-By46GZlo.d.ts → stream-agent-turn-NFWCv1X1.d.ts} +2 -2
  59. package/dist/{structural-rollout-OPAUocq7.js → structural-rollout-Cy0l0bbT.js} +5 -5
  60. package/dist/{structural-rollout-OPAUocq7.js.map → structural-rollout-Cy0l0bbT.js.map} +1 -1
  61. package/dist/{supervise-Da_e1GgK.js → supervise-DZxpJGK_.js} +98 -29
  62. package/dist/supervise-DZxpJGK_.js.map +1 -0
  63. package/dist/{supervisor-BwU40H4n.js → supervisor-BpIcKHy7.js} +78 -17
  64. package/dist/supervisor-BpIcKHy7.js.map +1 -0
  65. package/dist/testing.d.ts +2 -2
  66. package/dist/testing.js +12 -12
  67. package/dist/{types-BjUQODeG.d.ts → types-DJ7k6vHE.d.ts} +30 -6
  68. package/dist/{workspace-archive-Cm3rtP4F.js → workspace-archive-DdrlLnIj.js} +2 -2
  69. package/dist/{workspace-archive-Cm3rtP4F.js.map → workspace-archive-DdrlLnIj.js.map} +1 -1
  70. package/package.json +1 -1
  71. package/dist/materialization-BkL7gRP6.js.map +0 -1
  72. package/dist/runtime-DtRTgm3B.js.map +0 -1
  73. package/dist/spawn-journal-CNg5-D9p.js.map +0 -1
  74. package/dist/supervise-Da_e1GgK.js.map +0 -1
  75. package/dist/supervisor-BwU40H4n.js.map +0 -1
package/dist/kernel.js CHANGED
@@ -1,13 +1,13 @@
1
- import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-B4Mvk5G-.js";
2
- import { _ as captureWorkerTraceEvidence, a as loadSpawnForest, b as workerTraceAnalysisStore, c as replaySpawnTree, g as WORKER_TOOL_TRACE_SCHEMA_VERSION, i as InMemorySpawnJournal, n as FileSpawnJournal, o as materializeTreeView, r as InMemoryResultBlobStore, s as pendingWaits, t as FileResultBlobStore, x as contentAddress, y as parseWorkerToolTraceArtifact } from "./spawn-journal-CNg5-D9p.js";
1
+ import { n as streamAgentTurn, t as collectAgentTurn } from "./stream-agent-turn-D8YHY0oO.js";
2
+ import { S as contentAddress, _ as WORKER_TOOL_TRACE_SCHEMA_VERSION, b as parseWorkerToolTraceArtifact, c as pendingWaits, i as InMemorySpawnJournal, l as replaySpawnTree, n as FileSpawnJournal, o as loadSpawnForest, r as InMemoryResultBlobStore, s as materializeTreeView, t as FileResultBlobStore, v as captureWorkerTraceEvidence, x as workerTraceAnalysisStore } from "./spawn-journal-BX3-4WDm.js";
3
3
  import { i as mapSandboxToolEvent, n as extractLlmCallEvent, o as sumSandboxUsage, r as mapSandboxEvent, t as createSandboxToolPartState } from "./sandbox-events-vIwmuPdl.js";
4
4
  import { n as assertModelAllowed, r as assertProfileModelsAllowed } from "./model-policy-Bv1DU2fw.js";
5
- import { $ as runAgentRounds, B as workerTraceHeaders, C as queueOf, G as decodeToolPart, H as DEFAULT_SANDBOX_STEERING_MAX_TURNS, I as createWorktreeCliExecutor, J as createActivityLog, K as sandboxSessionTraceSource, M as cliWorktreeExecutor, N as createExecutor, O as createBudgetPool, P as createExecutorRegistry, Q as defaultSelectWinner, R as readWorkerTraceContext, S as freeSlots, U as createSteerableSandboxSession, V as workerTraceSeamKey, W as createPushTraceSource, X as createInbox, Y as readWorkerProgress, _ as pollFor, a as pickBestDelivered, b as waitUntil, et as createSandboxLineage, g as isWaitOutcome, h as createWaitProbes, ht as createOtelExporter, i as collectDelivered, k as spendFromUsageEvents, m as settledToIteration, mt as createOpenInferenceFileExporter, n as createSupervisor, nt as acquireSandbox, o as runFinalizer, q as DEFAULT_STALL_AFTER_MS, r as bestDelivered, s as runTree, t as createRootHandle, tt as probeSandboxCapabilities, u as createScope, v as timerAt, w as rollingDispatch, x as effectiveConcurrency, y as validateWaitSpec, z as workerTraceEnv } from "./supervisor-BwU40H4n.js";
5
+ import { $ as defaultSelectWinner, A as spendFromUsageEvents, B as workerTraceEnv, C as freeSlots, F as createExecutorRegistry, G as createPushTraceSource, H as workerTraceSeamKey, J as DEFAULT_STALL_AFTER_MS, K as decodeToolPart, L as createWorktreeCliExecutor, N as cliWorktreeExecutor, P as createExecutor, S as effectiveConcurrency, T as rollingDispatch, U as DEFAULT_SANDBOX_STEERING_MAX_TURNS, V as workerTraceHeaders, W as createSteerableSandboxSession, X as readWorkerProgress, Y as createActivityLog, Z as createInbox, _ as isWaitOutcome, _t as createOtelExporter, a as pickBestDelivered, b as validateWaitSpec, et as runAgentRounds, g as createWaitProbes, gt as createOpenInferenceFileExporter, h as settledToIteration, i as collectDelivered, k as createBudgetPool, n as createSupervisor, nt as probeSandboxCapabilities, o as runFinalizer, q as sandboxSessionTraceSource, r as bestDelivered, rt as acquireSandbox, s as runTree, t as createRootHandle, tt as createSandboxLineage, u as createScope, v as pollFor, w as queueOf, x as waitUntil, y as timerAt, z as readWorkerTraceContext } from "./supervisor-BpIcKHy7.js";
6
6
  import { a as sandboxClientAsProvider, i as resolveAgentEnvironmentProvider, n as providerAsExecutor, o as createTangleSandboxExactProcessProvider, r as providerAsSandboxClient, t as createAgentEnvironmentProviderRegistry } from "./environment-provider-mDsjfGjY.js";
7
- import { C as observe, E as profileOptimizerModelCall, S as defaultAnalystInstruction, T as profileChatClient, _ as depthStrategy, a as defaultStructuralRolloutPolicy, b as sample, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as defineStrategy, h as breadthStrategy, i as defaultExtractCandidate, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, v as refine, w as renderReport, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-OPAUocq7.js";
8
- import { $ as flatWidenGate, A as assertStrategyContract, At as defaultAuditorInstruction, B as startRetainedRun, Bt as secretEnvOfMcpServer, C as chatTransportExecutor, Ct as leaderboard, D as pickChampion, Dt as renderLeaderboardSvg, E as discriminatingMeans, Et as renderLeaderboardMarkdown, F as openSandboxRun, Ft as sanitizeMcpToolSchema, G as runPersonified, H as equalKOnCost, I as printBenchmarkReport, It as envKeyProvider, J as registerShape, K as builtinShapes, L as runBenchmark, Lt as mcpSecretEnvMetadataKey, M as strategyAuthorContract, Mt as connectStdioMcp, N as strategyAuthorSystemPrompt, Nt as materializeLocalMcp, O as runStrategyEvolution, Ot as renderPairwiseMarkdown, P as SandboxRunAbortError, Pt as createMcpEnvironment, Q as fanout, R as reconnectRetainedRun, Rt as resolveMcpServerLaunch, St as stopSentinel, T as createChatSessionStore, Tt as renderLeaderboardHtml, U as trajectoryReport, V as promotionGate, W as definePersona, X as InMemoryCorpus, Y as FileCorpus, Z as renderCorpusToInstructions, _ as settledWorkerOut, _t as loopDispatch, a as localShell, at as widen, b as analyzeTrace, bt as deterministicCompletion, c as createVerifierEnvironment, ct as createScopeAnalyst, d as worktreeFanout, dt as harvestCorpus, et as loopUntil, f as EVIDENCE_MAX_CHARS, ft as defineLeaderboard, g as composeWorkerEvidence, gt as loopCampaignDispatch, h as closingWorkerNote, ht as inlineSandboxClient, i as jjWorkspace, it as verify, j as authorStrategy, jt as McpSpawnFault, k as selectChampion, kt as auditIntent, l as failuresAnalyst, lt as registryScopeAnalyst, m as VERIFY_TAIL_CHARS, mt as localSandboxClient, n as makeFinding, nt as pipeline, o as runInWorkspace, ot as assertTraceDerivedFindings, p as NOTE_MAX_CHARS, pt as resolveSandboxClient, q as createShapeRegistry, r as gitWorkspace, rt as selectValidWinner, s as createWaterfallCollector, st as buildSteerContext, t as computeFindingId, tt as panel, u as superviseSurface, ut as inProcessSandboxClient, v as copyUntrackedIntoClone, vt as superviseDispatch, w as chatWorkerSeam, wt as pairwiseSignificance, x as patchDelivered, xt as sentinelCompletion, y as withUntrackedArtifacts, yt as completionAuthorizes, z as recoverRetainedRun, zt as resolveSecretEnv } from "./runtime-DtRTgm3B.js";
9
- import { At as defaultToolDetectors, Ct as plateauLength, Et as canonicalFindingEvent, Ft as createSupervisorSpanRecorder, It as gateOnDeliverable, Lt as mapExecutorResult, Mt as createFileRunContext, Nt as createInMemoryRunContext, Ot as normalizeAnalyzeOnSettle, Pt as FileCoordinationLog, St as bestSoFar, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, X as delegate, Y as defaultDelegateBudget, _ as promptHandle, _t as noProgressFor, a as assertCoordinationBinding, b as classifyDriverFailure, bt as anytimeReport, d as delegatesWorkerBriefPrompt, f as dumbContinuationFailPrompt, ft as finalizeBestDelivered, g as naiveContinuationPrompt, gt as createProgressTracker, h as kernelPromptRegistry, ht as anyOf, i as workerFromBackend, jt as watchTrace, kt as createEventBus, l as analyzesFindingsReportPrompt, m as formatPromptHandle, mt as allWorkersStalled, n as supervise, o as resolveSupervisorProfile, p as dumbContinuationPassPrompt, pt as allOf, s as supervisorAgent, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as createPromptRegistry, v as supervisorPolicyPrompt, vt as plateau, wt as renderAnytimeTable, x as serveCoordinationMcp, xt as areaUnderCurve, y as DriverAttemptsExhaustedError, yt as sampleFromSettled } from "./supervise-Da_e1GgK.js";
10
- import { a as supervisorInstructions, i as profileRichnessFinding, n as assessAuthoredProfile, r as defaultProfileRichnessThresholds, t as asAuthoredProfile } from "./authoring-Dt5lGaM7.js";
11
- import { n as defaultEdgeTraversalCap, r as runGraph, t as GraphEdgeCapError } from "./graph-CEFPJQRh.js";
7
+ import { C as observe, E as profileOptimizerModelCall, S as defaultAnalystInstruction, T as profileChatClient, _ as depthStrategy, a as defaultStructuralRolloutPolicy, b as sample, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as defineStrategy, h as breadthStrategy, i as defaultExtractCandidate, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, v as refine, w as renderReport, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-Cy0l0bbT.js";
8
+ import { $ as flatWidenGate, A as assertStrategyContract, At as defaultAuditorInstruction, B as startRetainedRun, Bt as secretEnvOfMcpServer, C as chatTransportExecutor, Ct as leaderboard, D as pickChampion, Dt as renderLeaderboardSvg, E as discriminatingMeans, Et as renderLeaderboardMarkdown, F as openSandboxRun, Ft as sanitizeMcpToolSchema, G as runPersonified, H as equalKOnCost, I as printBenchmarkReport, It as envKeyProvider, J as registerShape, K as builtinShapes, L as runBenchmark, Lt as mcpSecretEnvMetadataKey, M as strategyAuthorContract, Mt as connectStdioMcp, N as strategyAuthorSystemPrompt, Nt as materializeLocalMcp, O as runStrategyEvolution, Ot as renderPairwiseMarkdown, P as SandboxRunAbortError, Pt as createMcpEnvironment, Q as fanout, R as reconnectRetainedRun, Rt as resolveMcpServerLaunch, St as stopSentinel, T as createChatSessionStore, Tt as renderLeaderboardHtml, U as trajectoryReport, V as promotionGate, W as definePersona, X as InMemoryCorpus, Y as FileCorpus, Z as renderCorpusToInstructions, _ as settledWorkerOut, _t as loopDispatch, a as localShell, at as widen, b as analyzeTrace, bt as deterministicCompletion, c as createVerifierEnvironment, ct as createScopeAnalyst, d as worktreeFanout, dt as harvestCorpus, et as loopUntil, f as EVIDENCE_MAX_CHARS, ft as defineLeaderboard, g as composeWorkerEvidence, gt as loopCampaignDispatch, h as closingWorkerNote, ht as inlineSandboxClient, i as jjWorkspace, it as verify, j as authorStrategy, jt as McpSpawnFault, k as selectChampion, kt as auditIntent, l as failuresAnalyst, lt as registryScopeAnalyst, m as VERIFY_TAIL_CHARS, mt as localSandboxClient, n as makeFinding, nt as pipeline, o as runInWorkspace, ot as assertTraceDerivedFindings, p as NOTE_MAX_CHARS, pt as resolveSandboxClient, q as createShapeRegistry, r as gitWorkspace, rt as selectValidWinner, s as createWaterfallCollector, st as buildSteerContext, t as computeFindingId, tt as panel, u as superviseSurface, ut as inProcessSandboxClient, v as copyUntrackedIntoClone, vt as superviseDispatch, w as chatWorkerSeam, wt as pairwiseSignificance, x as patchDelivered, xt as sentinelCompletion, y as withUntrackedArtifacts, yt as completionAuthorizes, z as recoverRetainedRun, zt as resolveSecretEnv } from "./runtime-CmTSbexZ.js";
9
+ import { At as defaultToolDetectors, Ct as plateauLength, Et as canonicalFindingEvent, Ft as createSupervisorSpanRecorder, It as gateOnDeliverable, Lt as mapExecutorResult, Mt as createFileRunContext, Nt as createInMemoryRunContext, Ot as normalizeAnalyzeOnSettle, Pt as FileCoordinationLog, St as bestSoFar, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, X as delegate, Y as defaultDelegateBudget, _ as promptHandle, _t as noProgressFor, a as assertCoordinationBinding, b as classifyDriverFailure, bt as anytimeReport, d as delegatesWorkerBriefPrompt, f as dumbContinuationFailPrompt, ft as finalizeBestDelivered, g as naiveContinuationPrompt, gt as createProgressTracker, h as kernelPromptRegistry, ht as anyOf, i as workerFromBackend, jt as watchTrace, kt as createEventBus, l as analyzesFindingsReportPrompt, m as formatPromptHandle, mt as allWorkersStalled, n as supervise, o as resolveSupervisorProfile, p as dumbContinuationPassPrompt, pt as allOf, s as supervisorAgent, t as DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, u as createPromptRegistry, v as supervisorPolicyPrompt, vt as plateau, wt as renderAnytimeTable, x as serveCoordinationMcp, xt as areaUnderCurve, y as DriverAttemptsExhaustedError, yt as sampleFromSettled } from "./supervise-DZxpJGK_.js";
10
+ import { a as supervisorInstructions, i as profileRichnessFinding, n as assessAuthoredProfile, r as defaultProfileRichnessThresholds, t as asAuthoredProfile } from "./authoring-CoJWo0Ju.js";
11
+ import { n as defaultEdgeTraversalCap, r as runGraph, t as GraphEdgeCapError } from "./graph-B2xqnhnF.js";
12
12
  import { a as supervisorRunDir, c as workerControlLogFile, d as writeWorkerSteer, i as safeWorkerFile, l as workerInboxFile, n as legacySupervisorRunsRoot, o as supervisorRunsRoot, r as readWorkerSteerRequests, s as supervisorWorkersDir, t as legacySupervisorRunDir, u as workerInboxFileFromEventDir } from "./run-layout-CeJsEAom.js";
13
13
  export { DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_STALL_AFTER_MS, DriverAttemptsExhaustedError, EVIDENCE_MAX_CHARS, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, GraphEdgeCapError, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, McpSpawnFault, NOTE_MAX_CHARS, SandboxRunAbortError, VERIFY_TAIL_CHARS, WORKER_TOOL_TRACE_SCHEMA_VERSION, acquireSandbox, adaptiveRefine, allOf, allWorkersStalled, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertCoordinationBinding, assertModelAllowed, assertProfileModelsAllowed, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, auditIntent, authorStrategy, bestDelivered, bestSoFar, breadthStrategy, buildSteerContext, builtinShapes, canDisplace, canonicalFindingEvent, captureWorkerTraceEvidence, chatTransportExecutor, chatWorkerSeam, classifyDriverFailure, cliWorktreeExecutor, closingWorkerNote, collectAgentTurn, collectDelivered, compareCheckOutcomes, completionAuthorizes, composeCheckSources, composeWorkerEvidence, computeFindingId, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createEventBus, createExecutor, createExecutorRegistry, createFileRunContext, createInMemoryRunContext, createInbox, createMcpEnvironment, createOpenInferenceFileExporter, createOtelExporter, createProgressTracker, createPromptRegistry, createPushTraceSource, createRootHandle, createSandboxLineage, createSandboxToolPartState, createScope, createScopeAnalyst, createShapeRegistry, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createTangleSandboxExactProcessProvider, createVerifierEnvironment, createWaitProbes, createWaterfallCollector, createWorktreeCliExecutor, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, discriminatingMeans, dumbContinuationFailPrompt, dumbContinuationPassPrompt, effectiveConcurrency, envKeyProvider, equalKOnCost, extractLlmCallEvent, failuresAnalyst, fanout, filterAuthoredAsserts, finalizeBestDelivered, flatWidenGate, formatPromptHandle, freeSlots, gateOnDeliverable, gitWorkspace, harvestCorpus, inProcessSandboxClient, inlineSandboxClient, isWaitOutcome, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, legacySupervisorRunsRoot, loadSpawnForest, localSandboxClient, localShell, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, normalizeAnalyzeOnSettle, observe, officialChecksFromMeta, openSandboxRun, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, patchDelivered, pendingWaits, pickBestDelivered, pickChampion, pipeline, plateau, plateauLength, pollFor, printBenchmarkReport, probeSandboxCapabilities, profileChatClient, profileOptimizerModelCall, profileRichnessFinding, promotionGate, promptHandle, providerAsExecutor, providerAsSandboxClient, queueOf, readWorkerProgress, readWorkerSteerRequests, readWorkerTraceContext, reconnectRetainedRun, recoverRetainedRun, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, resolveSupervisorProfile, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runFinalizer, runGraph, runInWorkspace, runPersonified, runStrategyEvolution, runTree, safeWorkerFile, sample, sampleFromSettled, sampleThenRefine, sandboxCheckRunner, sandboxClientAsProvider, sandboxSessionTraceSource, sanitizeMcpToolSchema, secretEnvOfMcpServer, selectBestIndex, selectChampion, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, spendFromUsageEvents, startRetainedRun, stopSentinel, strategyAuthorContract, strategyAuthorSystemPrompt, streamAgentTurn, structuralRollout, sumSandboxUsage, supervise, superviseDispatch, superviseSurface, supervisorAgent, supervisorInstructions, supervisorPolicyPrompt, supervisorRunDir, supervisorRunsRoot, supervisorWorkersDir, timerAt, trajectoryReport, validateWaitSpec, verify, visibleCheckScore, waitUntil, watchTrace, widen, withUntrackedArtifacts, workerControlLogFile, workerFromBackend, workerInboxFile, workerInboxFileFromEventDir, workerTraceAnalysisStore, workerTraceEnv, workerTraceHeaders, workerTraceSeamKey, worktreeFanout, writeWorkerSteer };
@@ -1,9 +1,9 @@
1
- import { a as persistCandidateOutputArtifact, ct as omitTopLevelDigest, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact } from "./prepare-DggAvkbq.js";
2
- import { i as sealAgentCandidateBundle, t as captureAgentCandidateWorkspace } from "./workspace-archive-Cm3rtP4F.js";
1
+ import { a as persistCandidateOutputArtifact, ct as omitTopLevelDigest, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact } from "./prepare-DWH0J5z2.js";
2
+ import { i as sealAgentCandidateBundle, t as captureAgentCandidateWorkspace } from "./workspace-archive-DdrlLnIj.js";
3
3
  import { t as assertExecutableAgentProfile } from "./model-policy-Bv1DU2fw.js";
4
- import { t as createAgentImprovementActivationResult } from "./activation-B4nhh8w3.js";
4
+ import { t as createAgentImprovementActivationResult } from "./activation-BKeGUWTV.js";
5
5
  import { t as RESEARCHER_SYSTEM_PROMPT } from "./researcher-BiWSFLi6.js";
6
- import { n as supervise } from "./supervise-Da_e1GgK.js";
6
+ import { n as supervise } from "./supervise-DZxpJGK_.js";
7
7
  import { agentCandidateKnowledgeSchema, agentProfileSchema, sha256DigestSchema } from "@tangle-network/agent-interface";
8
8
  import { realpath } from "node:fs/promises";
9
9
  import { evaluateKnowledgeBaseReadiness, fromAgentCandidateKnowledgeRef, improveKnowledgeBase, knowledgeImprovementCandidateRef, loadKnowledgeImprovementActivationResult, promoteKnowledgeCandidate, restoreKnowledgeCandidateBaseline, toAgentCandidateKnowledgeRef, withKnowledgeImprovementComparison } from "@tangle-network/agent-knowledge";
@@ -432,4 +432,4 @@ function addSpent(target, result) {
432
432
  //#endregion
433
433
  export { createSupervisedKnowledgeUpdater as a, runSupervisedKnowledgeUpdate as c, RESEARCH_SUPERVISOR_SYSTEM_PROMPT as i, createKnowledgeImprovementActivationExecutor as l, createAgentKnowledgeReadinessCheck as n, formatSupervisedKnowledgeTask as o, runKnowledgeImprovementJob as r, knowledgeReadinessDeliverable as s, buildKnowledgeImprovementExperimentBundles as t };
434
434
 
435
- //# sourceMappingURL=knowledge-Dj7e4Pg8.js.map
435
+ //# sourceMappingURL=knowledge-D-ofzi3v.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge-Dj7e4Pg8.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { RESEARCHER_SYSTEM_PROMPT } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n /** Caller-owned exact supervisor harness/provider/model identity. */\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const exactSupervisor = agentProfileSchema.parse(options.supervisorProfile) as SupervisorProfile\n assertExecutableAgentProfile(exactSupervisor, 'runSupervisedKnowledgeUpdate')\n const baseInstructions = exactSupervisor.prompt?.systemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = RESEARCHER_SYSTEM_PROMPT\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n ...exactSupervisor,\n prompt: { ...exactSupervisor.prompt, systemPrompt },\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorProfile,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n supervisorProfile,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAAS,KAAA;EAChD;EACA,YAAY,OAAO,eAAe;GAChC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,mEAAmE;GAErF,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,IAAI,UAAU,SAAS,OAAO,UAAU;GAExC,MAAM,kBAAkB;IACtB,MAAM,QAAQ;IACd,WAAW,UAAU;IACrB,YAAY;KACV,YAAY,WAAW;KACvB,aAAa,WAAW;KACxB,UAAU,QAAQ;KAClB,eAAe,YACb,UAAU,OACR,yBAAyB,SAAS,WAAW,WAAW,WAAW,MAAM,CAC3E;IACJ;IACA,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;IACtD,GAAI,QAAQ,eAAe,KAAA,IAAY,CAA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":3,"file":"knowledge-D-ofzi3v.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import { agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { RESEARCHER_SYSTEM_PROMPT } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n /** Caller-owned exact supervisor harness/provider/model identity. */\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const exactSupervisor = agentProfileSchema.parse(options.supervisorProfile) as SupervisorProfile\n assertExecutableAgentProfile(exactSupervisor, 'runSupervisedKnowledgeUpdate')\n const baseInstructions = exactSupervisor.prompt?.systemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = RESEARCHER_SYSTEM_PROMPT\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n ...exactSupervisor,\n prompt: { ...exactSupervisor.prompt, systemPrompt },\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n supervisorProfile: SupervisorProfile\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorProfile,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n supervisorProfile,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAAS,KAAA;EAChD;EACA,YAAY,OAAO,eAAe;GAChC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,mEAAmE;GAErF,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,IAAI,UAAU,SAAS,OAAO,UAAU;GAExC,MAAM,kBAA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,UAAU;EAAM,KAAK;EAAG,IAAI;CAAE;AACzF;AAEA,SAAS,SACP,QACA,QACM;CACN,MAAM,QAAQ,OAAO;CACrB,OAAO,cAAc,MAAM;CAC3B,OAAO,eAAe,MAAM,OAAO;CACnC,OAAO,gBAAgB,MAAM,OAAO;CACpC,OAAO,WAAW,OAAO,YAAY,MAAM,aAAa;CACxD,OAAO,OAAO,MAAM;CACpB,OAAO,MAAM,MAAM;AACrB"}
@@ -1,2 +1,2 @@
1
- import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-Cw0RMLao.js";
1
+ import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-BNz-BzLt.js";
2
2
  export { type AgentKnowledgeReadinessCheckOptions, type CreateKnowledgeImprovementActivationExecutorOptions, type KnowledgeImprovementActivationExecutor, type KnowledgeImprovementCandidatePair, type KnowledgeImprovementExperimentBundles, type KnowledgeImprovementJobMeasurement, type KnowledgeImprovementJobResult, type KnowledgeReadinessCheck, type KnowledgeReadinessCheckInput, type KnowledgeReadinessCheckResult, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, type RunKnowledgeImprovementJobOptions, type SupervisedKnowledgeUpdateInput, type SupervisedKnowledgeUpdateOptions, type SupervisedKnowledgeUpdateResult, type SupervisedKnowledgeUpdater, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
package/dist/knowledge.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-Dj7e4Pg8.js";
1
+ import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-D-ofzi3v.js";
2
2
  export { RESEARCH_SUPERVISOR_SYSTEM_PROMPT, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
@@ -1,6 +1,6 @@
1
1
  import { i as ConfigError } from "./errors-DRoXIc7E.js";
2
- import { P as createExecutorRegistry } from "./supervisor-BwU40H4n.js";
3
- import { G as runPersonified, W as definePersona, d as worktreeFanout } from "./runtime-DtRTgm3B.js";
2
+ import { F as createExecutorRegistry } from "./supervisor-BpIcKHy7.js";
3
+ import { G as runPersonified, W as definePersona, d as worktreeFanout } from "./runtime-CmTSbexZ.js";
4
4
  import { t as runAnalystLoop } from "./analyst-loop-C189F6v8.js";
5
5
  import { t as createKbGate } from "./kb-gate-DpaSwXVx.js";
6
6
  //#region src/loop-runner.ts
@@ -243,4 +243,4 @@ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main()
243
243
  //#endregion
244
244
  export { isDelegatedLoopMode as a, worktreeLoopRunner as c, auditLoopRunner as i, runLoopRunnerCli as n, researchLoopRunner as o, DELEGATED_LOOP_MODES as r, runDelegatedLoop as s, parseLoopRunnerArgv as t };
245
245
 
246
- //# sourceMappingURL=loop-runner-bin-DJDMsJus.js.map
246
+ //# sourceMappingURL=loop-runner-bin-BwF5A_xf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-DJDMsJus.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;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DelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invoked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AnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
2
- import { Ys as WinnerStrategy, _ as WorktreeFanoutOptions, _t as WorktreePatchArtifact, g as AuthoredHarness } from "./index-BzP_EK1N.js";
3
- import { i as Budget } from "./types-BjUQODeG.js";
2
+ import { Ys as WinnerStrategy, _ as WorktreeFanoutOptions, _t as WorktreePatchArtifact, g as AuthoredHarness } from "./index-B7qKWyMV.js";
3
+ import { i as Budget } from "./types-DJ7k6vHE.js";
4
4
  import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
5
5
  import { AgentProfile } from "@tangle-network/agent-interface";
6
6
  //#region src/loop-runner.d.ts
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
162
162
  };
163
163
  //#endregion
164
164
  export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
165
- //# sourceMappingURL=loop-runner-bin-rmUSJ0jy.d.ts.map
165
+ //# sourceMappingURL=loop-runner-bin-CBW9ri20.d.ts.map
@@ -1,2 +1,2 @@
1
- import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-rmUSJ0jy.js";
1
+ import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-CBW9ri20.js";
2
2
  export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-DJDMsJus.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-BwF5A_xf.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
@@ -32,7 +32,8 @@ function executableAgentSpecSnapshot(raw, context) {
32
32
  //#region src/runtime/supervise/materialization.ts
33
33
  const runtimeOwnedExecutorMaterializations = /* @__PURE__ */ new WeakMap();
34
34
  const runtimeOwnedScopeOwners = /* @__PURE__ */ new WeakMap();
35
- const runtimeOwnedDriveHarnessModelObservations = /* @__PURE__ */ new WeakMap();
35
+ const runtimeOwnedExecutorProviderEvidenceState = /* @__PURE__ */ new WeakMap();
36
+ const runtimeOwnedDriveHarnessProviderEvidenceState = /* @__PURE__ */ new WeakMap();
36
37
  const declarationKeys = /* @__PURE__ */ new Set([
37
38
  "effectiveProfile",
38
39
  "backend",
@@ -53,6 +54,7 @@ function attestRuntimeOwnedExecutor(executor, declaration, binding) {
53
54
  declaration: detachedSnapshot(declaration, "runtime-owned executor materialization"),
54
55
  ...binding === void 0 ? {} : { binding: detachedSnapshot(binding, "runtime-owned executor execution binding") }
55
56
  }) });
57
+ ensureProviderEvidenceState(executor);
56
58
  return executor;
57
59
  }
58
60
  /** Brand an external Runtime executor whose exact remote materialization is provable only after
@@ -92,8 +94,17 @@ function attestRuntimeOwnedDeferredExecutor(executor, runtime) {
92
94
  function inheritRuntimeOwnedExecutorAttestation(source, wrapper) {
93
95
  const ref = runtimeOwnedExecutorMaterializations.get(source);
94
96
  if (ref !== void 0) runtimeOwnedExecutorMaterializations.set(wrapper, ref);
97
+ const providerState = ensureProviderEvidenceState(source);
98
+ runtimeOwnedExecutorProviderEvidenceState.set(wrapper, providerState);
95
99
  return wrapper;
96
100
  }
101
+ function ensureProviderEvidenceState(executor) {
102
+ const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor);
103
+ if (existing !== void 0) return existing;
104
+ const state = { attempts: [] };
105
+ runtimeOwnedExecutorProviderEvidenceState.set(executor, state);
106
+ return state;
107
+ }
97
108
  /** Read a declaration only when Runtime itself branded this exact executor object. */
98
109
  function runtimeOwnedExecutorMaterialization(executor) {
99
110
  const attestation = runtimeOwnedExecutorMaterializations.get(executor)?.current;
@@ -129,20 +140,70 @@ function attestRuntimeOwnedScopeOwner(owner, runtime) {
129
140
  function runtimeOwnedScopeOwnerRuntime(owner) {
130
141
  return runtimeOwnedScopeOwners.get(owner);
131
142
  }
132
- /** Record provider model observations only for a Runtime-owned drive adapter. Arbitrary caller
133
- * harnesses cannot publish a lookalike receipt, so their root identity remains unknown. */
134
- function recordRuntimeOwnedDriveHarnessModel(owner, model) {
135
- const state = runtimeOwnedDriveHarnessModelObservations.get(owner);
136
- if (state === void 0) {
137
- runtimeOwnedDriveHarnessModelObservations.set(owner, { observations: [model] });
143
+ /** Mark one provider inference attempt on a Runtime-owned executor. */
144
+ function recordRuntimeOwnedProviderAttemptStart(executor) {
145
+ ensureProviderEvidenceState(executor).attempts.push({ observations: [] });
146
+ }
147
+ /** Record a trusted served model on the current provider attempt. */
148
+ function recordRuntimeOwnedProviderModel(executor, model) {
149
+ const attempt = runtimeOwnedExecutorProviderEvidenceState.get(executor)?.attempts.at(-1);
150
+ if (attempt === void 0) throw new ValidationError("provider model observation arrived before an attempt started");
151
+ if (attempt.observations.at(-1) !== model) attempt.observations.push(model);
152
+ }
153
+ /** Convert process-local provider observations into a frozen, replayable evidence value. */
154
+ function runtimeOwnedExecutorProviderEvidence(executor) {
155
+ const state = runtimeOwnedExecutorProviderEvidenceState.get(executor);
156
+ if (state === void 0 || state.attempts.length === 0) return void 0;
157
+ const attempts = Object.freeze(state.attempts.map((attempt) => Object.freeze({
158
+ observations: Object.freeze([...attempt.observations]),
159
+ ...attempt.identityConflict ? { identityConflict: true } : {}
160
+ })));
161
+ const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))]);
162
+ const missing = attempts.some((attempt) => attempt.observations.length === 0);
163
+ const conflict = attempts.some((attempt) => attempt.identityConflict === true);
164
+ return Object.freeze(missing || conflict ? {
165
+ status: "unknown",
166
+ attempts,
167
+ models,
168
+ reason: conflict ? "provider-model-conflict" : "provider-model-missing"
169
+ } : {
170
+ status: "known",
171
+ attempts,
172
+ models
173
+ });
174
+ }
175
+ /** Mark the current provider attempt unusable after conflicting served identity metadata. */
176
+ function recordRuntimeOwnedProviderIdentityConflict(executor) {
177
+ const attempt = ensureProviderEvidenceState(executor).attempts.at(-1);
178
+ if (attempt === void 0) throw new ValidationError("provider identity conflict arrived before an attempt started");
179
+ attempt.identityConflict = true;
180
+ }
181
+ /** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */
182
+ function recordRuntimeOwnedDriveHarnessProviderEvidence(owner, evidence) {
183
+ if (evidence === void 0) return;
184
+ const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner);
185
+ if (prior === void 0) {
186
+ runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence);
138
187
  return;
139
188
  }
140
- state.observations.push(model);
189
+ const attempts = Object.freeze([...prior.attempts, ...evidence.attempts]);
190
+ const models = Object.freeze([.../* @__PURE__ */ new Set([...prior.models, ...evidence.models])]);
191
+ const missing = attempts.some((attempt) => attempt.observations.length === 0);
192
+ const conflict = attempts.some((attempt) => attempt.identityConflict === true);
193
+ runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, Object.freeze(missing || conflict ? {
194
+ status: "unknown",
195
+ attempts,
196
+ models,
197
+ reason: conflict ? "provider-model-conflict" : "provider-model-missing"
198
+ } : {
199
+ status: "known",
200
+ attempts,
201
+ models
202
+ }));
141
203
  }
142
- /** Read settled provider observations from one Runtime-owned drive adapter. */
143
- function runtimeOwnedDriveHarnessModels(owner) {
144
- const state = runtimeOwnedDriveHarnessModelObservations.get(owner);
145
- return state === void 0 ? void 0 : Object.freeze([...state.observations]);
204
+ /** Read provider evidence recorded by a Runtime-owned root drive. */
205
+ function runtimeOwnedDriveHarnessProviderEvidence(owner) {
206
+ return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner);
146
207
  }
147
208
  /** Build one kernel-owned known receipt from a data-only executor declaration. */
148
209
  function knownMaterializationReceipt(input) {
@@ -283,6 +344,6 @@ function jsonWireSnapshot(value, path = "$") {
283
344
  return out;
284
345
  }
285
346
  //#endregion
286
- export { runtimeOwnedScopeOwnerRuntime as _, authoredProfileDigest as a, executableAgentProfileSnapshot as b, knownExecutionBindingReceipt as c, recordRuntimeOwnedDriveHarnessModel as d, runtimeOwnedDeferredExecutorRuntime as f, runtimeOwnedPendingExecutorMaterialization as g, runtimeOwnedExecutorMaterialization as h, attestRuntimeOwnedScopeOwner as i, knownMaterializationReceipt as l, runtimeOwnedExecutorExecutionBinding as m, attestRuntimeOwnedExecutor as n, finalizeRuntimeOwnedPendingExecutor as o, runtimeOwnedDriveHarnessModels as p, attestRuntimeOwnedPendingExecutor as r, inheritRuntimeOwnedExecutorAttestation as s, attestRuntimeOwnedDeferredExecutor as t, newExecutionAttemptId as u, unknownExecutionBindingReceipt as v, executableAgentSpecSnapshot as x, unknownMaterializationReceipt as y };
347
+ export { unknownMaterializationReceipt as C, unknownExecutionBindingReceipt as S, executableAgentSpecSnapshot as T, runtimeOwnedExecutorExecutionBinding as _, authoredProfileDigest as a, runtimeOwnedPendingExecutorMaterialization as b, knownExecutionBindingReceipt as c, recordRuntimeOwnedDriveHarnessProviderEvidence as d, recordRuntimeOwnedProviderAttemptStart as f, runtimeOwnedDriveHarnessProviderEvidence as g, runtimeOwnedDeferredExecutorRuntime as h, attestRuntimeOwnedScopeOwner as i, knownMaterializationReceipt as l, recordRuntimeOwnedProviderModel as m, attestRuntimeOwnedExecutor as n, finalizeRuntimeOwnedPendingExecutor as o, recordRuntimeOwnedProviderIdentityConflict as p, attestRuntimeOwnedPendingExecutor as r, inheritRuntimeOwnedExecutorAttestation as s, attestRuntimeOwnedDeferredExecutor as t, newExecutionAttemptId as u, runtimeOwnedExecutorMaterialization as v, executableAgentProfileSnapshot as w, runtimeOwnedScopeOwnerRuntime as x, runtimeOwnedExecutorProviderEvidence as y };
287
348
 
288
- //# sourceMappingURL=materialization-BkL7gRP6.js.map
349
+ //# sourceMappingURL=materialization-D2bdTfkK.js.map