taskforce-loop-engineering 0.15.21 → 0.16.0

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 (40) hide show
  1. package/CHANGELOG.md +54 -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/core.mjs +643 -109
  13. package/lib/durable-journal.mjs +23 -6
  14. package/lib/execution-ledger.mjs +4 -4
  15. package/lib/file-mutex.mjs +102 -0
  16. package/lib/human-gate-channel-adapter.mjs +4 -2
  17. package/lib/human-gate-command.mjs +5 -3
  18. package/lib/operator-dashboard.mjs +72 -10
  19. package/lib/production-evidence.mjs +37 -15
  20. package/lib/quota-runtime-decision.mjs +11 -6
  21. package/lib/redaction.mjs +34 -0
  22. package/lib/todo-control-plane.mjs +12 -16
  23. package/lib/transactional-state-kernel.mjs +96 -18
  24. package/package.json +2 -3
  25. package/scripts/dashboard-autostart-install.mjs +33 -8
  26. package/scripts/dashboard-autostart-self-test.mjs +12 -3
  27. package/scripts/final-judgement-self-test.mjs +21 -0
  28. package/scripts/hermes-install-self-test.mjs +8 -1
  29. package/scripts/hermes-install.mjs +29 -8
  30. package/scripts/hermes-smoke.mjs +2 -1
  31. package/scripts/human-gate-command-self-test.mjs +34 -5
  32. package/scripts/install-shared.mjs +61 -0
  33. package/scripts/openclaw-install-self-test.mjs +47 -1
  34. package/scripts/openclaw-install.mjs +42 -17
  35. package/scripts/openclaw-manage.mjs +22 -3
  36. package/scripts/openclaw-smoke.mjs +2 -1
  37. package/scripts/project-relay-self-test.mjs +145 -1
  38. package/scripts/run-loop-cron.sh +22 -7
  39. package/scripts/safety-regression-self-test.mjs +349 -0
  40. package/skills/taskforce-loop-engineering/SKILL.md +1 -1
package/lib/core.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { access, copyFile, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
1
+ import { access, copyFile, link, mkdir, mkdtemp, open, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { tmpdir } from 'node:os';
6
- import { createHash } from 'node:crypto';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
7
  import { listSteps } from './execution-ledger.mjs';
8
8
  import { readAndVerifyEvidence } from './production-evidence.mjs';
9
9
 
@@ -94,13 +94,62 @@ export async function exists(p) {
94
94
  }
95
95
  }
96
96
 
97
+ // JSON equality must not depend on object key order.
98
+ function canonicalJson(value) {
99
+ const sort = (item) => Array.isArray(item)
100
+ ? item.map(sort)
101
+ : item && typeof item === 'object'
102
+ ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, sort(item[key])]))
103
+ : item;
104
+ return JSON.stringify(sort(value));
105
+ }
106
+
97
107
  export async function readJson(file) {
98
108
  return JSON.parse(await readFile(file, 'utf8'));
99
109
  }
100
110
 
111
+ // Write through a temporary file and rename, so a crash can never leave a
112
+ // truncated JSON file that later poisons a queue scan.
101
113
  export async function writeJson(file, value) {
102
114
  await mkdir(path.dirname(file), { recursive: true });
103
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
115
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
116
+ try {
117
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`);
118
+ await rename(temporary, file);
119
+ } catch (error) {
120
+ await rm(temporary, { force: true });
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ // Publish a new JSON file only if nothing exists at that path yet. link()
126
+ // fails with EEXIST instead of replacing, so two writers cannot overwrite
127
+ // each other, and readers never see a partial file.
128
+ async function writeJsonExclusive(file, value) {
129
+ await mkdir(path.dirname(file), { recursive: true });
130
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
131
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`);
132
+ try {
133
+ await link(temporary, file);
134
+ } finally {
135
+ await rm(temporary, { force: true });
136
+ }
137
+ }
138
+
139
+ // Move an unreadable queue file aside so one corrupt file cannot block every
140
+ // task behind it. The original bytes are kept for inspection.
141
+ async function quarantineQueueFile(root, queue, file, reason) {
142
+ const dir = path.join(queueDirFor(root, queue), 'quarantine');
143
+ await mkdir(dir, { recursive: true });
144
+ const target = path.join(dir, `${isoStamp()}_${path.basename(file)}`);
145
+ try {
146
+ await rename(file, target);
147
+ } catch (error) {
148
+ if (error?.code === 'ENOENT') return null;
149
+ throw error;
150
+ }
151
+ await writeFile(`${target}.reason.txt`, `${reason}\n`);
152
+ return path.relative(root, target);
104
153
  }
105
154
 
