@tangle-network/agent-runtime 0.193.1 → 0.195.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 (131) hide show
  1. package/dist/{activation-BismttgN.js → activation-DtIbcFOX.js} +3 -3
  2. package/dist/{activation-BismttgN.js.map → activation-DtIbcFOX.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-nvqVIMyS.js} +5 -4
  7. package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-nvqVIMyS.js.map} +1 -1
  8. package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
  9. package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/conversation.js +1 -1
  12. package/dist/{coordination-driver-DujHiIGa.js → coordination-driver-iSN-m3VX.js} +281 -244
  13. package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
  14. package/dist/{authoring-DWiqKSDY.js → delegate-DCC2muUd.js} +56 -13
  15. package/dist/delegate-DCC2muUd.js.map +1 -0
  16. package/dist/delegation-status-BlsbSeOB.js +358 -0
  17. package/dist/delegation-status-BlsbSeOB.js.map +1 -0
  18. package/dist/durable.d.ts +2 -2
  19. package/dist/durable.js +3 -3
  20. package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
  21. package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
  22. package/dist/{environment-provider-DpPGJfK-.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{graph-DORfp9WX.js → graph-DghidDx5.js} +138 -5
  26. package/dist/graph-DghidDx5.js.map +1 -0
  27. package/dist/graph.d.ts +3 -3
  28. package/dist/graph.js +4 -5
  29. package/dist/graph.js.map +1 -1
  30. package/dist/{improve-Bn1zpWHF.d.ts → improve-7VTwse1c.d.ts} +6 -6
  31. package/dist/{improvement-cycle-BbsiYcpH.js → improvement-cycle-bTBySunH.js} +22 -8
  32. package/dist/{improvement-cycle-BbsiYcpH.js.map → improvement-cycle-bTBySunH.js.map} +1 -1
  33. package/dist/{index-Vz-13VZq.d.ts → index-CVD30soi.d.ts} +4 -4
  34. package/dist/{index-DV1lzp9p.d.ts → index-DNx0nWZH.d.ts} +57 -51
  35. package/dist/{index-RM2oRI9s.d.ts → index-DO6DHgRP.d.ts} +2 -2
  36. package/dist/index.d.ts +10 -9
  37. package/dist/index.js +75 -29
  38. package/dist/index.js.map +1 -1
  39. package/dist/intelligence.d.ts +5 -5
  40. package/dist/intelligence.js +7 -6
  41. package/dist/intelligence.js.map +1 -1
  42. package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
  43. package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
  44. package/dist/kernel.d.ts +6 -6
  45. package/dist/kernel.js +11 -12
  46. package/dist/{knowledge-RW1pbZCH.js → knowledge-U8WJ5xCI.js} +7 -17
  47. package/dist/knowledge-U8WJ5xCI.js.map +1 -0
  48. package/dist/knowledge.d.ts +1 -1
  49. package/dist/knowledge.js +1 -1
  50. package/dist/{loop-runner-bin-sBwcyQTc.js → loop-runner-bin-BU2NACsF.js} +3 -3
  51. package/dist/{loop-runner-bin-sBwcyQTc.js.map → loop-runner-bin-BU2NACsF.js.map} +1 -1
  52. package/dist/{loop-runner-bin-CGraqNiA.d.ts → loop-runner-bin-b4585v9Z.d.ts} +3 -3
  53. package/dist/loop-runner-bin.d.ts +1 -1
  54. package/dist/loop-runner-bin.js +1 -1
  55. package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
  56. package/dist/materialization-vZssF9Nx.js.map +1 -0
  57. package/dist/mcp/bin.js +3 -3
  58. package/dist/mcp/index.d.ts +4 -4
  59. package/dist/mcp/index.js +8 -8
  60. package/dist/mcp/index.js.map +1 -1
  61. package/dist/{openai-tools-6jUqkGG7.js → openai-tools-DmvmaG0a.js} +2 -2
  62. package/dist/{openai-tools-6jUqkGG7.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
  63. package/dist/{prepare-B5fJ7mLS.js → prepare-DDGp0-rW.js} +4 -59
  64. package/dist/prepare-DDGp0-rW.js.map +1 -0
  65. package/dist/primeintellect/index.d.ts +1 -1
  66. package/dist/profiles.js +454 -1
  67. package/dist/profiles.js.map +1 -1
  68. package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-DxFN8DLS.js} +3 -2
  69. package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-DxFN8DLS.js.map} +1 -1
  70. package/dist/{protected-redaction--F3v1oo8.js → protected-redaction-wGo44k2K.js} +54 -3
  71. package/dist/protected-redaction-wGo44k2K.js.map +1 -0
  72. package/dist/{provision-supervisor-CddfH9mg.js → provision-supervisor-CRPbnJiB.js} +6 -8
  73. package/dist/{provision-supervisor-CddfH9mg.js.map → provision-supervisor-CRPbnJiB.js.map} +1 -1
  74. package/dist/{redact-D0OzQsyt.js → redact-BOU77QfQ.js} +1013 -24
  75. package/dist/redact-BOU77QfQ.js.map +1 -0
  76. package/dist/{runtime-V91N6sPc.d.ts → runtime-B8x43nGP.d.ts} +5 -4
  77. package/dist/{runtime-ZM4i-jEF.js → runtime-CuNJ0opC.js} +153 -77
  78. package/dist/runtime-CuNJ0opC.js.map +1 -0
  79. package/dist/server-D6XmE1Du.js +1311 -0
  80. package/dist/server-D6XmE1Du.js.map +1 -0
  81. package/dist/{stream-agent-turn-1ahpdeIo.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
  82. package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
  83. package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
  84. package/dist/{structural-rollout-CktnUTCC.js → structural-rollout-DxEQ77H7.js} +37 -51
  85. package/dist/structural-rollout-DxEQ77H7.js.map +1 -0
  86. package/dist/{supervise-Dj6zd2C7.js → supervise-C0V3pZXK.js} +154 -1961
  87. package/dist/supervise-C0V3pZXK.js.map +1 -0
  88. package/dist/testing.d.ts +2 -2
  89. package/dist/testing.js +14 -13
  90. package/dist/testing.js.map +1 -1
  91. package/dist/tui/index.d.ts +1 -1
  92. package/dist/tui/index.js +1 -1
  93. package/dist/{types-CGez_ZHQ.d.ts → types-B_pNTBjK.d.ts} +5 -2
  94. package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-Ybomp7AN.js} +3 -2
  95. package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-Ybomp7AN.js.map} +1 -1
  96. package/package.json +4 -4
  97. package/skills/agent-graphs/SKILL.md +28 -123
  98. package/skills/agent-graphs/references/authoring.md +34 -0
  99. package/skills/agent-graphs/references/measurement.md +18 -0
  100. package/skills/build-with-agent-runtime/SKILL.md +31 -117
  101. package/skills/build-with-agent-runtime/references/improvement.md +32 -0
  102. package/skills/codemode/SKILL.md +22 -34
  103. package/skills/codemode/references/runtime-execution.md +14 -0
  104. package/skills/generate-eval/SKILL.md +2 -1
  105. package/skills/loop-writer/SKILL.md +30 -84
  106. package/skills/supervise/SKILL.md +43 -77
  107. package/skills/supervise/references/profile-authoring.md +19 -0
  108. package/dist/authoring-DWiqKSDY.js.map +0 -1
  109. package/dist/coordination-driver-DujHiIGa.js.map +0 -1
  110. package/dist/environment-provider-DEwsolvi.js.map +0 -1
  111. package/dist/executable-spec-DxuiDFAU.js.map +0 -1
  112. package/dist/graph-DORfp9WX.js.map +0 -1
  113. package/dist/jsonl-file-CDfsCI5s.js +0 -59
  114. package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
  115. package/dist/knowledge-RW1pbZCH.js.map +0 -1
  116. package/dist/materialization-CekWK6OO.js.map +0 -1
  117. package/dist/prepare-B5fJ7mLS.js.map +0 -1
  118. package/dist/protected-redaction--F3v1oo8.js.map +0 -1
  119. package/dist/redact-D0OzQsyt.js.map +0 -1
  120. package/dist/researcher-hgPa5p9i.js +0 -457
  121. package/dist/researcher-hgPa5p9i.js.map +0 -1
  122. package/dist/runtime-ZM4i-jEF.js.map +0 -1
  123. package/dist/snapshot-CTAf4uuA.js +0 -26
  124. package/dist/snapshot-CTAf4uuA.js.map +0 -1
  125. package/dist/spawn-journal-B9eTmVAn.js +0 -999
  126. package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
  127. package/dist/structural-rollout-CktnUTCC.js.map +0 -1
  128. package/dist/supervise-Dj6zd2C7.js.map +0 -1
  129. package/dist/util-mCNUeboW.js +0 -419
  130. package/dist/util-mCNUeboW.js.map +0 -1
  131. package/skills/agent-graphs/IMPROVE.md +0 -58
