@cleocode/core 2026.11.1-canary.9 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/.source-stamp.json +1 -1
  2. package/dist/build-provenance.json +2 -2
  3. package/dist/config.js +2 -0
  4. package/dist/config.js.map +1 -1
  5. package/dist/doctor/db-substrate.js +14 -6
  6. package/dist/doctor/db-substrate.js.map +1 -1
  7. package/dist/doctor/migrations.d.ts +16 -0
  8. package/dist/doctor/migrations.js +85 -1
  9. package/dist/doctor/migrations.js.map +1 -1
  10. package/dist/doctor/system-health.d.ts +77 -1
  11. package/dist/doctor/system-health.js +145 -0
  12. package/dist/doctor/system-health.js.map +1 -1
  13. package/dist/errors-to-engine.d.ts +8 -4
  14. package/dist/errors-to-engine.js +9 -5
  15. package/dist/errors-to-engine.js.map +1 -1
  16. package/dist/errors.d.ts +14 -0
  17. package/dist/errors.js +10 -0
  18. package/dist/errors.js.map +1 -1
  19. package/dist/git/work-tree.js +1 -1
  20. package/dist/git/work-tree.js.map +1 -1
  21. package/dist/hygiene/census.d.ts +181 -12
  22. package/dist/hygiene/census.js +564 -86
  23. package/dist/hygiene/census.js.map +1 -1
  24. package/dist/hygiene/prune-plan-worker.d.ts +17 -0
  25. package/dist/hygiene/prune-plan-worker.js +42 -0
  26. package/dist/hygiene/prune-plan-worker.js.map +1 -0
  27. package/dist/hygiene/task-status.d.ts +20 -0
  28. package/dist/hygiene/task-status.js +71 -0
  29. package/dist/hygiene/task-status.js.map +1 -0
  30. package/dist/memory/pipeline-manifest-sqlite.d.ts +2 -1
  31. package/dist/memory/pipeline-manifest-sqlite.js +3 -2
  32. package/dist/memory/pipeline-manifest-sqlite.js.map +1 -1
  33. package/dist/orchestrate/agentmbx.d.ts +5 -2
  34. package/dist/orchestrate/agentmbx.js +7 -4
  35. package/dist/orchestrate/agentmbx.js.map +1 -1
  36. package/dist/orchestrate/dispatch-workers.d.ts +10 -3
  37. package/dist/orchestrate/dispatch-workers.js +26 -14
  38. package/dist/orchestrate/dispatch-workers.js.map +1 -1
  39. package/dist/orchestrate/lead.d.ts +3 -0
  40. package/dist/orchestrate/lead.js +1 -0
  41. package/dist/orchestrate/lead.js.map +1 -1
  42. package/dist/orchestrate/orca-execution.d.ts +151 -0
  43. package/dist/orchestrate/orca-execution.js +571 -0
  44. package/dist/orchestrate/orca-execution.js.map +1 -0
  45. package/dist/orchestrate/orca-routing.d.ts +13 -0
  46. package/dist/orchestrate/orca-routing.js +142 -0
  47. package/dist/orchestrate/orca-routing.js.map +1 -0
  48. package/dist/orchestrate/spawn-ops.d.ts +50 -20
  49. package/dist/orchestrate/spawn-ops.js +332 -86
  50. package/dist/orchestrate/spawn-ops.js.map +1 -1
  51. package/dist/orchestrate/worker-records.d.ts +97 -5
  52. package/dist/orchestrate/worker-records.js +503 -11
  53. package/dist/orchestrate/worker-records.js.map +1 -1
  54. package/dist/orchestrate/worker-report.js +1 -0
  55. package/dist/orchestrate/worker-report.js.map +1 -1
  56. package/dist/orchestration/index.d.ts +8 -2
  57. package/dist/orchestration/index.js +70 -17
  58. package/dist/orchestration/index.js.map +1 -1
  59. package/dist/orchestration/spawn-prompt.d.ts +9 -2
  60. package/dist/orchestration/spawn-prompt.js +47 -18
  61. package/dist/orchestration/spawn-prompt.js.map +1 -1
  62. package/dist/orchestration/spawn.d.ts +20 -6
  63. package/dist/orchestration/spawn.js +14 -6
  64. package/dist/orchestration/spawn.js.map +1 -1
  65. package/dist/release/ci-evidence.d.ts +55 -2
  66. package/dist/release/ci-evidence.js +161 -51
  67. package/dist/release/ci-evidence.js.map +1 -1
  68. package/dist/resources/admission-ledger.d.ts +6 -0
  69. package/dist/resources/admission-ledger.js +100 -10
  70. package/dist/resources/admission-ledger.js.map +1 -1
  71. package/dist/resources/agent-lease.d.ts +7 -0
  72. package/dist/resources/agent-lease.js +37 -4
  73. package/dist/resources/agent-lease.js.map +1 -1
  74. package/dist/resources/hook-footprint.d.ts +22 -0
  75. package/dist/resources/hook-footprint.js +49 -2
  76. package/dist/resources/hook-footprint.js.map +1 -1
  77. package/dist/resources/run-class.d.ts +9 -1
  78. package/dist/resources/run-class.js +87 -6
  79. package/dist/resources/run-class.js.map +1 -1
  80. package/dist/spawn/adapter-registry.js +5 -0
  81. package/dist/spawn/adapter-registry.js.map +1 -1
  82. package/dist/spawn/branch-integration.d.ts +4 -0
  83. package/dist/spawn/branch-integration.js +10 -1
  84. package/dist/spawn/branch-integration.js.map +1 -1
  85. package/dist/store/open-cleo-db.d.ts +17 -0
  86. package/dist/store/open-cleo-db.js +39 -0
  87. package/dist/store/open-cleo-db.js.map +1 -1
  88. package/dist/store/restore-marker.js +4 -0
  89. package/dist/store/restore-marker.js.map +1 -1
  90. package/dist/store/sqlite.d.ts +21 -0
  91. package/dist/store/sqlite.js +33 -0
  92. package/dist/store/sqlite.js.map +1 -1
  93. package/dist/store/worktree-build-guard.js +3 -0
  94. package/dist/store/worktree-build-guard.js.map +1 -1
  95. package/dist/tasks/add.js +8 -0
  96. package/dist/tasks/add.js.map +1 -1
  97. package/dist/tasks/complete.d.ts +7 -3
  98. package/dist/tasks/complete.js +5 -0
  99. package/dist/tasks/complete.js.map +1 -1
  100. package/dist/tasks/engine-wrap.d.ts +3 -1
  101. package/dist/tasks/engine-wrap.js +6 -18
  102. package/dist/tasks/engine-wrap.js.map +1 -1
  103. package/dist/tasks/merge-close.d.ts +5 -3
  104. package/dist/tasks/merge-close.js +30 -10
  105. package/dist/tasks/merge-close.js.map +1 -1
  106. package/dist/tasks/pipeline-stage.d.ts +7 -1
  107. package/dist/tasks/pipeline-stage.js +44 -0
  108. package/dist/tasks/pipeline-stage.js.map +1 -1
  109. package/dist/tasks/update.js +8 -0
  110. package/dist/tasks/update.js.map +1 -1
  111. package/dist/upgrade.d.ts +4 -0
  112. package/dist/upgrade.js +32 -0
  113. package/dist/upgrade.js.map +1 -1
  114. package/dist/worktree/in-use-probe.d.ts +19 -0
  115. package/dist/worktree/in-use-probe.js +87 -0
  116. package/dist/worktree/in-use-probe.js.map +1 -1
  117. package/dist/worktree/list.d.ts +6 -6
  118. package/dist/worktree/list.js +42 -30
  119. package/dist/worktree/list.js.map +1 -1
  120. package/dist/worktree/own-project.d.ts +32 -0
  121. package/dist/worktree/own-project.js +68 -0
  122. package/dist/worktree/own-project.js.map +1 -0
  123. package/dist/worktree/prune.d.ts +11 -1
  124. package/dist/worktree/prune.js +83 -2
  125. package/dist/worktree/prune.js.map +1 -1
  126. package/package.json +12 -12
  127. package/templates/CLEO-INJECTION.md +1 -1
  128. package/templates/CLEO-REFERENCE.md +2 -2
