taskforce-loop-engineering 0.15.21 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/MIGRATING.md +80 -0
- package/README.md +37 -8
- 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/context-budget.mjs +147 -0
- package/lib/core.mjs +746 -241
- package/lib/dispatch-classification.mjs +114 -0
- 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/context-budget-self-test.mjs +249 -0
- package/scripts/dashboard-autostart-install.mjs +33 -8
- package/scripts/dashboard-autostart-self-test.mjs +12 -3
- package/scripts/final-judgement-self-test.mjs +113 -4
- 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 +158 -2
- package/scripts/openclaw-install.mjs +105 -30
- package/scripts/openclaw-manage.mjs +22 -3
- package/scripts/openclaw-smoke.mjs +2 -1
- package/scripts/project-relay-self-test.mjs +145 -1
- package/scripts/run-loop-cron.sh +22 -7
- package/scripts/safety-regression-self-test.mjs +350 -0
- package/skills/taskforce-loop-engineering/SKILL.md +7 -1
- package/skills/taskforce-loop-engineering/references/context-budget.md +11 -0
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { chmod, mkdtemp, readFile, readdir, 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';
|
|
6
|
+
import assert from 'node:assert/strict';
|
|
7
|
+
import { enqueueTask, runQueueOnce } from '../lib/core.mjs';
|
|
6
8
|
|
|
7
9
|
const root = await mkdtemp(path.join(tmpdir(), 'loop openclaw 安装-'));
|
|
8
10
|
const deliveryCapture = path.join(root, 'delivery.json');
|
|
@@ -25,6 +27,11 @@ else {
|
|
|
25
27
|
if (args[0] === 'agent' && process.env.LOOP_CHECKPOINTS_DIR) {
|
|
26
28
|
const dir = path.resolve(process.cwd(), process.env.LOOP_CHECKPOINTS_DIR);
|
|
27
29
|
await mkdir(dir, { recursive: true });
|
|
30
|
+
if (process.env.LOOP_REVIEW_TEST) {
|
|
31
|
+
for (const [id, sequence, blockers] of [['cp99', 1, []], ['progress-latest', 2, ['Unknown external outcome']]]) await writeFile(path.join(dir, id + '.json'), JSON.stringify({ task_id: process.env.LOOP_TASK_ID, checkpoint_id: id, sequence, status: blockers.length ? 'needs_human_input' : 'ready_for_acceptance', project_completion: process.env.LOOP_REVIEW_TEST.startsWith('terminal-') ? { status: sequence === 1 ? 'complete' : 'needs_human_acceptance' } : undefined, summary: 'Mock progress', blockers, risks: [], verification: [{ command: 'mock check', outcome: 'passed' }] }));
|
|
32
|
+
console.error(process.env.LOOP_REVIEW_TEST.endsWith('overflow') ? 'context_length_exceeded' : 'generic worker failure');
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
28
35
|
await writeFile(path.join(dir, 'cp1.json'), JSON.stringify({ version: 1, task_id: process.env.LOOP_TASK_ID, checkpoint_id: 'cp1', status: 'ready_for_acceptance', summary: 'Read-only smoke completed.', files_changed: [], verification: [{ command: 'mock smoke', outcome: 'passed' }], blockers: [], risks: [], next_action: 'acceptance_review' }));
|
|
29
36
|
}
|
|
30
37
|
if (process.env.DELIVERY_CAPTURE) await writeFile(process.env.DELIVERY_CAPTURE, JSON.stringify(args));
|
|
@@ -69,10 +76,113 @@ if (queue.language !== 'en') throw new Error('resolved installation language was
|
|
|
69
76
|
if (queue.scheduler?.required !== true || queue.scheduler?.heartbeatMaxAgeMs !== 300000) throw new Error('required scheduler heartbeat was not installed');
|
|
70
77
|
const dispatcher = await readFile(path.join(root, 'scripts/loops/openclaw-loop-dispatch.mjs'), 'utf8');
|
|
71
78
|
if (!dispatcher.includes('already loop-managed') || !dispatcher.includes("'--agent', \"builder\"") || !dispatcher.includes('LOOP_LATEST_AMENDMENT_FILE') || !dispatcher.includes('LOOP_SESSION_GENERATION') || !dispatcher.includes('-g${sessionGeneration}')) throw new Error('worker, recursion guard, amendment polling, or session generation missing');
|
|
72
|
-
if (queue.retry?.runtimeRecoveryMaxAttempts !== 2 || queue.retry?.sessionMaxTicks !==
|
|
79
|
+
if (queue.retry?.runtimeRecoveryMaxAttempts !== 2 || queue.retry?.sessionMaxTicks !== 3) throw new Error('bounded runtime recovery policy was not installed');
|
|
80
|
+
// Exercise the generated dispatcher, including large-task prompt bounds and
|
|
81
|
+
// concrete file references (the Gateway worker does not inherit CLI env vars).
|
|
82
|
+
const largeTaskFile = path.join(root, 'large-task.json');
|
|
83
|
+
const largeCapture = path.join(root, 'large-task-args.json');
|
|
84
|
+
await writeFile(largeTaskFile, JSON.stringify({ id: 'large-task', body: 'x'.repeat(100000) }));
|
|
85
|
+
const largeDispatch = await new Promise((resolve, reject) => {
|
|
86
|
+
const child = spawn(process.execPath, [path.join(root, 'scripts/loops/openclaw-loop-dispatch.mjs')], { cwd: root, env: { ...process.env, LOOP_TASK_FILE: largeTaskFile, LOOP_TASK_ID: 'large-task', LOOP_SESSION_GENERATION: '3', DELIVERY_CAPTURE: largeCapture }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
87
|
+
let stderr = '';
|
|
88
|
+
child.stdout.resume();
|
|
89
|
+
child.stderr.on('data', x => stderr += x);
|
|
90
|
+
child.on('error', reject);
|
|
91
|
+
child.on('close', code => resolve({ code, stderr }));
|
|
92
|
+
});
|
|
93
|
+
if (largeDispatch.code !== 0) throw new Error('generated context dispatcher failed: ' + largeDispatch.stderr);
|
|
94
|
+
const largeArgs = JSON.parse(await readFile(largeCapture, 'utf8'));
|
|
95
|
+
const largePrompt = largeArgs[largeArgs.indexOf('--message') + 1];
|
|
96
|
+
if (Buffer.byteLength(largePrompt) > 16384 || !largePrompt.includes(largeTaskFile) || !largePrompt.includes('CONTEXT BUDGET') || !largeArgs.includes('agent:builder:loop-task-large-task-g3')) throw new Error('generated dispatcher lost bounded prompt, file reference, context instructions or session generation');
|
|
97
|
+
// The generated dispatcher/observer must preserve checkpoint gating through
|
|
98
|
+
// actual queue retries and overflow recovery, not just prompt source checks.
|
|
99
|
+
for (const failure of ['ordinary', 'overflow', 'terminal-ordinary', 'terminal-overflow']) {
|
|
100
|
+
await enqueueTask(root, { queue: 'review-order', title: failure, task: 'Inspect mocked local data' });
|
|
101
|
+
const options = { queue: 'review-order', dispatcher: `LOOP_REVIEW_TEST=${failure} node scripts/loops/openclaw-loop-dispatch.mjs`, retry: { ...queue.retry, maxAttempts: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
102
|
+
const result = await runQueueOnce(root, options);
|
|
103
|
+
assert.equal(result.status, 'needs_human_input');
|
|
104
|
+
assert.equal(result.run.dispatchAttempts.length, 1);
|
|
105
|
+
assert.equal(result.run.revisionRequest, null);
|
|
106
|
+
assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
107
|
+
}
|
|
73
108
|
const instructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
|
|
74
109
|
if (!instructions.includes('Use Loop Engineering to fix this issue') || !instructions.includes('Queue this only; do not run it yet') || /走 loop|只入队|只排队/.test(instructions)) throw new Error('English conversation instructions are missing or contain Chinese routing examples');
|
|
75
110
|
const wrapper = await readFile(path.join(root, 'scripts/loops/openclaw-loop.mjs'), 'utf8');
|
|
111
|
+
// A slow worker must outlive its routing caller, retaining observable output.
|
|
112
|
+
const fakeLoop = path.join(root, 'slow-loop.mjs');
|
|
113
|
+
const asyncWrapper = path.join(root, 'async-wrapper.mjs');
|
|
114
|
+
const workerDone = path.join(root, 'worker-done');
|
|
115
|
+
await writeFile(fakeLoop, `import { writeFile } from 'node:fs/promises';
|
|
116
|
+
if (process.argv[2] === 'run-queue') {
|
|
117
|
+
await new Promise(resolve => setTimeout(resolve, 4000));
|
|
118
|
+
await writeFile(${JSON.stringify(workerDone)}, 'done');
|
|
119
|
+
}
|
|
120
|
+
`);
|
|
121
|
+
await writeFile(asyncWrapper, wrapper.replace(/spawn\(process\.execPath, \["[^"]+"/, 'spawn(process.execPath, [' + JSON.stringify(fakeLoop)));
|
|
122
|
+
const launchStart = Date.now();
|
|
123
|
+
const launched = await new Promise((resolve, reject) => {
|
|
124
|
+
const child = spawn(process.execPath, [asyncWrapper, 'route', '--message', 'Use loop: slow task', '--source-channel', 'feishu', '--source-target', 'test', '--source-account', 'default', '--source-message-id', 'test-launch'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
125
|
+
let stdout = ''; let stderr = '';
|
|
126
|
+
child.stdout.on('data', x => stdout += x); child.stderr.on('data', x => stderr += x);
|
|
127
|
+
child.on('error', reject); child.on('close', code => resolve({ code, stdout, stderr }));
|
|
128
|
+
});
|
|
129
|
+
if (launched.code !== 0 || Date.now() - launchStart >= 3000 || !launched.stdout.includes('worker_started')) throw new Error('routing waited for slow worker: ' + launched.stderr);
|
|
130
|
+
const receipt = JSON.parse(launched.stdout.trim());
|
|
131
|
+
if (receipt.accepted !== false || !receipt.pid || !receipt.log) throw new Error('launch receipt misrepresents acceptance');
|
|
132
|
+
while (Date.now() - launchStart < 8000 && !(await readFile(workerDone, 'utf8').catch(() => ''))) await new Promise(resolve => setTimeout(resolve, 100));
|
|
133
|
+
if (await readFile(workerDone, 'utf8') !== 'done') throw new Error('background worker did not finish');
|
|
134
|
+
// Exercise the actual generated background entry, not just a function-name check.
|
|
135
|
+
// Each fixture has its own CLI, counters and completion marker; no real delivery.
|
|
136
|
+
for (const scenario of ['lock-once', 'lock-timeout', 'preflight', 'malformed', 'fatal', 'manual-lock']) {
|
|
137
|
+
const cli = path.join(root, scenario + '-cli.mjs');
|
|
138
|
+
const entry = path.join(root, scenario + '-wrapper.mjs');
|
|
139
|
+
const countFile = path.join(root, scenario + '-count');
|
|
140
|
+
const doneFile = path.join(root, scenario + '-done');
|
|
141
|
+
await writeFile(cli, `import { readFile, writeFile } from 'node:fs/promises';
|
|
142
|
+
const scenario = ${JSON.stringify(scenario)};
|
|
143
|
+
const command = process.argv[2];
|
|
144
|
+
if (command === 'run-queue') {
|
|
145
|
+
const count = Number(await readFile(${JSON.stringify(countFile)}, 'utf8').catch(() => '0')) + 1;
|
|
146
|
+
await writeFile(${JSON.stringify(countFile)}, String(count));
|
|
147
|
+
if (scenario === 'fatal') process.exit(1);
|
|
148
|
+
if (scenario === 'malformed') { console.log('not JSON'); process.exit(2); }
|
|
149
|
+
if (scenario === 'preflight') { console.log(JSON.stringify({ processed: true, status: 'blocked_preflight' })); process.exit(2); }
|
|
150
|
+
if (scenario !== 'lock-once' || count === 1) {
|
|
151
|
+
console.log(JSON.stringify({ processed: false, status: 'locked' })); process.exit(2);
|
|
152
|
+
}
|
|
153
|
+
console.log(JSON.stringify({ processed: true, status: 'completed' }));
|
|
154
|
+
}
|
|
155
|
+
if (command === 'queue-terminal-notify') await writeFile(${JSON.stringify(doneFile)}, 'done');
|
|
156
|
+
`);
|
|
157
|
+
const source = wrapper
|
|
158
|
+
.replace(/spawn\(process\.execPath, \["[^"]+"/, 'spawn(process.execPath, [' + JSON.stringify(cli))
|
|
159
|
+
.replace('waitMs = 300000', 'waitMs = 600');
|
|
160
|
+
await writeFile(entry, source);
|
|
161
|
+
const startedAt = Date.now();
|
|
162
|
+
const result = await new Promise((resolve, reject) => {
|
|
163
|
+
const args = scenario === 'manual-lock' ? ['run-once'] : ['route', '--message', 'Use loop: lock regression', '--source-channel', 'feishu', '--source-target', 'test', '--source-account', 'default', '--source-message-id', scenario];
|
|
164
|
+
const child = spawn(process.execPath, [entry, ...args], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
165
|
+
let stdout = ''; let stderr = '';
|
|
166
|
+
child.stdout.on('data', chunk => stdout += chunk);
|
|
167
|
+
child.stderr.on('data', chunk => stderr += chunk);
|
|
168
|
+
child.on('error', reject);
|
|
169
|
+
child.on('close', code => resolve({ code, stdout, stderr }));
|
|
170
|
+
});
|
|
171
|
+
while (Date.now() - startedAt < 8000 && !(await readFile(doneFile, 'utf8').catch(() => ''))) await new Promise(resolve => setTimeout(resolve, 50));
|
|
172
|
+
if (await readFile(doneFile, 'utf8').catch(() => '') !== 'done') throw new Error(scenario + ': worker did not reach notifications');
|
|
173
|
+
const count = Number(await readFile(countFile, 'utf8'));
|
|
174
|
+
if (scenario === 'manual-lock') {
|
|
175
|
+
if (result.code !== 2 || count !== 1) throw new Error('manual run-once changed semantics');
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (result.code !== 0) throw new Error(scenario + ': route failed: ' + result.stderr);
|
|
179
|
+
const receipt = JSON.parse(result.stdout.trim());
|
|
180
|
+
if (receipt.status !== 'worker_started' || receipt.accepted !== false) throw new Error(scenario + ': invalid receipt');
|
|
181
|
+
const log = await readFile(path.join(root, receipt.log), 'utf8');
|
|
182
|
+
if (scenario === 'lock-once' && (count !== 2 || !log.includes('worker_waiting_for_lock') || !log.includes('completed'))) throw new Error('background worker did not recover after lock release');
|
|
183
|
+
if (scenario === 'lock-timeout' && (count < 2 || count > 10 || !log.includes('worker_lock_wait_timeout'))) throw new Error('lock wait was not bounded/observable');
|
|
184
|
+
if (['preflight', 'malformed', 'fatal'].includes(scenario) && (count !== 1 || log.includes('worker_waiting_for_lock'))) throw new Error(scenario + ': non-lock failure was retried');
|
|
185
|
+
}
|
|
76
186
|
if (!wrapper.includes('--supersede-active') || !wrapper.includes('--amend-active') || !wrapper.includes('--progress-notify-command') || !wrapper.includes('runWhenUnlocked') || wrapper.includes("run-queue-drain', '--config'") || wrapper.includes("spawn('loop-engineering'") || !wrapper.includes('queue-human-input-notify') || !wrapper.includes('queue-terminal-notify') || !wrapper.includes('queue-scheduler-tick') || !wrapper.includes('queue') || !wrapper.includes('continue') || /只入队|只排队|继续当前/.test(wrapper) || !wrapper.includes('requiredSource') || !wrapper.includes('--source-message-id')) throw new Error('supersede/amend routing, source fail-closed policy, localization, absolute CLI, scheduler, live progress, async notification, or queue-only routing missing');
|
|
77
187
|
if (!wrapper.includes('process.exitCode = tickCode;') || wrapper.includes('process.exitCode = tickCode || humanNotifyCode || terminalNotifyCode;')) throw new Error('scheduler health still depends on notification delivery');
|
|
78
188
|
const missingSourceRoute = await new Promise((resolve) => {
|
|
@@ -90,6 +200,7 @@ const timer = await readFile(timerFile, 'utf8');
|
|
|
90
200
|
if (!service.includes('scheduler-tick') || !timer.includes('OnUnitActiveSec=1min')) throw new Error('scheduler systemd units were not installed');
|
|
91
201
|
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
202
|
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');
|
|
203
|
+
if (service.match(/^WorkingDirectory=(.*)$/m)?.[1] !== root) throw new Error('WorkingDirectory must be the literal workspace path; systemd does not decode escapes there');
|
|
93
204
|
const systemdVerify = await new Promise((resolve) => {
|
|
94
205
|
const child = spawn('systemd-analyze', ['verify', serviceFile, timerFile], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
95
206
|
let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk) => { stdout += chunk; }); child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
@@ -229,4 +340,49 @@ const queuedTasks = await Promise.all(queuedFiles.map(async (file) => JSON.parse
|
|
|
229
340
|
if (!queuedTasks.some((task) => task.body.includes('[project-relay:relay-project/local-1]'))
|
|
230
341
|
|| !queuedTasks.some((task) => task.body.includes('[project-scout:abc123]'))
|
|
231
342
|
|| queuedTasks.some((task) => task.body.includes('只入队'))) throw new Error('internal relay corrupted task intent');
|
|
343
|
+
// Install lifecycle: reinstall updates the managed AGENTS.md block, uninstall
|
|
344
|
+
// removes the dashboard this install owns, a mid-install failure is still
|
|
345
|
+
// uninstallable, another workspace's dashboard is left alone, and upgrade
|
|
346
|
+
// keeps the Tailnet listen mode.
|
|
347
|
+
const dashboardService = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/loop-engineering-dashboard.service');
|
|
348
|
+
const exists = (file) => readFile(file).then(() => true, () => false);
|
|
349
|
+
const blockCount = (text) => text.split('<!-- loop-engineering:openclaw:start -->').length - 1;
|
|
350
|
+
const enInstall = await run([...installBase, '--worker-agent', 'builder', '--language', 'en', '--confirm-install', '--force', '--json']);
|
|
351
|
+
if (enInstall.code !== 0) throw new Error(`reinstall failed: ${enInstall.stderr}`);
|
|
352
|
+
const enInstructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
|
|
353
|
+
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');
|
|
354
|
+
await writeFile(path.join(root, 'AGENTS.md'), enInstructions.replace('Loop Engineering conversation routing', 'Loop Engineering conversation routing (edited)'));
|
|
355
|
+
const editedReinstall = await run([...installBase, '--worker-agent', 'builder', '--language', 'zh', '--confirm-install', '--force', '--json']);
|
|
356
|
+
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');
|
|
357
|
+
const lifecycleUninstall = await manage(['--action', 'uninstall', '--confirm-uninstall']);
|
|
358
|
+
if (lifecycleUninstall.code !== 0) throw new Error(`uninstall after reinstall failed: ${lifecycleUninstall.stderr}`);
|
|
359
|
+
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');
|
|
360
|
+
if (!(await readFile(systemctlCapture, 'utf8')).includes('["--user","stop","loop-engineering-dashboard.service"]')) throw new Error('uninstall did not stop the dashboard');
|
|
361
|
+
if (blockCount(await readFile(path.join(root, 'AGENTS.md'), 'utf8')) !== 0) throw new Error('uninstall left the managed block');
|
|
362
|
+
|
|
363
|
+
const failingSystemctl = path.join(root, 'failing-systemctl.mjs');
|
|
364
|
+
await writeFile(failingSystemctl, `#!/usr/bin/env node\nif (process.argv.includes('enable')) { console.error('enable refused'); process.exit(1); }\n`);
|
|
365
|
+
await chmod(failingSystemctl, 0o755);
|
|
366
|
+
const failedInstall = await run(['--root', root, '--queue', 'test-tasks', '--openclaw-bin', mockOpenClaw, '--systemctl-bin', failingSystemctl, '--worker-agent', 'builder', '--confirm-install', '--json']);
|
|
367
|
+
if (failedInstall.code === 0) throw new Error('installer ignored a failed timer enable');
|
|
368
|
+
const partialManifest = JSON.parse(await readFile(path.join(root, 'runtime/loop-engineering-openclaw-install.json'), 'utf8'));
|
|
369
|
+
if (partialManifest.status !== 'installing') throw new Error('a failed install left no manifest');
|
|
370
|
+
const partialUninstall = await manage(['--action', 'uninstall', '--confirm-uninstall']);
|
|
371
|
+
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}`);
|
|
372
|
+
|
|
373
|
+
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';
|
|
374
|
+
await writeFile(dashboardService, foreignService);
|
|
375
|
+
const sharedInstall = await run([...installBase, '--worker-agent', 'builder', '--confirm-install', '--json']);
|
|
376
|
+
if (sharedInstall.code !== 0 || !JSON.parse(sharedInstall.stdout).dashboardAutostart?.skipped) throw new Error(`installer did not skip another workspace's dashboard: ${sharedInstall.stderr}`);
|
|
377
|
+
if (await readFile(dashboardService, 'utf8') !== foreignService) throw new Error('installer repointed another workspace dashboard');
|
|
378
|
+
if ((await manage(['--action', 'uninstall', '--confirm-uninstall'])).code !== 0 || await readFile(dashboardService, 'utf8') !== foreignService) throw new Error('uninstall touched another workspace dashboard');
|
|
379
|
+
await rm(dashboardService);
|
|
380
|
+
|
|
381
|
+
const mockTailscale = path.join(root, 'mock-tailscale.mjs');
|
|
382
|
+
await writeFile(mockTailscale, `#!/usr/bin/env node\nconsole.log('100.64.10.20');\n`);
|
|
383
|
+
await chmod(mockTailscale, 0o755);
|
|
384
|
+
const tailnetInstall = await run([...installBase, '--worker-agent', 'builder', '--dashboard-listen', 'tailscale', '--tailscale-bin', mockTailscale, '--confirm-install', '--json']);
|
|
385
|
+
if (tailnetInstall.code !== 0) throw new Error(`Tailnet install failed: ${tailnetInstall.stderr}`);
|
|
386
|
+
const tailnetUpgrade = await manage(['--action', 'upgrade', '--confirm-upgrade']);
|
|
387
|
+
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}`);
|
|
232
388
|
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'] });
|
|
@@ -140,6 +151,7 @@ function dispatcherSource({ workerAgent, openclawBin, language }) {
|
|
|
140
151
|
return `#!/usr/bin/env node
|
|
141
152
|
import { readFile } from 'node:fs/promises';
|
|
142
153
|
import { spawn } from 'node:child_process';
|
|
154
|
+
import { contextWorkerInstructions, observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
|
|
143
155
|
const task = JSON.parse(await readFile(process.env.LOOP_TASK_FILE, 'utf8'));
|
|
144
156
|
const sessionGeneration = Number.parseInt(process.env.LOOP_SESSION_GENERATION || '0', 10) || 0;
|
|
145
157
|
const prompt = [
|
|
@@ -150,7 +162,8 @@ const prompt = [
|
|
|
150
162
|
\`${labels.acceptancePlan}: \${process.env.LOOP_ACCEPTANCE_PLAN_FILE || ${JSON.stringify(labels.missing)}}\`,
|
|
151
163
|
\`${labels.amendments}: \${process.env.LOOP_LATEST_AMENDMENT_FILE || ${JSON.stringify(labels.missing)}}\`,
|
|
152
164
|
\`${labels.checkpoints}: \${process.env.LOOP_CHECKPOINTS_DIR || ${JSON.stringify(labels.missing)}}\`,
|
|
153
|
-
'', task.body, '',
|
|
165
|
+
'', Buffer.byteLength(String(task.body || ''), 'utf8') <= 8192 ? task.body : 'Read the full task in bounded ranges from: ' + process.env.LOOP_TASK_FILE, '',
|
|
166
|
+
contextWorkerInstructions(),
|
|
154
167
|
${JSON.stringify(labels.reread)},
|
|
155
168
|
${JSON.stringify(labels.finish)}
|
|
156
169
|
].join('\\n');
|
|
@@ -158,8 +171,8 @@ const child = spawn(${JSON.stringify(openclawBin)}, [
|
|
|
158
171
|
'agent', '--agent', ${JSON.stringify(workerAgent)},
|
|
159
172
|
'--session-key', \`agent:${workerAgent}:loop-task-\${task.id}-g\${sessionGeneration}\`,
|
|
160
173
|
'--message', prompt, '--json', '--timeout', '1800'
|
|
161
|
-
], { cwd: process.cwd(), env: process.env, stdio: '
|
|
162
|
-
|
|
174
|
+
], { cwd: process.cwd(), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
175
|
+
process.exitCode = await observeOpenClawWorker(child);
|
|
163
176
|
`;
|
|
164
177
|
}
|
|
165
178
|
|
|
@@ -174,21 +187,62 @@ function wrapperSource({ queue, loopBin, language }) {
|
|
|
174
187
|
: '(?:queue\\s+(?:this|it)\\s+only|only\\s+queue\\s+(?:this|it)|enqueue\\s+(?:this|it)\\s+only|do\\s+not\\s+(?:run|execute)\\s+(?:this|it)\\s+(?:yet|now))';
|
|
175
188
|
return `#!/usr/bin/env node
|
|
176
189
|
import { spawn } from 'node:child_process';
|
|
190
|
+
import { mkdirSync, openSync, closeSync } from 'node:fs';
|
|
177
191
|
const [command, ...rest] = process.argv.slice(2);
|
|
178
|
-
function
|
|
192
|
+
async function launchWorker() {
|
|
193
|
+
mkdirSync('runtime/loops/${queue}/launches', { recursive: true });
|
|
194
|
+
const log = 'runtime/loops/${queue}/launches/' + Date.now() + '-' + process.pid + '.log';
|
|
195
|
+
const fd = openSync(log, 'wx', 0o600);
|
|
196
|
+
try {
|
|
197
|
+
const child = spawn(process.execPath, [process.argv[1], 'run-background'], {
|
|
198
|
+
cwd: process.cwd(), env: process.env, detached: true, stdio: ['ignore', fd, fd]
|
|
199
|
+
});
|
|
200
|
+
await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
|
|
201
|
+
child.unref();
|
|
202
|
+
console.log(JSON.stringify({ status: 'worker_started', pid: child.pid, log, accepted: false }));
|
|
203
|
+
} finally { closeSync(fd); }
|
|
204
|
+
}
|
|
205
|
+
function run(args, inspectLock = false) {
|
|
179
206
|
return new Promise((resolve) => {
|
|
180
|
-
const child = spawn(process.execPath, [${JSON.stringify(loopBin)}, ...args], {
|
|
181
|
-
|
|
207
|
+
const child = spawn(process.execPath, [${JSON.stringify(loopBin)}, ...args], {
|
|
208
|
+
cwd: process.cwd(), env: process.env,
|
|
209
|
+
stdio: inspectLock ? ['ignore', 'pipe', 'inherit'] : 'inherit'
|
|
210
|
+
});
|
|
211
|
+
let stdout = ''; let overflow = false;
|
|
212
|
+
if (inspectLock) child.stdout.on('data', (chunk) => {
|
|
213
|
+
process.stdout.write(chunk);
|
|
214
|
+
if (stdout.length + chunk.length <= 1024 * 1024 && !overflow) stdout += chunk;
|
|
215
|
+
else { stdout = ''; overflow = true; }
|
|
216
|
+
});
|
|
217
|
+
child.on('error', (error) => {
|
|
218
|
+
console.error(error.message);
|
|
219
|
+
resolve(inspectLock ? { code: 1, locked: false } : 1);
|
|
220
|
+
});
|
|
221
|
+
child.on('close', (code, signal) => {
|
|
222
|
+
code = code ?? (signal ? 128 : 1);
|
|
223
|
+
let result;
|
|
224
|
+
if (inspectLock && !overflow) { try { result = JSON.parse(stdout); } catch {} }
|
|
225
|
+
resolve(inspectLock ? { code, locked: code === 2 && result?.status === 'locked' && result?.processed === false } : code);
|
|
226
|
+
});
|
|
182
227
|
});
|
|
183
228
|
}
|
|
184
229
|
|
|
185
230
|
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
186
231
|
async function runWhenUnlocked(args, waitMs = 300000) {
|
|
187
232
|
const deadline = Date.now() + waitMs;
|
|
233
|
+
let attempts = 0;
|
|
188
234
|
while (true) {
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
235
|
+
const result = await run([...args, '--json'], true);
|
|
236
|
+
attempts++;
|
|
237
|
+
// Exit 2 also represents preflight/gate failures: never retry those.
|
|
238
|
+
if (!result.locked) return result.code;
|
|
239
|
+
const remaining = deadline - Date.now();
|
|
240
|
+
if (remaining <= 0) {
|
|
241
|
+
console.error(JSON.stringify({ status: 'worker_lock_wait_timeout', attempts, waitMs, accepted: false }));
|
|
242
|
+
return result.code;
|
|
243
|
+
}
|
|
244
|
+
console.log(JSON.stringify({ status: 'worker_waiting_for_lock', attempts, accepted: false }));
|
|
245
|
+
await wait(Math.min(250, remaining));
|
|
192
246
|
}
|
|
193
247
|
}
|
|
194
248
|
if (command === 'route') {
|
|
@@ -215,12 +269,17 @@ if (command === 'route') {
|
|
|
215
269
|
const routedArgs = rest.filter((arg) => arg !== '--relay-enqueue');
|
|
216
270
|
const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', routeMode, ...routedArgs]);
|
|
217
271
|
const queueOnly = relayEnqueue || new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
|
|
218
|
-
|
|
272
|
+
if (!routeCode && !queueOnly && !amendment) {
|
|
273
|
+
await launchWorker();
|
|
274
|
+
process.exit(0);
|
|
275
|
+
}
|
|
276
|
+
const runCode = routeCode;
|
|
219
277
|
const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
220
278
|
const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
221
279
|
process.exitCode = routeCode || runCode || humanNotifyCode || terminalNotifyCode;
|
|
222
|
-
} else if (command === 'run-once') {
|
|
223
|
-
const
|
|
280
|
+
} else if (command === 'run-once' || command === 'run-background') {
|
|
281
|
+
const execute = command === 'run-background' ? runWhenUnlocked : run;
|
|
282
|
+
const runCode = await execute(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/openclaw-loop-notify.mjs', ...rest]);
|
|
224
283
|
const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
225
284
|
const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
226
285
|
process.exitCode = runCode || humanNotifyCode || terminalNotifyCode;
|
|
@@ -262,7 +321,7 @@ process.stdout.write(JSON.stringify(result) + '\\n');
|
|
|
262
321
|
}
|
|
263
322
|
|
|
264
323
|
function schedulerServiceSource({ root, queue, language }) {
|
|
265
|
-
return `[Unit]\nDescription=${text(language, `Taskforce Loop Engineering scheduler for ${queue}`, `${queue} 的 Taskforce Loop Engineering 调度器`)}\nAfter=default.target\n\n[Service]\nType=oneshot\nWorkingDirectory=${
|
|
324
|
+
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`;
|
|
266
325
|
}
|
|
267
326
|
|
|
268
327
|
function schedulerTimerSource({ queue, language }) {
|
|
@@ -306,6 +365,8 @@ function instructionsBlock({ queue, language }) {
|
|
|
306
365
|
- 飞书回调必须先由可信传输层验签,再设置 \`LOOP_FEISHU_SIGNATURE_VERIFIED=1\` 调用 Gate bridge;未验签失败关闭。普通聊天、引用、转发和截图不能审批。
|
|
307
366
|
- 已由 Loop 管理的任务必须直接执行,不能再次路由。
|
|
308
367
|
- 状态查询只读。高风险外部动作、破坏性操作、生产变更、凭据操作和记忆迁移仍需单独确认。
|
|
368
|
+
- 进度、证据和失败原因问询:只读检查点、验证结果及 worker 存活状态后立即回复;发现失败不等于获准在聊天主会话修复、构建或复测。已授权的后续执行留给独立任务 worker。
|
|
369
|
+
- 会话路由返回后台 worker 启动回执后结束本轮聊天等待;启动回执不代表验收通过。不得把独立 worker 的实现工作接回聊天主会话。
|
|
309
370
|
- 队列:\`${queue}\`。
|
|
310
371
|
<!-- loop-engineering:openclaw:end -->\n`;
|
|
311
372
|
return `\n<!-- loop-engineering:openclaw:start -->
|
|
@@ -337,7 +398,7 @@ async function main() {
|
|
|
337
398
|
args.openclawBin = await resolveExecutable(args.openclawBin);
|
|
338
399
|
const worker = await resolveWorkerAgent(args);
|
|
339
400
|
args.workerAgent = worker.workerAgent;
|
|
340
|
-
args.loopBin = new URL('../bin/loop-engineering.mjs', import.meta.url)
|
|
401
|
+
args.loopBin = fileURLToPath(new URL('../bin/loop-engineering.mjs', import.meta.url));
|
|
341
402
|
args.humanGateAdapter = new URL('../lib/human-gate-channel-adapter.mjs', import.meta.url).href;
|
|
342
403
|
const systemdUserDir = path.join(process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || '', '.config'), 'systemd', 'user');
|
|
343
404
|
const schedulerUnit = `openclaw-loop-${args.queue}-scheduler.service`;
|
|
@@ -382,7 +443,7 @@ async function main() {
|
|
|
382
443
|
preflightConfig: 'configs/loops/workspace-health.json',
|
|
383
444
|
timeoutMs: 1800000, leaseMs: 1860000, staleActiveMs: 3600000,
|
|
384
445
|
scheduler: { required: true, heartbeatMaxAgeMs: 300000, initialInterval: '1m', minInterval: '1m', maxInterval: '4h', speedupFactor: 0.5, backoffFactor: 2, idleBackoffFactor: 2, humanGateBackoffFactor: 3, longRunHeadroomFactor: 1.25, jitter: '10s' },
|
|
385
|
-
retry: { maxAttempts: 1, runtimeRecoveryMaxAttempts: 2, sessionMaxTicks:
|
|
446
|
+
retry: { maxAttempts: 1, runtimeRecoveryMaxAttempts: 2, sessionMaxTicks: 3, contextBudget: { softRatio: 0.60, hardRatio: 0.75 }, retryDelayMs: 0, retryExitCodes: [1], requiresHumanActionPatterns: ['requires human', '需要人工', 'Permission denied', 'Operation not permitted'] },
|
|
386
447
|
revisionPolicy: { enabled: true, maxRevisionRounds: 3, sameFailureThreshold: 2, requireStrategyChange: true }
|
|
387
448
|
}, null, 2)}\n`;
|
|
388
449
|
const dispatcherContent = dispatcherSource(args);
|
|
@@ -399,19 +460,18 @@ async function main() {
|
|
|
399
460
|
await mkdir(systemdUserDir, { recursive: true });
|
|
400
461
|
await writeFile(files.schedulerService, schedulerServiceContent);
|
|
401
462
|
await writeFile(files.schedulerTimer, schedulerTimerContent);
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
const
|
|
405
|
-
if (enableTimer.code !== 0) throw new Error(`Cannot enable Loop scheduler timer ${schedulerTimer}: ${(enableTimer.stderr || enableTimer.stdout).trim() || `exit ${enableTimer.code}`}`);
|
|
406
|
-
const dashboardInstaller = new URL('./dashboard-autostart-install.mjs', import.meta.url).pathname;
|
|
407
|
-
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 });
|
|
408
|
-
if (dashboardInstall.code !== 0) throw new Error(`Cannot install Dashboard gateway autostart: ${(dashboardInstall.stderr || dashboardInstall.stdout).trim()}`);
|
|
409
|
-
const instructions = await exists(files.instructions) ? await readFile(files.instructions, 'utf8') : '';
|
|
463
|
+
// Record ownership before anything is enabled, so a failure in a later
|
|
464
|
+
// step leaves an integration that manage --action uninstall can remove.
|
|
465
|
+
const previousManifest = await readFile(files.manifest, 'utf8').then(JSON.parse).catch(() => null);
|
|
410
466
|
const managedInstructions = instructionsBlock(args);
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
467
|
+
const recordedInstructions = await applyManagedInstructions(files.instructions, managedInstructions, {
|
|
468
|
+
previousBlock: previousManifest?.managedInstructions?.content,
|
|
469
|
+
force: args.force,
|
|
470
|
+
startMarker: '<!-- loop-engineering:openclaw:start -->',
|
|
471
|
+
endMarker: '<!-- loop-engineering:openclaw:end -->'
|
|
472
|
+
});
|
|
473
|
+
const manifest = {
|
|
474
|
+
version: 5, status: 'installing', queue: args.queue, language: args.language, workerAgent: args.workerAgent, openclawBin: args.openclawBin, systemctlBin: args.systemctlBin, installedAt: new Date().toISOString(),
|
|
415
475
|
managedFiles: [
|
|
416
476
|
{ path: path.relative(args.root, files.queueConfig), sha256: sha256(queueContent) },
|
|
417
477
|
{ path: path.relative(args.root, files.dispatcher), sha256: sha256(dispatcherContent) },
|
|
@@ -423,9 +483,24 @@ async function main() {
|
|
|
423
483
|
{ path: files.schedulerService, unit: schedulerUnit, sha256: sha256(schedulerServiceContent) },
|
|
424
484
|
{ path: files.schedulerTimer, unit: schedulerTimer, sha256: sha256(schedulerTimerContent) }
|
|
425
485
|
],
|
|
426
|
-
managedInstructions: { path: 'AGENTS.md', sha256: sha256(
|
|
486
|
+
managedInstructions: { path: 'AGENTS.md', sha256: sha256(recordedInstructions), content: recordedInstructions },
|
|
487
|
+
dashboard: { listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, installed: false },
|
|
427
488
|
retainedOnUninstall: [`runtime/loops/${args.queue}`]
|
|
428
|
-
}
|
|
489
|
+
};
|
|
490
|
+
const writeManifest = async () => {
|
|
491
|
+
await mkdir(path.dirname(files.manifest), { recursive: true });
|
|
492
|
+
await writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
493
|
+
};
|
|
494
|
+
await writeManifest();
|
|
495
|
+
const daemonReload = await run(args.systemctlBin, ['--user', 'daemon-reload'], { cwd: args.root });
|
|
496
|
+
if (daemonReload.code !== 0) throw new Error(`Cannot reload user systemd units: ${(daemonReload.stderr || daemonReload.stdout).trim() || `exit ${daemonReload.code}`}`);
|
|
497
|
+
const enableTimer = await run(args.systemctlBin, ['--user', 'enable', '--now', schedulerTimer], { cwd: args.root });
|
|
498
|
+
if (enableTimer.code !== 0) throw new Error(`Cannot enable Loop scheduler timer ${schedulerTimer}: ${(enableTimer.stderr || enableTimer.stdout).trim() || `exit ${enableTimer.code}`}`);
|
|
499
|
+
const dashboard = await installDashboardUnlessShared({ root: args.root, listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, systemctlBin: args.systemctlBin, run });
|
|
500
|
+
manifest.dashboard = dashboard;
|
|
501
|
+
if (dashboard.skipped) report.dashboardAutostart = { ...report.dashboardAutostart, skipped: dashboard.skipped };
|
|
502
|
+
manifest.status = 'installed';
|
|
503
|
+
await writeManifest();
|
|
429
504
|
}
|
|
430
505
|
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}`));
|
|
431
506
|
}
|
|
@@ -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 {
|