taskforce-loop-engineering 0.16.1 → 0.16.3

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.
@@ -1,5 +1,5 @@
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';
@@ -14,14 +14,22 @@ const systemctlCapture = path.join(root, 'systemctl-calls.jsonl');
14
14
  process.env.XDG_CONFIG_HOME = path.join(root, 'xdg');
15
15
  process.env.SYSTEMCTL_CAPTURE = systemctlCapture;
16
16
  await writeFile(mockOpenClaw, `#!/usr/bin/env node
17
- import { mkdir, writeFile } from 'node:fs/promises';
17
+ import { mkdir, writeFile, appendFile } from 'node:fs/promises';
18
18
  import path from 'node:path';
19
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');
20
21
  if (args.includes('--account') && args[args.indexOf('--account') + 1] === 'doctor') {
21
22
  console.error('Unknown account: doctor');
22
23
  process.exit(1);
23
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
+ }
24
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'] } }));
25
33
  else if (args[0] === 'agents' && args[1] === 'list') console.log(JSON.stringify([{ id: 'builder' }]));
26
34
  else {
27
35
  if (args[0] === 'agent' && process.env.LOOP_CHECKPOINTS_DIR) {
@@ -236,6 +244,8 @@ const deliveredArgs = JSON.parse(await readFile(deliveryCapture, 'utf8'));
236
244
  for (const expected of ['message', 'send', '--channel', 'slack', '--target', 'channel:C123', '--account', 'work', '--reply-to', 'M456', 'async result']) {
237
245
  if (!deliveredArgs.includes(expected)) throw new Error(`notifier did not forward ${expected}`);
238
246
  }
247
+ process.env.TEST_IM_CHANNEL = process.env.DIAGNOSTIC_TEST_CHANNEL || 'feishu';
248
+ process.env.TEST_IM_ACCOUNT = 'diagnostic-account';
239
249
  const doctor = new URL('./openclaw-doctor.mjs', import.meta.url).pathname;
240
250
  const doctorResult = await new Promise((resolve) => {
241
251
  const child = spawn(process.execPath, [doctor, '--root', root, '--queue', 'test-tasks', '--worker-agent', 'builder', '--openclaw-bin', mockOpenClaw, '--json'], { stdio: ['ignore', 'pipe', 'pipe'] });
@@ -249,6 +259,98 @@ const doctorReport = JSON.parse(doctorResult.stdout);
249
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');
250
260
  if (JSON.parse(await readFile(deliveryCapture, 'utf8')).includes('doctor')) throw new Error('doctor notification forwarded a synthetic account');
251
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
+
252
354
  const smokeSource = await readFile(smoke, 'utf8');
253
355
  if (!smokeSource.includes('Do not change user or project files, configuration, credentials, or external state.')
254
356
  || !smokeSource.includes('Writing the required Loop checkpoint and verification evidence under')
@@ -257,8 +359,9 @@ if (!smokeSource.includes('Do not change user or project files, configuration, c
257
359
  throw new Error('OpenClaw smoke permission boundary or checkpoint requirement is missing');
258
360
  }
259
361
  const loopBin = new URL('../bin/loop-engineering.mjs', import.meta.url).pathname;
362
+ await writeFile(callsFile, '');
260
363
  const smokeResult = await new Promise((resolve) => {
261
- 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'] });
262
365
  let stdout = ''; let stderr = '';
263
366
  child.stdout.on('data', (chunk) => { stdout += chunk; });
264
367
  child.stderr.on('data', (chunk) => { stderr += chunk; });
@@ -266,8 +369,13 @@ const smokeResult = await new Promise((resolve) => {
266
369
  });
267
370
  if (smokeResult.code !== 0) throw new Error(`smoke failed: ${smokeResult.stderr}`);
268
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]);
269
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');
270
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;
271
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; }
272
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; }
273
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']) {
@@ -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) {
@@ -61,6 +61,41 @@ assert.equal(status.waiting, 0, 'B-01 waiting gate must disappear after B-01 lea
61
61
  assert.equal(status.canceled, 1);
62
62
  assert.equal(JSON.parse(await readFile(gateFile, 'utf8')).status, 'canceled');
63
63
 
64
+ // A task-scoped human gate has no project id by design. Project reconciliation
65
+ // must not reinterpret that absence as project_not_found and cancel the task.
66
+ const taskScoped = await enqueueTask(root, {
67
+ queue,
68
+ title: 'Task-scoped external precondition',
69
+ task: 'Wait for a task-local external precondition',
70
+ sourceChannel: 'test',
71
+ sourceTarget: 'owner',
72
+ sourceAccount: 'main'
73
+ });
74
+ const taskScopedDir = path.join(taskRuntimeDirFor(root, queue, taskScoped.task.id), 'checkpoints');
75
+ await mkdir(taskScopedDir, { recursive: true });
76
+ await writeFile(path.join(taskScopedDir, 'cp1.json'), `${JSON.stringify({
77
+ version: 1,
78
+ task_id: taskScoped.task.id,
79
+ checkpoint_id: 'cp1',
80
+ status: 'blocked',
81
+ blockers: [{
82
+ action: 'Wait for task-local connectivity.',
83
+ required_authority: 'Owner confirms the external precondition is restored.',
84
+ authorization_state: 'missing',
85
+ needed_when: 'now',
86
+ materialize: true
87
+ }]
88
+ }, null, 2)}\n`);
89
+ const taskScopedNotice = await notifyHumanInputRequests(root, { queue, notifyCommand: '/bin/true' });
90
+ const taskScopedResult = taskScopedNotice.results.find((item) => item.taskId === taskScoped.task.id);
91
+ assert.equal(taskScopedResult.outcome, 'sent');
92
+ const taskScopedGateFile = path.join(root, taskScopedResult.ledger);
93
+ assert.equal(JSON.parse(await readFile(taskScopedGateFile, 'utf8')).project_id, null);
94
+ await reconcileProjectGates(root, { queue });
95
+ assert.equal(JSON.parse(await readFile(taskScopedGateFile, 'utf8')).status, 'waiting_for_human');
96
+ assert.equal((await queueStatus(root, queue)).waiting, 1, 'task-scoped gate must remain waiting');
97
+ await resolveHumanInput(root, { queue, gateId: `${taskScoped.task.id}:cp1`, input: 'task-local precondition restored' });
98
+
64
99
  const other = await enqueueTask(root, { queue, title: 'Other project task', task: 'Project other', projectId: 'other' });
65
100
  const openreel = await enqueueTask(root, { queue, title: 'OpenReel target', task: 'Project openreel', projectId: 'openreel' });
66
101
  await rename(path.join(root, other.file), path.join(root, 'runtime', 'loops', queue, 'active', path.basename(other.file)));
@@ -399,4 +434,4 @@ assert.equal(unboundResult.outcome, 'fail_closed');
399
434
  assert.equal(unboundResult.message, undefined);
400
435
  assert.equal((await queueStatus(root, queue)).waiting, 0);
401
436
 
402
- console.log(JSON.stringify({ status: 'ok', assertions: ['standing project authorization reaches task contract', 'structured gate context', 'B-01 waiting to zero', 'project-isolated supersede', 'doctor strong validation', 'authoritative ledger drift', 'ready milestone deferred gate', 'future gate does not stop safe actionable backlog', 'conditional policy prose does not create a gate', 'authorized and consumed authority do not create gates', 'checkpoint-bound subproject backlog remains actionable', 'missing current authority creates a gate', 'standing-authorized production blocker does not create a gate', 'missing publication blocker creates a gate', 'accepted project optional deferred gate stays out of queue', 'unbound gate fails closed without actionable text'] }));
437
+ console.log(JSON.stringify({ status: 'ok', assertions: ['standing project authorization reaches task contract', 'structured gate context', 'B-01 waiting to zero', 'task-scoped gate survives project reconciliation', 'project-isolated supersede', 'doctor strong validation', 'authoritative ledger drift', 'ready milestone deferred gate', 'future gate does not stop safe actionable backlog', 'conditional policy prose does not create a gate', 'authorized and consumed authority do not create gates', 'checkpoint-bound subproject backlog remains actionable', 'missing current authority creates a gate', 'standing-authorized production blocker does not create a gate', 'missing publication blocker creates a gate', 'accepted project optional deferred gate stays out of queue', 'unbound gate fails closed without actionable text'] }));
@@ -52,6 +52,10 @@ node bin/loop-engineering.mjs --help
52
52
 
53
53
  Do not guess a workspace source path. Use `node packages/loop-engineering/bin/loop-engineering.mjs ...` only after confirming that exact path exists in the current workspace.
54
54
 
55
+ ### Verify the effective implementation
56
+
57
+ A skill update does not upgrade the CLI or generated integration. Before relying on scope inference, task-gate reconciliation or isolated verification, inspect the installed package and wrapper imports against the exact implementation that provides the feature. A candidate may share a version label with an older published package. Keep PR source, merged source, published packages, installed CLI and live integration as separate states; do not infer deployment from a green CI run.
58
+
55
59
  ### OpenClaw Integration
56
60
 
57
61
  Installing the npm package exposes the CLI, but it does not automatically route conversations, select a worker agent, or create queue wrappers. First generate a read-only installation plan:
@@ -90,6 +94,12 @@ loop-engineering-openclaw-smoke \
90
94
 
91
95
  If the CLI or integration is missing and the user requested installation or repair, install it within the authorized host/workspace scope, then run doctor and the disposable smoke. If the user only asked what is missing, report the exact package, repository, commands, and current deployment state without mutating the system.
92
96
 
97
+ ### Multi-IM Diagnostic Acceptance
98
+
99
+ Before OpenClaw doctor/smoke, follow [the multi-IM diagnostic procedure](references/openclaw-diagnostics.md): select the correct CLI/profile, check installed capabilities, and discover actual channels/accounts rather than assuming Feishu. Doctor probes all matching accounts; smoke exercises one selected source per run. For multi-channel acceptance, explicitly test each required channel/account pair and record the coverage.
100
+
101
+ Notification probes are dry-run only, not evidence of real delivery or authenticated inbound approval support. Smoke still executes a real worker in a disposable queue. Updating this skill alone does not upgrade the installed CLI; the discovery/selection behavior requires package version 0.16.2 or newer; 0.16.1 does not include it.
102
+
93
103
  ### Hermes Agent Integration
94
104
 
95
105
  The core CLI is platform-neutral, but Hermes conversation routing requires its own dispatcher and notifier. Generate a plan and verify its installation confirmation summary identifies Hermes, the absolute Hermes CLI path, intended workspace and queue, systemd scheduler, source-bound notification routing, and `writes enabled: no (plan only)`. If any field identifies the wrong platform or destination, stop. Confirm installation only after that review, then run the read-only doctor and disposable smoke:
@@ -160,7 +170,7 @@ For OpenClaw workers, follow `references/context-budget.md` before long-running
160
170
 
161
171
  ## Task vs Project Classification
162
172
 
163
- Classify scope before enqueueing.
173
+ Classify scope before enqueueing. For scope inference, task-level gate reconciliation and effective acceptance reviews, follow [scope and task acceptance](references/scope-task-acceptance.md). Verify the generated contract against the original request; inference is heuristic, not authority.
164
174
 
165
175
  ### Scoped task
166
176
 
@@ -295,6 +305,10 @@ Default revision policy may stop after three rounds, two repeated goal signature
295
305
 
296
306
  For L2 code-changing tasks, prefer isolated worktrees. The runner prepares reviewable local changes and verification evidence; it does not implicitly commit, push, publish, deploy, merge, or delete branches.
297
307
 
308
+ Before enabling or diagnosing this backend, follow [frozen-input verification](references/frozen-input-verification.md) for prerequisites, receipt checks and compatibility boundaries.
309
+
310
+ For Linux code queues whose verification must not read the shared project tree, use the opt-in `worktree.isolatedVerification` backend described in [isolated verification](../../docs/isolated-verification.md). Declare the exact project inputs and any user-local runtime files before running the gate. Frozen project files preserve permission bits, which are included in input identity; mode-only changes invalidate stability. Failed undeclared file accesses remain failures from nested working directories even if the command swallows the error. Treat missing/failed receipts, undeclared reads, changed input digests between commands, or unsupported host isolation as `verify_failed`; a zero command exit alone is not acceptance evidence. This generic backend does not cover browser profiles, Docker/Git replay, networked checks, or undeclared dynamic dependencies. Keep those on a separately reviewed project-specific gate until explicitly enrolled and proven; do not silently fall back to ordinary `verifyCommands`.
311
+
298
312
  Safe review flow:
299
313
 
300
314
  ```bash
@@ -0,0 +1,40 @@
1
+ # Frozen-input verification
2
+
3
+ ## Configure and prove prerequisites
4
+
5
+ Use this opt-in backend only on Linux with `python3`, `bwrap`, and `strace` supporting `--decode-pids=pidns`. Missing capabilities fail closed; never silently substitute ordinary verification.
6
+
7
+ Configure `worktree.isolatedVerification` beside `worktree.verifyCommands`:
8
+
9
+ ```json
10
+ {
11
+ "worktree": {
12
+ "enabled": true,
13
+ "verifyCommands": ["python3 -m unittest discover -s tests"],
14
+ "isolatedVerification": {
15
+ "inputs": ["src", "tests", "pyproject.toml"],
16
+ "runtimeFiles": []
17
+ }
18
+ }
19
+ }
20
+ ```
21
+
22
+ Declare exact project files or recursive directories. Missing inputs, symlinks and special files fail closed; exclude generated outputs. Required user-local runtime files must be exact regular files under `/home` or `/opt`. Do not weaken the allowlist to admit a temporary runtime under `/tmp`.
23
+
24
+ Project inputs are frozen read-only at `/work`; `/out` is persistent writable output. Network and inherited home/proxy/Node options are unavailable. Input identity covers content, size and permissions, including executable bits. Require stable source, snapshot and tool identities and the same input digest across commands.
25
+
26
+ ## Inspect receipts, not only command exit
27
+
28
+ Inspect each host-owned trace and `terminal.json`, command and supervisor exits, declared reads, input stability and process-group cleanup. Missing, malformed, stale or failed receipts mean `verify_failed` even if the command swallowed an error or exited zero. A sandbox receipt, checkpoint acceptance and final task judgement are separate evidence levels.
29
+
30
+ Before making this backend mandatory, prove the project's real command and dependencies with declared-input positive controls and existing-undeclared-input negative controls. Browser profiles, directory toolchains, Docker/Git replay and networked checks need a separately reviewed project-specific gate.
31
+
32
+ ## Path-audit boundaries
33
+
34
+ - Pair existing undeclared files with genuinely absent optional files. Optional absence may pass; swallowing an existing undeclared access must not. Include failed stat/access/exec prechecks, not only opens.
35
+ - Track nested cwd, chdir/fchdir, child inheritance and directory descriptors. PID-namespace decoding is required to associate child traces correctly. Include C-escaped non-ASCII, quotes and backslashes; unresolved or truncated paths fail closed.
36
+ - Preserve raw components. Missing/non-directory ancestors before `..` and trailing slashes retain traversal semantics. Repeated slashes and re-entry into `/work` must not bypass auditing.
37
+ - Distinguish explicit sandbox mount roots from unknown internal symlinks: a host `/bin` symlink can be a directory at its read-only mount destination. Pair missing and existing undeclared probes across these roots.
38
+ - Resolve proven `/proc/self/cwd`, `/proc/thread-self/cwd` and self-root aliases using traced cwd or sandbox root, retaining raw suffixes. Unknown process/fd aliases, including `/dev/fd`, and unresolved internal symlink traversal remain conservative failures; legitimate optional accesses may be rejected.
39
+
40
+ This is bounded trace auditing, not unrestricted syscall/procfs emulation. A missed attempted-access audit is not by itself proof of hidden-content exposure. Run paired controls through the real sandbox and disposable queue; record isolation and final task verdicts independently. Keep local tests, exact-HEAD remote CI and live deployment claims separate.
@@ -1,7 +1,14 @@
1
1
  # npm Package
2
2
 
3
3
  Package name: `taskforce-loop-engineering`
4
- Version: `0.15.19`
4
+ Version source: the candidate checkout's `package.json`; do not infer the installed
5
+ or public-registry version from this skill. Check the actual installed package
6
+ and `npm view taskforce-loop-engineering version` separately.
7
+
8
+ The multi-IM OpenClaw diagnostic changes require `0.16.2` or newer;
9
+ the `0.16.1` package does not support them. A skill update alone does
10
+ not install these capabilities. See [OpenClaw multi-IM diagnostics](openclaw-diagnostics.md)
11
+ for capability checks, channel/account selection, and acceptance boundaries.
5
12
 
6
13
  Install from npm:
7
14
 
@@ -0,0 +1,93 @@
1
+ # OpenClaw Multi-IM Diagnostics
2
+
3
+ ## Compatibility and scope
4
+
5
+ This procedure requires package version 0.16.2 or newer; 0.16.1 does not
6
+ include these capabilities. Until a compatible release is installed, use a reviewed
7
+ source candidate for validation and report installed diagnostics as unchanged. Do not
8
+ pass new flags to an old binary or claim that updating the skill upgrades code.
9
+ This procedure applies to OpenClaw; it does not change Hermes diagnostics.
10
+
11
+ 1. Identify the installed package, managed workspace, worker and queue. Check
12
+ `loop-engineering-openclaw-doctor --help` and
13
+ `loop-engineering-openclaw-smoke --help` for all three source flags below.
14
+ Help alone is not acceptance: verify discovery and dry-run report results.
15
+ 2. Select the intended OpenClaw CLI/profile environment. `--root` selects a
16
+ workspace, not an OpenClaw profile. Both commands accept `--openclaw-bin`
17
+ for the selected executable; retain that profile's normal environment.
18
+ Inspect `openclaw channels list --json` using that same CLI/environment.
19
+ Doctor resolves executable aliases and requires the same executable as the
20
+ install manifest, plus unchanged manifest hashes for notifier/dispatcher.
21
+ A missing/incomplete manifest, different CLI, or caller drift fails
22
+ `diagnostic_runtime`: no notification probe or smoke worker runs. Choose
23
+ the installed CLI or repair the integration within the authorized scope;
24
+ `--openclaw-bin` does not rewrite installed callers.
25
+ Never print channel credentials to diagnose selection.
26
+ 3. Run doctor. Without source filters, it discovers channel/account pairs from
27
+ the inventory and dry-runs each through the installed notifier. Inspect
28
+ `notificationSources` and the per-account `notification_dry_run` checks.
29
+ A configured inventory is not proof of a connected channel.
30
+ 4. Run smoke only within the authorized worker-execution scope. It first
31
+ requires doctor to pass, then uses the first returned source for the isolated
32
+ task's routing and terminal notification dry-run. It executes a real worker,
33
+ so it is not merely a read-only notification probe and may consume model
34
+ resources. It removes its temporary queue/config/runtime unless
35
+ `--keep-artifacts` is requested; verify cleanup and required task artifacts.
36
+ 5. For acceptance across multiple IMs/accounts, repeat smoke with explicit
37
+ channel/account pairs. One default smoke does not cover every configured
38
+ route. Report tested pairs, failures, retained evidence and cleanup status.
39
+
40
+ ## Explicit selection
41
+
42
+ Both doctor and smoke accept:
43
+
44
+ - `--source-channel`: filter to an actual configured IM channel.
45
+ - `--source-account`: filter to an actual account ID. Pair with a channel to
46
+ avoid matching the same account name across different IMs.
47
+ - `--source-target`: override the synthetic dry-run destination when a plugin
48
+ requires a particular target format. This does not enable real sending or
49
+ change channel/account discovery.
50
+
51
+ For a configured Telegram account named `personal` (replace all placeholders
52
+ and select its actual profile environment first):
53
+
54
+ ```bash
55
+ loop-engineering-openclaw-doctor --root /path/to/workspace --queue agent-tasks --worker-agent main --source-channel telegram --source-account personal --source-target 1 --json
56
+ loop-engineering-openclaw-smoke --root /path/to/workspace --queue agent-tasks --worker-agent main --source-channel telegram --source-account personal --source-target 1 --json
57
+ ```
58
+
59
+ Targets are synthetic by default. Discovery failure, malformed/empty channel
60
+ inventory or unmatched filters must fail closed; never fall back to Feishu or
61
+ silently drop the account. Within the selected channels, malformed account
62
+ lists or non-string/blank account entries fail even alongside valid entries
63
+ and even when an account filter would exclude them. An explicit channel filter
64
+ excludes unrelated channels from validation. Empty account arrays are valid,
65
+ but fail selection if no matching accounts remain. Correct the profile or selection instead of editing
66
+ a temporary test script to hardcode another IM.
67
+
68
+ ## Evidence boundaries
69
+
70
+ Notification probes remain dry-run even with an explicit target. Passing them
71
+ proves only the tested routing/argument path, not real outbound delivery,
72
+ inbound reception, or trusted approval callback transport. Real end-to-end
73
+ messaging requires separate authorization and observed delivery/receipt.
74
+ Do not infer universal IM support from Feishu, Telegram and Slack mock tests;
75
+ other configured plugins need their own acceptance evidence. Keep diagnostic
76
+ coverage distinct from production notification and human-gate support.
77
+
78
+ ### Diagnostic invocation and environment isolation
79
+
80
+ After checking executable identity and managed caller hashes, doctor uses the
81
+ exact CLI invocation recorded by installation for version, agent, channel and
82
+ notification checks. PATH/symlink aliases remain accepted when they resolve to
83
+ the same executable, but their invocation names are not used to select a second
84
+ profile. To change the installed profile, explicitly repair the integration.
85
+ Equal realpaths alone do not establish profile equivalence for name-sensitive
86
+ wrappers.
87
+
88
+ Doctor notification probes and smoke subprocesses discard inherited
89
+ `LOOP_HUMAN_INPUT_SOURCE` and `LOOP_NOTIFICATION_SOURCE` before supplying their
90
+ own discovered/task source. Production human-gate source precedence is unchanged.
91
+ Regression checks compare reported channel/account/target against captured
92
+ message arguments (including `--dry-run`), with conflicting inherited sources,
93
+ multiple accounts, and invocation-name-sensitive wrappers.
@@ -0,0 +1,19 @@
1
+ # Scope and task acceptance
2
+
3
+ ## Classify the requested outcome
4
+
5
+ Read the original request and generated `task_contract.json` before dispatch. Explicit complete-project goals and affirmative bounded work are distinct. Negation applies to its object, not every later cue: neither/nor, not-only/but-also, double negatives and unrelated “without deploying” context must not silently expand or narrow scope.
6
+
7
+ For example, “Complete the project-level objective, not just the first bounded milestone” remains a project; “Without deploying anything implement a bounded milestone for the project-level objective” remains scoped work. Verify Chinese and English affirmative/negative controls and generated contracts in disposable queues after changes. The inference is not a complete natural-language parser; correct a mismatched contract before executing it.
8
+
9
+ ## Inspect effective reviews and gates
10
+
11
+ - Read checkpoint reviews, task gates and `final_judgement.json` together. Checkpoint sequence and creation time establish chronology; filename numbering and regenerated review timestamps do not. Missing or conflicting ordering must not erase a live blocker.
12
+ - For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews. Multiple planned milestones still require their effective reviews.
13
+ - A task terminal result is not project completion or deployment authorization. Inspect the original completion contract and project backlog independently.
14
+ - Reconcile a consumed gate only through the recorded same-task successor link, `revises_checkpoint_id`. A satisfied gate records the successor, not proof that the successor passed acceptance. Check the effective review and final queue state separately.
15
+ - Effective human/authority blockers and uncertain external outcomes remain `needs_human_input`, including after ordinary worker failure; do not turn them into development revisions or automatic retries. Resolved historical blockers do not permanently veto continuation.
16
+
17
+ ## Evidence boundaries
18
+
19
+ Inspect artifacts rather than dispatcher exit status. A checkpoint accepted by the worker is not the outer queue's final judgement; `ready_to_apply` is not applied. For multiple PRs, test each exact candidate and a correctly constructed combined tree separately. Local tests, exact-HEAD remote CI, package installation and live-instance acceptance are distinct claims.