@@ -61,10 +61,13 @@ import { execFileSync } from 'node:child_process';
61
61
  import { existsSync } from 'node:fs';
62
62
  import { join } from 'node:path';
63
63
  import { RESOURCE_DEFERRED_CODE, RESOURCE_EXTERNAL_PRESSURE_CODE, } from '@cleocode/contracts/resource-governor.js';
64
- import { acquireWorktreeTaskLock, destroyWorktree, isWorktreeLockedError, releaseWorktreeTaskLock, runWorktreeHooks, } from '@cleocode/worktree';
64
+ import { readDeclaredProjectIdentity } from '@cleocode/paths';
65
+ import { acquireWorktreeTaskLock, destroyWorktree, disposeOwnedWorktree, isWorktreeLockedError, releaseWorktreeTaskLock, runWorktreeHooks, } from '@cleocode/worktree';
65
66
  import { findLeastLoadedAgent } from '../agents/capacity.js';
66
67
  import { substituteCantAgentBody } from '../agents/variable-substitution.js';
67
68
  import { engineError } from '../engine-result.js';
69
+ import { CleoError } from '../errors.js';
70
+ import { cleoErrorToEngineResult } from '../errors-to-engine.js';
68
71
  import { selectHarnessSpawnProvider } from '../harness/spawn-provider-selection.js';
69
72
  import { hooks } from '../hooks/registry.js';
70
73
  import { getLogger } from '../logger.js';
@@ -81,10 +84,25 @@ import { getSpawnAdapterFix, initializeDefaultAdapters, spawnRegistry, } from '.
81
84
  import { abandonSpawnSession, requireSpawnSession, } from '../spawn/agent-identity.js';
82
85
  import { auditWorktreeLockReclaim, resolveLockSessionProbe, resolveSpawnLockHolder, } from '../spawn/worktree-lock-holder.js';
83
86
  import { getTaskAccessor } from '../store/data-accessor.js';
87
+ import { resolveBoundSession } from '../store/session-store.js';
88
+ import { getTaskPipelineStageSource } from '../tasks/pipeline-stage.js';
84
89
  import { resolveLeadMailbox } from './agentmbx.js';
85
90
  import { isLeadWorkerV1Enabled, resolveIsolation } from './isolation-policy.js';
86
91
  import { openAgentRegistryDbForComposer } from './plan.js';
87
- import { abandonWorkerRecord, newWorkerInstanceId, recordWorker, settleWorkerAtSpawn, } from './worker-records.js';
92
+ import { abandonWorkerRecord, findOrcaWorker, newWorkerInstanceId, recordWorker, settleWorkerAtSpawn, } from './worker-records.js';
93
+ /** Refuse every spawn entry point while an external attempt retains custody. */
94
+ function orcaCustodyRefusal(record) {
95
+ // @sync-invariant none:local-only an external editor may still run even after its launch CLI disappeared
96
+ return engineError('E_ORCA_ATTEMPT_FENCED', `Task ${record.taskId} has a retained Orca execution attempt.`, {
97
+ details: {
98
+ recordId: record.recordId,
99
+ state: record.execution?.state,
100
+ dispatchId: record.execution?.dispatchId,
101
+ runtimeId: record.execution?.context.runtimeId,
102
+ },
103
+ fix: 'Inspect the stored runtime, Dispatch and issued request; recover that exact attempt before dispatching another editor.',
104
+ });
105
+ }
88
106
  // ---------------------------------------------------------------------------
