@tangle-network/agent-runtime 0.338.0 → 0.340.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/{activation-kbkAuSmY.js → activation-D2PVljaw.js} +5 -18
  2. package/dist/{activation-kbkAuSmY.js.map → activation-D2PVljaw.js.map} +1 -1
  3. package/dist/{activation-CsbNax2X.d.ts → activation-DGDl4wwI.d.ts} +4 -24
  4. package/dist/agent.d.ts +4 -18
  5. package/dist/agent.js +3 -21
  6. package/dist/agent.js.map +1 -1
  7. package/dist/analyst-loop.d.ts +2 -2
  8. package/dist/{bundle-DM60AI2B.js → bundle-DNUq-OPW.js} +2 -2
  9. package/dist/{bundle-DM60AI2B.js.map → bundle-DNUq-OPW.js.map} +1 -1
  10. package/dist/candidate-execution/index.d.ts +4 -101
  11. package/dist/candidate-execution/index.js +10 -395
  12. package/dist/candidate-execution/index.js.map +1 -1
  13. package/dist/{delegate-Se1YZKMb.js → delegate-CtJIS-tp.js} +2 -2
  14. package/dist/{delegate-Se1YZKMb.js.map → delegate-CtJIS-tp.js.map} +1 -1
  15. package/dist/{driver-control-acknowledgers-T2a1Ouay.js → driver-control-acknowledgers-MTrs8HAF.js} +15 -11
  16. package/dist/driver-control-acknowledgers-MTrs8HAF.js.map +1 -0
  17. package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
  18. package/dist/durable-file-gNI9ILAn.js.map +1 -0
  19. package/dist/durable.d.ts +3 -35
  20. package/dist/durable.js +10 -10
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-CY0wH838.js → graph-DfWqp_1e.js} +4 -4
  23. package/dist/graph-DfWqp_1e.js.map +1 -0
  24. package/dist/{graph-registry-By0tUj4S.js → graph-registry-BnO64cn8.js} +3 -3
  25. package/dist/{graph-registry-By0tUj4S.js.map → graph-registry-BnO64cn8.js.map} +1 -1
  26. package/dist/{improve-CWGBT13K.js → improve-CKRVQqzt.js} +8 -35
  27. package/dist/improve-CKRVQqzt.js.map +1 -0
  28. package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-sIthWkcN.d.ts} +3 -21
  29. package/dist/index.d.ts +10 -215
  30. package/dist/index.js +91 -302
  31. package/dist/index.js.map +1 -1
  32. package/dist/intelligence.d.ts +11 -143
  33. package/dist/intelligence.js +7 -81
  34. package/dist/intelligence.js.map +1 -1
  35. package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
  36. package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
  37. package/dist/kernel.d.ts +4 -3
  38. package/dist/kernel.js +12 -14
  39. package/dist/loop-runner-C4EWEcXf.d.ts +32 -0
  40. package/dist/loop-runner-DNWbTcVm.js +59 -0
  41. package/dist/loop-runner-DNWbTcVm.js.map +1 -0
  42. package/dist/loop-runner-bin.d.ts +32 -2
  43. package/dist/loop-runner-bin.js +93 -1
  44. package/dist/loop-runner-bin.js.map +1 -0
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +99 -418
  47. package/dist/mcp/index.js +121 -203
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/memory-bin.js +231 -1
  50. package/dist/mcp/memory-bin.js.map +1 -1
  51. package/dist/model-policy-CyCUwHed.js.map +1 -1
  52. package/dist/placement.d.ts +2 -33
  53. package/dist/placement.js +1 -35
  54. package/dist/placement.js.map +1 -1
  55. package/dist/platform.d.ts +188 -1
  56. package/dist/platform.js +129 -1
  57. package/dist/platform.js.map +1 -1
  58. package/dist/{prepare-Bt0IouPq.js → prepare-FzJoS68l.js} +8 -160
  59. package/dist/prepare-FzJoS68l.js.map +1 -0
  60. package/dist/{profile-Do-5xO_D.js → profile-DToH0XEs.js} +2 -2
  61. package/dist/profile-DToH0XEs.js.map +1 -0
  62. package/dist/profile-materialization-bPm0gGLO.d.ts +49 -0
  63. package/dist/profiles.d.ts +2 -2
  64. package/dist/profiles.js +3 -40
  65. package/dist/profiles.js.map +1 -1
  66. package/dist/{protected-model-port-DGxQ8_YM.d.ts → protected-model-port-DVVh-hEk.d.ts} +3 -33
  67. package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
  68. package/dist/{provision-supervisor-0jMufp4h.js → provision-supervisor-DqvWXmAE.js} +6 -6
  69. package/dist/{provision-supervisor-0jMufp4h.js.map → provision-supervisor-DqvWXmAE.js.map} +1 -1
  70. package/dist/{run-cancellation-BoW5Sg9Y.js → run-cancellation-C9oL62sW.js} +3 -7
  71. package/dist/{run-cancellation-BoW5Sg9Y.js.map → run-cancellation-C9oL62sW.js.map} +1 -1
  72. package/dist/{runtime-D37zRSs7.js → runtime-C55Zgo1R.js} +2531 -2889
  73. package/dist/runtime-C55Zgo1R.js.map +1 -0
  74. package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
  75. package/dist/{sandbox-profile-compat-xSoVtdWw.js → sandbox-profile-compat-DRr3JwDx.js} +2 -4
  76. package/dist/sandbox-profile-compat-DRr3JwDx.js.map +1 -0
  77. package/dist/{search-executor-DmgUm5p7.js → search-executor-ChOlRBgg.js} +3 -3
  78. package/dist/search-executor-ChOlRBgg.js.map +1 -0
  79. package/dist/{server-DQHJszfk.js → server-DkVBSN_S.js} +362 -67
  80. package/dist/server-DkVBSN_S.js.map +1 -0
  81. package/dist/{structural-rollout-DAvIE8mw.js → structural-rollout-C1LEk_zq.js} +80 -80
  82. package/dist/structural-rollout-C1LEk_zq.js.map +1 -0
  83. package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
  84. package/dist/substrate-CGDFTSRh.js.map +1 -0
  85. package/dist/{supervise-WuPAwfPh.js → supervise-CaUAxZZP.js} +92 -75
  86. package/dist/supervise-CaUAxZZP.js.map +1 -0
  87. package/dist/{supervisor-CPG1I9UN.js → supervisor-VXuN2OHT.js} +205 -319
  88. package/dist/supervisor-VXuN2OHT.js.map +1 -0
  89. package/dist/testing.d.ts +2 -2
  90. package/dist/testing.js +13 -13
  91. package/dist/testing.js.map +1 -1
  92. package/dist/tool-loop.d.ts +1 -1
  93. package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
  94. package/dist/tool-server-XV4aJwoQ.js.map +1 -0
  95. package/dist/top-snapshot-CbZE1JsU.js +502 -0
  96. package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
  97. package/dist/tui/bin.js +711 -1
  98. package/dist/tui/bin.js.map +1 -1
  99. package/dist/tui/index.d.ts +2 -70
  100. package/dist/tui/index.js +3 -3
  101. package/dist/{types-zWfqDjeL.d.ts → types-Cwrea-bU.d.ts} +2 -17
  102. package/dist/{types-CrNWif8-.d.ts → types-DZ6L0Bv3.d.ts} +765 -2152
  103. package/dist/workspace-store/index.d.ts +1 -107
  104. package/dist/workspace-store/index.js +1 -415
  105. package/dist/workspace-store/index.js.map +1 -1
  106. package/dist/{workspace-streams-BZZds1Fw.d.ts → workspace-streams-BiS4ABah.d.ts} +3 -18
  107. package/package.json +1 -1
  108. package/skills/agent-graphs/references/authoring.md +3 -2
  109. package/dist/coder-yhVWbdWc.js +0 -40
  110. package/dist/coder-yhVWbdWc.js.map +0 -1
  111. package/dist/delegation-status-CF4D0NZ_.js +0 -358
  112. package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
  113. package/dist/driver-control-acknowledgers-T2a1Ouay.js.map +0 -1
  114. package/dist/durable-file-B_eJr6Mb.js.map +0 -1
  115. package/dist/graph-CY0wH838.js.map +0 -1
  116. package/dist/improve-CWGBT13K.js.map +0 -1
  117. package/dist/integrations-6xttbPi9.d.ts +0 -190
  118. package/dist/integrations-dFi-ALk7.js +0 -132
  119. package/dist/integrations-dFi-ALk7.js.map +0 -1
  120. package/dist/kb-gate-C8z2juK8.d.ts +0 -80
  121. package/dist/kb-gate-DpaSwXVx.js +0 -80
  122. package/dist/kb-gate-DpaSwXVx.js.map +0 -1
  123. package/dist/loop-runner-bin-CFnrAHpl.d.ts +0 -164
  124. package/dist/loop-runner-bin-CdPlhy9g.js +0 -246
  125. package/dist/loop-runner-bin-CdPlhy9g.js.map +0 -1
  126. package/dist/memory-server-DXQ8IxGR.js +0 -234
  127. package/dist/memory-server-DXQ8IxGR.js.map +0 -1
  128. package/dist/openai-tools-DoQ32vpe.js +0 -44
  129. package/dist/openai-tools-DoQ32vpe.js.map +0 -1
  130. package/dist/openai-tools-zh2I_uD7.d.ts +0 -24
  131. package/dist/prepare-Bt0IouPq.js.map +0 -1
  132. package/dist/profile-Do-5xO_D.js.map +0 -1
  133. package/dist/profile-materialization-BnoEf1co.d.ts +0 -96
  134. package/dist/runtime-D37zRSs7.js.map +0 -1
  135. package/dist/sandbox-profile-compat-xSoVtdWw.js.map +0 -1
  136. package/dist/search-executor-DmgUm5p7.js.map +0 -1
  137. package/dist/server-DQHJszfk.js.map +0 -1
  138. package/dist/structural-rollout-DAvIE8mw.js.map +0 -1
  139. package/dist/substrate-B0TYNrXn.js.map +0 -1
  140. package/dist/supervise-WuPAwfPh.js.map +0 -1
  141. package/dist/supervisor-CPG1I9UN.js.map +0 -1
  142. package/dist/tool-server-Dqer2M4_.js.map +0 -1
  143. package/dist/top-app-C55Wa7uy.js +0 -1214
  144. package/dist/top-app-C55Wa7uy.js.map +0 -1
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { BT as OutputAdapter, HT as SandboxClient, S as RuntimeStreamEvent, _T as AgentRunSpec } from "./types-CrNWif8-.js";
2
- import { C as worktreeCliProfileMaterialization, S as validateProfileMaterialization, _ as promptModelProfileMaterialization, a as DefineProfileMaterializationContractOptions, b as renderProfileMaterializationIssues, c as ProfileMaterializationIssue, d as assertProfileMaterializes, f as controlProfileMaterialization, g as promptControlProfileMaterialization, h as profileMaterializationAxes, i as CanonicalAgentProfileMaterializationAxis, l as ValidateProfileMaterializationOptions, m as fullProfileMaterialization, n as AgentProfileMaterializationAxis, o as KnownAgentProfileMaterializationAxis, p as defineProfileMaterializationContract, r as AssertProfileMaterializationOptions, s as ProfileMaterializationContract, t as AGENT_PROFILE_MATERIALIZATION_AXES, u as assertProfileMaterialization, v as promptOnlyProfileMaterialization, x as sandboxActProfileMaterialization, y as promptResourceProfileMaterialization } from "./profile-materialization-BnoEf1co.js";
3
- import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, d as validateSurfaces, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as resolveSubjectPath } from "./improvement-adapter-D5gwwoXQ.js";
1
+ import { Px as AgentRunSpec, S as RuntimeStreamEvent, aS as SandboxClient, rS as OutputAdapter } from "./types-DZ6L0Bv3.js";
2
+ import { a as ProfileMaterializationContract, c as assertProfileMaterializes, n as AssertProfileMaterializationOptions, o as ProfileMaterializationIssue, r as DefineProfileMaterializationContractOptions, s as ValidateProfileMaterializationOptions, t as AgentProfileMaterializationAxis } from "./profile-materialization-bPm0gGLO.js";
3
+ import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as validateSurfaces } from "./improvement-adapter-sIthWkcN.js";
4
4
  import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
5
5
  import { TraceAnalystDefinition } from "@tangle-network/agent-eval";
6
6
  import { SandboxEvent } from "@tangle-network/sandbox";