106
155
  export function runtimeDirFor(root, id) {
@@ -251,7 +300,7 @@ export async function runCheck(root, check) {
251
300
  } catch (err) {
252
301
  readError = err instanceof Error ? err.message : String(err);
253
302
  }
254
- const equal = readError === null && JSON.stringify(actual) === JSON.stringify(check.expected);
303
+ const equal = readError === null && canonicalJson(actual) === canonicalJson(check.expected);
255
304
  return {
256
305
  id: check.id,
257
306
  type: check.type,
@@ -304,12 +353,38 @@ function jsonPointerGet(value, pointer) {
304
353
  export function runCommand(cmd, options = {}) {
305
354
  return new Promise((resolve) => {
306
355
  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']
356
+ // A spawn failure (missing cwd, NUL byte in the command or environment)
357
+ // is a failed command, not a crash that strands the task in active/.
358
+ const spawnFailure = (error) => ({
359
+ exitCode: 127,
360
+ timedOut: false,
361
+ canceled: false,
362
+ cancelFile: null,
363
+ killedProcessGroup: false,
364
+ stdout: '',
365
+ stderr: `spawn failed: ${error instanceof Error ? error.message : String(error)}`
312
366
  });
367
+ let child;
368
+ try {
369
+ child = spawn('/bin/sh', ['-lc', cmd], {
370
+ cwd: options.cwd ?? process.cwd(),
371
+ env: options.env ?? process.env,
372
+ detached,
373
+ stdio: ['ignore', 'pipe', 'pipe']
374
+ });
375
+ } catch (error) {
376
+ resolve(spawnFailure(error));
377
+ return;
378
+ }
379
+ let settled = false;
380
+ const finish = (result) => {
381
+ if (settled) return;
382
+ settled = true;
383
+ clearTimeout(timer);
384
+ if (cancelTimer) clearInterval(cancelTimer);
385
+ resolve(result);
386
+ };
387
+ child.on('error', (error) => finish(spawnFailure(error)));
313
388
  let stdout = '';
314
389
  let stderr = '';
315
390
  let timedOut = false;
@@ -349,12 +424,13 @@ export function runCommand(cmd, options = {}) {
349
424
  }
350
425
  }, options.cancelPollMs ?? 250) : null;
351
426
  cancelTimer?.unref();
352
- child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
353
- child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
427
+ // setEncoding keeps multi-byte characters intact across chunk boundaries.
428
+ child.stdout.setEncoding('utf8');
429
+ child.stderr.setEncoding('utf8');
430
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
431
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
354
432
  child.on('close', (code, signal) => {
355
- clearTimeout(timer);
356
- if (cancelTimer) clearInterval(cancelTimer);
357
- resolve({
433
+ finish({
358
434
  exitCode: code ?? (signal ? 128 : 1),
359
435
  timedOut,
360
436
  canceled,
@@ -1030,8 +1106,9 @@ export async function parkQueueTask(root, options = {}) {
1030
1106
  authorization: options.authorization ?? task.parked?.authorization ?? null
1031
1107
  };
1032
1108
  const waitingFile = path.join(queueSubdirFor(root, queue, 'waiting'), path.basename(found.file));
1109
+ if (path.resolve(found.file) !== path.resolve(waitingFile)) await rename(found.file, waitingFile);
1033
1110
  await writeJson(waitingFile, { ...task, status: 'parked', parked });
1034
- if (path.resolve(found.file) !== path.resolve(waitingFile)) await rm(found.file, { force: true });
1111
+ if (found.subdir === 'active') await requestTaskStop(root, queue, taskId, 'operator_park');
1035
1112
  return { outcome: 'parked', task: { ...task, status: 'parked', parked }, file: path.relative(root, waitingFile) };
1036
1113
  }
1037
1114
 
@@ -1127,8 +1204,8 @@ export async function resumeParkedTask(root, options = {}) {
1127
1204
  execution_boundary: { ...task.parked.execution_boundary, resumed_at: now.toISOString() }
1128
1205
  };
1129
1206
  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 });
1207
+ if (path.resolve(found.file) !== path.resolve(inboxFile)) await rename(found.file, inboxFile);
1208
+ await writeJson(inboxFile, { ...task, status: 'queued', parked: resumed, requeuedAt: now.toISOString(), requeuedFrom: 'waiting', supersedeClearedAt: new Date().toISOString() });
1132
1209
  return { outcome: 'verified_and_requeued', signalSha256, task: { ...task, status: 'queued', parked: resumed }, file: path.relative(root, inboxFile) };
1133
1210
  }
1134
1211
 
@@ -1213,6 +1290,16 @@ function requirementIdsFromCheckpoint(checkpoint, specs) {
1213
1290
  return [...known].filter((id) => new RegExp(`(^|[^A-Za-z0-9_-])${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^A-Za-z0-9_-]|$)`).test(text));
1214
1291
  }
1215
1292
 
1293
+ // A project is mentioned only as a whole token: "ui" must not match "build".
1294
+ // Project ids are [A-Za-z0-9._-], so neighbouring id characters (or a
1295
+ // trailing dot followed by one) mean the name is part of another word.
1296
+ function projectNameMentioned(text, project) {
1297
+ const name = String(project ?? '').toLowerCase();
1298
+ if (!name) return false;
1299
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1300
+ return new RegExp(`(^|[^a-z0-9_-])${escaped}(?![a-z0-9_-]|\\.[a-z0-9])`, 'i').test(text);
1301
+ }
1302
+
1216
1303
  function inferProjectSpec(task, checkpoint, specs, requirementIds = []) {
1217
1304
  const explicit = checkpoint?.project_id
1218
1305
  ?? checkpoint?.projectId
@@ -1225,7 +1312,7 @@ function inferProjectSpec(task, checkpoint, specs, requirementIds = []) {
1225
1312
  const candidates = specs.map((spec) => ({
1226
1313
  spec,
1227
1314
  requirementMatches: requirementIds.filter((id) => (spec.backlog ?? []).some((item) => item.id === id)).length,
1228
- nameMatch: text.includes(String(spec.project).toLowerCase()) ? 1 : 0
1315
+ nameMatch: projectNameMentioned(text, spec.project) ? 1 : 0
1229
1316
  })).filter((item) => item.requirementMatches > 0 || item.nameMatch > 0)
1230
1317
  .sort((a, b) => b.requirementMatches - a.requirementMatches || b.nameMatch - a.nameMatch || b.spec.project.length - a.spec.project.length);
1231
1318
  return candidates[0]?.spec ?? null;
@@ -1286,6 +1373,10 @@ export async function reconcileProjectGates(root, options = {}) {
1286
1373
  await writeJson(full, gate);
1287
1374
  }
1288
1375
  const spec = await projectSpecForCheckpoint(root, [...specs.values()], gate.project_id, checkpoint);
1376
+ // Gates for tasks outside any project are not project-governed: there
1377
+ // is no contract to go stale, so reconciliation must leave them alone.
1378
+ // A gate bound to a project that has since disappeared still fails.
1379
+ if (!spec && !gate.project_id) continue;
1289
1380
  if (spec?.project && gate.project_id !== spec.project) {
1290
1381
  gate = { ...gate, project_id: spec.project };
1291
1382
  await writeJson(full, gate);
@@ -1924,10 +2015,10 @@ export async function enqueueTask(root, options) {
1924
2015
  throw new Error('enqueue requires --task or --file.');
1925
2016
  }
1926
2017
 
1927
- const id = taskIdForTitle(options.title);
2018
+ const baseId = taskIdForTitle(options.title);
1928
2019
  const task = {
1929
2020
  version: 1,
1930
- id,
2021
+ id: baseId,
1931
2022
  queue,
1932
2023
  title: options.title.trim(),
1933
2024
  body: body.trim(),
@@ -1940,9 +2031,27 @@ export async function enqueueTask(root, options) {
1940
2031
  ...(options.supersedeReason ? { supersedeReason: options.supersedeReason } : {}),
1941
2032
  ...(taskSourceFromOptions(options) ? { source: taskSourceFromOptions(options) } : {})
1942
2033
  };
1943
- const file = path.join(queueSubdirFor(root, queue, 'inbox'), `${id}.json`);
1944
- await writeJson(file, task);
1945
- return { task, file: path.relative(root, file) };
2034
+ // Ids are a millisecond timestamp plus a title slug (non-ASCII titles all
2035
+ // slug to "task"), so concurrent enqueues can collide. Never overwrite:
2036
+ // take the next free suffix across every task state.
2037
+ for (let attempt = 1; attempt <= 1000; attempt += 1) {
2038
+ const id = attempt === 1 ? baseId : `${baseId}-${attempt}`;
2039
+ let taken = false;
2040
+ for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
2041
+ if (await exists(path.join(queueSubdirFor(root, queue, subdir), `${id}.json`))) { taken = true; break; }
2042
+ }
2043
+ if (taken) continue;
2044
+ const file = path.join(queueSubdirFor(root, queue, 'inbox'), `${id}.json`);
2045
+ task.id = id;
2046
+ try {
2047
+ await writeJsonExclusive(file, task);
2048
+ } catch (error) {
2049
+ if (error?.code === 'EEXIST') continue;
2050
+ throw error;
2051
+ }
2052
+ return { task, file: path.relative(root, file) };
2053
+ }
2054
+ throw new Error(`Unable to allocate a unique task id for ${baseId}.`);
1946
2055
  }
1947
2056
 
1948
2057
  function taskSourceFromOptions(options = {}) {
@@ -2038,7 +2147,14 @@ async function appendActiveTaskAmendment(root, queue, activeTask, options = {})
2038
2147
  });
2039
2148
  updatedPlans.push(path.relative(root, file));
2040
2149
  }
2041
- await writeJson(path.join(queueSubdirFor(root, queue, 'active'), `${activeTask.id}.json`), {
2150
+ const activeFile = path.join(queueSubdirFor(root, queue, 'active'), `${activeTask.id}.json`);
2151
+ // The runner may have finished meanwhile. Writing here would re-create the
2152
+ // task in active/ and get it re-executed; the amendment artifacts above
2153
+ // still record the instruction.
2154
+ if (!(await exists(activeFile))) {
2155
+ return { amendment, file: path.relative(root, versionedFile), latestFile: path.relative(root, latestFile), updatedPlans, taskFinished: true };
2156
+ }
2157
+ await writeJson(activeFile, {
2042
2158
  ...activeTask,
2043
2159
  amendmentCount: sequence,
2044
2160
  lastAmendmentAt: amendment.requestedAt,
@@ -2590,7 +2706,21 @@ async function projectHasSafeActionableBacklog(root, spec, checkpoint = null) {
2590
2706
  });
2591
2707
  }
2592
2708
 
2593
- export async function projectRelayReconcile(root, { queue, project } = {}) {
2709
+ const RELAY_TASK_SUBDIRS = ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled'];
2710
+
2711
+ // Read each queue task file once so the relay checks of one scheduler pass
2712
+ // can share it instead of rescanning every directory.
2713
+ async function relayTaskSnapshot(root, queue, subdirs = RELAY_TASK_SUBDIRS) {
2714
+ const snapshot = {};
2715
+ for (const subdir of subdirs) {
2716
+ const dir = queueSubdirFor(root, queue, subdir);
2717
+ snapshot[subdir] = [];
2718
+ for (const file of await listJson(dir)) snapshot[subdir].push(await readJson(path.join(dir, file)));
2719
+ }
2720
+ return snapshot;
2721
+ }
2722
+
2723
+ export async function projectRelayReconcile(root, { queue, project, beforeWrite, tasks } = {}) {
2594
2724
  project = normalizeProjectId(project);
2595
2725
  const spec = await readJson(projectConfigPathFor(root, project));
2596
2726
  if (spec.relayStatusReconciliation !== true || !spec.backlogSource
@@ -2601,21 +2731,49 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2601
2731
  || !['in_progress', 'ongoing'].includes(ledger.status)
2602
2732
  || ledger.terminalState?.accepted === true || ledger.terminalAccepted === true) return { changed: 0 };
2603
2733
  const backlogFile = path.resolve(root, safeRelativePath(spec.backlogSource, 'project backlog source'));
2734
+ let backlogText;
2604
2735
  let backlog;
2605
- try { backlog = await readJson(backlogFile); } catch { return { changed: 0 }; }
2736
+ try {
2737
+ backlogText = await readFile(backlogFile, 'utf8');
2738
+ backlog = JSON.parse(backlogText);
2739
+ } catch { return { changed: 0 }; }
2606
2740
  if (!backlog || typeof backlog !== 'object' || Array.isArray(backlog)) return { changed: 0 };
2607
2741
  const field = Array.isArray(backlog.items) ? 'items' : Array.isArray(backlog.tasks) ? 'tasks' : null;
2608
2742
  if (!field) return { changed: 0 };
2743
+ // Revision rounds keep the backlog binding but not the leading marker, so
2744
+ // resolve each completed task to the relay task that started its lineage.
2745
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue, ['done', 'failed']);
2746
+ const finished = new Map();
2747
+ for (const subdir of ['done', 'failed']) {
2748
+ for (const task of snapshot[subdir]) {
2749
+ if (task?.id && !finished.has(task.id)) finished.set(task.id, { task, subdir });
2750
+ }
2751
+ }
2752
+ const relayRoot = (task) => {
2753
+ const seen = new Set();
2754
+ let current = task;
2755
+ while (current && !seen.has(current.id)) {
2756
+ if (current.projectId !== project || current.backlogItemId !== task.backlogItemId) return null;
2757
+ seen.add(current.id);
2758
+ if (!current.revisionOf) {
2759
+ const marker = String(current.body ?? '').match(/^\[project-relay:([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)\](?:\n|$)/);
2760
+ return marker?.[1] === project && marker[2] === task.backlogItemId ? current.id : null;
2761
+ }
2762
+ current = finished.get(current.revisionOf)?.task;
2763
+ }
2764
+ return null;
2765
+ };
2609
2766
  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
2767
+ for (const { task, subdir } of finished.values()) {
2768
+ if (subdir !== 'done' || task.projectId !== project || task.status !== 'completed'
2769
+ || typeof task.backlogItemId !== 'string'
2613
2770
  || !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);
2771
+ const rootId = relayRoot(task);
2772
+ if (!rootId) continue;
2773
+ const evidence = completed.get(task.backlogItemId) ?? { roots: new Set(), taskIds: [] };
2774
+ evidence.roots.add(rootId);
2775
+ evidence.taskIds.push(task.id);
2776
+ completed.set(task.backlogItemId, evidence);
2619
2777
  }
2620
2778
  const itemCounts = new Map();
2621
2779
  for (const item of backlog[field]) {
@@ -2626,15 +2784,21 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2626
2784
  for (const item of backlog[field]) {
2627
2785
  if (!item || typeof item !== 'object' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(item.id ?? ''))
2628
2786
  || itemCounts.get(item.id) !== 1
2629
- || (completed.get(item.id) ?? []).length !== 1
2787
+ || completed.get(item.id)?.roots.size !== 1
2630
2788
  || item.status !== 'ready' || item.autoRun !== true || item.scope !== 'local_only'
2631
2789
  || item.externalActionsAllowed !== false || item.humanGateRequired !== false) {
2632
2790
  items.push(item);
2633
2791
  continue;
2634
2792
  }
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) {
2793
+ // One relay lineage may contain rejected rounds, but exactly one round
2794
+ // must carry an accepted, gate-free final judgement.
2795
+ let accepted = 0;
2796
+ for (const taskId of completed.get(item.id).taskIds) {
2797
+ const judgementFile = path.join(taskRuntimeDirFor(root, queue, taskId), 'final_judgement.json');
2798
+ const judgement = await exists(judgementFile) ? await readJson(judgementFile) : null;
2799
+ if (judgement?.outcome === 'ready_to_apply' && judgement.requires_human_gate === false) accepted += 1;
2800
+ }
2801
+ if (accepted !== 1) {
2638
2802
  items.push(item);
2639
2803
  continue;
2640
2804
  }
@@ -2644,12 +2808,21 @@ export async function projectRelayReconcile(root, { queue, project } = {}) {
2644
2808
  if (changed) {
2645
2809
  const temporary = `${backlogFile}.${process.pid}.tmp`;
2646
2810
  await writeJson(temporary, { ...backlog, [field]: items });
2811
+ if (beforeWrite) await beforeWrite();
2812
+ // The backlog is shared with agents that may edit it from another queue
2813
+ // or process. Never replace a version this reconciliation did not read.
2814
+ let currentText = null;
2815
+ try { currentText = await readFile(backlogFile, 'utf8'); } catch {}
2816
+ if (currentText !== backlogText) {
2817
+ await rm(temporary, { force: true });
2818
+ return { changed: 0, conflict: true };
2819
+ }
2647
2820
  await rename(temporary, backlogFile);
2648
2821
  }
2649
2822
  return { changed };
2650
2823
  }
2651
2824
 
2652
- export async function projectRelayNext(root, { queue, task, finalJudgement } = {}) {
2825
+ export async function projectRelayNext(root, { queue, task, finalJudgement, tasks } = {}) {
2653
2826
  if (!task?.projectId || finalJudgement?.outcome !== 'ready_to_apply' || finalJudgement.requires_human_gate) return null;
2654
2827
  const project = normalizeProjectId(task.projectId);
2655
2828
  const spec = await readJson(projectConfigPathFor(root, project));
@@ -2666,26 +2839,27 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
2666
2839
  if (typeof predecessorId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(predecessorId)) return null;
2667
2840
  const queueState = await queueStatus(root, queue);
2668
2841
  if (queueState.queued || queueState.active || queueState.waiting) return null;
2669
- await projectRelayReconcile(root, { queue, project });
2842
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue);
2843
+ await projectRelayReconcile(root, { queue, project, tasks: snapshot });
2670
2844
  const backlogSource = spec.backlogSource ?? spec.authoritativeBacklog;
2671
2845
  if (typeof backlogSource !== 'string' || !backlogSource.trim()) return null;
2672
2846
  let backlog;
2673
2847
  try {
2674
2848
  backlog = await readJson(path.resolve(root, safeRelativePath(backlogSource, 'project backlog source')));
2675
2849
  } 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]));
2850
+ const rows = Array.isArray(backlog?.items) ? backlog.items : Array.isArray(backlog?.tasks) ? backlog.tasks : null;
2851
+ if (!rows?.length) return null;
2852
+ // Ambiguous ids cannot prove a predecessor or dependency, and cannot be
2853
+ // relayed: drop every row that shares its id with another row.
2854
+ const items = rows.filter((item) => item && typeof item === 'object' && !Array.isArray(item));
2855
+ const idCounts = new Map();
2856
+ for (const item of items) idCounts.set(item.id, (idCounts.get(item.id) ?? 0) + 1);
2857
+ const byId = new Map(items.filter((item) => idCounts.get(item.id) === 1).map((item) => [item.id, item]));
2679
2858
  const complete = new Set(['accepted', 'complete', 'completed', 'done', 'phase_complete']);
2680
2859
  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
- }
2860
+ const queuedBodies = RELAY_TASK_SUBDIRS.flatMap((subdir) => snapshot[subdir].map((entry) => String(entry?.body ?? '')));
2687
2861
  const item = items.find((candidate) => {
2688
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(candidate.id ?? ''))) return false;
2862
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(candidate.id ?? '')) || byId.get(candidate.id) !== candidate) return false;
2689
2863
  if (candidate.status !== 'ready' || candidate.autoRun !== true || candidate.scope !== 'local_only'
2690
2864
  || candidate.externalActionsAllowed !== false || candidate.humanGateRequired !== false
2691
2865
  || candidate.blocked === true || candidate.requires_human_input === true
@@ -2708,6 +2882,29 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
2708
2882
  return { project, itemId: item.id, taskId: result.task.id, file: result.file };
2709
2883
  }
2710
2884
 
2885
+ // Relay is attempted when a bound task is accepted, but it is skipped while
2886
+ // the queue is busy. Retry once the queue is idle, but only when the most
2887
+ // recently enqueued backlog-bound task is the accepted one: a failed or
2888
+ // canceled relay task stops the chain until a person acts on it.
2889
+ // projectRelayNext keeps every authority and duplicate check.
2890
+ export async function projectRelayResume(root, { queue, project, tasks } = {}) {
2891
+ project = normalizeProjectId(project);
2892
+ const snapshot = tasks ?? await relayTaskSnapshot(root, queue);
2893
+ let newest = null;
2894
+ for (const subdir of ['done', 'failed', 'canceled']) {
2895
+ for (const task of snapshot[subdir]) {
2896
+ if (task?.projectId !== project || typeof task.backlogItemId !== 'string' || !task.id) continue;
2897
+ const time = Date.parse(task.enqueuedAt ?? task.finishedAt ?? '') || 0;
2898
+ if (!newest || time > newest.time) newest = { task, subdir, time, tied: false };
2899
+ else if (time === newest.time) newest.tied = true;
2900
+ }
2901
+ }
2902
+ if (!newest || newest.tied || newest.subdir !== 'done' || newest.task.status !== 'completed') return null;
2903
+ const judgementFile = path.join(taskRuntimeDirFor(root, queue, newest.task.id), 'final_judgement.json');
2904
+ if (!await exists(judgementFile)) return null;
2905
+ return projectRelayNext(root, { queue, task: newest.task, finalJudgement: await readJson(judgementFile), tasks: snapshot });
2906
+ }
2907
+
2711
2908
  async function tasksById(root, queue) {
2712
2909
  const tasks = new Map();
2713
2910
  for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
@@ -4704,6 +4901,31 @@ function decideQueueProgressNotification(previousProgress, policy, observed, sch
4704
4901
  };
4705
4902
  }
4706
4903
 
4904
+ function relayMaintenanceStatePath(root, queue) {
4905
+ return path.join(queueDirFor(root, queue), 'scheduler', 'relay-maintenance.json');
4906
+ }
4907
+
4908
+ // Cheap change detector for relay maintenance: task file names per state
4909
+ // directory (a task changing state is a rename), each project spec, and the
4910
+ // size and mtime of its backlog and acceptance files. In-place task edits are
4911
+ // intentionally left to the periodic full pass.
4912
+ async function relayMaintenanceFingerprint(root, queue, specs) {
4913
+ const hash = createHash('sha256');
4914
+ for (const subdir of RELAY_TASK_SUBDIRS) {
4915
+ hash.update(`${subdir}\0${(await listJson(queueSubdirFor(root, queue, subdir))).join('\0')}\n`);
4916
+ }
4917
+ for (const spec of specs) {
4918
+ hash.update(`${JSON.stringify(spec)}\n`);
4919
+ for (const configured of [spec.backlogSource, spec.authoritativeBacklog, spec.acceptanceLedger, spec.ledger, spec.terminalContract]) {
4920
+ if (typeof configured !== 'string') continue;
4921
+ let info = null;
4922
+ try { info = await stat(path.resolve(root, safeRelativePath(configured, 'project relay file'))); } catch {}
4923
+ hash.update(`${configured}\0${info ? `${info.mtimeMs}:${info.size}` : 'missing'}\n`);
4924
+ }
4925
+ }
4926
+ return hash.digest('hex');
4927
+ }
4928
+
4707
4929
  export async function queueSchedulerTick(root, options) {
4708
4930
  const queue = normalizeLoopId(options.queue);
4709
4931
  await ensureQueueDirs(root, queue);
@@ -4747,13 +4969,70 @@ export async function queueSchedulerTick(root, options) {
4747
4969
  }
4748
4970
 
4749
4971
  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;
4972
+ const projectRelay = [];
4973
+ let relayMaintenance = 'not_configured';
4974
+ const relaySpecs = options.planOnly ? [] : (await projectSpecs(root))
4975
+ .filter((spec) => spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true));
4976
+ if (relaySpecs.length) {
4977
+ // Agents edit project backlogs while they hold this queue's lock. Only
4978
+ // reconcile or relay when this tick owns the lock and nothing is active.
4979
+ const lockResult = await acquireQueueLock(root, queue, 5 * 60 * 1000);
4980
+ relayMaintenance = lockResult.acquired ? 'queue_active' : 'queue_locked';
4981
+ if (lockResult.acquired) {
4753
4982
  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) });
4983
+ if ((await queueStatus(root, queue)).active === 0) {
4984
+ // Most ticks change nothing relay-relevant. Skip the full scan when
4985
+ // the cheap fingerprint is unchanged; a periodic full pass covers
4986
+ // in-place edits the fingerprint cannot see. Skipping only delays a
4987
+ // relay: every decision is still recomputed from the task files.
4988
+ const fingerprint = await relayMaintenanceFingerprint(root, queue, relaySpecs);
4989
+ const statePath = relayMaintenanceStatePath(root, queue);
4990
+ const previousPass = await exists(statePath) ? await readJson(statePath).catch(() => null) : null;
4991
+ const fullIntervalMs = options.relayMaintenanceFullIntervalMs ?? 60 * 60 * 1000;
4992
+ const sinceFullPassMs = nowMs - Date.parse(previousPass?.fullPassAt ?? '');
4993
+ if (previousPass?.fingerprint === fingerprint && sinceFullPassMs >= 0 && sinceFullPassMs < fullIntervalMs) {
4994
+ relayMaintenance = 'unchanged';
4995
+ } else {
4996
+ relayMaintenance = 'completed';
4997
+ let tasks = null;
4998
+ let clean = true;
4999
+ try {
5000
+ tasks = await relayTaskSnapshot(root, queue);
5001
+ } catch (error) {
5002
+ clean = false;
5003
+ relayMaintenance = 'error';
5004
+ projectRelay.push({ error: error instanceof Error ? error.message : String(error) });
5005
+ }
5006
+ for (const spec of tasks ? relaySpecs : []) {
5007
+ if (spec.relayStatusReconciliation === true) {
5008
+ try {
5009
+ const reconciled = await projectRelayReconcile(root, { queue, project: spec.project, tasks });
5010
+ if (reconciled.conflict) clean = false;
5011
+ relayReconciliation.push({ project: spec.project, ...reconciled });
5012
+ } catch (error) {
5013
+ clean = false;
5014
+ relayReconciliation.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
5015
+ }
5016
+ }
5017
+ try {
5018
+ const relayed = await projectRelayResume(root, { queue, project: spec.project, tasks });
5019
+ if (relayed) {
5020
+ projectRelay.push(relayed);
5021
+ tasks = await relayTaskSnapshot(root, queue);
5022
+ }
5023
+ } catch (error) {
5024
+ clean = false;
5025
+ projectRelay.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
5026
+ }
5027
+ }
5028
+ // Record the fingerprint read before this pass, so anything that
5029
+ // changed during it triggers another full pass. Failed passes are
5030
+ // not recorded and retry on the next tick.
5031
+ if (clean) await writeJson(statePath, { version: 1, fingerprint, fullPassAt: now });
5032
+ }
5033
+ }
5034
+ } finally {
5035
+ await releaseQueueLock(root, queue, lockResult.lock);
4757
5036
  }
4758
5037
  }
4759
5038
  }
@@ -4849,6 +5128,8 @@ export async function queueSchedulerTick(root, options) {
4849
5128
  statusBefore,
4850
5129
  statusAfter,
4851
5130
  relayReconciliation,
5131
+ relayMaintenance,
5132
+ projectRelay,
4852
5133
  run: runResult
4853
5134
  };
4854
5135
  }
@@ -5024,15 +5305,68 @@ function queueLockOwnerAlive(lock) {
5024
5305
  return Boolean(lock && processIsAlive(lock.pid));
5025
5306
  }
5026
5307
 
5308
+ const QUEUE_LOCK_UNREADABLE_GRACE_MS = 30 * 1000;
5309
+ const QUEUE_LOCK_RECLAIM_STALE_MS = 10 * 1000;
5310
+
5311
+ // Decide whether an existing lock file still protects a runner. An unreadable
5312
+ // lock is normal for a moment while its creator writes it, so it only counts
5313
+ // as stale after a grace period.
5314
+ async function queueLockState(root, queue, now) {
5315
+ const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5316
+ let info;
5317
+ try { info = await stat(lockFile); } catch (error) {
5318
+ if (error?.code === 'ENOENT') return { present: false };
5319
+ throw error;
5320
+ }
5321
+ const lock = await readQueueLock(root, queue);
5322
+ if (!lock) return { present: true, lock: null, held: now - info.mtimeMs < QUEUE_LOCK_UNREADABLE_GRACE_MS, ownerAlive: false, reason: 'unreadable_lock' };
5323
+ const ownerAlive = queueLockOwnerAlive(lock);
5324
+ return { present: true, lock, held: Date.parse(lock.expiresAt) > now && ownerAlive, ownerAlive };
5325
+ }
5326
+
5027
5327
  async function acquireQueueLock(root, queue, leaseMs) {
5028
5328
  const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5029
5329
  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 };
5330
+ const state = await queueLockState(root, queue, now);
5331
+ if (state.present && state.held) return { acquired: false, lock: state.lock };
5332
+ let reclaimedLock = null;
5333
+ if (state.present) {
5334
+ // Reclaiming means deleting someone else's lock file. Serialize it with
5335
+ // an atomic mkdir so two runners cannot both delete-and-create, and
5336
+ // re-check the lock inside the critical section.
5337
+ const mutex = `${lockFile}.reclaim`;
5338
+ try {
5339
+ await mkdir(mutex);
5340
+ } catch (error) {
5341
+ if (error?.code !== 'EEXIST') throw error;
5342
+ const info = await stat(mutex).catch(() => null);
5343
+ if (info && now - info.mtimeMs > QUEUE_LOCK_RECLAIM_STALE_MS) await rmdir(mutex).catch(() => {});
5344
+ return { acquired: false, lock: state.lock };
5345
+ }
5346
+ try {
5347
+ const current = await queueLockState(root, queue, Date.now());
5348
+ if (current.present && current.held) return { acquired: false, lock: current.lock };
5349
+ if (current.present) {
5350
+ if (current.lock?.acquiredAt !== state.lock?.acquiredAt || current.lock?.pid !== state.lock?.pid) {
5351
+ return { acquired: false, lock: current.lock };
5352
+ }
5353
+ await rm(lockFile, { force: true });
5354
+ reclaimedLock = {
5355
+ lock: current.lock,
5356
+ reason: current.reason ?? (current.ownerAlive ? 'expired_lease' : 'dead_owner_pid')
5357
+ };
5358
+ }
5359
+ return await createQueueLock(root, queue, leaseMs, reclaimedLock);
5360
+ } finally {
5361
+ await rmdir(mutex).catch(() => {});
5362
+ }
5034
5363
  }
5035
- if (existing) await rm(lockFile, { force: true });
5364
+ return createQueueLock(root, queue, leaseMs, null);
5365
+ }
5366
+
5367
+ async function createQueueLock(root, queue, leaseMs, reclaimedLock) {
5368
+ const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5369
+ const now = Date.now();
5036
5370
  const lock = {
5037
5371
  version: 1,
5038
5372
  queue,
@@ -5040,28 +5374,26 @@ async function acquireQueueLock(root, queue, leaseMs) {
5040
5374
  acquiredAt: new Date(now).toISOString(),
5041
5375
  expiresAt: new Date(now + leaseMs).toISOString()
5042
5376
  };
5043
- let handle = null;
5044
5377
  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
- };
5378
+ await writeJsonExclusive(lockFile, lock);
5379
+ return { acquired: true, lock, reclaimedLock };
5055
5380
  } catch (err) {
5056
5381
  if (err && err.code === 'EEXIST') {
5057
5382
  return { acquired: false, lock: await readQueueLock(root, queue) };
5058
5383
  }
5059
5384
  throw err;
5060
- } finally {
5061
- if (handle) await handle.close();
5062
5385
  }