89
107
  // T9545 — Spawn pipeline timeout supervisor
90
108
  // ---------------------------------------------------------------------------
@@ -116,17 +134,6 @@ export const SPAWN_BUDGET_MS = 180_000;
116
134
  * @task T9545
117
135
  */
118
136
  export const CLEANUP_BUDGET_MS = 5_000;
119
- /**
120
- * Best-effort, bounded cleanup of a partially-provisioned worktree after the
121
- * spawn supervisor fires. Idempotent: re-running against an absent worktree
122
- * returns `worktreeRemoved: true` without erroring. Wrapped in its own
123
- * `setTimeout` so cleanup itself can never wedge the timeout envelope.
124
- *
125
- * @param projectRoot - Absolute path to the project root.
126
- * @param taskId - Task ID whose worktree is being cleaned up.
127
- * @returns Structured cleanup outcome (never throws).
128
- * @task T9545
129
- */
130
137
  /**
131
138
  * Map a {@link SpawnResult} status onto the `SubagentStop` payload vocabulary.
132
139
  *
@@ -159,27 +166,81 @@ export function toSubagentStopStatus(status) {
159
166
  }
160
167
  }
161
168
  /**
162
- * Decide whether a failed `spawnWorktree` may be answered with
163
- * {@link runTimeoutCleanup} (T12506). Only a worktree the failing call itself
164
- * created (`freshWorktreeCreated === true`, set by `createWorktree`) is ours
165
- * to destroy; every other failure — including every lock error — is a
166
- * refusal that leaves the existing worktree untouched.
169
+ * The cleanup `createWorktree` already ran for a worktree its failed call
170
+ * freshly created (T12506). It runs there, while the per-task lock is still
171
+ * held: once the lock is released a concurrent re-spawn may own the path, so
172
+ * a failed provision is never cleaned up from here (T14407). Every other
173
+ * failure, including every lock error, carries none and left the existing
174
+ * worktree untouched.
167
175
  *
168
176
  * @param err - The error thrown by `spawnWorktree` / `createWorktree`.
169
- * @returns True only when cleanup is safe.
170
- * @task T12506
177
+ * @returns The cleanup outcome, or `undefined` when no worktree was created.
178
+ * @task T14407
171
179
  */
