taskforce-loop-engineering 0.16.0 → 0.16.2

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.
@@ -2,6 +2,7 @@
2
2
  import { access, readFile } from 'node:fs/promises';
3
3
  import { spawn } from 'node:child_process';
4
4
  import path from 'node:path';
5
+ import { diagnosticSources, verifyDiagnosticRuntime, diagnosticEnvironment } from '../lib/openclaw-diagnostic-source.mjs';
5
6
 
6
7
  function parseArgs(argv) {
7
8
  const out = { root: process.cwd(), queue: 'agent-tasks', workerAgent: 'main', openclawBin: 'openclaw', json: false };
@@ -11,6 +12,12 @@ function parseArgs(argv) {
11
12
  else if (arg === '--queue') out.queue = argv[++i];
12
13
  else if (arg === '--worker-agent') out.workerAgent = argv[++i];
13
14
  else if (arg === '--openclaw-bin') out.openclawBin = argv[++i];
15
+ else if (['--source-channel', '--source-account', '--source-target'].includes(arg)) {
16
+ const key = { '--source-channel': 'sourceChannel', '--source-account': 'sourceAccount', '--source-target': 'sourceTarget' }[arg];
17
+ const value = argv[++i];
18
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`);
19
+ out[key] = value;
20
+ }
14
21
  else if (arg === '--json') out.json = true;
15
22
  else if (arg === '--help' || arg === '-h') out.help = true;
16
23
  else throw new Error(`Unknown argument: ${arg}`);
@@ -34,7 +41,7 @@ async function present(file) { try { await access(file); return true; } catch {
34
41
  async function main() {
35
42
  const args = parseArgs(process.argv.slice(2));
36
43
  if (args.help) {
37
- console.log('Usage: loop-engineering-openclaw-doctor [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--json]');
44
+ console.log('Usage: loop-engineering-openclaw-doctor [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--source-channel channel] [--source-account account] [--source-target dry-run-target] [--json]');
38
45
  return;
39
46
  }
40
47
  const required = [
@@ -53,6 +60,13 @@ async function main() {
53
60
  );
54
61
  const checks = [];
55
62
  for (const relative of required) checks.push({ id: `file:${relative}`, ok: await present(path.join(args.root, relative)) });
63
+ let runtimeVerified = false;
64
+ try {
65
+ const executable = await verifyDiagnosticRuntime(args);
66
+ args.openclawBin = executable;
67
+ runtimeVerified = true;
68
+ checks.push({ id: 'diagnostic_runtime', ok: true, detail: executable });
69
+ } catch (error) { checks.push({ id: 'diagnostic_runtime', ok: false, detail: error.message }); }
56
70
  const cli = await run(args.openclawBin, ['--version'], { cwd: args.root });
57
71
  checks.push({ id: 'openclaw_cli', ok: cli.code === 0, detail: (cli.stdout || cli.stderr).trim().slice(0, 300) });
58
72
  const agentsResult = await run(args.openclawBin, ['agents', 'list', '--json'], { cwd: args.root });
@@ -67,12 +81,17 @@ async function main() {
67
81
  } catch (error) { checks.push({ id: 'queue_config', ok: false, detail: error.message }); }
68
82
  }
69
83
  const notifier = path.join(args.root, 'scripts/loops/openclaw-loop-notify.mjs');
70
- if (await present(notifier)) {
71
- const smoke = await run(process.execPath, [notifier, 'Loop Engineering notification dry-run'], {
72
- cwd: args.root,
73
- env: { ...process.env, LOOP_NOTIFICATION_DRY_RUN: '1', LOOP_NOTIFICATION_SOURCE: JSON.stringify({ channel: 'feishu', target: 'user:loop-doctor-dry-run', reply_to: 'doctor-message' }) }
74
- });
75
- checks.push({ id: 'notification_dry_run', ok: smoke.code === 0, detail: (smoke.stdout || smoke.stderr).trim().slice(0, 500) });
84
+ let notificationSources = [];
85
+ try { if (runtimeVerified) notificationSources = await diagnosticSources(args, run); }
86
+ catch (error) { checks.push({ id: 'notification_channels', ok: false, detail: error.message }); }
87
+ if (runtimeVerified && await present(notifier)) {
88
+ for (const source of notificationSources) {
89
+ const smoke = await run(process.execPath, [notifier, 'Loop Engineering notification dry-run'], {
90
+ cwd: args.root,
91
+ env: { ...diagnosticEnvironment(), LOOP_NOTIFICATION_DRY_RUN: '1', LOOP_NOTIFICATION_SOURCE: JSON.stringify(source) }
92
+ });
93
+ checks.push({ id: 'notification_dry_run', channel: source.channel, account: source.account, ok: smoke.code === 0, detail: (smoke.stdout || smoke.stderr).trim().slice(0, 500) });
94
+ }
76
95
  }
77
96
  const gateBridge = path.join(args.root, 'scripts/loops/openclaw-loop-gate.mjs');
78
97
  if (await present(gateBridge)) {
@@ -82,7 +101,7 @@ async function main() {
82
101
  checks.push({ id: 'human_gate_bridge_self_test', ok: selfTest.code === 0 && /"externalWrite":false/.test(selfTest.stdout), detail: (selfTest.stdout || selfTest.stderr).trim().slice(0, 500) });
83
102
  }
84
103
  const failed = checks.filter((check) => !check.ok);
85
- const report = { version: 1, status: failed.length ? 'fail' : 'ok', readOnly: true, externalWrite: false, root: args.root, queue: args.queue, workerAgent: args.workerAgent, checks, failed: failed.map((check) => check.id) };
104
+ const report = { version: 1, status: failed.length ? 'fail' : 'ok', readOnly: true, externalWrite: false, root: args.root, queue: args.queue, workerAgent: args.workerAgent, notificationSources, checks, failed: failed.map((check) => check.id) };
86
105
  console.log(args.json ? JSON.stringify(report, null, 2) : `OpenClaw Loop doctor: ${report.status}\nchecks: ${checks.length - failed.length}/${checks.length}\nfailed: ${report.failed.join(', ') || 'none'}`);
87
106
  if (failed.length) process.exitCode = 1;
88
107
  }
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { chmod, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
2
+ import { chmod, mkdtemp, readFile, readdir, rm, writeFile, symlink } 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');
@@ -12,19 +14,32 @@ const systemctlCapture = path.join(root, 'systemctl-calls.jsonl');
12
14
  process.env.XDG_CONFIG_HOME = path.join(root, 'xdg');
13
15
  process.env.SYSTEMCTL_CAPTURE = systemctlCapture;
14
16
  await writeFile(mockOpenClaw, `#!/usr/bin/env node
15
- import { mkdir, writeFile } from 'node:fs/promises';
17
+ import { mkdir, writeFile, appendFile } from 'node:fs/promises';
16
18
  import path from 'node:path';
17
19
  const args = process.argv.slice(2);
20
+ if (process.env.DIAGNOSTIC_CALLS) await appendFile(process.env.DIAGNOSTIC_CALLS, JSON.stringify({ invocation: process.env.TEST_INVOKED_AS, args }) + '\\n');
18
21
  if (args.includes('--account') && args[args.indexOf('--account') + 1] === 'doctor') {
19
22
  console.error('Unknown account: doctor');
20
23
  process.exit(1);
21
24
  }
25
+ if (args[0] === 'message' && process.env.TEST_IM_CHANNEL) {
26
+ const value = (flag) => args[args.indexOf(flag) + 1];
27
+ if (!args.includes('--dry-run') || value('--channel') !== process.env.TEST_IM_CHANNEL || value('--account') !== (process.env.TEST_IM_ACCOUNT || 'main')) {
28
+ console.error('Wrong channel/account or unsafe notification'); process.exit(1);
29
+ }
30
+ }
22
31
  if (args[0] === '--version') console.log('OpenClaw mock 1.0');
32
+ else if (args[0] === 'channels' && args[1] === 'list') console.log(process.env.TEST_BROKEN_INVENTORY || JSON.stringify({ chat: { [process.env.TEST_IM_CHANNEL || 'feishu']: [process.env.TEST_IM_ACCOUNT || 'main'] } }));
23
33
  else if (args[0] === 'agents' && args[1] === 'list') console.log(JSON.stringify([{ id: 'builder' }]));
24
34
  else {
25
35
  if (args[0] === 'agent' && process.env.LOOP_CHECKPOINTS_DIR) {
26
36
  const dir = path.resolve(process.cwd(), process.env.LOOP_CHECKPOINTS_DIR);
27
37
  await mkdir(dir, { recursive: true });
38
+ if (process.env.LOOP_REVIEW_TEST) {
39
+ 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' }] }));
40
+ console.error(process.env.LOOP_REVIEW_TEST.endsWith('overflow') ? 'context_length_exceeded' : 'generic worker failure');
41
+ process.exit(1);
42
+ }
28
43
  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
44
  }
30
45
  if (process.env.DELIVERY_CAPTURE) await writeFile(process.env.DELIVERY_CAPTURE, JSON.stringify(args));
@@ -69,10 +84,113 @@ if (queue.language !== 'en') throw new Error('resolved installation language was
69
84
  if (queue.scheduler?.required !== true || queue.scheduler?.heartbeatMaxAgeMs !== 300000) throw new Error('required scheduler heartbeat was not installed');
70
85
  const dispatcher = await readFile(path.join(root, 'scripts/loops/openclaw-loop-dispatch.mjs'), 'utf8');
71
86
  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 !== 10) throw new Error('bounded runtime recovery policy was not installed');
87
+ if (queue.retry?.runtimeRecoveryMaxAttempts !== 2 || queue.retry?.sessionMaxTicks !== 3) throw new Error('bounded runtime recovery policy was not installed');
88
+ // Exercise the generated dispatcher, including large-task prompt bounds and
89
+ // concrete file references (the Gateway worker does not inherit CLI env vars).
90
+ const largeTaskFile = path.join(root, 'large-task.json');
91
+ const largeCapture = path.join(root, 'large-task-args.json');
92
+ await writeFile(largeTaskFile, JSON.stringify({ id: 'large-task', body: 'x'.repeat(100000) }));
93
+ const largeDispatch = await new Promise((resolve, reject) => {
94
+ 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'] });
95
+ let stderr = '';
96
+ child.stdout.resume();
97
+ child.stderr.on('data', x => stderr += x);
98
+ child.on('error', reject);
99
+ child.on('close', code => resolve({ code, stderr }));
100
+ });
101
+ if (largeDispatch.code !== 0) throw new Error('generated context dispatcher failed: ' + largeDispatch.stderr);
102
+ const largeArgs = JSON.parse(await readFile(largeCapture, 'utf8'));
103
+ const largePrompt = largeArgs[largeArgs.indexOf('--message') + 1];
104
+ 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');
105
+ // The generated dispatcher/observer must preserve checkpoint gating through
106
+ // actual queue retries and overflow recovery, not just prompt source checks.
107
+ for (const failure of ['ordinary', 'overflow', 'terminal-ordinary', 'terminal-overflow']) {
108
+ await enqueueTask(root, { queue: 'review-order', title: failure, task: 'Inspect mocked local data' });
109
+ 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 };
110
+ const result = await runQueueOnce(root, options);
111
+ assert.equal(result.status, 'needs_human_input');
112
+ assert.equal(result.run.dispatchAttempts.length, 1);
113
+ assert.equal(result.run.revisionRequest, null);
114
+ assert.equal((await runQueueOnce(root, options)).processed, false);
115
+ }
73
116
  const instructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
74
117
  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
118
  const wrapper = await readFile(path.join(root, 'scripts/loops/openclaw-loop.mjs'), 'utf8');
119
+ // A slow worker must outlive its routing caller, retaining observable output.
120
+ const fakeLoop = path.join(root, 'slow-loop.mjs');
121
+ const asyncWrapper = path.join(root, 'async-wrapper.mjs');
122
+ const workerDone = path.join(root, 'worker-done');
123
+ await writeFile(fakeLoop, `import { writeFile } from 'node:fs/promises';
124
+ if (process.argv[2] === 'run-queue') {
125
+ await new Promise(resolve => setTimeout(resolve, 4000));
126
+ await writeFile(${JSON.stringify(workerDone)}, 'done');
127
+ }
128
+ `);
129
+ await writeFile(asyncWrapper, wrapper.replace(/spawn\(process\.execPath, \["[^"]+"/, 'spawn(process.execPath, [' + JSON.stringify(fakeLoop)));
130
+ const launchStart = Date.now();
131
+ const launched = await new Promise((resolve, reject) => {
132
+ 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'] });
133
+ let stdout = ''; let stderr = '';
134
+ child.stdout.on('data', x => stdout += x); child.stderr.on('data', x => stderr += x);
135
+ child.on('error', reject); child.on('close', code => resolve({ code, stdout, stderr }));
136
+ });
137
+ if (launched.code !== 0 || Date.now() - launchStart >= 3000 || !launched.stdout.includes('worker_started')) throw new Error('routing waited for slow worker: ' + launched.stderr);
138
+ const receipt = JSON.parse(launched.stdout.trim());
139
+ if (receipt.accepted !== false || !receipt.pid || !receipt.log) throw new Error('launch receipt misrepresents acceptance');
140
+ while (Date.now() - launchStart < 8000 && !(await readFile(workerDone, 'utf8').catch(() => ''))) await new Promise(resolve => setTimeout(resolve, 100));
141
+ if (await readFile(workerDone, 'utf8') !== 'done') throw new Error('background worker did not finish');
142
+ // Exercise the actual generated background entry, not just a function-name check.
143
+ // Each fixture has its own CLI, counters and completion marker; no real delivery.
144
+ for (const scenario of ['lock-once', 'lock-timeout', 'preflight', 'malformed', 'fatal', 'manual-lock']) {
145
+ const cli = path.join(root, scenario + '-cli.mjs');
146
+ const entry = path.join(root, scenario + '-wrapper.mjs');
147
+ const countFile = path.join(root, scenario + '-count');
148
+ const doneFile = path.join(root, scenario + '-done');
149
+ await writeFile(cli, `import { readFile, writeFile } from 'node:fs/promises';
150
+ const scenario = ${JSON.stringify(scenario)};
151
+ const command = process.argv[2];
152
+ if (command === 'run-queue') {
153
+ const count = Number(await readFile(${JSON.stringify(countFile)}, 'utf8').catch(() => '0')) + 1;
154
+ await writeFile(${JSON.stringify(countFile)}, String(count));
155
+ if (scenario === 'fatal') process.exit(1);
156
+ if (scenario === 'malformed') { console.log('not JSON'); process.exit(2); }
157
+ if (scenario === 'preflight') { console.log(JSON.stringify({ processed: true, status: 'blocked_preflight' })); process.exit(2); }
158
+ if (scenario !== 'lock-once' || count === 1) {
159
+ console.log(JSON.stringify({ processed: false, status: 'locked' })); process.exit(2);
160
+ }
161
+ console.log(JSON.stringify({ processed: true, status: 'completed' }));
162
+ }
163
+ if (command === 'queue-terminal-notify') await writeFile(${JSON.stringify(doneFile)}, 'done');
164
+ `);
165
+ const source = wrapper
166
+ .replace(/spawn\(process\.execPath, \["[^"]+"/, 'spawn(process.execPath, [' + JSON.stringify(cli))
167
+ .replace('waitMs = 300000', 'waitMs = 600');
168
+ await writeFile(entry, source);
169
+ const startedAt = Date.now();
170
+ const result = await new Promise((resolve, reject) => {
171
+ 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];
172
+ const child = spawn(process.execPath, [entry, ...args], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
173
+ let stdout = ''; let stderr = '';
174
+ child.stdout.on('data', chunk => stdout += chunk);
175
+ child.stderr.on('data', chunk => stderr += chunk);
176
+ child.on('error', reject);
177
+ child.on('close', code => resolve({ code, stdout, stderr }));
178
+ });
179
+ while (Date.now() - startedAt < 8000 && !(await readFile(doneFile, 'utf8').catch(() => ''))) await new Promise(resolve => setTimeout(resolve, 50));
180
+ if (await readFile(doneFile, 'utf8').catch(() => '') !== 'done') throw new Error(scenario + ': worker did not reach notifications');
181
+ const count = Number(await readFile(countFile, 'utf8'));
182
+ if (scenario === 'manual-lock') {
183
+ if (result.code !== 2 || count !== 1) throw new Error('manual run-once changed semantics');
184
+ continue;
185
+ }
186
+ if (result.code !== 0) throw new Error(scenario + ': route failed: ' + result.stderr);
187
+ const receipt = JSON.parse(result.stdout.trim());
188
+ if (receipt.status !== 'worker_started' || receipt.accepted !== false) throw new Error(scenario + ': invalid receipt');
189
+ const log = await readFile(path.join(root, receipt.log), 'utf8');
190
+ 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');
191
+ if (scenario === 'lock-timeout' && (count < 2 || count > 10 || !log.includes('worker_lock_wait_timeout'))) throw new Error('lock wait was not bounded/observable');
192
+ if (['preflight', 'malformed', 'fatal'].includes(scenario) && (count !== 1 || log.includes('worker_waiting_for_lock'))) throw new Error(scenario + ': non-lock failure was retried');
193
+ }
76
194
  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
195
  if (!wrapper.includes('process.exitCode = tickCode;') || wrapper.includes('process.exitCode = tickCode || humanNotifyCode || terminalNotifyCode;')) throw new Error('scheduler health still depends on notification delivery');
78
196
  const missingSourceRoute = await new Promise((resolve) => {
@@ -126,6 +244,8 @@ const deliveredArgs = JSON.parse(await readFile(deliveryCapture, 'utf8'));
126
244
  for (const expected of ['message', 'send', '--channel', 'slack', '--target', 'channel:C123', '--account', 'work', '--reply-to', 'M456', 'async result']) {
127
245
  if (!deliveredArgs.includes(expected)) throw new Error(`notifier did not forward ${expected}`);
128
246
  }
247
+ process.env.TEST_IM_CHANNEL = process.env.DIAGNOSTIC_TEST_CHANNEL || 'feishu';
248
+ process.env.TEST_IM_ACCOUNT = 'diagnostic-account';
129
249
  const doctor = new URL('./openclaw-doctor.mjs', import.meta.url).pathname;
130
250
  const doctorResult = await new Promise((resolve) => {
131
251
  const child = spawn(process.execPath, [doctor, '--root', root, '--queue', 'test-tasks', '--worker-agent', 'builder', '--openclaw-bin', mockOpenClaw, '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
@@ -139,6 +259,98 @@ const doctorReport = JSON.parse(doctorResult.stdout);
139
259
  if (doctorReport.status !== 'ok' || doctorReport.externalWrite !== false || !doctorReport.checks.some((check) => check.id === 'notification_dry_run' && check.ok) || !doctorReport.checks.some((check) => check.id === 'human_gate_bridge_self_test' && check.ok)) throw new Error('doctor did not complete safe notification and Human Gate self-tests');
140
260
  if (JSON.parse(await readFile(deliveryCapture, 'utf8')).includes('doctor')) throw new Error('doctor notification forwarded a synthetic account');
141
261
  const smoke = new URL('./openclaw-smoke.mjs', import.meta.url).pathname;
262
+
263
+ // Different executable, same reported version/inventory: never probe installed A
264
+ // after discovering B, and never let smoke dispatch a worker after this failure.
265
+ async function diagnosticRun(script, executable, extraEnv = {}) {
266
+ return new Promise((resolve) => {
267
+ const child = spawn(process.execPath, [script, '--root', root, '--queue', 'test-tasks', '--worker-agent', 'builder', '--openclaw-bin', executable, '--json'], { env: { ...process.env, ...extraEnv }, stdio: ['ignore', 'pipe', 'pipe'] });
268
+ let stdout = ''; let stderr = '';
269
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
270
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
271
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
272
+ });
273
+ }
274
+ const alternate = path.join(root, 'alternate-openclaw.mjs');
275
+ await writeFile(alternate, await readFile(mockOpenClaw));
276
+ await chmod(alternate, 0o755);
277
+ const deliveryBefore = await readFile(deliveryCapture, 'utf8');
278
+ const mismatch = await diagnosticRun(doctor, alternate);
279
+ assert.equal(mismatch.code, 1);
280
+ assert.ok(JSON.parse(mismatch.stdout).failed.includes('diagnostic_runtime'));
281
+ assert.ok(!JSON.parse(mismatch.stdout).checks.some((check) => check.id === 'notification_dry_run'));
282
+ const mismatchSmoke = await diagnosticRun(smoke, alternate);
283
+ assert.equal(mismatchSmoke.code, 1);
284
+ assert.match(mismatchSmoke.stderr, /diagnostic_runtime/);
285
+ assert.equal(await readFile(deliveryCapture, 'utf8'), deliveryBefore);
286
+ assert.ok(!(await readdir(path.join(root, 'configs/loops/queues'))).some((name) => name.startsWith('smoke-')));
287
+ // PATH and symlink aliases of the same runtime remain valid.
288
+ const alias = path.join(root, 'alias-openclaw');
289
+ await symlink(mockOpenClaw, alias);
290
+ assert.equal((await diagnosticRun(doctor, alias)).code, 0);
291
+ assert.equal((await diagnosticRun(doctor, path.basename(mockOpenClaw), { PATH: root + path.delimiter + process.env.PATH })).code, 0);
292
+ // Conflicting inherited sources must never override any reported route.
293
+ const callsFile = path.join(root, 'diagnostic-calls.jsonl');
294
+ const staleEnv = {
295
+ LOOP_HUMAN_INPUT_SOURCE: JSON.stringify({ channel: 'feishu', account: 'stale', target: 'user:stale' }),
296
+ LOOP_NOTIFICATION_SOURCE: JSON.stringify({ channel: 'slack', account: 'stale', target: 'channel:stale' }),
297
+ DIAGNOSTIC_CALLS: callsFile
298
+ };
299
+ async function capturedCalls() {
300
+ return (await readFile(callsFile, 'utf8')).trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));
301
+ }
302
+ function assertRoutes(calls, sources) {
303
+ const messages = calls.filter((call) => call.args[0] === 'message');
304
+ assert.equal(messages.length, sources.length);
305
+ messages.forEach(({ args }, index) => {
306
+ const value = (flag) => args[args.indexOf(flag) + 1];
307
+ assert.ok(args.includes('--dry-run'));
308
+ assert.equal(value('--channel'), sources[index].channel);
309
+ assert.equal(value('--account'), sources[index].account);
310
+ assert.equal(value('--target'), sources[index].target);
311
+ });
312
+ }
313
+ await writeFile(callsFile, '');
314
+ const multi = await diagnosticRun(doctor, mockOpenClaw, { ...staleEnv, TEST_IM_CHANNEL: '', TEST_BROKEN_INVENTORY: JSON.stringify({ chat: { telegram: ['one', 'two'], slack: { accounts: ['team'] } } }) });
315
+ assert.equal(multi.code, 0, multi.stderr);
316
+ assertRoutes(await capturedCalls(), JSON.parse(multi.stdout).notificationSources);
317
+
318
+ // A shared shell wrapper selects its profile from $0 (not realpath).
319
+ // Even when the caller supplies the B alias, all probes must use installed A.
320
+ const originalMock = await readFile(mockOpenClaw, 'utf8');
321
+ const backingMock = path.join(root, 'backing-mock.mjs');
322
+ await writeFile(backingMock, originalMock);
323
+ try {
324
+ await writeFile(mockOpenClaw, `#!/bin/sh
325
+ export TEST_INVOKED_AS="$0"
326
+ case "$0" in *alias-openclaw) export TEST_IM_CHANNEL=telegram TEST_IM_ACCOUNT=profile-b ;; esac
327
+ exec node "$(dirname "$0")/backing-mock.mjs" "$@"
328
+ `);
329
+ await writeFile(callsFile, '');
330
+ const profiled = await diagnosticRun(doctor, alias, staleEnv);
331
+ assert.equal(profiled.code, 0, profiled.stderr);
332
+ const report = JSON.parse(profiled.stdout);
333
+ assert.equal(report.notificationSources[0].channel, process.env.TEST_IM_CHANNEL);
334
+ const calls = await capturedCalls();
335
+ assert.ok(calls.some((call) => call.args[0] === 'channels'));
336
+ assert.ok(calls.every((call) => call.invocation === mockOpenClaw));
337
+ assertRoutes(calls, report.notificationSources);
338
+ } finally { await writeFile(mockOpenClaw, originalMock); }
339
+ // A stale/tampered generated caller must fail even if manifest CLI matches.
340
+ const notifierPath = path.join(root, 'scripts/loops/openclaw-loop-notify.mjs');
341
+ const notifierOriginal = await readFile(notifierPath, 'utf8');
342
+ try {
343
+ await writeFile(notifierPath, notifierOriginal.replace(JSON.stringify(mockOpenClaw), JSON.stringify(alternate)));
344
+ const drift = await diagnosticRun(doctor, mockOpenClaw);
345
+ assert.equal(drift.code, 1);
346
+ assert.ok(JSON.parse(drift.stdout).failed.includes('diagnostic_runtime'));
347
+ } finally { await writeFile(notifierPath, notifierOriginal); }
348
+ const brokenInventory = { TEST_BROKEN_INVENTORY: JSON.stringify({ chat: { [process.env.TEST_IM_CHANNEL]: ['diagnostic-account'], broken: { accounts: 'invalid' } } }) };
349
+ const malformed = await diagnosticRun(doctor, mockOpenClaw, brokenInventory);
350
+ assert.equal(malformed.code, 1);
351
+ assert.ok(JSON.parse(malformed.stdout).failed.includes('notification_channels'));
352
+ assert.equal((await diagnosticRun(smoke, mockOpenClaw, brokenInventory)).code, 1);
353
+
142
354
  const smokeSource = await readFile(smoke, 'utf8');
143
355
  if (!smokeSource.includes('Do not change user or project files, configuration, credentials, or external state.')
144
356
  || !smokeSource.includes('Writing the required Loop checkpoint and verification evidence under')
@@ -147,8 +359,9 @@ if (!smokeSource.includes('Do not change user or project files, configuration, c
147
359
  throw new Error('OpenClaw smoke permission boundary or checkpoint requirement is missing');
148
360
  }
149
361
  const loopBin = new URL('../bin/loop-engineering.mjs', import.meta.url).pathname;
362
+ await writeFile(callsFile, '');
150
363
  const smokeResult = await new Promise((resolve) => {
151
- const child = spawn(process.execPath, [smoke, '--root', root, '--queue', 'test-tasks', '--worker-agent', 'builder', '--openclaw-bin', mockOpenClaw, '--loop-bin', loopBin, '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
364
+ const child = spawn(process.execPath, [smoke, '--root', root, '--queue', 'test-tasks', '--worker-agent', 'builder', '--openclaw-bin', mockOpenClaw, '--loop-bin', loopBin, '--json'], { env: { ...process.env, ...staleEnv }, stdio: ['ignore', 'pipe', 'pipe'] });
152
365
  let stdout = ''; let stderr = '';
153
366
  child.stdout.on('data', (chunk) => { stdout += chunk; });
154
367
  child.stderr.on('data', (chunk) => { stderr += chunk; });
@@ -156,8 +369,13 @@ const smokeResult = await new Promise((resolve) => {
156
369
  });
157
370
  if (smokeResult.code !== 0) throw new Error(`smoke failed: ${smokeResult.stderr}`);
158
371
  const smokeReport = JSON.parse(smokeResult.stdout);
372
+ assert.equal(smokeReport.notificationSource.channel, process.env.TEST_IM_CHANNEL);
373
+ assert.equal(smokeReport.notificationSource.account, 'diagnostic-account');
374
+ assertRoutes(await capturedCalls(), [smokeReport.notificationSource, smokeReport.notificationSource]);
159
375
  if (smokeReport.status !== 'ok' || smokeReport.externalWrite !== false || !smokeReport.steps.every((step) => step.ok)) throw new Error('end-to-end smoke did not pass safely');
160
376
  if (JSON.parse(await readFile(deliveryCapture, 'utf8')).includes('doctor')) throw new Error('smoke notification forwarded a synthetic account');
377
+ delete process.env.TEST_IM_CHANNEL;
378
+ delete process.env.TEST_IM_ACCOUNT;
161
379
  try { await readFile(path.join(root, `configs/loops/queues/${smokeReport.smokeQueue}.json`)); throw new Error('smoke config was not cleaned'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
162
380
  try { await readFile(path.join(root, `runtime/loops/${smokeReport.smokeQueue}/state.json`)); throw new Error('smoke runtime was not cleaned'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
163
381
  for (const generated of ['scripts/loops/openclaw-loop-dispatch.mjs', 'scripts/loops/openclaw-loop.mjs', 'scripts/loops/openclaw-loop-notify.mjs', 'scripts/loops/openclaw-loop-gate.mjs']) {
@@ -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: 'inherit' });
173
- child.on('close', (code, signal) => { process.exitCode = code ?? (signal ? 128 : 1); });
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 run(args) {
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], { cwd: process.cwd(), env: process.env, stdio: 'inherit' });
192
- child.on('close', (code, signal) => resolve(code ?? (signal ? 128 : 1)));
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 code = await run(args);
201
- if (code !== 2 || Date.now() >= deadline) return code;
202
- await wait(250);
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
- 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']);
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 runCode = await run(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/openclaw-loop-notify.mjs', ...rest]);
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: 10, retryDelayMs: 0, retryExitCodes: [1], requiresHumanActionPatterns: ['requires human', '需要人工', 'Permission denied', 'Operation not permitted'] },
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);
@@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
3
3
  import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { spawn } from 'node:child_process';
5
5
  import path from 'node:path';
6
+ import { diagnosticEnvironment } from '../lib/openclaw-diagnostic-source.mjs';
6
7
 
7
8
  function parseArgs(argv) {
8
9
  const out = { root: process.cwd(), queue: 'agent-tasks', workerAgent: 'main', openclawBin: 'openclaw', loopBin: 'loop-engineering', json: false, keepArtifacts: false };
@@ -14,6 +15,12 @@ function parseArgs(argv) {
14
15
  else if (arg === '--openclaw-bin') out.openclawBin = argv[++i];
15
16
  else if (arg === '--loop-bin') out.loopBin = argv[++i];
16
17
  else if (arg === '--keep-artifacts') out.keepArtifacts = true;
18
+ else if (['--source-channel', '--source-account', '--source-target'].includes(arg)) {
19
+ const key = { '--source-channel': 'sourceChannel', '--source-account': 'sourceAccount', '--source-target': 'sourceTarget' }[arg];
20
+ const value = argv[++i];
21
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`);
22
+ out[key] = value;
23
+ }
17
24
  else if (arg === '--json') out.json = true;
18
25
  else if (arg === '--help' || arg === '-h') out.help = true;
19
26
  else throw new Error(`Unknown argument: ${arg}`);
@@ -23,7 +30,7 @@ function parseArgs(argv) {
23
30
 
24
31
  function run(command, args, options = {}) {
25
32
  return new Promise((resolve) => {
26
- const child = spawn(command, args, { cwd: options.cwd, env: options.env || process.env, stdio: ['ignore', 'pipe', 'pipe'] });
33
+ const child = spawn(command, args, { cwd: options.cwd, env: diagnosticEnvironment(options.env || process.env), stdio: ['ignore', 'pipe', 'pipe'] });
27
34
  let stdout = ''; let stderr = '';
28
35
  child.stdout.on('data', (chunk) => { stdout += chunk; });
29
36
  child.stderr.on('data', (chunk) => { stderr += chunk; });
@@ -38,7 +45,7 @@ function safeId(value) { if (!/^[a-zA-Z0-9._-]+$/.test(value)) throw new Error('
38
45
  async function main() {
39
46
  const args = parseArgs(process.argv.slice(2));
40
47
  if (args.help) {
41
- console.log('Usage: loop-engineering-openclaw-smoke [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--loop-bin loop-engineering] [--keep-artifacts] [--json]');
48
+ console.log('Usage: loop-engineering-openclaw-smoke [--root workspace] [--queue agent-tasks] [--worker-agent main] [--openclaw-bin openclaw] [--loop-bin loop-engineering] [--keep-artifacts] [--source-channel channel] [--source-account account] [--source-target dry-run-target] [--json]');
42
49
  return;
43
50
  }
44
51
  safeId(args.queue);
@@ -51,10 +58,12 @@ async function main() {
51
58
  const steps = [];
52
59
  let taskId = null;
53
60
  try {
54
- const doctor = await run(process.execPath, [doctorScript, '--root', args.root, '--queue', args.queue, '--worker-agent', args.workerAgent, '--openclaw-bin', args.openclawBin, '--json'], { cwd: args.root });
61
+ const doctor = await run(process.execPath, [doctorScript, '--root', args.root, '--queue', args.queue, '--worker-agent', args.workerAgent, '--openclaw-bin', args.openclawBin, ...['sourceChannel', 'sourceAccount', 'sourceTarget'].flatMap((key) => args[key] ? [{ sourceChannel: '--source-channel', sourceAccount: '--source-account', sourceTarget: '--source-target' }[key], args[key]] : []), '--json'], { cwd: args.root });
55
62
  steps.push({ id: 'doctor', ok: doctor.code === 0 });
56
63
  if (doctor.code !== 0) throw new Error(`doctor failed: ${doctor.stderr || doctor.stdout}`);
57
64
  const doctorReport = JSON.parse(doctor.stdout);
65
+ const source = doctorReport.notificationSources?.[0];
66
+ if (!source) throw new Error('doctor did not resolve a configured notification source');
58
67
  const gateSelfTestOk = doctorReport.checks?.some((check) => check.id === 'human_gate_bridge_self_test' && check.ok);
59
68
  steps.push({ id: 'human_gate_bridge_self_test', ok: gateSelfTestOk === true });
60
69
  if (!gateSelfTestOk) throw new Error('doctor did not verify the installed Human Gate bridge');
@@ -66,7 +75,7 @@ async function main() {
66
75
  await writeFile(smokeConfig, `${JSON.stringify(config, null, 2)}\n`);
67
76
  const smokeRuntimeRel = path.relative(args.root, smokeRuntime);
68
77
  const message = `走 loop:Perform a read-only integration smoke. Do not change user or project files, configuration, credentials, or external state. Writing the required Loop checkpoint and verification evidence under ${smokeRuntimeRel}/ is allowed and required; do not write anywhere else. Report SMOKE_OK with verification evidence.`;
69
- const route = await run(args.loopBin, ['route-message', '--root', args.root, '--queue', smokeQueue, '--message', message, '--route', '--confirm-execute', '--source-channel', 'feishu', '--source-target', 'user:loop-smoke-dry-run', '--source-message-id', `smoke-${runToken}`, '--source-reply-to', `smoke-${runToken}`, '--json'], { cwd: args.root });
78
+ const route = await run(args.loopBin, ['route-message', '--root', args.root, '--queue', smokeQueue, '--message', message, '--route', '--confirm-execute', '--source-channel', source.channel, '--source-target', source.target, '--source-account', source.account, '--source-message-id', `smoke-${runToken}`, '--source-reply-to', `smoke-${runToken}`, '--json'], { cwd: args.root });
70
79
  steps.push({ id: 'route', ok: route.code === 0 });
71
80
  if (route.code !== 0) throw new Error(`route failed: ${route.stderr || route.stdout}`);
72
81
  const routed = JSON.parse(route.stdout);
@@ -89,7 +98,7 @@ async function main() {
89
98
  const terminalOk = terminalNotify.code === 0 && terminal?.sent === 1;
90
99
  steps.push({ id: 'terminal_dry_run_return', ok: terminalOk });
91
100
  if (!terminalOk) throw new Error(`terminal dry-run failed: ${terminalNotify.stderr || terminalNotify.stdout}`);
92
- const report = { version: 1, status: 'ok', readOnlyTask: true, externalWrite: false, queue: args.queue, smokeQueue, workerAgent: args.workerAgent, taskId, steps, keptArtifacts: args.keepArtifacts };
101
+ const report = { version: 1, status: 'ok', readOnlyTask: true, externalWrite: false, queue: args.queue, smokeQueue, workerAgent: args.workerAgent, notificationSource: source, taskId, steps, keptArtifacts: args.keepArtifacts };
93
102
  console.log(args.json ? JSON.stringify(report, null, 2) : `OpenClaw Loop smoke: ok\ntask: ${taskId}\nexternal write: no\nartifacts: ${args.keepArtifacts ? smokeRuntime : 'cleaned'}`);
94
103
  } finally {
95
104
  if (!args.keepArtifacts) {
@@ -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: 50 });
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
- await new Promise((resolve) => setTimeout(resolve, 80));
312
- await recoverTodos(root);
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/);