5063
5386
  }
5064
5387
 
5388
+ // Extend a held lease while its runner is still working, so a long dispatch
5389
+ // is not mistaken for an abandoned one. Returns false once the lock is lost.
5390
+ async function renewQueueLock(root, queue, lock, leaseMs) {
5391
+ const current = await readQueueLock(root, queue);
5392
+ if (current?.pid !== lock.pid || current?.acquiredAt !== lock.acquiredAt) return false;
5393
+ await writeJson(path.join(queueDirFor(root, queue), 'queue.lock'), { ...current, expiresAt: new Date(Date.now() + leaseMs).toISOString(), renewedAt: new Date().toISOString() });
5394
+ return true;
5395
+ }
5396
+
5065
5397
  async function releaseQueueLock(root, queue, lock) {
5066
5398
  const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
5067
5399
  const current = await readQueueLock(root, queue);
@@ -5077,7 +5409,9 @@ async function nextQueuedTaskFile(root, queue) {
5077
5409
  }
5078
5410
 
5079
5411
  async function findTaskFile(root, queue, taskId, subdirs = ['inbox', 'active', 'waiting', 'failed', 'done', 'canceled']) {
5080
- const wanted = taskId.endsWith('.json') ? taskId : `${taskId}.json`;
5412
+ // Task ids reach here from CLI flags; never let one escape the queue.
5413
+ const id = safeTaskId(String(taskId ?? '').replace(/\.json$/, ''));
5414
+ const wanted = `${id}.json`;
5081
5415
  for (const subdir of subdirs) {
5082
5416
  const file = path.join(queueSubdirFor(root, queue, subdir), wanted);
5083
5417
  if (await exists(file)) return { file, subdir };
@@ -5106,6 +5440,35 @@ export async function queuePeek(root, queue, options = {}) {
5106
5440
  return { queue: normalized, tasks };
5107
5441
  }
5108
5442
 
5443
+ // Ask a running dispatcher to stop: runCommand polls this marker and kills the
5444
+ // process group. Used when an operator takes a task out of active/.
5445
+ async function requestTaskStop(root, queue, taskId, reason) {
5446
+ await writeJson(path.join(taskRuntimeDirFor(root, queue, taskId), 'supersede_request.json'), {
5447
+ version: 1,
5448
+ requestedAt: new Date().toISOString(),
5449
+ activeTaskId: taskId,
5450
+ reason,
5451
+ kind: 'operator_stop',
5452
+ status: 'requested'
5453
+ });
5454
+ }
5455
+
5456
+ // A supersede marker only applies to the run it was written for. An operator
5457
+ // requeue or verified resume records supersedeClearedAt, and older markers are
5458
+ // discarded so the restarted task actually runs.
5459
+ async function currentSupersedeRequest(root, queue, task) {
5460
+ const file = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
5461
+ if (!(await exists(file))) return null;
5462
+ const request = await readJson(file).catch(() => ({}));
5463
+ const clearedAt = Date.parse(task.supersedeClearedAt ?? '');
5464
+ const requestedAt = Date.parse(request.requestedAt ?? '');
5465
+ if (Number.isFinite(clearedAt) && (!Number.isFinite(requestedAt) || requestedAt <= clearedAt)) {
5466
+ await rm(file, { force: true });
5467
+ return null;
5468
+ }
5469
+ return { file, request };
5470
+ }
5471
+
5109
5472
  export async function queueCancel(root, queue, taskId, options = {}) {
5110
5473
  const normalized = normalizeLoopId(queue);
5111
5474
  await ensureQueueDirs(root, normalized);
@@ -5113,6 +5476,9 @@ export async function queueCancel(root, queue, taskId, options = {}) {
5113
5476
  if (!found) throw new Error(`Task not found in cancelable state: ${taskId}`);
5114
5477
  const task = await readJson(found.file);
5115
5478
  const canceledFile = path.join(queueSubdirFor(root, normalized, 'canceled'), path.basename(found.file));
5479
+ // Move, then rewrite: the runner treats a missing active file as taken
5480
+ // over by an operator and will not write its own copy.
5481
+ await rename(found.file, canceledFile);
5116
5482
  await writeJson(canceledFile, {
5117
5483
  ...task,
5118
5484
  status: 'canceled',
@@ -5120,7 +5486,7 @@ export async function queueCancel(root, queue, taskId, options = {}) {
5120
5486
  canceledFrom: found.subdir,
5121
5487
  cancelReason: options.reason ?? null
5122
5488
  });
5123
- await rm(found.file, { force: true });
5489
+ if (found.subdir === 'active') await requestTaskStop(root, normalized, task.id, 'operator_cancel');
5124
5490
  return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, canceledFile) };
5125
5491
  }
5126
5492
 
@@ -5133,13 +5499,16 @@ export async function queueRequeue(root, queue, taskId, options = {}) {
5133
5499
  if (!found) throw new Error(`Task not found in requeueable state: ${taskId}`);
5134
5500
  const task = await readJson(found.file);
5135
5501
  const inboxFile = path.join(queueSubdirFor(root, normalized, 'inbox'), path.basename(found.file));
5502
+ if (found.subdir === 'active') await requestTaskStop(root, normalized, task.id, 'operator_requeue');
5503
+ await rename(found.file, inboxFile);
5504
+ const requeuedAt = new Date().toISOString();
5136
5505
  await writeJson(inboxFile, {
5137
5506
  ...task,
5138
5507
  status: 'queued',
5139
- requeuedAt: new Date().toISOString(),
5140
- requeuedFrom: found.subdir
5508
+ requeuedAt,
5509
+ requeuedFrom: found.subdir,
5510
+ supersedeClearedAt: requeuedAt
5141
5511
  });
5142
- await rm(found.file, { force: true });
5143
5512
  return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, inboxFile) };
5144
5513
  }
5145
5514
 
@@ -5715,11 +6084,27 @@ export async function queueRevisionPlan(root, queue, taskId, options = {}) {
5715
6084
  };
5716
6085
  }