@@ -167,20 +167,6 @@ interface AgentRunInvocation<TRunOutput> {
167
167
  * the eval path consumes the manifest end-to-end.
168
168
  */
169
169
  declare function unimplementedAgentRun<TRunOutput = unknown>(reason?: string): AgentRunInvocation<TRunOutput>;
170
- /**
171
- * Drain `act`'s `events` into an array AND await its `output`. Useful for
172
- * eval / outcome-measurement code paths that don't care about live
173
- * rendering. The events array is preserved so the substrate can inspect
174
- * tool calls / readiness / questions retrospectively.
175
- *
176
- * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming
177
- * (no incremental render). Use `for await (const ev of invocation.events)`
178
- * directly in the chat surface.
179
- */
180
- declare function collectAgentRun<TRunOutput>(invocation: AgentRunInvocation<TRunOutput>): Promise<{
181
- events: ReadonlyArray<RuntimeStreamEvent>;
182
- output: TRunOutput;
183
- }>;
184
170
  interface AgentRunContext {
185
171
  /** Substrate-managed trace emitter. */
186
172
  emitter: import('@tangle-network/agent-eval').TraceEmitter;
@@ -274,5 +260,5 @@ interface CreateSandboxActOptions<TPersona, TRunOutput> {
274
260
  */
275
261
  declare function createSandboxAct<TPersona, TRunOutput>(options: CreateSandboxActOptions<TPersona, TRunOutput>): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>;
276
262
  //#endregion
277
- export { AGENT_PROFILE_MATERIALIZATION_AXES, type AgentManifest, AgentManifestError, type AgentProfileMaterializationAxis, type AgentRubric, type AgentRunContext, type AgentRunInvocation, type AgentRuntime, type AgentSurfaces, type AnalystConfig, type AssertProfileMaterializationOptions, type CanonicalAgentProfileMaterializationAxis, type CreateSandboxActOptions, type CreateSurfaceImprovementProposerOptions, type DefineProfileMaterializationContractOptions, type DraftPatchInput, type DraftPatchOutput, type JudgeConfig, type KnownAgentProfileMaterializationAxis, type ProfileMaterializationContract, type ProfileMaterializationIssue, type ResolvedSurface, type RubricDimension, type SandboxActComposeOverrides, type SurfaceImprovementEdit, type SurfaceValidationIssue, type ValidateProfileMaterializationOptions, assertProfileMaterialization, assertProfileMaterializes, collectAgentRun, controlProfileMaterialization, createSandboxAct, createSurfaceImprovementProposer, defineAgent, defineProfileMaterializationContract, fullProfileMaterialization, profileMaterializationAxes, promptControlProfileMaterialization, promptModelProfileMaterialization, promptOnlyProfileMaterialization, promptResourceProfileMaterialization, renderProfileMaterializationIssues, renderSurfaceIssues, resolveSubjectPath, sandboxActProfileMaterialization, unimplementedAgentRun, validateProfileMaterialization, validateSurfaces, worktreeCliProfileMaterialization };
263
+ export { type AgentManifest, AgentManifestError, type AgentRubric, type AgentRunContext, type AgentRunInvocation, type AgentRuntime, type AgentSurfaces, type AnalystConfig, type AssertProfileMaterializationOptions, type CreateSandboxActOptions, type CreateSurfaceImprovementProposerOptions, type DefineProfileMaterializationContractOptions, type DraftPatchInput, type DraftPatchOutput, type JudgeConfig, type ProfileMaterializationContract, type ProfileMaterializationIssue, type ResolvedSurface, type RubricDimension, type SandboxActComposeOverrides, type SurfaceImprovementEdit, type SurfaceValidationIssue, type ValidateProfileMaterializationOptions, assertProfileMaterializes, createSandboxAct, createSurfaceImprovementProposer, defineAgent, renderSurfaceIssues, unimplementedAgentRun, validateSurfaces };
278
264
  //# sourceMappingURL=agent.d.ts.map
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
- import { Ca as mapSandboxEvent, Ci as validateProfileMaterialization, Dt as createSandboxForSpec, _i as promptResourceProfileMaterialization, bi as sandboxActProfileMaterialization, ci as assertProfileMaterialization, di as defineProfileMaterializationContract, fi as fullProfileMaterialization, gi as promptOnlyProfileMaterialization, hi as promptModelProfileMaterialization, li as assertProfileMaterializes, mi as promptControlProfileMaterialization, pi as profileMaterializationAxes, si as AGENT_PROFILE_MATERIALIZATION_AXES, ui as controlProfileMaterialization, vi as renderProfileMaterializationIssues, wi as worktreeCliProfileMaterialization } from "./supervisor-CPG1I9UN.js";
1
+ import { Dr as assertProfileMaterializes, Er as assertProfileMaterialization, Fi as mapSandboxEvent, Fr as sandboxActProfileMaterialization, xt as createSandboxForSpec } from "./supervisor-VXuN2OHT.js";
2
2
  import { t as sha256 } from "./content-digest-sBTLujlK.js";
3
- import "./runtime-D37zRSs7.js";
3
+ import "./runtime-C55Zgo1R.js";
4
4
  import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { parseFindingSubject } from "@tangle-network/agent-eval/analyst";
@@ -262,24 +262,6 @@ function unimplementedAgentRun(reason = "AgentRuntime.act is not yet wired for t
262
262
  output: Promise.reject(new Error(reason))
263
263
  };
264
264
  }
265
- /**
266
- * Drain `act`'s `events` into an array AND await its `output`. Useful for
267
- * eval / outcome-measurement code paths that don't care about live
268
- * rendering. The events array is preserved so the substrate can inspect
269
- * tool calls / readiness / questions retrospectively.
270
- *
271
- * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming
272
- * (no incremental render). Use `for await (const ev of invocation.events)`
273
- * directly in the chat surface.
274
- */
275
- async function collectAgentRun(invocation) {
276
- const events = [];
277
- for await (const ev of invocation.events) events.push(ev);
278
- return {
279
- events,
280
- output: await invocation.output
281
- };
282
- }
283
265
  /** Thrown when `defineAgent` finds a required surface missing on disk. */
284
266
  var AgentManifestError = class extends Error {
285
267
  agentId;
@@ -513,6 +495,6 @@ function applyComposeOverrides(base, overrides) {
513
495
  };
514
496
  }
515
497
  //#endregion
516
- export { AGENT_PROFILE_MATERIALIZATION_AXES, AgentManifestError, assertProfileMaterialization, assertProfileMaterializes, collectAgentRun, controlProfileMaterialization, createSandboxAct, createSurfaceImprovementProposer, defineAgent, defineProfileMaterializationContract, fullProfileMaterialization, profileMaterializationAxes, promptControlProfileMaterialization, promptModelProfileMaterialization, promptOnlyProfileMaterialization, promptResourceProfileMaterialization, renderProfileMaterializationIssues, renderSurfaceIssues, resolveSubjectPath, sandboxActProfileMaterialization, unimplementedAgentRun, validateProfileMaterialization, validateSurfaces, worktreeCliProfileMaterialization };
498
+ export { AgentManifestError, assertProfileMaterializes, createSandboxAct, createSurfaceImprovementProposer, defineAgent, renderSurfaceIssues, unimplementedAgentRun, validateSurfaces };
517
499
 
518
500
  //# sourceMappingURL=agent.js.map
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","names":[],"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n /** Optional: directory containing Agent Skill packages. */\n skills?: string\n /** Optional: directory containing MCP server/tool configuration. */\n mcp?: string\n /** Optional: directory containing hook definitions. */\n hooks?: string\n /** Optional: directory containing subagent definitions. */\n subagents?: string\n /** Optional: directory containing orchestration/workflow policies. */\n workflows?: string\n /** Optional: single file containing rollout-policy settings. */\n rolloutPolicy?: string\n /** Optional: single canonical AgentProfile file. */\n agentProfile?: string\n /** Optional: source root for code findings. */\n code?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return optionalPath(safeJoin(surfaces.knowledge, `${subject.slug}.md`))\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return optionalPath(safeJoin(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`))\n case 'knowledge.raw':\n return optionalPath(safeJoin(surfaces.knowledge, 'raw', `${subject.sourceId}.md`))\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n safeJoin(surfaces.systemPrompt, `${slug}.md`),\n safeJoin(surfaces.systemPrompt, slug, 'SKILL.md'),\n safeJoin(surfaces.systemPrompt, slug, 'index.md'),\n ].filter((path): path is string => path !== null)\n }\n case 'skill': {\n if (!surfaces.skills) return []\n return [\n safeJoin(surfaces.skills, subject.name, 'SKILL.md'),\n safeJoin(surfaces.skills, `${subject.name}.md`),\n ].filter((path): path is string => path !== null)\n }\n case 'tool-doc':\n if (subject.aspect) {\n return optionalPath(safeJoin(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`))\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n safeJoin(surfaces.tools, subject.tool, 'README.md'),\n safeJoin(surfaces.tools, `${subject.tool}.md`),\n ].filter((path): path is string => path !== null)\n case 'new-tool':\n return optionalPath(safeJoin(surfaces.tools, subject.name, 'README.md'))\n case 'mcp':\n if (!surfaces.mcp) return []\n return subject.tool\n ? optionalPath(safeJoin(surfaces.mcp, subject.server, `${subject.tool}.md`))\n : [\n safeJoin(surfaces.mcp, `${subject.server}.json`),\n safeJoin(surfaces.mcp, subject.server, 'README.md'),\n ].filter((path): path is string => path !== null)\n case 'hook':\n if (!surfaces.hooks) return []\n return [\n safeJoin(surfaces.hooks, `${subject.name}.md`),\n safeJoin(surfaces.hooks, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'subagent':\n if (!surfaces.subagents) return []\n return [\n safeJoin(surfaces.subagents, `${subject.name}.md`),\n safeJoin(surfaces.subagents, `${subject.name}.yaml`),\n safeJoin(surfaces.subagents, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'workflow':\n if (!surfaces.workflows) return []\n return [\n safeJoin(surfaces.workflows, `${subject.name}.md`),\n safeJoin(surfaces.workflows, `${subject.name}.yaml`),\n safeJoin(surfaces.workflows, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'rollout-policy':\n return surfaces.rolloutPolicy ? [surfaces.rolloutPolicy] : []\n case 'agent-profile':\n return surfaces.agentProfile ? [surfaces.agentProfile] : []\n case 'code': {\n if (!surfaces.code) return []\n const path = safeJoin(surfaces.code, subject.path)\n return path ? [path] : []\n }\n case 'rag':\n if (!surfaces.rag) return []\n return optionalPath(safeJoin(surfaces.rag, subject.corpus, `${subject.docId}.md`))\n case 'memory':\n if (!surfaces.memory) return []\n return optionalPath(safeJoin(surfaces.memory, `${slugify(subject.key)}.json`))\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return optionalPath(safeJoin(surfaces.scaffolding, `${slugify(subject.concern)}.md`))\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction safeJoin(root: string, ...children: string[]): string | null {\n if (children.some((child) => child.includes('\\0') || isAbsolute(child))) return null\n const rootAbsolute = resolve(root)\n const targetAbsolute = resolve(rootAbsolute, ...children)\n const escaped = relative(rootAbsolute, targetAbsolute)\n if (escaped === '..' || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) return null\n return join(root, ...children)\n}\n\nfunction optionalPath(path: string | null): string[] {\n return path ? [path] : []\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\n/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'scaffolding',\n 'memory',\n 'rag',\n 'skills',\n 'mcp',\n 'hooks',\n 'subagents',\n 'workflows',\n 'code',\n ]\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'outputSchema',\n 'rolloutPolicy',\n 'agentProfile',\n ]\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n continue\n }\n const expectedDirectory = optionalDirSurfaces.includes(key)\n if (expectedDirectory && !statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n } else if (!expectedDirectory && !statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n return issues\n}\n\n/** Format a list of surface validation issues into a human-readable error string. */\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementProposalSource`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n *\n * @experimental Manifests validate and load, but `runtime.act` is not yet wired\n * end-to-end into the substrate's eval path (`unimplementedAgentRun` is the\n * shipped default).\n */\n\nimport type { TraceAnalystDefinition } from '@tangle-network/agent-eval'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystDefinition>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\n/** Thrown when `defineAgent` finds a required surface missing on disk. */\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Surface improvement proposer — resolves analyst findings into LLM-drafted\n * candidate patches without changing the caller's repository.\n *\n * The proposer parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementProposalSource } from '../analyst-loop/types'\nimport { sha256 } from '../content-digest'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementProposerOptions {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\n/** Resolve each finding to a real surface and draft a detached patch candidate. */\nexport function createSurfaceImprovementProposer(\n opts: CreateSurfaceImprovementProposerOptions,\n): ImprovementProposalSource<SurfaceImprovementEdit> {\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // Knowledge findings flow to the knowledge proposal source so they do not double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n }\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/iteration-sandboxes'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\nimport {\n type AgentProfileMaterializationAxis,\n assertProfileMaterialization,\n sandboxActProfileMaterialization,\n} from './profile-materialization'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Optional changed axes the caller expects this path to carry. */\n requiredProfileAxes?: readonly AgentProfileMaterializationAxis[]\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n assertProfileMaterialization({\n contract: sandboxActProfileMaterialization,\n changedAxes: options.requiredProfileAxes ?? [],\n context: 'createSandboxAct',\n })\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools: mergedTools } : {}),\n ...(mergedMcp ? { mcp: mergedMcp } : {}),\n resources: { ...base.resources, files: mergedFiles },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,mBACd,SACA,UACA,UACwB;CACxB,MAAM,aAAa,yBAAyB,SAAS,QAAQ;CAC7D,IAAI,WAAW,WAAW,GAAG,OAAO;CAMpC,KAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,MAAM,WAAW,GAAG,IAAI,MAAM,KAAK,UAAU,GAAG;EACtD,IAAI,WAAW,GAAG,GAChB,OAAO;GAAE,cAAc;GAAK,kBAAkB;GAAK,QAAQ;GAAM,QAAQ;EAAgB;CAE7F;CACA,MAAM,WAAW,WAAW;CAE5B,OAAO;EACL,cAFkB,WAAW,QAAQ,IAAI,WAAW,KAAK,UAAU,QAAQ;EAG3E,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GAAG,UAAU;CAAe,IACnD,KAAK;CACT,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;CAC5C,MAAM,cAAuC,UAAU,YAAY,SAC/D,CAAC,GAAG,WAAW,GAAG,UAAU,UAAU,IACtC,CAAC,GAAG,SAAS;CACjB,OAAO;EACL,GAAG;EACH,MAAM,UAAU,QAAQ,KAAK;EAC7B;EACA,GAAI,cAAc,EAAE,OAAO,YAAY,IAAI,CAAC;EAC5C,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;EACtC,WAAW;GAAE,GAAG,KAAK;GAAW,OAAO;EAAY;CACrD;AACF"}
1
+ {"version":3,"file":"agent.js","names":[],"sources":["../src/agent/surfaces.ts","../src/agent/define-agent.ts","../src/agent/improvement-adapter.ts","../src/agent/sandbox-act.ts"],"sourcesContent":["/**\n * `AgentSurfaces` — declarative map of the mutable file/directory paths\n * the self-improvement loop can edit on behalf of an agent.\n *\n * The substrate uses this map to resolve every parsed `FindingSubject`\n * (from agent-eval) to a real on-disk path. No per-vertical glue;\n * no fabricated paths; no silent `existsSync(...)` skips that hide\n * misconfiguration from the operator.\n *\n * Surfaces are validated at `defineAgent` time — missing paths fail\n * loud with a list of every offender. A surface that's not needed\n * (e.g. an agent with no RAG corpora) is simply omitted; the loop\n * refuses to route those subjects rather than fabricating a target.\n */\n\nimport { existsSync, statSync } from 'node:fs'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { FindingSubject } from '@tangle-network/agent-eval'\n\n/**\n * Surface declarations. Every path is repo-relative (or absolute) at\n * `defineAgent` time. At resolution time, paths are joined against the\n * agent's `repoRoot`.\n *\n * `systemPrompt`, `tools`, `personas` are DIRECTORIES; the loop appends\n * `<section>.md`, `<tool>/README.md`, `<persona-id>.yaml` etc.\n * `rubric`, `outputSchema` are SINGLE FILES; the loop edits them in\n * place.\n *\n * `knowledge` is the agent-knowledge root (typically `.agent-knowledge`);\n * `applyKnowledgeWriteBlocks` writes pages relative to it.\n *\n * Optional surfaces (`scaffolding`, `memory`, `rag`, `outputSchema`)\n * can be omitted — the loop will reject findings targeting them with a\n * clear log message instead of fabricating a path.\n */\nexport interface AgentSurfaces {\n /** Directory containing one markdown file per system-prompt section. */\n systemPrompt: string\n /** Directory containing one subdir per tool (`<tool>/README.md`). */\n tools: string\n /** Single file (TypeScript module) defining the rubric weights + dimensions. */\n rubric: string\n /** Knowledge-base root; typically `.agent-knowledge`. */\n knowledge: string\n /** Directory containing one YAML/JSON file per persona. */\n personas: string\n /** Optional: directory containing scaffolding rules (precondition checks, retry policies). */\n scaffolding?: string\n /** Optional: memory store path (JSONL / SQLite / DB). */\n memory?: string\n /** Optional: directory containing RAG corpora (`<corpus>/<doc-id>.md`). */\n rag?: string\n /** Optional: single file defining the output schema (Zod / JSON Schema). */\n outputSchema?: string\n /** Optional: directory containing Agent Skill packages. */\n skills?: string\n /** Optional: directory containing MCP server/tool configuration. */\n mcp?: string\n /** Optional: directory containing hook definitions. */\n hooks?: string\n /** Optional: directory containing subagent definitions. */\n subagents?: string\n /** Optional: directory containing orchestration/workflow policies. */\n workflows?: string\n /** Optional: single file containing rollout-policy settings. */\n rolloutPolicy?: string\n /** Optional: single canonical AgentProfile file. */\n agentProfile?: string\n /** Optional: source root for code findings. */\n code?: string\n}\n\nexport interface ResolvedSurface {\n /** Absolute filesystem path the operator can `cat` / `vim`. */\n absolutePath: string\n /** Repo-relative path for PR descriptions, diffs, audit logs. */\n repoRelativePath: string\n /** Whether the path currently exists on disk. */\n exists: boolean\n /** The substrate's intent: edit an existing file or create a new one. */\n intent: 'edit-existing' | 'create-new'\n}\n\n/**\n * Resolve a parsed `FindingSubject` to the file path the substrate\n * should edit (or create) on disk.\n *\n * Returns `null` when:\n * - the subject targets a surface the agent didn't declare\n * (e.g. `rag:*` when `surfaces.rag` is undefined), OR\n * - the subject is a `cluster` (failure-mode emits these as evidence,\n * not actionable mutations — they don't route to a file).\n *\n * Returns a `ResolvedSurface` with `intent: 'create-new'` when the\n * subject names a path that doesn't yet exist (e.g. a new wiki page).\n * The caller chooses whether to honour the create — for tightly-managed\n * surfaces like `systemPrompt` it's usually a contract violation\n * (the analyst named a section that doesn't exist); for `knowledge`\n * it's the whole point.\n */\nexport function resolveSubjectPath(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ResolvedSurface | null {\n const candidates = candidatePathsForSubject(subject, surfaces)\n if (candidates.length === 0) return null\n\n // Probe candidates in order, preferring the first one that exists on disk.\n // Lets the substrate accept both the flat `<section>.md` convention and\n // the skill-dir `<section>/SKILL.md` convention without forcing one layout.\n // When none exists, fall back to the first candidate (canonical create-new).\n for (const rel of candidates) {\n const abs = isAbsolute(rel) ? rel : join(repoRoot, rel)\n if (existsSync(abs)) {\n return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: 'edit-existing' }\n }\n }\n const fallback = candidates[0]!\n const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback)\n return {\n absolutePath: fallbackAbs,\n repoRelativePath: fallback,\n exists: false,\n intent: 'create-new',\n }\n}\n\nfunction candidatePathsForSubject(\n subject: FindingSubject,\n surfaces: AgentSurfaces,\n): ReadonlyArray<string> {\n switch (subject.kind) {\n case 'knowledge.wiki':\n case 'knowledge.stale':\n return optionalPath(safeJoin(surfaces.knowledge, `${subject.slug}.md`))\n case 'knowledge.claim':\n // Claims land in a per-topic claims directory under the knowledge root.\n return optionalPath(safeJoin(surfaces.knowledge, 'claims', `${slugify(subject.topic)}.md`))\n case 'knowledge.raw':\n return optionalPath(safeJoin(surfaces.knowledge, 'raw', `${subject.sourceId}.md`))\n case 'system-prompt': {\n const slug = slugify(subject.section)\n // Prefer flat layout for create-new (canonical); probe skill-dir layout\n // in case the existing repo (tax/legal/gtm/creative) uses\n // `<section>/SKILL.md` already.\n return [\n safeJoin(surfaces.systemPrompt, `${slug}.md`),\n safeJoin(surfaces.systemPrompt, slug, 'SKILL.md'),\n safeJoin(surfaces.systemPrompt, slug, 'index.md'),\n ].filter((path): path is string => path !== null)\n }\n case 'skill': {\n if (!surfaces.skills) return []\n return [\n safeJoin(surfaces.skills, subject.name, 'SKILL.md'),\n safeJoin(surfaces.skills, `${subject.name}.md`),\n ].filter((path): path is string => path !== null)\n }\n case 'tool-doc':\n if (subject.aspect) {\n return optionalPath(safeJoin(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`))\n }\n // tool-doc default: `<tool>/README.md`; also probe `<tool>.md` for flat\n // tool-list repos.\n return [\n safeJoin(surfaces.tools, subject.tool, 'README.md'),\n safeJoin(surfaces.tools, `${subject.tool}.md`),\n ].filter((path): path is string => path !== null)\n case 'new-tool':\n return optionalPath(safeJoin(surfaces.tools, subject.name, 'README.md'))\n case 'mcp':\n if (!surfaces.mcp) return []\n return subject.tool\n ? optionalPath(safeJoin(surfaces.mcp, subject.server, `${subject.tool}.md`))\n : [\n safeJoin(surfaces.mcp, `${subject.server}.json`),\n safeJoin(surfaces.mcp, subject.server, 'README.md'),\n ].filter((path): path is string => path !== null)\n case 'hook':\n if (!surfaces.hooks) return []\n return [\n safeJoin(surfaces.hooks, `${subject.name}.md`),\n safeJoin(surfaces.hooks, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'subagent':\n if (!surfaces.subagents) return []\n return [\n safeJoin(surfaces.subagents, `${subject.name}.md`),\n safeJoin(surfaces.subagents, `${subject.name}.yaml`),\n safeJoin(surfaces.subagents, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'workflow':\n if (!surfaces.workflows) return []\n return [\n safeJoin(surfaces.workflows, `${subject.name}.md`),\n safeJoin(surfaces.workflows, `${subject.name}.yaml`),\n safeJoin(surfaces.workflows, `${subject.name}.json`),\n ].filter((path): path is string => path !== null)\n case 'rollout-policy':\n return surfaces.rolloutPolicy ? [surfaces.rolloutPolicy] : []\n case 'agent-profile':\n return surfaces.agentProfile ? [surfaces.agentProfile] : []\n case 'code': {\n if (!surfaces.code) return []\n const path = safeJoin(surfaces.code, subject.path)\n return path ? [path] : []\n }\n case 'rag':\n if (!surfaces.rag) return []\n return optionalPath(safeJoin(surfaces.rag, subject.corpus, `${subject.docId}.md`))\n case 'memory':\n if (!surfaces.memory) return []\n return optionalPath(safeJoin(surfaces.memory, `${slugify(subject.key)}.json`))\n case 'scaffolding':\n if (!surfaces.scaffolding) return []\n return optionalPath(safeJoin(surfaces.scaffolding, `${slugify(subject.concern)}.md`))\n case 'output-schema':\n if (!surfaces.outputSchema) return []\n return [surfaces.outputSchema]\n case 'websearch.outdated':\n case 'prior-run-summary':\n // Stale signals don't map to a single file — handled by the knowledge\n // adapter as `agent-knowledge:stale:*` after operator review.\n return []\n case 'cluster':\n // failure-mode cluster labels are evidence, not mutations.\n return []\n }\n}\n\nfunction safeJoin(root: string, ...children: string[]): string | null {\n if (children.some((child) => child.includes('\\0') || isAbsolute(child))) return null\n const rootAbsolute = resolve(root)\n const targetAbsolute = resolve(rootAbsolute, ...children)\n const escaped = relative(rootAbsolute, targetAbsolute)\n if (escaped === '..' || escaped.startsWith(`..${sep}`) || isAbsolute(escaped)) return null\n return join(root, ...children)\n}\n\nfunction optionalPath(path: string | null): string[] {\n return path ? [path] : []\n}\n\nfunction slugify(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\n/**\n * Validate that every declared surface exists on disk under `repoRoot`.\n *\n * Returns an array of `SurfaceValidationIssue` — empty when all required\n * surfaces resolve. `defineAgent` throws with the issues rendered, so\n * a misconfigured manifest fails at startup (not at the first finding\n * the loop produces 20 minutes later).\n */\nexport interface SurfaceValidationIssue {\n surface: keyof AgentSurfaces\n path: string\n reason: 'missing' | 'not-directory' | 'not-file'\n}\n\n/** Validate an `AgentSurfaces` map on disk — missing paths fail loud at `defineAgent` time instead of silently skipping self-improvement edits. */\nexport function validateSurfaces(\n surfaces: AgentSurfaces,\n repoRoot: string,\n): ReadonlyArray<SurfaceValidationIssue> {\n const issues: SurfaceValidationIssue[] = []\n const dirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'systemPrompt',\n 'tools',\n 'personas',\n 'knowledge',\n ]\n const fileSurfaces: ReadonlyArray<keyof AgentSurfaces> = ['rubric']\n const optionalDirSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'scaffolding',\n 'memory',\n 'rag',\n 'skills',\n 'mcp',\n 'hooks',\n 'subagents',\n 'workflows',\n 'code',\n ]\n const optionalFileSurfaces: ReadonlyArray<keyof AgentSurfaces> = [\n 'outputSchema',\n 'rolloutPolicy',\n 'agentProfile',\n ]\n\n for (const key of dirSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n }\n }\n for (const key of fileSurfaces) {\n const p = surfaces[key] as string | undefined\n if (!p) {\n issues.push({ surface: key, path: '', reason: 'missing' })\n continue\n }\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n } else if (!statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {\n const p = surfaces[key] as string | undefined\n if (p === undefined) continue\n const abs = isAbsolute(p) ? p : join(repoRoot, p)\n if (!existsSync(abs)) {\n issues.push({ surface: key, path: p, reason: 'missing' })\n continue\n }\n const expectedDirectory = optionalDirSurfaces.includes(key)\n if (expectedDirectory && !statSync(abs).isDirectory()) {\n issues.push({ surface: key, path: p, reason: 'not-directory' })\n } else if (!expectedDirectory && !statSync(abs).isFile()) {\n issues.push({ surface: key, path: p, reason: 'not-file' })\n }\n }\n return issues\n}\n\n/** Format a list of surface validation issues into a human-readable error string. */\nexport function renderSurfaceIssues(\n issues: ReadonlyArray<SurfaceValidationIssue>,\n repoRoot: string,\n): string {\n if (issues.length === 0) return ''\n const lines = issues.map(\n (i) => ` - ${i.surface}: ${i.path ? `\"${i.path}\"` : '<not set>'} (${i.reason})`,\n )\n return [\n `Agent surface validation failed against repoRoot=${repoRoot}:`,\n ...lines,\n '',\n 'Fix the manifest: every required surface must point at an existing',\n 'directory (systemPrompt / tools / personas / knowledge) or file',\n '(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)',\n 'may be omitted; the loop will reject findings targeting omitted',\n 'surfaces rather than fabricating a path.',\n ].join('\\n')\n}\n","/**\n * `defineAgent` — typed, validated manifest API for declarative agent\n * configuration. The substrate consumes this manifest to wire the\n * canonical eval pattern + analyst self-improvement loop without any\n * per-vertical glue.\n *\n * Design goal: scale to 1000s of vertical agents. Every agent declares\n * its surfaces, rubric, runtime, and analyst configuration in ~50 lines.\n * No per-vertical `ImprovementProposalSource`. No per-vertical CLI. No\n * fabricated paths.\n *\n * Validation: `defineAgent` runs `validateSurfaces` synchronously and\n * throws a structured error if any required surface is missing on\n * disk. The cost is one filesystem stat per surface (cheap); the\n * benefit is a manifest that can't ship broken.\n *\n * @experimental Manifests validate and load, but `runtime.act` is not yet wired\n * end-to-end into the substrate's eval path (`unimplementedAgentRun` is the\n * shipped default).\n */\n\nimport type { TraceAnalystDefinition } from '@tangle-network/agent-eval'\nimport type { RuntimeStreamEvent } from '../types'\nimport { type AgentSurfaces, renderSurfaceIssues, validateSurfaces } from './surfaces'\n\n// ── manifest ─────────────────────────────────────────────────────────\n\n/**\n * The full agent manifest. Each agent ships ONE of these.\n *\n * Generics:\n * `TPersona` — the agent's persona shape (loaded from\n * `surfaces.personas`). Defaults to `unknown` so the substrate's\n * persona discovery (`loadPersonas`) can accept anything; per-agent\n * code re-narrows when it matters.\n * `TRunOutput` — the shape `runtime.act` returns. Used by the rubric\n * scorers and emitted into the trace.\n */\nexport interface AgentManifest<TPersona = unknown, TRunOutput = unknown> {\n /**\n * Stable identifier — used as `projectId` in traces, as the analyst\n * loop's `runId` prefix, and as the namespace under which findings\n * are persisted. MUST match the agent's repo name to keep\n * cross-repo telemetry joinable.\n */\n id: string\n\n /**\n * Filesystem root the substrate resolves surface paths against.\n * Typically `process.cwd()` or a fixed absolute path. Use an\n * absolute path when the agent's tests may run from subdirectories\n * (vitest sometimes shifts cwd).\n */\n repoRoot: string\n\n /**\n * Map of mutable surfaces the self-improvement loop can edit. See\n * `AgentSurfaces` — required: `systemPrompt`, `tools`, `rubric`,\n * `knowledge`, `personas`. Optional: `scaffolding`, `memory`, `rag`,\n * `outputSchema`.\n *\n * Every required path is validated at `defineAgent` time. Missing\n * paths throw with the full list of offenders.\n */\n surfaces: AgentSurfaces\n\n /**\n * Rubric the substrate uses to score each run. Dimensions × weights\n * × judges. The substrate computes the weighted composite and\n * stamps it into the RunRecord.\n */\n rubric: AgentRubric<TRunOutput>\n\n /**\n * Runtime adapter — how the substrate INVOKES the agent against a\n * persona. The `act` function takes a persona + a context (with the\n * tracer the substrate threads through for span emission) and\n * returns the run output the rubric will score.\n *\n * The agent's existing production runtime goes in here; the\n * substrate is intentionally thin around it.\n */\n runtime: AgentRuntime<TPersona, TRunOutput>\n\n /**\n * Persona discovery — the substrate loads personas via this function\n * at eval start. Can read from `surfaces.personas`, an API, or be\n * hardcoded. The substrate calls it once per `runAgentEval` call;\n * persona ordering is preserved.\n */\n personas: () => Promise<ReadonlyArray<TPersona>>\n\n /**\n * Analyst kinds the substrate runs against each persona's trace.\n * Defaults to `DEFAULT_TRACE_ANALYST_KINDS` from agent-eval. Per-agent\n * authors can prune (e.g. skip `knowledge-poisoning` when there's no\n * knowledge base) or extend (custom domain kinds).\n *\n * Empty array disables the loop — useful for `pnpm eval --no-analyst`.\n */\n analystKinds: ReadonlyArray<TraceAnalystDefinition>\n\n /**\n * Analyst LLM configuration. The substrate uses these for all four\n * kinds (override per-kind via `analystKinds` if needed).\n */\n analyst: AnalystConfig\n}\n\nexport interface AgentRubric<TRunOutput> {\n /** Dimensions composing the weighted score. Weights sum to 1.0 by convention. */\n dimensions: ReadonlyArray<RubricDimension<TRunOutput>>\n /**\n * Optional judges layered on top of deterministic dimensions. Each\n * judge returns a score per dimension; the substrate averages judges\n * (mean by default) for the LLM contribution.\n */\n judges?: ReadonlyArray<JudgeConfig<TRunOutput>>\n}\n\nexport interface RubricDimension<TRunOutput> {\n /** Unique identifier — appears in finding subjects (`rubric:<id>`). */\n id: string\n /** 0..1 — weight in the composite. */\n weight: number\n /**\n * Deterministic scorer: given the persona + run output, returns a\n * 0..1 score. The substrate sums weight × score across dimensions\n * for the deterministic composite; judges supplement subjective dims.\n */\n score: (input: { persona: unknown; output: TRunOutput }) => number\n /** Optional human-readable label for reports. */\n label?: string\n}\n\nexport interface JudgeConfig<TRunOutput> {\n /** Judge identifier — appears in trace spans + manifest. */\n id: string\n /** Model snapshot to invoke. Pin the snapshot (`claude-sonnet-4-6@2025-04-15`); the validator rejects bare aliases. */\n model: string\n /** Dimensions this judge scores. */\n dimensions: ReadonlyArray<string>\n /**\n * Optional rubric anchors — text examples the judge sees as a\n * few-shot prompt to calibrate. STRONGLY recommended for subjective\n * dimensions; required by the calibration gate (Pearson ≥0.7).\n */\n anchors?: ReadonlyArray<{ input: string; output: TRunOutput; expected: Record<string, number> }>\n}\n\nexport interface AgentRuntime<TPersona, TRunOutput> {\n /**\n * Invoke the agent against one persona. Returns BOTH:\n * - `events`: an `AsyncIterable<RuntimeStreamEvent>` the chat-centric\n * product consumes verbatim (SSE / WebSocket / inline render).\n * **Streaming is mandatory — never collapse this to a single Promise.**\n * The agent's existing `runChatTurn` (or equivalent async generator)\n * plugs in here directly.\n * - `output`: a `Promise<TRunOutput>` resolved AFTER the event stream\n * drains. The eval substrate awaits this for rubric scoring; chat\n * products usually ignore it (they already rendered incrementally).\n *\n * Implementation contract:\n * 1. `act` MUST return immediately (synchronous construction of the\n * `events` iterator + the `output` promise).\n * 2. Iterating `events` drives the underlying LLM/tool calls — the\n * caller chooses when to consume.\n * 3. `output` resolves only after the iterator yields its terminal\n * event (typically `task_end`); see `collectAgentRun` helper.\n *\n * `ctx.emitter` is the substrate-threaded `TraceEmitter` — runtimes\n * SHOULD record LLM/tool spans through it for capture integrity.\n * `ctx.deadlineMs` is wall-clock; the runtime SHOULD honour for graceful\n * cancel. `ctx.signal` is the standard abort signal.\n */\n act: (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput>\n}\n\nexport interface AgentRunInvocation<TRunOutput> {\n /** Live stream of typed runtime events. Consumed by chat UX directly. */\n events: AsyncIterable<RuntimeStreamEvent>\n /** Final structured output the rubric scores. Resolves after `events` drains. */\n output: Promise<TRunOutput>\n}\n\n/**\n * Stub for agents whose `runtime.act` is not yet wired to the substrate's\n * eval path. Preserves the streaming contract (empty event stream + a\n * rejected `output` promise that tells the caller exactly what to fix).\n *\n * Per-vertical manifests usually start with this stub and replace it with\n * the agent's real streaming runtime (`runChatTurn` or equivalent) once\n * the eval path consumes the manifest end-to-end.\n */\nexport function unimplementedAgentRun<TRunOutput = unknown>(\n reason = 'AgentRuntime.act is not yet wired for this manifest',\n): AgentRunInvocation<TRunOutput> {\n return {\n events: (async function* empty(): AsyncIterable<RuntimeStreamEvent> {})(),\n output: Promise.reject(new Error(reason)),\n }\n}\n\n/**\n * Drain `act`'s `events` into an array AND await its `output`. Useful for\n * eval / outcome-measurement code paths that don't care about live\n * rendering. The events array is preserved so the substrate can inspect\n * tool calls / readiness / questions retrospectively.\n *\n * IMPORTANT: chat-centric UX MUST NOT call this — it defeats streaming\n * (no incremental render). Use `for await (const ev of invocation.events)`\n * directly in the chat surface.\n */\nexport async function collectAgentRun<TRunOutput>(\n invocation: AgentRunInvocation<TRunOutput>,\n): Promise<{ events: ReadonlyArray<RuntimeStreamEvent>; output: TRunOutput }> {\n const events: RuntimeStreamEvent[] = []\n for await (const ev of invocation.events) events.push(ev)\n const output = await invocation.output\n return { events, output }\n}\n\nexport interface AgentRunContext {\n /** Substrate-managed trace emitter. */\n emitter: import('@tangle-network/agent-eval').TraceEmitter\n /** Stable run id for this persona × variant cell. */\n runId: string\n /** Variant the runtime is exercising (e.g. `'baseline'`, `'source-grounded'`). */\n variantId?: string\n /** Wall-clock deadline (epoch ms). The runtime SHOULD honour for graceful cancel. */\n deadlineMs?: number\n /** Optional abort signal. */\n signal?: AbortSignal\n}\n\nexport interface AnalystConfig {\n /** Model the analyst kinds use. Override per-kind via `analystKinds[i].cost.models`. */\n model: string\n /** Optional total budget across all kinds for one run. Substrate enforces via `BudgetGuard`. */\n budgetUsd?: number\n /** Backend hint for the AxAIService factory — same shape every kind uses. */\n backend?: {\n name?: 'openai' | 'router'\n apiKey?: string\n baseUrl?: string\n }\n}\n\n// ── factory + validation ─────────────────────────────────────────────\n\n/** Thrown when `defineAgent` finds a required surface missing on disk. */\nexport class AgentManifestError extends Error {\n constructor(\n message: string,\n public readonly agentId: string,\n public readonly issues: ReadonlyArray<unknown> = [],\n ) {\n super(message)\n this.name = 'AgentManifestError'\n }\n}\n\n/**\n * Construct a validated agent manifest. Throws `AgentManifestError`\n * if any required surface is missing on disk.\n *\n * Generics: pass your persona / output types if you want narrowed\n * `runtime.act` signatures:\n * `defineAgent<TaxPersona, TaxRunOutput>({ ... })`\n *\n * Most callers don't need the generics — the substrate operates on\n * `unknown` payloads internally and the manifest's `score` /\n * `runtime.act` see the typed shapes via TypeScript inference at\n * the call site.\n */\nexport function defineAgent<TPersona = unknown, TRunOutput = unknown>(\n manifest: AgentManifest<TPersona, TRunOutput>,\n): AgentManifest<TPersona, TRunOutput> {\n if (!manifest.id || manifest.id.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `id` is required', manifest.id ?? '')\n }\n if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {\n throw new AgentManifestError('defineAgent: `repoRoot` is required', manifest.id)\n }\n const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot)\n if (issues.length > 0) {\n throw new AgentManifestError(\n renderSurfaceIssues(issues, manifest.repoRoot),\n manifest.id,\n issues,\n )\n }\n // Lightweight rubric sanity: weights sum to ~1.0 (no hard requirement —\n // the substrate normalizes — but flag wildly miscalibrated weights).\n const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0)\n if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {\n throw new AgentManifestError(\n `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} — should be ~1.0`,\n manifest.id,\n )\n }\n return manifest\n}\n","/**\n * Surface improvement proposer — resolves analyst findings into LLM-drafted\n * candidate patches without changing the caller's repository.\n *\n * The proposer parses each finding's `subject` via\n * `parseFindingSubject` (agent-eval), resolves it to a real file path\n * via the agent's `AgentSurfaces`, reads the current content, and asks\n * an LLM to draft a unified-diff patch given the finding + current\n * content + per-kind editing-discipline rules.\n *\n * Fail-loud rules:\n * - Findings whose subject doesn't parse → counted in `errors`.\n * - Findings whose subject targets an undeclared surface → counted in\n * `errors` with the offending kind in the message.\n * - Findings whose target path doesn't exist AND the kind isn't a\n * create-new variant (`new-tool`, `knowledge.wiki`) → counted in\n * `errors` with the resolved path in the message.\n * - LLM drafts that fail JSON-schema validation → counted in\n * `errors` with the schema issue.\n *\n * No silent skips. Every dropped finding has a recorded reason the\n * loop's report surfaces.\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { AnalystFinding, FindingSubject } from '@tangle-network/agent-eval'\nimport { parseFindingSubject } from '@tangle-network/agent-eval/analyst'\nimport type { ImprovementProposalSource } from '../analyst-loop/types'\nimport { sha256 } from '../content-digest'\nimport type { AgentSurfaces, ResolvedSurface } from './surfaces'\nimport { resolveSubjectPath } from './surfaces'\n\n// ── proposal shape ───────────────────────────────────────────────────\n\nexport interface SurfaceImprovementEdit {\n /** Stable id derived from the source finding so re-proposals are idempotent. */\n id: string\n /** The finding that produced this edit — for revert + audit trail. */\n sourceFindingId: string\n /** Parsed subject; included so the apply step doesn't re-parse. */\n subject: FindingSubject\n /** Resolved on-disk target. */\n target: ResolvedSurface\n /** SHA-256 of the current file content the patch was drafted against. */\n baseSha256: string\n /** Unified-diff patch the LLM drafted (relative to `target.absolutePath`). */\n patch: string\n /** One-line summary the operator sees in the report / PR title. */\n summary: string\n /** Multi-line rationale for the PR body — finding context + LLM reasoning. */\n rationale: string\n /** Carry-forward from the finding so the apply gate can check the threshold. */\n confidence: number\n /** Carry-forward severity for prioritization. */\n severity: AnalystFinding['severity']\n}\n\nexport interface CreateSurfaceImprovementProposerOptions {\n surfaces: AgentSurfaces\n repoRoot: string\n /**\n * LLM-draft callback. Given a finding + current file content + the\n * resolved target, returns a unified-diff patch + summary + rationale.\n *\n * Required — the substrate doesn't ship a hardcoded prompt; the agent\n * author picks the model (Haiku for cheap routine drafts, Sonnet for\n * substantive prompt rewrites, etc.) via this callback.\n */\n draftPatch: (input: DraftPatchInput) => Promise<DraftPatchOutput>\n /**\n * When the resolved target doesn't exist, allow the substrate to\n * CREATE the file (for `knowledge.wiki`, `new-tool` subjects). Default\n * true for those kinds, false for `system-prompt` / `rubric` / etc.\n * (named sections that don't exist are a contract violation, not a\n * scaffolding opportunity).\n */\n allowCreateForKinds?: ReadonlyArray<FindingSubject['kind']>\n}\n\nexport interface DraftPatchInput {\n finding: AnalystFinding\n subject: FindingSubject\n target: ResolvedSurface\n /** Current file content (empty string when `intent === 'create-new'`). */\n currentContent: string\n}\n\nexport interface DraftPatchOutput {\n /** Unified diff against the current file content. Empty string skips this finding. */\n patch: string\n /** One-line summary for the operator. */\n summary: string\n /** Multi-line rationale for the PR body. */\n rationale: string\n}\n\n// ── factory ──────────────────────────────────────────────────────────\n\nconst DEFAULT_CREATE_KINDS: ReadonlyArray<FindingSubject['kind']> = [\n 'knowledge.wiki',\n 'knowledge.claim',\n 'knowledge.raw',\n 'new-tool',\n]\n\n/** Resolve each finding to a real surface and draft a detached patch candidate. */\nexport function createSurfaceImprovementProposer(\n opts: CreateSurfaceImprovementProposerOptions,\n): ImprovementProposalSource<SurfaceImprovementEdit> {\n const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS\n\n return {\n async proposeFromFindings(findings) {\n const edits: SurfaceImprovementEdit[] = []\n const errors: Array<{ findingId: string; subject: string; message: string }> = []\n let skipped = 0\n\n for (const f of findings) {\n const subject = parseFindingSubject(f.subject)\n if (subject === null) {\n if (f.subject !== undefined) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject,\n message: 'subject does not parse against the finding-subject grammar',\n })\n } else {\n // Subject-less findings are descriptive, not actionable —\n // legitimate; count in `skipped` not `errors`.\n skipped += 1\n }\n continue\n }\n\n // `cluster` findings (failure-mode) are evidence, not mutations.\n if (subject.kind === 'cluster') {\n skipped += 1\n continue\n }\n\n // Knowledge findings flow to the knowledge proposal source so they do not double-route.\n if (subject.kind.startsWith('knowledge.')) {\n skipped += 1\n continue\n }\n\n const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot)\n if (target === null) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `subject kind \"${subject.kind}\" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`,\n })\n continue\n }\n\n if (target.intent === 'create-new' && !allowCreate.includes(subject.kind)) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `target ${target.repoRelativePath} does not exist; the kind \"${subject.kind}\" requires an existing target (analyst named a section that isn't in the codebase)`,\n })\n continue\n }\n\n const currentContent = target.exists ? readFileSync(target.absolutePath, 'utf-8') : ''\n\n let draft: DraftPatchOutput\n try {\n draft = await opts.draftPatch({ finding: f, subject, target, currentContent })\n } catch (err) {\n errors.push({\n findingId: f.finding_id,\n subject: f.subject ?? '',\n message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`,\n })\n continue\n }\n\n if (draft.patch.trim().length === 0) {\n skipped += 1\n continue\n }\n\n edits.push({\n id: `imp-${f.finding_id}`,\n sourceFindingId: f.finding_id,\n subject,\n target,\n baseSha256: sha256(currentContent),\n patch: draft.patch,\n summary: draft.summary,\n rationale: draft.rationale,\n confidence: f.confidence,\n severity: f.severity,\n })\n }\n\n return { edits, skipped, errors }\n },\n }\n}\n","/**\n * Sandbox bridge for `AgentRuntime.act` — prod-faithful eval execution.\n *\n * The point of this adapter is parity: the eval substrate must run the agent\n * through the SAME profile the production chat turn uses, or scorecard numbers\n * grade a profile that never ships. `createSandboxAct` boots a sandbox with the\n * agent's profile (the caller's `baseProfile`, with optional per-persona\n * overrides) through the loop kernel's own {@link createSandboxForSpec},\n * streams the `streamPrompt` events mapped to the `RuntimeStreamEvent`\n * vocabulary, and resolves the `OutputAdapter`-parsed output for rubric scoring\n * — satisfying the `act` streaming contract with one code path shared by chat\n * and eval.\n *\n * Agents with a bespoke streaming chat turn should wire THAT into `act`\n * directly (the contract is designed for it); this adapter is the default for\n * agents whose turn is a plain prod-profile sandbox dispatch — notably the\n * agents agent-builder generates.\n */\n\nimport type {\n AgentProfile,\n AgentProfileFileMount,\n AgentProfileMcpServer,\n} from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport type { AgentRunSpec, OutputAdapter, SandboxClient } from '../runtime'\nimport { mapSandboxEvent } from '../runtime'\nimport { createSandboxForSpec } from '../runtime/iteration-sandboxes'\nimport type { RuntimeStreamEvent } from '../types'\nimport type { AgentRunContext, AgentRunInvocation } from './define-agent'\nimport {\n type AgentProfileMaterializationAxis,\n assertProfileMaterialization,\n sandboxActProfileMaterialization,\n} from './profile-materialization'\n\n/** Per-persona profile-merge slots applied over the base profile (§1.5: the caller authors the\n * per-persona profile). Each slot overlays the base; an absent slot leaves the base untouched. */\nexport interface SandboxActComposeOverrides {\n /** Replace the base profile's system prompt (e.g. a workspace-augmented prompt). */\n systemPrompt?: string\n /** Extra file mounts layered after the base profile's `resources.files`. */\n extraFiles?: AgentProfileFileMount[]\n /** Override the profile `name`. Defaults to the base profile's name. */\n name?: string\n /** Box built-in tool ON/OFF flags merged over the base profile's `tools` (overlay wins per key). */\n tools?: Record<string, boolean>\n /** MCP connections merged over the base profile's `mcp` (overlay wins per key). */\n mcpConnections?: Record<string, AgentProfileMcpServer>\n}\n\nexport interface CreateSandboxActOptions<TPersona, TRunOutput> {\n /** Canonical agent profile — the same one the prod chat turn uses. */\n baseProfile: AgentProfile\n /** Sandbox client used to boot the per-run sandbox. */\n sandboxClient: SandboxClient\n /** Persona → prompt. Pure; the eval cell's input. */\n buildPrompt: (persona: TPersona) => string\n /** Sandbox event stream → typed output the rubric scores. */\n output: OutputAdapter<TRunOutput>\n /**\n * Per-persona profile overrides (workspace-augmented system prompt, extra\n * file mounts, tool flags, MCP connections). Overlaid onto `baseProfile`.\n */\n compose?: (persona: TPersona) => SandboxActComposeOverrides\n /** Sandbox-SDK overrides forwarded to `createSandboxForSpec`. */\n sandboxOverrides?: AgentRunSpec<unknown>['sandboxOverrides']\n /** Optional changed axes the caller expects this path to carry. */\n requiredProfileAxes?: readonly AgentProfileMaterializationAxis[]\n /** Stable run name surfaced in mapped `llm_call` events. */\n name?: string\n /** Override the `SandboxEvent → RuntimeStreamEvent` mapper. */\n mapEvent?: (\n event: SandboxEvent,\n opts: { agentRunName?: string },\n ) => RuntimeStreamEvent | undefined\n}\n\n/**\n * Build an `AgentRuntime.act` implementation backed by a single prod-profile\n * sandbox run. The returned function honours the `act` contract: it returns\n * synchronously with a live `events` iterator and an `output` promise that\n * resolves only after the iterator drains.\n */\nexport function createSandboxAct<TPersona, TRunOutput>(\n options: CreateSandboxActOptions<TPersona, TRunOutput>,\n): (persona: TPersona, ctx: AgentRunContext) => AgentRunInvocation<TRunOutput> {\n assertProfileMaterialization({\n contract: sandboxActProfileMaterialization,\n changedAxes: options.requiredProfileAxes ?? [],\n context: 'createSandboxAct',\n })\n const mapEvent = options.mapEvent ?? mapSandboxEvent\n\n return (persona: TPersona, ctx: AgentRunContext): AgentRunInvocation<TRunOutput> => {\n const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona))\n const agentRunName = options.name ?? profile.name ?? 'agent'\n const message = options.buildPrompt(persona)\n const signal = ctx.signal ?? new AbortController().signal\n\n const raw: SandboxEvent[] = []\n let settle!: (value: TRunOutput) => void\n let fail!: (err: unknown) => void\n const output = new Promise<TRunOutput>((resolve, reject) => {\n settle = resolve\n fail = reject\n })\n // The output promise rejects when the stream errors; if the caller ignores\n // `output` (chat UX) the rejection is still observed by the events iterator\n // throwing. Attach a no-op catch so an ignored rejection is never \"unhandled\".\n output.catch(() => {})\n\n const spec: AgentRunSpec<unknown> = {\n profile,\n taskToPrompt: () => message,\n name: agentRunName,\n ...(options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}),\n }\n\n async function* events(): AsyncIterable<RuntimeStreamEvent> {\n try {\n const box = await createSandboxForSpec(options.sandboxClient, spec, signal)\n for await (const event of box.streamPrompt(message, { signal })) {\n raw.push(event)\n const mapped = mapEvent(event, { agentRunName })\n if (mapped) yield mapped\n }\n settle(options.output.parse(raw))\n } catch (err) {\n fail(err)\n throw err\n }\n }\n\n return { events: events(), output }\n }\n}\n\n/** Overlay the per-persona overrides onto the base profile. Each slot merges over the base; an\n * absent override leaves the base profile untouched. */\nfunction applyComposeOverrides(\n base: AgentProfile,\n overrides: SandboxActComposeOverrides | undefined,\n): AgentProfile {\n if (!overrides) return base\n const prompt = overrides.systemPrompt\n ? { ...base.prompt, systemPrompt: overrides.systemPrompt }\n : base.prompt\n const mergedTools = overrides.tools ? { ...(base.tools ?? {}), ...overrides.tools } : base.tools\n const mergedMcp = overrides.mcpConnections\n ? { ...(base.mcp ?? {}), ...overrides.mcpConnections }\n : base.mcp\n const baseFiles = base.resources?.files ?? []\n const mergedFiles: AgentProfileFileMount[] = overrides.extraFiles?.length\n ? [...baseFiles, ...overrides.extraFiles]\n : [...baseFiles]\n return {\n ...base,\n name: overrides.name ?? base.name,\n prompt,\n ...(mergedTools ? { tools: mergedTools } : {}),\n ...(mergedMcp ? { mcp: mergedMcp } : {}),\n resources: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pC;AACF;;;AAIA,SAAS,sBACP,MACA,WACc;CACd,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,SAAS,UAAU,eACrB;EAAE,GAAG,KAAK;EAAQ,cAAc,UAAU;CAAa,IACvD,KAAK;CACT,MAAM,cAAc,UAAU,QAAQ;EAAE,GAAI,KAAK,SAAS,CAAC;EAAI,GAAG,UAAU;CAAM,IAAI,KAAK;CAC3F,MAAM,YAAY,UAAU,iBACxB;EAAE,GAAI,KAAK,OAAO,CAAC;EAAI,GAAG,UAAU;CAAe,IACnD,KAAK;CACT,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;CAC5C,MAAM,cAAuC,UAAU,YAAY,SAC/D,CAAC,GAAG,WAAW,GAAG,UAAU,UAAU,IACtC,CAAC,GAAG,SAAS;CACjB,OAAO;EACL,GAAG;EACH,MAAM,UAAU,QAAQ,KAAK;EAC7B;EACA,GAAI,cAAc,EAAE,OAAO,YAAY,IAAI,CAAC;EAC5C,GAAI,YAAY,EAAE,KAAK,UAAU,IAAI,CAAC;EACtC,WAAW;GAAE,GAAG,KAAK;GAAW,OAAO;EAAY;CACrD;AACF"}
@@ -1,7 +1,7 @@
1
- import { a as ImprovementEditBatch, c as KnowledgeProposalBatch, d as RunAnalystLoopOpts, f as RunAnalystLoopResult, i as FindingsStoreLike, l as KnowledgeProposalSource, n as AnalystRegistryLike, o as ImprovementProposalSource, r as AnalystRegistryStreamingLike, s as ImprovementReport, t as AnalystLoopEvent, u as KnowledgeReport } from "./types-zWfqDjeL.js";
1
+ import { a as ImprovementProposalSource, c as KnowledgeProposalSource, d as RunAnalystLoopResult, i as ImprovementEditBatch, l as KnowledgeReport, n as AnalystRegistryLike, o as ImprovementReport, r as FindingsStoreLike, s as KnowledgeProposalBatch, t as AnalystLoopEvent, u as RunAnalystLoopOpts } from "./types-Cwrea-bU.js";
2
2
  //#region src/analyst-loop/run-analyst-loop.d.ts
3
3
  /** Analyze a run and apply accepted knowledge and agent-surface proposals. */
4
4
  declare function runAnalystLoop<TProposal = unknown, TEdit = unknown>(opts: RunAnalystLoopOpts): Promise<RunAnalystLoopResult<TProposal, TEdit>>;
5
5
  //#endregion
6
- export { type AnalystLoopEvent, type AnalystRegistryLike, type AnalystRegistryStreamingLike, type FindingsStoreLike, type ImprovementEditBatch, type ImprovementProposalSource, type ImprovementReport, type KnowledgeProposalBatch, type KnowledgeProposalSource, type KnowledgeReport, type RunAnalystLoopOpts, type RunAnalystLoopResult, runAnalystLoop };
6
+ export { type AnalystLoopEvent, type AnalystRegistryLike, type FindingsStoreLike, type ImprovementEditBatch, type ImprovementProposalSource, type ImprovementReport, type KnowledgeProposalBatch, type KnowledgeProposalSource, type KnowledgeReport, type RunAnalystLoopOpts, type RunAnalystLoopResult, runAnalystLoop };
7
7
  //# sourceMappingURL=analyst-loop.d.ts.map
@@ -1,4 +1,4 @@
1
- import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, z as immutableCandidateValue } from "./sandbox-profile-compat-xSoVtdWw.js";
1
+ import { P as canonicalCandidateDigest$1, R as immutableCandidateValue, z as omitTopLevelDigest } from "./sandbox-profile-compat-DRr3JwDx.js";
2
2
  import { agentCandidateBundleSchema } from "@tangle-network/agent-interface";
3
3
  //#region src/candidate-execution/bundle.ts
4
4
  /** Validate and content-address a candidate bundle before it crosses an approval boundary. */
@@ -14,4 +14,4 @@ function sealAgentCandidateBundle(input) {
14
14
  //#endregion
15
15
  export { sealAgentCandidateBundle as t };
16
16
 
17
- //# sourceMappingURL=bundle-DM60AI2B.js.map
17
+ //# sourceMappingURL=bundle-DNUq-OPW.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle-DM60AI2B.js","names":["canonicalCandidateDigest"],"sources":["../src/candidate-execution/bundle.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\n}\n"],"mappings":";;;;AASA,SAAgB,yBAAyB,OAAwD;CAC/F,MAAM,SAASA,2BAAyB,KAAK;CAC7C,MAAM,SAAS,2BAA2B,MAAM;EAAE,GAAG;EAAO;CAAO,CAAC;CAEpE,IADqBA,2BAAyB,mBAAmB,MAAM,CACxD,MAAM,QACnB,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO,wBAAwB,MAAM;AACvC"}
1
+ {"version":3,"file":"bundle-DNUq-OPW.js","names":["canonicalCandidateDigest"],"sources":["../src/candidate-execution/bundle.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\n}\n"],"mappings":";;;;AASA,SAAgB,yBAAyB,OAAwD;CAC/F,MAAM,SAASA,2BAAyB,KAAK;CAC7C,MAAM,SAAS,2BAA2B,MAAM;EAAE,GAAG;EAAO;CAAO,CAAC;CAEpE,IADqBA,2BAAyB,mBAAmB,MAAM,CACxD,MAAM,QACnB,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO,wBAAwB,MAAM;AACvC"}
@@ -1,7 +1,6 @@
1
- import { $ as PreparedAgentCandidateLaunch, A as AgentCandidateMemoryPort, B as AgentCandidateProtectedRunCapture, C as AgentCandidateExecutorPort, D as AgentCandidateExecutorTaskOutcomeCapture, E as AgentCandidateExecutorStopRequest, F as AgentCandidateOutputPurpose, G as AgentCandidateWorkspacePort, H as AgentCandidateRunFinalization, I as AgentCandidateProtectedModelActivation, J as CanonicalCandidateDocument, K as CANDIDATE_TRACE_ENV, L as AgentCandidateProtectedModelReservation, M as AgentCandidateModelLimits, N as AgentCandidateModelPort, O as AgentCandidateExecutorWorkspaceFile, P as AgentCandidateOutputArtifactPort, Q as PreparedAgentCandidateKnowledge, R as AgentCandidateProtectedModelSettlement, S as AgentCandidateExecutorMemoryCapture, T as AgentCandidateExecutorRequest, U as AgentCandidateTaskExecution, V as AgentCandidateRepositoryPort, W as AgentCandidateVerificationPorts, X as PreparedAgentCandidateExecution, Y as PersistedTaskOutcomeEvidence, Z as PreparedAgentCandidateInstruction, _ as AgentCandidateBenchmarkGraderIdentity, a as captureAgentCandidateWorkspaceTreeToArtifacts, b as AgentCandidateExecutionPorts, c as verifyAgentCandidateWorkspaceTree, d as captureAgentCandidateWorkspaceFiles, et as PreparedAgentCandidateTrace, f as CaptureAgentCandidateWorkspaceOptions, g as AgentCandidateArtifactPort, h as createAgentCandidateWorkspacePort, i as captureAgentCandidateWorkspaceToArtifacts, it as AgentCandidateExecutionRoots, j as AgentCandidateMemoryResetResult, k as AgentCandidateExecutorWorkspaceInput, l as AgentCandidateWorkspaceArchiveLimits, m as captureAgentCandidateWorkspace, n as AgentCandidateWorkspaceTree, nt as VerifiedAgentCandidate, o as materializeAgentCandidateWorkspaceFromArtifacts, p as CreateAgentCandidateWorkspacePortOptions, q as CANDIDATE_TRACE_TAGS, r as CaptureAgentCandidateWorkspaceToArtifactsOptions, rt as VerifiedAgentCandidateTaskOutcome, s as verifyAgentCandidateWorkspaceArtifacts, t as AgentCandidateWorkspaceArtifactsOptions, tt as ResolvedAgentCandidateContainer, u as CapturedAgentCandidateWorkspace, v as AgentCandidateBenchmarkGraderPort, w as AgentCandidateExecutorProfileFile, x as AgentCandidateExecutorFinalCapture, y as AgentCandidateContainerPort, z as AgentCandidateProtectedModelSettlementCall } from "../workspace-streams-BZZds1Fw.js";
2
- import { A as AgentCandidateExecutionPhase, B as AgentCandidatePreparationEvidence, C as AgentCandidateExecutionClaim, D as AgentCandidateExecutionFailureClass, E as AgentCandidateExecutionCleanupHandles, F as AgentCandidateExecutionTerminalResult, I as AgentCandidateRetryRejection, L as InMemoryAgentCandidateExecutionClaimStore, M as AgentCandidateExecutionRecoveryEvidence, N as AgentCandidateExecutionStageResult, O as AgentCandidateExecutionFinishResult, P as AgentCandidateExecutionTerminalRecord, R as InMemoryAgentCandidateExecutionClaimStoreOptions, S as AgentCandidateExecutionAttemptRef, T as AgentCandidateExecutionClaimStore, _ as PrepareAgentCandidateExecutionOptions, a as AgentCandidateModelGrantSettleInput, b as executePreparedAgentCandidate, c as agentCandidateProfileAsAgentProfile, d as freezeGenericAgentCandidateProfile, f as omitUndefinedObjectFields, g as parseExactCandidateProfile, h as parseExactAgentProfileDiff, i as AgentCandidateModelGrantReserveInput, j as AgentCandidateExecutionPhaseResult, k as AgentCandidateExecutionLease, l as applyExactAgentProfileDiff, m as parseExactAgentProfile, n as AgentCandidateModelGrantClient, o as CreateProtectedAgentCandidateModelPortOptions, r as AgentCandidateModelGrantReservation, s as createProtectedAgentCandidateModelPort, t as AgentCandidateModelGrantActivateInput, u as assertCandidateProfileBinding, v as prepareAgentCandidateExecution, w as AgentCandidateExecutionClaimResult, x as AgentCandidateExecutionAttemptRecord, y as ExecutePreparedAgentCandidateOptions, z as candidateExecutionClaim } from "../protected-model-port-DGxQ8_YM.js";
3
- import { AgentCandidateArtifactRef, AgentCandidateBundle, AgentCandidateCapturedArtifact, AgentCandidateCodeDisabled, AgentCandidateCodeNoOp, AgentCandidateExecution, AgentCandidateGitHubRepository, AgentCandidateKnowledge, AgentCandidateMemoryPolicy, AgentCandidateProfile, AgentCandidateResolvedModel, AgentCandidateRunCell, AgentCandidateWorkspaceManifestMaterial, AgentCandidateWorkspaceSnapshotEvidence, AgentProfile, AgentProfileDiff, Sha256Digest } from "@tangle-network/agent-interface";
4
- import { TraceStore } from "@tangle-network/agent-eval";
1
+ import { $ as VerifiedAgentCandidate, A as AgentCandidateMemoryResetResult, B as AgentCandidateRepositoryPort, C as AgentCandidateExecutorProfileFile, D as AgentCandidateExecutorWorkspaceFile, E as AgentCandidateExecutorTaskOutcomeCapture, F as AgentCandidateProtectedModelActivation, G as CanonicalCandidateDocument, H as AgentCandidateTaskExecution, I as AgentCandidateProtectedModelReservation, J as PreparedAgentCandidateInstruction, K as PersistedTaskOutcomeEvidence, L as AgentCandidateProtectedModelSettlement, M as AgentCandidateModelPort, N as AgentCandidateOutputArtifactPort, O as AgentCandidateExecutorWorkspaceInput, P as AgentCandidateOutputPurpose, Q as ResolvedAgentCandidateContainer, R as AgentCandidateProtectedModelSettlementCall, S as AgentCandidateExecutorPort, T as AgentCandidateExecutorStopRequest, U as AgentCandidateVerificationPorts, V as AgentCandidateRunFinalization, W as AgentCandidateWorkspacePort, X as PreparedAgentCandidateLaunch, Y as PreparedAgentCandidateKnowledge, Z as PreparedAgentCandidateTrace, _ as AgentCandidateBenchmarkGraderPort, a as captureAgentCandidateWorkspaceTreeToArtifacts, b as AgentCandidateExecutorFinalCapture, c as verifyAgentCandidateWorkspaceTree, d as captureAgentCandidateWorkspaceFiles, et as VerifiedAgentCandidateTaskOutcome, f as CaptureAgentCandidateWorkspaceOptions, g as AgentCandidateArtifactPort, h as createAgentCandidateWorkspacePort, i as captureAgentCandidateWorkspaceToArtifacts, j as AgentCandidateModelLimits, k as AgentCandidateMemoryPort, l as AgentCandidateWorkspaceArchiveLimits, m as captureAgentCandidateWorkspace, n as AgentCandidateWorkspaceTree, o as materializeAgentCandidateWorkspaceFromArtifacts, p as CreateAgentCandidateWorkspacePortOptions, q as PreparedAgentCandidateExecution, r as CaptureAgentCandidateWorkspaceToArtifactsOptions, s as verifyAgentCandidateWorkspaceArtifacts, t as AgentCandidateWorkspaceArtifactsOptions, tt as AgentCandidateExecutionRoots, u as CapturedAgentCandidateWorkspace, v as AgentCandidateContainerPort, w as AgentCandidateExecutorRequest, x as AgentCandidateExecutorMemoryCapture, y as AgentCandidateExecutionPorts, z as AgentCandidateProtectedRunCapture } from "../workspace-streams-BiS4ABah.js";
2
+ import { A as AgentCandidateExecutionTerminalResult, C as AgentCandidateExecutionFinishResult, D as AgentCandidateExecutionRecoveryEvidence, E as AgentCandidateExecutionPhaseResult, M as AgentCandidatePreparationEvidence, O as AgentCandidateExecutionStageResult, S as AgentCandidateExecutionFailureClass, T as AgentCandidateExecutionPhase, _ as AgentCandidateExecutionAttemptRef, a as createProtectedAgentCandidateModelPort, b as AgentCandidateExecutionClaimStore, c as assertCandidateProfileBinding, d as parseExactAgentProfileDiff, g as AgentCandidateExecutionAttemptRecord, h as executePreparedAgentCandidate, i as CreateProtectedAgentCandidateModelPortOptions, j as AgentCandidateRetryRejection, k as AgentCandidateExecutionTerminalRecord, l as freezeGenericAgentCandidateProfile, m as ExecutePreparedAgentCandidateOptions, n as AgentCandidateModelGrantClient, o as agentCandidateProfileAsAgentProfile, p as prepareAgentCandidateExecution, r as AgentCandidateModelGrantReserveInput, s as applyExactAgentProfileDiff, t as AgentCandidateModelGrantActivateInput, v as AgentCandidateExecutionClaim, w as AgentCandidateExecutionLease, x as AgentCandidateExecutionCleanupHandles, y as AgentCandidateExecutionClaimResult } from "../protected-model-port-DVVh-hEk.js";
3
+ import { AgentCandidateArtifactRef, AgentCandidateBundle, AgentCandidateCapturedArtifact, AgentCandidateCodeDisabled, AgentCandidateCodeNoOp, AgentCandidateExecution, AgentCandidateGitHubRepository, AgentCandidateKnowledge, AgentCandidateMemoryPolicy, AgentCandidateProfile, AgentCandidateResolvedModel, AgentCandidateWorkspaceManifestMaterial, AgentCandidateWorkspaceSnapshotEvidence, AgentProfile, AgentProfileDiff, Sha256Digest } from "@tangle-network/agent-interface";
5
4
  import { CodeSurface } from "@tangle-network/agent-eval/campaign";
6
5
  import { AgentEnvironmentProvider, AgentExactProcessResources } from "@tangle-network/agent-interface/environment-provider";
7
6
  //#region src/candidate-execution/artifacts.d.ts
@@ -35,24 +34,6 @@ interface WorkspaceScanOptions {
35
34
  */
36
35
  readonly portableTree?: boolean;
37
36
  }
38
- /**
39
- * Refuse a materialized workspace whose files, modes, or bytes are not the signed manifest.
40
- *
41
- * The scan streams, so the size of the largest file does not decide whether the check can run, and
42
- * the refusal names the one mismatch a caller can produce on its own: a capture and a verify that
43
- * disagree about `portableTree`.
44
- */
45
- declare function verifyMaterializedWorkspace(root: string, expected: AgentCandidateWorkspaceManifestMaterial, options?: Omit<WorkspaceScanOptions, 'limits'>): Promise<void>;
46
- /**
47
- * The canonical manifest of one materialized workspace, read without holding any file.
48
- *
49
- * Every file is digested by streaming, so the size of the largest file does not decide whether the
50
- * workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with
51
- * `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify
52
- * against a manifest it already matched. The digest is sha-256 over the same bytes either way, so
53
- * a manifest a buffered read produced is reproduced exactly.
54
- */
55
- declare function scanMaterializedWorkspaceManifest(root: string, options?: WorkspaceScanOptions): Promise<AgentCandidateWorkspaceManifestMaterial>;
56
37
  /**
57
38
  * Build the canonical manifest for files a caller already holds — the shape a remote executor
58
39
  * returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and
@@ -161,26 +142,6 @@ interface ExactProcessCandidateExecutorOptions {
161
142
  /** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */
162
143
  declare function exactProcessProviderAsCandidateExecutor(options: ExactProcessCandidateExecutorOptions): AgentCandidateExecutorPort;
163
144
  //#endregion
164
- //#region src/candidate-execution/knowledge.d.ts
165
- /** Environment variable containing the materialized candidate knowledge root. */
166
- declare const CANDIDATE_KNOWLEDGE_ROOT_ENV = "TANGLE_CANDIDATE_KNOWLEDGE_ROOT";
167
- /** Environment variable containing the materialized retrieval configuration path. */
168
- declare const CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV = "TANGLE_CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG";
169
- /** Deterministic, signed locations used by every candidate executor. */
170
- declare function candidateKnowledgeExecutionPaths(taskRoot: string, hasRetrievalConfig: boolean): {
171
- root: string;
172
- retrievalConfig?: string;
173
- };
174
- //#endregion
175
- //#region src/candidate-execution/output-artifacts.d.ts
176
- /** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
177
- declare function persistCandidateOutputArtifact(port: AgentCandidateOutputArtifactPort, input: {
178
- executionId: string;
179
- purpose: AgentCandidateOutputPurpose;
180
- bytes: Uint8Array;
181
- signal?: AbortSignal;
182
- }): Promise<AgentCandidateArtifactRef>;
183
- //#endregion
184
145
  //#region src/candidate-execution/protected-model-grant.d.ts
185
146
  /** Reservation fields supplied by a caller before Runtime resolves the model. */
186
147
  type AgentCandidateModelGrantRunReservationInput = Omit<AgentCandidateModelGrantReserveInput, 'resolved'>;
@@ -220,37 +181,7 @@ interface RunProtectedAgentCandidateModelGrantResult<TResult> {
220
181
  */
221
182
  declare function runProtectedAgentCandidateModelGrant<TResult>(options: RunProtectedAgentCandidateModelGrantOptions<TResult>): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>>;
222
183
  //#endregion
223
- //#region src/candidate-execution/recover.d.ts
224
- interface RecoverExpiredAgentCandidateOptions {
225
- attempt: AgentCandidateExecutionAttemptRef;
226
- claimStore: AgentCandidateExecutionClaimStore;
227
- executor: AgentCandidateExecutorPort;
228
- traceStore: TraceStore;
229
- ports: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>;
230
- outputArtifacts: AgentCandidateOutputArtifactPort;
231
- cleanupTimeoutMs?: number;
232
- /** Evaluator clock; must be the same clock used by the claim store. */
233
- now?: () => number;
234
- }
235
- /** Close an expired crashed attempt from persisted non-secret handles, then record failure. */
236
- declare function recoverExpiredAgentCandidateExecution(options: RecoverExpiredAgentCandidateOptions): Promise<AgentCandidateExecutionFinishResult>;
237
- //#endregion
238
184
  //#region src/candidate-execution/verify.d.ts
239
- /** Surfaces admitted by Runtime's verifier before an environment adapter is selected. */
240
- declare const AGENT_CANDIDATE_EXECUTION_SUPPORT: Readonly<{
241
- outcomes: readonly ["workspace", "output"];
242
- code: readonly ["disabled", "no-op", "git-patch"];
243
- memory: readonly ["disabled", "isolated"];
244
- knowledge: true;
245
- profile: Readonly<{
246
- mcpTransports: readonly ["stdio"];
247
- remoteMcp: false;
248
- tools: false;
249
- permissions: false;
250
- modes: false;
251
- confidential: false;
252
- }>;
253
- }>;
254
185
  /** Verifies every digest, resource, workspace, and Git object in a candidate bundle. */
255
186
  declare function verifyAgentCandidateBundle(input: unknown, ports: AgentCandidateVerificationPorts): Promise<VerifiedAgentCandidate>;
256
187
  //#endregion
@@ -346,34 +277,6 @@ interface SeedWorkspaceTreeInput {
346
277
  /** Default `'tree-v1'`; decides only the digest this returns, never the bytes it writes. */
347
278
  readonly algorithm?: WorkspaceTreeAlgorithm;
348
279
  }
349
- /**
350
- * Describe one directory tree by content, streaming every file.
351
- *
352
- * The digest covers, for every entry in sorted order: its kind, its tree-relative path, its mode
353
- * under the selected algorithm, and then — for a file, its length and its own sha-256; for a kept
354
- * link, its target; for an excluded entry, the reason and the target. A file's content therefore
355
- * never enters the tree hash directly, which is what removes any in-memory size ceiling: the tree
356
- * hash consumes 32 bytes per file however large the file is.
357
- *
358
- * A hard-linked regular file is described like any other regular file. Its content is what the
359
- * digest is about, and a package manager that links a store into `node_modules` is ordinary
360
- * content, not a reason to refuse a workspace.
361
- */
362
- declare function describeWorkspaceTree(directory: string, options?: DescribeWorkspaceTreeOptions): Promise<WorkspaceTreeDescriptor>;
363
- /**
364
- * Seed a workspace from a directory, one entry at a time, and return the digest of what was
365
- * seeded.
366
- *
367
- * Nothing is packed: `cp` walks and copies file by file, so a multi-gigabyte seed costs one file
368
- * handle rather than one archive in memory. Existing destination entries are never overwritten —
369
- * a seed that could replace a file the workspace already holds would make the resulting tree
370
- * depend on the order two seeds ran in.
371
- *
372
- * Links are copied verbatim, exactly as they were written. Following them would copy bytes from
373
- * outside the seed into the workspace, which is the same rule {@link describeWorkspaceTree}
374
- * applies to the digest.
375
- */
376
- declare function seedWorkspaceTree(input: SeedWorkspaceTreeInput): Promise<WorkspaceTreeDescriptor>;
377
280
  //#endregion
378
- export { AGENT_CANDIDATE_EXECUTION_SUPPORT, type AgentCandidateArtifactPort, type AgentCandidateBenchmarkGraderIdentity, type AgentCandidateBenchmarkGraderPort, type AgentCandidateBundleInput, type AgentCandidateCodeSource, type AgentCandidateCodeSurfaceSource, type AgentCandidateContainerPort, type AgentCandidateExecutionAttemptRecord, type AgentCandidateExecutionAttemptRef, type AgentCandidateExecutionClaim, type AgentCandidateExecutionClaimResult, type AgentCandidateExecutionClaimStore, type AgentCandidateExecutionCleanupHandles, type AgentCandidateExecutionFailureClass, type AgentCandidateExecutionFinishResult, type AgentCandidateExecutionLease, type AgentCandidateExecutionPhase, type AgentCandidateExecutionPhaseResult, type AgentCandidateExecutionPorts, type AgentCandidateExecutionRecoveryEvidence, type AgentCandidateExecutionRoots, type AgentCandidateExecutionStageResult, type AgentCandidateExecutionTerminalRecord, type AgentCandidateExecutionTerminalResult, type AgentCandidateExecutorFinalCapture, type AgentCandidateExecutorMemoryCapture, type AgentCandidateExecutorPort, type AgentCandidateExecutorProfileFile, type AgentCandidateExecutorRequest, type AgentCandidateExecutorStopRequest, type AgentCandidateExecutorTaskOutcomeCapture, type AgentCandidateExecutorWorkspaceFile, type AgentCandidateExecutorWorkspaceInput, type AgentCandidateMemoryPort, type AgentCandidateMemoryResetResult, type AgentCandidateModelGrantActivateInput, type AgentCandidateModelGrantClient, type AgentCandidateModelGrantReservation, type AgentCandidateModelGrantReserveInput, type AgentCandidateModelGrantRunReservationInput, type AgentCandidateModelGrantSettleInput, type AgentCandidateModelLimits, type AgentCandidateModelPort, type AgentCandidateOutputArtifactPort, type AgentCandidateOutputPurpose, type AgentCandidatePreparationEvidence, type AgentCandidateProfileSource, type AgentCandidateProtectedModelActivation, type AgentCandidateProtectedModelReservation, type AgentCandidateProtectedModelSettlement, type AgentCandidateProtectedModelSettlementCall, type AgentCandidateProtectedRunCapture, type AgentCandidateRepositoryPort, type AgentCandidateRetryRejection, type AgentCandidateRunFinalization, type AgentCandidateTaskExecution, type AgentCandidateVerificationPorts, type AgentCandidateWorkspaceArchiveLimits, type AgentCandidateWorkspaceArtifactsOptions, type AgentCandidateWorkspacePort, type AgentCandidateWorkspaceSnapshotReferences, type AgentCandidateWorkspaceTree, type BuildAgentCandidateBundleInput, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, CANDIDATE_KNOWLEDGE_ROOT_ENV, CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, type CanonicalCandidateDocument, type CaptureAgentCandidateWorkspaceOptions, type CaptureAgentCandidateWorkspaceToArtifactsOptions, type CaptureAgentWorkspaceSnapshotOptions, type CapturedAgentCandidateWorkspace, type CreateAgentCandidateWorkspacePortOptions, type CreateProtectedAgentCandidateModelPortOptions, type DescribeWorkspaceTreeOptions, type DisposePreparedAgentCandidateOptions, type ExactProcessCandidateExecutorOptions, type ExecutePreparedAgentCandidateOptions, FileAgentCandidateExecutionClaimStore, type FileAgentCandidateExecutionClaimStoreOptions, InMemoryAgentCandidateExecutionClaimStore, type InMemoryAgentCandidateExecutionClaimStoreOptions, type MaterializeAgentWorkspaceSnapshotOptions, type PersistedTaskOutcomeEvidence, type PrepareAgentCandidateExecutionOptions, type PreparedAgentCandidateExecution, type PreparedAgentCandidateInstruction, type PreparedAgentCandidateKnowledge, type PreparedAgentCandidateLaunch, type PreparedAgentCandidateTrace, type ProtectedAgentCandidateModelGrantContext, type RecoverExpiredAgentCandidateOptions, type ResolvedAgentCandidateContainer, type RunProtectedAgentCandidateModelGrantOptions, type RunProtectedAgentCandidateModelGrantResult, type SeedWorkspaceTreeInput, type VerifiedAgentCandidate, type VerifiedAgentCandidateTaskOutcome, type WorkspaceScanLimits, type WorkspaceScanOptions, type WorkspaceTreeAlgorithm, type WorkspaceTreeDescriptor, type WorkspaceTreeEntryPolicy, type WorkspaceTreeExclusion, type WorkspaceTreeExclusionReason, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateExecutionClaim, candidateKnowledgeExecutionPaths, candidateWorkspaceManifest, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, captureAgentCandidateWorkspaceToArtifacts, captureAgentCandidateWorkspaceTreeToArtifacts, captureAgentWorkspaceSnapshot, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, describeWorkspaceTree, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, materializeAgentCandidateWorkspaceFromArtifacts, materializeAgentWorkspaceSnapshot, omitUndefinedObjectFields, parseExactAgentProfile, parseExactAgentProfileDiff, parseExactCandidateProfile, persistCandidateOutputArtifact, prepareAgentCandidateExecution, recoverExpiredAgentCandidateExecution, runProtectedAgentCandidateModelGrant, scanMaterializedWorkspaceManifest, sealAgentCandidateBundle, seedWorkspaceTree, verifyAgentCandidateBundle, verifyAgentCandidateWorkspaceArtifacts, verifyAgentCandidateWorkspaceTree, verifyMaterializedWorkspace };
281
+ export { type AgentCandidateArtifactPort, type AgentCandidateBenchmarkGraderPort, type AgentCandidateBundleInput, type AgentCandidateCodeSource, type AgentCandidateCodeSurfaceSource, type AgentCandidateContainerPort, type AgentCandidateExecutionAttemptRecord, type AgentCandidateExecutionAttemptRef, type AgentCandidateExecutionClaim, type AgentCandidateExecutionClaimResult, type AgentCandidateExecutionClaimStore, type AgentCandidateExecutionCleanupHandles, type AgentCandidateExecutionFailureClass, type AgentCandidateExecutionFinishResult, type AgentCandidateExecutionLease, type AgentCandidateExecutionPhase, type AgentCandidateExecutionPhaseResult, type AgentCandidateExecutionPorts, type AgentCandidateExecutionRecoveryEvidence, type AgentCandidateExecutionRoots, type AgentCandidateExecutionStageResult, type AgentCandidateExecutionTerminalRecord, type AgentCandidateExecutionTerminalResult, type AgentCandidateExecutorFinalCapture, type AgentCandidateExecutorMemoryCapture, type AgentCandidateExecutorPort, type AgentCandidateExecutorProfileFile, type AgentCandidateExecutorRequest, type AgentCandidateExecutorStopRequest, type AgentCandidateExecutorTaskOutcomeCapture, type AgentCandidateExecutorWorkspaceFile, type AgentCandidateExecutorWorkspaceInput, type AgentCandidateMemoryPort, type AgentCandidateMemoryResetResult, type AgentCandidateModelGrantClient, type AgentCandidateModelGrantReserveInput, type AgentCandidateModelGrantRunReservationInput, type AgentCandidateModelLimits, type AgentCandidateModelPort, type AgentCandidateOutputArtifactPort, type AgentCandidateOutputPurpose, type AgentCandidatePreparationEvidence, type AgentCandidateProfileSource, type AgentCandidateProtectedModelActivation, type AgentCandidateProtectedModelReservation, type AgentCandidateProtectedModelSettlement, type AgentCandidateProtectedModelSettlementCall, type AgentCandidateProtectedRunCapture, type AgentCandidateRepositoryPort, type AgentCandidateRetryRejection, type AgentCandidateRunFinalization, type AgentCandidateTaskExecution, type AgentCandidateVerificationPorts, type AgentCandidateWorkspaceArtifactsOptions, type AgentCandidateWorkspacePort, type AgentCandidateWorkspaceSnapshotReferences, type AgentCandidateWorkspaceTree, type BuildAgentCandidateBundleInput, type CanonicalCandidateDocument, type CaptureAgentCandidateWorkspaceOptions, type CaptureAgentCandidateWorkspaceToArtifactsOptions, type CaptureAgentWorkspaceSnapshotOptions, type CapturedAgentCandidateWorkspace, type CreateAgentCandidateWorkspacePortOptions, type CreateProtectedAgentCandidateModelPortOptions, type DescribeWorkspaceTreeOptions, type DisposePreparedAgentCandidateOptions, type ExactProcessCandidateExecutorOptions, type ExecutePreparedAgentCandidateOptions, FileAgentCandidateExecutionClaimStore, type FileAgentCandidateExecutionClaimStoreOptions, type MaterializeAgentWorkspaceSnapshotOptions, type PersistedTaskOutcomeEvidence, type PreparedAgentCandidateExecution, type PreparedAgentCandidateInstruction, type PreparedAgentCandidateKnowledge, type PreparedAgentCandidateLaunch, type PreparedAgentCandidateTrace, type ProtectedAgentCandidateModelGrantContext, type ResolvedAgentCandidateContainer, type RunProtectedAgentCandidateModelGrantOptions, type RunProtectedAgentCandidateModelGrantResult, type SeedWorkspaceTreeInput, type VerifiedAgentCandidate, type VerifiedAgentCandidateTaskOutcome, type WorkspaceScanLimits, type WorkspaceScanOptions, type WorkspaceTreeAlgorithm, type WorkspaceTreeDescriptor, type WorkspaceTreeEntryPolicy, type WorkspaceTreeExclusion, type WorkspaceTreeExclusionReason, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateWorkspaceManifest, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, captureAgentCandidateWorkspaceToArtifacts, captureAgentCandidateWorkspaceTreeToArtifacts, captureAgentWorkspaceSnapshot, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, materializeAgentCandidateWorkspaceFromArtifacts, materializeAgentWorkspaceSnapshot, parseExactAgentProfileDiff, prepareAgentCandidateExecution, runProtectedAgentCandidateModelGrant, sealAgentCandidateBundle, verifyAgentCandidateBundle, verifyAgentCandidateWorkspaceArtifacts, verifyAgentCandidateWorkspaceTree };
379
282
  //# sourceMappingURL=index.d.ts.map