@andorra-labs/code 0.1.6 → 0.1.7

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 (108) hide show
  1. package/dist/src/agent-execution.js +404 -25
  2. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  3. package/dist/src/agent-mcp-catalog.js +40 -0
  4. package/dist/src/agent-mcp.d.ts +19 -3
  5. package/dist/src/agent-mcp.js +18 -44
  6. package/dist/src/app-server/protocol.d.ts +25 -3
  7. package/dist/src/app-server/protocol.js +5 -1
  8. package/dist/src/app-server/workspace.d.ts +8 -1
  9. package/dist/src/app-server/workspace.js +43 -2
  10. package/dist/src/app-server.js +88 -3
  11. package/dist/src/auth/AuthManager.d.ts +33 -1
  12. package/dist/src/auth/AuthManager.js +138 -10
  13. package/dist/src/auth/callback-page.d.ts +4 -0
  14. package/dist/src/auth/callback-page.js +70 -0
  15. package/dist/src/auth/callback.d.ts +39 -0
  16. package/dist/src/auth/callback.js +146 -22
  17. package/dist/src/auth/index.d.ts +10 -6
  18. package/dist/src/auth/index.js +2 -2
  19. package/dist/src/auth/store.d.ts +142 -3
  20. package/dist/src/auth/store.js +334 -13
  21. package/dist/src/auth/types.d.ts +17 -1
  22. package/dist/src/auth-commands.d.ts +11 -2
  23. package/dist/src/auth-commands.js +14 -7
  24. package/dist/src/automation-tool.js +10 -2
  25. package/dist/src/automations.d.ts +5 -0
  26. package/dist/src/automations.js +10 -0
  27. package/dist/src/capabilities.d.ts +9 -3
  28. package/dist/src/capabilities.js +7 -3
  29. package/dist/src/cli.js +31 -4
  30. package/dist/src/codex-provider.js +12 -0
  31. package/dist/src/coding-tools.d.ts +5 -0
  32. package/dist/src/coding-tools.js +54 -48
  33. package/dist/src/commands.d.ts +5 -1
  34. package/dist/src/commands.js +7 -6
  35. package/dist/src/completion.js +46 -0
  36. package/dist/src/config.d.ts +48 -0
  37. package/dist/src/config.js +248 -10
  38. package/dist/src/context-budget.d.ts +7 -0
  39. package/dist/src/context-budget.js +18 -1
  40. package/dist/src/decision/FactContinuations.d.ts +41 -6
  41. package/dist/src/decision/FactContinuations.js +211 -64
  42. package/dist/src/decision/PreparedSteps.js +3 -1
  43. package/dist/src/decision/checks.d.ts +25 -0
  44. package/dist/src/decision/checks.js +77 -6
  45. package/dist/src/delegation-changes.d.ts +109 -0
  46. package/dist/src/delegation-changes.js +431 -0
  47. package/dist/src/graph-server.d.ts +1 -0
  48. package/dist/src/graph-server.js +15 -3
  49. package/dist/src/graph-sync.d.ts +15 -0
  50. package/dist/src/graph-sync.js +50 -1
  51. package/dist/src/graph-tool.d.ts +52 -0
  52. package/dist/src/graph-tool.js +136 -0
  53. package/dist/src/graph-ui/app.js +212 -43
  54. package/dist/src/graph-ui/controls.js +6 -0
  55. package/dist/src/graph-ui/drafts.js +39 -0
  56. package/dist/src/graph-ui/embed.js +1 -1
  57. package/dist/src/graph-ui/index.html +2 -2
  58. package/dist/src/graph-ui/studio.css +7 -5
  59. package/dist/src/graph-ui/style.css +46 -12
  60. package/dist/src/graphs.d.ts +15 -2
  61. package/dist/src/graphs.js +42 -13
  62. package/dist/src/hardened-runtime.d.ts +4 -4
  63. package/dist/src/hardened-runtime.js +109 -9
  64. package/dist/src/powershell-pool.d.ts +9 -0
  65. package/dist/src/powershell-pool.js +16 -0
  66. package/dist/src/provider-keys.d.ts +48 -0
  67. package/dist/src/provider-keys.js +121 -0
  68. package/dist/src/pull-requests.d.ts +14 -5
  69. package/dist/src/pull-requests.js +28 -10
  70. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  71. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  72. package/dist/src/react-runtime.js +30 -2
  73. package/dist/src/read-image.d.ts +30 -0
  74. package/dist/src/read-image.js +97 -0
  75. package/dist/src/secret-redaction.d.ts +13 -0
  76. package/dist/src/secret-redaction.js +71 -0
  77. package/dist/src/session-summary.d.ts +10 -4
  78. package/dist/src/session-summary.js +14 -7
  79. package/dist/src/sessions.js +4 -1
  80. package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/telemetry/schema.d.ts +1 -1
  83. package/dist/src/telemetry/schema.js +1 -1
  84. package/dist/src/terminal-ui.d.ts +9 -0
  85. package/dist/src/terminal-ui.js +14 -0
  86. package/dist/src/tool-dependencies.js +4 -0
  87. package/dist/src/tools.d.ts +9 -0
  88. package/dist/src/tools.js +116 -11
  89. package/dist/src/transcript.js +5 -0
  90. package/dist/src/types.d.ts +13 -0
  91. package/dist/src/web-search.d.ts +59 -0
  92. package/dist/src/web-search.js +216 -0
  93. package/docs/agents/README.md +2 -2
  94. package/docs/agents/mcp-server.md +15 -2
  95. package/docs/concepts/README.md +1 -1
  96. package/docs/concepts/security.md +2 -2
  97. package/docs/getting-started/accounts.md +15 -4
  98. package/docs/getting-started/configure-providers.md +1 -1
  99. package/docs/guides/README.md +1 -0
  100. package/docs/guides/desktop-app.md +1 -1
  101. package/docs/guides/graph-builder.md +1 -1
  102. package/docs/guides/web-search.md +47 -0
  103. package/docs/reference/cli.md +4 -3
  104. package/docs/reference/config.md +3 -3
  105. package/docs/reference/slash-commands.md +2 -1
  106. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  107. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  108. package/package.json +1 -1
@@ -15,21 +15,27 @@ import { randomUUID } from 'node:crypto';
15
15
  import { TodoStore } from './todos.js';
16
16
  import { execFile } from 'node:child_process';
17
17
  import { promisify } from 'node:util';
18
- import { mkdtemp } from 'node:fs/promises';
18
+ import { mkdtemp, realpath } from 'node:fs/promises';
19
19
  import { tmpdir } from 'node:os';
