@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
@@ -26,15 +26,21 @@
26
26
  * SubagentStop, so it fires exactly once whichever path wins.
27
27
  *
28
28
  * @module orchestrate/worker-records
29
+ * @packageDocumentation
29
30
  * @task T14359
30
31
  */
32
+ import { createHash } from 'node:crypto';
33
+ import { isAbsolute } from 'node:path';
34
+ import { orcaAttemptSchema, orcaReportDeliverySchema, orcaWorkerReportSchema, orcaWorkerSettlementSchema, } from '@cleocode/contracts/orca-execution.js';
31
35
  import { and, eq, isNull } from 'drizzle-orm';
32
36
  import { generateAgentId } from '../agents/registry.js';
33
37
  import { hooks } from '../hooks/registry.js';
34
38
  import { getLogger } from '../logger.js';
35
39
  import { getTaskAccessor } from '../store/data-accessor.js';
36
40
  import { tasksAgentInstances } from '../store/schema/cleo-project/runtime.js';
41
+ import { tasksTasks } from '../store/schema/cleo-project/tasks-core.js';
37
42
  import { getDb } from '../store/sqlite.js';
43
+ import { claimFromColumns, isLiveClaim } from '../store/task-claim.js';
38
44
  /**
39
45
  * A fresh adapter instance id, assigned before spawn so the record and the
40
46
  * worker's exit hook share it. Only `[A-Za-z0-9-]`, so it is safe in a shell
@@ -49,15 +55,25 @@ export function newWorkerInstanceId(providerId) {
49
55
  }
50
56
  /** Parse a worker row's metadata; null for any non-worker agent instance. */
51
57
  function parseWorkerMetadata(row) {
58
+ let meta;
52
59
  try {
53
- const meta = JSON.parse(row.metadataJson ?? '{}');
54
- return meta.kind === 'worker' && typeof meta.instanceId === 'string'
55
- ? meta
56
- : null;
60
+ meta = JSON.parse(row.metadataJson ?? '{}');
57
61
  }
58
62
  catch {
59
63
  return null;
60
64
  }
65
+ if (meta === null ||
66
+ typeof meta !== 'object' ||
67
+ meta.kind !== 'worker' ||
68
+ typeof meta.instanceId !== 'string')
69
+ return null;
70
+ // Invalid external custody must fail a read, never disappear from the census.
71
+ if (meta.execution !== undefined)
72
+ meta.execution = orcaAttemptSchema.parse(meta.execution);
73
+ if (meta.report !== undefined)
74
+ meta.report = orcaWorkerReportSchema.parse(meta.report);
75
+ Object.assign(meta, orcaWorkerSettlementSchema.parse(meta));
76
+ return meta;
61
77
  }
62
78
  /** Project an agent instance row onto a {@link WorkerRecord}. */
63
79
  function toWorkerRecord(row, meta) {
@@ -74,6 +90,9 @@ function toWorkerRecord(row, meta) {
74
90
  sessionId: row.sessionId,
75
91
  startedAt: row.startedAt,
76
92
  stoppedAt: row.stoppedAt,
93
+ ...(meta.execution ? { execution: meta.execution } : {}),
94
+ ...(meta.report ? { report: meta.report } : {}),
95
+ ...orcaWorkerSettlementSchema.parse(meta),
77
96
  };
78
97
  }
79
98
  /**
@@ -81,9 +100,10 @@ function toWorkerRecord(row, meta) {
81
100
  *
82
101
  * @param worker - The worker to record.
83
102
  * @param cwd - Project root.
103
+ * @param predecessor - Exact resource-free Orca attempt atomically replaced by its retry.
84
104
  * @returns The stored record.
85
105
  */
