@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
@@ -0,0 +1,295 @@
1
+ # Orchestrator Delegation Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Let an Orchestrator node delegate implementation to writing subagents, each in its own Git worktree with a shell, review their diffs and test reports, land accepted changes into the working folder, and finish on a new `delivered` outcome, without the Orchestrator itself ever writing code.
6
+
7
+ **Architecture:** Graph validation learns a "delegating Orchestrator" (spawning on and at least one writing role) with two capability ceilings and a `delivered` output port. A new `src/delegation-changes.ts` module owns every Git operation: snapshot the working folder, create a worktree from the snapshot, collect a child's change, three-way land it with `git merge-tree`, and clean up. `executeAgentNode` wires those into `spawn_subagent`, adds `accept_change` / `discard_change`, and guards the `delivered` completion. The graph builder and desktop view gain the matching port, copy and change states.
8
+
9
+ **Tech Stack:** TypeScript (Node ESM), `node:test` via `scripts/run-tests.mjs` for engine tests, Vitest for `desktop/`, Git CLI ≥ 2.40.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - Existing graphs, including `DEFAULT_HARNESS`, `DEFAULT_HARNESS_REVISION_1..5` and every saved graph, load, validate and run exactly as before.
16
+ - `createOrchestratorNode()` must return exactly what it returns today (revision 5 and the default harness are built from it at load time).
17
+ - With delegation inactive (no writing role, spawning off, or no `delivered` edge in `options.graph`), `executeAgentNode` behaves byte-for-byte as today, including the existing refusal "Subagent capabilities exceed its parent".
18
+ - The Orchestrator's own capabilities stay `intakeCapabilities(node)` in every mode. It never gets `Write`, `Edit`, a shell, or a Git write tool.
19
+ - Only writing roles of a delegating Orchestrator, running in `workspace: 'worktree'`, may get command tools. Every other child keeps `canRunCommands === false`.
20
+ - Accepted changes land as uncommitted working-folder edits. The user's index, refs, stash and branches are never modified.
21
+ - Every Git invocation uses `-c core.hooksPath= -c core.fsmonitor=false`, `windowsHide: true`, a timeout, and the run's abort signal, as the existing worktree code does.
22
+ - Delegated writing requires Git ≥ 2.40 (`git merge-tree --write-tree --merge-base`). Older Git fails the first writing spawn with: `Delegated writing needs Git 2.40 or newer.`
23
+ - The Orchestrator remains Premium (`src/graph-quota.ts` unchanged).
24
+ - Build with `npm run build`. Run engine tests one file at a time with `node scripts/run-tests.mjs dist/test/<name>.test.js`; never bare `node --test`, and do not run the whole suite (AGENTS.md).
25
+ - Ships with `tests/orchestrator-delegation-test-plan.md` (AGENTS.md QA plan rules).
26
+
27
+ ## Review Focus
28
+
29
+ 1. **Ignored dependency folders are missing in a worktree** (for example `node_modules`). A child that runs `npm test` must not fail confusingly. Designer's call: nothing is linked into the worktree, because a link would let a child mutate the user's dependencies. Instead, the child's task text carries a notice. Pinned in Task 3.
30
+ 2. **The user edits the working folder while subagents run.** `accept_change` merges three ways against the folder as it is now. A conflict writes nothing. Pinned in Task 2.
31
+ 3. **Deletes, renames, binary files and paths with spaces in a change** must land exactly. Pinned in Task 2.
32
+ 4. **Cancel or wall-time while children are running.** Every worktree is removed, nothing partial lands, and changes already accepted stay. Pinned in Task 4.
33
+ 5. **The workspace is not a Git repository, or has no commit yet.** The first writing spawn fails with a clear message, and no directory or worktree is created. Pinned in Task 2 (message) and Task 3 (no side effects).
34
+
35
+ ---
36
+
37
+ ## File Structure
38
+
39
+ | File | Change | Responsibility |
40
+ |---|---|---|
41
+ | `src/graphs.ts` | modify | `isWritingRole`, `delegatesWriting`, `DELIVERED_OUTCOME`, `CommandScope`; ceilings, outcomes and validation |
42
+ | `src/capabilities.ts` | modify | `capabilityTools` accepts `CommandScope` |
43
+ | `src/delegation-changes.ts` | create | All Git work: snapshot, worktree, collect, land, remove |
44
+ | `src/agent-execution.ts` | modify | Activation, writing spawns, change registry, `accept_change` / `discard_change`, `delivered` guard, cleanup |
45
+ | `src/tools.ts`, `src/types.ts` | modify | `ToolContext.delegationRoots` trusted for reads |
46
+ | `src/graph-ui/app.js` | modify | `delivered` port, help copy, worktree requirement |
47
+ | `desktop/src/engine/rows.ts`, `desktop/src/engine/workflow.ts`, `desktop/src/components/WorkflowView.tsx` | modify | Change state on subagent entries |
48
+ | `test/orchestrator-delegation-graph.test.ts` | create | Validation and outcomes |
49
+ | `test/delegation-changes.test.ts` | create | Git module against real temp repos |
50
+ | `test/orchestrator-delegation-runtime.test.ts` | create | Runtime against a real temp repo with stub adapters |
51
+ | `test/orchestrator-role-ceiling.test.ts` | modify | Expectations that change for writing roles |
52
+ | `tests/orchestrator-delegation-test-plan.md` | create | QA plan |
53
+
54
+ ---
55
+
56
+ ### Task 1: Graph model — delegating Orchestrator, ceilings, `delivered` port, child command scope
57
+
58
+ **Files:**
59
+ - Modify: `src/graphs.ts` (`canRunCommands` / `permitsBuiltInTool` ~233-249, `nodeOutcomes` ~257, subagent validation ~575-610, required-route check ~673, Orchestrator checks ~704-720)
60
+ - Modify: `src/capabilities.ts:12` (`capabilityTools`)
61
+ - Create: `test/orchestrator-delegation-graph.test.ts`
62
+ - Modify: `test/orchestrator-role-ceiling.test.ts`
63
+
64
+ **Interfaces:**
65
+ - Produces (in `src/graphs.ts`):
66
+ - `export const DELIVERED_OUTCOME = 'delivered'`
67
+ - `export type CommandScope = boolean | 'delegated-worktree'` (`false` = primary agent, `true` = ordinary child, `'delegated-worktree'` = writing child of a delegating Orchestrator)
68
+ - `export function isWritingRole(role: SubagentRole): boolean`: `role.capabilities?.filesystem === 'read-write' || role.capabilities?.git === 'write'`
69
+ - `export function delegatesWriting(node: GraphNode): boolean`: `node.type === 'agent' && node.agentRole === 'orchestrator' && node.subagents?.enabled === true && node.maxSubagents !== 0 && (node.subagents.roles ?? []).some(isWritingRole)`
70
+ - `permitsBuiltInTool(node, name, child: CommandScope = false)`. Command and QA tools are allowed when `child !== true` and the existing policy test holds.
71
+ - `nodeOutcomes(node)` returns `[node.completion?.outcome ?? 'completed', DELIVERED_OUTCOME]` when `delegatesWriting(node)`
72
+ - Produces (in `src/capabilities.ts`): `capabilityTools(node: GraphNode, tools: Tool[], child: CommandScope = false)`. The external-MCP exclusion applies to any truthy `child`.
73
+
74
+ - [ ] **Step 1: Write the failing tests** in `test/orchestrator-delegation-graph.test.ts`. Build fixtures from `structuredClone(DEFAULT_HARNESS)` with `orchestrator.capabilities = { filesystem: 'read-write', shell: 'allowed', git: 'write', github: 'none', browser: 'disabled', deployment: 'none' }`, `subagents = { enabled: true, workspace: 'worktree', maxConcurrent: 2, maxTotal: 6, roles: [{ id: 'coder', name: 'Coder', instruction: 'Implement', capabilities: { ...thatPolicy } }] }`.
75
+ - `delegating Orchestrator validates and exposes completed and delivered ports`: `validateGraph` does not throw, and `nodeOutcomes(orchestrator)` deep-equals `['completed', 'delivered']`.
76
+ - `delivered needs no route`: the fixture has no `delivered` edge and validates.
77
+ - `an edge may route delivered`: add `{ id: 'o-done', source: 'orchestrator', target: 'done', outcome: 'delivered' }`, and it validates.
78
+ - `writing roles require separate worktrees`: `workspace: 'shared-write', maxConcurrent: 1` throws `/writing roles on an Orchestrator require separate worktrees/`.
79
+ - `delegation requires single completion`: `completion = { mode: 'outcomes', outcomes: ['a', 'b'] }` throws `/delegation needs a single completion outcome/`.
80
+ - `writing role is checked against the node ceiling, not intake`: role `{ ...policy }` passes. A role with `deployment: 'allowed'` throws `/capability exceeds parent/`.
81
+ - `read-only roles on a delegating Orchestrator keep the intake ceiling`: a role `{ filesystem: 'read', shell: 'allowed', git: 'read', ... }` throws `/intake read-only ceiling/`.
82
+ - `spawning off keeps today's behavior`: `subagents.enabled = false` with a writing role means `delegatesWriting` is false, `nodeOutcomes` is `['completed']`, and it validates as today.
83
+ - `command tools only for delegated worktree children`: for `{ capabilities: policy }`, `permitsBuiltInTool(n, 'Bash', true) === false`, `permitsBuiltInTool(n, 'Bash', 'delegated-worktree') === true`, `permitsBuiltInTool(n, 'qa.test', 'delegated-worktree') === true`, and `permitsBuiltInTool({ capabilities: { ...policy, git: 'read' } }, 'Bash', 'delegated-worktree') === false`.
84
+ - `frozen and default graphs are unchanged`: for `DEFAULT_HARNESS` and each `DEFAULT_HARNESS_REVISION_*` that has an Orchestrator, `delegatesWriting(orchestrator) === false`, `nodeOutcomes(orchestrator)` deep-equals `['completed']`, and `createOrchestratorNode()` deep-equals the JSON snapshot `test/fixtures/orchestrator-preset.json`. Write that snapshot in Step 1 from the unmodified `createOrchestratorNode()`, before touching `src/graphs.ts`.
85
+ - `minimum tool calls ignore an unrouted delivered port`: `minimumGraphToolCalls(fixture)` equals `minimumGraphToolCalls` of the same graph with spawning disabled.
86
+
87
+ - [ ] **Step 2: Update `test/orchestrator-role-ceiling.test.ts`.** In the first test, the `{ filesystem: 'read-write' }` and `{ git: 'write' }` cases now make the node delegating with `workspace: 'shared-write'`, so they assert `/writing roles on an Orchestrator require separate worktrees/`. The `shell`, `github` and `deployment` cases keep `/intake read-only ceiling/`.
88
+
89
+ - [ ] **Step 3: Build and run, expect failures.** Run: `npm run build && node scripts/run-tests.mjs dist/test/orchestrator-delegation-graph.test.js dist/test/orchestrator-role-ceiling.test.js`. Expected: FAIL (`delegatesWriting` is not exported).
90
+
91
+ - [ ] **Step 4: Implement** the Interfaces above.
92
+ - Validation, inside the subagent block: when `delegatesWriting(node)`, validate writing roles against `effectiveCapabilities(node)` and other roles against `intakeCapabilities(node)`. Require `(s.workspace ?? 'shared-read-only') === 'worktree'` (message: `${label}: writing roles on an Orchestrator require separate worktrees; select Separate Git worktree`). Require `node.completion?.mode !== 'outcomes'` (message: `${label}: Orchestrator delegation needs a single completion outcome; remove declared outcomes or the writing roles`).
93
+ - Validate writing-role `tools` with `permitsBuiltInTool({capabilities: child}, t, 'delegated-worktree')`.
94
+ - Exclude `DELIVERED_OUTCOME` of a delegating node from the required-route check, and from `guaranteedGraphInvocations` alternatives when it has no route.
95
+ - Update the "custom Orchestrator delegation … rejects explicit writer roles" runtime test only if it breaks. It should not, because its node is validated nowhere and has no graph.
96
+
97
+ - [ ] **Step 5: Run tests and the neighbors.** Run: `npm run build && node scripts/run-tests.mjs dist/test/orchestrator-delegation-graph.test.js dist/test/orchestrator-role-ceiling.test.js dist/test/graphs.test.js dist/test/graph-policy-validation.test.js dist/test/orchestrator-schema.test.js dist/test/graph-quota.test.js`. Expected: PASS, apart from failures already listed in memory as baseline.
98
+
99
+ - [ ] **Step 6: Commit** `feat(graphs): delegating Orchestrator ceilings and delivered outcome`.
100
+
101
+ ---
102
+
103
+ ### Task 2: Git change module
104
+
105
+ **Files:**
106
+ - Create: `src/delegation-changes.ts`
107
+ - Create: `test/delegation-changes.test.ts`
108
+
109
+ **Interfaces:**
110
+ - Produces:
111
+ - `export const DELEGATION_DIFF_LIMIT = 20_000` (characters of diff inlined into an observation)
112
+ - `export async function assertDelegationGit(workspace: string, signal: AbortSignal): Promise<void>`. Throws `Delegated writing needs Git 2.40 or newer.`, `Delegated writing needs the workspace to be a Git repository.`, or `Delegated writing needs a Git repository with at least one commit.`
113
+ - `export async function snapshotWorkspace(workspace: string, signal: AbortSignal): Promise<string>` returns a commit id. Its tree is the working folder's tracked plus untracked non-ignored files, and its parent is `HEAD`. It uses a temporary `GIT_INDEX_FILE` and `git add -A`, `git write-tree`, `git commit-tree`. It never touches the real index, refs or stash.
114
+ - `export async function addChangeWorktree(workspace: string, commit: string, signal: AbortSignal): Promise<string>` returns the worktree path, created with `mkdtemp(join(tmpdir(), 'andorra-subagent-'))` + `/worktree` and `git worktree add --detach <path> <commit>`.
115
+ - `export interface CollectedChange { tree: string; files: { path: string; status: 'A' | 'M' | 'D' | 'R' }[]; diff: string }`
116
+ - `export async function collectChange(worktree: string, base: string, signal: AbortSignal): Promise<CollectedChange>`. Snapshots the worktree's final files with a temporary index (commits made inside the worktree don't matter). `diff` is `git diff --binary -M <base>^{tree} <tree>`. `files` comes from `--name-status -M`.
117
+ - `export type LandResult = { landed: true; files: string[] } | { landed: false; conflicts: string[]; detail: string }`
118
+ - `export async function landChange(workspace: string, base: string, tree: string, signal: AbortSignal): Promise<LandResult>`. `ours = snapshotWorkspace(workspace)^{tree}`, then `git merge-tree --write-tree --merge-base <base> <ours> <tree>`. On a clean merge, apply `git diff --binary <ours> <merged>` to the working tree with `git apply` (no `--index`). On a conflict, write nothing and return the conflicted paths.
119
+ - `export async function removeChangeWorktree(workspace: string, worktree: string): Promise<void>`. Best effort and never throws: `git worktree remove --force`, then `rm -rf` of the `mkdtemp` parent, then `git worktree prune`.
120
+
121
+ - [ ] **Step 1: Write the failing tests** in `test/delegation-changes.test.ts`. Each test creates a real temp repo with `mkdtemp`, `git init`, a committed `README.md` and `src/a.txt`, and `t.after` removal. Set `git config user.email/name` locally in the repo.
122
+ - `snapshot includes uncommitted and untracked files and leaves index and refs alone`: modify `src/a.txt`, add untracked `new file.txt`, and add `ignored.log` with `.gitignore` containing `*.log`. After `snapshotWorkspace`, `git ls-tree -r --name-only <commit>` contains `new file.txt` and not `ignored.log`. `git status --porcelain`, `git rev-parse HEAD` and `git stash list` are byte-identical before and after.
123
+ - `worktree starts from the snapshot`: `addChangeWorktree(ws, commit)` contains the modified `src/a.txt` content and `new file.txt`.
124
+ - `collect reports adds, edits, deletes, renames and binary`: in the worktree, edit `src/a.txt`, delete `README.md`, rename `src/b.txt` (committed in setup) to `src/c.txt`, add `img.bin` with bytes `[0, 255, 1]`, then `git commit -am x` inside the worktree. `files` maps to statuses M, D, R (`src/c.txt`) and A, and `diff` contains `GIT binary patch`.
125
+ - `land applies a clean change as uncommitted edits`: after `landChange`, the working folder has the worktree's file contents (byte-equal for `img.bin`), `git diff --cached --quiet` exits 0, and `HEAD` is unchanged.
126
+ - `land merges with edits the user made meanwhile`: the user edits line 1 of `src/a.txt` in the workspace after spawn, and the child edits line 3. The result is `landed: true` and both edits are present.
127
+ - `land conflict writes nothing`: the user and the child both edit line 2 differently. The result is `{ landed: false }` with `conflicts` containing `src/a.txt`, and the workspace bytes are identical to before the call.
128
+ - `paths with spaces land`: the child adds `docs/my notes.md`, and it lands.
129
+ - `remove cleans the worktree and the temp directory`: after `removeChangeWorktree`, the path does not exist and `git worktree list` no longer lists it. A second call does not throw.
130
+ - `refuses non-repositories and unborn repositories`: an empty dir rejects with `/must be a Git repository|needs the workspace to be a Git repository/`. `git init` without a commit rejects with `/at least one commit/`.
131
+
132
+ - [ ] **Step 2: Run, expect failure.** Run: `npm run build && node scripts/run-tests.mjs dist/test/delegation-changes.test.js`. Expected: FAIL (module not found).
133
+
134
+ - [ ] **Step 3: Implement `src/delegation-changes.ts`** per the Interfaces. Run Git through `promisify(execFile)` with the hardened `-c` flags from the Global Constraints. Pass `GIT_INDEX_FILE` via `env: { ...process.env, GIT_INDEX_FILE }`, pointing at a file inside a `mkdtemp` directory that is removed in `finally`. For `assertDelegationGit`, parse `git --version` and compare major.minor ≥ 2.40.
135
+
136
+ - [ ] **Step 4: Run tests.** Same command. Expected: PASS.
137
+
138
+ - [ ] **Step 5: Commit** `feat: Git snapshot, worktree and three-way landing for delegated changes`.
139
+
140
+ ---
141
+
142
+ ### Task 3: Runtime — activation, writing spawns, review record, child shell
143
+
144
+ **Files:**
145
+ - Modify: `src/agent-execution.ts` (instructions ~54, tool filter ~298, `spawn_subagent` ~357-470, approvals ~440-462)
146
+ - Modify: `src/types.ts:125` (add `delegationRoots?: readonly string[]` next to `attachmentRoots`), `src/tools.ts:40` (`trustedAttachment` also consults `delegationRoots`, which is cleared wherever `attachmentRoots` is cleared for mutations)
147
+ - Create: `test/orchestrator-delegation-runtime.test.ts`
148
+
149
+ **Interfaces:**
150
+ - Consumes: Task 1 (`delegatesWriting`, `isWritingRole`, `DELIVERED_OUTCOME`, `CommandScope`, `capabilityTools`), Task 2 (all exports).
151
+ - Produces (module-internal to `executeAgentNode`, used by Task 4):
152
+ - `const delegationActive: boolean` = `orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(e => e.source === node.id && e.outcome === DELIVERED_OUTCOME)`
153
+ - `interface ChangeRecord { id: string; subagentId: string; role: string; worktree: string; base: string; tree?: string; files: CollectedChange['files']; state: 'pending' | 'landed' | 'discarded' | 'conflict'; diffArtifact?: ArtifactRef }`
154
+ - `const changes = new Map<string, ChangeRecord>()`, scoped to the node visit, next to `active` / `total`
155
+ - Event `subagent.change` with data `{ subagentId, changeId, state, files?: string[] }`
156
+ - The writing spawn's observation JSON adds `change: { id, files, diff, truncated: boolean, diffArtifact }` and `tests: string[]` (from `result.completion?.tests ?? []`)
157
+
158
+ - [ ] **Step 1: Write the failing tests** in `test/orchestrator-delegation-runtime.test.ts`. Reuse the harness style of `test/orchestrator-runtime.test.ts` (`tool()`, `plan()`, `read()`, `ask()`, `createTools()`), plus a real temp Git repo fixture from Task 2. The graph is `DEFAULT_HARNESS` with the Task 1 delegating Orchestrator and an edge `orchestrator → done` on `delivered`. Call `executeAgentNode(node, { ...opts, graph })` with `context.permissions = 'full-access'` unless stated.
159
+ - `inactive without a delivered route`: same node, `graph` without the edge. Spawning `coder` returns an observation matching `/capabilities exceed its parent/` and no worktree is created (`git worktree list` has one entry).
160
+ - `writing child gets a shell and works in its worktree`: the stub child adapter's first request has a tool whose `canonicalToolName` is `Bash` or `PowerShell`, and `Write`/`Edit` tools. Replace the shell tool with a stub that records `ctx.workspace`; the recorded workspace is not the repo root and starts with `join(tmpdir(), 'andorra-subagent-')`.
161
+ - `child task notes missing ignored files`: the child's first user message contains `Files ignored by Git (for example node_modules) are not in this worktree`.
162
+ - `review record reaches the Orchestrator`: the child writes `src/a.txt` and completes with `tests: ['npm test: 3 passed']`. The parent's next request has a tool observation whose JSON has `change.files` `[{ path: 'src/a.txt', status: 'M' }]`, `change.diff` containing the edit, `truncated: false`, and `tests` `['npm test: 3 passed']`. The repo's working folder is unchanged at that point.
163
+ - `large diffs are truncated with an artifact`: the child writes 30,000 characters, so `change.diff.length <= 20_000`, `truncated === true`, and `diffArtifact.ref` is readable with `read_artifact` and contains the full diff.
164
+ - `Orchestrator can read inside a child's worktree without prompts`: in `ask-for-approval` with `approve` counting calls, the parent calls `read_file` with the absolute worktree path of the changed file. It returns the new content with zero `approve` calls for that read.
165
+ - `worktree approval is asked once per visit`: in `ask-for-approval` with `approve` returning `true`, two writing spawns produce exactly one `approve` call named `spawn_subagent.worktree`.
166
+ - `failed child yields no change`: a child completing with a failure status means the observation has no `change`, and the worktree path no longer exists.
167
+ - `not a repository fails before side effects`: the workspace is a plain temp dir. The spawn observation matches `/needs the workspace to be a Git repository/`, and `fs.readdir(tmpdir())` shows no new `andorra-subagent-*` entry created by this test (compare before and after).
168
+ - `the Orchestrator still has no write or shell tools`: in every parent request, no tool's canonical name is `Write`, `Edit`, `Bash` or `PowerShell`.
169
+ - `writing spawn waits for clarification`: a writing spawn after `update_todos` but before a successful `ask_user` returns an observation matching `/Ask the user to confirm the design before starting writing subagents/`, and no worktree is created. Read-only research spawns keep today's rule (plan only).
170
+
171
+ - [ ] **Step 2: Run, expect failure.** Run: `npm run build && node scripts/run-tests.mjs dist/test/orchestrator-delegation-runtime.test.js`. Expected: FAIL.
172
+
173
+ - [ ] **Step 3: Implement.**
174
+ - Compute `delegationActive`. When it is false, change nothing.
175
+ - In `spawn_subagent`, for a writing role when `delegationActive`:
176
+ - Refuse with the clarification message from the test while `clarified` is false.
177
+ - Take `parentCapabilities` from `effectiveCapabilities(node)` (the configured ceiling), not the intake-clamped `configured`.
178
+ - Build `available` from `capabilityTools({ ...node, capabilities: parentCapabilities, tools: undefined }, options.tools, 'delegated-worktree')` minus `browser.panel`.
179
+ - Default `childToolNames` for a writing role with no `tools` is all of `available`.
180
+ - Run `assertDelegationGit` before any approval or mkdtemp.
181
+ - Replace the clean-tree `git status` check and `HEAD` base with `snapshotWorkspace` + `addChangeWorktree`.
182
+ - Hoist the worktree approval state (`audited`, `explicitlyApproved`) to the node-visit scope so one grant covers the visit, while keeping its live-mode recheck.
183
+ - Pass a new `commandScope: CommandScope` argument through `run` → `runWithinDeadline` and into `capabilityTools`/`permitsBuiltInTool` (default `depth > 0`). Writing delegated children get `'delegated-worktree'`.
184
+ - Append the ignored-files notice (exact text from the test, followed by: `Install what you need inside this worktree if a build or test requires it.`) to the child task.
185
+ - After the child returns `succeeded`, call `collectChange`. When `files` is empty, remove the worktree and add no change. Otherwise register a `pending` `ChangeRecord`, put the full diff in the `ArtifactStore` as type `delegation-diff`, emit `subagent.change`, and add `worktree` to the parent context's `delegationRoots`.
186
+ - When the child does not succeed, remove the worktree.
187
+ - Append `DELEGATION_INSTRUCTIONS` to the Orchestrator's instructions only when `delegationActive`. It covers: the two paths (`completed` handoff or `delivered`); clarify first; spawn writing roles in parallel; review each `change` and `tests` report; `accept_change` / `discard_change`; spawn fixes with findings; complete `delivered` only when every change is decided; never write code.
188
+
189
+ - [ ] **Step 4: Run tests** plus `dist/test/subagent-worktree-permissions.test.js` and `dist/test/orchestrator-runtime.test.js`. Expected: PASS, apart from known baseline failures.
190
+
191
+ - [ ] **Step 5: Commit** `feat(runtime): writing subagents for a delegating Orchestrator`.
192
+
193
+ ---
194
+
195
+ ### Task 4: Landing tools, `delivered` completion, cleanup, end-to-end routing
196
+
197
+ **Files:**
198
+ - Modify: `src/agent-execution.ts` (tool registration next to `spawn_subagent`, `completionGuard` ~1074, `completionPolicy` ~1079, node `finish`/`finally`)
199
+ - Modify: `test/orchestrator-delegation-runtime.test.ts`
200
+
201
+ **Interfaces:**
202
+ - Consumes: Task 3 `changes`, `ChangeRecord`, `delegationActive`. Task 2 `landChange`, `removeChangeWorktree`.
203
+ - Produces:
204
+ - Tool `accept_change` with `{ id: string }`, returning `{"state":"landed","files":[...]}` or `{"state":"conflict","conflicts":[...],"detail":"..."}`. Allowed from `pending` or `conflict`.
205
+ - Tool `discard_change` with `{ id: string }`, returning `{"state":"discarded"}`. Allowed from `pending` or `conflict`.
206
+ - Both refuse unknown ids (`Unknown change`) and finished changes (`Change already landed` / `Change already discarded`), and both are `executionMode: 'sequential'`.
207
+ - Completion policy when `delegationActive`: `{ mode: 'outcomes', outcomes: [configured completion outcome ?? 'completed', 'delivered'] }`.
208
+
209
+ - [ ] **Step 1: Write the failing tests** (append to the runtime test file):
210
+ - `accept lands and discard removes`: two writing children. `accept_change(c1)` → the working folder has c1's edit, the state is `landed`, and the `subagent.change` event has `state: 'landed'`. `discard_change(c2)` → c2's worktree path is gone and the folder lacks c2's edit.
211
+ - `accept conflict writes nothing and can be retried or discarded`: the user edit conflicts, so the result is `state: 'conflict'` and the folder bytes are unchanged. After the test reverts the user edit, `accept_change` again → `landed`.
212
+ - `landing does not prompt where a workspace edit would not`: in `ask-for-approval` and `approve-for-me`, `accept_change` makes zero `approve` calls. In `read-only`, one `approve` call named `accept_change`, and the change lands only when it returns `true`.
213
+ - `delivered requires every change decided`: completing `delivered` with a `pending` change gets a repair message matching `/Accept or discard every change before completing as delivered/`. With nothing landed, `/Land at least one accepted change before completing as delivered/`. After a decision, it succeeds.
214
+ - `delivered uses the handoff schema`: `delivered` without `taskInstruction` gets the existing handoff repair message.
215
+ - `delivered output references the delivery record`: `result.completion.artifacts` contains one ref of type `delegation-record` whose content lists each change's `role`, `files` and `state`.
216
+ - `runGraph routes delivered`: graph `orchestrator →(completed) engineer`, `orchestrator →(delivered) done`. A delivered run finishes without the engineer adapter being called, and `result.nodeResults.orchestrator.outcome === 'delivered'`.
217
+ - `cancel removes every worktree and keeps accepted changes`: accept c1, then abort `context` while c2's child adapter is awaiting. The run is `cancelled`, the folder has c1's edit and not c2's, and `git worktree list` shows only the main worktree.
218
+ - `undecided changes are discarded at node end`: after a `completed` (handoff) completion with a `pending` change, its worktree is removed and a `subagent.change` `discarded` event fires.
219
+ - `cannot pass content through landing tools`: `accept_change` with an extra `patch` argument is refused by schema validation (`additionalProperties: false`).
220
+
221
+ - [ ] **Step 2: Run, expect failure.** Run: `npm run build && node scripts/run-tests.mjs dist/test/orchestrator-delegation-runtime.test.js`.
222
+
223
+ - [ ] **Step 3: Implement.**
224
+ - Register both tools only when `delegationActive`.
225
+ - Landing approval: call `assertPlanMutationAllowed`. Skip approval when `permissionMode(ctx)` is `full-access`, `ask-for-approval` or `approve-for-me`. Otherwise call `approveOperation(ctx, 'accept_change', { id, files })`.
226
+ - Extend `completionGuard`: when `completion.outcome === 'delivered'`, after the existing handoff checks, require `active === 0`, at least one `landed`, and no `pending`/`conflict` change, using the exact messages from the tests. Then `put` a `delegation-record` artifact and add its ref to the completion's artifacts.
227
+ - In the node's `finally`, for each change not `landed`/`discarded`: run `removeChangeWorktree`, set `discarded`, and emit the event. Also remove worktrees of landed or discarded changes not yet removed.
228
+
229
+ - [ ] **Step 4: Run tests** plus `dist/test/orchestrator-runtime.test.js`, `dist/test/orchestrator-outcome-routing.test.js` and `dist/test/graph-runner.test.js`. Expected: PASS, apart from known baseline failures.
230
+
231
+ - [ ] **Step 5: Commit** `feat(runtime): land, discard and deliver delegated changes`.
232
+
233
+ ---
234
+
235
+ ### Task 5: Graph builder
236
+
237
+ **Files:**
238
+ - Modify: `src/graph-ui/app.js` (`outcomes` ~168, `renderSubagents` ~1126-1160)
239
+ - Modify: `test/graph-ui.test.ts` (or a new `test/graph-ui-delegation.test.ts` using the same vm fixture as `test/graph-ui-orchestrator-reuse.test.ts`)
240
+
241
+ **Interfaces:**
242
+ - Produces in `app.js`: `function delegatesWriting(node)`, mirroring Task 1 exactly. `outcomes(node)` appends `'delivered'` when it is true.
243
+
244
+ - [ ] **Step 1: Write the failing tests:**
245
+ - `outcomes(node)` for the Task 1 fixture deep-equals `['completed', 'delivered']`, and for `DEFAULT_HARNESS.nodes.orchestrator` deep-equals `['completed']`.
246
+ - With the delegating fixture rendered, the subagent help text contains `Writing roles of an Orchestrator run in their own Git worktree with a shell` and does not contain `Subagents never receive the unsandboxed host shell, including in worktrees`.
247
+ - Adding a writing role to an Orchestrator whose workspace is `shared-read-only` sets `policy.workspace` to `worktree`.
248
+
249
+ - [ ] **Step 2: Run, expect failure.** Run: `npm run build && node scripts/run-tests.mjs dist/test/graph-ui-delegation.test.js`.
250
+
251
+ - [ ] **Step 3: Implement.** Help text for a delegating Orchestrator, exactly: `Writing roles of an Orchestrator run in their own Git worktree with a shell. The shell is not sandboxed and follows your permission mode. The Orchestrator reviews each change and lands the ones it accepts into your working folder; it never writes code itself.` Other nodes get today's copy with the "never receive the unsandboxed host shell" sentence changed to `Subagents of ordinary agents never receive the unsandboxed host shell.`
252
+
253
+ - [ ] **Step 4: Run tests** plus `dist/test/graph-ui.test.js` and `dist/test/graph-ui-orchestrator-reuse.test.js`. Expected: PASS.
254
+
255
+ - [ ] **Step 5: Commit** `feat(graph-ui): delivered port and delegation settings`.
256
+
257
+ ---
258
+
259
+ ### Task 6: Desktop change states
260
+
261
+ **Files:**
262
+ - Modify: `desktop/src/engine/rows.ts` (`SubagentItem` ~145, fold `case 'subagent.change'` next to ~2158)
263
+ - Modify: `desktop/src/engine/workflow.ts` (`subagentStatusLabel` ~62)
264
+ - Modify: `desktop/src/components/WorkflowView.tsx` (~183)
265
+ - Test: `desktop/src/engine/rows.test.ts`, `desktop/src/engine/workflow.test.ts`
266
+
267
+ **Interfaces:**
268
+ - Produces: `SubagentItem.change?: 'pending' | 'landed' | 'discarded' | 'conflict'`. `export function subagentChangeLabel(item: SubagentItem): string | undefined` returns `Awaiting review`, `Landed`, `Discarded` or `Conflict`, or `undefined` when there is no change.
269
+
270
+ - [ ] **Step 1: Write failing tests:**
271
+ - `rows.test.ts`: folding `subagent.started` then `subagent.change { subagentId, state: 'pending' }` then `{ state: 'landed' }` leaves `state.subagents[0].change === 'landed'`. A `subagent.change` for an unknown id is ignored.
272
+ - `workflow.test.ts`: `subagentChangeLabel` maps all four states, and `undefined` for an item without `change`.
273
+
274
+ - [ ] **Step 2: Run, expect failure.** Run: `npm test --prefix desktop -- rows workflow`.
275
+
276
+ - [ ] **Step 3: Implement.** The fold replaces the item immutably, like the existing cases. `WorkflowView` renders the label after the status in a `workflow-agent-change` span.
277
+
278
+ - [ ] **Step 4: Run tests and typecheck.** Run: `npm test --prefix desktop -- rows workflow WorkflowView && npm run check --prefix desktop`. Expected: PASS.
279
+
280
+ - [ ] **Step 5: Commit** `feat(desktop): show delegated change state on subagents`.
281
+
282
+ ---
283
+
284
+ ### Task 7: QA plan, run verification, pull request
285
+
286
+ **Files:**
287
+ - Create: `tests/orchestrator-delegation-test-plan.md`
288
+
289
+ - [ ] **Step 1: Write the QA plan** to the AGENTS.md outline. Cover: scope and prerequisites (Premium account, Git ≥ 2.40, two providers), how to configure the graph in the builder, and cases for each spec goal, the five Review Focus items, each permission mode, Windows paths with spaces, and the no-`delivered`-route fallback. Include gaps and limitations, and validation evidence (only what was actually run).
290
+
291
+ - [ ] **Step 2: Run verification with the built CLI.** `npm run build`. Then, in a throwaway home (`home=$(mktemp -d) || exit 1; export ANDORRACODE_HOME="$home"`, removed in the same invocation), drive `node dist/src/cli.js app-server --stdio` against a temp Git repo and a local stub provider (see memory "Verify desktop renderer headless"). Run a delegating graph through: clarify, two writing spawns, accept one, discard one, deliver. Observe: the folder has the accepted change only, `git worktree list` is clean, `git diff --cached` is empty, and the run ends on `delivered`. Record the commands and output for the PR.
292
+
293
+ - [ ] **Step 3: Confirm nothing is left behind.** `git status --short` shows only intended changes, and no `andorra-subagent-*` directory from the run remains in `tmpdir()`.
294
+
295
+ - [ ] **Step 4: Commit, push and open the PR** to `main` using `.github/PULL_REQUEST_TEMPLATE.md`. List the exact tests run and the verification above in Validation, linking the QA plan. Then follow the Codex review loop in AGENTS.md.
@@ -0,0 +1,291 @@
1
+ # Orchestrator delegation: write-capable subagents, review and landing
2
+
3
+ Date: 2026-11-09
4
+ Status: design for review, pending user approval
5
+
6
+ ## Intent
7
+
8
+ The user wants to run the Orchestrator on an expensive, strong model (for example Fable 5.5) as a
9
+ lead that plans, delegates and reviews but never writes code itself. The implementation work goes to
10
+ subagents running on other (typically cheaper) models, several at a time. When subagent work comes
11
+ back wrong or incomplete, the Orchestrator spawns more subagents to fix it, and finishes only when it
12
+ is satisfied.
13
+
14
+ This is optional. The Orchestrator's current job (intake: research, clarify, hand a task instruction
15
+ to the next node) stays the default and keeps working unchanged.
16
+
17
+ ## Current state
18
+
19
+ - An Orchestrator is an Agent node with `agentRole: 'orchestrator'`, built by `createOrchestratorNode`
20
+ (`src/graphs.ts`). A version 3 graph allows at most one, and it must be the entry with no incoming
21
+ edges.
22
+ - At runtime its capabilities are clamped to `intakeCapabilities` (`src/graphs.ts`): read-only
23
+ filesystem and Git, no shell, no GitHub, no deployment (`src/agent-execution.ts`, start of
24
+ `runWithinDeadline`). Its tool list is filtered to research tools plus `ask_user`, `update_todos`,
25
+ artifacts, skills and the browser.
26
+ - It can already spawn subagents through `spawn_subagent` (`src/agent-execution.ts`), using the
27
+ node's `subagents` policy: `maxConcurrent` (≤16), `maxTotal`, `maxDepth`, `modelPolicy`
28
+ (`inherit` / `specific` / `per-role`), `workspace` (`shared-read-only` / `shared-write` /
29
+ `worktree`), `toolInheritance`, `context`, `roles`. The graph builder exposes all of these
30
+ (`renderSubagents` in `src/graph-ui/app.js`).
31
+ - A child's capabilities must be a subset of its parent's. For the Orchestrator the parent ceiling is
32
+ the intake ceiling, so graph validation rejects any writing role ("role … capability exceeds parent
33
+ intake read-only ceiling", `src/graphs.ts`) and the runtime rejects it again at spawn time.
34
+ - `spawn_subagent` blocks until the child finishes and returns `{status, outcome, output, artifacts}`
35
+ as a tool observation. Several spawn calls in one model turn run concurrently up to `maxConcurrent`.
36
+ - With `workspace: 'worktree'`, a writing child gets a detached worktree created from `HEAD` in a
37
+ temp directory. Creation requires a clean parent working tree and parent Git write. The worktree is
38
+ recorded as a `git-worktree` artifact and is never merged back.
39
+ - Subagents never get a shell: `canRunCommands` in `src/graphs.ts` returns false for every child,
40
+ including in worktrees, and the QA tools follow the same rule.
41
+ - The preset Orchestrator completes with a single outcome, `completed`, but nothing enforces that: the
42
+ graph builder lets an author switch it to `completion.mode: 'outcomes'` with their own outcome
43
+ names (`src/graph-ui/app.js`). Its output is validated against one `outputSchema` whatever the
44
+ outcome (`src/graph-runner.ts`); the preset schema is closed and requires the handoff fields
45
+ (`validateOrchestratorContracts`, `src/graphs.ts`).
46
+ - Before completing, the Orchestrator must have clarified with the user (`ask_user`), published a
47
+ plan (`update_todos`) and observed research (`orchestratorCompletionGuard`). Headless runs stop with
48
+ `needs_clarification`.
49
+ - The intake ceiling is checked against roles only while spawning is enabled (`subagents.enabled`
50
+ and `maxSubagents !== 0`). A saved Orchestrator with spawning off can already carry writing roles.
51
+ - `DEFAULT_HARNESS_REVISION_5` and the current default harness are built from
52
+ `createOrchestratorNode()` at load time; only revisions 1–4 are literal snapshots.
53
+ - The Orchestrator is a Premium feature (`src/graph-quota.ts`).
54
+
55
+ ## Goals
56
+
57
+ 1. **A no-code lead.** The Orchestrator never edits files, runs a shell or commits, whatever model it
58
+ runs on. It reads, decides and delegates.
59
+ 2. **Writing subagents.** An Orchestrator can be configured with roles that write code. Each role's
60
+ model is set in the graph builder through the existing Model policy (one model for all subagents,
61
+ or one per role).
62
+ 3. **Parallel writers.** Several writing subagents run at once, bounded by the existing
63
+ "Max concurrent" setting on the Orchestrator.
64
+ 4. **Review.** When a writing subagent finishes, the Orchestrator sees what it changed (the diff), the
65
+ commands and tests it ran with their results, and can read the changed files before deciding.
66
+ 5. **Landing.** Changes the Orchestrator accepts land in the user's working folder automatically, as
67
+ uncommitted edits. Changes it rejects are discarded.
68
+ 6. **Fix loop.** When work is wrong or incomplete, the Orchestrator spawns subagents to fix it, with
69
+ its review findings in their task, and reviews again. The loop is bounded by "Max total per node
70
+ run".
71
+ 7. **Routing.** The Orchestrator reports which path it took, and the graph author routes each path in
72
+ the graph builder.
73
+
74
+ ## Non-goals
75
+
76
+ - Live management of a running child: no status polling, mid-task messages or per-child cancel. The
77
+ existing call-and-return `spawn_subagent` (with concurrent batches) is enough.
78
+ - The Orchestrator choosing models at run time. Models come from the graph.
79
+ - Committing, pushing or opening pull requests from the Orchestrator.
80
+ - Changing ordinary (non-Orchestrator) Agent nodes' subagent behavior.
81
+ - Changing the bundled default harness or any frozen revision (`DEFAULT_HARNESS_REVISION_*`).
82
+
83
+ ## Anti-goals (a failure even if it technically works)
84
+
85
+ - The Orchestrator writing code itself through a back door (for example by passing file contents to
86
+ a "land" tool, or by running `git apply` with text it composed).
87
+ - An existing graph changing behavior, failing to load, or failing validation after this ships.
88
+ - Parallel writers overwriting each other's work in the working folder.
89
+ - A failed or rejected subagent leaving partial edits in the working folder.
90
+ - Asking the user to review every change before it lands.
91
+
92
+ ## Design
93
+
94
+ ### 1. Turning it on
95
+
96
+ Delegation is on for an Orchestrator when spawning is enabled (`subagents.enabled` and
97
+ `maxSubagents !== 0`) and its subagent policy has at least one **writing role** (a role whose
98
+ capabilities include filesystem `read-write` or Git `write`). An Orchestrator with no writing roles,
99
+ or with spawning off, behaves exactly as today. No existing graph has writing roles with spawning on,
100
+ because validation rejects that combination today.
101
+
102
+ *Designer's call:* delegation requires the Orchestrator's completion to be in `single` mode.
103
+ Combining it with author-declared outcomes (`completion.mode: 'outcomes'`) is refused at
104
+ validation with a message that names the conflict. This can be relaxed later.
105
+
106
+ The Orchestrator then gets two completion outcomes:
107
+
108
+ - `completed` keeps today's meaning: intake finished and the requirements are handed onward. The
109
+ name is unchanged so existing edges keep routing.
110
+ - `delivered` (new): the work was done by subagents, reviewed, and landed.
111
+
112
+ The graph author draws a route for each outcome in the graph builder. If the graph has no route for
113
+ `delivered`, the Orchestrator is not offered the delivery path at run time: writing roles are refused
114
+ at spawn exactly as they are today, and it cannot complete as `delivered`. A graph that has writing
115
+ roles but no `delivered` route still behaves like intake. The `delivered` outcome should not be
116
+ required to have a route (`requireRoutes: false` semantics for that outcome only, or equivalent).
117
+
118
+ ### 2. Choosing a path per prompt
119
+
120
+ The Orchestrator decides from the prompt whether to hand off or deliver. Clarification is unchanged
121
+ in both paths: it researches, asks the user its questions with `ask_user`, and publishes its plan
122
+ with `update_todos` before any writing subagent starts. Headless runs still stop with
123
+ `needs_clarification`.
124
+
125
+ - Completing as `completed` requires today's handoff output (`taskInstruction`, `requirements`, …).
126
+ - Completing as `delivered` requires: no child still running, at least one accepted change landed,
127
+ and no reviewed change left undecided.
128
+
129
+ *Designer's call:* `delivered` uses the same `outputSchema` as `completed`. There are no
130
+ per-outcome schemas. The handoff fields keep their meaning (`requirements`, `acceptanceCriteria`,
131
+ `designConsiderations`, `codebaseFindings`), and `taskInstruction` says what landed and what is left
132
+ to verify, so a downstream Agent fed by `ORCHESTRATOR_HANDOFF` works unchanged. The full delivery
133
+ record (each change: role, model, files, accepted or discarded, conflicts) is written as an artifact
134
+ and referenced from the completion.
135
+
136
+ ### 3. Two ceilings instead of one
137
+
138
+ Split what the Orchestrator may do from what its children may do:
139
+
140
+ - **Orchestrator's own capabilities:** always `intakeCapabilities`, as today. No Write/Edit, no
141
+ shell, no commits.
142
+ - **Delegation ceiling:** the node's configured `capabilities`. Writing roles are validated against
143
+ this ceiling instead of the intake ceiling, in both graph validation (`src/graphs.ts`) and the
144
+ spawn-time check (`src/agent-execution.ts`). Read-only roles keep working as today.
145
+
146
+ Writing roles on an Orchestrator require `workspace: 'worktree'`. `shared-write` is refused for an
147
+ Orchestrator, even with `maxConcurrent: 1`, because only worktrees give the review-then-land step a
148
+ clean diff and keep rejected work out of the working folder.
149
+
150
+ The Orchestrator's node needs Git `write` in its configured capabilities to create worktrees. That
151
+ grant applies to the delegation ceiling only; the Orchestrator itself still has no Git write tool.
152
+
153
+ ### 4. Worktrees start from the working folder as it stands
154
+
155
+ Today a worktree starts from `HEAD` and requires a clean working tree. That breaks delegation: after
156
+ the first change lands, the folder has uncommitted edits, and later subagents must build on them.
157
+
158
+ For Orchestrator delegation, each writing child's worktree starts from a snapshot of the working
159
+ folder at spawn time, including uncommitted and untracked (non-ignored) files, without modifying the
160
+ working folder, the index, refs or stash. The clean-tree requirement is dropped for this path only.
161
+ The snapshot mechanism is the builder's call (for example a temporary index plus `git write-tree`
162
+ and `git commit-tree`, kept under a private ref until cleanup).
163
+
164
+ The worktree approval prompt (`spawn_subagent.worktree`) still applies under the user's permission
165
+ mode.
166
+
167
+ ### 5. Review
168
+
169
+ When a writing child finishes, its `spawn_subagent` result also carries a change record: an id, the
170
+ list of changed files, and the diff against the child's snapshot (truncated past a size limit, with
171
+ the full diff available through `read_artifact`). The Orchestrator can read files inside the child's
172
+ worktree with its normal read tools, scoped read-only to that worktree, to inspect the result in
173
+ context.
174
+
175
+ A child that failed, was cancelled, or produced no changes yields no change to land, and its
176
+ worktree is discarded.
177
+
178
+ ### 6. Landing
179
+
180
+ Two new Orchestrator-only tools act on a change record by id:
181
+
182
+ - `accept_change(id)`: Andorra applies the child's diff to the working folder with a three-way
183
+ merge against the child's snapshot. On success the files land as uncommitted edits. On conflict,
184
+ nothing is written to the working folder, and the tool returns the conflicting files and hunks so
185
+ the Orchestrator can spawn a subagent to redo or reconcile the work on top of the current folder.
186
+ - `discard_change(id)`: the change is dropped and its worktree removed.
187
+
188
+ The Orchestrator passes only an id. It never supplies file contents, patches or commands, so it
189
+ cannot use these tools to write code itself.
190
+
191
+ *Designer's call on approvals.* The user asked for accepted changes to land automatically, so landing
192
+ must not prompt per change in any permission mode that already auto-approves in-workspace file
193
+ writes (`workspace-policy`, `src/tools.ts`). It follows that same rule: no prompt where an Edit
194
+ inside the workspace would not prompt, and a prompt where it would. Worktree setup is a host
195
+ operation and still goes through `approveOperation`, but outside Full Access it asks once per
196
+ Orchestrator node visit, not once per spawn: the first writing spawn's grant covers that visit's
197
+ worktrees. The Orchestrator's reads inside its children's worktrees are treated as reads inside a
198
+ trusted root, so they do not prompt as "outside the workspace."
199
+
200
+ Accepting changes from two children that touched the same files is allowed; the second accept
201
+ merges against the current folder and either lands or reports a conflict.
202
+
203
+ ### 7. The fix loop
204
+
205
+ After review, the Orchestrator either accepts, discards, or spawns a fix subagent. A fix subagent
206
+ gets a normal task that includes the Orchestrator's findings. It starts from the current folder
207
+ snapshot, so a fix can build on an accepted change, or redo a discarded one. Every spawn counts
208
+ toward "Max total per node run"; when it is used up, the Orchestrator must finish with what it has
209
+ or report that it could not complete.
210
+
211
+ ### 8. Checking that the work runs
212
+
213
+ **Decided by the user: writing subagents get a shell inside their own worktree.**
214
+
215
+ - A writing role on a delegating Orchestrator, running in `workspace: 'worktree'`, may have
216
+ `shell: 'allowed'` when the Orchestrator's delegation ceiling allows it. That role then gets the
217
+ command tools (`Bash` / `PowerShell` and the related process tools) and the QA tools, with the
218
+ working directory set to its own worktree.
219
+ - `canRunCommands` (`src/graphs.ts`) stops refusing every child. It permits these children
220
+ specifically, and keeps refusing every other child: read-only roles, shared-workspace children,
221
+ and children of ordinary Agent nodes. Graph validation and the spawn-time check use the same rule.
222
+ - The shell is not sandboxed. Starting in the worktree is a working directory, not a boundary.
223
+ Commands go through the same approval rules as the main agent's shell under the user's permission
224
+ mode, and the approval prompt names the subagent and its worktree. Several parallel subagents in an
225
+ asking mode can each prompt; that is accepted.
226
+ - A subagent reports the commands it ran and their results in its completion (for example tests run,
227
+ pass/fail). The Orchestrator sees that report next to the diff and uses it in its review. A failure
228
+ report is grounds to spawn a fix.
229
+ - The Orchestrator itself still has no shell.
230
+ - The graph builder's subagent help text, which today says "Subagents never receive the unsandboxed
231
+ host shell, including in worktrees" (`src/graph-ui/app.js`), changes to describe the exception
232
+ accurately.
233
+ - A child with Git `write` may commit inside its worktree. Landing uses the worktree's final file
234
+ state against its snapshot, so commits made there do not change what lands, and nothing it
235
+ commits reaches the user's branches.
236
+
237
+ ### 9. Models
238
+
239
+ No new setting. The Orchestrator's existing subagent Model policy covers it: "Use specific model"
240
+ for one model across all subagents, or "Per-role model" to give coding and other roles different
241
+ models. The Orchestrator's own model is its node model.
242
+
243
+ ### 10. Graph builder
244
+
245
+ - Writing roles become allowed on the Orchestrator's role editor when the Orchestrator's
246
+ capabilities grant them; the help text explains that the Orchestrator itself still cannot write.
247
+ - Selecting a writing role on an Orchestrator forces or requires "Separate Git worktree".
248
+ - The Orchestrator node shows a `delivered` output port next to `completed` once it has a writing
249
+ role.
250
+ - Validation messages name the fix (for example "writing roles on an Orchestrator require separate
251
+ worktrees").
252
+
253
+ ### 11. Desktop
254
+
255
+ Subagents already appear nested under the Orchestrator's node visit. Each writing child's entry also
256
+ shows its change state (pending review, landed, discarded, conflict). Visual treatment is the
257
+ builder's call.
258
+
259
+ ### 12. Cleanup and failure
260
+
261
+ - Every worktree and snapshot ref created for a child is removed when its change is accepted or
262
+ discarded, and when the Orchestrator's node ends for any reason (completion, failure, cancel,
263
+ wall-time). Undecided changes at node end are discarded, and the run reports that.
264
+ - A cancelled run leaves the working folder with only the changes already accepted.
265
+
266
+ ## Constraints
267
+
268
+ - Existing graphs, including the bundled default harness and frozen revisions, load, validate and run
269
+ exactly as before.
270
+ - `createOrchestratorNode()` must not change what it returns, because revision 5 and the current
271
+ default harness are built from it at load time. Delegation is configured by the graph author on top
272
+ of the preset. If the builder has to change the preset, it first freezes revisions 5 and 6 as
273
+ literal snapshots, the way revisions 1–4 are.
274
+ - The Orchestrator remains Premium (`src/graph-quota.ts`).
275
+ - Per `AGENTS.md`, the feature ships with a QA plan at `tests/orchestrator-delegation-test-plan.md`.
276
+ - Works on Windows (the primary dev machine) and POSIX; Git operations go through the same hardened
277
+ options the worktree path uses today (`core.hooksPath=`, `core.fsmonitor=false`).
278
+
279
+ ## Left to the builder
280
+
281
+ - The exact schema of the `delivered` output and of the change record.
282
+ - The snapshot mechanism for worktree bases, and the diff size limit.
283
+ - How `delivered` is excluded when it has no route (tool enum, completion guard, or both).
284
+ - How resume behaves when a run is resumed with children mid-flight or changes undecided (the safe
285
+ default is to discard undecided changes and tell the Orchestrator).
286
+ - Whether the Jev decision layer needs to know about the new tools.
287
+ - Desktop presentation of change states.
288
+
289
+ ## Open questions
290
+
291
+ None. The user chose a worktree-scoped shell for writing subagents (section 8).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andorra-labs/code",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Terminal-first coding agent with a ReAct graph runtime",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",