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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { chmod, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { spawn } from 'node:child_process';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
@@ -90,6 +90,7 @@ const timer = await readFile(timerFile, 'utf8');
|
|
|
90
90
|
if (!service.includes('scheduler-tick') || !timer.includes('OnUnitActiveSec=1min')) throw new Error('scheduler systemd units were not installed');
|
|
91
91
|
if (!(await readFile(dashboardServiceFile, 'utf8')).includes('dashboard-serve') || !(await readFile(dashboardDropIn, 'utf8')).includes('Wants=loop-engineering-dashboard.service')) throw new Error('OpenClaw installer did not install Dashboard gateway autostart');
|
|
92
92
|
if (service.includes('WorkingDirectory="') || service.includes('ExecStart="') || !service.includes('\\x20') || !service.includes('\\xe5\\xae\\x89\\xe8\\xa3\\x85')) throw new Error('scheduler service paths were not encoded with systemd path escapes');
|
|
93
|
+
if (service.match(/^WorkingDirectory=(.*)$/m)?.[1] !== root) throw new Error('WorkingDirectory must be the literal workspace path; systemd does not decode escapes there');
|
|
93
94
|
const systemdVerify = await new Promise((resolve) => {
|
|
94
95
|
const child = spawn('systemd-analyze', ['verify', serviceFile, timerFile], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
95
96
|
let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk) => { stdout += chunk; }); child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
@@ -205,4 +206,73 @@ const zhInstructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
|
|
|
205
206
|
const zhDispatcher = await readFile(path.join(root, 'scripts/loops/openclaw-loop-dispatch.mjs'), 'utf8');
|
|
206
207
|
const zhNotifier = await readFile(path.join(root, 'scripts/loops/openclaw-loop-notify.mjs'), 'utf8');
|
|
207
208
|
if (zhQueue.language !== 'zh' || !zhInstructions.includes('Loop Engineering 会话路由') || !zhDispatcher.includes('已经由 Loop Engineering 管理') || !zhNotifier.includes('通知器需要消息参数')) throw new Error('Chinese installation did not localize generated configuration and runtime files');
|
|
209
|
+
const installedWrapper = path.join(root, 'scripts/loops/openclaw-loop.mjs');
|
|
210
|
+
async function routeWithRelayFlag(message) {
|
|
211
|
+
return new Promise((resolve) => {
|
|
212
|
+
const child = spawn(process.execPath, [installedWrapper, 'route', '--relay-enqueue', '--message', message,
|
|
213
|
+
'--source-channel', 'feishu', '--source-target', 'owner', '--source-account', 'main',
|
|
214
|
+
'--source-message-id', 'relay-source-1'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
215
|
+
let stderr = '';
|
|
216
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
217
|
+
child.on('close', (code) => resolve({ code, stderr }));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const rejectedRelay = await routeWithRelayFlag('走 loop:普通任务');
|
|
221
|
+
if (rejectedRelay.code !== 2 || !rejectedRelay.stderr.includes('internal project relay marker')) throw new Error('internal enqueue flag accepted an unmarked task');
|
|
222
|
+
const projectRelay = await routeWithRelayFlag('走 loop: [project-relay:relay-project/local-1] 本地任务');
|
|
223
|
+
if (projectRelay.code !== 0) throw new Error(`project relay marker was rejected: ${projectRelay.stderr}`);
|
|
224
|
+
const internalRelay = await routeWithRelayFlag('走 loop: [project-scout:abc123] 本地只读扫描');
|
|
225
|
+
if (internalRelay.code !== 0) throw new Error(`internal relay enqueue failed: ${internalRelay.stderr}`);
|
|
226
|
+
const inboxDir = path.join(root, 'runtime/loops/test-tasks/inbox');
|
|
227
|
+
const queuedFiles = (await readdir(inboxDir)).filter((name) => name.endsWith('.json'));
|
|
228
|
+
if (queuedFiles.length !== 2) throw new Error('internal relays did not defer exactly two tasks to the scheduler');
|
|
229
|
+
const queuedTasks = await Promise.all(queuedFiles.map(async (file) => JSON.parse(await readFile(path.join(inboxDir, file), 'utf8'))));
|
|
230
|
+
if (!queuedTasks.some((task) => task.body.includes('[project-relay:relay-project/local-1]'))
|
|
231
|
+
|| !queuedTasks.some((task) => task.body.includes('[project-scout:abc123]'))
|
|
232
|
+
|| queuedTasks.some((task) => task.body.includes('只入队'))) throw new Error('internal relay corrupted task intent');
|
|
233
|
+
// Install lifecycle: reinstall updates the managed AGENTS.md block, uninstall
|
|
234
|
+
// removes the dashboard this install owns, a mid-install failure is still
|
|
235
|
+
// uninstallable, another workspace's dashboard is left alone, and upgrade
|
|
236
|
+
// keeps the Tailnet listen mode.
|
|
237
|
+
const dashboardService = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/loop-engineering-dashboard.service');
|
|
238
|
+
const exists = (file) => readFile(file).then(() => true, () => false);
|
|
239
|
+
const blockCount = (text) => text.split('<!-- loop-engineering:openclaw:start -->').length - 1;
|
|
240
|
+
const enInstall = await run([...installBase, '--worker-agent', 'builder', '--language', 'en', '--confirm-install', '--force', '--json']);
|
|
241
|
+
if (enInstall.code !== 0) throw new Error(`reinstall failed: ${enInstall.stderr}`);
|
|
242
|
+
const enInstructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
|
|
243
|
+
if (blockCount(enInstructions) !== 1 || enInstructions.includes('Loop Engineering 会话路由') || !enInstructions.includes('Loop Engineering conversation routing')) throw new Error('reinstall did not replace the managed AGENTS.md block');
|
|
244
|
+
await writeFile(path.join(root, 'AGENTS.md'), enInstructions.replace('Loop Engineering conversation routing', 'Loop Engineering conversation routing (edited)'));
|
|
245
|
+
const editedReinstall = await run([...installBase, '--worker-agent', 'builder', '--language', 'zh', '--confirm-install', '--force', '--json']);
|
|
246
|
+
if (editedReinstall.code !== 0 || blockCount(await readFile(path.join(root, 'AGENTS.md'), 'utf8')) !== 1) throw new Error('--force reinstall did not replace an edited block');
|
|
247
|
+
const lifecycleUninstall = await manage(['--action', 'uninstall', '--confirm-uninstall']);
|
|
248
|
+
if (lifecycleUninstall.code !== 0) throw new Error(`uninstall after reinstall failed: ${lifecycleUninstall.stderr}`);
|
|
249
|
+
if (await exists(dashboardService) || await exists(path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/openclaw-gateway.service.d/loop-engineering-dashboard.conf'))) throw new Error('uninstall left the dashboard service or gateway drop-in behind');
|
|
250
|
+
if (!(await readFile(systemctlCapture, 'utf8')).includes('["--user","stop","loop-engineering-dashboard.service"]')) throw new Error('uninstall did not stop the dashboard');
|
|
251
|
+
if (blockCount(await readFile(path.join(root, 'AGENTS.md'), 'utf8')) !== 0) throw new Error('uninstall left the managed block');
|
|
252
|
+
|
|
253
|
+
const failingSystemctl = path.join(root, 'failing-systemctl.mjs');
|
|
254
|
+
await writeFile(failingSystemctl, `#!/usr/bin/env node\nif (process.argv.includes('enable')) { console.error('enable refused'); process.exit(1); }\n`);
|
|
255
|
+
await chmod(failingSystemctl, 0o755);
|
|
256
|
+
const failedInstall = await run(['--root', root, '--queue', 'test-tasks', '--openclaw-bin', mockOpenClaw, '--systemctl-bin', failingSystemctl, '--worker-agent', 'builder', '--confirm-install', '--json']);
|
|
257
|
+
if (failedInstall.code === 0) throw new Error('installer ignored a failed timer enable');
|
|
258
|
+
const partialManifest = JSON.parse(await readFile(path.join(root, 'runtime/loop-engineering-openclaw-install.json'), 'utf8'));
|
|
259
|
+
if (partialManifest.status !== 'installing') throw new Error('a failed install left no manifest');
|
|
260
|
+
const partialUninstall = await manage(['--action', 'uninstall', '--confirm-uninstall']);
|
|
261
|
+
if (partialUninstall.code !== 0 || await exists(path.join(root, 'scripts/loops/openclaw-loop.mjs'))) throw new Error(`a partial install could not be uninstalled: ${partialUninstall.stderr}`);
|
|
262
|
+
|
|
263
|
+
const foreignService = '[Service]\nExecStart=/usr/bin/node /opt/loop/bin/loop-engineering.mjs dashboard-serve --root /srv/other --host 127.0.0.1 --port 4174\n';
|
|
264
|
+
await writeFile(dashboardService, foreignService);
|
|
265
|
+
const sharedInstall = await run([...installBase, '--worker-agent', 'builder', '--confirm-install', '--json']);
|
|
266
|
+
if (sharedInstall.code !== 0 || !JSON.parse(sharedInstall.stdout).dashboardAutostart?.skipped) throw new Error(`installer did not skip another workspace's dashboard: ${sharedInstall.stderr}`);
|
|
267
|
+
if (await readFile(dashboardService, 'utf8') !== foreignService) throw new Error('installer repointed another workspace dashboard');
|
|
268
|
+
if ((await manage(['--action', 'uninstall', '--confirm-uninstall'])).code !== 0 || await readFile(dashboardService, 'utf8') !== foreignService) throw new Error('uninstall touched another workspace dashboard');
|
|
269
|
+
await rm(dashboardService);
|
|
270
|
+
|
|
271
|
+
const mockTailscale = path.join(root, 'mock-tailscale.mjs');
|
|
272
|
+
await writeFile(mockTailscale, `#!/usr/bin/env node\nconsole.log('100.64.10.20');\n`);
|
|
273
|
+
await chmod(mockTailscale, 0o755);
|
|
274
|
+
const tailnetInstall = await run([...installBase, '--worker-agent', 'builder', '--dashboard-listen', 'tailscale', '--tailscale-bin', mockTailscale, '--confirm-install', '--json']);
|
|
275
|
+
if (tailnetInstall.code !== 0) throw new Error(`Tailnet install failed: ${tailnetInstall.stderr}`);
|
|
276
|
+
const tailnetUpgrade = await manage(['--action', 'upgrade', '--confirm-upgrade']);
|
|
277
|
+
if (tailnetUpgrade.code !== 0 || !(await readFile(dashboardService, 'utf8')).includes('--host 100.64.10.20')) throw new Error(`upgrade did not keep the Tailnet dashboard: ${tailnetUpgrade.stderr}`);
|
|
208
278
|
console.log('openclaw installer self-test passed');
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
4
|
import { createHash } from 'node:crypto';
|
|
4
5
|
import { spawn } from 'node:child_process';
|
|
5
6
|
import path from 'node:path';
|
|
7
|
+
import { applyManagedInstructions, installDashboardUnlessShared } from './install-shared.mjs';
|
|
6
8
|
|
|
7
9
|
function parseArgs(argv) {
|
|
8
10
|
const out = { root: process.cwd(), queue: 'agent-tasks', workerAgent: null, openclawBin: 'openclaw', systemctlBin: 'systemctl', dashboardListen: 'localhost', tailscaleBin: 'tailscale', language: 'auto', json: false, confirmInstall: false, force: false };
|
|
@@ -35,6 +37,14 @@ function resolveLanguage(requested = 'auto', env = process.env) {
|
|
|
35
37
|
|
|
36
38
|
const text = (language, en, zh) => language === 'zh' ? zh : en;
|
|
37
39
|
|
|
40
|
+
// WorkingDirectory= takes the path literally (systemd does not decode C
|
|
41
|
+
// escapes there); only specifiers need escaping. Newlines cannot be encoded.
|
|
42
|
+
function systemdWorkingDirectory(value) {
|
|
43
|
+
const text = String(value);
|
|
44
|
+
if (/[\n\r]/.test(text)) throw new Error('Workspace path must not contain a newline.');
|
|
45
|
+
return text.replace(/%/g, '%%');
|
|
46
|
+
}
|
|
47
|
+
|
|
38
48
|
function systemdEscapePath(value) {
|
|
39
49
|
return [...Buffer.from(String(value))]
|
|
40
50
|
.map((byte) => /[A-Za-z0-9/_.:-]/.test(String.fromCharCode(byte))
|
|
@@ -49,6 +59,7 @@ function safeId(value, label) {
|
|
|
49
59
|
}
|
|
50
60
|
const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
51
61
|
|
|
62
|
+
|
|
52
63
|
function run(command, args, options = {}) {
|
|
53
64
|
return new Promise((resolve) => {
|
|
54
65
|
const child = spawn(command, args, { cwd: options.cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
@@ -194,6 +205,11 @@ async function runWhenUnlocked(args, waitMs = 300000) {
|
|
|
194
205
|
if (command === 'route') {
|
|
195
206
|
const messageIndex = rest.indexOf('--message');
|
|
196
207
|
const message = messageIndex >= 0 ? String(rest[messageIndex + 1] || '') : '';
|
|
208
|
+
const relayEnqueue = rest.includes('--relay-enqueue');
|
|
209
|
+
if (relayEnqueue && !/\\[project-(?:relay:[a-zA-Z0-9._-]+\\/[a-zA-Z0-9._-]+|scout:[a-z0-9_-]+)\\]/.test(message)) {
|
|
210
|
+
console.error('--relay-enqueue requires an internal project relay marker');
|
|
211
|
+
process.exit(2);
|
|
212
|
+
}
|
|
197
213
|
const optionValue = (name) => {
|
|
198
214
|
const index = rest.indexOf(name);
|
|
199
215
|
return index >= 0 ? String(rest[index + 1] || '').trim() : '';
|
|
@@ -207,8 +223,9 @@ if (command === 'route') {
|
|
|
207
223
|
}
|
|
208
224
|
const amendment = new RegExp(${JSON.stringify(amendmentPattern)}, 'i').test(message);
|
|
209
225
|
const routeMode = amendment ? '--amend-active' : '--supersede-active';
|
|
210
|
-
const
|
|
211
|
-
const
|
|
226
|
+
const routedArgs = rest.filter((arg) => arg !== '--relay-enqueue');
|
|
227
|
+
const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', routeMode, ...routedArgs]);
|
|
228
|
+
const queueOnly = relayEnqueue || new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
|
|
212
229
|
const runCode = routeCode || queueOnly || amendment ? routeCode : await runWhenUnlocked(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
213
230
|
const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
214
231
|
const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
@@ -256,7 +273,7 @@ process.stdout.write(JSON.stringify(result) + '\\n');
|
|
|
256
273
|
}
|
|
257
274
|
|
|
258
275
|
function schedulerServiceSource({ root, queue, language }) {
|
|
259
|
-
return `[Unit]\nDescription=${text(language, `Taskforce Loop Engineering scheduler for ${queue}`, `${queue} 的 Taskforce Loop Engineering 调度器`)}\nAfter=default.target\n\n[Service]\nType=oneshot\nWorkingDirectory=${
|
|
276
|
+
return `[Unit]\nDescription=${text(language, `Taskforce Loop Engineering scheduler for ${queue}`, `${queue} 的 Taskforce Loop Engineering 调度器`)}\nAfter=default.target\n\n[Service]\nType=oneshot\nWorkingDirectory=${systemdWorkingDirectory(root)}\nExecStart=${systemdEscapePath(process.execPath)} ${systemdEscapePath(path.join(root, 'scripts', 'loops', 'openclaw-loop.mjs'))} scheduler-tick --json\n`;
|
|
260
277
|
}
|
|
261
278
|
|
|
262
279
|
function schedulerTimerSource({ queue, language }) {
|
|
@@ -331,7 +348,7 @@ async function main() {
|
|
|
331
348
|
args.openclawBin = await resolveExecutable(args.openclawBin);
|
|
332
349
|
const worker = await resolveWorkerAgent(args);
|
|
333
350
|
args.workerAgent = worker.workerAgent;
|
|
334
|
-
args.loopBin = new URL('../bin/loop-engineering.mjs', import.meta.url)
|
|
351
|
+
args.loopBin = fileURLToPath(new URL('../bin/loop-engineering.mjs', import.meta.url));
|
|
335
352
|
args.humanGateAdapter = new URL('../lib/human-gate-channel-adapter.mjs', import.meta.url).href;
|
|
336
353
|
const systemdUserDir = path.join(process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || '', '.config'), 'systemd', 'user');
|
|
337
354
|
const schedulerUnit = `openclaw-loop-${args.queue}-scheduler.service`;
|
|
@@ -393,19 +410,18 @@ async function main() {
|
|
|
393
410
|
await mkdir(systemdUserDir, { recursive: true });
|
|
394
411
|
await writeFile(files.schedulerService, schedulerServiceContent);
|
|
395
412
|
await writeFile(files.schedulerTimer, schedulerTimerContent);
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
if (enableTimer.code !== 0) throw new Error(`Cannot enable Loop scheduler timer ${schedulerTimer}: ${(enableTimer.stderr || enableTimer.stdout).trim() || `exit ${enableTimer.code}`}`);
|
|
400
|
-
const dashboardInstaller = new URL('./dashboard-autostart-install.mjs', import.meta.url).pathname;
|
|
401
|
-
const dashboardInstall = await run(process.execPath, [dashboardInstaller, '--root', args.root, '--listen', args.dashboardListen, '--tailscale-bin', args.tailscaleBin, '--systemctl-bin', args.systemctlBin, '--confirm-install', '--json'], { cwd: args.root });
|
|
402
|
-
if (dashboardInstall.code !== 0) throw new Error(`Cannot install Dashboard gateway autostart: ${(dashboardInstall.stderr || dashboardInstall.stdout).trim()}`);
|
|
403
|
-
const instructions = await exists(files.instructions) ? await readFile(files.instructions, 'utf8') : '';
|
|
413
|
+
// Record ownership before anything is enabled, so a failure in a later
|
|
414
|
+
// step leaves an integration that manage --action uninstall can remove.
|
|
415
|
+
const previousManifest = await readFile(files.manifest, 'utf8').then(JSON.parse).catch(() => null);
|
|
404
416
|
const managedInstructions = instructionsBlock(args);
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
417
|
+
const recordedInstructions = await applyManagedInstructions(files.instructions, managedInstructions, {
|
|
418
|
+
previousBlock: previousManifest?.managedInstructions?.content,
|
|
419
|
+
force: args.force,
|
|
420
|
+
startMarker: '<!-- loop-engineering:openclaw:start -->',
|
|
421
|
+
endMarker: '<!-- loop-engineering:openclaw:end -->'
|
|
422
|
+
});
|
|
423
|
+
const manifest = {
|
|
424
|
+
version: 5, status: 'installing', queue: args.queue, language: args.language, workerAgent: args.workerAgent, openclawBin: args.openclawBin, systemctlBin: args.systemctlBin, installedAt: new Date().toISOString(),
|
|
409
425
|
managedFiles: [
|
|
410
426
|
{ path: path.relative(args.root, files.queueConfig), sha256: sha256(queueContent) },
|
|
411
427
|
{ path: path.relative(args.root, files.dispatcher), sha256: sha256(dispatcherContent) },
|
|
@@ -417,9 +433,24 @@ async function main() {
|
|
|
417
433
|
{ path: files.schedulerService, unit: schedulerUnit, sha256: sha256(schedulerServiceContent) },
|
|
418
434
|
{ path: files.schedulerTimer, unit: schedulerTimer, sha256: sha256(schedulerTimerContent) }
|
|
419
435
|
],
|
|
420
|
-
managedInstructions: { path: 'AGENTS.md', sha256: sha256(
|
|
436
|
+
managedInstructions: { path: 'AGENTS.md', sha256: sha256(recordedInstructions), content: recordedInstructions },
|
|
437
|
+
dashboard: { listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, installed: false },
|
|
421
438
|
retainedOnUninstall: [`runtime/loops/${args.queue}`]
|
|
422
|
-
}
|
|
439
|
+
};
|
|
440
|
+
const writeManifest = async () => {
|
|
441
|
+
await mkdir(path.dirname(files.manifest), { recursive: true });
|
|
442
|
+
await writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
443
|
+
};
|
|
444
|
+
await writeManifest();
|
|
445
|
+
const daemonReload = await run(args.systemctlBin, ['--user', 'daemon-reload'], { cwd: args.root });
|
|
446
|
+
if (daemonReload.code !== 0) throw new Error(`Cannot reload user systemd units: ${(daemonReload.stderr || daemonReload.stdout).trim() || `exit ${daemonReload.code}`}`);
|
|
447
|
+
const enableTimer = await run(args.systemctlBin, ['--user', 'enable', '--now', schedulerTimer], { cwd: args.root });
|
|
448
|
+
if (enableTimer.code !== 0) throw new Error(`Cannot enable Loop scheduler timer ${schedulerTimer}: ${(enableTimer.stderr || enableTimer.stdout).trim() || `exit ${enableTimer.code}`}`);
|
|
449
|
+
const dashboard = await installDashboardUnlessShared({ root: args.root, listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, systemctlBin: args.systemctlBin, run });
|
|
450
|
+
manifest.dashboard = dashboard;
|
|
451
|
+
if (dashboard.skipped) report.dashboardAutostart = { ...report.dashboardAutostart, skipped: dashboard.skipped };
|
|
452
|
+
manifest.status = 'installed';
|
|
453
|
+
await writeManifest();
|
|
423
454
|
}
|
|
424
455
|
console.log(args.json ? JSON.stringify(report, null, 2) : text(args.language, `OpenClaw integration: ${report.status}\nconflicts: ${report.conflicts.join(', ') || 'none'}\nnext: ${report.next}`, `OpenClaw 集成:${report.status}\n冲突:${report.conflicts.join(', ') || '无'}\n下一步:${report.next}`));
|
|
425
456
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
2
3
|
import { createHash } from 'node:crypto';
|
|
3
4
|
import { access, readFile, rm, writeFile } from 'node:fs/promises';
|
|
4
5
|
import { spawn } from 'node:child_process';
|
|
@@ -54,7 +55,20 @@ async function main() {
|
|
|
54
55
|
const block = manifest.managedInstructions?.content || '';
|
|
55
56
|
const instructionsClean = Boolean(block) && sha256(block) === manifest.managedInstructions?.sha256 && agentsText.includes(block);
|
|
56
57
|
const modified = [...files.filter((item) => item.present && !item.clean).map((item) => item.path), ...units.filter((item) => item.present && !item.clean).map((item) => item.path)];
|
|
57
|
-
|
|
58
|
+
// The per-user dashboard is removed only while it is exactly what this
|
|
59
|
+
// installation wrote; otherwise another workspace or a person now owns it.
|
|
60
|
+
const dashboardFiles = [];
|
|
61
|
+
if (manifest.dashboard?.installed && manifest.dashboard.service) {
|
|
62
|
+
const service = await readFile(manifest.dashboard.service, 'utf8').catch(() => null);
|
|
63
|
+
dashboardFiles.push({ path: manifest.dashboard.service, present: service !== null, clean: service !== null && sha256(service) === manifest.dashboard.serviceSha256 });
|
|
64
|
+
for (const dropIn of manifest.dashboard.dropIns ?? []) {
|
|
65
|
+
const content = await readFile(dropIn, 'utf8').catch(() => null);
|
|
66
|
+
dashboardFiles.push({ path: dropIn, present: content !== null, clean: content !== null && sha256(content) === manifest.dashboard.dropInSha256 });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const dashboardOwned = dashboardFiles.length > 0 && dashboardFiles[0].clean;
|
|
70
|
+
const retained = [...(manifest.retainedOnUninstall || []), ...(dashboardFiles.length && !dashboardOwned ? [`${manifest.dashboard.service} (changed since install)`] : [])];
|
|
71
|
+
const plan = { version: 3, action: args.action, readOnly: args.action.endsWith('-plan'), installStatus: manifest.status ?? 'installed', queue: manifest.queue, workerAgent: manifest.workerAgent, files, units, dashboard: dashboardFiles, instructionsClean, modified, retained, ready: modified.length === 0 && instructionsClean };
|
|
58
72
|
if (args.action === 'uninstall') {
|
|
59
73
|
if (!plan.ready) throw new Error(`Refusing uninstall because managed content changed: ${[...modified, ...(!instructionsClean ? ['AGENTS.md managed block'] : [])].join(', ')}`);
|
|
60
74
|
const timer = units.find((item) => item.unit?.endsWith('.timer'));
|
|
@@ -64,6 +78,11 @@ async function main() {
|
|
|
64
78
|
}
|
|
65
79
|
for (const item of files) if (item.present && item.clean) await rm(path.join(args.root, item.path), { force: true });
|
|
66
80
|
for (const item of units) if (item.present && item.clean) await rm(item.path, { force: true });
|
|
81
|
+
if (dashboardOwned) {
|
|
82
|
+
const stopped = await run(manifest.systemctlBin || 'systemctl', ['--user', 'stop', manifest.dashboard.unit || 'loop-engineering-dashboard.service'], args.root);
|
|
83
|
+
if (stopped.code !== 0) throw new Error(`Cannot stop the Dashboard service: ${stopped.stderr || stopped.stdout}`);
|
|
84
|
+
for (const item of dashboardFiles) if (item.present && item.clean) await rm(item.path, { force: true });
|
|
85
|
+
}
|
|
67
86
|
const reload = await run(manifest.systemctlBin || 'systemctl', ['--user', 'daemon-reload'], args.root);
|
|
68
87
|
if (reload.code !== 0) throw new Error(`Cannot reload user systemd units: ${reload.stderr || reload.stdout}`);
|
|
69
88
|
await writeFile(agentsFile, agentsText.replace(block, ''));
|
|
@@ -71,9 +90,9 @@ async function main() {
|
|
|
71
90
|
plan.status = 'uninstalled'; plan.readOnly = false;
|
|
72
91
|
} else if (args.action === 'upgrade') {
|
|
73
92
|
if (!plan.ready) throw new Error(`Refusing upgrade because managed content changed: ${[...modified, ...(!instructionsClean ? ['AGENTS.md managed block'] : [])].join(', ')}`);
|
|
74
|
-
const installer = new URL('./openclaw-install.mjs', import.meta.url)
|
|
93
|
+
const installer = fileURLToPath(new URL('./openclaw-install.mjs', import.meta.url));
|
|
75
94
|
const result = await new Promise((resolve) => {
|
|
76
|
-
const child = spawn(process.execPath, [installer, '--root', args.root, '--queue', manifest.queue, '--worker-agent', manifest.workerAgent, '--language', manifest.language || 'en', '--openclaw-bin', manifest.openclawBin || 'openclaw', '--systemctl-bin', manifest.systemctlBin || 'systemctl', '--confirm-install', '--force', '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
95
|
+
const child = spawn(process.execPath, [installer, '--root', args.root, '--queue', manifest.queue, '--worker-agent', manifest.workerAgent, '--language', manifest.language || 'en', '--openclaw-bin', manifest.openclawBin || 'openclaw', '--systemctl-bin', manifest.systemctlBin || 'systemctl', '--dashboard-listen', manifest.dashboard?.listen || 'localhost', '--tailscale-bin', manifest.dashboard?.tailscaleBin || 'tailscale', '--confirm-install', '--force', '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
77
96
|
let stdout = ''; let stderr = ''; child.stdout.on('data', (c) => { stdout += c; }); child.stderr.on('data', (c) => { stderr += c; });
|
|
78
97
|
child.on('close', (code) => resolve({ code, stdout, stderr }));
|
|
79
98
|
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
2
3
|
import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
4
|
import { spawn } from 'node:child_process';
|
|
4
5
|
import path from 'node:path';
|
|
@@ -46,7 +47,7 @@ async function main() {
|
|
|
46
47
|
const baseConfig = path.join(args.root, `configs/loops/queues/${args.queue}.json`);
|
|
47
48
|
const smokeConfig = path.join(args.root, `configs/loops/queues/${smokeQueue}.json`);
|
|
48
49
|
const smokeRuntime = path.join(args.root, 'runtime', 'loops', smokeQueue);
|
|
49
|
-
const doctorScript = new URL('./openclaw-doctor.mjs', import.meta.url)
|
|
50
|
+
const doctorScript = fileURLToPath(new URL('./openclaw-doctor.mjs', import.meta.url));
|
|
50
51
|
const steps = [];
|
|
51
52
|
let taskId = null;
|
|
52
53
|
try {
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
|
-
import { mkdtemp, mkdir, readFile, writeFile, unlink } from 'node:fs/promises';
|
|
2
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile, unlink } from 'node:fs/promises';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import {
|
|
5
|
+
import { readdir } from 'node:fs/promises';
|
|
6
|
+
import { ensureQueueDirs, projectRelayNext, projectRelayReconcile, projectRelayResume, queueSchedulerTick, queueStatus } from '../lib/core.mjs';
|
|
6
7
|
|
|
7
8
|
const root = await mkdtemp(path.join(os.tmpdir(), 'loop-project-relay-'));
|
|
8
9
|
const queue = 'relay-test';
|
|
@@ -67,4 +68,185 @@ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null
|
|
|
67
68
|
assert.equal((await queueStatus(root, queue)).queued, 1);
|
|
68
69
|
await writeJson(ledgerFile, { status: 'accepted' });
|
|
69
70
|
assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'accepted project cannot relay');
|
|
71
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'reconciliation is opt-in');
|
|
72
|
+
await writeJson(configFile, { ...spec, relayStatusReconciliation: true });
|
|
73
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, status: 'completed' });
|
|
74
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a queue row alone is not acceptance');
|
|
75
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'tasks', queued.id, 'final_judgement.json'), { outcome: 'ready_to_apply', requires_human_gate: false });
|
|
76
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'accepted project cannot mutate backlog');
|
|
77
|
+
await writeJson(ledgerFile, { status: 'in_progress' });
|
|
78
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, backlogItemId: 'wrong', status: 'completed' });
|
|
79
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'marker without matching backlog binding is not evidence');
|
|
80
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, status: 'completed' });
|
|
81
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 1);
|
|
82
|
+
assert.equal((await readFile(backlogFile, 'utf8')).includes('"status": "completed"'), true);
|
|
83
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'reconciliation is idempotent');
|
|
84
|
+
await writeJson(backlogFile, { items: [{ ...item, externalActionsAllowed: true }] });
|
|
85
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'unsafe backlog rows are not promoted');
|
|
86
|
+
await writeJson(backlogFile, { items: [item] });
|
|
87
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'done', 'duplicate.json'), { ...queued, id: 'duplicate', status: 'completed' });
|
|
88
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'tasks', 'duplicate', 'final_judgement.json'), { outcome: 'ready_to_apply' });
|
|
89
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'duplicate task evidence cannot promote a row');
|
|
90
|
+
await writeJson(backlogFile, { items: [item] });
|
|
91
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
|
|
92
|
+
const planned = await queueSchedulerTick(root, { queue, planOnly: true });
|
|
93
|
+
assert.equal(planned.relayReconciliation.length, 0, 'plan-only scheduler cannot mutate the backlog');
|
|
94
|
+
assert.equal(JSON.parse(await readFile(backlogFile, 'utf8')).items[0].status, 'ready');
|
|
95
|
+
await writeJson(path.join(root, 'runtime/loops', queue, 'done', 'duplicate.json'), { ...queued, id: 'duplicate', projectId: 'another-project', status: 'completed' });
|
|
96
|
+
await writeJson(backlogFile, { items: [item, { ...item }] });
|
|
97
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'duplicate backlog ids cannot be reconciled');
|
|
98
|
+
await writeJson(backlogFile, { items: [item] });
|
|
99
|
+
await writeJson(ledgerFile, { status: 'unknown' });
|
|
100
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'invalid project acceptance cannot change backlog');
|
|
101
|
+
await writeJson(ledgerFile, { status: 'in_progress' });
|
|
102
|
+
await unlink(backlogFile);
|
|
103
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'missing authoritative backlog fails closed');
|
|
104
|
+
await writeJson(backlogFile, { items: [item] });
|
|
105
|
+
await rm(path.join(root, result.file));
|
|
106
|
+
const tick = await queueSchedulerTick(root, { queue });
|
|
107
|
+
assert.deepEqual(tick.relayReconciliation, [{ project, changed: 1 }], 'idle scheduler repairs interrupted status writes');
|
|
108
|
+
assert.equal((await readFile(backlogFile, 'utf8')).includes('"status": "completed"'), true);
|
|
109
|
+
// A relay item that needed a revision round is still reconcilable through
|
|
110
|
+
// its lineage: the revision body has no leading marker, but its revisionOf
|
|
111
|
+
// chain ends at the bound relay task.
|
|
112
|
+
const revisedItem = { ...item, id: 'local-2' };
|
|
113
|
+
const doneDir = path.join(root, 'runtime/loops', queue, 'done');
|
|
114
|
+
const judgementFor = (id) => path.join(root, 'runtime/loops', queue, 'tasks', id, 'final_judgement.json');
|
|
115
|
+
const relayRootTask = { ...queued, id: 'relay-root', backlogItemId: revisedItem.id, status: 'completed',
|
|
116
|
+
body: `[project-relay:${project}/${revisedItem.id}]\nVerify the local entry` };
|
|
117
|
+
const revisionTask = { ...relayRootTask, id: 'relay-revision', revisionOf: relayRootTask.id, revisionRound: 1,
|
|
118
|
+
body: `Revision round for a loop-managed task.\n\nOriginal task body:\n${relayRootTask.body}` };
|
|
119
|
+
await writeJson(backlogFile, { items: [revisedItem] });
|
|
120
|
+
await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), relayRootTask);
|
|
121
|
+
await writeJson(judgementFor(relayRootTask.id), { outcome: 'needs_revision', requires_human_gate: false });
|
|
122
|
+
await writeJson(path.join(doneDir, `${revisionTask.id}.json`), revisionTask);
|
|
123
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a lineage without an accepted round is not evidence');
|
|
124
|
+
await writeJson(judgementFor(revisionTask.id), { outcome: 'ready_to_apply', requires_human_gate: true });
|
|
125
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a gated revision is not evidence');
|
|
126
|
+
await writeJson(path.join(doneDir, `${revisionTask.id}.json`), { ...revisionTask, revisionOf: 'unknown-task' });
|
|
127
|
+
await writeJson(judgementFor(revisionTask.id), { outcome: 'ready_to_apply', requires_human_gate: false });
|
|
128
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a revision without a relay root is not evidence');
|
|
129
|
+
await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), { ...relayRootTask, backlogItemId: 'other-item' });
|
|
130
|
+
await writeJson(path.join(doneDir, `${revisionTask.id}.json`), revisionTask);
|
|
131
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a lineage with a different binding is not evidence');
|
|
132
|
+
await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), relayRootTask);
|
|
133
|
+
await writeJson(path.join(doneDir, 'second-root.json'), { ...relayRootTask, id: 'second-root' });
|
|
134
|
+
await writeJson(judgementFor('second-root'), { outcome: 'needs_revision', requires_human_gate: false });
|
|
135
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'two independent relay lineages fail closed');
|
|
136
|
+
await unlink(path.join(doneDir, 'second-root.json'));
|
|
137
|
+
assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 1, 'an accepted revision round completes its relay item');
|
|
138
|
+
assert.equal(JSON.parse(await readFile(backlogFile, 'utf8')).items[0].status, 'completed');
|
|
139
|
+
// Reconciliation must not overwrite a backlog edited after it was read.
|
|
140
|
+
await writeJson(backlogFile, { items: [revisedItem] });
|
|
141
|
+
const concurrentEdit = { items: [{ ...revisedItem, note: 'edited by an agent' }] };
|
|
142
|
+
const raced = await projectRelayReconcile(root, { queue, project, beforeWrite: () => writeJson(backlogFile, concurrentEdit) });
|
|
143
|
+
assert.deepEqual(raced, { changed: 0, conflict: true }, 'a concurrent backlog edit aborts reconciliation');
|
|
144
|
+
assert.deepEqual(JSON.parse(await readFile(backlogFile, 'utf8')), concurrentEdit, 'the concurrent edit survives');
|
|
145
|
+
assert.deepEqual((await readdir(path.dirname(backlogFile))).filter((name) => name.endsWith('.tmp')), [], 'no temporary backlog is left behind');
|
|
146
|
+
|
|
147
|
+
// Fresh workspace for relay retry, duplicate ids, and scheduler locking.
|
|
148
|
+
{
|
|
149
|
+
const root = await mkdtemp(path.join(os.tmpdir(), 'loop-project-relay-resume-'));
|
|
150
|
+
const queueDir = path.join(root, 'runtime/loops', queue);
|
|
151
|
+
const backlogFile = path.join(root, 'project/backlog.json');
|
|
152
|
+
await ensureQueueDirs(root, queue);
|
|
153
|
+
await writeJson(path.join(root, 'configs/loops/projects', `${project}.json`), spec);
|
|
154
|
+
await writeJson(path.join(root, 'project/ledger.json'), { status: 'in_progress' });
|
|
155
|
+
const next = { ...item, id: 'local-2' };
|
|
156
|
+
|
|
157
|
+
// Duplicate or malformed rows can neither prove a predecessor nor be relayed.
|
|
158
|
+
await writeJson(backlogFile, { items: [null, predecessor, { ...predecessor, status: 'ready' }, next] });
|
|
159
|
+
assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'duplicate predecessor ids fail closed');
|
|
160
|
+
await writeJson(backlogFile, { items: [null, predecessor, next, { ...next, title: 'Shadow' }] });
|
|
161
|
+
assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'duplicate candidate ids are not relayed');
|
|
162
|
+
await writeJson(backlogFile, { items: [predecessor, next, { ...next, title: 'Shadow' }, { ...item, id: 'local-3', dependsOn: ['local-2'] }] });
|
|
163
|
+
assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'a duplicated dependency is never complete');
|
|
164
|
+
|
|
165
|
+
// The accepted predecessor finished while the queue was busy, so the
|
|
166
|
+
// completion-time relay was skipped. An idle scheduler tick resumes it.
|
|
167
|
+
await writeJson(backlogFile, { items: [predecessor, next] });
|
|
168
|
+
const accepted = { ...task, title: 'Accepted', body: 'Accepted work', status: 'completed', finishedAt: '2026-10-01T00:00:00.000Z' };
|
|
169
|
+
await writeJson(path.join(queueDir, 'done', `${accepted.id}.json`), accepted);
|
|
170
|
+
await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), finalJudgement);
|
|
171
|
+
const older = { ...accepted, id: 'older-task', backlogItemId: 'local-0', finishedAt: '2026-09-01T00:00:00.000Z' };
|
|
172
|
+
await writeJson(path.join(queueDir, 'done', `${older.id}.json`), older);
|
|
173
|
+
await writeJson(path.join(queueDir, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
|
|
174
|
+
|
|
175
|
+
await writeJson(path.join(queueDir, 'inbox', 'busy.json'), { id: 'busy', title: 'Busy', body: 'User work', status: 'queued' });
|
|
176
|
+
assert.equal(await projectRelayResume(root, { queue, project }), null, 'a busy queue still defers the relay');
|
|
177
|
+
await unlink(path.join(queueDir, 'inbox', 'busy.json'));
|
|
178
|
+
|
|
179
|
+
const lockFile = path.join(queueDir, 'queue.lock');
|
|
180
|
+
await writeFile(lockFile, JSON.stringify({ version: 1, queue, pid: process.pid,
|
|
181
|
+
acquiredAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 60000).toISOString() }));
|
|
182
|
+
const locked = await queueSchedulerTick(root, { queue });
|
|
183
|
+
assert.equal(locked.relayMaintenance, 'queue_locked');
|
|
184
|
+
assert.deepEqual(locked.projectRelay, [], 'a tick without the queue lock cannot relay');
|
|
185
|
+
assert.equal((await queueStatus(root, queue)).queued, 0);
|
|
186
|
+
await unlink(lockFile);
|
|
187
|
+
|
|
188
|
+
await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), { outcome: 'needs_revision', requires_human_gate: false });
|
|
189
|
+
const rejected = await queueSchedulerTick(root, { queue });
|
|
190
|
+
assert.equal(rejected.relayMaintenance, 'completed');
|
|
191
|
+
assert.deepEqual(rejected.projectRelay, [], 'the newest bound task must be accepted');
|
|
192
|
+
assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'unchanged', 'an unchanged queue skips the full relay scan');
|
|
193
|
+
|
|
194
|
+
// An in-place judgement edit is invisible to the cheap fingerprint: it is
|
|
195
|
+
// picked up by the periodic full pass, never acted on from stale state.
|
|
196
|
+
await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), finalJudgement);
|
|
197
|
+
const skipped = await queueSchedulerTick(root, { queue });
|
|
198
|
+
assert.equal(skipped.relayMaintenance, 'unchanged');
|
|
199
|
+
assert.deepEqual(skipped.projectRelay, []);
|
|
200
|
+
const maintenanceFile = path.join(queueDir, 'scheduler/relay-maintenance.json');
|
|
201
|
+
const lastPass = JSON.parse(await readFile(maintenanceFile, 'utf8'));
|
|
202
|
+
await writeJson(maintenanceFile, { ...lastPass, fullPassAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() });
|
|
203
|
+
const resumed = await queueSchedulerTick(root, { queue });
|
|
204
|
+
assert.equal(resumed.relayMaintenance, 'completed', 'the periodic full pass runs despite an unchanged fingerprint');
|
|
205
|
+
assert.equal(resumed.projectRelay.length, 1);
|
|
206
|
+
assert.equal(resumed.projectRelay[0].itemId, 'local-2');
|
|
207
|
+
const relayed = JSON.parse(await readFile(path.join(root, resumed.projectRelay[0].file), 'utf8'));
|
|
208
|
+
assert.equal(relayed.backlogItemId, 'local-2');
|
|
209
|
+
assert.equal(relayed.source.message_id, 'message-1');
|
|
210
|
+
const afterRelay = await queueSchedulerTick(root, { queue });
|
|
211
|
+
assert.equal(afterRelay.relayMaintenance, 'completed', 'a queue change during a pass triggers another full pass');
|
|
212
|
+
assert.deepEqual(afterRelay.projectRelay, [], 'a resumed relay is not enqueued twice');
|
|
213
|
+
assert.equal((await queueStatus(root, queue)).queued, 1);
|
|
214
|
+
assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'unchanged');
|
|
215
|
+
await writeFile(backlogFile, `${await readFile(backlogFile, 'utf8')}\n`);
|
|
216
|
+
assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'completed', 'a backlog edit invalidates the fingerprint');
|
|
217
|
+
assert.equal((await queueSchedulerTick(root, { queue, relayMaintenanceFullIntervalMs: 0 })).relayMaintenance, 'completed',
|
|
218
|
+
'a zero interval always runs the full pass');
|
|
219
|
+
// An unreadable task file fails the pass without throwing from the tick,
|
|
220
|
+
// and the pass is not recorded, so it is retried on the next tick.
|
|
221
|
+
await writeFile(path.join(queueDir, 'done', 'corrupt.json'), '{');
|
|
222
|
+
const broken = await queueSchedulerTick(root, { queue });
|
|
223
|
+
assert.equal(broken.relayMaintenance, 'error');
|
|
224
|
+
assert.equal(typeof broken.projectRelay[0].error, 'string');
|
|
225
|
+
assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'error', 'a failed pass is retried');
|
|
226
|
+
await unlink(path.join(queueDir, 'done', 'corrupt.json'));
|
|
227
|
+
await rm(root, { recursive: true, force: true });
|
|
228
|
+
}
|
|
229
|
+
// A failed or canceled relay task stops the chain: an idle tick must not skip
|
|
230
|
+
// it and relay the next independent item. Ambiguous ordering fails closed.
|
|
231
|
+
for (const stop of ['canceled', 'failed', 'tied']) {
|
|
232
|
+
const root = await mkdtemp(path.join(os.tmpdir(), `loop-project-relay-stop-${stop}-`));
|
|
233
|
+
const queueDir = path.join(root, 'runtime/loops', queue);
|
|
234
|
+
await ensureQueueDirs(root, queue);
|
|
235
|
+
await writeJson(path.join(root, 'configs/loops/projects', `${project}.json`), spec);
|
|
236
|
+
await writeJson(path.join(root, 'project/ledger.json'), { status: 'in_progress' });
|
|
237
|
+
await writeJson(path.join(root, 'project/backlog.json'), { items: [predecessor, { ...item, id: 'local-1' }, { ...item, id: 'local-2' }] });
|
|
238
|
+
await writeJson(path.join(queueDir, 'done', `${task.id}.json`), { ...task, status: 'completed', body: 'Accepted work',
|
|
239
|
+
enqueuedAt: '2026-10-01T00:00:00.000Z', finishedAt: '2026-10-01T01:00:00.000Z' });
|
|
240
|
+
await writeJson(path.join(queueDir, 'tasks', task.id, 'final_judgement.json'), finalJudgement);
|
|
241
|
+
const stopped = { ...task, id: 'relay-local-1', backlogItemId: 'local-1', body: `[project-relay:${project}/local-1]\nVerify`,
|
|
242
|
+
status: stop === 'tied' ? 'completed' : stop,
|
|
243
|
+
enqueuedAt: stop === 'tied' ? '2026-10-01T00:00:00.000Z' : '2026-10-01T01:00:01.000Z' };
|
|
244
|
+
await writeJson(path.join(queueDir, stop === 'tied' ? 'done' : stop, `${stopped.id}.json`), stopped);
|
|
245
|
+
await writeJson(path.join(queueDir, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
|
|
246
|
+
const tick = await queueSchedulerTick(root, { queue });
|
|
247
|
+
assert.equal(tick.relayMaintenance, 'completed');
|
|
248
|
+
assert.deepEqual(tick.projectRelay, [], `a ${stop} relay task stops the relay chain`);
|
|
249
|
+
assert.equal((await queueStatus(root, queue)).queued, 0);
|
|
250
|
+
await rm(root, { recursive: true, force: true });
|
|
251
|
+
}
|
|
70
252
|
console.log('project relay self-test passed');
|
package/scripts/run-loop-cron.sh
CHANGED
|
@@ -14,7 +14,20 @@ fi
|
|
|
14
14
|
mkdir -p "$LOG_DIR"
|
|
15
15
|
cd "$WORKDIR"
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
# LOOP_ALERT_COMMAND may include arguments ("openclaw message send --target x");
|
|
18
|
+
# the message is passed as one extra argument, never interpolated.
|
|
19
|
+
alert() {
|
|
20
|
+
local message="$1" log="$2"
|
|
21
|
+
if [[ -n "$SEND_CMD" ]]; then
|
|
22
|
+
if ! sh -c "$SEND_CMD \"\$1\"" loop-alert "$message"; then
|
|
23
|
+
printf '[%s] alert command failed: %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$SEND_CMD" >> "$log"
|
|
24
|
+
fi
|
|
25
|
+
else
|
|
26
|
+
printf '%s\n' "$message" >&2
|
|
27
|
+
fi
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if ! loop_id="$(node -e '
|
|
18
31
|
const fs = require("fs");
|
|
19
32
|
const config = process.argv[1];
|
|
20
33
|
try {
|
|
@@ -24,7 +37,13 @@ try {
|
|
|
24
37
|
} catch {
|
|
25
38
|
process.exit(2);
|
|
26
39
|
}
|
|
27
|
-
' "$CONFIG")"
|
|
40
|
+
' "$CONFIG")"; then
|
|
41
|
+
stamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
|
|
42
|
+
log_file="$LOG_DIR/loop-cron-invalid-config.log"
|
|
43
|
+
printf '[%s] %s: unreadable config or invalid id\n' "$stamp" "$CONFIG" >> "$log_file"
|
|
44
|
+
alert "Loop escalation ($stamp): $CONFIG is unreadable or has an invalid id; the loop did not run." "$log_file"
|
|
45
|
+
exit 2
|
|
46
|
+
fi
|
|
28
47
|
|
|
29
48
|
stamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
|
|
30
49
|
log_file="$LOG_DIR/loop-cron-${loop_id}.log"
|
|
@@ -74,11 +93,7 @@ process.stdout.write(latest || "runner failed before writing a run artifact");
|
|
|
74
93
|
' "$loop_id")"
|
|
75
94
|
|
|
76
95
|
message="Loop escalation ($stamp): $loop_id exit=$exit_code. $summary"
|
|
77
|
-
|
|
78
|
-
"$SEND_CMD" "$message" || true
|
|
79
|
-
else
|
|
80
|
-
printf '%s\n' "$message" >&2
|
|
81
|
-
fi
|
|
96
|
+
alert "$message" "$log_file"
|
|
82
97
|
|
|
83
98
|
rm -f "$tmp_out"
|
|
84
99
|
exit "$exit_code"
|