20
- import { join } from 'node:path';
20
+ import { join, relative } from 'node:path';
21
21
  import { ClarificationRequiredError, DEFAULT_GRAPH, LIMIT_KEYS, isUnlimitedAlias, resolveLimits, turnModelTask } from './runtime.js';
22
22
  import { createRunTelemetry, mergeRunTelemetry, recordAttempt, recordDecisionEvent, recordEfficiencyEvent } from './telemetry/capture.js';
23
23
  import { bindUserWaits, createRuntimeBudget } from './deadline.js';
24
24
  import { createAgentEngine } from './hardened-runtime.js';
25
25
  import { completionTool } from './completion.js';
26
- import { capabilitySubset, effectiveCapabilities, intakeCapabilities, permitsBuiltInTool } from './graphs.js';
26
+ import { DELIVERED_OUTCOME, capabilitySubset, delegatesWriting, effectiveCapabilities, intakeCapabilities, isWritingRole, permitsBuiltInTool } from './graphs.js';
27
+ import { DELEGATION_DIFF_LIMIT, LandingRestoreError, addChangeWorktree, assertDelegationGit, applyLanding, collectChange, prepareLanding, removeChangeWorktree, repositoryRoot, snapshotWorkspace } from './delegation-changes.js';
28
+ import { classifyWorkspaceWrites } from './tools.js';
29
+ import { stopQaProcessesUnder } from './qa/runtime/ProcessManager.js';
30
+ import { disposePooledPowerShellUnder } from './powershell-pool.js';
27
31
  import { validateValue } from './handoffs.js';
28
32
  import { ArtifactStore } from './artifacts.js';
29
33
  import { approveOperation, capabilityTools, gitReadTool } from './capabilities.js';
30
34
  import { permissionMode, serializeApprovals, assertPlanMutationAllowed } from './permissions.js';
31
35
  import { adaptLegacyCodingToolArguments, canonicalToolName, canonicalizeToolList } from './tool-names.js';
32
36
  const exec = promisify(execFile);
37
+ /** How many times one accept_change prepares a landing when the working folder keeps changing under it. */
38
+ const LANDING_ATTEMPTS = 3;
33
39
  /** Serialized size of the `restore_tools` schema the engine adds when a catalog omits anything. */
34
40
  const RESTORE_TOOL_SCHEMA_CHARS = 420;
35
41
  const MISSING_CONFIRMATION = 'Use ask_user and obtain a real answer confirming design considerations before completing.';
@@ -45,6 +51,18 @@ Use ask_user to clarify requirements and explicitly confirm or revise proposed d
45
51
  Write user-facing questions, choices and progress in plain everyday language. Ask one concrete decision at a time. Explain what changes for the user, not file names, code symbols, terminal escape sequences, git jargon or internal terms. Keep detailed research, repository workflow rules and test plans in codebaseFindings and taskInstruction, not the question or answer choices. Use 1-3 short proposedDesign notes only for consequences the user needs to decide. Prefer 2-3 short choices (about 2-6 words each), put your recommendation first and label it (Recommended). Never repeat tool-result JSON in public messages. For example: "Should this update include both scrolling and the Enter-key change?" with "Fix scrolling only (Recommended)" and "Include both changes".
46
52
  After inspection and user confirmation, return a compact structured handoff containing the originalTask, requirements, acceptanceCriteria, designConsiderations, codebaseFindings and taskInstruction. Include agreed decisions and unresolved facts, not conversation transcripts. Do not implement code during intake. Spawning is optional and bounded by policy.
47
53
  When multiple completion outcomes are declared, use this node's prompt and the confirmed task to choose exactly one declared outcome string. The graph follows every connection for that outcome, which may start several downstream branches. Never return an array of outcomes or invent an undeclared outcome. Selecting a route does not replace the required plan, research, user confirmation or structured handoff.`;