86
- export async function recordWorker(worker, cwd) {
106
+ export async function recordWorker(worker, cwd, predecessor) {
87
107
  const metadata = {
88
108
  kind: 'worker',
89
109
  instanceId: worker.instanceId,
@@ -93,7 +113,61 @@ export async function recordWorker(worker, cwd) {
93
113
  pgid: worker.pgid,
94
114
  worktree: worker.worktree,
95
115
  leadMailbox: worker.leadMailbox,
116
+ ...(worker.execution ? { execution: orcaAttemptSchema.parse(worker.execution) } : {}),
96
117
  };
118
+ if (metadata.execution &&
119
+ (metadata.execution.launch.taskId !== worker.taskId ||
120
+ metadata.execution.launch.instanceId !== worker.instanceId ||
121
+ metadata.execution.launch.agentId !== worker.agentId ||
122
+ metadata.execution.launch.workerSessionId !== worker.sessionId ||
123
+ metadata.execution.launch.harness !== worker.provider ||
124
+ metadata.execution.launch.worktreePath !== worker.worktree ||
125
+ worker.pid !== null ||
126
+ worker.pgid !== null)) {
127
+ // @sync-invariant none:local-only external resource custody cannot acquire native PID ownership or another worker identity
128
+ throw new Error('Orca attempt does not match its worker record.');
129
+ }
130
+ if (predecessor) {
131
+ const previous = predecessor.execution;
132
+ const next = metadata.execution;
133
+ if (!previous ||
134
+ !next ||
135
+ predecessor.taskId !== worker.taskId ||
136
+ !previous.dispatchId ||
137
+ !previous.runId ||
138
+ !previous.orcaTaskId ||
139
+ !['failed', 'stopped'].includes(previous.state) ||
140
+ previous.resourceState !== 'stopped' ||
141
+ previous.failureCount >= 3 ||
142
+ next.failureCount !== previous.failureCount ||
143
+ next.state !== 'launching' ||
144
+ next.dispatchId !== null ||
145
+ !next.startRequestKey ||
146
+ next.startRequestKey === previous.startRequestKey ||
147
+ next.startRequestKey === previous.startRequestId ||
148
+ next.startRequestId !== null ||
149
+ next.stopRequestKey !== undefined ||
150
+ next.stopRequestId !== null ||
151
+ next.retryOf !== previous.dispatchId ||
152
+ next.runId !== previous.runId ||
153
+ next.orcaTaskId !== previous.orcaTaskId ||
154
+ next.launch.instanceId === previous.launch.instanceId ||
155
+ next.promptDigest !== previous.promptDigest ||
156
+ next.workspaceId !== previous.workspaceId ||
157
+ next.workspaceSelector !== previous.workspaceSelector ||
158
+ JSON.stringify(next.context) !== JSON.stringify(previous.context) ||
159
+ JSON.stringify({ ...next.launch, instanceId: previous.launch.instanceId }) !==
160
+ JSON.stringify(previous.launch) ||
161
+ JSON.stringify(next.startBinding) !==
162
+ JSON.stringify({
163
+ runId: previous.runId,
164
+ orcaTaskId: previous.orcaTaskId,
165
+ retryOf: previous.dispatchId,
166
+ })) {
167
+ // @sync-invariant none:local-only replacement custody requires a resource-free exact predecessor and the same Task retry chain
168
+ throw new Error('Orca retry cannot replace unresolved custody or change its assignment.');
169
+ }
170
+ }
97
171
  const now = new Date().toISOString();
98
172
  const row = {
99
173
  id: generateAgentId(),
@@ -112,16 +186,410 @@ export async function recordWorker(worker, cwd) {
112
186
  parentAgentId: null,
113
187
  };
114
188
  const db = await getDb(cwd);
115
- await db.insert(tasksAgentInstances).values(row).run();
189
+ db.transaction((tx) => {
190
+ const open = tx
191
+ .select()
192
+ .from(tasksAgentInstances)
193
+ .where(eq(tasksAgentInstances.taskId, worker.taskId))
194
+ .all()
195
+ .filter((existing) => {
196
+ const meta = parseWorkerMetadata(existing);
197
+ return (existing.stoppedAt === null ||
198
+ (meta !== null && isCurrentOrcaWorker(toWorkerRecord(existing, meta))));
199
+ });
200
+ if (predecessor) {
201
+ const previous = open.find((existing) => existing.id === predecessor.recordId);
202
+ if (open.length !== 1 ||
203
+ !previous ||
204
+ JSON.stringify(parseWorkerMetadata(previous)?.execution) !==
205
+ JSON.stringify(predecessor.execution)) {
206
+ // @sync-invariant none:local-only a concurrent retry or observation invalidates this replacement reservation
207
+ throw new Error('Orca predecessor changed; reload its exact worker record before retry.');
208
+ }
209
+ const retired = tx
210
+ .update(tasksAgentInstances)
211
+ .set({
212
+ status: 'stopped',
213
+ stoppedAt: previous.stoppedAt ?? now,
214
+ metadataJson: JSON.stringify({ ...parseWorkerMetadata(previous), retiredAt: now }),
215
+ })
216
+ .where(and(eq(tasksAgentInstances.id, predecessor.recordId), eq(tasksAgentInstances.metadataJson, previous.metadataJson ?? '{}'), previous.stoppedAt === null
217
+ ? isNull(tasksAgentInstances.stoppedAt)
218
+ : eq(tasksAgentInstances.stoppedAt, previous.stoppedAt)))
219
+ .run();
220
+ if (Number(retired.changes) !== 1) {
221
+ // @sync-invariant none:local-only only one successor may acquire this exact predecessor's custody
222
+ throw new Error('Orca retry reservation lost; no new launch is authorized.');
223
+ }
224
+ }
225
+ else if (open.some((existing) => worker.execution || parseWorkerMetadata(existing)?.execution)) {
226
+ // @sync-invariant none:local-only duplicate local execution custody cannot start another editor
227
+ throw new Error(`Execution custody already exists for ${worker.taskId}; inspect its worker record before recovery.`);
228
+ }
229
+ tx.insert(tasksAgentInstances).values(row).run();
230
+ });
116
231
  return toWorkerRecord(row, metadata);
117
232
  }
233
+ /**
234
+ * Compare-and-set external custody on an existing worker row. Concurrent CLI
235
+ * calls cannot both reserve a stop or replay, or overwrite a newer receipt.
236
+ * @remarks Preserves assignment identity and monotonic circuit-breaker history.
237
+ * @param record - Last read worker record and expected CAS revision.
238
+ * @param execution - New observation or operation reservation for the same attempt.
239
+ * @param cwd - Owning CLEO project root.
240
+ * @returns The updated record with its next local CAS revision.
241
+ * @example
242
+ * ```ts
243
+ * const reserved = await updateWorkerExecution(record, pendingStop, projectRoot);
244
+ * ```
245
+ */
246
+ export async function updateWorkerExecution(record, execution, cwd) {
247
+ const expected = record.execution;
248
+ const next = orcaAttemptSchema.parse({ ...execution, revision: (expected?.revision ?? 0) + 1 });
249
+ if (!expected ||
250
+ JSON.stringify(expected.launch) !== JSON.stringify(next.launch) ||
251
+ JSON.stringify(expected.context) !== JSON.stringify(next.context) ||
252
+ expected.promptDigest !== next.promptDigest ||
253
+ expected.workspaceId !== next.workspaceId ||
254
+ expected.workspaceSelector !== next.workspaceSelector ||
255
+ next.failureCount < expected.failureCount ||
256
+ expected.retryOf !== next.retryOf ||
257
+ (expected.startRefusal !== undefined && expected.startRefusal !== next.startRefusal) ||
258
+ JSON.stringify(expected.startBinding) !== JSON.stringify(next.startBinding) ||
259
+ expected.startRequestKey !== next.startRequestKey ||
260
+ (expected.startRequestKey !== undefined &&
261
+ next.startRequestId !== null &&
262
+ next.startRequestId !== expected.startRequestKey) ||
263
+ (expected.startRequestId !== null && next.startRequestId !== expected.startRequestId) ||
264
+ (expected.stopRequestKey !== undefined && next.stopRequestKey !== expected.stopRequestKey) ||
265
+ (expected.stopRequestId !== null && next.stopRequestId !== expected.stopRequestId) ||
266
+ (expected.runId !== null && next.runId !== expected.runId) ||
267
+ (expected.orcaTaskId !== null && next.orcaTaskId !== expected.orcaTaskId) ||
268
+ (expected.dispatchId !== null && next.dispatchId !== expected.dispatchId)) {
269
+ // @sync-invariant none:local-only external attempt identity and breaker history are immutable
270
+ throw new Error('Cannot replace the identity or breaker history of an Orca attempt.');
271
+ }
272
+ const db = await getDb(cwd);
273
+ const row = db
274
+ .select()
275
+ .from(tasksAgentInstances)
276
+ .where(eq(tasksAgentInstances.id, record.recordId))
277
+ .get();
278
+ const meta = row ? parseWorkerMetadata(row) : null;
279
+ if (!row ||
280
+ !meta ||
281
+ !isCurrentOrcaWorker(toWorkerRecord(row, meta)) ||
282
+ JSON.stringify(meta.execution) !== JSON.stringify(expected)) {
283
+ // @sync-invariant none:local-only stale external custody updates cannot overwrite a newer observation
284
+ throw new Error('Worker execution changed; reload the exact record before recovery.');
285
+ }
286
+ const result = db
287
+ .update(tasksAgentInstances)
288
+ .set({ metadataJson: JSON.stringify({ ...meta, execution: next }) })
289
+ .where(and(eq(tasksAgentInstances.id, record.recordId), eq(tasksAgentInstances.metadataJson, row.metadataJson ?? '{}'), row.stoppedAt === null
290
+ ? isNull(tasksAgentInstances.stoppedAt)
291
+ : eq(tasksAgentInstances.stoppedAt, row.stoppedAt)))
292
+ .run();
293
+ if (Number(result.changes) !== 1) {
294
+ // @sync-invariant none:local-only only one caller may reserve an external execution mutation
295
+ throw new Error('Worker execution reservation lost; no new operation is authorized.');
296
+ }
297
+ return toWorkerRecord(row, { ...meta, execution: next });
298
+ }
299
+ /**
300
+ * Persist one validated logical report on its exact worker without releasing custody.
301
+ * @param record - Current worker and expected execution revision.
302
+ * @param report - Original report bytes, transport identity and validated manifest link.
303
+ * @param cwd - Owning project root.
304
+ * @returns The stored record; identical duplicate reports retain the first receipt.
305
+ * @throws When identity, content or a concurrent custody change conflicts.
306
+ * @remarks Uses the existing local-only worker metadata transaction; no acceptance or resource hook is emitted.
307
+ * @example
308
+ * ```ts
309
+ * const settled = await recordWorkerReport(record, validatedReport, projectRoot);
310
+ * ```
311
+ */
312
+ export async function recordWorkerReport(record, report, cwd) {
313
+ const receipt = orcaWorkerReportSchema.parse(report);
314
+ const execution = record.execution;
315
+ if (!execution ||
316
+ receipt.event.runtimeId !== execution.context.runtimeId ||
317
+ receipt.event.runId !== execution.runId ||
318
+ receipt.event.orcaTaskId !== execution.orcaTaskId ||
319
+ receipt.event.dispatchId !== execution.dispatchId ||
320
+ receipt.reportDigest !== createHash('sha256').update(receipt.reportText).digest('hex')) {
321
+ // @sync-invariant none:local-only a report cannot change its exact worker identity or original bytes
322
+ throw new Error('Worker report identity or digest does not match its record.');
323
+ }
324
+ const db = await getDb(cwd);
325
+ return db.transaction((tx) => {
326
+ const row = tx
327
+ .select()
328
+ .from(tasksAgentInstances)
329
+ .where(eq(tasksAgentInstances.id, record.recordId))
330
+ .get();
331
+ const meta = row ? parseWorkerMetadata(row) : null;
332
+ if (!row ||
333
+ !meta ||
334
+ !isCurrentOrcaWorker(toWorkerRecord(row, meta)) ||
335
+ JSON.stringify(meta.execution) !== JSON.stringify(execution)) {
336
+ // @sync-invariant none:local-only retired or concurrently changed custody cannot receive a stale report
337
+ throw new Error('Worker execution changed; reload the exact record before report ingestion.');
338
+ }
339
+ if (meta.report) {
340
+ if (meta.report.reportDigest !== receipt.reportDigest ||
341
+ meta.report.manifestId !== receipt.manifestId ||
342
+ meta.report.manifestDigest !== receipt.manifestDigest) {
343
+ // @sync-invariant none:local-only a second delivery cannot replace the settled logical report
344
+ throw new Error('A different worker report is already settled for this Dispatch.');
345
+ }
346
+ if (meta.reportDelivery)
347
+ return toWorkerRecord(row, meta);
348
+ }
349
+ if (!meta.report) {
350
+ const task = tx.select().from(tasksTasks).where(eq(tasksTasks.id, record.taskId)).get();
351
+ const claim = task ? claimFromColumns(task) : undefined;
352
+ if (!isLiveClaim(claim) ||
353
+ claim?.sessionId !== record.sessionId ||
354
+ claim?.agentId !== record.agentId) {
355
+ // @sync-invariant none:local-only report settlement must still own the exact claim at commit time
356
+ throw new Error('Worker task claim changed before report settlement.');
357
+ }
358
+ }
359
+ const canonical = meta.report ?? receipt;
360
+ const event = canonical.event;
361
+ const metadata = {
362
+ ...meta,
363
+ report: canonical,
364
+ reportDelivery: {
365
+ key: `cleo-orca-report:${createHash('sha256')
366
+ .update(JSON.stringify([event.runtimeId, event.runId, event.dispatchId, event.messageId]))
367
+ .digest('hex')}`,
368
+ mailbox: meta.leadMailbox ?? null,
369
+ state: 'pending',
370
+ messageId: null,
371
+ deliveredAt: null,
372
+ lastError: null,
373
+ },
374
+ };
375
+ const updated = tx
376
+ .update(tasksAgentInstances)
377
+ .set({ metadataJson: JSON.stringify(metadata) })
378
+ .where(and(eq(tasksAgentInstances.id, record.recordId), eq(tasksAgentInstances.metadataJson, row.metadataJson ?? '{}'), row.stoppedAt === null
379
+ ? isNull(tasksAgentInstances.stoppedAt)
380
+ : eq(tasksAgentInstances.stoppedAt, row.stoppedAt)))
381
+ .run();
382
+ if (Number(updated.changes) !== 1) {
383
+ // @sync-invariant none:local-only report settlement has one winner and never changes task or resource state
384
+ throw new Error('Worker report settlement lost; reload the exact record.');
385
+ }
386
+ return toWorkerRecord(row, metadata);
387
+ });
388
+ }
389
+ /**
390
+ * Retire a confirmed `agent_unconfigured` refusal that created no Dispatch.
391
+ * @remarks This releases no task, session or filesystem resource and emits no exit hook.
392
+ * @param record - Exact persisted refusal, after recording its unusable route.
393
+ * @param cwd - Owning project root.
394
+ * @returns The archived pre-dispatch attempt, still readable for audit.
395
+ */
396
+ export async function retireUnconfiguredOrcaWorker(record, cwd) {
397
+ const execution = record.execution;
398
+ if (execution?.startRefusal !== 'agent_unconfigured' ||
399
+ execution.state !== 'failed' ||
400
+ execution.resourceState !== 'stopped' ||
401
+ execution.dispatchId !== null ||
402
+ execution.orcaTaskId !== null ||
403
+ execution.retryOf !== null ||
404
+ execution.failureCount !== 0) {
405
+ // @sync-invariant none:local-only only a confirmed pre-dispatch route refusal can be retired without exit proof
406
+ throw new Error('Cannot retire an unresolved or dispatched Orca attempt.');
407
+ }
408
+ const db = await getDb(cwd);
409
+ const row = db
410
+ .select()
411
+ .from(tasksAgentInstances)
412
+ .where(eq(tasksAgentInstances.id, record.recordId))
413
+ .get();
414
+ const meta = row ? parseWorkerMetadata(row) : null;
415
+ if (!row || !meta || JSON.stringify(meta.execution) !== JSON.stringify(execution)) {
416
+ // @sync-invariant none:local-only stale refusal receipts cannot retire newer custody
417
+ throw new Error('Orca refusal changed; reload its exact record.');
418
+ }
419
+ const stoppedAt = new Date().toISOString();
420
+ const result = db
421
+ .update(tasksAgentInstances)
422
+ .set({ stoppedAt, status: 'stopped' })
423
+ .where(and(eq(tasksAgentInstances.id, record.recordId), eq(tasksAgentInstances.metadataJson, row.metadataJson ?? '{}'), isNull(tasksAgentInstances.stoppedAt)))
424
+ .run();
425
+ if (Number(result.changes) !== 1) {
426
+ // @sync-invariant none:local-only one caller owns retirement of a confirmed refusal
427
+ throw new Error('Orca refusal retirement lost; no replacement is authorized.');
428
+ }
429
+ return { ...record, stoppedAt };
430
+ }
431
+ /**
432
+ * Find external custody that forbids another spawn, including uncertain attempts.
433
+ * @remarks Unreadable ownership for the same task refuses dispatch.
434
+ * @param taskId - CLEO task whose external custody must be checked.
435
+ * @param cwd - Owning CLEO project root.
436
+ * @returns The retained Orca worker, or null when none exists.
437
+ * @example
438
+ * ```ts
439
+ * const retained = await findOrcaWorker('T14455', projectRoot);
440
+ * ```
441
+ */
442
+ export async function findOrcaWorker(taskId, cwd) {
443
+ const db = await getDb(cwd);
444
+ const rows = db
445
+ .select()
446
+ .from(tasksAgentInstances)
447
+ .where(and(eq(tasksAgentInstances.taskId, taskId), eq(tasksAgentInstances.agentType, 'executor')))
448
+ .all();
449
+ for (const row of rows) {
450
+ const meta = parseWorkerMetadata(row);
451
+ if (!meta && row.stoppedAt !== null)
452
+ continue;
453
+ if (!meta) {
454
+ // @sync-invariant none:local-only unreadable custody for the same task cannot authorize another editor
455
+ throw new Error(`Worker ownership unavailable for ${row.id}; inspect it before spawning ${taskId}.`);
456
+ }
457
+ const record = toWorkerRecord(row, meta);
458
+ if (isCurrentOrcaWorker(record))
459
+ return record;
460
+ }
461
+ return null;
462
+ }
463
+ /**
464
+ * Whether an Orca assignment still owns its execution mapping, even after physical exit.
465
+ * @param record - Worker record to inspect.
466
+ * @returns False for explicit retirement and legacy retired predecessors.
467
+ * @remarks Physical exit does not authorize a replacement Run or Task.
468
+ * @example
469
+ * ```ts
470
+ * if (isCurrentOrcaWorker(record)) retainItsExactDispatch(record);
471
+ * ```
472
+ */
473
+ export function isCurrentOrcaWorker(record) {
474
+ return Boolean(record.execution && !record.retiredAt && (record.stoppedAt === null || record.resourceRelease));
475
+ }
476
+ /**
477
+ * Record an AgentMBX send result without changing report, task or resource settlement.
478
+ * @param recordId - Worker holding the durable outbox entry.
479
+ * @param delivery - Result for its immutable logical key and lead mailbox.
480
+ * @param cwd - Owning project root.
481
+ * @returns The current worker; delivery acknowledgements never regress.
482
+ * @remarks A lost acknowledgement is replayed through the same provider idempotency key.
483
+ * @example
484
+ * ```ts
485
+ * await recordWorkerReportDelivery(recordId, acknowledged, projectRoot);
486
+ * ```
487
+ */
488
+ export async function recordWorkerReportDelivery(recordId, delivery, cwd) {
489
+ const next = orcaReportDeliverySchema.parse(delivery);
490
+ const db = await getDb(cwd);
491
+ return db.transaction((tx) => {
492
+ const row = tx
493
+ .select()
494
+ .from(tasksAgentInstances)
495
+ .where(eq(tasksAgentInstances.id, recordId))
496
+ .get();
497
+ const meta = row ? parseWorkerMetadata(row) : null;
498
+ if (!row ||
499
+ !meta?.report ||
500
+ !meta.reportDelivery ||
501
+ meta.reportDelivery.key !== next.key ||
502
+ meta.reportDelivery.mailbox !== next.mailbox ||
503
+ (next.state === 'delivered' && (!next.messageId || !next.deliveredAt))) {
504
+ // @sync-invariant none:local-only only the stored report's exact outbox entry may be acknowledged
505
+ throw new Error('Worker report delivery does not match its durable outbox.');
506
+ }
507
+ if (meta.reportDelivery.state === 'delivered')
508
+ return toWorkerRecord(row, meta);
509
+ const metadata = { ...meta, reportDelivery: next };
510
+ const updated = tx
511
+ .update(tasksAgentInstances)
512
+ .set({ metadataJson: JSON.stringify(metadata) })
513
+ .where(and(eq(tasksAgentInstances.id, recordId), eq(tasksAgentInstances.metadataJson, row.metadataJson ?? '{}')))
514
+ .run();
515
+ if (Number(updated.changes) !== 1) {
516
+ // @sync-invariant none:local-only concurrent transport acknowledgements cannot replace newer settlement
517
+ throw new Error('Worker report delivery changed; retry its stored logical key.');
518
+ }
519
+ return toWorkerRecord(row, metadata);
520
+ });
521
+ }
522
+ /**
523
+ * Close physical Orca resources only after an exact provider observation proves release.
524
+ * @param record - Worker after the adapter's verified worker-show observation.
525
+ * @param cwd - Owning project root.
526
+ * @returns Its physical exit receipt; concurrent observations emit one stop hook.
527
+ * @remarks Keeps report, claim, checkout and retry-chain custody independent of exit.
528
+ * @example
529
+ * ```ts
530
+ * const exited = await settleOrcaWorkerResource(observed, projectRoot);
531
+ * ```
532
+ */
533
+ export async function settleOrcaWorkerResource(record, cwd) {
534
+ const execution = record.execution;
535
+ if (record.resourceRelease || execution?.resourceState !== 'stopped')
536
+ return record;
537
+ const dispatchId = execution.dispatchId;
538
+ const receipt = execution.lastReceipt;
539
+ if (!dispatchId || !receipt || !isCurrentOrcaWorker(record)) {
540
+ // @sync-invariant none:local-only only a current provider-proven exact resource exit can close a worker
541
+ throw new Error('No exact Orca resource release proof is stored.');
542
+ }
543
+ const db = await getDb(cwd);
544
+ const releasedAt = new Date().toISOString();
545
+ const closed = db.transaction((tx) => {
546
+ const row = tx
547
+ .select()
548
+ .from(tasksAgentInstances)
549
+ .where(eq(tasksAgentInstances.id, record.recordId))
550
+ .get();
551
+ const meta = row ? parseWorkerMetadata(row) : null;
552
+ if (!row ||
553
+ !meta ||
554
+ JSON.stringify(meta.execution) !== JSON.stringify(execution) ||
555
+ !isCurrentOrcaWorker(toWorkerRecord(row, meta))) {
556
+ // @sync-invariant none:local-only stale release observations cannot close replacement custody
557
+ throw new Error('Orca resource observation changed; reload the exact worker.');
558
+ }
559
+ if (meta.resourceRelease)
560
+ return null;
561
+ const metadata = {
562
+ ...meta,
563
+ resourceRelease: {
564
+ dispatchId,
565
+ releasedAt,
566
+ receiptDigest: createHash('sha256').update(receipt).digest('hex'),
567
+ receipt,
568
+ },
569
+ };
570
+ const updated = tx
571
+ .update(tasksAgentInstances)
572
+ .set({ status: 'stopped', stoppedAt: releasedAt, metadataJson: JSON.stringify(metadata) })
573
+ .where(and(eq(tasksAgentInstances.id, row.id), eq(tasksAgentInstances.metadataJson, row.metadataJson ?? '{}'), isNull(tasksAgentInstances.stoppedAt)))
574
+ .run();
575
+ if (Number(updated.changes) !== 1)
576
+ return null;
577
+ return toWorkerRecord({ ...row, stoppedAt: releasedAt }, metadata);
578
+ });
579
+ if (!closed)
580
+ return ((await listWorkerRecords(cwd, true)).find((worker) => worker.recordId === record.recordId) ??
581
+ record);
582
+ await dispatchWorkerStop(closed, releasedAt, undefined, cwd);
583
+ return closed;
584
+ }
118
585
  /**
119
586
  * List every persisted worker record, newest first.
120
587
  *
121
588
  * @param cwd - Project root.
589
+ * @param strict - Refuse incomplete ownership metadata before destructive cleanup.
122
590
  * @returns All worker records, open and stopped.
123
591
  */
124
- export async function listWorkerRecords(cwd) {
592
+ export async function listWorkerRecords(cwd, strict = false) {
125
593
  const db = await getDb(cwd);
126
594
  const rows = await db
127
595
  .select()
@@ -131,6 +599,12 @@ export async function listWorkerRecords(cwd) {
131
599
  const records = [];
132
600
  for (const row of rows) {
133
601
  const meta = parseWorkerMetadata(row);
602
+ if (strict &&
603
+ row.stoppedAt === null &&
604
+ (!meta || typeof meta.worktree !== 'string' || !isAbsolute(meta.worktree))) {
605
+ // @sync-invariant none:local-only unreadable local worker ownership forbids worktree cleanup
606
+ throw new Error(`Worker ownership unavailable for ${row.id}`);
607
+ }
134
608
  if (meta)
135
609
  records.push(toWorkerRecord(row, meta));
136
610
  }
@@ -191,6 +665,8 @@ async function updateWorkerSpawn(record, spawned, cwd) {
191
665
  * @returns True when the worker is tracked (its stop comes later).
192
666
  */
193
667
  export async function settleWorkerAtSpawn(record, spawned, cwd) {
668
+ if (record.execution)
669
+ return true;
194
670
  const pid = spawned.ownership?.pid ?? null;
195
671
  const hasExitHook = spawned.instanceId === record.instanceId;
196
672
  const updated = await updateWorkerSpawn(record, { instanceId: spawned.instanceId, pid, pgid: spawned.ownership?.pgid ?? null }, cwd);
@@ -206,6 +682,8 @@ export async function settleWorkerAtSpawn(record, spawned, cwd) {
206
682
  * @param cwd - Project root.
207
683
  */
208
684
  export async function abandonWorkerRecord(record, cwd) {
685
+ if (record.execution)
686
+ return;
209
687
  await closeWorker(record, 'failed', cwd);
210
688
  }
211
689
  /** Accepted values of {@link WorkerExitStatus}, for input validation. */
@@ -253,6 +731,11 @@ async function closeWorker(record, explicitStatus, cwd) {
253
731
  const stoppedAt = await claimWorkerStop(record.recordId, cwd);
254
732
  if (stoppedAt === null)
255
733
  return null;
734
+ await dispatchWorkerStop(record, stoppedAt, explicitStatus, cwd);
735
+ return { ...record, stoppedAt };
736
+ }
737
+ /** Send the existing lifecycle hook after the relevant durable exit CAS wins. */
738
+ async function dispatchWorkerStop(record, stoppedAt, explicitStatus, cwd) {
256
739
  const status = explicitStatus ?? (await deriveWorkerExitStatus(record.taskId, cwd));
257
740
  await hooks
258
741
  .dispatch('SubagentStop', cwd, {
@@ -260,12 +743,21 @@ async function closeWorker(record, explicitStatus, cwd) {
260
743
  taskId: record.taskId,
261
744
  agentId: record.agentId,
262
745
  status,
263
- metadata: { instanceId: record.instanceId, pid: record.pid },
746
+ metadata: {
747
+ instanceId: record.instanceId,
748
+ pid: record.pid,
749
+ ...(record.execution
750
+ ? {
751
+ backend: 'orca',
752
+ dispatchId: record.execution.dispatchId,
753
+ runtimeId: record.execution.context.runtimeId,
754
+ }
755
+ : {}),
756
+ },
264
757
  })
265
758
  .catch((err) => {
266
759
  getLogger('engine:orchestrate').warn({ taskId: record.taskId, err: String(err) }, 'SubagentStop hook failed for an exited worker');
267
760
  });
268
- return { ...record, stoppedAt };
269
761
  }
270
762
  /**
271
763
  * The worker's own completion signal: close its record and fire SubagentStop.
@@ -286,7 +778,7 @@ export async function markWorkerExited(target, status, cwd) {
286
778
  const record = (target.instanceId !== undefined
287
779
  ? records.find((r) => r.instanceId === target.instanceId)
288
780
  : records.find((r) => r.stoppedAt === null && r.sessionId === target.sessionId)) ?? null;
289
- if (record === null || record.stoppedAt !== null)
781
+ if (record === null || record.stoppedAt !== null || record.execution)
290
782
  return { record, emitted: false };
291
783
  const closed = await closeWorker(record, status, cwd);
292
784
  return closed ? { record: closed, emitted: true } : { record, emitted: false };
@@ -324,7 +816,7 @@ function isProcessAlive(pid) {
324
816
  export async function reconcileWorkerExits(cwd, isAlive = isProcessAlive) {
325
817
  const closed = [];
326
818
  for (const record of await listWorkerRecords(cwd)) {
327
- if (record.stoppedAt !== null || record.pid === null || isAlive(record.pid))
819
+ if (record.execution || record.stoppedAt !== null || record.pid === null || isAlive(record.pid))
328
820
  continue;
329
821
  const done = await closeWorker(record, undefined, cwd);
330
822
  if (done)