package/dist/index.js CHANGED
@@ -1,20 +1,24 @@
1
1
  import { a as JudgeError, c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError, o as NotFoundError, r as BackendTransportError, s as PlannerError, t as AgentEvalError, u as RetainedRunAdmissionError } from "./errors-CDZ8XsVj.js";
2
- import { a as normalizeBackendStreamEvent, c as nowIso, i as createSandboxPromptBackend, l as startOrResumeRuntimeSession, o as InMemoryRuntimeSessionStore, r as createIterableBackend, u as touchSession } from "./stream-agent-turn-DWWe_7bh.js";
3
- import { $ as parseExactAgentProfile, G as applyExactAgentProfileDiff, K as assertCandidateProfileBinding, S as CANDIDATE_TRACE_TAGS, W as agentCandidateProfileAsAgentProfile, Y as freezeGenericAgentCandidateProfile, Z as omitUndefinedObjectFields, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, at as scanMaterializedWorkspaceManifest, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, lt as canonicalCandidateDigest$1, n as executePreparedAgentCandidate, nt as candidateWorkspaceManifest, pt as immutableCandidateValue, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, st as verifyMaterializedWorkspace, t as prepareAgentCandidateExecution, tt as parseExactCandidateProfile, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "./prepare-B5fJ7mLS.js";
4
- import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "./workspace-archive-yAPDklLV.js";
5
- import { a as disposePreparedAgentCandidateExecution, i as runProtectedAgentCandidateModelGrant, n as seedWorkspaceTree, o as FileAgentCandidateExecutionClaimStore, r as recoverExpiredAgentCandidateExecution, s as buildAgentCandidateBundle, t as describeWorkspaceTree } from "./candidate-execution-BSkZErxD.js";
6
- import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "./protected-model-port-B0xFSAjt.js";
7
- import { C as makePerAttemptSignal, S as defaultIsRetryable, T as createProfileExecutionBackend, _ as readDepth, a as FileConversationJournal, b as DeadlineExceededError, c as createConversationBackend, d as slugifySpeaker, f as turnId, g as isDepthExceeded, h as buildForwardHeaders, i as d1ToSqlAdapter, l as runConversation, m as FORWARD_HEADERS, n as runPersonaDispatch, o as InMemoryConversationJournal, p as DEFAULT_MAX_DEPTH, r as SqlConversationJournal, s as defineConversation, t as runPersonaConversation, u as runConversationStream, v as CircuitBreakerState, w as sleep, x as computeBackoff, y as CircuitOpenError } from "./conversation-DILnmy84.js";
8
- import { Cn as sanitizeKnowledgeReadinessReport, Sn as sanitizeAgentRuntimeEvent, _n as padSpanId, bn as createRuntimeEventCollector, cn as buildLoopOtelSpans, dn as createOpenInferenceFileExporter, fn as createOtelExporter, gn as loopEventToOtelSpan, hn as generateSpanId, ln as buildLoopSpanNodes, n as defaultRedactorIdentityMaterial, pn as exportEvalRuns, r as resolveRedactor, sn as INTELLIGENCE_WIRE_VERSION, t as defaultRedactor, un as buildRuntimeEventOtelSpans, vn as padTraceId, wn as sanitizeRuntimeStreamEvent, xn as createRuntimeStreamEventCollector, yn as toOtelAttributes } from "./redact-D0OzQsyt.js";
2
+ import { a as normalizeBackendStreamEvent, c as nowIso, i as createSandboxPromptBackend, l as startOrResumeRuntimeSession, o as InMemoryRuntimeSessionStore, r as createIterableBackend, u as touchSession } from "./stream-agent-turn-DOtEsvCV.js";
3
+ import { o as canonicalCandidateDigest$1, u as immutableCandidateValue } from "./protected-redaction-wGo44k2K.js";
4
+ import { $ as parseExactAgentProfile, G as applyExactAgentProfileDiff, K as assertCandidateProfileBinding, S as CANDIDATE_TRACE_TAGS, W as agentCandidateProfileAsAgentProfile, Y as freezeGenericAgentCandidateProfile, Z as omitUndefinedObjectFields, _ as candidateExecutionClaim, a as persistCandidateOutputArtifact, at as scanMaterializedWorkspaceManifest, c as CANDIDATE_KNOWLEDGE_ROOT_ENV, et as parseExactAgentProfileDiff, f as verifyAgentCandidateBundle, h as InMemoryAgentCandidateExecutionClaimStore, l as candidateKnowledgeExecutionPaths, n as executePreparedAgentCandidate, nt as candidateWorkspaceManifest, s as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, st as verifyMaterializedWorkspace, t as prepareAgentCandidateExecution, tt as parseExactCandidateProfile, u as AGENT_CANDIDATE_EXECUTION_SUPPORT, x as CANDIDATE_TRACE_ENV } from "./prepare-DDGp0-rW.js";
5
+ import { i as sealAgentCandidateBundle, n as captureAgentCandidateWorkspaceFiles, r as createAgentCandidateWorkspacePort, t as captureAgentCandidateWorkspace } from "./workspace-archive-Ybomp7AN.js";
6
+ import { a as disposePreparedAgentCandidateExecution, i as runProtectedAgentCandidateModelGrant, n as seedWorkspaceTree, o as FileAgentCandidateExecutionClaimStore, r as recoverExpiredAgentCandidateExecution, s as buildAgentCandidateBundle, t as describeWorkspaceTree } from "./candidate-execution-nvqVIMyS.js";
7
+ import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "./protected-model-port-DxFN8DLS.js";
8
+ import { C as makePerAttemptSignal, S as defaultIsRetryable, T as createProfileExecutionBackend, _ as readDepth, a as FileConversationJournal, b as DeadlineExceededError, c as createConversationBackend, d as slugifySpeaker, f as turnId, g as isDepthExceeded, h as buildForwardHeaders, i as d1ToSqlAdapter, l as runConversation, m as FORWARD_HEADERS, n as runPersonaDispatch, o as InMemoryConversationJournal, p as DEFAULT_MAX_DEPTH, r as SqlConversationJournal, s as defineConversation, t as runPersonaConversation, u as runConversationStream, v as CircuitBreakerState, w as sleep, x as computeBackoff, y as CircuitOpenError } from "./conversation-BXPWMOSd.js";
9
+ import { Bn as sanitizeRuntimeStreamEvent, Cn as INTELLIGENCE_WIRE_VERSION, Dn as createOpenInferenceFileExporter, En as buildRuntimeEventOtelSpans, Fn as toOtelAttributes, In as createRuntimeEventCollector, Ln as createRuntimeStreamEventCollector, Mn as loopEventToOtelSpan, Nn as padSpanId, On as createOtelExporter, Pn as padTraceId, Rn as sanitizeAgentRuntimeEvent, Tn as buildLoopSpanNodes, jn as generateSpanId, kn as exportEvalRuns, n as defaultRedactorIdentityMaterial, r as resolveRedactor, t as defaultRedactor, wn as buildLoopOtelSpans, zn as sanitizeKnowledgeReadinessReport } from "./redact-BOU77QfQ.js";
9
10
  import { i as notifyRuntimeHookEvent, n as defineRuntimeHooks, r as notifyRuntimeDecisionPoint, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
10
- import { D as optimizerMethod, O as strategyAuthorMethod } from "./structural-rollout-CktnUTCC.js";
11
- import { B as ROLLOUT_POLICY_EXTENSION, G as structuralRolloutPolicyFromProfile, H as normalizeRolloutPolicy, J as defaultBuildPrompt, K as agenticGenerator, L as improve, R as withMethodRuntimeControls, U as parseRolloutPolicy, V as applyRolloutPolicyToProfile, W as serializeRolloutPolicy, q as commandVerifier, z as rawTraceDistiller } from "./improvement-cycle-BbsiYcpH.js";
12
- import { Ft as connectStdioMcp, Pt as McpSpawnFault } from "./runtime-ZM4i-jEF.js";
13
- import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-RW1pbZCH.js";
14
- import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-sBwcyQTc.js";
15
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-6jUqkGG7.js";
11
+ import { D as optimizerMethod, O as strategyAuthorMethod } from "./structural-rollout-DxEQ77H7.js";
12
+ import { B as ROLLOUT_POLICY_EXTENSION, G as structuralRolloutPolicyFromProfile, H as normalizeRolloutPolicy, J as defaultBuildPrompt, K as agenticGenerator, L as improve, R as withMethodRuntimeControls, U as parseRolloutPolicy, V as applyRolloutPolicyToProfile, W as serializeRolloutPolicy, q as commandVerifier, z as rawTraceDistiller } from "./improvement-cycle-bTBySunH.js";
13
+ import { Ft as connectStdioMcp, Pt as McpSpawnFault } from "./runtime-CuNJ0opC.js";
14
+ import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-U8WJ5xCI.js";
15
+ import { a as isDelegatedLoopMode, c as worktreeLoopRunner, i as auditLoopRunner, n as runLoopRunnerCli, o as researchLoopRunner, r as DELEGATED_LOOP_MODES, s as runDelegatedLoop, t as parseLoopRunnerArgv } from "./loop-runner-bin-BU2NACsF.js";
16
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "./openai-tools-DmvmaG0a.js";
16
17
  import { agentProfileSchema, canonicalAgentProfileDigest } from "@tangle-network/agent-interface";
17
18
  import { FAILURE_CLASSES, acquisitionPlansForKnowledgeGaps, blockingKnowledgeEval, canonicalJson, runAgentControlLoop, scoreKnowledgeReadiness, userQuestionsForKnowledgeGaps } from "@tangle-network/agent-eval";
19
+ import { createHash } from "node:crypto";
20
+ import { readFileSync, realpathSync } from "node:fs";
21
+ import { isAbsolute, relative, resolve, sep } from "node:path";
18
22
  import { gepaOptimizationMethod, skillOptOptimizationMethod } from "@tangle-network/agent-eval/campaign";
19
23
  import { spawnSync } from "node:child_process";
20
24
  import { isDeepStrictEqual } from "node:util";
@@ -509,38 +513,80 @@ const promptInstructionsProfileComponents = Object.freeze({
509
513
  function reflectiveGenerator(opts) {
510
514
  return {
511
515
  kind: "reflective",
512
- async generate({ worktreePath, findings }) {
513
- const batch = await opts.improvementProposalSource.proposeFromFindings(findings);
516
+ async generate(context) {
517
+ const { worktreePath, findings, signal } = context;
518
+ signal.throwIfAborted();
519
+ const batch = await opts.createImprovementProposalSource(context).proposeFromFindings(findings);
520
+ signal.throwIfAborted();
521
+ if (batch.errors.length > 0) throw new AggregateError(batch.errors.map((error) => /* @__PURE__ */ new Error(`${error.findingId}: ${error.message}`)), `reflectiveGenerator: proposal failed: ${batch.errors.map((error) => error.message).join("; ")}`);
514
522
  if (batch.edits.length === 0) return {
515
523
  applied: false,
516
524
  summary: ""
517
525
  };
518
- let applied = 0;
519
- for (const edit of batch.edits) if (applyPatch(edit.patch, worktreePath)) applied++;
520
- if (applied === 0) return {
521
- applied: false,
522
- summary: ""
523
- };
526
+ for (const edit of batch.edits) {
527
+ assertPatchTarget(edit, worktreePath);
528
+ assertCurrentBase(edit, worktreePath);
529
+ }
530
+ applyPatches(batch.edits, worktreePath);
531
+ signal.throwIfAborted();
524
532
  return {
525
533
  applied: true,
526
- summary: batch.edits.length === 1 ? batch.edits[0].summary : `analyst: ${applied} surface edit${applied === 1 ? "" : "s"}`
534
+ summary: batch.edits.length === 1 ? batch.edits[0].summary : `analyst: ${batch.edits.length} surface edits`
527
535
  };
528
536
  }
529
537
  };
530
538
  }
531
- /** Apply a proposed patch inside the isolated candidate worktree.
532
- * candidate worktree (a fresh checkout of baseRef, so `-p0` paths match). */
533
- function applyPatch(patch, cwd) {
534
- return spawnSync("git", [
539
+ function assertPatchTarget(edit, cwd) {
540
+ for (const reverse of [false, true]) {
541
+ const result = spawnSync("git", [
542
+ "apply",
543
+ "--numstat",
544
+ "-z",
545
+ "-p0",
546
+ ...reverse ? ["--reverse"] : [],
547
+ "-"
548
+ ], {
549
+ cwd,
550
+ input: edit.patch,
551
+ encoding: "utf8"
552
+ });
553
+ if (result.error) throw result.error;
554
+ if (result.status !== 0) throw new Error(`reflectiveGenerator: invalid patch: ${result.stderr.trim()}`);
555
+ const paths = result.stdout.split("\0").filter(Boolean).map((entry) => entry.slice(entry.indexOf(" ", entry.indexOf(" ") + 1) + 1));
556
+ const target = resolve(cwd, edit.target.repoRelativePath);
557
+ if (paths.length === 0 || paths.some((path) => resolve(cwd, path) !== target)) throw new Error("reflectiveGenerator: patch paths do not match the declared target");
558
+ }
559
+ }
560
+ function assertCurrentBase(edit, cwd) {
561
+ const root = realpathSync(cwd);
562
+ const path = resolve(root, edit.target.repoRelativePath);
563
+ assertWithinWorktree(root, path);
564
+ let content;
565
+ try {
566
+ assertWithinWorktree(root, realpathSync(path));
567
+ content = readFileSync(path, "utf8");
568
+ } catch (error) {
569
+ if (edit.target.intent !== "create-new" || !(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
570
+ content = "";
571
+ }
572
+ if (createHash("sha256").update(content, "utf8").digest("hex") !== edit.baseSha256) throw new Error(`reflectiveGenerator: stale proposal base for ${edit.target.repoRelativePath}`);
573
+ }
574
+ function assertWithinWorktree(root, path) {
575
+ const local = relative(root, path);
576
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local)) throw new Error("reflectiveGenerator: proposal target is outside the candidate worktree");
577
+ }
578
+ function applyPatches(edits, cwd) {
579
+ const result = spawnSync("git", [
535
580
  "apply",
536
- "--whitespace=fix",
537
581
  "-p0",
538
582
  "-"
539
583
  ], {
540
584
  cwd,
541
- input: patch,
585
+ input: edits.map((edit) => `${edit.patch.trimEnd()}\n`).join(""),
542
586
  encoding: "utf-8"
543
- }).status === 0;
587
+ });
588
+ if (result.error) throw result.error;
589
+ if (result.status !== 0) throw new Error(`reflectiveGenerator: patch batch failed: ${result.stderr.trim()}`);
544
590
  }
545
591
  //#endregion
546
592
  //#region src/model-resolution.ts