54
+ /** Appended to the Orchestrator instructions only while delegation is active (a writing role and a routed `delivered` outcome). */
55
+ const DELEGATION_INSTRUCTIONS = `This Orchestrator can also deliver the work through writing subagents. Two paths end this node: complete with the outcome "completed" to hand the task instruction to the next node as usual, or complete with the outcome "delivered" once subagents implemented the work and you reviewed and accepted their changes. Choose from the task: hand off when the next node should implement, deliver when the work fits bounded subagent tasks you can review.
56
+ Clarify first on either path: publish the plan with update_todos, research, and obtain the user's confirmation with ask_user before any writing subagent starts; writing spawns are refused until then.
57
+ Delegate implementation to the writing roles with spawn_subagent, several in parallel when their tasks are independent. Each runs in its own Git worktree started from the working folder as it stands and may run commands and tests there. Give each one a bounded task carrying the confirmed requirements and acceptance criteria, and ask it to report the commands and tests it ran.
58
+ Each writing spawn returns a change record: an id (use it exactly as returned), the changed files, the diff (the full diff is behind read_artifact when truncated), the worktree path, and the tests report the subagent gave. Review every change: read the diff, read files inside the worktree with your read tools when the diff is not enough, and weigh the tests report; a failure report is grounds for a fix.
59
+ Decide every change: accept_change with its id lands it in the working folder as uncommitted edits; discard_change drops it. A new subagent starts from the working folder, so it sees landed work only, never a change still waiting for your decision. To build on a change, accept it first and then spawn the follow-up. When work is wrong or incomplete, discard it and spawn a redo whose task carries your review findings, then review the redo. A conflict lands nothing and names the files: the change no longer fits the working folder and accepting it again conflicts again, so discard it, spawn a redo (it starts from the folder as it now stands) and accept the redo.
60
+ Complete with "delivered" only when no subagent is still running, at least one change landed, and every change is accepted or discarded. Never write code or run commands yourself: you have no write or shell tools, and the change tools take only an id.`;
61
+ /**
62
+ * Appended to a delegating Orchestrator's instructions when it continues a resumed conversation:
63
+ * the change registry is per visit and is not restored.
64
+ */
65
+ const RESUMED_DELEGATION_INSTRUCTIONS = `This run was resumed. Changes from before the resume are no longer tracked: their ids are unknown to accept_change and discard_change, and their worktrees are gone. Work that was already landed stays in the working folder. Spawn again for anything that was still undecided. Completing as "delivered" needs at least one change accepted after the resume; otherwise complete as "completed".`;
48
66
  /**
49
67
  * The exemption a retry attempt needs from the rule above.
50
68
  *
@@ -165,6 +183,15 @@ export async function executeAgentNode(node, options) {
165
183
  options = { ...options, runId: randomUUID() };
166
184
  const store = options.artifactStore ?? new ArtifactStore(options.runId ?? randomUUID());
167
185
  const orchestrator = node.agentRole === 'orchestrator';
186
+ // Delegation is offered only when the graph routes `delivered`; otherwise a writing role is refused
187
+ // at spawn exactly as before, and nothing below changes behavior.
188
+ const delegationActive = orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME);
189
+ // A resumed conversation is continued under the system message of its checkpoint, so the note
190
+ // goes there, once: the instructions built below for a fresh conversation are not sent.
191
+ if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(RESUMED_DELEGATION_INSTRUCTIONS)) {
192
+ const [system, ...rest] = options.resumeMessages;
193
+ options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${RESUMED_DELEGATION_INSTRUCTIONS}` }, ...rest] };
194
+ }
168
195
  const retainedIntake = orchestrator && options.resumeMessages && options.resumeState?.orchestratorIntake?.nodeId === node.id
169
196
  ? options.resumeState.orchestratorIntake : undefined;
170
197
  let clarified = retainedIntake?.clarified ?? false;
@@ -175,6 +202,79 @@ export async function executeAgentNode(node, options) {
175
202
  const maxTotal = Math.min(policy.maxTotal ?? 8, node.maxSubagents ?? Infinity);
176
203
  const approve = serializeApprovals((name, args, approvalSignal) => bounded.approve(name, args, approvalSignal), () => permissionMode(bounded));
177
204
  let active = 0, total = 0;
205
+ /** Changes of this visit's writing subagents, by change id. */
206
+ const changes = new Map();
207
+ /** Worktrees holding a pending change: the Orchestrator reads inside them without an outside-workspace prompt. */
208
+ const delegationRoots = [];
209
+ /** Every delegated worktree still on disk, whether or not a change holds it; all are removed when the node ends. */
210
+ const liveWorktrees = new Set();
211
+ /**
212
+ * Stops the processes a writing child left running inside its delegated worktree. There are two
213
+ * kinds, each kept by its own registry: a background job started with AsyncProcess, which
214
+ * outlives the tool call and the child, and the interpreter PowerShellFast reuses, which stays
215
+ * alive for its idle time after a command. Nothing can stop either afterwards (the Orchestrator
216
+ * has no shell), so they end with their child, and again before the worktree is removed: a
217
+ * job's listeners would outlive the folder, and on Windows a process whose current directory is
218
+ * a folder keeps the folder from being deleted. Both stops wait until the processes are gone.
219
+ */
220
+ const stopWorktreeJobs = async (worktree) => {
221
+ // The tools key a process by the real path of the child's workspace, which can be spelled differently.
222
+ const root = await realpath(worktree).catch(() => undefined);
223
+ for (const folder of root !== undefined && root !== worktree ? [worktree, root] : [worktree]) {
224
+ await stopQaProcessesUnder(folder);
225
+ await disposePooledPowerShellUnder(folder);
226
+ }
227
+ };
228
+ /** Removes a delegated worktree and forgets it as a trusted read root. Best effort, like the removal itself. */
229
+ const dropWorktree = async (worktree) => {
230
+ liveWorktrees.delete(worktree);
231
+ await stopWorktreeJobs(worktree);
232
+ const root = await realpath(worktree).catch(() => undefined);
233
+ const index = root === undefined ? -1 : delegationRoots.indexOf(root);
234
+ if (index >= 0)
235
+ delegationRoots.splice(index, 1);
236
+ await removeChangeWorktree(options.context.workspace, worktree);
237
+ };
238
+ /**
239
+ * Node-end cleanup, on every exit: an undecided change is discarded and announced, and every
240
+ * delegated worktree goes, including one a cancelled child was still working in. Accepted changes
241
+ * are already in the working folder and stay there. Also runs before a retry attempt, which
242
+ * starts a conversation that never saw the undecided changes. Returns the changes it discarded.
243
+ */
244
+ const releaseChanges = async () => {
245
+ const discarded = [];
246
+ for (const change of changes.values()) {
247
+ if (change.state !== 'pending' && change.state !== 'conflict')
248
+ continue;
249
+ change.state = 'discarded';
250
+ discarded.push(change);
251
+ }
252
+ for (const worktree of [...liveWorktrees])
253
+ await dropWorktree(worktree);
254
+ for (const change of discarded)
255
+ await emit('subagent.change', { subagentId: change.subagentId, changeId: change.id, state: 'discarded', files: change.files.map(file => file.path) });
256
+ return discarded;
257
+ };
258
+ // Delegated worktree setup is approved once per node visit: the first writing spawn's grant covers
259
+ // the visit's worktrees, with the same live-mode recheck the per-spawn path keeps. Concurrent
260
+ // writing spawns share one prompt rather than each raising their own.
261
+ let worktreeAudited = false, worktreeGranted = false;
262
+ let worktreeApproval;
263
+ const authorizeDelegatedWorktree = async (parentContext, approvalArgs) => {
264
+ parentContext.signal.throwIfAborted();
265
+ assertPlanMutationAllowed(parentContext);
266
+ while (!worktreeAudited || (!worktreeGranted && permissionMode(parentContext) !== 'full-access')) {
267
+ worktreeApproval ??= approveOperation({ ...parentContext, approve: async (...approval) => {
268
+ const allowed = await parentContext.approve(...approval);
269
+ assertPlanMutationAllowed(parentContext);
270
+ if (allowed === true)
271
+ worktreeGranted = true;
272
+ return allowed;
273
+ } }, 'spawn_subagent.worktree', approvalArgs).then(() => { worktreeAudited = true; }).finally(() => { worktreeApproval = undefined; });
274
+ await worktreeApproval;
275
+ assertPlanMutationAllowed(parentContext);
276
+ }
277
+ };
178
278
  const waiters = [];
179
279
  const emit = async (type, data) => options.onEvent?.({ type, time: new Date().toISOString(), data: { runId: options.runId, nodeId: node.id, ...data } });
180
280
  /** Release this node's budget and abort its controller. Both operations are idempotent. */
@@ -220,7 +320,7 @@ export async function executeAgentNode(node, options) {
220
320
  const intake = await runIntake();
221
321
  if (intake)
222
322
  return intake;
223
- const run = async (configured, context, depth, inputs, task, subagentId, parentFallback = false) => {
323
+ const run = async (configured, context, depth, inputs, task, subagentId, parentFallback = false, commandScope = depth > 0) => {
224
324
  const nodeLimits = mergeLimits(configured, depth ? { ...limits, wallTimeMs: configured.limits?.wallTimeMs } : limits);
225
325
  const nodeBudget = createRuntimeBudget(context.signal, nodeLimits.wallTimeMs, context.runControl);
226
326
  const observationController = options.decisionManager?.enabled ? new AbortController() : undefined;
@@ -239,7 +339,7 @@ export async function executeAgentNode(node, options) {
239
339
  const resumeInvocation = suspendInvocationMemoryBudget();
240
340
  const resume = nodeBudget.suspend();
241
341
  return () => { resume(); resumeInvocation(); };
242
- });
342
+ }, commandScope);
243
343
  }
