taskforce-loop-engineering 0.15.21 → 0.16.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 (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/MIGRATING.md +80 -0
  3. package/README.md +37 -8
  4. package/bin/loop-engineering.mjs +142 -114
  5. package/docs/architecture.md +3 -2
  6. package/docs/human-gate-command.md +1 -1
  7. package/docs/operator-dashboard.md +16 -5
  8. package/docs/operator-workspace-project.md +2 -2
  9. package/docs/production-trust-contract.md +9 -2
  10. package/docs/transactional-kernel-and-goal-api.md +3 -1
  11. package/lib/action-reservations.mjs +21 -23
  12. package/lib/context-budget.mjs +147 -0
  13. package/lib/core.mjs +746 -241
  14. package/lib/dispatch-classification.mjs +114 -0
  15. package/lib/durable-journal.mjs +23 -6
  16. package/lib/execution-ledger.mjs +4 -4
  17. package/lib/file-mutex.mjs +102 -0
  18. package/lib/human-gate-channel-adapter.mjs +4 -2
  19. package/lib/human-gate-command.mjs +5 -3
  20. package/lib/operator-dashboard.mjs +72 -10
  21. package/lib/production-evidence.mjs +37 -15
  22. package/lib/quota-runtime-decision.mjs +11 -6
  23. package/lib/redaction.mjs +34 -0
  24. package/lib/todo-control-plane.mjs +12 -16
  25. package/lib/transactional-state-kernel.mjs +96 -18
  26. package/package.json +2 -3
  27. package/scripts/context-budget-self-test.mjs +249 -0
  28. package/scripts/dashboard-autostart-install.mjs +33 -8
  29. package/scripts/dashboard-autostart-self-test.mjs +12 -3
  30. package/scripts/final-judgement-self-test.mjs +113 -4
  31. package/scripts/hermes-install-self-test.mjs +8 -1
  32. package/scripts/hermes-install.mjs +29 -8
  33. package/scripts/hermes-smoke.mjs +2 -1
  34. package/scripts/human-gate-command-self-test.mjs +34 -5
  35. package/scripts/install-shared.mjs +61 -0
  36. package/scripts/openclaw-install-self-test.mjs +158 -2
  37. package/scripts/openclaw-install.mjs +105 -30
  38. package/scripts/openclaw-manage.mjs +22 -3
  39. package/scripts/openclaw-smoke.mjs +2 -1
  40. package/scripts/project-relay-self-test.mjs +145 -1
  41. package/scripts/run-loop-cron.sh +22 -7
  42. package/scripts/safety-regression-self-test.mjs +350 -0
  43. package/skills/taskforce-loop-engineering/SKILL.md +7 -1
  44. package/skills/taskforce-loop-engineering/references/context-budget.md +11 -0
package/lib/core.mjs CHANGED
@@ -1,9 +1,12 @@
1
- import { access, copyFile, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
1
+ import { dispatchFailureClassification } from './dispatch-classification.mjs';
2
+ export { dispatchFailureClassification } from './dispatch-classification.mjs';
3
+ import { access, copyFile, link, mkdir, mkdtemp, open, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from 'node:fs/promises';
2
4
  import path from 'node:path';
3
5
  import { spawn } from 'node:child_process';
4
6
  import { fileURLToPath } from 'node:url';
5
7
  import { tmpdir } from 'node:os';
6
- import { createHash } from 'node:crypto';
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { contextPolicy, contextRotation, readBoundedJson, validHandoff, handoffCheckpoint } from './context-budget.mjs';
7
10
  import { listSteps } from './execution-ledger.mjs';
8
11
  import { readAndVerifyEvidence } from './production-evidence.mjs';
9
12
 
@@ -94,13 +97,62 @@ export async function exists(p) {
94
97
  }
95
98
  }
96
99
 
100
+ // JSON equality must not depend on object key order.
101
+ function canonicalJson(value) {
102
+ const sort = (item) => Array.isArray(item)
103
+ ? item.map(sort)
104
+ : item && typeof item === 'object'
105
+ ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, sort(item[key])]))
106
+ : item;
107
+ return JSON.stringify(sort(value));
108
+ }
109
+
97
110
  export async function readJson(file) {
98
111
  return JSON.parse(await readFile(file, 'utf8'));
99
112
  }
100
113
 
114
+ // Write through a temporary file and rename, so a crash can never leave a
115
+ // truncated JSON file that later poisons a queue scan.
101
116
  export async function writeJson(file, value) {
102
117
  await mkdir(path.dirname(file), { recursive: true });
103
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
118
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
119
+ try {
120
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`);
121
+ await rename(temporary, file);
122
+ } catch (error) {
123
+ await rm(temporary, { force: true });
124
+ throw error;
125
+ }
126
+ }
127
+
128
+ // Publish a new JSON file only if nothing exists at that path yet. link()
129
+ // fails with EEXIST instead of replacing, so two writers cannot overwrite
130
+ // each other, and readers never see a partial file.
131
+ async function writeJsonExclusive(file, value) {
132
+ await mkdir(path.dirname(file), { recursive: true });
133
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
134
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`);
135
+ try {
136
+ await link(temporary, file);
137
+ } finally {
138
+ await rm(temporary, { force: true });
139
+ }
140
+ }
141
+
142
+ // Move an unreadable queue file aside so one corrupt file cannot block every
143
+ // task behind it. The original bytes are kept for inspection.
144
+ async function quarantineQueueFile(root, queue, file, reason) {
145
+ const dir = path.join(queueDirFor(root, queue), 'quarantine');
146
+ await mkdir(dir, { recursive: true });
147
+ const target = path.join(dir, `${isoStamp()}_${path.basename(file)}`);
148
+ try {
149
+ await rename(file, target);
150
+ } catch (error) {
151
+ if (error?.code === 'ENOENT') return null;
152
+ throw error;
153
+ }
154
+ await writeFile(`${target}.reason.txt`, `${reason}\n`);
155
+ return path.relative(root, target);
104
156
  }
105
157
 