172
- export function shouldCleanUpFailedProvision(err) {
173
- if (isWorktreeLockedError(err))
174
- return false;
175
- return (err !== null &&
176
- typeof err === 'object' &&
177
- err.freshWorktreeCreated === true);
180
+ function failedProvisionCleanup(err) {
181
+ const cleanup = err?.cleanup;
182
+ if (!cleanup)
183
+ return undefined;
184
+ return {
185
+ attempted: true,
186
+ worktreeRemoved: cleanup.worktreeRemoved,
187
+ branchDeleted: cleanup.branchDeleted,
188
+ ...(cleanup.error !== undefined ? { error: cleanup.error } : {}),
189
+ };
178
190
  }
179
- export async function runTimeoutCleanup(projectRoot, taskId) {
191
+ /**
192
+ * Best-effort, bounded cleanup of a partially-provisioned worktree after the
193
+ * spawn supervisor fires. Idempotent: re-running against an absent worktree
194
+ * returns `worktreeRemoved: true` without erroring. Wrapped in its own
195
+ * `setTimeout` so cleanup itself can never wedge the timeout envelope.
196
+ *
197
+ * With `owned`, removal goes through `disposeOwnedWorktree`: nothing is
198
+ * removed unless, under the task lock's mutex, the lock still carries the
199
+ * token this spawn acquired and the task's checkout is the exact path and
200
+ * branch this spawn created (T14483). After a supervisor timeout or a session
201
+ * abandonment a newer spawn of the same task may have reclaimed the lock and
202
+ * now owns that checkout. The branch is kept.
203
+ *
204
+ * @param projectRoot - Absolute path to the project root.
205
+ * @param taskId - Task ID whose worktree is being cleaned up.
206
+ * @param owned - The exact worktree path and lock token this spawn created.
207
+ * @returns Structured cleanup outcome (never throws).
208
+ * @task T9545
209
+ * @task T14483
210
+ */
211
+ export async function runTimeoutCleanup(projectRoot, taskId, owned) {
180
212
  const startedAt = Date.now();
181
213
  let timer;
182
214
  try {
215
+ if (owned) {
216
+ // T14483: token, canonical path, branch and removal are all checked
217
+ // under the task lock's mutex, so a re-spawn never loses its worktree.
218
+ const disposed = disposeOwnedWorktree({
219
+ projectHash: owned.projectHash,
220
+ taskId,
221
+ worktreePath: owned.worktreePath,
222
+ branch: owned.branch,
223
+ lockToken: owned.lockToken,
224
+ projectRoot,
225
+ reason: 'spawn-timeout-cleanup',
226
+ force: true,
227
+ });
228
+ return disposed.outcome === 'removed'
229
+ ? {
230
+ attempted: true,
231
+ worktreeRemoved: true,
232
+ branchDeleted: false,
233
+ elapsedMs: Date.now() - startedAt,
234
+ }
235
+ : {
236
+ attempted: false,
237
+ worktreeRemoved: false,
238
+ branchDeleted: false,
239
+ notOwned: true,
240
+ error: `Cleanup skipped: ${disposed.reason}; nothing was removed`,
241
+ elapsedMs: Date.now() - startedAt,
242
+ };
243
+ }
183
244
  const result = await Promise.race([
184
245
  destroyWorktree(projectRoot, {
185
246
  taskId,
@@ -426,8 +487,12 @@ export async function composeSpawnForTask(taskId, root, options = {}) {
426
487
  tier: effectiveTier,
427
488
  projectRoot: root,
428
489
  sessionId: options.sessionId ?? null,
490
+ workerSession: options.workerSession,
491
+ coordinatorSessionId: options.coordinatorSessionId,
429
492
  role: inferredRole,
430
493
  protocol: options.protocol,
494
+ harnessHint: options.harnessHint,
495
+ pipelineStageSource: await getTaskPipelineStageSource(task, accessor),
431
496
  skipAtomicityCheck: options.skipAtomicityCheck ?? false,
432
497
  worktreePath: options.worktreePath,
433
498
  worktreeBranch: options.worktreeBranch,
@@ -502,6 +567,8 @@ function codedError(error) {
502
567
  * (`git merge --no-ff` per ADR-062) back into the project default branch
503
568
  * and pruned. The behaviour is idempotent and can be disabled by passing
504
569
  * `autoComplete: false` in {@link OrchestrateSpawnExecuteOpts}.
570
+ * A supplied Orca port selects supervised execution only after local context
571
+ * verification; those launches retain custody and never integrate at spawn.
505
572
  *
506
573
  * @param taskId - Task to spawn.
507
574
  * @param adapterId - Optional adapter id to use. Auto-selects if not provided.
@@ -550,19 +617,34 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
550
617
  /** T14359 — worker record written before spawn (only with `orchestrate.leadWorker.v1`). */
551
618
  let pendingWorker = null;
552
619
  try {
620
+ const custodyBudget = new AbortController();
621
+ const custodyTimer = setTimeout(() => custodyBudget.abort(), SPAWN_BUDGET_MS);
622
+ const external = await raceAgainstAbort(findOrcaWorker(taskId, cwd), custodyBudget.signal, 'validate-readiness').finally(() => clearTimeout(custodyTimer));
623
+ if (external)
624
+ return orcaCustodyRefusal(external);
625
+ // A lead's own restricted launch remains native; its worker dispatches use this port.
626
+ const orca = opts.lead === undefined ? await opts.orca?.discover(cwd) : null;
627
+ if (orca && opts.accountId !== undefined) {
628
+ // @sync-invariant none:input-shape unsupported account placement cannot silently become the host's active account
629
+ return engineError('E_ORCA_ACCOUNT_UNSUPPORTED', 'Exact per-worker account placement is unavailable.', {
630
+ exitCode: 63,
631
+ fix: 'Omit the account constraint to use Orca’s active account for an agent in orchestrate.orca.agents.',
632
+ });
633
+ }
553
634
  // Get spawn registry
554
- await initializeDefaultAdapters();
635
+ if (!orca)
636
+ await initializeDefaultAdapters();
555
637
  // Find adapter
556
638
  let adapter;
557
- if (adapterId) {
639
+ if (!orca && adapterId) {
558
640
  adapter = spawnRegistry.get(adapterId);
559
641
  }
560
- else {
642
+ else if (!orca) {
561
643
  // Auto-select first capable adapter
562
644
  const capable = await spawnRegistry.listSpawnCapable();
563
645
  adapter = capable[0];
564
646
  }
565
- if (!adapter) {
647
+ if (!orca && !adapter) {
566
648
  return {
567
649
  success: false,
568
650
  error: {
@@ -575,7 +657,7 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
575
657
  }
576
658
  // Verify provider supports subagents using providerSupportsById
577
659
  const { providerSupportsById } = await import('@cleocode/caamp');
578
- if (!providerSupportsById(adapter.providerId, 'spawn.supportsSubagents')) {
660
+ if (adapter && !providerSupportsById(adapter.providerId, 'spawn.supportsSubagents')) {
579
661
  return {
580
662
  success: false,
581
663
  error: {
@@ -594,6 +676,7 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
594
676
  // orchestrateSpawn for the full rationale. T12500 — no fallback: a failed
595
677
  // allocation refuses the spawn with the REAL store error instead of handing
596
678
  // over the orchestrator's (newest active) session.
679
+ const coordinatorSessionId = (await resolveBoundSession(cwd))?.session.id ?? null;
597
680
  const spawnSession = await requireSpawnSession(cwd, taskId);
598
681
  if (!spawnSession.ok) {
599
682
  return {
@@ -614,10 +697,17 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
614
697
  execClaim = spawnSession;
615
698
  const activeSessionId = spawnSession.identity.sessionId;
616
699
  const spawnAgentId = spawnSession.identity.agentId;
617
- const payload = await composeSpawnForTask(taskId, cwd, {
700
+ const workerSession = {
701
+ ...spawnSession.identity,
702
+ role: opts.lead ? 'lead' : 'worker',
703
+ };
704
+ let payload = await composeSpawnForTask(taskId, cwd, {
618
705
  tier,
619
706
  sessionId: activeSessionId,
707
+ workerSession,
708
+ coordinatorSessionId,
620
709
  protocol: protocolType,
710
+ ...(orca ? { harnessHint: 'generic' } : {}),
621
711
  ...(opts.leadMailbox ? { leadMailbox: opts.leadMailbox } : {}),
622
712
  // T14363 — a lead is told it is one: the ct-lead excerpt and dispatch rules load.
623
713
  ...(opts.lead !== undefined ? { role: 'lead' } : {}),
@@ -643,8 +733,10 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
643
733
  // Build CLEO spawn context from core spawn payload
644
734
  const { getSpawnCapableProviders } = await import('@cleocode/caamp');
645
735
  const providers = getSpawnCapableProviders();
646
- const provider = providers.find((p) => p.id === adapter.providerId);
647
- if (!provider) {
736
+ const provider = adapter
737
+ ? providers.find((p) => p.id === adapter.providerId)
738
+ : undefined;
739
+ if (adapter && !provider) {
648
740
  return {
649
741
  success: false,
650
742
  error: {
@@ -676,13 +768,6 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
676
768
  // body was substituted (T1238), it is prepended to the composer prompt
677
769
  // so subagents receive the fully-resolved template alongside the
678
770
  // standard spawn context.
679
- const composedPrompt = templateSubstitution.resolvedBody
680
- ? `${templateSubstitution.resolvedBody}\n\n${payload.prompt}`
681
- : payload.prompt;
682
- // T14363 — a lead's mode-specific instructions (how it asks the owner).
683
- const rawPrompt = opts.lead?.promptAppendix
684
- ? `${composedPrompt}\n\n${opts.lead.promptAppendix}`
685
- : composedPrompt;
686
771
  // T1759 — Worktree provisioning + centralized isolation.
687
772
  //
688
773
  // Provision a worktree for the task so the agent runs in its own isolated
@@ -692,7 +777,11 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
692
777
  // `orchestrate.leadWorker.v1` on (or a `--base` asked for) the spawn is
693
778
  // refused; otherwise it falls back to the project root without isolation.
694
779
  let agentWorkingDirectory = cwd;
695
- let agentEnvOverride;
780
+ let agentEnvOverride = {
781
+ CLEO_SESSION_ID: activeSessionId,
782
+ CLEO_AGENT_ID: spawnAgentId,
783
+ CLEO_AGENT_ROLE: opts.lead ? 'lead' : 'worker',
784
+ };
696
785
  const leadWorkerV1 = await isLeadWorkerV1Enabled(cwd);
697
786
  const provisionWorktree = async () => {
698
787
  const worktreeResult = await spawnWorktree(cwd, {
@@ -720,7 +809,7 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
720
809
  const isolationResolution = opts.lead !== undefined
721
810
  ? { kind: 'lead' }
722
811
  : await resolveIsolation(provisionWorktree, {
723
- failClosed: leadWorkerV1 || opts.baseRef !== undefined,
812
+ failClosed: Boolean(orca) || leadWorkerV1 || opts.baseRef !== undefined,
724
813
  });
725
814
  if (isolationResolution.kind === 'isolated') {
726
815
  const { worktreeResult, isolation } = isolationResolution.result;
@@ -732,6 +821,16 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
732
821
  token: worktreeResult.lock.record.token,
733
822
  };
734
823
  }
824
+ payload = await composeSpawnForTask(taskId, cwd, {
825
+ tier,
826
+ workerSession,
827
+ coordinatorSessionId,
828
+ protocol: protocolType,
829
+ ...(orca ? { harnessHint: 'generic' } : {}),
830
+ worktreePath: worktreeResult.path,
831
+ worktreeBranch: worktreeResult.branch,
832
+ ...(opts.leadMailbox ? { leadMailbox: opts.leadMailbox } : {}),
833
+ });
735
834
  }
736
835
  else if (isolationResolution.kind === 'refused') {
737
836
  const wtErr = isolationResolution.error;
@@ -753,11 +852,9 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
753
852
  ? refusalCode
754
853
  : 'E_WORKTREE_PROVISION_FAILED';
755
854
  const message = wtErr instanceof Error ? wtErr.message : String(wtErr);
756
- // T14396: like orchestrateSpawn, remove a worktree THIS call freshly
757
- // created before refusing; any other failure leaves the worktree alone.
758
- const cleanup = shouldCleanUpFailedProvision(wtErr)
759
- ? await runTimeoutCleanup(cwd, taskId)
760
- : undefined;
855
+ // T14396: like orchestrateSpawn, report the removal of a worktree THIS
856
+ // call freshly created; any other failure left the worktree alone.
857
+ const cleanup = failedProvisionCleanup(wtErr);
761
858
  const cleanupDetails = cleanup ? { cleanup } : {};
762
859
  // T14046: a bad --base ref or a worktree on another base. Running the
763
860
  // agent in the project root would ignore the base it was asked for.
@@ -768,6 +865,14 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
768
865
  fix: `Check that '${opts.baseRef}' resolves to a commit and that no worktree or branch for ${taskId} exists on another base.`,
769
866
  });
770
867
  }
868
+ if (orca) {
869
+ // @sync-invariant none:local-only a verified Orca context requires canonical isolation even with leadWorker.v1 off
870
+ return engineError(code, message, {
871
+ exitCode: 63,
872
+ details: { taskId, isolation: 'refused', ...cleanupDetails },
873
+ fix: `Repair canonical worktree provisioning for ${taskId}; the Orca backend requires its exact task checkout and lock.`,
874
+ });
875
+ }
771
876
  // T14358: orchestrate.leadWorker.v1 is on — no agent runs in the project root.
772
877
  // @sync-invariant none:local-only fail-closed isolation refuses; the finally hands the claim back
773
878
  return engineError(code, message, {
@@ -784,24 +889,133 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
784
889
  // Worktree provisioning failure — spawn continues without isolation.
785
890
  getLogger('engine:orchestrate').warn({ taskId }, 'T1759 worktree provisioning failed in orchestrateSpawnExecute — spawning without isolation');
786
891
  }
787
- else {
788
- // T14363 — the lead runs under its OWN allocated CLEO session, never the
789
- // caller's: verbs it runs through the runner (`review verdict`,
790
- // `merge train`) act as the lead.
791
- agentEnvOverride = {
792
- CLEO_SESSION_ID: activeSessionId,
793
- CLEO_AGENT_ROLE: 'lead',
794
- ...(spawnAgentId ? { CLEO_AGENT_ID: spawnAgentId } : {}),
795
- };
892
+ if (!payload.atomicity.allowed)
893
+ return atomicityRefusal(taskId, payload);
894
+ const composedPrompt = templateSubstitution.resolvedBody
895
+ ? `${templateSubstitution.resolvedBody}\n\n${payload.prompt}`
896
+ : payload.prompt;
897
+ // A lead's mode-specific instructions follow the final bound prompt.
898
+ const rawPrompt = opts.lead?.promptAppendix
899
+ ? `${composedPrompt}\n\n${opts.lead.promptAppendix}`
900
+ : composedPrompt;
901
+ if (orca && opts.orca) {
902
+ const identity = readDeclaredProjectIdentity(cwd);
903
+ if (!identity || !execLock || isolationResolution.kind !== 'isolated') {
904
+ // @sync-invariant none:local-only Orca never creates another checkout or launches without canonical custody
905
+ return engineError('E_ORCA_WORKSPACE', 'The canonical CLEO project, worktree or lock is unproven.', {
906
+ exitCode: 63,
907
+ fix: 'Repair the declared CLEO project identity and canonical task worktree before retrying this dispatch.',
908
+ });
909
+ }
910
+ try {
911
+ const { launchRoutedOrcaWorker } = await import('./orca-routing.js');
912
+ const record = await launchRoutedOrcaWorker({
913
+ projectId: identity.projectId,
914
+ projectRoot: cwd,
915
+ taskId,
916
+ workerSessionId: activeSessionId,
917
+ agentId: spawnAgentId,
918
+ role: 'worker',
919
+ protocol: protocolType ?? payload.meta.protocol,
920
+ worktreePath: agentWorkingDirectory,
921
+ worktreeBranch: isolationResolution.result.worktreeResult.branch,
922
+ projectHash: execLock.projectHash,
923
+ lockToken: execLock.token,
924
+ prompt: rawPrompt,
925
+ leadMailbox: (await resolveLeadMailbox(cwd, opts.leadMailbox)) ?? null,
926
+ }, orca, opts.orca, adapterId);
927
+ const execution = record.execution;
928
+ // @sync-invariant none:local-only admission requires the persisted external binding
929
+ if (!execution)
930
+ throw new Error('The Orca worker has no durable execution binding.');
931
+ if (!['ready', 'turn_unobserved'].includes(execution.state)) {
932
+ // @sync-invariant none:local-only uncertain launch receipts retain their exact worker record and task claim
933
+ return engineError('E_ORCA_ATTEMPT_FENCED', `Orca launch remains ${execution.state}.`, {
934
+ exitCode: 63,
935
+ details: {
936
+ recordId: record.recordId,
937
+ state: execution.state,
938
+ dispatchId: execution.dispatchId,
939
+ },
940
+ fix: `Inspect cleo orchestrate worker show ${record.recordId}; recover its original issued request before dispatching another editor.`,
941
+ });
942
+ }
943
+ return {
944
+ success: true,
945
+ data: {
946
+ backend: 'orca',
947
+ instanceId: record.instanceId,
948
+ recordId: record.recordId,
949
+ status: execution.state === 'ready' ? 'running' : 'pending',
950
+ providerId: record.provider,
951
+ taskId,
952
+ agentId: spawnAgentId,
953
+ persona: payload.agentId,
954
+ role: payload.role,
955
+ tier: tier ?? null,
956
+ atomicity: payload.atomicity,
957
+ execution: {
958
+ runtimeId: execution.context.runtimeId,
959
+ runId: execution.runId,
960
+ orcaTaskId: execution.orcaTaskId,
961
+ dispatchId: execution.dispatchId,
962
+ workspaceId: execution.workspaceId,
963
+ state: execution.state,
964
+ },
965
+ meta: {
966
+ ...payload.meta,
967
+ autoComplete: { ran: false, reason: 'Orca launch is not worker completion' },
968
+ },
969
+ },
970
+ };
971
+ }
972
+ catch (error) {
973
+ const retained = await findOrcaWorker(taskId, cwd);
974
+ if (retained) {
975
+ // @sync-invariant none:local-only every post-launch refusal must retain exact recovery addressing
976
+ return engineError('E_ORCA_ATTEMPT_FENCED', error instanceof Error ? error.message : String(error), {
977
+ exitCode: 63,
978
+ details: {
979
+ recordId: retained.recordId,
980
+ state: retained.execution?.state,
981
+ dispatchId: retained.execution?.dispatchId,
982
+ },
983
+ fix: `Inspect cleo orchestrate worker show ${retained.recordId}; preserve its claim and worktree while reconciling the original Run.`,
984
+ });
985
+ }
986
+ if (error instanceof CleoError) {
987
+ // @sync-invariant none:local-only routing refusals preserve the repair instruction and release only proven unsent custody
988
+ return engineError(error.toLAFSError().code, error.message, {
989
+ exitCode: error.code,
990
+ fix: error.fix,
991
+ details: error.details,
992
+ });
993
+ }
994
+ throw error;
995
+ }
996
+ finally {
997
+ // A failure after persistence cannot release custody, even if receipt storage threw.
998
+ dispatched = true;
999
+ keepExecLock = true;
1000
+ const retained = await findOrcaWorker(taskId, cwd);
1001
+ dispatched = retained !== null;
1002
+ keepExecLock = dispatched;
1003
+ }
796
1004
  }
1005
+ // @sync-invariant none:local-only native execution requires its previously selected provider and adapter
1006
+ if (!adapter || !provider)
1007
+ throw new Error('The native spawn adapter is unavailable.');
797
1008
  const cleoSpawnContext = {
798
1009
  taskId: payload.taskId,
799
1010
  protocol: protocolType || payload.meta.protocol,
1011
+ protocolResolution: payload.meta.protocolResolution,
1012
+ workerSession,
1013
+ coordinatorSessionId,
800
1014
  prompt: rawPrompt,
801
1015
  provider: provider.id,
802
1016
  options: {
803
1017
  prompt: rawPrompt,
804
- ...(agentEnvOverride !== undefined ? { env: agentEnvOverride } : {}),
1018
+ env: agentEnvOverride,
805
1019
  },
806
1020
  workingDirectory: agentWorkingDirectory,
807
1021
  tokenResolution: {
@@ -1050,6 +1264,12 @@ export async function orchestrateSpawnExecute(taskId, adapterId, protocolType, p
1050
1264
  // T14359 — the spawn threw, so the pre-spawn record's worker never ran.
1051
1265
  if (pendingWorker)
1052
1266
  await abandonWorkerRecord(pendingWorker, cwd).catch(() => undefined);
1267
+ // T14490 — a thrown CleoError keeps its own code name, exit code and fix.
1268
+ // The custody read opens the store before adapter preflight, so a store
1269
+ // refusal (E_STORE_RESTORING, E_WORKTREE_BUILD_SCHEMA) reaches this catch:
1270
+ // it must not collapse to E_SPAWN_FAILED with its fix dropped.
1271
+ if (error instanceof CleoError)
1272
+ return cleoErrorToEngineResult(error);
1053
1273
  // T14363 — keep a coded refusal's own code (e.g. E_LEAD_TOOLS_UNSTRIPPED).
1054
1274
  const coded = codedError(error);
1055
1275
  // @sync-invariant none:local-only the spawn threw before an agent ran; the finally hands the claim back
@@ -1206,10 +1426,29 @@ includeDeps) {
1206
1426
  // skip otherwise so we don't churn against absent state. destroyWorktree
1207
1427
  // is idempotent (returns worktreeRemoved=true when the path is already
1208
1428
  // gone) so repeated invocations are safe.
1429
+ // T14483: `spawnLock` may no longer be ours. A session abandonment or a
1430
+ // lock reclaim may have handed the task to a newer spawn while this one
1431
+ // was stuck, so only the exact worktree, branch and lock token this spawn
1432
+ // created are removed, checked under the lock (disposeOwnedWorktree).
1209
1433
  let cleanup;
1210
1434
  if (partialState.worktreePath && partialState.rootResolved) {
1211
1435
  try {
1212
- cleanup = await runTimeoutCleanup(partialState.rootResolved, taskId);
1436
+ cleanup =
1437
+ spawnLock && partialState.worktreeBranch
1438
+ ? await runTimeoutCleanup(partialState.rootResolved, taskId, {
1439
+ worktreePath: partialState.worktreePath,
1440
+ branch: partialState.worktreeBranch,
1441
+ projectHash: spawnLock.projectHash,
1442
+ lockToken: spawnLock.token,
1443
+ })
1444
+ : {
1445
+ attempted: false,
1446
+ worktreeRemoved: false,
1447
+ branchDeleted: false,
1448
+ notOwned: true,
1449
+ error: 'Cleanup skipped: this spawn holds no task lock token or branch; nothing was removed',
1450
+ elapsedMs: 0,
1451
+ };
1213
1452
  spawnLogger.info({ taskId, cleanup }, 'T9545 auto-cleanup completed after spawn timeout');
1214
1453
  }
1215
1454
  catch (cleanupErr) {
@@ -1233,13 +1472,18 @@ includeDeps) {
1233
1472
  partial,
1234
1473
  ...(cleanup ? { cleanup } : {}),
1235
1474
  },
1236
- fix: cleanup && !cleanup.worktreeRemoved
1237
- ? 'Auto-cleanup did not remove the worktree — run `cleo worktree prune --taskId <id>` to force-remove the orphan, then retry the spawn.'
1238
- : 'Auto-cleanup removed the partial worktree — safe to retry the spawn directly.',
1475
+ fix: cleanup?.notOwned
1476
+ ? `Nothing was removed: the worktree for ${taskId} may belong to a newer spawn. Check \`cleo worktree list\` before retrying.`
1477
+ : cleanup && !cleanup.worktreeRemoved
1478
+ ? 'Auto-cleanup did not remove the worktree — run `cleo worktree prune --taskId <id>` to force-remove the orphan, then retry the spawn.'
1479
+ : 'Auto-cleanup removed the partial worktree — safe to retry the spawn directly.',
1239
1480
  });
1240
1481
  };
1241
1482
  try {
1242
1483
  const root = getProjectRoot(projectRoot);
1484
+ const external = await raceAgainstAbort(findOrcaWorker(taskId, root), budgetCtrl.signal, 'validate-readiness');
1485
+ if (external)
1486
+ return orcaCustodyRefusal(external);
1243
1487
  partialState.rootResolved = root;
1244
1488
  spawnLogger.info({ taskId, tier, noWorktree, budgetMs: SPAWN_BUDGET_MS }, 'T9545 spawn pipeline started');
1245
1489
  // Step 1: Validate readiness.
@@ -1339,6 +1583,7 @@ includeDeps) {
1339
1583
  }
1340
1584
  spawnLease = leased.lease;
1341
1585
  spawnLeaseReused = leased.reused;
1586
+ const coordinatorSessionId = (await resolveBoundSession(root))?.session.id ?? null;
1342
1587
  const spawnSession = await requireSpawnSession(root, taskId);
1343
1588
  if (!spawnSession.ok) {
1344
1589
  spawnLogger.error({ taskId, cause: spawnSession.cause }, 'spawn session allocation failed');
@@ -1514,13 +1759,13 @@ includeDeps) {
1514
1759
  const wtErr = isolationResolution.error;
1515
1760
  const message = wtErr instanceof Error ? wtErr.message : String(wtErr);
1516
1761
  getLogger('engine:orchestrate').error({ taskId, err: wtErr }, `T1878 worktree provisioning failed for ${taskId}: ${message}`);
1517
- // T12506 — cleanup runs ONLY for a worktree THIS invocation freshly
1518
- // created (createWorktree flags it). Every other failure — a lock
1519
- // refusal, a lock I/O error, a dirty branch, an invalid path, a
1520
- // failure while re-attaching — left a pre-existing, possibly live
1521
- // worktree behind, and destroyWorktree(force, deleteBranch) would
1522
- // delete its holder's work.
1523
- if (!shouldCleanUpFailedProvision(wtErr)) {
1762
+ // T12506 — only a worktree THIS invocation freshly created is removed,
1763
+ // by createWorktree itself under the task lock (T14407). Every other
1764
+ // failure — a lock refusal, a lock I/O error, a dirty branch, an
1765
+ // invalid path, a failure while re-attaching — left a pre-existing,
1766
+ // possibly live worktree behind that holds its holder's work.
1767
+ const cleanup = failedProvisionCleanup(wtErr);
1768
+ if (cleanup === undefined) {
1524
1769
  const refusalCode = wtErr?.code;
1525
1770
  const code = typeof refusalCode === 'string' && refusalCode.startsWith('E_')
1526
1771
  ? refusalCode
@@ -1539,22 +1784,10 @@ includeDeps) {
1539
1784
  : `Inspect the existing worktree/branch for ${taskId} (\`git worktree list\`, \`git branch --list task/${taskId}\`); nothing was removed.`,
1540
1785
  });
1541
1786
  }
1542
- // T10078 — best-effort cleanup of any partially-provisioned worktree.
1543
- // If createWorktree partially succeeded (e.g. git worktree add ran but
1544
- // a later step failed), an orphan worktree + task branch would remain.
1545
- // destroyWorktree is idempotent — it safely no-ops when nothing exists.
1546
- let cleanupNote;
1547
- try {
1548
- const cleanupResult = await runTimeoutCleanup(root, taskId);
1549
- cleanupNote = cleanupResult.worktreeRemoved
1550
- ? 'Orphan worktree cleaned up'
1551
- : cleanupResult.error
1552
- ? `Cleanup attempted but may be incomplete: ${cleanupResult.error}`
1553
- : 'No orphan worktree found';
1554
- }
1555
- catch {
1556
- cleanupNote = 'Cleanup attempt failed';
1557
- }
1787
+ // T10078 — an orphan worktree + task branch would otherwise remain.
1788
+ const cleanupNote = cleanup.worktreeRemoved
1789
+ ? 'Orphan worktree cleaned up'
1790
+ : `Cleanup attempted but may be incomplete: ${cleanup.error ?? 'worktree kept'}`;
1558
1791
  return engineError('E_WORKTREE_PROVISION_FAILED', message, {
1559
1792
  details: { taskId, cause: message, cleanup: cleanupNote },
1560
1793
  fix: 'Check git repository state, branch availability, and disk space. Run `git worktree list` and `git branch --list task/<taskId>` to diagnose.',
@@ -1576,6 +1809,8 @@ includeDeps) {
1576
1809
  const payload = await raceAgainstAbort(composeSpawnForTask(taskId, root, {
1577
1810
  tier,
1578
1811
  sessionId: activeSessionId,
1812
+ workerSession: spawnSession.identity,
1813
+ coordinatorSessionId,
1579
1814
  protocol: protocolType,
1580
1815
  worktreePath,
1581
1816
  worktreeBranch,
@@ -1650,6 +1885,8 @@ includeDeps) {
1650
1885
  harnessHint: payload.harnessHint,
1651
1886
  atomicity: payload.atomicity,
1652
1887
  meta: payload.meta,
1888
+ workerSession: spawnSession.identity,
1889
+ coordinatorSessionId,
1653
1890
  // T1118 L1+L2 / T1140 — worktree binding for harness adapters.
1654
1891
  worktree: worktreeAdapterResult?.worktree ?? null,
1655
1892
  worktreeEnv: worktreeAdapterResult?.envVars ?? null,
@@ -1662,6 +1899,9 @@ includeDeps) {
1662
1899
  protocolType: protocolType || payload.meta.protocol,
1663
1900
  tier: payload.tier,
1664
1901
  prompt: finalPrompt,
1902
+ workerSession: spawnSession.identity,
1903
+ coordinatorSessionId,
1904
+ protocolResolution: payload.meta.protocolResolution,
1665
1905
  },
1666
1906
  protocolType: protocolType || payload.meta.protocol,
1667
1907
  sessionId: activeSessionId,
@@ -1669,6 +1909,12 @@ includeDeps) {
1669
1909
  };
1670
1910
  }
1671
1911
  catch (err) {
1912
+ // T14490 — a thrown CleoError keeps its own code name, exit code and fix.
1913
+ // The custody read opens the store before any pipeline step, so a store
1914
+ // refusal (E_STORE_RESTORING, E_WORKTREE_BUILD_SCHEMA) reaches this catch:
1915
+ // it must not surface as a bare numeric code with its fix dropped.
1916
+ if (err instanceof CleoError)
1917
+ return cleoErrorToEngineResult(err);
1672
1918
  const code = err.code ?? 'E_GENERAL';
1673
1919
  // T9545 — when our budget supervisor aborts a step, the helper throws
1674
1920
  // an Error with `code === 'E_TIMEOUT'`. Surface a structured envelope