244
344
  catch (error) {
245
345
  if (!nodeSignal.aborted)
@@ -264,9 +364,17 @@ export async function executeAgentNode(node, options) {
264
364
  nodeBudget.dispose();
265
365
  }
266
366
  };
267
- const runWithinDeadline = async (configured, context, depth, inputs, task, subagentId, parentFallback = false, suspendMemoryBudget) => {
268
- if (orchestrator)
367
+ const runWithinDeadline = async (configured, context, depth, inputs, task, subagentId, parentFallback = false, suspendMemoryBudget, commandScope = depth > 0) => {
368
+ // The Orchestrator and its ordinary children run at the intake ceiling. A delegated writing child
369
+ // was admitted against the node's configured ceiling and keeps the capabilities it was given.
370
+ const delegatedChild = commandScope === 'delegated-worktree';
371
+ if (orchestrator && !delegatedChild)
269
372
  configured = { ...configured, capabilities: intakeCapabilities(configured) };
373
+ // A delegating Orchestrator ends with `completed` (the handoff) or `delivered`; every other node
374
+ // keeps its configured policy, so an inactive Orchestrator is unchanged.
375
+ const completionPolicy = delegationActive && depth === 0 && configured.completion?.mode !== 'outcomes'
376
+ ? { mode: 'outcomes', outcomes: [configured.completion?.outcome ?? 'completed', DELIVERED_OUTCOME] }
377
+ : configured.completion ?? { mode: 'single', outcome: 'completed' };
270
378
  context.toolState ??= { fileReads: new Map() };
271
379
  if (configured.executor && configured.executor !== 'react-basic')
272
380
  throw new Error('Only react-basic is available');
@@ -312,10 +420,11 @@ export async function executeAgentNode(node, options) {
312
420
  // The panel browser tool is bound to the primary agent's session panel: a child
313
421
  // driving the same visible tabs the parent is using cannot be authorized apart,
314
422
  // so children never inherit it (and a role naming it fails selection below).
315
- let tools = capabilityTools(configured, [...options.tools, ...(options.tools.some(tool => tool.name === 'git_read') ? [] : [gitReadTool()])], depth > 0).filter(tool => !['ask_user', 'spawn_subagent', 'present_plan'].includes(tool.name) && (depth === 0 || !['browser.panel', 'browser.incognito'].includes(tool.name)) && (!orchestrator || researchTool(tool.name) || ['read_skill_resource', 'qa.browser_session', 'browser.panel', 'browser.incognito'].includes(tool.name)));
423
+ const catalog = [...options.tools, ...(options.tools.some(tool => tool.name === 'git_read') ? [] : [gitReadTool()])];
424
+ let tools = capabilityTools(configured, catalog, commandScope).filter(tool => !['ask_user', 'spawn_subagent', 'present_plan'].includes(tool.name) && (depth === 0 || !['browser.panel', 'browser.incognito'].includes(tool.name)) && (!orchestrator || delegatedChild || researchTool(tool.name) || ['read_skill_resource', 'qa.browser_session', 'browser.panel', 'browser.incognito'].includes(tool.name)));
316
425
  const compatibilityRecoverTools = options.tools.filter(tool => tool.providerVisible === false
317
- && permitsBuiltInTool(configured, tool.name, depth > 0)
318
- && (!orchestrator || researchTool(tool.name))).flatMap(legacy => {
426
+ && permitsBuiltInTool(configured, tool.name, commandScope)
427
+ && (!orchestrator || delegatedChild || researchTool(tool.name))).flatMap(legacy => {
319
428
  const canonical = options.tools.find(candidate => candidate.providerVisible !== false
320
429
  && candidate.name === canonicalToolName(legacy.name));
321
430
  if (!canonical)
@@ -333,7 +442,7 @@ export async function executeAgentNode(node, options) {
333
442
  if (orchestrator && !codeIntel && configured.tools?.some(name => canonicalToolName(name) === 'repo_explore') && effectiveCapabilities(configured).filesystem !== 'none') {
334
443
  const existing = new Set(tools.map(tool => tool.name));
335
444
  for (const fallback of options.tools.filter(tool => ['Read', 'Glob', 'Grep'].includes(canonicalToolName(tool.name)) && tool.providerVisible !== false)) {
336
- if (!existing.has(fallback.name) && permitsBuiltInTool(configured, fallback.name, depth > 0)) {
445
+ if (!existing.has(fallback.name) && permitsBuiltInTool(configured, fallback.name, commandScope)) {
337
446
  tools.push(fallback);
338
447
  existing.add(fallback.name);
339
448
  }
@@ -435,7 +544,10 @@ export async function executeAgentNode(node, options) {
435
544
  // Skill wrappers replace the visible resource reader later in this invocation.
436
545
  // Delegation still needs its original, capability-filtered name to load inherited skills.
437
546
  const canDelegateSkillReader = tools.some(tool => tool.name === 'read_skill_resource');
438
- if (policy.enabled && maxTotal > 0 && depth < (policy.maxDepth ?? 1)) {
547
+ // Under a delegating Orchestrator no child spawns further, whatever the depth limit: a writing
548
+ // role spawned from a child would take the ordinary path, with a worktree made from HEAD that is
549
+ // kept and registered in the user's repository, outside the review this node promises.
550
+ if (policy.enabled && maxTotal > 0 && depth < (policy.maxDepth ?? 1) && !(delegationActive && depth > 0)) {
439
551
  tools.push({ name: 'spawn_subagent', description: 'Run one configured role on a bounded task. Its typed result returns as an observation. Batch spawn calls can run concurrently within configured limits. Role contracts: ' + JSON.stringify((policy.roles ?? []).map(role => ({ id: role.id, name: role.name, instruction: role.instruction, inputSchema: role.inputSchema, outputSchema: role.outputSchema }))),
440
552
  parameters: { type: 'object', properties: { role: { type: 'string', enum: (policy.roles ?? []).map(role => role.id) }, task: { type: 'string' }, input: { type: 'object' } }, required: ['role', 'task'], additionalProperties: false },
441
553
  execute: async (args, parentContext) => {
@@ -451,7 +563,15 @@ export async function executeAgentNode(node, options) {
451
563
  throw new Error('Subagent input must be an object');
452
564
  if (role.inputSchema)
453
565
  validateValue(role.inputSchema, childInputs, `Subagent ${role.name} input`);
454
- const parentCapabilities = effectiveCapabilities(configured);
566
+ // A writing role of a delegating Orchestrator is admitted against the node's configured
567
+ // ceiling, not the intake ceiling the Orchestrator itself runs under; it starts only once
568
+ // the user has confirmed the design.
569
+ const delegated = delegationActive && depth === 0 && isWritingRole(role);
570
+ if (delegated && !clarified)
571
+ throw new Error('Ask the user to confirm the design before starting writing subagents: a real ask_user answer is required first.');
572
+ if (delegated && policy.workspace !== 'worktree')
573
+ throw new Error('Writing roles on an Orchestrator require separate worktrees; select Separate Git worktree.');
574
+ const parentCapabilities = delegated ? effectiveCapabilities(node) : effectiveCapabilities(configured);
455
575
  const childCapabilities = role.capabilities ?? { ...parentCapabilities, ...(policy.workspace === undefined || policy.workspace === 'shared-read-only' ? { filesystem: parentCapabilities.filesystem === 'none' ? 'none' : 'read', git: parentCapabilities.git === 'none' ? 'none' : 'read', shell: 'disabled' } : {}) };
456
576
  if (!capabilitySubset(childCapabilities, parentCapabilities))
457
577
  throw new Error('Subagent capabilities exceed its parent');
@@ -463,8 +583,14 @@ export async function executeAgentNode(node, options) {
463
583
  // `browser.panel` and `browser.incognito` stay with the primary agent (see the tools filter above);
464
584
  // excluded here rather than at selection so a role naming it explicitly is
465
585
  // refused as exceeding the parent instead of silently losing its browser.
466
- const available = new Set([...tools.map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]);
467
- const childToolNames = policy.toolInheritance === 'inherit' ? [...available] : canonicalizeToolList(role.tools) ?? [...available].filter(name => ['Read', 'Glob', 'Grep', 'git_read', 'qa.browser_session', 'read_skill_resource'].includes(canonicalToolName(name)));
586
+ // A delegated writing role's tools come from the node's capabilities, not from the
587
+ // Orchestrator's own read-only intake kit: a worktree child may write and run commands.
588
+ const available = new Set(delegated
589
+ ? [...capabilityTools({ ...node, capabilities: parentCapabilities, tools: undefined }, catalog, 'delegated-worktree').map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito'),
590
+ ...tools.map(tool => tool.name).filter(name => name === 'read_artifact' || name === 'write_artifact'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]
591
+ : [...tools.map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]);
592
+ const childToolNames = delegated ? canonicalizeToolList(role.tools) ?? [...available]
593
+ : policy.toolInheritance === 'inherit' ? [...available] : canonicalizeToolList(role.tools) ?? [...available].filter(name => ['Read', 'Glob', 'Grep', 'git_read', 'qa.browser_session', 'read_skill_resource'].includes(canonicalToolName(name)));
468
594
  if (childToolNames.some(name => !available.has(name)))
469
595
  throw new Error('Subagent tool selection exceeds its parent');
470
596
  const childProvider = policy.modelPolicy === 'specific' ? policy.provider ?? provider : policy.modelPolicy === 'per-role' ? role.provider ?? provider : provider;
@@ -496,9 +622,36 @@ export async function executeAgentNode(node, options) {
496
622
  total++;
497
623
  const id = randomUUID();
498
624
  let workspaceArtifact;
625
+ /** The delegated child's worktree and the snapshot it started from; kept only while a change is pending. */
626
+ let delegatedWorktree;
627
+ let keepWorktree = false;
499
628
  try {
500
- let workspace = parentContext.workspace;
501
- if (policy.workspace === 'worktree' && writingChild) {
629
+ const parentWorkspace = parentContext.workspace;
630
+ let workspace = parentWorkspace;
631
+ let task = args.task;
632
+ if (delegated) {
633
+ if (parentCapabilities.git !== 'write')
634
+ throw new Error('Creating child worktrees requires parent Git write capability');
635
+ // Git itself is checked before any approval or temporary directory, so an unsuitable
636
+ // workspace fails without side effects.
637
+ await assertDelegationGit(parentWorkspace, parentContext.signal);
638
+ // A workspace that is a subfolder of its repository puts the child in the same
639
+ // subfolder of the worktree; the snapshot and the worktree cover the whole repository.
640
+ const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
641
+ const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
642
+ const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
643
+ operations: ['git snapshot of the working folder through a temporary index (no ref, stash or index change)', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree <snapshot>'],
644
+ warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. One grant covers every writing subagent of this Orchestrator visit; a change reaches the working folder only when the Orchestrator accepts it.' };
645
+ await authorizeDelegatedWorktree(parentContext, approvalArgs);
646
+ const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
647
+ await authorizeDelegatedWorktree(parentContext, approvalArgs);
648
+ const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
649
+ liveWorktrees.add(worktree);
650
+ delegatedWorktree = { worktree, base };
651
+ workspace = inside ? join(worktree, inside) : worktree;
652
+ task += `\n\nThis task runs in a separate Git worktree started from the working folder as it stands: ${workspace}. Files ignored by Git (for example node_modules) are not in this worktree. Install what you need inside this worktree if a build or test requires it. Report the commands and tests you ran and their results in the tests list of your completion. This worktree shares the Git repository of the user's working folder: do not create or change stashes, branches, tags or Git configuration. Commit only if the task needs it; commits stay in this worktree, and your result is taken from the files as you leave them.`;
653
+ }
654
+ else if (policy.workspace === 'worktree' && writingChild) {
502
655
  if (parentCapabilities.git !== 'write')
503
656
  throw new Error('Creating child worktrees requires parent Git write capability');
504
657
  // Worktree setup is a host operation: even status can follow an external
@@ -551,7 +704,9 @@ export async function executeAgentNode(node, options) {
551
704
  await emit('subagent.started', { subagentId: id, role: role.id, depth: depth + 1 });
552
705
  let result;
553
706
  try {
554
- result = await run(child, { ...parentContext, workspace }, depth + 1, childInputs, args.task, id, fallbackAttempt);
707
+ // The worktrees awaiting review are the Orchestrator's review aid: no child reads
708
+ // them, whether it is a delegated writer or an ordinary research role.
709
+ result = await run(child, { ...parentContext, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
555
710
  }
556
711
  catch (error) {
557
712
  // A child that throws once started (oversized mapped inputs, a cancelled parent) still
@@ -560,6 +715,12 @@ export async function executeAgentNode(node, options) {
560
715
  await emit('subagent.completed', { subagentId: id, role: role.id, status: parentContext.signal.aborted ? 'cancelled' : 'failed' });
561
716
  throw error;
562
717
  }
718
+ finally {
719
+ // However the child ended, its background jobs end with it, before its files are
720
+ // collected: a worktree kept for review must not have a process still writing in it.
721
+ if (delegatedWorktree)
722
+ await stopWorktreeJobs(delegatedWorktree.worktree);
723
+ }
563
724
  // The child's requests, tools and decisions were billed to the run, so its capture is
564
725
  // folded into the parent's; the result object itself is consumed as a tool observation
565
726
  // and would otherwise take those totals with it.
@@ -572,14 +733,180 @@ export async function executeAgentNode(node, options) {
572
733
  for (const artifact of returnedArtifacts)
573
734
  scopedRefs.add(artifact.ref);
574
735
  references(result.completion?.output, scopedRefs);
575
- return JSON.stringify({ status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts });
736
+ const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
737
+ if (delegatedWorktree) {
738
+ observation.tests = result.completion?.tests ?? [];
739
+ // A child that failed, was cancelled or changed nothing yields no change: its worktree
740
+ // goes in the cleanup below. Otherwise the change waits for the Orchestrator's review.
741
+ const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
742
+ if (collected?.files.length) {
743
+ const { worktree, base } = delegatedWorktree;
744
+ // Random rather than counted: a resumed visit starts a new registry, and a counter
745
+ // would hand out ids the resumed conversation already uses for other changes.
746
+ let changeId = `change-${randomUUID().slice(0, 8)}`;
747
+ while (changes.has(changeId))
748
+ changeId = `change-${randomUUID().slice(0, 8)}`;
749
+ const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
750
+ // The full diff is an artifact the Orchestrator can page through; one too large even
751
+ // for an artifact stays readable in the worktree, and the observation says so.
752
+ let diffArtifact, diffNote;
753
+ try {
754
+ diffArtifact = await store.put('delegation-diff', collected.diff);
755
+ scopedRefs.add(diffArtifact.ref);
756
+ }
757
+ catch (error) {
758
+ diffNote = `The full diff could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}); read the changed files inside the worktree.`;
759
+ }
760
+ // The record is registered only after every step that can throw: a pending record must
761
+ // never point at a worktree the cleanup below already removed.
762
+ const root = await realpath(worktree);
763
+ changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
764
+ provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
765
+ delegationRoots.push(root);
766
+ keepWorktree = true;
767
+ await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
768
+ observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
769
+ ...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
770
+ }
771
+ }
772
+ return JSON.stringify(observation);
576
773
  }
577
774
  finally {
775
+ if (delegatedWorktree && !keepWorktree)
776
+ await dropWorktree(delegatedWorktree.worktree);
578
777
  active--;
579
778
  waiters.shift()?.();
580
779
  }
581
780
  } });
582
781
  }
782
+ // The landing tools act on a change record by id and nothing else: the Orchestrator cannot
783
+ // supply content, a patch or a command through them, so it still cannot write code itself.
784
+ if (delegationActive && depth === 0) {
785
+ const idOnly = () => ({ type: 'object', properties: { id: { type: 'string', minLength: 1, description: 'The change id from a spawn_subagent result.' } }, required: ['id'], additionalProperties: false });
786
+ const undecided = (args, name) => {
787
+ if (Object.keys(args).some(key => key !== 'id') || typeof args.id !== 'string')
788
+ throw new Error(`${name} takes only the id of a change record`);
789
+ const change = changes.get(args.id);
790
+ if (!change)
791
+ throw new Error('Unknown change');
792
+ if (change.state === 'landed')
793
+ throw new Error('Change already landed');
794
+ if (change.state === 'discarded')
795
+ throw new Error('Change already discarded');
796
+ return change;
797
+ };
798
+ const announce = (change, files = change.files.map(file => file.path)) => emit('subagent.change', { subagentId: change.subagentId, changeId: change.id, state: change.state, files });
799
+ tools.push({ name: 'accept_change', executionMode: 'sequential', description: 'Land a reviewed change in the working folder as uncommitted edits, merged three-way against the snapshot its subagent started from. On a conflict nothing is written and the conflicting files are returned; accepting the same change again conflicts again, so discard it, spawn a redo from the working folder as it now stands, and accept the redo.',
800
+ parameters: idOnly(),
801
+ execute: async (args, ctx) => {
802
+ ctx.signal.throwIfAborted();
803
+ const change = undecided(args, 'accept_change');
804
+ if (!change.tree)
805
+ throw new Error('Change has no collected tree to land');
806
+ const { base, tree } = change;
807
+ assertPlanMutationAllowed(ctx);
808
+ const conflict = async (conflicts, detail) => {
809
+ // The paths stay on the record after a later clean landing: the delivery record says
810
+ // the change conflicted before it landed.
811
+ change.state = 'conflict';
812
+ change.conflicts = conflicts;
813
+ await announce(change);
814
+ return JSON.stringify({ state: 'conflict', conflicts, detail });
815
+ };
816
+ const failed = async (error) => {
817
+ // A landing that wrote part of the change and could not put the folder back is not a
818
+ // conflict the Orchestrator can review its way out of: the node stops, and its reason
819
+ // carries the snapshot commit and the files the user needs to recover.
820
+ if (error instanceof LandingRestoreError) {
821
+ change.state = 'conflict';
822
+ change.conflicts = error.paths;
823
+ await announce(change);
824
+ throw new ClarificationRequiredError(error.message);
825
+ }
826
+ // A cancelled run propagates as cancellation. Any other failure happened before
827
+ // anything was written (the snapshot, the merge or the copy made before applying), so
828
+ // it is a conflict in effect.
829
+ if (ctx.signal.aborted || (error instanceof Error && error.name === 'AbortError'))
830
+ throw error;
831
+ return conflict([], error instanceof Error ? error.message : String(error));
832
+ };
833
+ /** Paths an approval prompt of this call already covered. */
834
+ const granted = new Set();
835
+ let asked = false;
836
+ // A landing is prepared, authorized for the paths it writes, then applied. The folder can
837
+ // change while a prompt is open; the apply then refuses the prepared patch as a whole and
838
+ // the landing is prepared again from the folder as it now stands.
839
+ for (let attempt = 1;; attempt++) {
840
+ ctx.signal.throwIfAborted();
841
+ let prepared;
842
+ try {
843
+ prepared = await prepareLanding(ctx.workspace, base, tree, ctx.signal);
844
+ }
845
+ catch (error) {
846
+ return failed(error);
847
+ }
848
+ if (!prepared.ready)
849
+ return conflict(prepared.conflicts, prepared.detail);
850
+ // Landing follows the rule for an Edit of the same files, and the files are the ones
851
+ // the merged patch writes or removes, not the ones the subagent changed: a file the
852
+ // user moved meanwhile takes the edit at its new place. A change lands at the
853
+ // repository root, so it can reach files above a subfolder workspace or protected
854
+ // metadata inside it; those prompt exactly where an Edit of them would. Inside the
855
+ // workspace, the modes that auto-approve workspace writes land without a prompt and
856
+ // audit the grant.
857
+ const files = prepared.landing.files;
858
+ const { outside, protected: protectedPaths } = await classifyWorkspaceWrites(ctx.workspace, prepared.landing.root, files);
859
+ const automatic = () => !outside.length && !protectedPaths.length && ['ask-for-approval', 'approve-for-me'].includes(permissionMode(ctx) ?? '');
860
+ while (!(asked && files.every(file => granted.has(file)))) {
861
+ ctx.signal.throwIfAborted();
862
+ assertPlanMutationAllowed(ctx);
863
+ if (!automatic()) {
864
+ await approveOperation(ctx, 'accept_change', { id: change.id, files, outside, protected: protectedPaths });
865
+ asked = true;
866
+ for (const file of files)
867
+ granted.add(file);
868
+ break;
869
+ }
870
+ await ctx.onApprovalEvent?.('node.tool.approval.requested', { name: 'accept_change', arguments: { id: change.id, files }, mode: 'workspace-policy' });
871
+ await ctx.onApprovalEvent?.('node.tool.approval.decided', { name: 'accept_change', mode: 'workspace-policy', approved: true, actor: 'workspace-policy' });
872
+ // The audit hooks can yield to a live permission change; a policy grant holds only
873
+ // while the policy that gave it is still the live one.
874
+ assertPlanMutationAllowed(ctx);
875
+ if (automatic())
876
+ break;
877
+ }
878
+ ctx.signal.throwIfAborted();
879
+ assertPlanMutationAllowed(ctx);
880
+ let result;
881
+ try {
882
+ result = await applyLanding(prepared.landing, ctx.signal);
883
+ }
884
+ catch (error) {
885
+ return failed(error);
886
+ }
887
+ if (result.landed) {
888
+ change.state = 'landed';
889
+ change.landedFiles = result.files;
890
+ await dropWorktree(change.worktree);
891
+ await announce(change, result.files);
892
+ return JSON.stringify({ state: 'landed', files: result.files });
893
+ }
894
+ if (result.stale && attempt < LANDING_ATTEMPTS)
895
+ continue;
896
+ return conflict(result.conflicts, result.stale ? `The working folder kept changing while the change was being landed, so nothing was written. Accept the change again once the folder is no longer being edited. ${result.detail}` : result.detail);
897
+ }
898
+ } });
899
+ tools.push({ name: 'discard_change', executionMode: 'sequential', description: 'Drop a reviewed change and remove its worktree. Nothing reaches the working folder.',
900
+ parameters: idOnly(),
901
+ execute: async (args, ctx) => {
902
+ ctx.signal.throwIfAborted();
903
+ const change = undecided(args, 'discard_change');
904
+ change.state = 'discarded';
905
+ await dropWorktree(change.worktree);
906
+ await announce(change);
907
+ return JSON.stringify({ state: 'discarded' });
908
+ } });
909
+ }
583
910
  const requirePublishedPlan = (tool) => !orchestrator || depth !== 0 ? tool : {
584
911
  ...tool, execute: async (args, ctx) => {
585
912
  if (!publishedPlan)
@@ -591,12 +918,12 @@ export async function executeAgentNode(node, options) {
591
918
  // The manager applies provider-specific bounds to its decision snapshot.
592
919
  const decisionRoles = tools.some(tool => tool.name === 'spawn_subagent')
593
920
  ? (policy.roles ?? []).map(role => role.id) : [];
594
- const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
921
+ const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', orchestrator && depth === 0 && delegationActive ? DELEGATION_INSTRUCTIONS : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
595
922
  const inheritedSkills = [...new Set(options.inheritedSkills ?? [])];
596
923
  // Skills the node's own prompts name as `/name`. A delegated child runs a dispatched task, not
597
924
  // these prompts, so only the node itself reads them.
598
925
  const promptSkillNames = depth === 0 ? promptSkillReferences(configured.instruction, configured.systemPrompt ?? configured.prompt) : [];
599
- const canReadProjectSkills = ['Read', 'Glob', 'Grep', 'repo_explore'].some(name => permitsBuiltInTool(configured, name, depth > 0));
926
+ const canReadProjectSkills = ['Read', 'Glob', 'Grep', 'repo_explore'].some(name => permitsBuiltInTool(configured, name, commandScope));
600
927
  // Pin discovery in all experiment arms; undefined preserves JEV-assisted discovery.
601
928
  // Inherited and prompt-named references still load even if ambient discovery is disabled.
602
929
  const discoverProjectSkills = canReadProjectSkills && (inheritedSkills.length > 0 || promptSkillNames.length > 0
@@ -698,8 +1025,16 @@ export async function executeAgentNode(node, options) {
698
1025
  // attempt read is retained here and offered again to the next one; without that, the run would
699
1026
  // finish under the instructions the message corrected while its transcript says it was read.
700
1027
  const consumedSteers = [];
1028
+ // Ids of the changes that were still undecided when an attempt failed. A retry starts a fresh
1029
+ // conversation that has none of the failed attempt's spawn results, so it could not review
1030
+ // them, and completing as delivered requires every change decided: they are discarded before
1031
+ // the retry starts, and the retry is told so. Landed changes stay and still count.
1032
+ const discardedAtRetry = [];
701
1033
  for (let attempt = 1; attempt <= attempts; attempt++) {
702
1034
  context.signal.throwIfAborted();
1035
+ if (delegationActive && depth === 0 && attempt > 1)
1036
+ for (const change of await releaseChanges())
1037
+ discardedAtRetry.push(change.id);
703
1038
  if (attempt > 1 && configured.retry?.fallback)
704
1039
  fallbackAttempt = true;
705
1040
  // This invocation's identity for the caller's live-selection resolver: a delegated child is
@@ -727,6 +1062,14 @@ export async function executeAgentNode(node, options) {
727
1062
  // The escalated attempt starts a fresh conversation; the files are the only state it inherits.
728
1063
  taskBase += `\n\nA previous attempt on another model already changed these workspace files: ${JSON.stringify(previousMutations)}. Inspect them before changing them again and do not repeat work that is already done.`;
729
1064
  }
1065
+ if (delegationActive && depth === 0 && attempt > 1) {
1066
+ const landed = [...changes.values()].filter(change => change.state === 'landed').map(change => ({ id: change.id, files: change.landedFiles ?? change.files.map(file => file.path) }));
1067
+ if (landed.length || discardedAtRetry.length) {
1068
+ taskBase += '\n\nA previous attempt of this task delegated work to writing subagents and ended before it completed. This attempt starts a new conversation.'
1069
+ + (landed.length ? ` These changes were accepted and are already in the working folder as uncommitted edits: ${JSON.stringify(landed)}. Do not redo or accept them again; read the files if you need to build on them. They count as landed when you complete as delivered.` : ' None of its changes was landed.')
1070
+ + (discardedAtRetry.length ? ` These changes were still awaiting a decision and were discarded, and their worktrees removed: ${JSON.stringify(discardedAtRetry)}. Their ids are no longer valid; spawn that work again if it is still needed.` : '');
1071
+ }
1072
+ }
730
1073
  if (approvedPlan !== undefined && permissionMode(context) !== 'plan') {
731
1074
  // The approval granted editing permissions to this invocation, so the fresh attempt
732
1075
  // implements the plan the user approved rather than reinterpreting the raw task. Still in
@@ -771,7 +1114,6 @@ export async function executeAgentNode(node, options) {
771
1114
  // These values are pinned in the executor request. Count their serialized
772
1115
  // representation (including nested JSON escaping), not only task text.
773
1116
  const skillContextBudget = () => {
774
- const completionPolicy = configured.completion ?? { mode: 'single', outcome: 'completed' };
775
1117
  const pinned = [taskBase, attemptPrompt, options.instructions ?? '',
776
1118
  JSON.stringify(configured.outputSchema ?? { type: 'object' }),
777
1119
  JSON.stringify(completionPolicy),
@@ -1221,7 +1563,18 @@ export async function executeAgentNode(node, options) {
1221
1563
  const output = completion.output;
1222
1564
  if (!output || typeof output.taskInstruction !== 'string' || !output.taskInstruction.trim() || ['requirements', 'acceptanceCriteria', 'designConsiderations', 'codebaseFindings'].some(key => !Array.isArray(output[key]) || output[key].some(value => typeof value !== 'string')))
1223
1565
  return 'Return requirements, acceptanceCriteria, designConsiderations and codebaseFindings as string arrays and a nonempty taskInstruction in the structured handoff.';
1224
- } : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy: configured.completion ?? { mode: 'single', outcome: 'completed' }, outputSchema: configured.outputSchema,
1566
+ // `delivered` keeps the handoff contract and adds the delivery conditions: no child still
1567
+ // running, every reviewed change decided, and at least one of them landed.
1568
+ if (completion.outcome === DELIVERED_OUTCOME) {
1569
+ if (active > 0)
1570
+ return 'Wait for every running subagent to finish before completing as delivered.';
1571
+ const records = [...changes.values()];
1572
+ if (records.some(change => change.state === 'pending' || change.state === 'conflict'))
1573
+ return 'Accept or discard every change before completing as delivered.';
1574
+ if (!records.some(change => change.state === 'landed'))
1575
+ return 'Land at least one accepted change before completing as delivered.';
1576
+ }
1577
+ } : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
1225
1578
  history: configured.contextPolicy?.history ? options.history : [],
1226
1579
  task: attemptRepoBlock ? `${taskBase}\n\n${attemptRepoBlock}` : taskBase,
1227
1580
  onUsage: (usage, origin) => {
@@ -1273,12 +1626,30 @@ export async function executeAgentNode(node, options) {
1273
1626
  // A wake this node arms is its own reminder about its own work, so the wake names the node and the
1274
1627
  // attempt: delivery returns it to this node rather than to the graph's entry.
1275
1628
  const wakeOrigin = options.runId === undefined ? undefined : { runId: options.runId, nodeId: node.id };
1276
- const result = await run(node, { ...bounded, approve, ...(wakeOrigin === undefined ? {} : { wakeOrigin }) }, 0, orchestrator ? { ...options.mappedInputs, originalTask: options.task } : options.mappedInputs ?? {}, options.task);
1629
+ const result = await run(node, { ...bounded, approve, ...(wakeOrigin === undefined ? {} : { wakeOrigin }), ...(delegationActive ? { delegationRoots } : {}) }, 0, orchestrator ? { ...options.mappedInputs, originalTask: options.task } : options.mappedInputs ?? {}, options.task);
1277
1630
  if (orchestrator && !clarified && result.status === 'exhausted' && result.reason === MISSING_CONFIRMATION) {
1278
1631
  result.status = 'needs_clarification';
1279
1632
  result.reason = 'Needs clarification: use ask_user to confirm the user design considerations before implementation.';
1280
1633
  delete result.completion;
1281
1634
  }
1635
+ // The delivery record: every change of this visit with its role, model, files, final state and
1636
+ // the conflicts it last hit. The guard already proved each one was decided, so the record is
1637
+ // written once, after acceptance. The accepted edits are already in the working folder, so a
1638
+ // store that cannot take the record (ENOSPC, EACCES) must not turn the delivered run into a
1639
+ // failure: the completion is kept and its summary says the record is missing.
1640
+ if (delegationActive && result.status === 'succeeded' && result.completion?.outcome === DELIVERED_OUTCOME) {
1641
+ const content = JSON.stringify({ changes: [...changes.values()].map(change => ({
1642
+ id: change.id, subagentId: change.subagentId, role: change.role, provider: change.provider, model: change.model, state: change.state,
1643
+ files: change.files, conflicts: change.conflicts ?? [], ...(change.diffArtifact ? { diffArtifact: change.diffArtifact } : {}),
1644
+ })) }, null, 2);
1645
+ try {
1646
+ const record = await store.put('delegation-record', content);
1647
+ result.completion.artifacts = [...(result.completion.artifacts ?? []), record];
1648
+ }
1649
+ catch (error) {
1650
+ result.completion.summary += `\n\nThe delivery record could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}). The landed changes are in the working folder; this run's subagent.change events carry each change's final state.`;
1651
+ }
1652
+ }
1282
1653
  result.usage = { ...budget.usage };
1283
1654
  result.toolCalls = budget.toolCalls;
1284
1655
  result.limits = limits;
@@ -1299,6 +1670,14 @@ export async function executeAgentNode(node, options) {
1299
1670
  return result;
1300
1671
  }
1301
1672
  finally {
1302
- finish();
1673
+ // Delegated worktrees never outlive the node, whatever ended it; the release runs before the
1674
+ // node's controller is aborted so its announcements still reach the event sink.
1675
+ try {
1676
+ if (delegationActive)
1677
+ await releaseChanges();
1678
+ }
1679
+ finally {
1680
+ finish();
1681
+ }
1303
1682
  }
1304
1683
  }