taskforce-loop-engineering 0.16.0 → 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 +16 -0
- package/lib/context-budget.mjs +147 -0
- package/lib/core.mjs +113 -142
- package/lib/dispatch-classification.mjs +114 -0
- package/package.json +2 -2
- package/scripts/context-budget-self-test.mjs +249 -0
- package/scripts/final-judgement-self-test.mjs +92 -4
- package/scripts/openclaw-install-self-test.mjs +111 -1
- package/scripts/openclaw-install.mjs +63 -13
- package/scripts/safety-regression-self-test.mjs +4 -3
- package/skills/taskforce-loop-engineering/SKILL.md +6 -0
- package/skills/taskforce-loop-engineering/references/context-budget.md +11 -0
|
@@ -3,6 +3,8 @@ import { chmod, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis
|
|
|
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) => {
|
|
@@ -151,6 +151,7 @@ function dispatcherSource({ workerAgent, openclawBin, language }) {
|
|
|
151
151
|
return `#!/usr/bin/env node
|
|
152
152
|
import { readFile } from 'node:fs/promises';
|
|
153
153
|
import { spawn } from 'node:child_process';
|
|
154
|
+
import { contextWorkerInstructions, observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
|
|
154
155
|
const task = JSON.parse(await readFile(process.env.LOOP_TASK_FILE, 'utf8'));
|
|
155
156
|
const sessionGeneration = Number.parseInt(process.env.LOOP_SESSION_GENERATION || '0', 10) || 0;
|
|
156
157
|
const prompt = [
|
|
@@ -161,7 +162,8 @@ const prompt = [
|
|
|
161
162
|
\`${labels.acceptancePlan}: \${process.env.LOOP_ACCEPTANCE_PLAN_FILE || ${JSON.stringify(labels.missing)}}\`,
|
|
162
163
|
\`${labels.amendments}: \${process.env.LOOP_LATEST_AMENDMENT_FILE || ${JSON.stringify(labels.missing)}}\`,
|
|
163
164
|
\`${labels.checkpoints}: \${process.env.LOOP_CHECKPOINTS_DIR || ${JSON.stringify(labels.missing)}}\`,
|
|
164
|
-
'', 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(),
|
|
165
167
|
${JSON.stringify(labels.reread)},
|
|
166
168
|
${JSON.stringify(labels.finish)}
|
|
167
169
|
].join('\\n');
|
|
@@ -169,8 +171,8 @@ const child = spawn(${JSON.stringify(openclawBin)}, [
|
|
|
169
171
|
'agent', '--agent', ${JSON.stringify(workerAgent)},
|
|
170
172
|
'--session-key', \`agent:${workerAgent}:loop-task-\${task.id}-g\${sessionGeneration}\`,
|
|
171
173
|
'--message', prompt, '--json', '--timeout', '1800'
|
|
172
|
-
], { cwd: process.cwd(), env: process.env, stdio: '
|
|
173
|
-
|
|
174
|
+
], { cwd: process.cwd(), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
175
|
+
process.exitCode = await observeOpenClawWorker(child);
|
|
174
176
|
`;
|
|
175
177
|
}
|
|
176
178
|
|
|
@@ -185,21 +187,62 @@ function wrapperSource({ queue, loopBin, language }) {
|
|
|
185
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))';
|
|
186
188
|
return `#!/usr/bin/env node
|
|
187
189
|
import { spawn } from 'node:child_process';
|
|
190
|
+
import { mkdirSync, openSync, closeSync } from 'node:fs';
|
|
188
191
|
const [command, ...rest] = process.argv.slice(2);
|
|
189
|
-
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) {
|
|
190
206
|
return new Promise((resolve) => {
|
|
191
|
-
const child = spawn(process.execPath, [${JSON.stringify(loopBin)}, ...args], {
|
|
192
|
-
|
|
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
|
+
});
|
|
193
227
|
});
|
|
194
228
|
}
|
|
195
229
|
|
|
196
230
|
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
197
231
|
async function runWhenUnlocked(args, waitMs = 300000) {
|
|
198
232
|
const deadline = Date.now() + waitMs;
|
|
233
|
+
let attempts = 0;
|
|
199
234
|
while (true) {
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
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));
|
|
203
246
|
}
|
|
204
247
|
}
|
|
205
248
|
if (command === 'route') {
|
|
@@ -226,12 +269,17 @@ if (command === 'route') {
|
|
|
226
269
|
const routedArgs = rest.filter((arg) => arg !== '--relay-enqueue');
|
|
227
270
|
const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', routeMode, ...routedArgs]);
|
|
228
271
|
const queueOnly = relayEnqueue || new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
|
|
229
|
-
|
|
272
|
+
if (!routeCode && !queueOnly && !amendment) {
|
|
273
|
+
await launchWorker();
|
|
274
|
+
process.exit(0);
|
|
275
|
+
}
|
|
276
|
+
const runCode = routeCode;
|
|
230
277
|
const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
231
278
|
const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
232
279
|
process.exitCode = routeCode || runCode || humanNotifyCode || terminalNotifyCode;
|
|
233
|
-
} else if (command === 'run-once') {
|
|
234
|
-
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]);
|
|
235
283
|
const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
236
284
|
const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
|
|
237
285
|
process.exitCode = runCode || humanNotifyCode || terminalNotifyCode;
|
|
@@ -317,6 +365,8 @@ function instructionsBlock({ queue, language }) {
|
|
|
317
365
|
- 飞书回调必须先由可信传输层验签,再设置 \`LOOP_FEISHU_SIGNATURE_VERIFIED=1\` 调用 Gate bridge;未验签失败关闭。普通聊天、引用、转发和截图不能审批。
|
|
318
366
|
- 已由 Loop 管理的任务必须直接执行,不能再次路由。
|
|
319
367
|
- 状态查询只读。高风险外部动作、破坏性操作、生产变更、凭据操作和记忆迁移仍需单独确认。
|
|
368
|
+
- 进度、证据和失败原因问询:只读检查点、验证结果及 worker 存活状态后立即回复;发现失败不等于获准在聊天主会话修复、构建或复测。已授权的后续执行留给独立任务 worker。
|
|
369
|
+
- 会话路由返回后台 worker 启动回执后结束本轮聊天等待;启动回执不代表验收通过。不得把独立 worker 的实现工作接回聊天主会话。
|
|
320
370
|
- 队列:\`${queue}\`。
|
|
321
371
|
<!-- loop-engineering:openclaw:end -->\n`;
|
|
322
372
|
return `\n<!-- loop-engineering:openclaw:start -->
|
|
@@ -393,7 +443,7 @@ async function main() {
|
|
|
393
443
|
preflightConfig: 'configs/loops/workspace-health.json',
|
|
394
444
|
timeoutMs: 1800000, leaseMs: 1860000, staleActiveMs: 3600000,
|
|
395
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' },
|
|
396
|
-
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'] },
|
|
397
447
|
revisionPolicy: { enabled: true, maxRevisionRounds: 3, sameFailureThreshold: 2, requireStrategyChange: true }
|
|
398
448
|
}, null, 2)}\n`;
|
|
399
449
|
const dispatcherContent = dispatcherSource(args);
|
|
@@ -306,10 +306,11 @@ try {
|
|
|
306
306
|
// A stale handoff cannot take back a recovered and completed todo.
|
|
307
307
|
for (const id of ['A', 'B', 'C']) await registerAgent(root, { id, quota_grants: { default: 100 }, authority_grants: ['local'] });
|
|
308
308
|
await createTodo(root, { id: 't1', title: 'x', acceptance_contract: { c: 1 }, evidence_requirements: ['e'] });
|
|
309
|
-
const claimA = await claimTodo(root, { agent_id: 'A', lease_ms:
|
|
309
|
+
const claimA = await claimTodo(root, { agent_id: 'A', lease_ms: 60_000 });
|
|
310
310
|
const packet = await handoffTodo(root, { todo_id: 't1', agent_id: 'A', target_agent_id: 'B', fencing_token: claimA.fencing_token });
|
|
311
|
-
|
|
312
|
-
|
|
311
|
+
// Expire deterministically through the recovery clock, not a 50 ms race
|
|
312
|
+
// between filesystem operations on a shared CI runner.
|
|
313
|
+
await recoverTodos(root, { now: Date.parse(claimA.todo.claim.lease_expires_at) + 1 });
|
|
313
314
|
const claimC = await claimTodo(root, { agent_id: 'C' });
|
|
314
315
|
await releaseTodo(root, { todo_id: 't1', agent_id: 'C', fencing_token: claimC.fencing_token, completed: true, evidence: 'done' });
|
|
315
316
|
await assert.rejects(() => decideHandoff(root, { handoff_id: packet.id, agent_id: 'B', accept: true }), /Pending handoff not found/);
|
|
@@ -138,6 +138,8 @@ Interpret explicit loop language as follows:
|
|
|
138
138
|
- `继续当前 loop,补充要求:…`: amend the active task in place. Preserve the task id and worker session, write a versioned amendment, update the task contract/dev plan/acceptance plan, and require the worker to reread the latest amendment before checkpoints and completion.
|
|
139
139
|
- A new explicit `走 loop` request while another task is active is a correction/replacement, not ordinary backlog. Supersede the active task at a safe boundary, retain its evidence and lineage, then start the replacement after the lock is released.
|
|
140
140
|
- Status, progress, evidence, or failure questions are read-only and must not start another tick unless the user explicitly asks to continue/run.
|
|
141
|
+
- For status questions, read the latest checkpoint, verification result and worker liveness, then reply before doing further work. A failed check is a result to report, not authorization to edit files, rebuild images or rerun tests in the chat session. Send authorized follow-up execution to the task's independent worker session; never adopt its implementation into the conversation session.
|
|
142
|
+
- Conversation routing starts a background worker and returns a launch receipt; it must not await the full worker tick. A receipt proves process launch only, not lock acquisition, task execution, or acceptance. The background entry waits for a confirmed queue-lock conflict for up to five minutes by default; only exit code 2 with JSON status=locked and processed=false is retried. Read the launch log and queue state after timeout; do not start a duplicate worker from the chat. Keep scheduler/manual `run-once` execution synchronous and inspect its final artifacts separately.
|
|
141
143
|
|
|
142
144
|
Do not infer a queue or dispatcher from this skill. Use the integration installed in the current workspace. For OpenClaw, inspect the generated queue configuration under `configs/loops/queues/` and use the managed wrapper when present. A default installation uses queue `agent-tasks` and the generic wrapper below; an operator may choose another queue or worker during installation.
|
|
143
145
|
|
|
@@ -152,6 +154,10 @@ If the managed wrapper or queue configuration is absent, stop and run the platfo
|
|
|
152
154
|
|
|
153
155
|
Pass the original request faithfully. Preserve source channel, target, account, message id, and reply-to metadata so progress, human gates, and terminal results return to the originating conversation. Missing delivery routing must fail closed.
|
|
154
156
|
|
|
157
|
+
## Context Budget and Durable Handoff
|
|
158
|
+
|
|
159
|
+
For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Keep one bounded objective per turn, read bounded file ranges, and save checkpoints instead of replaying transcripts. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
|
|
160
|
+
|
|
155
161
|
## Task vs Project Classification
|
|
156
162
|
|
|
157
163
|
Classify scope before enqueueing.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Context budget and recovery
|
|
2
|
+
|
|
3
|
+
1. Inspect the installed OpenClaw dispatcher and queue `retry` configuration. New installations use `sessionMaxTicks: 3` and `contextBudget: { softRatio: 0.60, hardRatio: 0.75 }`. Existing explicit tick limits are retained until a reviewed integration upgrade. A package/skill update alone does not update generated workspace files. Hermes does not yet expose the OpenClaw telemetry adapter; do not claim equivalent telemetry protection there.
|
|
4
|
+
2. Keep one bounded objective per worker turn. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
|
|
5
|
+
3. Read `LOOP_RESUME_FILE`, the task contract/plans, latest amendment and latest relevant checkpoint. Resolve relative references against its `workspaceRoot`. Read a previous handoff only for outstanding context; newer checkpoints and amendments take precedence. Do not reload complete transcripts or all historical checkpoints.
|
|
6
|
+
4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, use a small work unit rather than inventing a percentage. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
|
|
7
|
+
5. For unfinished work requiring a new session, write a normal progress checkpoint with `task_id`, `loop_run_id`, and `blockers`, then the bounded JSON handoff at `LOOP_CONTEXT_HANDOFF_FILE` using the schema provided in the worker prompt. Include task/run/generation/attempt binding, the checkpoint path, summary, completed and remaining work, evidence, next action, authority, pending external actions and blockers. Keep it under 16 KiB and omit secrets. The runner validates binding and a real checkpoint inside this task's checkpoint directory; missing/malformed/stale evidence stops recovery rather than accepting the task.
|
|
8
|
+
6. Verify pending external, paid or destructive actions against durable receipts/reservations before replay. Uncertain outcomes and authority blockers stop automatic continuation, including when the worker exits nonzero. An existing handoff is checked before any retry; malformed or stale handoffs fail closed. A clean handoff never overrides a permission failure. Effective blocked checkpoint reviews are checked before each ordinary dispatch retry and also veto runtime recovery when interruption happens before handoff creation. Ordinary and verification failures with effective blockers remain `needs_human_input`, not development revisions; resolved historical blockers do not. Record checkpoint `created_at` (UTC) and, when known, a task-monotonic numeric `sequence`; checkpoint IDs and regenerated review timestamps are not ordering evidence. Conflicting or missing chronology preserves unresolved reviews rather than guessing from names. A newer unblocked snapshot with unambiguous chronology can resolve historical blockers. Multi-milestone plans use the same rule within each milestone and count each planned milestone only once. Terminal acceptance may ignore a chronologically later `needs_human_acceptance` project snapshot only if that review independently passes acceptance and carries no materializable deferred gates. The project label alone cannot hide a blocked/revise review; missing blocker details are not proof of broader-project-only governance. Test accepted terminal + later unknown external outcome under ordinary failure (one and multiple attempts), overflow, incomplete turn and exhausted recovery, including the generated dispatcher. The veto must prevent queue re-entry, not merely change the judgement report. A handoff cannot authorize an action. The runner preserves the task id and increments the session generation on a validated handoff or recognized context overflow; it never retries a known runtime interruption in the same session. Consecutive runtime recoveries (including voluntary handoffs) share `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Accepted project progress resets that recovery counter.
|
|
9
|
+
7. Inspect task/run artifacts after each tick. Accepted unfinished project milestones rotate at the soft/hard threshold or tick limit, whichever occurs first; completed tasks are never requeued just because usage is high. Handoffs remain `runtime_interrupted`, not completed. Full worker stdout/stderr stay in per-run/per-attempt logs; bounded tails plus deduplicated diagnostic signatures reach the runner. Signatures are matched across the complete stream before clipping (including split UTF-8 chunks), using the queue's configured patterns; human-action classification retains priority over runtime recovery. CLI JSON parsing is capped at 2 MiB. No protection here guarantees that one tool-heavy turn cannot overflow: worker discipline and the underlying runtime's compaction remain necessary.
|
|
10
|
+
|
|
11
|
+
Validate with `node scripts/context-budget-self-test.mjs` and `node scripts/openclaw-install-self-test.mjs` in a source checkout. Use disposable queues and mocked workers; do not probe production queues or paid providers for these tests.
|