106
158
  export function runtimeDirFor(root, id) {
@@ -251,7 +303,7 @@ export async function runCheck(root, check) {
251
303
  } catch (err) {
252
304
  readError = err instanceof Error ? err.message : String(err);
253
305
  }
254
- const equal = readError === null && JSON.stringify(actual) === JSON.stringify(check.expected);
306
+ const equal = readError === null && canonicalJson(actual) === canonicalJson(check.expected);
255
307
  return {
256
308
  id: check.id,
257
309
  type: check.type,
@@ -304,12 +356,38 @@ function jsonPointerGet(value, pointer) {
304
356
  export function runCommand(cmd, options = {}) {
305
357
  return new Promise((resolve) => {
306
358
  const detached = process.platform !== 'win32';
307
- const child = spawn('/bin/sh', ['-lc', cmd], {
308
- cwd: options.cwd ?? process.cwd(),
309
- env: options.env ?? process.env,
310
- detached,
311
- stdio: ['ignore', 'pipe', 'pipe']
359
+ // A spawn failure (missing cwd, NUL byte in the command or environment)
360
+ // is a failed command, not a crash that strands the task in active/.
361
+ const spawnFailure = (error) => ({
362
+ exitCode: 127,
363
+ timedOut: false,
364
+ canceled: false,
365
+ cancelFile: null,
366
+ killedProcessGroup: false,
367
+ stdout: '',
368
+ stderr: `spawn failed: ${error instanceof Error ? error.message : String(error)}`
312
369
  });
370
+ let child;
371
+ try {
372
+ child = spawn('/bin/sh', ['-lc', cmd], {
373
+ cwd: options.cwd ?? process.cwd(),
374
+ env: options.env ?? process.env,
375
+ detached,
376
+ stdio: ['ignore', 'pipe', 'pipe']
377
+ });
378
+ } catch (error) {
379
+ resolve(spawnFailure(error));
380
+ return;
381
+ }
382
+ let settled = false;
383
+ const finish = (result) => {
384
+ if (settled) return;
385
+ settled = true;
386
+ clearTimeout(timer);
387
+ if (cancelTimer) clearInterval(cancelTimer);
388
+ resolve(result);
389
+ };
390
+ child.on('error', (error) => finish(spawnFailure(error)));
313
391
  let stdout = '';
314
392
  let stderr = '';
315
393
  let timedOut = false;
@@ -349,12 +427,13 @@ export function runCommand(cmd, options = {}) {
349
427
  }
350
428
  }, options.cancelPollMs ?? 250) : null;
351
429
  cancelTimer?.unref();
352
- child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
353
- child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
430
+ // setEncoding keeps multi-byte characters intact across chunk boundaries.
431
+ child.stdout.setEncoding('utf8');
432
+ child.stderr.setEncoding('utf8');
433
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
434
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
354
435
  child.on('close', (code, signal) => {
355
- clearTimeout(timer);
356
- if (cancelTimer) clearInterval(cancelTimer);
357
- resolve({
436
+ finish({
358
437
  exitCode: code ?? (signal ? 128 : 1),
359
438
  timedOut,
360
439
  canceled,
@@ -1030,8 +1109,9 @@ export async function parkQueueTask(root, options = {}) {
1030
1109
  authorization: options.authorization ?? task.parked?.authorization ?? null
1031
1110
  };
1032
1111
  const waitingFile = path.join(queueSubdirFor(root, queue, 'waiting'), path.basename(found.file));
1112
+ if (path.resolve(found.file) !== path.resolve(waitingFile)) await rename(found.file, waitingFile);
1033
1113
  await writeJson(waitingFile, { ...task, status: 'parked', parked });
1034
- if (path.resolve(found.file) !== path.resolve(waitingFile)) await rm(found.file, { force: true });
1114
+ if (found.subdir === 'active') await requestTaskStop(root, queue, taskId, 'operator_park');
1035
1115
  return { outcome: 'parked', task: { ...task, status: 'parked', parked }, file: path.relative(root, waitingFile) };
1036
1116
  }
1037
1117
 
@@ -1127,8 +1207,8 @@ export async function resumeParkedTask(root, options = {}) {
1127
1207
  execution_boundary: { ...task.parked.execution_boundary, resumed_at: now.toISOString() }
1128
1208
  };
1129
1209
  const inboxFile = path.join(queueSubdirFor(root, queue, 'inbox'), path.basename(found.file));
1130
- await writeJson(inboxFile, { ...task, status: 'queued', parked: resumed, requeuedAt: now.toISOString(), requeuedFrom: 'waiting' });
1131
- if (path.resolve(found.file) !== path.resolve(inboxFile)) await rm(found.file, { force: true });
1210
+ if (path.resolve(found.file) !== path.resolve(inboxFile)) await rename(found.file, inboxFile);
1211
+ await writeJson(inboxFile, { ...task, status: 'queued', parked: resumed, requeuedAt: now.toISOString(), requeuedFrom: 'waiting', supersedeClearedAt: new Date().toISOString() });
1132
1212
  return { outcome: 'verified_and_requeued', signalSha256, task: { ...task, status: 'queued', parked: resumed }, file: path.relative(root, inboxFile) };
1133
1213
  }
1134
1214
 
@@ -1213,6 +1293,16 @@ function requirementIdsFromCheckpoint(checkpoint, specs) {
1213
1293
  return [...known].filter((id) => new RegExp(`(^|[^A-Za-z0-9_-])${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^A-Za-z0-9_-]|$)`).test(text));
1214
1294
  }
1215
1295
 
1296
+ // A project is mentioned only as a whole token: "ui" must not match "build".
1297
+ // Project ids are [A-Za-z0-9._-], so neighbouring id characters (or a
1298
+ // trailing dot followed by one) mean the name is part of another word.
1299
+ function projectNameMentioned(text, project) {
1300
+ const name = String(project ?? '').toLowerCase();
1301
+ if (!name) return false;
1302
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1303
+ return new RegExp(`(^|[^a-z0-9_-])${escaped}(?![a-z0-9_-]|\\.[a-z0-9])`, 'i').test(text);
1304
+ }
1305
+
1216
1306
  function inferProjectSpec(task, checkpoint, specs, requirementIds = []) {
1217
1307
  const explicit = checkpoint?.project_id
1218
1308
  ?? checkpoint?.projectId
@@ -1225,7 +1315,7 @@ function inferProjectSpec(task, checkpoint, specs, requirementIds = []) {
1225
1315
  const candidates = specs.map((spec) => ({
1226
1316
  spec,
1227
1317
  requirementMatches: requirementIds.filter((id) => (spec.backlog ?? []).some((item) => item.id === id)).length,
1228
- nameMatch: text.includes(String(spec.project).toLowerCase()) ? 1 : 0
1318
+ nameMatch: projectNameMentioned(text, spec.project) ? 1 : 0
1229
1319
  })).filter((item) => item.requirementMatches > 0 || item.nameMatch > 0)
1230
1320
  .sort((a, b) => b.requirementMatches - a.requirementMatches || b.nameMatch - a.nameMatch || b.spec.project.length - a.spec.project.length);
1231
1321
  return candidates[0]?.spec ?? null;
@@ -1286,6 +1376,10 @@ export async function reconcileProjectGates(root, options = {}) {
1286
1376
  await writeJson(full, gate);
1287
1377
  }
1288
1378
  const spec = await projectSpecForCheckpoint(root, [...specs.values()], gate.project_id, checkpoint);
1379
+ // Gates for tasks outside any project are not project-governed: there
1380
+ // is no contract to go stale, so reconciliation must leave them alone.
1381
+ // A gate bound to a project that has since disappeared still fails.
1382
+ if (!spec && !gate.project_id) continue;
1289
1383
  if (spec?.project && gate.project_id !== spec.project) {
1290
1384
  gate = { ...gate, project_id: spec.project };
1291
1385
  await writeJson(full, gate);
@@ -1924,10 +2018,10 @@ export async function enqueueTask(root, options) {
1924
2018
  throw new Error('enqueue requires --task or --file.');
1925
2019
  }
1926
2020
 
1927
- const id = taskIdForTitle(options.title);
2021
+ const baseId = taskIdForTitle(options.title);
1928
2022
  const task = {
1929
2023
  version: 1,
1930
- id,
2024
+ id: baseId,
1931
2025
  queue,
1932
2026
  title: options.title.trim(),
1933
2027
  body: body.trim(),
@@ -1940,9 +2034,27 @@ export async function enqueueTask(root, options) {
1940
2034
  ...(options.supersedeReason ? { supersedeReason: options.supersedeReason } : {}),
1941
2035
  ...(taskSourceFromOptions(options) ? { source: taskSourceFromOptions(options) } : {})
1942
2036
  };
1943
- const file = path.join(queueSubdirFor(root, queue, 'inbox'), `${id}.json`);
1944
- await writeJson(file, task);
1945
- return { task, file: path.relative(root, file) };
2037
+ // Ids are a millisecond timestamp plus a title slug (non-ASCII titles all
2038
+ // slug to "task"), so concurrent enqueues can collide. Never overwrite:
2039
+ // take the next free suffix across every task state.
2040
+ for (let attempt = 1; attempt <= 1000; attempt += 1) {
2041
+ const id = attempt === 1 ? baseId : `${baseId}-${attempt}`;
2042
+ let taken = false;
2043
+ for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
2044
+ if (await exists(path.join(queueSubdirFor(root, queue, subdir), `${id}.json`))) { taken = true; break; }
2045
+ }
2046
+ if (taken) continue;
2047
+ const file = path.join(queueSubdirFor(root, queue, 'inbox'), `${id}.json`);
2048
+ task.id = id;
2049
+ try {
2050
+ await writeJsonExclusive(file, task);
2051
+ } catch (error) {
2052
+ if (error?.code === 'EEXIST') continue;
2053
+ throw error;
2054
+ }
2055
+ return { task, file: path.relative(root, file) };
2056
+ }
2057
+ throw new Error(`Unable to allocate a unique task id for ${baseId}.`);
1946
2058
  }
1947
2059
 
1948
2060
  function taskSourceFromOptions(options = {}) {
@@ -2038,7 +2150,14 @@ async function appendActiveTaskAmendment(root, queue, activeTask, options = {})
2038
2150
  });
2039
2151
  updatedPlans.push(path.relative(root, file));
2040
2152
  }
2041
- await writeJson(path.join(queueSubdirFor(root, queue, 'active'), `${activeTask.id}.json`), {
2153
+ const activeFile = path.join(queueSubdirFor(root, queue, 'active'), `${activeTask.id}.json`);
2154
+ // The runner may have finished meanwhile. Writing here would re-create the
2155
+ // task in active/ and get it re-executed; the amendment artifacts above
2156
+ // still record the instruction.
2157
+ if (!(await exists(activeFile))) {
2158
+ return { amendment, file: path.relative(root, versionedFile), latestFile: path.relative(root, latestFile), updatedPlans, taskFinished: true };
2159
+ }
2160
+ await writeJson(activeFile, {
2042
2161
  ...activeTask,
2043
2162
  amendmentCount: sequence,
2044
2163
  lastAmendmentAt: amendment.requestedAt,
@@ -2590,7 +2709,21 @@ async function projectHasSafeActionableBacklog(root, spec, checkpoint = null) {
2590
2709
  });
2591
2710
  }
2592
2711
 
2593
- export async function projectRelayReconcile(root, { queue, project } = {}) {
2712
+ const RELAY_TASK_SUBDIRS = ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled'];
2713
+
2714
+ // Read each queue task file once so the relay checks of one scheduler pass
2715
+ // can share it instead of rescanning every directory.
2716
+ async function relayTaskSnapshot(root, queue, subdirs = RELAY_TASK_SUBDIRS) {
2717
+ const snapshot = {};
2718
+ for (const subdir of subdirs) {
2719
+ const dir = queueSubdirFor(root, queue, subdir);
2720
+ snapshot[subdir] = [];
2721
+ for (const file of await listJson(dir)) snapshot[subdir].push(await readJson(path.join(dir, file)));
2722
+ }
2723
+ return snapshot;
2724
+ }
2725
+
2726
+ export async function projectRelayReconcile(root, { queue, project, beforeWrite, tasks } = {}) {
2594
2727
  project = normalizeProjectId(project);
2595
2728
  const spec = await readJson(projectConfigPathFor(root, project));
2596
2729
  if (spec.relayStatusReconciliation !== true || !spec.backlogSource
@@ -2601,21 +2734,49 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2601
2734
  || !['in_progress', 'ongoing'].includes(ledger.status)
2602
2735
  || ledger.terminalState?.accepted === true || ledger.terminalAccepted === true) return { changed: 0 };
2603
2736
  const backlogFile = path.resolve(root, safeRelativePath(spec.backlogSource, 'project backlog source'));
2737
+ let backlogText;
2604
2738
  let backlog;
2605
- try { backlog = await readJson(backlogFile); } catch { return { changed: 0 }; }
2739
+ try {
2740
+ backlogText = await readFile(backlogFile, 'utf8');
2741
+ backlog = JSON.parse(backlogText);
2742
+ } catch { return { changed: 0 }; }
2606
2743
  if (!backlog || typeof backlog !== 'object' || Array.isArray(backlog)) return { changed: 0 };
2607
2744
  const field = Array.isArray(backlog.items) ? 'items' : Array.isArray(backlog.tasks) ? 'tasks' : null;
2608
2745
  if (!field) return { changed: 0 };
2746
+ // Revision rounds keep the backlog binding but not the leading marker, so
2747
+ // resolve each completed task to the relay task that started its lineage.
2748
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue, ['done', 'failed']);
2749
+ const finished = new Map();
2750
+ for (const subdir of ['done', 'failed']) {
2751
+ for (const task of snapshot[subdir]) {
2752
+ if (task?.id && !finished.has(task.id)) finished.set(task.id, { task, subdir });
2753
+ }
2754
+ }
2755
+ const relayRoot = (task) => {
2756
+ const seen = new Set();
2757
+ let current = task;
2758
+ while (current && !seen.has(current.id)) {
2759
+ if (current.projectId !== project || current.backlogItemId !== task.backlogItemId) return null;
2760
+ seen.add(current.id);
2761
+ if (!current.revisionOf) {
2762
+ const marker = String(current.body ?? '').match(/^\[project-relay:([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)\](?:\n|$)/);
2763
+ return marker?.[1] === project && marker[2] === task.backlogItemId ? current.id : null;
2764
+ }
2765
+ current = finished.get(current.revisionOf)?.task;
2766
+ }
2767
+ return null;
2768
+ };
2609
2769
  const completed = new Map();
2610
- for (const file of await listJson(queueSubdirFor(root, queue, 'done'))) {
2611
- const task = await readJson(path.join(queueSubdirFor(root, queue, 'done'), file));
2612
- if (task.projectId !== project || task.status !== 'completed' || !task.id
2770
+ for (const { task, subdir } of finished.values()) {
2771
+ if (subdir !== 'done' || task.projectId !== project || task.status !== 'completed'
2772
+ || typeof task.backlogItemId !== 'string'
2613
2773
  || !task.source?.channel || !task.source?.target || !task.source?.account || !task.source?.message_id) continue;
2614
- const marker = String(task.body ?? '').match(/^\[project-relay:([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)\](?:\n|$)/);
2615
- if (marker?.[1] !== project || task.backlogItemId !== marker[2]) continue;
2616
- const ids = completed.get(marker[2]) ?? [];
2617
- ids.push(task.id);
2618
- completed.set(marker[2], ids);
2774
+ const rootId = relayRoot(task);
2775
+ if (!rootId) continue;
2776
+ const evidence = completed.get(task.backlogItemId) ?? { roots: new Set(), taskIds: [] };
2777
+ evidence.roots.add(rootId);
2778
+ evidence.taskIds.push(task.id);
2779
+ completed.set(task.backlogItemId, evidence);
2619
2780
  }
2620
2781
  const itemCounts = new Map();
2621
2782
  for (const item of backlog[field]) {
@@ -2626,15 +2787,21 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2626
2787
  for (const item of backlog[field]) {
2627
2788
  if (!item || typeof item !== 'object' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(item.id ?? ''))
2628
2789
  || itemCounts.get(item.id) !== 1
2629
- || (completed.get(item.id) ?? []).length !== 1
2790
+ || completed.get(item.id)?.roots.size !== 1
2630
2791
  || item.status !== 'ready' || item.autoRun !== true || item.scope !== 'local_only'
2631
2792
  || item.externalActionsAllowed !== false || item.humanGateRequired !== false) {
2632
2793
  items.push(item);
2633
2794
  continue;
2634
2795
  }
2635
- const judgementFile = path.join(taskRuntimeDirFor(root, queue, completed.get(item.id)[0]), 'final_judgement.json');
2636
- const judgement = await exists(judgementFile) ? await readJson(judgementFile) : null;
2637
- if (judgement?.outcome !== 'ready_to_apply' || judgement.requires_human_gate !== false) {
2796
+ // One relay lineage may contain rejected rounds, but exactly one round
2797
+ // must carry an accepted, gate-free final judgement.
2798
+ let accepted = 0;
2799
+ for (const taskId of completed.get(item.id).taskIds) {
2800
+ const judgementFile = path.join(taskRuntimeDirFor(root, queue, taskId), 'final_judgement.json');
2801
+ const judgement = await exists(judgementFile) ? await readJson(judgementFile) : null;
2802
+ if (judgement?.outcome === 'ready_to_apply' && judgement.requires_human_gate === false) accepted += 1;
2803
+ }
2804
+ if (accepted !== 1) {
2638
2805
  items.push(item);
2639
2806
  continue;
2640
2807
  }
@@ -2644,12 +2811,21 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2644
2811
  if (changed) {
2645
2812
  const temporary = `${backlogFile}.${process.pid}.tmp`;
2646
2813
  await writeJson(temporary, { ...backlog, [field]: items });
2814
+ if (beforeWrite) await beforeWrite();
2815
+ // The backlog is shared with agents that may edit it from another queue
2816
+ // or process. Never replace a version this reconciliation did not read.
2817
+ let currentText = null;
2818
+ try { currentText = await readFile(backlogFile, 'utf8'); } catch {}
2819
+ if (currentText !== backlogText) {
2820
+ await rm(temporary, { force: true });
2821
+ return { changed: 0, conflict: true };
2822
+ }
2647
2823
  await rename(temporary, backlogFile);
2648
2824
  }
2649
2825
  return { changed };
2650
2826
  }
2651
2827
 
2652
- export async function projectRelayNext(root, { queue, task, finalJudgement } = {}) {
2828
+ export async function projectRelayNext(root, { queue, task, finalJudgement, tasks } = {}) {
2653
2829
  if (!task?.projectId || finalJudgement?.outcome !== 'ready_to_apply' || finalJudgement.requires_human_gate) return null;
2654
2830
  const project = normalizeProjectId(task.projectId);
2655
2831
  const spec = await readJson(projectConfigPathFor(root, project));
@@ -2666,26 +2842,27 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
2666
2842
  if (typeof predecessorId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(predecessorId)) return null;
2667
2843
  const queueState = await queueStatus(root, queue);
2668
2844
  if (queueState.queued || queueState.active || queueState.waiting) return null;
2669
- await projectRelayReconcile(root, { queue, project });
2845
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue);
2846
+ await projectRelayReconcile(root, { queue, project, tasks: snapshot });
2670
2847
  const backlogSource = spec.backlogSource ?? spec.authoritativeBacklog;
2671
2848
  if (typeof backlogSource !== 'string' || !backlogSource.trim()) return null;
2672
2849
  let backlog;
2673
2850
  try {
2674
2851
  backlog = await readJson(path.resolve(root, safeRelativePath(backlogSource, 'project backlog source')));
2675
2852
  } catch { return null; }
2676
- const items = Array.isArray(backlog?.items) ? backlog.items : Array.isArray(backlog?.tasks) ? backlog.tasks : null;
2677
- if (!items?.length) return null;
2678
- const byId = new Map(items.map((item) => [item.id, item]));
2853
+ const rows = Array.isArray(backlog?.items) ? backlog.items : Array.isArray(backlog?.tasks) ? backlog.tasks : null;
2854
+ if (!rows?.length) return null;
2855
+ // Ambiguous ids cannot prove a predecessor or dependency, and cannot be
2856
+ // relayed: drop every row that shares its id with another row.
2857
+ const items = rows.filter((item) => item && typeof item === 'object' && !Array.isArray(item));
2858
+ const idCounts = new Map();
2859
+ for (const item of items) idCounts.set(item.id, (idCounts.get(item.id) ?? 0) + 1);
2860
+ const byId = new Map(items.filter((item) => idCounts.get(item.id) === 1).map((item) => [item.id, item]));
2679
2861
  const complete = new Set(['accepted', 'complete', 'completed', 'done', 'phase_complete']);
2680
2862
  if (!complete.has(byId.get(predecessorId)?.status)) return null;
2681
- const queuedBodies = [];
2682
- for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
2683
- for (const file of await listJson(queueSubdirFor(root, queue, subdir))) {
2684
- queuedBodies.push(String((await readJson(path.join(queueSubdirFor(root, queue, subdir), file))).body ?? ''));
2685
- }
2686
- }
2863
+ const queuedBodies = RELAY_TASK_SUBDIRS.flatMap((subdir) => snapshot[subdir].map((entry) => String(entry?.body ?? '')));
2687
2864
  const item = items.find((candidate) => {
2688
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(candidate.id ?? ''))) return false;
2865
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(candidate.id ?? '')) || byId.get(candidate.id) !== candidate) return false;
2689
2866
  if (candidate.status !== 'ready' || candidate.autoRun !== true || candidate.scope !== 'local_only'
2690
2867
  || candidate.externalActionsAllowed !== false || candidate.humanGateRequired !== false
2691
2868
  || candidate.blocked === true || candidate.requires_human_input === true
@@ -2708,6 +2885,29 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
2708
2885
  return { project, itemId: item.id, taskId: result.task.id, file: result.file };
2709
2886
  }
2710
2887
 
2888
+ // Relay is attempted when a bound task is accepted, but it is skipped while
2889
+ // the queue is busy. Retry once the queue is idle, but only when the most
2890
+ // recently enqueued backlog-bound task is the accepted one: a failed or
2891
+ // canceled relay task stops the chain until a person acts on it.
2892
+ // projectRelayNext keeps every authority and duplicate check.
2893
+ export async function projectRelayResume(root, { queue, project, tasks } = {}) {
2894
+ project = normalizeProjectId(project);
2895
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue);
2896
+ let newest = null;
2897
+ for (const subdir of ['done', 'failed', 'canceled']) {
2898
+ for (const task of snapshot[subdir]) {
2899
+ if (task?.projectId !== project || typeof task.backlogItemId !== 'string' || !task.id) continue;
2900
+ const time = Date.parse(task.enqueuedAt ?? task.finishedAt ?? '') || 0;
2901
+ if (!newest || time > newest.time) newest = { task, subdir, time, tied: false };
2902
+ else if (time === newest.time) newest.tied = true;
2903
+ }
2904
+ }
2905
+ if (!newest || newest.tied || newest.subdir !== 'done' || newest.task.status !== 'completed') return null;
2906
+ const judgementFile = path.join(taskRuntimeDirFor(root, queue, newest.task.id), 'final_judgement.json');
2907
+ if (!await exists(judgementFile)) return null;
2908
+ return projectRelayNext(root, { queue, task: newest.task, finalJudgement: await readJson(judgementFile), tasks: snapshot });
2909
+ }
2910
+
2711
2911
  async function tasksById(root, queue) {
2712
2912
  const tasks = new Map();
2713
2913
  for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
@@ -4012,7 +4212,7 @@ export async function writeAcceptanceReviews(root, queue, task, taskContract, ac
4012
4212
  checkpointId: review.checkpoint_id,
4013
4213
  milestoneId: checkpoint.milestone_id ?? null,
4014
4214
  revisesCheckpointId: checkpoint.revises_checkpoint_id ?? null,
4015
- sequence: Number(checkpoint.sequence ?? String(checkpoint.checkpoint_id ?? '').match(/(\d+)$/)?.[1] ?? 0),
4215
+ sequence: checkpoint.sequence ?? null,
4016
4216
  checkpointCreatedAt: checkpoint.created_at ?? null,
4017
4217
  createdAt: checkpoint.created_at ?? review.created_at,
4018
4218
  projectCompletion: checkpoint.project_completion ?? null,
@@ -4036,24 +4236,31 @@ export async function writeAcceptanceReviews(root, queue, task, taskContract, ac
4036
4236
  };
4037
4237
  }
4038
4238
 
4039
- function compareReviewSequence(a, b) {
4040
- const sequenceDelta = Number(a.sequence ?? 0) - Number(b.sequence ?? 0);
4041
- if (sequenceDelta !== 0) return sequenceDelta;
4042
- return String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? ''));
4239
+ // IDs and review-generation timestamps are not chronology. A comparison is
4240
+ // conclusive only when checkpoint-owned clocks agree; missing/conflicting
4241
+ // evidence leaves both snapshots live (especially unresolved blockers).
4242
+ function compareReviewRecency(a, b) {
4243
+ const sequence = value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
4244
+ const timestamp = value => typeof value === 'string' && value.trim().length > 0 && Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;
4245
+ const signs = [];
4246
+ for (const [left, right] of [
4247
+ [sequence(a.sequence), sequence(b.sequence)],
4248
+ [timestamp(a.checkpointCreatedAt), timestamp(b.checkpointCreatedAt)]
4249
+ ]) {
4250
+ if (left !== null && right !== null && left !== right) signs.push(Math.sign(left - right));
4251
+ }
4252
+ if (signs.length && signs.every(sign => sign === signs[0])) return signs[0];
4253
+ return 0;
4043
4254
  }
4044
4255
 
4045
- function compareReviewRecency(a, b) {
4046
- const aCheckpoint = Number(String(a.checkpointId ?? '').match(/(\d+)$/)?.[1] ?? 0);
4047
- const bCheckpoint = Number(String(b.checkpointId ?? '').match(/(\d+)$/)?.[1] ?? 0);
4048
- if (aCheckpoint !== bCheckpoint) return aCheckpoint - bCheckpoint;
4049
- // Review artifacts are regenerated as a batch. Their generated_at values
4050
- // therefore describe directory traversal order, not checkpoint recency.
4051
- // Only trust a timestamp that came from the checkpoint itself.
4052
- const checkpointCreatedDelta = String(a.checkpointCreatedAt ?? '').localeCompare(String(b.checkpointCreatedAt ?? ''));
4053
- if (checkpointCreatedDelta !== 0 && a.checkpointCreatedAt && b.checkpointCreatedAt) return checkpointCreatedDelta;
4054
- const sequenceDelta = Number(a.sequence ?? 0) - Number(b.sequence ?? 0);
4055
- if (sequenceDelta !== 0) return sequenceDelta;
4056
- return compareReviewSequence(a, b);
4256
+ function effectiveReviewFrontier(reviews) {
4257
+ const frontier = reviews.filter(review => !reviews.some(other => compareReviewRecency(other, review) > 0));
4258
+ // Partial clocks can form a cycle when different pairs expose different
4259
+ // clocks. Never turn contradictory evidence into an empty acceptance set.
4260
+ return frontier.length
4261
+ ? reviews.filter(review => frontier.includes(review)
4262
+ || !frontier.some(latest => compareReviewRecency(latest, review) > 0))
4263
+ : reviews;
4057
4264
  }
4058
4265
 
4059
4266
  function terminalTaskReview(review, contract = {}) {
@@ -4066,12 +4273,18 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4066
4273
  const allReviews = acceptanceReviews?.reviews ?? [];
4067
4274
  const planned = Array.isArray(devPlan?.checkpoints) ? devPlan.checkpoints : [];
4068
4275
  if (planned.length <= 1) {
4069
- const ordered = [...allReviews].sort(compareReviewRecency);
4070
- // A task-level terminal acceptance is monotonic. Later checkpoints may
4071
- // report broader project governance, but they cannot reopen or overwrite
4072
- // the completed task. Broader work belongs to the project ledger/gates.
4073
- const terminal = ordered.find((review) => terminalTaskReview(review, contract));
4074
- return terminal ? [terminal] : ordered.slice(-1);
4276
+ // Terminal acceptance remains monotonic only with known chronology.
4277
+ // An unordered blocker cannot be dismissed as later project governance.
4278
+ const terminal = allReviews.find(review => terminalTaskReview(review, contract)
4279
+ && allReviews.every(other => other === review
4280
+ || compareReviewRecency(review, other) > 0
4281
+ || (compareReviewRecency(review, other) < 0
4282
+ && projectCompletionStatus(other.projectCompletion) === 'needs_human_acceptance'
4283
+ // A project label is not proof that a failed review is out of scope.
4284
+ // Only independently accepted, gate-free governance can be ignored.
4285
+ && other.status === 'accepted'
4286
+ && (other.deferredGates?.length ?? 0) === 0)));
4287
+ return terminal ? [terminal] : effectiveReviewFrontier(allReviews);
4075
4288
  }
4076
4289
  const selected = [];
4077
4290
  for (const checkpoint of planned) {
@@ -4080,7 +4293,7 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4080
4293
  review.milestoneId === milestoneId || review.checkpointId === milestoneId
4081
4294
  );
4082
4295
  if (candidates.length === 0) continue;
4083
- selected.push([...candidates].sort(compareReviewSequence).at(-1));
4296
+ selected.push(...effectiveReviewFrontier(candidates));
4084
4297
  }
4085
4298
  return selected;
4086
4299
  }
@@ -4096,7 +4309,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4096
4309
  // resolved historical blocker does not permanently poison the task.
4097
4310
  const effectiveReviews = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4098
4311
  const reviewCount = effectiveReviews.length;
4099
- const acceptedCount = effectiveReviews.filter((item) => item.status === 'accepted').length;
4312
+ const acceptedCount = requiredCheckpoints > 1
4313
+ ? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
4314
+ && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id))).length
4315
+ : effectiveReviews.filter((item) => item.status === 'accepted').length;
4100
4316
  const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
4101
4317
  const blockedCount = effectiveReviews.filter((item) => item.status === 'blocked').length;
4102
4318
  const dispatchStatus = context.dispatchStatus ?? 'unknown';
@@ -4110,7 +4326,13 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4110
4326
  const deferredGateCount = effectiveReviews.reduce((count, review) => count + (review.deferredGates?.length ?? 0), 0);
4111
4327
  let outcome = 'needs_revision';
4112
4328
 
4113
- if (dispatchStatus === 'runtime_interrupted') {
4329
+ // A worker can stop after persisting a blocker but before writing a handoff.
4330
+ // Use effective reviews, not historical blockers, before permitting recovery.
4331
+ if (['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed'].includes(dispatchStatus) && blockedCount > 0) {
4332
+ outcome = 'blocked';
4333
+ reasons.push(`${blockedCount} effective acceptance review(s) block automatic continuation.`);
4334
+ nextActions.push('Resolve the recorded human/external blocker before any continuation.');
4335
+ } else if (dispatchStatus === 'runtime_interrupted') {
4114
4336
  outcome = 'runtime_interrupted';
4115
4337
  reasons.push(`A recoverable runtime interruption stopped the worker${dispatchFailure?.category ? ` (${dispatchFailure.category})` : ''}.`);
4116
4338
  nextActions.push('Rotate the worker session and resume from the latest durable checkpoint without creating a development revision.');
@@ -4237,8 +4459,10 @@ export async function writeFinalJudgement(root, queue, task, taskContract, accep
4237
4459
 
4238
4460
  function queueStatusFromFinalJudgement(currentStatus, finalJudgement) {
4239
4461
  if (!finalJudgement?.judgement) return currentStatus;
4240
- if (currentStatus !== 'completed') return currentStatus;
4241
4462
  const outcome = finalJudgement.judgement.outcome;
4463
+ // Carry the recovery veto through to queue placement, not just the report.
4464
+ if (['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed'].includes(currentStatus) && outcome === 'blocked') return 'needs_human_input';
4465
+ if (currentStatus !== 'completed') return currentStatus;
4242
4466
  if (outcome === 'ready_to_apply') return currentStatus;
4243
4467
  if (outcome === 'project_in_progress') return outcome;
4244
4468
  if (outcome === 'runtime_interrupted') return outcome;
@@ -4704,6 +4928,31 @@ function decideQueueProgressNotification(previousProgress, policy, observed, sch
4704
4928
  };
4705
4929
  }
4706
4930
 
4931
+ function relayMaintenanceStatePath(root, queue) {
4932
+ return path.join(queueDirFor(root, queue), 'scheduler', 'relay-maintenance.json');
4933
+ }
4934
+
4935
+ // Cheap change detector for relay maintenance: task file names per state
4936
+ // directory (a task changing state is a rename), each project spec, and the
4937
+ // size and mtime of its backlog and acceptance files. In-place task edits are
4938
+ // intentionally left to the periodic full pass.
4939
+ async function relayMaintenanceFingerprint(root, queue, specs) {
4940
+ const hash = createHash('sha256');
4941
+ for (const subdir of RELAY_TASK_SUBDIRS) {
4942
+ hash.update(`${subdir}\0${(await listJson(queueSubdirFor(root, queue, subdir))).join('\0')}\n`);
4943
+ }
4944
+ for (const spec of specs) {
4945
+ hash.update(`${JSON.stringify(spec)}\n`);
4946
+ for (const configured of [spec.backlogSource, spec.authoritativeBacklog, spec.acceptanceLedger, spec.ledger, spec.terminalContract]) {
4947
+ if (typeof configured !== 'string') continue;
4948
+ let info = null;
4949
+ try { info = await stat(path.resolve(root, safeRelativePath(configured, 'project relay file'))); } catch {}
4950
+ hash.update(`${configured}\0${info ? `${info.mtimeMs}:${info.size}` : 'missing'}\n`);
4951
+ }
4952
+ }
4953
+ return hash.digest('hex');
4954
+ }
4955
+
4707
4956
  export async function queueSchedulerTick(root, options) {
4708
4957
  const queue = normalizeLoopId(options.queue);
4709
4958
  await ensureQueueDirs(root, queue);
@@ -4747,13 +4996,70 @@ export async function queueSchedulerTick(root, options) {
4747
4996
  }
4748
4997
 
4749
4998
  const relayReconciliation = [];
4750
- if (!options.planOnly) {
4751
- for (const spec of await projectSpecs(root)) {
4752
- if (spec.relayStatusReconciliation !== true || !spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true)) continue;
4999
+ const projectRelay = [];
5000
+ let relayMaintenance = 'not_configured';
5001
+ const relaySpecs = options.planOnly ? [] : (await projectSpecs(root))
5002
+ .filter((spec) => spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true));
5003
+ if (relaySpecs.length) {
5004
+ // Agents edit project backlogs while they hold this queue's lock. Only
5005
+ // reconcile or relay when this tick owns the lock and nothing is active.
5006
+ const lockResult = await acquireQueueLock(root, queue, 5 * 60 * 1000);
5007
+ relayMaintenance = lockResult.acquired ? 'queue_active' : 'queue_locked';
5008
+ if (lockResult.acquired) {
4753
5009
  try {
4754
- relayReconciliation.push({ project: spec.project, ...await projectRelayReconcile(root, { queue, project: spec.project }) });
4755
- } catch (error) {
4756
- relayReconciliation.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
5010
+ if ((await queueStatus(root, queue)).active === 0) {
5011
+ // Most ticks change nothing relay-relevant. Skip the full scan when
5012
+ // the cheap fingerprint is unchanged; a periodic full pass covers
5013
+ // in-place edits the fingerprint cannot see. Skipping only delays a
5014
+ // relay: every decision is still recomputed from the task files.
5015
+ const fingerprint = await relayMaintenanceFingerprint(root, queue, relaySpecs);
5016
+ const statePath = relayMaintenanceStatePath(root, queue);
5017
+ const previousPass = await exists(statePath) ? await readJson(statePath).catch(() => null) : null;
5018
+ const fullIntervalMs = options.relayMaintenanceFullIntervalMs ?? 60 * 60 * 1000;
5019
+ const sinceFullPassMs = nowMs - Date.parse(previousPass?.fullPassAt ?? '');
5020
+ if (previousPass?.fingerprint === fingerprint && sinceFullPassMs >= 0 && sinceFullPassMs < fullIntervalMs) {
5021
+ relayMaintenance = 'unchanged';
5022
+ } else {
5023
+ relayMaintenance = 'completed';
5024
+ let tasks = null;
5025
+ let clean = true;
5026
+ try {
5027
+ tasks = await relayTaskSnapshot(root, queue);
5028
+ } catch (error) {
5029
+ clean = false;
5030
+ relayMaintenance = 'error';
5031
+ projectRelay.push({ error: error instanceof Error ? error.message : String(error) });
5032
+ }
5033
+ for (const spec of tasks ? relaySpecs : []) {
5034
+ if (spec.relayStatusReconciliation === true) {
5035
+ try {
5036
+ const reconciled = await projectRelayReconcile(root, { queue, project: spec.project, tasks });
5037
+ if (reconciled.conflict) clean = false;
5038
+ relayReconciliation.push({ project: spec.project, ...reconciled });
5039
+ } catch (error) {
5040
+ clean = false;
5041
+ relayReconciliation.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
5042
+ }
5043
+ }
5044
+ try {
5045
+ const relayed = await projectRelayResume(root, { queue, project: spec.project, tasks });
5046
+ if (relayed) {
5047
+ projectRelay.push(relayed);
5048
+ tasks = await relayTaskSnapshot(root, queue);
5049
+ }
5050
+ } catch (error) {
5051
+ clean = false;
5052
+ projectRelay.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
5053
+ }
5054
+ }
5055
+ // Record the fingerprint read before this pass, so anything that
5056
+ // changed during it triggers another full pass. Failed passes are
5057
+ // not recorded and retry on the next tick.
5058
+ if (clean) await writeJson(statePath, { version: 1, fingerprint, fullPassAt: now });
5059
+ }
5060
+ }
5061
+ } finally {
5062
+ await releaseQueueLock(root, queue, lockResult.lock);
4757
5063
  }
4758
5064
  }
4759
5065
  }
@@ -4849,6 +5155,8 @@ export async function queueSchedulerTick(root, options) {
4849
5155
  statusBefore,
4850
5156
  statusAfter,
4851
5157
  relayReconciliation,
5158
+ relayMaintenance,
5159
+ projectRelay,
4852
5160
  run: runResult
4853
5161
  };
4854
5162
  }
@@ -5024,15 +5332,68 @@ function queueLockOwnerAlive(lock) {
5024
5332
  return Boolean(lock && processIsAlive(lock.pid));
5025
5333
  }
5026
5334
 
5335
+ const QUEUE_LOCK_UNREADABLE_GRACE_MS = 30 * 1000;
5336
+ const QUEUE_LOCK_RECLAIM_STALE_MS = 10 * 1000;
5337
+
5338
+ // Decide whether an existing lock file still protects a runner. An unreadable
5339
+ // lock is normal for a moment while its creator writes it, so it only counts
5340
+ // as stale after a grace period.
5341
+ async function queueLockState(root, queue, now) {
5342
+ const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5343
+ let info;
5344
+ try { info = await stat(lockFile); } catch (error) {
5345
+ if (error?.code === 'ENOENT') return { present: false };
5346
+ throw error;
5347
+ }
5348
+ const lock = await readQueueLock(root, queue);
5349
+ if (!lock) return { present: true, lock: null, held: now - info.mtimeMs < QUEUE_LOCK_UNREADABLE_GRACE_MS, ownerAlive: false, reason: 'unreadable_lock' };
5350
+ const ownerAlive = queueLockOwnerAlive(lock);
5351
+ return { present: true, lock, held: Date.parse(lock.expiresAt) > now && ownerAlive, ownerAlive };
5352
+ }
5353
+
5027
5354
  async function acquireQueueLock(root, queue, leaseMs) {
5028
5355
  const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5029
5356
  const now = Date.now();
5030
- const existing = await readQueueLock(root, queue);
5031
- const existingOwnerAlive = queueLockOwnerAlive(existing);
5032
- if (existing && Date.parse(existing.expiresAt) > now && existingOwnerAlive) {
5033
- return { acquired: false, lock: existing };
5357
+ const state = await queueLockState(root, queue, now);
5358
+ if (state.present && state.held) return { acquired: false, lock: state.lock };
5359
+ let reclaimedLock = null;
5360
+ if (state.present) {
5361
+ // Reclaiming means deleting someone else's lock file. Serialize it with
5362
+ // an atomic mkdir so two runners cannot both delete-and-create, and
5363
+ // re-check the lock inside the critical section.
5364
+ const mutex = `${lockFile}.reclaim`;
5365
+ try {
5366
+ await mkdir(mutex);
5367
+ } catch (error) {
5368
+ if (error?.code !== 'EEXIST') throw error;
5369
+ const info = await stat(mutex).catch(() => null);
5370
+ if (info && now - info.mtimeMs > QUEUE_LOCK_RECLAIM_STALE_MS) await rmdir(mutex).catch(() => {});
5371
+ return { acquired: false, lock: state.lock };
5372
+ }
5373
+ try {
5374
+ const current = await queueLockState(root, queue, Date.now());
5375
+ if (current.present && current.held) return { acquired: false, lock: current.lock };
5376
+ if (current.present) {
5377
+ if (current.lock?.acquiredAt !== state.lock?.acquiredAt || current.lock?.pid !== state.lock?.pid) {
5378
+ return { acquired: false, lock: current.lock };
5379
+ }
5380
+ await rm(lockFile, { force: true });
5381
+ reclaimedLock = {
5382
+ lock: current.lock,
5383
+ reason: current.reason ?? (current.ownerAlive ? 'expired_lease' : 'dead_owner_pid')
5384
+ };
5385
+ }
5386
+ return await createQueueLock(root, queue, leaseMs, reclaimedLock);
5387
+ } finally {
5388
+ await rmdir(mutex).catch(() => {});
5389
+ }
5034
5390
  }
5035
- if (existing) await rm(lockFile, { force: true });
5391
+ return createQueueLock(root, queue, leaseMs, null);
5392
+ }
5393
+
5394
+ async function createQueueLock(root, queue, leaseMs, reclaimedLock) {
5395
+ const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5396
+ const now = Date.now();
5036
5397
  const lock = {
5037
5398
  version: 1,
5038
5399
  queue,
@@ -5040,28 +5401,26 @@ async function acquireQueueLock(root, queue, leaseMs) {
5040
5401
  acquiredAt: new Date(now).toISOString(),
5041
5402
  expiresAt: new Date(now + leaseMs).toISOString()
5042
5403
  };
5043
- let handle = null;
5044
5404
  try {
5045
- handle = await open(lockFile, 'wx');
5046
- await handle.writeFile(`${JSON.stringify(lock, null, 2)}\n`);
5047
- return {
5048
- acquired: true,
5049
- lock,
5050
- reclaimedLock: existing ? {
5051
- lock: existing,
5052
- reason: existingOwnerAlive ? 'expired_lease' : 'dead_owner_pid'
5053
- } : null
5054
- };
5405
+ await writeJsonExclusive(lockFile, lock);
5406
+ return { acquired: true, lock, reclaimedLock };
5055
5407
  } catch (err) {
5056
5408
  if (err && err.code === 'EEXIST') {
5057
5409
  return { acquired: false, lock: await readQueueLock(root, queue) };
5058
5410
  }
5059
5411
  throw err;
5060
- } finally {
5061
- if (handle) await handle.close();
5062
5412
  }
5063
5413
  }
5064
5414
 
5415
+ // Extend a held lease while its runner is still working, so a long dispatch
5416
+ // is not mistaken for an abandoned one. Returns false once the lock is lost.
5417
+ async function renewQueueLock(root, queue, lock, leaseMs) {
5418
+ const current = await readQueueLock(root, queue);
5419
+ if (current?.pid !== lock.pid || current?.acquiredAt !== lock.acquiredAt) return false;
5420
+ await writeJson(path.join(queueDirFor(root, queue), 'queue.lock'), { ...current, expiresAt: new Date(Date.now() + leaseMs).toISOString(), renewedAt: new Date().toISOString() });
5421
+ return true;
5422
+ }
5423
+
5065
5424
  async function releaseQueueLock(root, queue, lock) {
5066
5425
  const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5067
5426
  const current = await readQueueLock(root, queue);
@@ -5077,7 +5436,9 @@ async function nextQueuedTaskFile(root, queue) {
5077
5436
  }
5078
5437
 
5079
5438
  async function findTaskFile(root, queue, taskId, subdirs = ['inbox', 'active', 'waiting', 'failed', 'done', 'canceled']) {
5080
- const wanted = taskId.endsWith('.json') ? taskId : `${taskId}.json`;
5439
+ // Task ids reach here from CLI flags; never let one escape the queue.
5440
+ const id = safeTaskId(String(taskId ?? '').replace(/\.json$/, ''));
5441
+ const wanted = `${id}.json`;
5081
5442
  for (const subdir of subdirs) {
5082
5443
  const file = path.join(queueSubdirFor(root, queue, subdir), wanted);
5083
5444
  if (await exists(file)) return { file, subdir };
@@ -5106,6 +5467,35 @@ export async function queuePeek(root, queue, options = {}) {
5106
5467
  return { queue: normalized, tasks };
5107
5468
  }
5108
5469
 
5470
+ // Ask a running dispatcher to stop: runCommand polls this marker and kills the
5471
+ // process group. Used when an operator takes a task out of active/.
5472
+ async function requestTaskStop(root, queue, taskId, reason) {
5473
+ await writeJson(path.join(taskRuntimeDirFor(root, queue, taskId), 'supersede_request.json'), {
5474
+ version: 1,
5475
+ requestedAt: new Date().toISOString(),
5476
+ activeTaskId: taskId,
5477
+ reason,
5478
+ kind: 'operator_stop',
5479
+ status: 'requested'
5480
+ });
5481
+ }
5482
+
5483
+ // A supersede marker only applies to the run it was written for. An operator
5484
+ // requeue or verified resume records supersedeClearedAt, and older markers are
5485
+ // discarded so the restarted task actually runs.
5486
+ async function currentSupersedeRequest(root, queue, task) {
5487
+ const file = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
5488
+ if (!(await exists(file))) return null;
5489
+ const request = await readJson(file).catch(() => ({}));
5490
+ const clearedAt = Date.parse(task.supersedeClearedAt ?? '');
5491
+ const requestedAt = Date.parse(request.requestedAt ?? '');
5492
+ if (Number.isFinite(clearedAt) && (!Number.isFinite(requestedAt) || requestedAt <= clearedAt)) {
5493
+ await rm(file, { force: true });
5494
+ return null;
5495
+ }
5496
+ return { file, request };
5497
+ }
5498
+
5109
5499
  export async function queueCancel(root, queue, taskId, options = {}) {
5110
5500
  const normalized = normalizeLoopId(queue);
5111
5501
  await ensureQueueDirs(root, normalized);
@@ -5113,6 +5503,9 @@ export async function queueCancel(root, queue, taskId, options = {}) {
5113
5503
  if (!found) throw new Error(`Task not found in cancelable state: ${taskId}`);
5114
5504
  const task = await readJson(found.file);
5115
5505
  const canceledFile = path.join(queueSubdirFor(root, normalized, 'canceled'), path.basename(found.file));
5506
+ // Move, then rewrite: the runner treats a missing active file as taken
5507
+ // over by an operator and will not write its own copy.
5508
+ await rename(found.file, canceledFile);
5116
5509
  await writeJson(canceledFile, {
5117
5510
  ...task,
5118
5511
  status: 'canceled',
@@ -5120,7 +5513,7 @@ export async function queueCancel(root, queue, taskId, options = {}) {
5120
5513
  canceledFrom: found.subdir,
5121
5514
  cancelReason: options.reason ?? null
5122
5515
  });
5123
- await rm(found.file, { force: true });
5516
+ if (found.subdir === 'active') await requestTaskStop(root, normalized, task.id, 'operator_cancel');
5124
5517
  return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, canceledFile) };
5125
5518
  }
5126
5519
 
@@ -5133,13 +5526,16 @@ export async function queueRequeue(root, queue, taskId, options = {}) {
5133
5526
  if (!found) throw new Error(`Task not found in requeueable state: ${taskId}`);
5134
5527
  const task = await readJson(found.file);
5135
5528
  const inboxFile = path.join(queueSubdirFor(root, normalized, 'inbox'), path.basename(found.file));
5529
+ if (found.subdir === 'active') await requestTaskStop(root, normalized, task.id, 'operator_requeue');
5530
+ await rename(found.file, inboxFile);
5531
+ const requeuedAt = new Date().toISOString();
5136
5532
  await writeJson(inboxFile, {
5137
5533
  ...task,
5138
5534
  status: 'queued',
5139
- requeuedAt: new Date().toISOString(),
5140
- requeuedFrom: found.subdir
5535
+ requeuedAt,
5536
+ requeuedFrom: found.subdir,
5537
+ supersedeClearedAt: requeuedAt
5141
5538
  });
5142
- await rm(found.file, { force: true });
5143
5539
  return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, inboxFile) };
5144
5540
  }
5145
5541
 
@@ -5715,11 +6111,27 @@ export async function queueRevisionPlan(root, queue, taskId, options = {}) {
5715
6111
  };
5716
6112
  }
5717
6113
 
6114
+ // A source task gets one live revision child. Re-running next/apply-plan
6115
+ // (for example after a timeout) must not enqueue the same revision twice;
6116
+ // a canceled child does not count.
6117
+ async function assertNoRevisionChild(root, queue, sourceTaskId, options = {}) {
6118
+ if (!sourceTaskId || options.force) return;
6119
+ for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed']) {
6120
+ for (const file of await listJson(queueSubdirFor(root, queue, subdir))) {
6121
+ const task = await readJson(path.join(queueSubdirFor(root, queue, subdir), file)).catch(() => null);
6122
+ if (task?.revisionOf === sourceTaskId) {
6123
+ throw new Error(`Revision of ${sourceTaskId} is already enqueued as ${task.id} (${subdir}). Use --force to enqueue another.`);
6124
+ }
6125
+ }
6126
+ }
6127
+ }
6128
+
5718
6129
  export async function queueRevisionNext(root, queue, taskId, options = {}) {
5719
6130
  const plan = await queueRevisionPlan(root, queue, taskId, options);
5720
6131
  if (!plan.revisionPolicyGuard.allowed) {
5721
6132
  throw new Error(`Revision guard blocked next round for ${taskId}: ${plan.revisionPolicyGuard.reasons.join('; ')}`);
5722
6133
  }
6134
+ await assertNoRevisionChild(root, plan.queue, plan.plannedTask.revisionOf, options);
5723
6135
  const enqueued = await enqueueTask(root, {
5724
6136
  queue: plan.queue,
5725
6137
  title: plan.plannedTask.title,
@@ -5774,6 +6186,7 @@ export async function queueRevisionApplyPlan(root, planPath, options = {}) {
5774
6186
  const reasons = plan.revisionPolicyGuard?.reasons?.join('; ') || 'plan canEnqueue=false';
5775
6187
  throw new Error(`Revision plan is blocked for ${plan.sourceTaskId ?? 'unknown source task'}: ${reasons}. Use --force to override.`);
5776
6188
  }
6189
+ await assertNoRevisionChild(root, normalized, plan.plannedTask.revisionOf ?? plan.sourceTaskId, options);
5777
6190
 
5778
6191
  const enqueued = await enqueueTask(root, {
5779
6192
  queue: normalized,
@@ -6529,6 +6942,28 @@ export async function codeWorktreeInspect(root, queue, options = {}) {
6529
6942
  };
6530
6943
  }
6531
6944
 
6945
+ // The complete pending change of a worktree: tracked edits plus every
6946
+ // untracked file as a real new-file diff, so an export can be applied and a
6947
+ // cleanup can prove nothing was left behind.
6948
+ async function worktreePendingPatch(worktreePath) {
6949
+ const tracked = await runCommand('git diff --binary HEAD', { cwd: worktreePath, timeoutMs: 120000 });
6950
+ if (tracked.exitCode !== 0) throw new Error(`Unable to read worktree patch: ${trimTail(tracked.stderr || tracked.stdout, 1200)}`);
6951
+ const listing = await runCommand('git ls-files -z --others --exclude-standard', { cwd: worktreePath, timeoutMs: 30000 });
6952
+ if (listing.exitCode !== 0) throw new Error(`Unable to list untracked files: ${trimTail(listing.stderr || listing.stdout, 1200)}`);
6953
+ const untrackedFiles = listing.stdout.split('\0').filter(Boolean);
6954
+ let untrackedPatch = '';
6955
+ for (const file of untrackedFiles) {
6956
+ // --no-index exits 1 when the files differ, which is always the case here.
6957
+ const added = await runCommand(`git diff --no-index --binary -- /dev/null ${shellQuote(file)}`, { cwd: worktreePath, timeoutMs: 120000 });
6958
+ if (added.exitCode !== 1 || !added.stdout.startsWith('diff --git ')) {
6959
+ throw new Error(`Unable to export untracked file ${file}: ${trimTail(added.stderr || added.stdout, 1200)}`);
6960
+ }
6961
+ untrackedPatch += added.stdout.endsWith('\n') ? added.stdout : `${added.stdout}\n`;
6962
+ }
6963
+ const patch = `${tracked.stdout}${untrackedPatch}`;
6964
+ return { patch, untrackedFiles, contentSha256: createHash('sha256').update(patch).digest('hex') };
6965
+ }
6966
+
6532
6967
  export async function codeWorktreeDiff(root, queue, options = {}) {
6533
6968
  const normalized = normalizeLoopId(queue);
6534
6969
  const found = await findCodeWorktreeRun(root, normalized, options);
@@ -6554,7 +6989,8 @@ export async function codeWorktreeDiff(root, queue, options = {}) {
6554
6989
  diffStat: trimTail(diffStat.stdout, 12000),
6555
6990
  diffNameStatus: trimTail(diffNameStatus.stdout, 12000),
6556
6991
  untracked: trimTail(untracked.stdout, 12000),
6557
- patch: trimTail(patch.stdout, 60000)
6992
+ patch: trimTail(patch.stdout, 60000),
6993
+ patchTruncated: patch.stdout.length > 60000
6558
6994
  };
6559
6995
  }
6560
6996
 
@@ -6566,6 +7002,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6566
7002
  throw new Error(`Patch export already exists: ${path.relative(root, patchFile)}. Use --force to overwrite.`);
6567
7003
  }
6568
7004
  const manifestFile = `${patchFile}.json`;
7005
+ // The display diff above is truncated for readability; the export must be
7006
+ // the complete change, including untracked files, or cleanup would lose work.
7007
+ const pending = await worktreePendingPatch(diff.worktreePath);
6569
7008
  const header = [
6570
7009
  `# loop-engineering patch export`,
6571
7010
  `# queue: ${normalized}`,
@@ -6576,9 +7015,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6576
7015
  `# exportedAt: ${new Date().toISOString()}`,
6577
7016
  ''
6578
7017
  ].join('\n');
6579
- const patchBody = diff.patch || '';
6580
- const untrackedBlock = diff.untracked
6581
- ? `\n# Untracked files from worktree:\n${diff.untracked.split('\n').filter(Boolean).map((line) => `# ${line}`).join('\n')}\n`
7018
+ const patchBody = pending.patch;
7019
+ const untrackedBlock = pending.untrackedFiles.length
7020
+ ? `\n# Untracked files from worktree (included above as new-file diffs):\n${pending.untrackedFiles.map((line) => `# ${line}`).join('\n')}\n`
6582
7021
  : '';
6583
7022
  const patchContent = `${header}${patchBody}${untrackedBlock}`;
6584
7023
  await mkdir(path.dirname(patchFile), { recursive: true });
@@ -6595,6 +7034,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6595
7034
  worktree: diff.worktree,
6596
7035
  patchFile: path.relative(root, patchFile),
6597
7036
  patchBytes: Buffer.byteLength(patchContent),
7037
+ complete: true,
7038
+ contentSha256: pending.contentSha256,
7039
+ untrackedIncluded: pending.untrackedFiles.length,
6598
7040
  diffStat: diff.diffStat,
6599
7041
  diffNameStatus: diff.diffNameStatus,
6600
7042
  untracked: diff.untracked
@@ -8379,6 +8821,13 @@ async function cleanupGate(root, queue, item) {
8379
8821
  if (!(await exists(reviewFile))) return { ok: false, reason: 'dirty_without_review_bundle' };
8380
8822
  const reviewJson = `${reviewFile}.json`;
8381
8823
  if (!(await exists(reviewJson))) return { ok: false, reason: 'dirty_without_review_json' };
8824
+ // A dirty worktree is force-removed only when its export is known to be
8825
+ // complete and the worktree has not changed since that export.
8826
+ const manifestFile = path.resolve(root, safeRelativePath(`${item.exportedPatchFile}.json`, 'patch manifest'));
8827
+ const manifest = await exists(manifestFile) ? await readJson(manifestFile).catch(() => null) : null;
8828
+ if (manifest?.complete !== true || typeof manifest.contentSha256 !== 'string') return { ok: false, reason: 'dirty_export_incomplete_reexport_required' };
8829
+ const current = await worktreePendingPatch(resolveWorktreePath(root, item.worktree.path));
8830
+ if (current.contentSha256 !== manifest.contentSha256) return { ok: false, reason: 'dirty_worktree_changed_since_export' };
8382
8831
  }
8383
8832
  return { ok: true, reason: null };
8384
8833
  }
@@ -8425,7 +8874,7 @@ function extractGitPatch(rawPatch) {
8425
8874
  if (start === -1) return '';
8426
8875
  let end = lines.length;
8427
8876
  for (let i = start; i < lines.length; i++) {
8428
- if (lines[i] === '# Untracked files from worktree:') {
8877
+ if (lines[i].startsWith('# Untracked files from worktree')) {
8429
8878
  end = i;
8430
8879
  break;
8431
8880
  }
@@ -8462,9 +8911,35 @@ async function runPatchApplyCheck(root, patch, timeoutMs) {
8462
8911
  }
8463
8912
  }
8464
8913
 
8914
+ // git C-quotes paths with non-ASCII or special characters, e.g.
8915
+ // "a/\351\241\271.txt"; decode the escapes (octal bytes are UTF-8).
8916
+ function unquoteGitPath(quoted) {
8917
+ const bytes = [];
8918
+ const simple = { n: 10, t: 9, r: 13, b: 8, f: 12, a: 7, v: 11, '"': 34, '\\': 92 };
8919
+ for (let i = 1; i < quoted.length - 1; i++) {
8920
+ const char = quoted[i];
8921
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue; }
8922
+ const next = quoted[i + 1];
8923
+ if (/[0-7]/.test(next)) { bytes.push(Number.parseInt(quoted.slice(i + 1, i + 4), 8)); i += 3; }
8924
+ else { bytes.push(simple[next] ?? next.charCodeAt(0)); i += 1; }
8925
+ }
8926
+ return Buffer.from(bytes).toString('utf8');
8927
+ }
8928
+
8465
8929
  function diffFilesFromPatch(patch) {
8466
8930
  const files = [];
8931
+ const token = '("(?:[^"\\\\]|\\\\.)*"|\\S+)';
8932
+ const header = new RegExp(`^diff --git ${token} ${token}$`);
8933
+ const strip = (value) => {
8934
+ const unquoted = value.startsWith('"') ? unquoteGitPath(value) : value;
8935
+ return unquoted.replace(/^[ab]\//, '');
8936
+ };
8467
8937
  for (const line of patch.split('\n')) {
8938
+ const quoted = header.exec(line);
8939
+ if (quoted && (quoted[1].startsWith('"') || quoted[2].startsWith('"'))) {
8940
+ files.push({ oldPath: strip(quoted[1]), newPath: strip(quoted[2]) });
8941
+ continue;
8942
+ }
8468
8943
  const match = /^diff --git a\/(.+?) b\/(.+)$/.exec(line);
8469
8944
  if (match) files.push({ oldPath: match[1], newPath: match[2] });
8470
8945
  }
@@ -9050,15 +9525,44 @@ async function recoverStaleActive(root, queue, staleActiveMs) {
9050
9525
  return recovered;
9051
9526
  }
9052
9527
 
9053
- async function recoverOrphanActive(root, queue, recoveryReason = 'queue_lock_reacquired_with_active_task') {
9528
+ const DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS = 3;
9529
+
9530
+ async function recoverOrphanActive(root, queue, recoveryReason = 'queue_lock_reacquired_with_active_task', options = {}) {
9054
9531
  const activeDir = queueSubdirFor(root, queue, 'active');
9055
9532
  const inboxDir = queueSubdirFor(root, queue, 'inbox');
9056
9533
  const files = await listJson(activeDir);
9057
9534
  const recovered = [];
9535
+ const maxAttempts = Number(options.retry?.orphanRecoveryMaxAttempts ?? DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS);
9058
9536
  for (const file of files) {
9059
9537
  const activeFile = path.join(activeDir, file);
9060
- const task = await readJson(activeFile);
9538
+ let task;
9539
+ try {
9540
+ task = await readJson(activeFile);
9541
+ } catch (error) {
9542
+ const quarantined = await quarantineQueueFile(root, queue, activeFile, `unreadable active task: ${error instanceof Error ? error.message : String(error)}`);
9543
+ recovered.push({ taskId: null, from: path.relative(root, activeFile), quarantined, outcome: 'quarantined_unreadable' });
9544
+ continue;
9545
+ }
9546
+ // A copy that already reached a terminal or waiting state was re-created
9547
+ // by a late writer; running it again would repeat finished work.
9548
+ let settledElsewhere = null;
9549
+ for (const subdir of ['done', 'failed', 'canceled', 'waiting']) {
9550
+ if (await exists(path.join(queueSubdirFor(root, queue, subdir), file))) { settledElsewhere = subdir; break; }
9551
+ }
9552
+ if (settledElsewhere) {
9553
+ const quarantined = await quarantineQueueFile(root, queue, activeFile, `stale active copy; task already in ${settledElsewhere}/`);
9554
+ recovered.push({ taskId: task.id, from: path.relative(root, activeFile), quarantined, outcome: 'quarantined_duplicate', settledIn: settledElsewhere });
9555
+ continue;
9556
+ }
9061
9557
  const recoveredAt = new Date().toISOString();
9558
+ // A task that keeps taking its runner down must not be replayed forever.
9559
+ if ((task.orphanRecoveryCount ?? 0) >= maxAttempts) {
9560
+ const failedFile = path.join(queueSubdirFor(root, queue, 'failed'), file);
9561
+ await rename(activeFile, failedFile);
9562
+ await writeJson(failedFile, { ...task, status: 'orphan_recovery_exhausted', orphanRecoveryExhaustedAt: recoveredAt, recoveryReason });
9563
+ recovered.push({ taskId: task.id, from: path.relative(root, activeFile), file: path.relative(root, failedFile), recoveredAt, outcome: 'orphan_recovery_exhausted' });
9564
+ continue;
9565
+ }
9062
9566
  const inboxFile = path.join(inboxDir, file);
9063
9567
  // Move first so a crash cannot leave duplicate active/inbox copies.
9064
9568
  await rename(activeFile, inboxFile);
@@ -9120,117 +9624,13 @@ function buildQueueEnv(root, queue, task, taskFile, runId, extra = {}) {
9120
9624
  };
9121
9625
  }
9122
9626
 
9123
- const DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS = [
9124
- 'INSTALL_FAILED_USER_RESTRICTED',
9125
- 'device unauthorized',
9126
- 'unauthorized',
9127
- 'offline',
9128
- 'more than one device',
9129
- 'no devices/emulators found',
9130
- 'Permission denied',
9131
- 'Operation not permitted',
9132
- 'user restricted',
9133
- 'requires human',
9134
- 'needs human',
9135
- '需要人工',
9136
- '需要用户确认',
9137
- '等待人工',
9138
- '权限未开',
9139
- '用户取消',
9140
- '用户限制'
9141
- ];
9142
-
9143
- const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
9144
- { category: 'incomplete_turn', pattern: '"kind": "incomplete_turn"' },
9145
- { category: 'incomplete_turn', pattern: '"livenessState": "abandoned"' },
9146
- { category: 'incomplete_turn', pattern: 'stopped before confirming the turn was complete' },
9147
- // The OpenClaw embedded runner injects a recovery prompt when an assistant
9148
- // turn completes its tool calls without a user-visible answer. A dispatch
9149
- // that exits non-zero with this signature hit a session protocol failure,
9150
- // not a task defect: classify it as a recoverable incomplete turn so the
9151
- // runtime recovery path rotates the worker session and resumes.
9152
- { category: 'incomplete_turn', pattern: 'did not produce a user-visible answer', nonZeroOnly: true },
9153
- // OpenClaw closes websocket admission while the Gateway drains for a
9154
- // restart. A worker launched inside that short window receives HTTP 503
9155
- // before task execution begins. Exact non-zero admission/drain signatures
9156
- // are runtime interruptions, not development failures.
9157
- { category: 'gateway_restart', pattern: 'gateway websocket admission closed', nonZeroOnly: true },
9158
- { category: 'gateway_restart', pattern: 'gateway is draining for restart', nonZeroOnly: true },
9159
- { category: 'gateway_restart', pattern: 'unavailable during gateway restart', nonZeroOnly: true },
9160
- { category: 'compaction_timeout', pattern: 'compaction timed out' },
9161
- { category: 'compaction_timeout', pattern: 'transcript compaction failed' },
9162
- { category: 'transport_error', pattern: 'connection reset' },
9163
- { category: 'transport_error', pattern: 'socket hang up' },
9164
- { category: 'transport_error', pattern: 'network error' },
9165
- { category: 'rate_limit', pattern: 'rate limit' }
9166
- ];
9167
-
9168
- export function dispatchFailureClassification(result, retry = {}) {
9169
- if (!result) {
9170
- return {
9171
- category: 'ok',
9172
- requiresHumanAction: false,
9173
- matchedPattern: null
9174
- };
9175
- }
9176
- // Some embedded runtimes exit their wrapper successfully after the model
9177
- // turn itself was abandoned. Inspect the structured trailer before trusting
9178
- // exitCode=0 or the queue may accept partial work and replay a stale gate.
9179
- const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`.toLowerCase();
9180
- const runtimePatterns = retry.recoverableRuntimePatterns ?? DEFAULT_RECOVERABLE_RUNTIME_PATTERNS;
9181
- const runtimeMatch = runtimePatterns.find((entry) => {
9182
- const pattern = typeof entry === 'string' ? entry : entry.pattern;
9183
- const nonZeroOnly = typeof entry === 'object' && entry !== null && entry.nonZeroOnly === true;
9184
- return (!nonZeroOnly || result.exitCode !== 0)
9185
- && output.includes(String(pattern ?? entry).toLowerCase());
9186
- });
9187
- if (runtimeMatch) {
9188
- return {
9189
- category: runtimeMatch.category ?? 'runtime_interruption',
9190
- requiresHumanAction: false,
9191
- recoverableRuntime: true,
9192
- matchedPattern: runtimeMatch.pattern ?? runtimeMatch
9193
- };
9194
- }
9195
- if (result.exitCode === 0) {
9196
- return {
9197
- category: 'ok',
9198
- requiresHumanAction: false,
9199
- matchedPattern: null
9200
- };
9201
- }
9202
- if (result.timedOut) {
9203
- return {
9204
- category: 'timeout',
9205
- requiresHumanAction: false,
9206
- recoverableRuntime: true,
9207
- matchedPattern: null
9208
- };
9209
- }
9210
- const patterns = retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS;
9211
- const matched = patterns.find((pattern) => output.includes(pattern.toLowerCase()));
9212
- if (matched) {
9213
- return {
9214
- category: 'requires_human_action',
9215
- requiresHumanAction: true,
9216
- recoverableRuntime: false,
9217
- matchedPattern: matched
9218
- };
9219
- }
9220
- return {
9221
- category: 'retryable_failure',
9222
- requiresHumanAction: false,
9223
- recoverableRuntime: false,
9224
- matchedPattern: null
9225
- };
9226
- }
9227
-
9228
9627
  function shouldRetryDispatch(result, retry, attempt) {
9229
9628
  const maxAttempts = retry?.maxAttempts ?? 1;
9230
9629
  if (attempt >= maxAttempts) return false;
9231
9630
  if (!result || result.exitCode === 0) return false;
9232
9631
  if (result.canceled) return false;
9233
- if (dispatchFailureClassification(result, retry).requiresHumanAction) return false;
9632
+ const classification = dispatchFailureClassification(result, retry);
9633
+ if (classification.requiresHumanAction || classification.recoverableRuntime) return false;
9234
9634
  const retryExitCodes = retry?.retryExitCodes;
9235
9635
  return !retryExitCodes || retryExitCodes.includes(result.exitCode);
9236
9636
  }
@@ -9331,6 +9731,8 @@ async function runDispatchWithRetry(root, options, queue, task, activeFile, runI
9331
9731
  cwd: runContext.cwd ?? root,
9332
9732
  env: {
9333
9733
  ...buildQueueEnv(root, queue, task, activeFile, runId, runContext.env ?? {}),
9734
+ ...(runContext.env?.LOOP_WORKER_OUTPUT_PREFIX ? { LOOP_WORKER_OUTPUT_PREFIX: runContext.env.LOOP_WORKER_OUTPUT_PREFIX + '.attempt' + attempt } : {}),
9735
+ LOOP_DISPATCH_RETRY_JSON: JSON.stringify(retry),
9334
9736
  LOOP_ATTEMPT: String(attempt),
9335
9737
  LOOP_MAX_ATTEMPTS: String(maxAttempts)
9336
9738
  },
@@ -9361,7 +9763,11 @@ async function runDispatchWithRetry(root, options, queue, task, activeFile, runI
9361
9763
  failureCategory: failureClassification.category,
9362
9764
  matchedPattern: failureClassification.matchedPattern
9363
9765
  });
9364
- if (!shouldRetryDispatch(result, retry, attempt)) break;
9766
+ // A handoff must be adjudicated before any retry, including nonzero exits.
9767
+ if (await exists(runContext.env?.LOOP_CONTEXT_HANDOFF_FILE ?? '') || !shouldRetryDispatch(result, retry, attempt)) break;
9768
+ // A checkpoint may precede its handoff. Reuse final judgement's effective
9769
+ // review selection so resolved historical blockers do not veto retries.
9770
+ if (await runContext.hasBlockingCheckpoints?.()) break;
9365
9771
  runContext.progress?.emit('dispatch', 'retry_wait', `Waiting ${retryDelayMs}ms before retry`, {
9366
9772
  attempt,
9367
9773
  retryDelayMs
@@ -9392,10 +9798,27 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
9392
9798
  const worktreeDir = path.join(baseDir, shortTask);
9393
9799
  const prefix = sanitizeBranchSegment(config.branchPrefix ?? `loop/${queue}`);
9394
9800
  const branch = `${prefix}/${shortTask}`;
9395
- const add = await runCommand(`git worktree add -b ${shellQuote(branch)} ${shellQuote(worktreeDir)} HEAD`, {
9396
- cwd: root,
9397
- timeoutMs: config.setupTimeoutMs ?? 120000
9398
- });
9801
+ const setupTimeoutMs = config.setupTimeoutMs ?? 120000;
9802
+ // A requeued task (runtime recovery, project continuation, operator
9803
+ // requeue) keeps its id, so its branch and worktree may already exist.
9804
+ // Continue in them instead of failing on `git worktree add -b`.
9805
+ let add;
9806
+ let reused = false;
9807
+ if (await exists(worktreeDir)) {
9808
+ const current = await runCommand('git rev-parse --abbrev-ref HEAD', { cwd: worktreeDir, timeoutMs: 30000 });
9809
+ if (current.exitCode === 0 && current.stdout.trim() === branch) {
9810
+ add = current;
9811
+ reused = true;
9812
+ } else {
9813
+ add = { ...current, exitCode: current.exitCode || 1, stderr: `${current.stderr}Existing ${path.relative(root, worktreeDir)} is not a worktree of ${branch}; refusing to reuse it.` };
9814
+ }
9815
+ } else {
9816
+ await runCommand('git worktree prune', { cwd: root, timeoutMs: 30000 });
9817
+ const branchExists = (await runCommand(`git rev-parse --verify --quiet ${shellQuote(`refs/heads/${branch}`)}`, { cwd: root, timeoutMs: 30000 })).exitCode === 0;
9818
+ add = branchExists
9819
+ ? await runCommand(`git worktree add ${shellQuote(worktreeDir)} ${shellQuote(branch)}`, { cwd: root, timeoutMs: setupTimeoutMs })
9820
+ : await runCommand(`git worktree add -b ${shellQuote(branch)} ${shellQuote(worktreeDir)} HEAD`, { cwd: root, timeoutMs: setupTimeoutMs });
9821
+ }
9399
9822
  const head = add.exitCode === 0
9400
9823
  ? await runCommand('git rev-parse HEAD', { cwd: worktreeDir, timeoutMs: 30000 })
9401
9824
  : null;
@@ -9405,6 +9828,7 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
9405
9828
  pathRel: path.relative(root, worktreeDir),
9406
9829
  branch,
9407
9830
  setup: compactCommandResult(add),
9831
+ reused,
9408
9832
  head: head?.exitCode === 0 ? head.stdout.trim() : null,
9409
9833
  runId
9410
9834
  };
@@ -9466,6 +9890,7 @@ async function runPreflight(root, config, timeoutMs) {
9466
9890
 
9467
9891
  export async function runQueueOnce(root, options) {
9468
9892
  const queue = normalizeLoopId(options.queue);
9893
+ const budgetPolicy = contextPolicy(options.retry);
9469
9894
  await ensureQueueDirs(root, queue);
9470
9895
  await reconcileProjectGates(root, { queue });
9471
9896
  let progressTask = null;
@@ -9507,6 +9932,13 @@ export async function runQueueOnce(root, options) {
9507
9932
  };
9508
9933
  }
9509
9934
 
9935
+ // Renew the lease while this runner works, so preflight, retries and
9936
+ // verification that outlast leaseMs are not reclaimed and re-executed.
9937
+ const leaseRenewal = setInterval(() => {
9938
+ renewQueueLock(root, queue, lockResult.lock, leaseMs).catch(() => {});
9939
+ }, Math.max(250, Math.floor(leaseMs / 3)));
9940
+ leaseRenewal.unref();
9941
+
9510
9942
  try {
9511
9943
  // Holding this newly acquired lock proves no previous runner owns a valid
9512
9944
  // queue lease. Any task left in active/ is therefore an orphan from an
@@ -9515,7 +9947,7 @@ export async function runQueueOnce(root, options) {
9515
9947
  const recoveryReason = lockResult.reclaimedLock?.reason === 'dead_owner_pid'
9516
9948
  ? 'dead_queue_lock_owner_pid'
9517
9949
  : 'queue_lock_reacquired_with_active_task';
9518
- const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason);
9950
+ const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason, options);
9519
9951
  if (orphanRecovered.length > 0) {
9520
9952
  progress.emit('queue', 'orphan_recovered', `Recovered ${orphanRecovered.length} orphan active task(s)`, {
9521
9953
  queue,
@@ -9530,7 +9962,21 @@ export async function runQueueOnce(root, options) {
9530
9962
  count: staleRecovered.length
9531
9963
  });
9532
9964
  }
9533
- const inboxFile = await nextQueuedTaskFile(root, queue);
9965
+ let inboxFile = await nextQueuedTaskFile(root, queue);
9966
+ let task = null;
9967
+ const quarantined = [];
9968
+ while (inboxFile) {
9969
+ try {
9970
+ task = await readJson(inboxFile);
9971
+ break;
9972
+ } catch (error) {
9973
+ quarantined.push(await quarantineQueueFile(root, queue, inboxFile, `unreadable queued task: ${error instanceof Error ? error.message : String(error)}`));
9974
+ inboxFile = await nextQueuedTaskFile(root, queue);
9975
+ }
9976
+ }
9977
+ if (quarantined.length) {
9978
+ progress.emit('queue', 'quarantined', `Quarantined ${quarantined.length} unreadable queued task file(s)`, { queue, files: quarantined });
9979
+ }
9534
9980
  if (!inboxFile) {
9535
9981
  progress.emit('queue', 'empty', `Queue ${queue} has no queued tasks`, {
9536
9982
  queue
@@ -9546,7 +9992,6 @@ export async function runQueueOnce(root, options) {
9546
9992
  };
9547
9993
  }
9548
9994
 
9549
- const task = await readJson(inboxFile);
9550
9995
  progressTask = task;
9551
9996
  const activeFile = path.join(queueSubdirFor(root, queue, 'active'), path.basename(inboxFile));
9552
9997
  await rename(inboxFile, activeFile);
@@ -9577,6 +10022,9 @@ export async function runQueueOnce(root, options) {
9577
10022
  let acceptanceReviews = null;
9578
10023
  let finalJudgement = null;
9579
10024
  let revisionRequest = null;
10025
+ let contextUsage = null;
10026
+ let contextHandoff = null;
10027
+ const contextPrefix = path.join(taskRuntimeDirFor(root, queue, task.id), runId);
9580
10028
 
9581
10029
  try {
9582
10030
  taskContract = await writeTaskContract(root, queue, task, {
@@ -9621,8 +10069,9 @@ export async function runQueueOnce(root, options) {
9621
10069
  } else {
9622
10070
  progress.emit('preflight', 'skipped', 'No preflight configured');
9623
10071
  }
10072
+ const supersede = await currentSupersedeRequest(root, queue, task);
9624
10073
  const supersedeFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
9625
- if (await exists(supersedeFile)) {
10074
+ if (supersede) {
9626
10075
  finalStatus = 'superseded';
9627
10076
  progress.emit('queue', 'superseded', 'A newer loop request replaced this task at a safe checkpoint', {
9628
10077
  taskId: task.id,
@@ -9633,10 +10082,17 @@ export async function runQueueOnce(root, options) {
9633
10082
  exitCode = 2;
9634
10083
  } else {
9635
10084
  const humanInputContextFile = await prepareHumanInputContext(root, queue, task.id);
10085
+ const resumeFile = contextPrefix + '.resume.json';
10086
+ await writeJson(resumeFile, { version: 1, workspaceRoot: root, taskId: task.id, generation: task.runtimeSessionGeneration ?? 0, previousRun: task.runPath ?? null, previousHandoff: task.contextHandoffFile ?? null, contract: taskContract.file, devPlan: devPlan.file, acceptancePlan: acceptancePlan.file, checkpointsDir: devPlan.checkpointsDir, instruction: 'Read only the latest relevant checkpoint and handoff. Verify pending external action outcomes before replay; preserve authority and amendments.' });
9636
10087
  const runContext = {
9637
10088
  env: {
9638
10089
  ...taskPlanningEnv(root, taskContract, acceptancePlan, devPlan),
9639
10090
  LOOP_SESSION_GENERATION: String(task.runtimeSessionGeneration ?? 0),
10091
+ LOOP_CONTEXT_POLICY: JSON.stringify(budgetPolicy),
10092
+ LOOP_RESUME_FILE: resumeFile,
10093
+ LOOP_CONTEXT_HANDOFF_FILE: contextPrefix + '.handoff.json',
10094
+ LOOP_CONTEXT_USAGE_FILE: contextPrefix + '.usage.json',
10095
+ LOOP_WORKER_OUTPUT_PREFIX: contextPrefix,
9640
10096
  LOOP_EXECUTION_TARGET_JSON: options.executionTarget
9641
10097
  ? JSON.stringify(options.executionTarget)
9642
10098
  : '',
@@ -9677,12 +10133,40 @@ export async function runQueueOnce(root, options) {
9677
10133
  finalStatus = 'superseded';
9678
10134
  }
9679
10135
  if (finalStatus === 'unknown') {
9680
- dispatchAttempts = await runDispatchWithRetry(root, options, queue, task, activeFile, runId, timeoutMs, runContext);
10136
+ dispatchAttempts = await runDispatchWithRetry(root, options, queue, task, activeFile, runId, timeoutMs, {
10137
+ ...runContext,
10138
+ hasBlockingCheckpoints: async () => {
10139
+ const reviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan);
10140
+ return selectEffectiveAcceptanceReviews(devPlan.plan, reviews, taskContract.contract)
10141
+ .some((review) => review.status === 'blocked');
10142
+ }
10143
+ });
9681
10144
  dispatch = dispatchAttempts[dispatchAttempts.length - 1]?.result ?? null;
9682
10145
  await destroyConsumedHumanInputSecrets(root, queue, task.id);
9683
- const dispatchClassification = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10146
+ let dispatchClassification = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10147
+ const usageReport = await readBoundedJson(contextPrefix + '.usage.json');
10148
+ if (usageReport?.taskId === task.id && usageReport.runId === runId && usageReport.generation === (task.runtimeSessionGeneration ?? 0) && usageReport.attempt === dispatchAttempts.at(-1)?.attempt) contextUsage = usageReport.usage;
10149
+ const handoff = await readBoundedJson(contextPrefix + '.handoff.json');
10150
+ if (!dispatch?.canceled && await exists(contextPrefix + '.handoff.json')) {
10151
+ const handoffValid = validHandoff(handoff, { taskId: task.id, runId, generation: task.runtimeSessionGeneration ?? 0, attempt: dispatchAttempts.at(-1)?.attempt });
10152
+ const proof = handoffValid ? await handoffCheckpoint(handoff, { root, checkpointsDir: path.join(root, devPlan.checkpointsDir), taskId: task.id, runId }) : { valid: false };
10153
+ if (!handoffValid || !proof.valid) {
10154
+ finalStatus = 'runtime_blocked';
10155
+ } else {
10156
+ contextHandoff = handoff;
10157
+ if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
10158
+ else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
10159
+ dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
10160
+ dispatchAttempts[dispatchAttempts.length - 1].failureClassification = dispatchClassification;
10161
+ }
10162
+ }
10163
+ }
9684
10164
  if (dispatch?.canceled) {
9685
10165
  finalStatus = 'superseded';
10166
+ } else if (finalStatus !== 'unknown') {
10167
+ // Invalid handoffs or unresolved authority/actions fail closed.
10168
+ } else if (dispatchClassification?.requiresHumanAction) {
10169
+ finalStatus = 'needs_human_input';
9686
10170
  } else if (dispatchClassification?.recoverableRuntime) {
9687
10171
  const recoveryCount = Number(task.runtimeRecoveryCount ?? 0);
9688
10172
  const recoveryMax = Number(options.retry?.runtimeRecoveryMaxAttempts ?? 2);
@@ -9718,7 +10202,7 @@ export async function runQueueOnce(root, options) {
9718
10202
  });
9719
10203
  if (finalStatus === 'superseded') {
9720
10204
  const requestFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
9721
- const request = await readJson(requestFile);
10205
+ const request = await readJson(requestFile).catch(() => ({}));
9722
10206
  acceptanceReviews = { count: 0, accepted: 0, revise: 0, blocked: 0, reviews: [] };
9723
10207
  const judgementFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'final_judgement.json');
9724
10208
  const judgement = {
@@ -9817,22 +10301,36 @@ export async function runQueueOnce(root, options) {
9817
10301
  completedTask.projectContinuedAt = finishedAt;
9818
10302
  completedTask.projectContinuationCount = (task.projectContinuationCount ?? 0) + 1;
9819
10303
  completedTask.runtimeRecoveryCount = 0;
9820
- const sessionMaxTicks = Math.max(1, Number(options.retry?.sessionMaxTicks ?? 10));
9821
- if (completedTask.projectContinuationCount % sessionMaxTicks === 0) {
10304
+ completedTask.sessionTickCount = Number(task.sessionTickCount ?? 0) + 1;
10305
+ const rotation = contextRotation(contextUsage, completedTask.sessionTickCount, budgetPolicy);
10306
+ completedTask.contextBudget = rotation;
10307
+ if (rotation.rotate) {
9822
10308
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10309
+ completedTask.sessionTickCount = 0;
9823
10310
  completedTask.sessionRotatedAt = finishedAt;
9824
- completedTask.sessionRotationReason = 'bounded_tick_limit';
10311
+ completedTask.sessionRotationReason = rotation.reason;
9825
10312
  }
9826
10313
  }
9827
10314
  if (finalStatus === 'runtime_interrupted') {
9828
10315
  completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + 1;
9829
10316
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10317
+ completedTask.sessionTickCount = 0;
10318
+ if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
9830
10319
  completedTask.runtimeInterruptedAt = finishedAt;
9831
10320
  completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
9832
10321
  }
9833
10322
  const completedFile = path.join(destination, path.basename(activeFile));
9834
- await writeJson(completedFile, completedTask);
9835
- await rm(activeFile, { force: true });
10323
+ // Claim the active file by moving it. If an operator canceled or parked
10324
+ // the task meanwhile, the file is gone and their copy stays authoritative
10325
+ // instead of a second copy being written to done/ or failed/.
10326
+ let movedByOperator = false;
10327
+ try {
10328
+ await rename(activeFile, completedFile);
10329
+ } catch (error) {
10330
+ if (error?.code !== 'ENOENT') throw error;
10331
+ movedByOperator = true;
10332
+ }
10333
+ if (!movedByOperator) await writeJson(completedFile, completedTask);
9836
10334
 
9837
10335
  const run = {
9838
10336
  version: 2,
@@ -9843,7 +10341,9 @@ export async function runQueueOnce(root, options) {
9843
10341
  startedAt,
9844
10342
  finishedAt,
9845
10343
  status: finalStatus,
10344
+ ...(movedByOperator ? { movedByOperator: true } : {}),
9846
10345
  retry: options.retry ?? null,
10346
+ contextBudget: { policy: budgetPolicy, usage: contextUsage, handoff: contextHandoff ? path.relative(root, contextPrefix + '.handoff.json') : null },
9847
10347
  taskContract: taskContract ? {
9848
10348
  path: taskContract.file,
9849
10349
  riskLevel: taskContract.contract.risk_level,
@@ -9899,6 +10399,7 @@ export async function runQueueOnce(root, options) {
9899
10399
  branch: worktree.branch,
9900
10400
  head: worktree.head,
9901
10401
  setup: worktree.setup,
10402
+ reused: Boolean(worktree.reused),
9902
10403
  inspection: worktreeInspection
9903
10404
  } : null,
9904
10405
  verification,
@@ -9918,21 +10419,24 @@ export async function runQueueOnce(root, options) {
9918
10419
  }
9919
10420
  await writeJson(runPath, run);
9920
10421
 
9921
- if (options.notifyCommand) {
10422
+ if (options.notifyCommand && !movedByOperator) {
9922
10423
  const detail = dispatch?.stdout || dispatch?.stderr || preflight?.stdout || preflight?.stderr || '';
10424
+ // NUL cannot travel in a command line; drop it rather than lose the
10425
+ // notification and everything after it.
9923
10426
  const message = [
9924
10427
  `Loop queue task ${finalStatus}: ${task.title}`,
9925
10428
  `queue: ${queue}`,
9926
10429
  `run: ${run.runPath}`,
9927
10430
  trimTail(detail, 1200)
9928
- ].filter(Boolean).join('\n');
9929
- await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
10431
+ ].filter(Boolean).join('\n').replace(/\0/g, '');
10432
+ run.notification = compactCommandResult(await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
9930
10433
  cwd: root,
9931
10434
  timeoutMs: 60 * 1000
9932
- });
10435
+ }));
10436
+ await writeJson(runPath, run);
9933
10437
  }
9934
10438
 
9935
- if (finalStatus === 'completed') {
10439
+ if (finalStatus === 'completed' && !movedByOperator) {
9936
10440
  try {
9937
10441
  run.projectRelay = await projectRelayNext(root, { queue, task, finalJudgement: finalJudgement?.judgement });
9938
10442
  } catch (error) {
@@ -9954,6 +10458,7 @@ export async function runQueueOnce(root, options) {
9954
10458
  progressNotifications
9955
10459
  };
9956
10460
  } finally {
10461
+ clearInterval(leaseRenewal);
9957
10462
  await releaseQueueLock(root, queue, lockResult.lock);
9958
10463
  }
9959
10464
  }