5717
6086
 
6087
+ // A source task gets one live revision child. Re-running next/apply-plan
6088
+ // (for example after a timeout) must not enqueue the same revision twice;
6089
+ // a canceled child does not count.
6090
+ async function assertNoRevisionChild(root, queue, sourceTaskId, options = {}) {
6091
+ if (!sourceTaskId || options.force) return;
6092
+ for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed']) {
6093
+ for (const file of await listJson(queueSubdirFor(root, queue, subdir))) {
6094
+ const task = await readJson(path.join(queueSubdirFor(root, queue, subdir), file)).catch(() => null);
6095
+ if (task?.revisionOf === sourceTaskId) {
6096
+ throw new Error(`Revision of ${sourceTaskId} is already enqueued as ${task.id} (${subdir}). Use --force to enqueue another.`);
6097
+ }
6098
+ }
6099
+ }
6100
+ }
6101
+
5718
6102
  export async function queueRevisionNext(root, queue, taskId, options = {}) {
5719
6103
  const plan = await queueRevisionPlan(root, queue, taskId, options);
5720
6104
  if (!plan.revisionPolicyGuard.allowed) {
5721
6105
  throw new Error(`Revision guard blocked next round for ${taskId}: ${plan.revisionPolicyGuard.reasons.join('; ')}`);
5722
6106
  }
6107
+ await assertNoRevisionChild(root, plan.queue, plan.plannedTask.revisionOf, options);
5723
6108
  const enqueued = await enqueueTask(root, {
5724
6109
  queue: plan.queue,
5725
6110
  title: plan.plannedTask.title,
@@ -5774,6 +6159,7 @@ export async function queueRevisionApplyPlan(root, planPath, options = {}) {
5774
6159
  const reasons = plan.revisionPolicyGuard?.reasons?.join('; ') || 'plan canEnqueue=false';
5775
6160
  throw new Error(`Revision plan is blocked for ${plan.sourceTaskId ?? 'unknown source task'}: ${reasons}. Use --force to override.`);
5776
6161
  }
6162
+ await assertNoRevisionChild(root, normalized, plan.plannedTask.revisionOf ?? plan.sourceTaskId, options);
5777
6163
 
5778
6164
  const enqueued = await enqueueTask(root, {
5779
6165
  queue: normalized,
@@ -6529,6 +6915,28 @@ export async function codeWorktreeInspect(root, queue, options = {}) {
6529
6915
  };
6530
6916
  }
6531
6917
 
6918
+ // The complete pending change of a worktree: tracked edits plus every
6919
+ // untracked file as a real new-file diff, so an export can be applied and a
6920
+ // cleanup can prove nothing was left behind.
6921
+ async function worktreePendingPatch(worktreePath) {
6922
+ const tracked = await runCommand('git diff --binary HEAD', { cwd: worktreePath, timeoutMs: 120000 });
6923
+ if (tracked.exitCode !== 0) throw new Error(`Unable to read worktree patch: ${trimTail(tracked.stderr || tracked.stdout, 1200)}`);
6924
+ const listing = await runCommand('git ls-files -z --others --exclude-standard', { cwd: worktreePath, timeoutMs: 30000 });
6925
+ if (listing.exitCode !== 0) throw new Error(`Unable to list untracked files: ${trimTail(listing.stderr || listing.stdout, 1200)}`);
6926
+ const untrackedFiles = listing.stdout.split('\0').filter(Boolean);
6927
+ let untrackedPatch = '';
6928
+ for (const file of untrackedFiles) {
6929
+ // --no-index exits 1 when the files differ, which is always the case here.
6930
+ const added = await runCommand(`git diff --no-index --binary -- /dev/null ${shellQuote(file)}`, { cwd: worktreePath, timeoutMs: 120000 });
6931
+ if (added.exitCode !== 1 || !added.stdout.startsWith('diff --git ')) {
6932
+ throw new Error(`Unable to export untracked file ${file}: ${trimTail(added.stderr || added.stdout, 1200)}`);
6933
+ }
6934
+ untrackedPatch += added.stdout.endsWith('\n') ? added.stdout : `${added.stdout}\n`;
6935
+ }
6936
+ const patch = `${tracked.stdout}${untrackedPatch}`;
6937
+ return { patch, untrackedFiles, contentSha256: createHash('sha256').update(patch).digest('hex') };
6938
+ }
6939
+
6532
6940
  export async function codeWorktreeDiff(root, queue, options = {}) {
6533
6941
  const normalized = normalizeLoopId(queue);
6534
6942
  const found = await findCodeWorktreeRun(root, normalized, options);
@@ -6554,7 +6962,8 @@ export async function codeWorktreeDiff(root, queue, options = {}) {
6554
6962
  diffStat: trimTail(diffStat.stdout, 12000),
6555
6963
  diffNameStatus: trimTail(diffNameStatus.stdout, 12000),
6556
6964
  untracked: trimTail(untracked.stdout, 12000),
6557
- patch: trimTail(patch.stdout, 60000)
6965
+ patch: trimTail(patch.stdout, 60000),
6966
+ patchTruncated: patch.stdout.length > 60000
6558
6967
  };
6559
6968
  }
6560
6969
 
@@ -6566,6 +6975,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6566
6975
  throw new Error(`Patch export already exists: ${path.relative(root, patchFile)}. Use --force to overwrite.`);
6567
6976
  }
6568
6977
  const manifestFile = `${patchFile}.json`;
6978
+ // The display diff above is truncated for readability; the export must be
6979
+ // the complete change, including untracked files, or cleanup would lose work.
6980
+ const pending = await worktreePendingPatch(diff.worktreePath);
6569
6981
  const header = [
6570
6982
  `# loop-engineering patch export`,
6571
6983
  `# queue: ${normalized}`,
@@ -6576,9 +6988,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6576
6988
  `# exportedAt: ${new Date().toISOString()}`,
6577
6989
  ''
6578
6990
  ].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`
6991
+ const patchBody = pending.patch;
6992
+ const untrackedBlock = pending.untrackedFiles.length
6993
+ ? `\n# Untracked files from worktree (included above as new-file diffs):\n${pending.untrackedFiles.map((line) => `# ${line}`).join('\n')}\n`
6582
6994
  : '';
6583
6995
  const patchContent = `${header}${patchBody}${untrackedBlock}`;
6584
6996
  await mkdir(path.dirname(patchFile), { recursive: true });
@@ -6595,6 +7007,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
6595
7007
  worktree: diff.worktree,
6596
7008
  patchFile: path.relative(root, patchFile),
6597
7009
  patchBytes: Buffer.byteLength(patchContent),
7010
+ complete: true,
7011
+ contentSha256: pending.contentSha256,
7012
+ untrackedIncluded: pending.untrackedFiles.length,
6598
7013
  diffStat: diff.diffStat,
6599
7014
  diffNameStatus: diff.diffNameStatus,
6600
7015
  untracked: diff.untracked
@@ -8379,6 +8794,13 @@ async function cleanupGate(root, queue, item) {
8379
8794
  if (!(await exists(reviewFile))) return { ok: false, reason: 'dirty_without_review_bundle' };
8380
8795
  const reviewJson = `${reviewFile}.json`;
8381
8796
  if (!(await exists(reviewJson))) return { ok: false, reason: 'dirty_without_review_json' };
8797
+ // A dirty worktree is force-removed only when its export is known to be
8798
+ // complete and the worktree has not changed since that export.
8799
+ const manifestFile = path.resolve(root, safeRelativePath(`${item.exportedPatchFile}.json`, 'patch manifest'));
8800
+ const manifest = await exists(manifestFile) ? await readJson(manifestFile).catch(() => null) : null;
8801
+ if (manifest?.complete !== true || typeof manifest.contentSha256 !== 'string') return { ok: false, reason: 'dirty_export_incomplete_reexport_required' };
8802
+ const current = await worktreePendingPatch(resolveWorktreePath(root, item.worktree.path));
8803
+ if (current.contentSha256 !== manifest.contentSha256) return { ok: false, reason: 'dirty_worktree_changed_since_export' };
8382
8804
  }
8383
8805
  return { ok: true, reason: null };
8384
8806
  }
@@ -8425,7 +8847,7 @@ function extractGitPatch(rawPatch) {
8425
8847
  if (start === -1) return '';
8426
8848
  let end = lines.length;
8427
8849
  for (let i = start; i < lines.length; i++) {
8428
- if (lines[i] === '# Untracked files from worktree:') {
8850
+ if (lines[i].startsWith('# Untracked files from worktree')) {
8429
8851
  end = i;
8430
8852
  break;
8431
8853
  }
@@ -8462,9 +8884,35 @@ async function runPatchApplyCheck(root, patch, timeoutMs) {
8462
8884
  }
8463
8885
  }
8464
8886
 
8887
+ // git C-quotes paths with non-ASCII or special characters, e.g.
8888
+ // "a/\351\241\271.txt"; decode the escapes (octal bytes are UTF-8).
8889
+ function unquoteGitPath(quoted) {
8890
+ const bytes = [];
8891
+ const simple = { n: 10, t: 9, r: 13, b: 8, f: 12, a: 7, v: 11, '"': 34, '\\': 92 };
8892
+ for (let i = 1; i < quoted.length - 1; i++) {
8893
+ const char = quoted[i];
8894
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue; }
8895
+ const next = quoted[i + 1];
8896
+ if (/[0-7]/.test(next)) { bytes.push(Number.parseInt(quoted.slice(i + 1, i + 4), 8)); i += 3; }
8897
+ else { bytes.push(simple[next] ?? next.charCodeAt(0)); i += 1; }
8898
+ }
8899
+ return Buffer.from(bytes).toString('utf8');
8900
+ }
8901
+
8465
8902
  function diffFilesFromPatch(patch) {
8466
8903
  const files = [];
8904
+ const token = '("(?:[^"\\\\]|\\\\.)*"|\\S+)';
8905
+ const header = new RegExp(`^diff --git ${token} ${token}$`);
8906
+ const strip = (value) => {
8907
+ const unquoted = value.startsWith('"') ? unquoteGitPath(value) : value;
8908
+ return unquoted.replace(/^[ab]\//, '');
8909
+ };
8467
8910
  for (const line of patch.split('\n')) {
8911
+ const quoted = header.exec(line);
8912
+ if (quoted && (quoted[1].startsWith('"') || quoted[2].startsWith('"'))) {
8913
+ files.push({ oldPath: strip(quoted[1]), newPath: strip(quoted[2]) });
8914
+ continue;
8915
+ }
8468
8916
  const match = /^diff --git a\/(.+?) b\/(.+)$/.exec(line);
8469
8917
  if (match) files.push({ oldPath: match[1], newPath: match[2] });
8470
8918
  }
@@ -9050,15 +9498,44 @@ async function recoverStaleActive(root, queue, staleActiveMs) {
9050
9498
  return recovered;
9051
9499
  }
9052
9500
 
9053
- async function recoverOrphanActive(root, queue, recoveryReason = 'queue_lock_reacquired_with_active_task') {
9501
+ const DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS = 3;
9502
+
9503
+ async function recoverOrphanActive(root, queue, recoveryReason = 'queue_lock_reacquired_with_active_task', options = {}) {
9054
9504
  const activeDir = queueSubdirFor(root, queue, 'active');
9055
9505
  const inboxDir = queueSubdirFor(root, queue, 'inbox');
9056
9506
  const files = await listJson(activeDir);
9057
9507
  const recovered = [];
9508
+ const maxAttempts = Number(options.retry?.orphanRecoveryMaxAttempts ?? DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS);
9058
9509
  for (const file of files) {
9059
9510
  const activeFile = path.join(activeDir, file);
9060
- const task = await readJson(activeFile);
9511
+ let task;
9512
+ try {
9513
+ task = await readJson(activeFile);
9514
+ } catch (error) {
9515
+ const quarantined = await quarantineQueueFile(root, queue, activeFile, `unreadable active task: ${error instanceof Error ? error.message : String(error)}`);
9516
+ recovered.push({ taskId: null, from: path.relative(root, activeFile), quarantined, outcome: 'quarantined_unreadable' });
9517
+ continue;
9518
+ }
9519
+ // A copy that already reached a terminal or waiting state was re-created
9520
+ // by a late writer; running it again would repeat finished work.
9521
+ let settledElsewhere = null;
9522
+ for (const subdir of ['done', 'failed', 'canceled', 'waiting']) {
9523
+ if (await exists(path.join(queueSubdirFor(root, queue, subdir), file))) { settledElsewhere = subdir; break; }
9524
+ }
9525
+ if (settledElsewhere) {
9526
+ const quarantined = await quarantineQueueFile(root, queue, activeFile, `stale active copy; task already in ${settledElsewhere}/`);
9527
+ recovered.push({ taskId: task.id, from: path.relative(root, activeFile), quarantined, outcome: 'quarantined_duplicate', settledIn: settledElsewhere });
9528
+ continue;
9529
+ }
9061
9530
  const recoveredAt = new Date().toISOString();
9531
+ // A task that keeps taking its runner down must not be replayed forever.
9532
+ if ((task.orphanRecoveryCount ?? 0) >= maxAttempts) {
9533
+ const failedFile = path.join(queueSubdirFor(root, queue, 'failed'), file);
9534
+ await rename(activeFile, failedFile);
9535
+ await writeJson(failedFile, { ...task, status: 'orphan_recovery_exhausted', orphanRecoveryExhaustedAt: recoveredAt, recoveryReason });
9536
+ recovered.push({ taskId: task.id, from: path.relative(root, activeFile), file: path.relative(root, failedFile), recoveredAt, outcome: 'orphan_recovery_exhausted' });
9537
+ continue;
9538
+ }
9062
9539
  const inboxFile = path.join(inboxDir, file);
9063
9540
  // Move first so a crash cannot leave duplicate active/inbox copies.
9064
9541
  await rename(activeFile, inboxFile);
@@ -9143,7 +9620,10 @@ const DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS = [
9143
9620
  const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
9144
9621
  { category: 'incomplete_turn', pattern: '"kind": "incomplete_turn"' },
9145
9622
  { category: 'incomplete_turn', pattern: '"livenessState": "abandoned"' },
9146
- { category: 'incomplete_turn', pattern: 'stopped before confirming the turn was complete' },
9623
+ // Free-text signatures can also appear in a successful task's own answer
9624
+ // (for example a task that implements rate limiting). Only the structured
9625
+ // runtime trailers above may override exitCode=0.
9626
+ { category: 'incomplete_turn', pattern: 'stopped before confirming the turn was complete', nonZeroOnly: true },
9147
9627
  // The OpenClaw embedded runner injects a recovery prompt when an assistant
9148
9628
  // turn completes its tool calls without a user-visible answer. A dispatch
9149
9629
  // that exits non-zero with this signature hit a session protocol failure,
@@ -9157,12 +9637,12 @@ const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
9157
9637
  { category: 'gateway_restart', pattern: 'gateway websocket admission closed', nonZeroOnly: true },
9158
9638
  { category: 'gateway_restart', pattern: 'gateway is draining for restart', nonZeroOnly: true },
9159
9639
  { 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' }
9640
+ { category: 'compaction_timeout', pattern: 'compaction timed out', nonZeroOnly: true },
9641
+ { category: 'compaction_timeout', pattern: 'transcript compaction failed', nonZeroOnly: true },
9642
+ { category: 'transport_error', pattern: 'connection reset', nonZeroOnly: true },
9643
+ { category: 'transport_error', pattern: 'socket hang up', nonZeroOnly: true },
9644
+ { category: 'transport_error', pattern: 'network error', nonZeroOnly: true },
9645
+ { category: 'rate_limit', pattern: 'rate limit', nonZeroOnly: true }
9166
9646
  ];
9167
9647
 
9168
9648
  export function dispatchFailureClassification(result, retry = {}) {
@@ -9392,10 +9872,27 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
9392
9872
  const worktreeDir = path.join(baseDir, shortTask);
9393
9873
  const prefix = sanitizeBranchSegment(config.branchPrefix ?? `loop/${queue}`);
9394
9874
  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
- });
9875
+ const setupTimeoutMs = config.setupTimeoutMs ?? 120000;
9876
+ // A requeued task (runtime recovery, project continuation, operator
9877
+ // requeue) keeps its id, so its branch and worktree may already exist.
9878
+ // Continue in them instead of failing on `git worktree add -b`.
9879
+ let add;
9880
+ let reused = false;
9881
+ if (await exists(worktreeDir)) {
9882
+ const current = await runCommand('git rev-parse --abbrev-ref HEAD', { cwd: worktreeDir, timeoutMs: 30000 });
9883
+ if (current.exitCode === 0 && current.stdout.trim() === branch) {
9884
+ add = current;
9885
+ reused = true;
9886
+ } else {
9887
+ add = { ...current, exitCode: current.exitCode || 1, stderr: `${current.stderr}Existing ${path.relative(root, worktreeDir)} is not a worktree of ${branch}; refusing to reuse it.` };
9888
+ }
9889
+ } else {
9890
+ await runCommand('git worktree prune', { cwd: root, timeoutMs: 30000 });
9891
+ const branchExists = (await runCommand(`git rev-parse --verify --quiet ${shellQuote(`refs/heads/${branch}`)}`, { cwd: root, timeoutMs: 30000 })).exitCode === 0;
9892
+ add = branchExists
9893
+ ? await runCommand(`git worktree add ${shellQuote(worktreeDir)} ${shellQuote(branch)}`, { cwd: root, timeoutMs: setupTimeoutMs })
9894
+ : await runCommand(`git worktree add -b ${shellQuote(branch)} ${shellQuote(worktreeDir)} HEAD`, { cwd: root, timeoutMs: setupTimeoutMs });
9895
+ }
9399
9896
  const head = add.exitCode === 0
9400
9897
  ? await runCommand('git rev-parse HEAD', { cwd: worktreeDir, timeoutMs: 30000 })
9401
9898
  : null;
@@ -9405,6 +9902,7 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
9405
9902
  pathRel: path.relative(root, worktreeDir),
9406
9903
  branch,
9407
9904
  setup: compactCommandResult(add),
9905
+ reused,
9408
9906
  head: head?.exitCode === 0 ? head.stdout.trim() : null,
9409
9907
  runId
9410
9908
  };
@@ -9507,6 +10005,13 @@ export async function runQueueOnce(root, options) {
9507
10005
  };
9508
10006
  }
9509
10007
 
10008
+ // Renew the lease while this runner works, so preflight, retries and
10009
+ // verification that outlast leaseMs are not reclaimed and re-executed.
10010
+ const leaseRenewal = setInterval(() => {
10011
+ renewQueueLock(root, queue, lockResult.lock, leaseMs).catch(() => {});
10012
+ }, Math.max(250, Math.floor(leaseMs / 3)));
10013
+ leaseRenewal.unref();
10014
+
9510
10015
  try {
9511
10016
  // Holding this newly acquired lock proves no previous runner owns a valid
9512
10017
  // queue lease. Any task left in active/ is therefore an orphan from an
@@ -9515,7 +10020,7 @@ export async function runQueueOnce(root, options) {
9515
10020
  const recoveryReason = lockResult.reclaimedLock?.reason === 'dead_owner_pid'
9516
10021
  ? 'dead_queue_lock_owner_pid'
9517
10022
  : 'queue_lock_reacquired_with_active_task';
9518
- const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason);
10023
+ const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason, options);
9519
10024
  if (orphanRecovered.length > 0) {
9520
10025
  progress.emit('queue', 'orphan_recovered', `Recovered ${orphanRecovered.length} orphan active task(s)`, {
9521
10026
  queue,
@@ -9530,7 +10035,21 @@ export async function runQueueOnce(root, options) {
9530
10035
  count: staleRecovered.length
9531
10036
  });
9532
10037
  }
9533
- const inboxFile = await nextQueuedTaskFile(root, queue);
10038
+ let inboxFile = await nextQueuedTaskFile(root, queue);
10039
+ let task = null;
10040
+ const quarantined = [];
10041
+ while (inboxFile) {
10042
+ try {
10043
+ task = await readJson(inboxFile);
10044
+ break;
10045
+ } catch (error) {
10046
+ quarantined.push(await quarantineQueueFile(root, queue, inboxFile, `unreadable queued task: ${error instanceof Error ? error.message : String(error)}`));
10047
+ inboxFile = await nextQueuedTaskFile(root, queue);
10048
+ }
10049
+ }
10050
+ if (quarantined.length) {
10051
+ progress.emit('queue', 'quarantined', `Quarantined ${quarantined.length} unreadable queued task file(s)`, { queue, files: quarantined });
10052
+ }
9534
10053
  if (!inboxFile) {
9535
10054
  progress.emit('queue', 'empty', `Queue ${queue} has no queued tasks`, {
9536
10055
  queue
@@ -9546,7 +10065,6 @@ export async function runQueueOnce(root, options) {
9546
10065
  };
9547
10066
  }
9548
10067
 
9549
- const task = await readJson(inboxFile);
9550
10068
  progressTask = task;
9551
10069
  const activeFile = path.join(queueSubdirFor(root, queue, 'active'), path.basename(inboxFile));
9552
10070
  await rename(inboxFile, activeFile);
@@ -9621,8 +10139,9 @@ export async function runQueueOnce(root, options) {
9621
10139
  } else {
9622
10140
  progress.emit('preflight', 'skipped', 'No preflight configured');
9623
10141
  }
10142
+ const supersede = await currentSupersedeRequest(root, queue, task);
9624
10143
  const supersedeFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
9625
- if (await exists(supersedeFile)) {
10144
+ if (supersede) {
9626
10145
  finalStatus = 'superseded';
9627
10146
  progress.emit('queue', 'superseded', 'A newer loop request replaced this task at a safe checkpoint', {
9628
10147
  taskId: task.id,
@@ -9718,7 +10237,7 @@ export async function runQueueOnce(root, options) {
9718
10237
  });
9719
10238
  if (finalStatus === 'superseded') {
9720
10239
  const requestFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
9721
- const request = await readJson(requestFile);
10240
+ const request = await readJson(requestFile).catch(() => ({}));
9722
10241
  acceptanceReviews = { count: 0, accepted: 0, revise: 0, blocked: 0, reviews: [] };
9723
10242
  const judgementFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'final_judgement.json');
9724
10243
  const judgement = {
@@ -9831,8 +10350,17 @@ export async function runQueueOnce(root, options) {
9831
10350
  completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
9832
10351
  }
9833
10352
  const completedFile = path.join(destination, path.basename(activeFile));
9834
- await writeJson(completedFile, completedTask);
9835
- await rm(activeFile, { force: true });
10353
+ // Claim the active file by moving it. If an operator canceled or parked
10354
+ // the task meanwhile, the file is gone and their copy stays authoritative
10355
+ // instead of a second copy being written to done/ or failed/.
10356
+ let movedByOperator = false;
10357
+ try {
10358
+ await rename(activeFile, completedFile);
10359
+ } catch (error) {
10360
+ if (error?.code !== 'ENOENT') throw error;
10361
+ movedByOperator = true;
10362
+ }
10363
+ if (!movedByOperator) await writeJson(completedFile, completedTask);
9836
10364
 
9837
10365
  const run = {
9838
10366
  version: 2,
@@ -9843,6 +10371,7 @@ export async function runQueueOnce(root, options) {
9843
10371
  startedAt,
9844
10372
  finishedAt,
9845
10373
  status: finalStatus,
10374
+ ...(movedByOperator ? { movedByOperator: true } : {}),
9846
10375
  retry: options.retry ?? null,
9847
10376
  taskContract: taskContract ? {
9848
10377
  path: taskContract.file,
@@ -9899,6 +10428,7 @@ export async function runQueueOnce(root, options) {
9899
10428
  branch: worktree.branch,
9900
10429
  head: worktree.head,
9901
10430
  setup: worktree.setup,
10431
+ reused: Boolean(worktree.reused),
9902
10432
  inspection: worktreeInspection
9903
10433
  } : null,
9904
10434
  verification,
@@ -9918,21 +10448,24 @@ export async function runQueueOnce(root, options) {
9918
10448
  }
9919
10449
  await writeJson(runPath, run);
9920
10450
 
9921
- if (options.notifyCommand) {
10451
+ if (options.notifyCommand && !movedByOperator) {
9922
10452
  const detail = dispatch?.stdout || dispatch?.stderr || preflight?.stdout || preflight?.stderr || '';
10453
+ // NUL cannot travel in a command line; drop it rather than lose the
10454
+ // notification and everything after it.
9923
10455
  const message = [
9924
10456
  `Loop queue task ${finalStatus}: ${task.title}`,
9925
10457
  `queue: ${queue}`,
9926
10458
  `run: ${run.runPath}`,
9927
10459
  trimTail(detail, 1200)
9928
- ].filter(Boolean).join('\n');
9929
- await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
10460
+ ].filter(Boolean).join('\n').replace(/\0/g, '');
10461
+ run.notification = compactCommandResult(await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
9930
10462
  cwd: root,
9931
10463
  timeoutMs: 60 * 1000
9932
- });
10464
+ }));
10465
+ await writeJson(runPath, run);
9933
10466
  }
9934
10467
 
9935
- if (finalStatus === 'completed') {
10468
+ if (finalStatus === 'completed' && !movedByOperator) {
9936
10469
  try {
9937
10470
  run.projectRelay = await projectRelayNext(root, { queue, task, finalJudgement: finalJudgement?.judgement });
9938
10471
  } catch (error) {
@@ -9954,6 +10487,7 @@ export async function runQueueOnce(root, options) {
9954
10487
  progressNotifications
9955
10488
  };
9956
10489
  } finally {
10490
+ clearInterval(leaseRenewal);
9957
10491
  await releaseQueueLock(root, queue, lockResult.lock);
9958
10492
  }
9959
10493
  }