taskforce-loop-engineering 0.15.20 → 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.
- package/CHANGELOG.md +59 -0
- package/MIGRATING.md +80 -0
- package/README.md +43 -4
- package/bin/loop-engineering.mjs +142 -114
- package/docs/architecture.md +3 -2
- package/docs/human-gate-command.md +1 -1
- package/docs/operator-dashboard.md +16 -5
- package/docs/operator-workspace-project.md +2 -2
- package/docs/production-trust-contract.md +9 -2
- package/docs/transactional-kernel-and-goal-api.md +3 -1
- package/lib/action-reservations.mjs +21 -23
- package/lib/core.mjs +695 -88
- package/lib/durable-journal.mjs +23 -6
- package/lib/execution-ledger.mjs +4 -4
- package/lib/file-mutex.mjs +102 -0
- package/lib/human-gate-channel-adapter.mjs +4 -2
- package/lib/human-gate-command.mjs +5 -3
- package/lib/operator-dashboard.mjs +72 -10
- package/lib/production-evidence.mjs +37 -15
- package/lib/quota-runtime-decision.mjs +11 -6
- package/lib/redaction.mjs +34 -0
- package/lib/todo-control-plane.mjs +12 -16
- package/lib/transactional-state-kernel.mjs +96 -18
- package/package.json +2 -3
- package/scripts/dashboard-autostart-install.mjs +33 -8
- package/scripts/dashboard-autostart-self-test.mjs +12 -3
- package/scripts/final-judgement-self-test.mjs +21 -0
- package/scripts/hermes-install-self-test.mjs +8 -1
- package/scripts/hermes-install.mjs +29 -8
- package/scripts/hermes-smoke.mjs +2 -1
- package/scripts/human-gate-command-self-test.mjs +34 -5
- package/scripts/install-shared.mjs +61 -0
- package/scripts/openclaw-install-self-test.mjs +71 -1
- package/scripts/openclaw-install.mjs +50 -19
- package/scripts/openclaw-manage.mjs +22 -3
- package/scripts/openclaw-smoke.mjs +2 -1
- package/scripts/project-relay-self-test.mjs +184 -2
- package/scripts/run-loop-cron.sh +22 -7
- package/scripts/safety-regression-self-test.mjs +349 -0
- 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
|
-
|
|
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 &&
|
|
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
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
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
|
-
|
|
353
|
-
child.
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
1131
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
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
|
-
|
|
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,123 @@ async function projectHasSafeActionableBacklog(root, spec, checkpoint = null) {
|
|
|
2590
2706
|
});
|
|
2591
2707
|
}
|
|
2592
2708
|
|
|
2593
|
-
|
|
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 } = {}) {
|
|
2724
|
+
project = normalizeProjectId(project);
|
|
2725
|
+
const spec = await readJson(projectConfigPathFor(root, project));
|
|
2726
|
+
if (spec.relayStatusReconciliation !== true || !spec.backlogSource
|
|
2727
|
+
|| !spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true)) return { changed: 0 };
|
|
2728
|
+
const acceptance = await projectAcceptanceRecord(root, spec);
|
|
2729
|
+
const ledger = acceptance?.record;
|
|
2730
|
+
if (!ledger || typeof ledger !== 'object' || Array.isArray(ledger)
|
|
2731
|
+
|| !['in_progress', 'ongoing'].includes(ledger.status)
|
|
2732
|
+
|| ledger.terminalState?.accepted === true || ledger.terminalAccepted === true) return { changed: 0 };
|
|
2733
|
+
const backlogFile = path.resolve(root, safeRelativePath(spec.backlogSource, 'project backlog source'));
|
|
2734
|
+
let backlogText;
|
|
2735
|
+
let backlog;
|
|
2736
|
+
try {
|
|
2737
|
+
backlogText = await readFile(backlogFile, 'utf8');
|
|
2738
|
+
backlog = JSON.parse(backlogText);
|
|
2739
|
+
} catch { return { changed: 0 }; }
|
|
2740
|
+
if (!backlog || typeof backlog !== 'object' || Array.isArray(backlog)) return { changed: 0 };
|
|
2741
|
+
const field = Array.isArray(backlog.items) ? 'items' : Array.isArray(backlog.tasks) ? 'tasks' : null;
|
|
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
|
+
};
|
|
2766
|
+
const completed = new Map();
|
|
2767
|
+
for (const { task, subdir } of finished.values()) {
|
|
2768
|
+
if (subdir !== 'done' || task.projectId !== project || task.status !== 'completed'
|
|
2769
|
+
|| typeof task.backlogItemId !== 'string'
|
|
2770
|
+
|| !task.source?.channel || !task.source?.target || !task.source?.account || !task.source?.message_id) continue;
|
|
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);
|
|
2777
|
+
}
|
|
2778
|
+
const itemCounts = new Map();
|
|
2779
|
+
for (const item of backlog[field]) {
|
|
2780
|
+
if (item?.id) itemCounts.set(item.id, (itemCounts.get(item.id) ?? 0) + 1);
|
|
2781
|
+
}
|
|
2782
|
+
let changed = 0;
|
|
2783
|
+
const items = [];
|
|
2784
|
+
for (const item of backlog[field]) {
|
|
2785
|
+
if (!item || typeof item !== 'object' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(item.id ?? ''))
|
|
2786
|
+
|| itemCounts.get(item.id) !== 1
|
|
2787
|
+
|| completed.get(item.id)?.roots.size !== 1
|
|
2788
|
+
|| item.status !== 'ready' || item.autoRun !== true || item.scope !== 'local_only'
|
|
2789
|
+
|| item.externalActionsAllowed !== false || item.humanGateRequired !== false) {
|
|
2790
|
+
items.push(item);
|
|
2791
|
+
continue;
|
|
2792
|
+
}
|
|
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) {
|
|
2802
|
+
items.push(item);
|
|
2803
|
+
continue;
|
|
2804
|
+
}
|
|
2805
|
+
items.push({ ...item, status: 'completed' });
|
|
2806
|
+
changed += 1;
|
|
2807
|
+
}
|
|
2808
|
+
if (changed) {
|
|
2809
|
+
const temporary = `${backlogFile}.${process.pid}.tmp`;
|
|
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
|
+
}
|
|
2820
|
+
await rename(temporary, backlogFile);
|
|
2821
|
+
}
|
|
2822
|
+
return { changed };
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
export async function projectRelayNext(root, { queue, task, finalJudgement, tasks } = {}) {
|
|
2594
2826
|
if (!task?.projectId || finalJudgement?.outcome !== 'ready_to_apply' || finalJudgement.requires_human_gate) return null;
|
|
2595
2827
|
const project = normalizeProjectId(task.projectId);
|
|
2596
2828
|
const spec = await readJson(projectConfigPathFor(root, project));
|
|
@@ -2607,25 +2839,27 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
|
|
|
2607
2839
|
if (typeof predecessorId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(predecessorId)) return null;
|
|
2608
2840
|
const queueState = await queueStatus(root, queue);
|
|
2609
2841
|
if (queueState.queued || queueState.active || queueState.waiting) return null;
|
|
2842
|
+
const snapshot = tasks ?? await relayTaskSnapshot(root, queue);
|
|
2843
|
+
await projectRelayReconcile(root, { queue, project, tasks: snapshot });
|
|
2610
2844
|
const backlogSource = spec.backlogSource ?? spec.authoritativeBacklog;
|
|
2611
2845
|
if (typeof backlogSource !== 'string' || !backlogSource.trim()) return null;
|
|
2612
2846
|
let backlog;
|
|
2613
2847
|
try {
|
|
2614
2848
|
backlog = await readJson(path.resolve(root, safeRelativePath(backlogSource, 'project backlog source')));
|
|
2615
2849
|
} catch { return null; }
|
|
2616
|
-
const
|
|
2617
|
-
if (!
|
|
2618
|
-
|
|
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]));
|
|
2619
2858
|
const complete = new Set(['accepted', 'complete', 'completed', 'done', 'phase_complete']);
|
|
2620
2859
|
if (!complete.has(byId.get(predecessorId)?.status)) return null;
|
|
2621
|
-
const queuedBodies = [];
|
|
2622
|
-
for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
|
|
2623
|
-
for (const file of await listJson(queueSubdirFor(root, queue, subdir))) {
|
|
2624
|
-
queuedBodies.push(String((await readJson(path.join(queueSubdirFor(root, queue, subdir), file))).body ?? ''));
|
|
2625
|
-
}
|
|
2626
|
-
}
|
|
2860
|
+
const queuedBodies = RELAY_TASK_SUBDIRS.flatMap((subdir) => snapshot[subdir].map((entry) => String(entry?.body ?? '')));
|
|
2627
2861
|
const item = items.find((candidate) => {
|
|
2628
|
-
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;
|
|
2629
2863
|
if (candidate.status !== 'ready' || candidate.autoRun !== true || candidate.scope !== 'local_only'
|
|
2630
2864
|
|| candidate.externalActionsAllowed !== false || candidate.humanGateRequired !== false
|
|
2631
2865
|
|| candidate.blocked === true || candidate.requires_human_input === true
|
|
@@ -2648,6 +2882,29 @@ export async function projectRelayNext(root, { queue, task, finalJudgement } = {
|
|
|
2648
2882
|
return { project, itemId: item.id, taskId: result.task.id, file: result.file };
|
|
2649
2883
|
}
|
|
2650
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
|
+
|
|
2651
2908
|
async function tasksById(root, queue) {
|
|
2652
2909
|
const tasks = new Map();
|
|
2653
2910
|
for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
|
|
@@ -4644,6 +4901,31 @@ function decideQueueProgressNotification(previousProgress, policy, observed, sch
|
|
|
4644
4901
|
};
|
|
4645
4902
|
}
|
|
4646
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
|
+
|
|
4647
4929
|
export async function queueSchedulerTick(root, options) {
|
|
4648
4930
|
const queue = normalizeLoopId(options.queue);
|
|
4649
4931
|
await ensureQueueDirs(root, queue);
|
|
@@ -4686,6 +4968,75 @@ export async function queueSchedulerTick(root, options) {
|
|
|
4686
4968
|
status = statusBefore.queued > 0 ? 'planned_due' : 'empty';
|
|
4687
4969
|
}
|
|
4688
4970
|
|
|
4971
|
+
const relayReconciliation = [];
|
|
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) {
|
|
4982
|
+
try {
|
|
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);
|
|
5036
|
+
}
|
|
5037
|
+
}
|
|
5038
|
+
}
|
|
5039
|
+
|
|
4689
5040
|
const statusAfter = await queueStatus(root, queue);
|
|
4690
5041
|
const run = runResult?.run ?? null;
|
|
4691
5042
|
const observed = {
|
|
@@ -4776,6 +5127,9 @@ export async function queueSchedulerTick(root, options) {
|
|
|
4776
5127
|
progressReportPath: path.relative(root, queueProgressStatePath(root, queue)),
|
|
4777
5128
|
statusBefore,
|
|
4778
5129
|
statusAfter,
|
|
5130
|
+
relayReconciliation,
|
|
5131
|
+
relayMaintenance,
|
|
5132
|
+
projectRelay,
|
|
4779
5133
|
run: runResult
|
|
4780
5134
|
};
|
|
4781
5135
|
}
|
|
@@ -4951,15 +5305,68 @@ function queueLockOwnerAlive(lock) {
|
|
|
4951
5305
|
return Boolean(lock && processIsAlive(lock.pid));
|
|
4952
5306
|
}
|
|
4953
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
|
+
|
|
4954
5327
|
async function acquireQueueLock(root, queue, leaseMs) {
|
|
4955
5328
|
const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
|
|
4956
5329
|
const now = Date.now();
|
|
4957
|
-
const
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
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
|
+
}
|
|
4961
5363
|
}
|
|
4962
|
-
|
|
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();
|
|
4963
5370
|
const lock = {
|
|
4964
5371
|
version: 1,
|
|
4965
5372
|
queue,
|
|
@@ -4967,28 +5374,26 @@ async function acquireQueueLock(root, queue, leaseMs) {
|
|
|
4967
5374
|
acquiredAt: new Date(now).toISOString(),
|
|
4968
5375
|
expiresAt: new Date(now + leaseMs).toISOString()
|
|
4969
5376
|
};
|
|
4970
|
-
let handle = null;
|
|
4971
5377
|
try {
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
return {
|
|
4975
|
-
acquired: true,
|
|
4976
|
-
lock,
|
|
4977
|
-
reclaimedLock: existing ? {
|
|
4978
|
-
lock: existing,
|
|
4979
|
-
reason: existingOwnerAlive ? 'expired_lease' : 'dead_owner_pid'
|
|
4980
|
-
} : null
|
|
4981
|
-
};
|
|
5378
|
+
await writeJsonExclusive(lockFile, lock);
|
|
5379
|
+
return { acquired: true, lock, reclaimedLock };
|
|
4982
5380
|
} catch (err) {
|
|
4983
5381
|
if (err && err.code === 'EEXIST') {
|
|
4984
5382
|
return { acquired: false, lock: await readQueueLock(root, queue) };
|
|
4985
5383
|
}
|
|
4986
5384
|
throw err;
|
|
4987
|
-
} finally {
|
|
4988
|
-
if (handle) await handle.close();
|
|
4989
5385
|
}
|
|
4990
5386
|
}
|
|
4991
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
|
+
|
|
4992
5397
|
async function releaseQueueLock(root, queue, lock) {
|
|
4993
5398
|
const lockFile = path.join(queueDirFor(root, queue), 'queue.lock');
|
|
4994
5399
|
const current = await readQueueLock(root, queue);
|
|
@@ -5004,7 +5409,9 @@ async function nextQueuedTaskFile(root, queue) {
|
|
|
5004
5409
|
}
|
|
5005
5410
|
|
|
5006
5411
|
async function findTaskFile(root, queue, taskId, subdirs = ['inbox', 'active', 'waiting', 'failed', 'done', 'canceled']) {
|
|
5007
|
-
|
|
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`;
|
|
5008
5415
|
for (const subdir of subdirs) {
|
|
5009
5416
|
const file = path.join(queueSubdirFor(root, queue, subdir), wanted);
|
|
5010
5417
|
if (await exists(file)) return { file, subdir };
|
|
@@ -5033,6 +5440,35 @@ export async function queuePeek(root, queue, options = {}) {
|
|
|
5033
5440
|
return { queue: normalized, tasks };
|
|
5034
5441
|
}
|
|
5035
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
|
+
|
|
5036
5472
|
export async function queueCancel(root, queue, taskId, options = {}) {
|
|
5037
5473
|
const normalized = normalizeLoopId(queue);
|
|
5038
5474
|
await ensureQueueDirs(root, normalized);
|
|
@@ -5040,6 +5476,9 @@ export async function queueCancel(root, queue, taskId, options = {}) {
|
|
|
5040
5476
|
if (!found) throw new Error(`Task not found in cancelable state: ${taskId}`);
|
|
5041
5477
|
const task = await readJson(found.file);
|
|
5042
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);
|
|
5043
5482
|
await writeJson(canceledFile, {
|
|
5044
5483
|
...task,
|
|
5045
5484
|
status: 'canceled',
|
|
@@ -5047,7 +5486,7 @@ export async function queueCancel(root, queue, taskId, options = {}) {
|
|
|
5047
5486
|
canceledFrom: found.subdir,
|
|
5048
5487
|
cancelReason: options.reason ?? null
|
|
5049
5488
|
});
|
|
5050
|
-
|
|
5489
|
+
if (found.subdir === 'active') await requestTaskStop(root, normalized, task.id, 'operator_cancel');
|
|
5051
5490
|
return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, canceledFile) };
|
|
5052
5491
|
}
|
|
5053
5492
|
|
|
@@ -5060,13 +5499,16 @@ export async function queueRequeue(root, queue, taskId, options = {}) {
|
|
|
5060
5499
|
if (!found) throw new Error(`Task not found in requeueable state: ${taskId}`);
|
|
5061
5500
|
const task = await readJson(found.file);
|
|
5062
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();
|
|
5063
5505
|
await writeJson(inboxFile, {
|
|
5064
5506
|
...task,
|
|
5065
5507
|
status: 'queued',
|
|
5066
|
-
requeuedAt
|
|
5067
|
-
requeuedFrom: found.subdir
|
|
5508
|
+
requeuedAt,
|
|
5509
|
+
requeuedFrom: found.subdir,
|
|
5510
|
+
supersedeClearedAt: requeuedAt
|
|
5068
5511
|
});
|
|
5069
|
-
await rm(found.file, { force: true });
|
|
5070
5512
|
return { queue: normalized, taskId: task.id, from: found.subdir, file: path.relative(root, inboxFile) };
|
|
5071
5513
|
}
|
|
5072
5514
|
|
|
@@ -5642,11 +6084,27 @@ export async function queueRevisionPlan(root, queue, taskId, options = {}) {
|
|
|
5642
6084
|
};
|
|
5643
6085
|
}
|
|
5644
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
|
+
|
|
5645
6102
|
export async function queueRevisionNext(root, queue, taskId, options = {}) {
|
|
5646
6103
|
const plan = await queueRevisionPlan(root, queue, taskId, options);
|
|
5647
6104
|
if (!plan.revisionPolicyGuard.allowed) {
|
|
5648
6105
|
throw new Error(`Revision guard blocked next round for ${taskId}: ${plan.revisionPolicyGuard.reasons.join('; ')}`);
|
|
5649
6106
|
}
|
|
6107
|
+
await assertNoRevisionChild(root, plan.queue, plan.plannedTask.revisionOf, options);
|
|
5650
6108
|
const enqueued = await enqueueTask(root, {
|
|
5651
6109
|
queue: plan.queue,
|
|
5652
6110
|
title: plan.plannedTask.title,
|
|
@@ -5701,6 +6159,7 @@ export async function queueRevisionApplyPlan(root, planPath, options = {}) {
|
|
|
5701
6159
|
const reasons = plan.revisionPolicyGuard?.reasons?.join('; ') || 'plan canEnqueue=false';
|
|
5702
6160
|
throw new Error(`Revision plan is blocked for ${plan.sourceTaskId ?? 'unknown source task'}: ${reasons}. Use --force to override.`);
|
|
5703
6161
|
}
|
|
6162
|
+
await assertNoRevisionChild(root, normalized, plan.plannedTask.revisionOf ?? plan.sourceTaskId, options);
|
|
5704
6163
|
|
|
5705
6164
|
const enqueued = await enqueueTask(root, {
|
|
5706
6165
|
queue: normalized,
|
|
@@ -6456,6 +6915,28 @@ export async function codeWorktreeInspect(root, queue, options = {}) {
|
|
|
6456
6915
|
};
|
|
6457
6916
|
}
|
|
6458
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
|
+
|
|
6459
6940
|
export async function codeWorktreeDiff(root, queue, options = {}) {
|
|
6460
6941
|
const normalized = normalizeLoopId(queue);
|
|
6461
6942
|
const found = await findCodeWorktreeRun(root, normalized, options);
|
|
@@ -6481,7 +6962,8 @@ export async function codeWorktreeDiff(root, queue, options = {}) {
|
|
|
6481
6962
|
diffStat: trimTail(diffStat.stdout, 12000),
|
|
6482
6963
|
diffNameStatus: trimTail(diffNameStatus.stdout, 12000),
|
|
6483
6964
|
untracked: trimTail(untracked.stdout, 12000),
|
|
6484
|
-
patch: trimTail(patch.stdout, 60000)
|
|
6965
|
+
patch: trimTail(patch.stdout, 60000),
|
|
6966
|
+
patchTruncated: patch.stdout.length > 60000
|
|
6485
6967
|
};
|
|
6486
6968
|
}
|
|
6487
6969
|
|
|
@@ -6493,6 +6975,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
|
|
|
6493
6975
|
throw new Error(`Patch export already exists: ${path.relative(root, patchFile)}. Use --force to overwrite.`);
|
|
6494
6976
|
}
|
|
6495
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);
|
|
6496
6981
|
const header = [
|
|
6497
6982
|
`# loop-engineering patch export`,
|
|
6498
6983
|
`# queue: ${normalized}`,
|
|
@@ -6503,9 +6988,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
|
|
|
6503
6988
|
`# exportedAt: ${new Date().toISOString()}`,
|
|
6504
6989
|
''
|
|
6505
6990
|
].join('\n');
|
|
6506
|
-
const patchBody =
|
|
6507
|
-
const untrackedBlock =
|
|
6508
|
-
? `\n# Untracked files from worktree:\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`
|
|
6509
6994
|
: '';
|
|
6510
6995
|
const patchContent = `${header}${patchBody}${untrackedBlock}`;
|
|
6511
6996
|
await mkdir(path.dirname(patchFile), { recursive: true });
|
|
@@ -6522,6 +7007,9 @@ export async function codeWorktreeExport(root, queue, options = {}) {
|
|
|
6522
7007
|
worktree: diff.worktree,
|
|
6523
7008
|
patchFile: path.relative(root, patchFile),
|
|
6524
7009
|
patchBytes: Buffer.byteLength(patchContent),
|
|
7010
|
+
complete: true,
|
|
7011
|
+
contentSha256: pending.contentSha256,
|
|
7012
|
+
untrackedIncluded: pending.untrackedFiles.length,
|
|
6525
7013
|
diffStat: diff.diffStat,
|
|
6526
7014
|
diffNameStatus: diff.diffNameStatus,
|
|
6527
7015
|
untracked: diff.untracked
|
|
@@ -8306,6 +8794,13 @@ async function cleanupGate(root, queue, item) {
|
|
|
8306
8794
|
if (!(await exists(reviewFile))) return { ok: false, reason: 'dirty_without_review_bundle' };
|
|
8307
8795
|
const reviewJson = `${reviewFile}.json`;
|
|
8308
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' };
|
|
8309
8804
|
}
|
|
8310
8805
|
return { ok: true, reason: null };
|
|
8311
8806
|
}
|
|
@@ -8352,7 +8847,7 @@ function extractGitPatch(rawPatch) {
|
|
|
8352
8847
|
if (start === -1) return '';
|
|
8353
8848
|
let end = lines.length;
|
|
8354
8849
|
for (let i = start; i < lines.length; i++) {
|
|
8355
|
-
if (lines[i]
|
|
8850
|
+
if (lines[i].startsWith('# Untracked files from worktree')) {
|
|
8356
8851
|
end = i;
|
|
8357
8852
|
break;
|
|
8358
8853
|
}
|
|
@@ -8389,9 +8884,35 @@ async function runPatchApplyCheck(root, patch, timeoutMs) {
|
|
|
8389
8884
|
}
|
|
8390
8885
|
}
|
|
8391
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
|
+
|
|
8392
8902
|
function diffFilesFromPatch(patch) {
|
|
8393
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
|
+
};
|
|
8394
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
|
+
}
|
|
8395
8916
|
const match = /^diff --git a\/(.+?) b\/(.+)$/.exec(line);
|
|
8396
8917
|
if (match) files.push({ oldPath: match[1], newPath: match[2] });
|
|
8397
8918
|
}
|
|
@@ -8977,15 +9498,44 @@ async function recoverStaleActive(root, queue, staleActiveMs) {
|
|
|
8977
9498
|
return recovered;
|
|
8978
9499
|
}
|
|
8979
9500
|
|
|
8980
|
-
|
|
9501
|
+
const DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS = 3;
|
|
9502
|
+
|
|
9503
|
+
async function recoverOrphanActive(root, queue, recoveryReason = 'queue_lock_reacquired_with_active_task', options = {}) {
|
|
8981
9504
|
const activeDir = queueSubdirFor(root, queue, 'active');
|
|
8982
9505
|
const inboxDir = queueSubdirFor(root, queue, 'inbox');
|
|
8983
9506
|
const files = await listJson(activeDir);
|
|
8984
9507
|
const recovered = [];
|
|
9508
|
+
const maxAttempts = Number(options.retry?.orphanRecoveryMaxAttempts ?? DEFAULT_ORPHAN_RECOVERY_MAX_ATTEMPTS);
|
|
8985
9509
|
for (const file of files) {
|
|
8986
9510
|
const activeFile = path.join(activeDir, file);
|
|
8987
|
-
|
|
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
|
+
}
|
|
8988
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
|
+
}
|
|
8989
9539
|
const inboxFile = path.join(inboxDir, file);
|
|
8990
9540
|
// Move first so a crash cannot leave duplicate active/inbox copies.
|
|
8991
9541
|
await rename(activeFile, inboxFile);
|
|
@@ -9070,7 +9620,10 @@ const DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS = [
|
|
|
9070
9620
|
const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
|
|
9071
9621
|
{ category: 'incomplete_turn', pattern: '"kind": "incomplete_turn"' },
|
|
9072
9622
|
{ category: 'incomplete_turn', pattern: '"livenessState": "abandoned"' },
|
|
9073
|
-
|
|
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 },
|
|
9074
9627
|
// The OpenClaw embedded runner injects a recovery prompt when an assistant
|
|
9075
9628
|
// turn completes its tool calls without a user-visible answer. A dispatch
|
|
9076
9629
|
// that exits non-zero with this signature hit a session protocol failure,
|
|
@@ -9084,12 +9637,12 @@ const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
|
|
|
9084
9637
|
{ category: 'gateway_restart', pattern: 'gateway websocket admission closed', nonZeroOnly: true },
|
|
9085
9638
|
{ category: 'gateway_restart', pattern: 'gateway is draining for restart', nonZeroOnly: true },
|
|
9086
9639
|
{ category: 'gateway_restart', pattern: 'unavailable during gateway restart', nonZeroOnly: true },
|
|
9087
|
-
{ category: 'compaction_timeout', pattern: 'compaction timed out' },
|
|
9088
|
-
{ category: 'compaction_timeout', pattern: 'transcript compaction failed' },
|
|
9089
|
-
{ category: 'transport_error', pattern: 'connection reset' },
|
|
9090
|
-
{ category: 'transport_error', pattern: 'socket hang up' },
|
|
9091
|
-
{ category: 'transport_error', pattern: 'network error' },
|
|
9092
|
-
{ 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 }
|
|
9093
9646
|
];
|
|
9094
9647
|
|
|
9095
9648
|
export function dispatchFailureClassification(result, retry = {}) {
|
|
@@ -9319,10 +9872,27 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
|
|
|
9319
9872
|
const worktreeDir = path.join(baseDir, shortTask);
|
|
9320
9873
|
const prefix = sanitizeBranchSegment(config.branchPrefix ?? `loop/${queue}`);
|
|
9321
9874
|
const branch = `${prefix}/${shortTask}`;
|
|
9322
|
-
const
|
|
9323
|
-
|
|
9324
|
-
|
|
9325
|
-
|
|
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
|
+
}
|
|
9326
9896
|
const head = add.exitCode === 0
|
|
9327
9897
|
? await runCommand('git rev-parse HEAD', { cwd: worktreeDir, timeoutMs: 30000 })
|
|
9328
9898
|
: null;
|
|
@@ -9332,6 +9902,7 @@ async function prepareWorktree(root, queue, task, runId, config = {}) {
|
|
|
9332
9902
|
pathRel: path.relative(root, worktreeDir),
|
|
9333
9903
|
branch,
|
|
9334
9904
|
setup: compactCommandResult(add),
|
|
9905
|
+
reused,
|
|
9335
9906
|
head: head?.exitCode === 0 ? head.stdout.trim() : null,
|
|
9336
9907
|
runId
|
|
9337
9908
|
};
|
|
@@ -9434,6 +10005,13 @@ export async function runQueueOnce(root, options) {
|
|
|
9434
10005
|
};
|
|
9435
10006
|
}
|
|
9436
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
|
+
|
|
9437
10015
|
try {
|
|
9438
10016
|
// Holding this newly acquired lock proves no previous runner owns a valid
|
|
9439
10017
|
// queue lease. Any task left in active/ is therefore an orphan from an
|
|
@@ -9442,7 +10020,7 @@ export async function runQueueOnce(root, options) {
|
|
|
9442
10020
|
const recoveryReason = lockResult.reclaimedLock?.reason === 'dead_owner_pid'
|
|
9443
10021
|
? 'dead_queue_lock_owner_pid'
|
|
9444
10022
|
: 'queue_lock_reacquired_with_active_task';
|
|
9445
|
-
const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason);
|
|
10023
|
+
const orphanRecovered = await recoverOrphanActive(root, queue, recoveryReason, options);
|
|
9446
10024
|
if (orphanRecovered.length > 0) {
|
|
9447
10025
|
progress.emit('queue', 'orphan_recovered', `Recovered ${orphanRecovered.length} orphan active task(s)`, {
|
|
9448
10026
|
queue,
|
|
@@ -9457,7 +10035,21 @@ export async function runQueueOnce(root, options) {
|
|
|
9457
10035
|
count: staleRecovered.length
|
|
9458
10036
|
});
|
|
9459
10037
|
}
|
|
9460
|
-
|
|
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
|
+
}
|
|
9461
10053
|
if (!inboxFile) {
|
|
9462
10054
|
progress.emit('queue', 'empty', `Queue ${queue} has no queued tasks`, {
|
|
9463
10055
|
queue
|
|
@@ -9473,7 +10065,6 @@ export async function runQueueOnce(root, options) {
|
|
|
9473
10065
|
};
|
|
9474
10066
|
}
|
|
9475
10067
|
|
|
9476
|
-
const task = await readJson(inboxFile);
|
|
9477
10068
|
progressTask = task;
|
|
9478
10069
|
const activeFile = path.join(queueSubdirFor(root, queue, 'active'), path.basename(inboxFile));
|
|
9479
10070
|
await rename(inboxFile, activeFile);
|
|
@@ -9548,8 +10139,9 @@ export async function runQueueOnce(root, options) {
|
|
|
9548
10139
|
} else {
|
|
9549
10140
|
progress.emit('preflight', 'skipped', 'No preflight configured');
|
|
9550
10141
|
}
|
|
10142
|
+
const supersede = await currentSupersedeRequest(root, queue, task);
|
|
9551
10143
|
const supersedeFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
|
|
9552
|
-
if (
|
|
10144
|
+
if (supersede) {
|
|
9553
10145
|
finalStatus = 'superseded';
|
|
9554
10146
|
progress.emit('queue', 'superseded', 'A newer loop request replaced this task at a safe checkpoint', {
|
|
9555
10147
|
taskId: task.id,
|
|
@@ -9645,7 +10237,7 @@ export async function runQueueOnce(root, options) {
|
|
|
9645
10237
|
});
|
|
9646
10238
|
if (finalStatus === 'superseded') {
|
|
9647
10239
|
const requestFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'supersede_request.json');
|
|
9648
|
-
const request = await readJson(requestFile);
|
|
10240
|
+
const request = await readJson(requestFile).catch(() => ({}));
|
|
9649
10241
|
acceptanceReviews = { count: 0, accepted: 0, revise: 0, blocked: 0, reviews: [] };
|
|
9650
10242
|
const judgementFile = path.join(taskRuntimeDirFor(root, queue, task.id), 'final_judgement.json');
|
|
9651
10243
|
const judgement = {
|
|
@@ -9758,8 +10350,17 @@ export async function runQueueOnce(root, options) {
|
|
|
9758
10350
|
completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
|
|
9759
10351
|
}
|
|
9760
10352
|
const completedFile = path.join(destination, path.basename(activeFile));
|
|
9761
|
-
|
|
9762
|
-
|
|
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);
|
|
9763
10364
|
|
|
9764
10365
|
const run = {
|
|
9765
10366
|
version: 2,
|
|
@@ -9770,6 +10371,7 @@ export async function runQueueOnce(root, options) {
|
|
|
9770
10371
|
startedAt,
|
|
9771
10372
|
finishedAt,
|
|
9772
10373
|
status: finalStatus,
|
|
10374
|
+
...(movedByOperator ? { movedByOperator: true } : {}),
|
|
9773
10375
|
retry: options.retry ?? null,
|
|
9774
10376
|
taskContract: taskContract ? {
|
|
9775
10377
|
path: taskContract.file,
|
|
@@ -9826,6 +10428,7 @@ export async function runQueueOnce(root, options) {
|
|
|
9826
10428
|
branch: worktree.branch,
|
|
9827
10429
|
head: worktree.head,
|
|
9828
10430
|
setup: worktree.setup,
|
|
10431
|
+
reused: Boolean(worktree.reused),
|
|
9829
10432
|
inspection: worktreeInspection
|
|
9830
10433
|
} : null,
|
|
9831
10434
|
verification,
|
|
@@ -9845,21 +10448,24 @@ export async function runQueueOnce(root, options) {
|
|
|
9845
10448
|
}
|
|
9846
10449
|
await writeJson(runPath, run);
|
|
9847
10450
|
|
|
9848
|
-
if (options.notifyCommand) {
|
|
10451
|
+
if (options.notifyCommand && !movedByOperator) {
|
|
9849
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.
|
|
9850
10455
|
const message = [
|
|
9851
10456
|
`Loop queue task ${finalStatus}: ${task.title}`,
|
|
9852
10457
|
`queue: ${queue}`,
|
|
9853
10458
|
`run: ${run.runPath}`,
|
|
9854
10459
|
trimTail(detail, 1200)
|
|
9855
|
-
].filter(Boolean).join('\n');
|
|
9856
|
-
await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
|
|
10460
|
+
].filter(Boolean).join('\n').replace(/\0/g, '');
|
|
10461
|
+
run.notification = compactCommandResult(await runCommand(`${options.notifyCommand} ${shellQuote(message)}`, {
|
|
9857
10462
|
cwd: root,
|
|
9858
10463
|
timeoutMs: 60 * 1000
|
|
9859
|
-
});
|
|
10464
|
+
}));
|
|
10465
|
+
await writeJson(runPath, run);
|
|
9860
10466
|
}
|
|
9861
10467
|
|
|
9862
|
-
if (finalStatus === 'completed') {
|
|
10468
|
+
if (finalStatus === 'completed' && !movedByOperator) {
|
|
9863
10469
|
try {
|
|
9864
10470
|
run.projectRelay = await projectRelayNext(root, { queue, task, finalJudgement: finalJudgement?.judgement });
|
|
9865
10471
|
} catch (error) {
|
|
@@ -9881,6 +10487,7 @@ export async function runQueueOnce(root, options) {
|
|
|
9881
10487
|
progressNotifications
|
|
9882
10488
|
};
|
|
9883
10489
|
} finally {
|
|
10490
|
+
clearInterval(leaseRenewal);
|
|
9884
10491
|
await releaseQueueLock(root, queue, lockResult.lock);
|
|
9885
10492
|
}
|
|
9886
10493
|
}
|