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.
@@ -0,0 +1,114 @@
1
+ export const DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS = [
2
+ 'INSTALL_FAILED_USER_RESTRICTED',
3
+ 'device unauthorized',
4
+ 'unauthorized',
5
+ 'offline',
6
+ 'more than one device',
7
+ 'no devices/emulators found',
8
+ 'Permission denied',
9
+ 'Operation not permitted',
10
+ 'user restricted',
11
+ 'requires human',
12
+ 'needs human',
13
+ '需要人工',
14
+ '需要用户确认',
15
+ '等待人工',
16
+ '权限未开',
17
+ '用户取消',
18
+ '用户限制'
19
+ ];
20
+
21
+ export const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
22
+ { category: 'context_overflow', pattern: 'context_length_exceeded', nonZeroOnly: true },
23
+ { category: 'context_overflow', pattern: 'maximum context length', nonZeroOnly: true },
24
+ { category: 'context_overflow', pattern: 'prompt is too long', nonZeroOnly: true },
25
+ { category: 'incomplete_turn', pattern: '"kind": "incomplete_turn"' },
26
+ { category: 'incomplete_turn', pattern: '"livenessState": "abandoned"' },
27
+ // Free-text signatures can also appear in a successful task's own answer
28
+ // (for example a task that implements rate limiting). Only the structured
29
+ // runtime trailers above may override exitCode=0.
30
+ { category: 'incomplete_turn', pattern: 'stopped before confirming the turn was complete', nonZeroOnly: true },
31
+ // The OpenClaw embedded runner injects a recovery prompt when an assistant
32
+ // turn completes its tool calls without a user-visible answer. A dispatch
33
+ // that exits non-zero with this signature hit a session protocol failure,
34
+ // not a task defect: classify it as a recoverable incomplete turn so the
35
+ // runtime recovery path rotates the worker session and resumes.
36
+ { category: 'incomplete_turn', pattern: 'did not produce a user-visible answer', nonZeroOnly: true },
37
+ // OpenClaw closes websocket admission while the Gateway drains for a
38
+ // restart. A worker launched inside that short window receives HTTP 503
39
+ // before task execution begins. Exact non-zero admission/drain signatures
40
+ // are runtime interruptions, not development failures.
41
+ { category: 'gateway_restart', pattern: 'gateway websocket admission closed', nonZeroOnly: true },
42
+ { category: 'gateway_restart', pattern: 'gateway is draining for restart', nonZeroOnly: true },
43
+ { category: 'gateway_restart', pattern: 'unavailable during gateway restart', nonZeroOnly: true },
44
+ { category: 'compaction_timeout', pattern: 'compaction timed out', nonZeroOnly: true },
45
+ { category: 'compaction_timeout', pattern: 'transcript compaction failed', nonZeroOnly: true },
46
+ { category: 'transport_error', pattern: 'connection reset', nonZeroOnly: true },
47
+ { category: 'transport_error', pattern: 'socket hang up', nonZeroOnly: true },
48
+ { category: 'transport_error', pattern: 'network error', nonZeroOnly: true },
49
+ { category: 'rate_limit', pattern: 'rate limit', nonZeroOnly: true }
50
+ ];
51
+
52
+ export function dispatchFailureClassification(result, retry = {}) {
53
+ if (!result) {
54
+ return {
55
+ category: 'ok',
56
+ requiresHumanAction: false,
57
+ matchedPattern: null
58
+ };
59
+ }
60
+ // Some embedded runtimes exit their wrapper successfully after the model
61
+ // turn itself was abandoned. Inspect the structured trailer before trusting
62
+ // exitCode=0 or the queue may accept partial work and replay a stale gate.
63
+ const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`.toLowerCase();
64
+ const humanPatterns = retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS;
65
+ const humanMatch = result.exitCode !== 0 && humanPatterns.find(pattern => output.includes(pattern.toLowerCase()));
66
+ if (humanMatch) return { category: 'requires_human_action', requiresHumanAction: true, recoverableRuntime: false, matchedPattern: humanMatch };
67
+ const runtimePatterns = retry.recoverableRuntimePatterns ?? DEFAULT_RECOVERABLE_RUNTIME_PATTERNS;
68
+ const runtimeMatch = runtimePatterns.find((entry) => {
69
+ const pattern = typeof entry === 'string' ? entry : entry.pattern;
70
+ const nonZeroOnly = typeof entry === 'object' && entry !== null && entry.nonZeroOnly === true;
71
+ return (!nonZeroOnly || result.exitCode !== 0)
72
+ && output.includes(String(pattern ?? entry).toLowerCase());
73
+ });
74
+ if (runtimeMatch) {
75
+ return {
76
+ category: runtimeMatch.category ?? 'runtime_interruption',
77
+ requiresHumanAction: false,
78
+ recoverableRuntime: true,
79
+ matchedPattern: runtimeMatch.pattern ?? runtimeMatch
80
+ };
81
+ }
82
+ if (result.exitCode === 0) {
83
+ return {
84
+ category: 'ok',
85
+ requiresHumanAction: false,
86
+ matchedPattern: null
87
+ };
88
+ }
89
+ if (result.timedOut) {
90
+ return {
91
+ category: 'timeout',
92
+ requiresHumanAction: false,
93
+ recoverableRuntime: true,
94
+ matchedPattern: null
95
+ };
96
+ }
97
+ const patterns = retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS;
98
+ const matched = patterns.find((pattern) => output.includes(pattern.toLowerCase()));
99
+ if (matched) {
100
+ return {
101
+ category: 'requires_human_action',
102
+ requiresHumanAction: true,
103
+ recoverableRuntime: false,
104
+ matchedPattern: matched
105
+ };
106
+ }
107
+ return {
108
+ category: 'retryable_failure',
109
+ requiresHumanAction: false,
110
+ recoverableRuntime: false,
111
+ matchedPattern: null
112
+ };
113
+ }
114
+
@@ -0,0 +1,71 @@
1
+ import { access, readFile, realpath } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import path from 'node:path';
5
+
6
+ async function executableIdentity(command, root) {
7
+ if (typeof command !== 'string' || !command.trim()) throw new Error('Missing OpenClaw executable');
8
+ const candidates = command.includes(path.sep)
9
+ ? [path.resolve(root, command)]
10
+ : String(process.env.PATH || '').split(path.delimiter).map((dir) => path.resolve(root, dir, command));
11
+ for (const candidate of candidates) {
12
+ try { await access(candidate, constants.X_OK); return await realpath(candidate); } catch { /* try next PATH entry */ }
13
+ }
14
+ throw new Error('Cannot resolve OpenClaw executable');
15
+ }
16
+
17
+ // Bind discovery to the recorded installation and its unchanged generated callers.
18
+ export async function verifyDiagnosticRuntime(args) {
19
+ const manifest = JSON.parse(await readFile(path.join(args.root, 'runtime/loop-engineering-openclaw-install.json'), 'utf8'));
20
+ if (manifest.status !== 'installed') throw new Error('OpenClaw installation is incomplete');
21
+ const selected = await executableIdentity(args.openclawBin, args.root);
22
+ const installed = await executableIdentity(manifest.openclawBin, args.root);
23
+ if (selected !== installed) throw new Error('Diagnostic OpenClaw CLI differs from installed CLI; select the installed executable or explicitly repair the integration');
24
+ for (const file of ['scripts/loops/openclaw-loop-notify.mjs', 'scripts/loops/openclaw-loop-dispatch.mjs']) {
25
+ const entry = manifest.managedFiles?.find((item) => item.path === file);
26
+ const content = await readFile(path.join(args.root, file));
27
+ if (!entry?.sha256 || createHash('sha256').update(content).digest('hex') !== entry.sha256) {
28
+ throw new Error('Installed notifier/dispatcher differs from install manifest; repair the integration before diagnostics');
29
+ }
30
+ }
31
+ // Preserve the recorded invocation name: symlink names can select profiles.
32
+ return manifest.openclawBin;
33
+ }
34
+
35
+ // Discover through the selected CLI/profile; never read or print channel credentials.
36
+ export async function diagnosticSources(args, run) {
37
+ const result = await run(args.openclawBin, ['channels', 'list', '--json'], { cwd: args.root });
38
+ if (result.code !== 0) throw new Error('Cannot discover OpenClaw channels for this profile');
39
+ let chat;
40
+ try { chat = JSON.parse(result.stdout).chat; } catch { throw new Error('Invalid OpenClaw channels JSON'); }
41
+ if (!chat || typeof chat !== 'object' || Array.isArray(chat)) throw new Error('Missing OpenClaw chat channel inventory');
42
+ const sources = [];
43
+ for (const [channel, entry] of Object.entries(chat)) {
44
+ if (args.sourceChannel && channel !== args.sourceChannel) continue;
45
+ const accounts = Array.isArray(entry) ? entry : entry?.accounts;
46
+ if (!channel.trim() || !Array.isArray(accounts)) throw new Error('Malformed OpenClaw channel account list');
47
+ for (const account of accounts) {
48
+ if (typeof account !== 'string' || !account.trim()) throw new Error('Malformed OpenClaw account entry');
49
+ if (args.sourceAccount && account !== args.sourceAccount) continue;
50
+ sources.push({ channel, account, target: args.sourceTarget || diagnosticTarget(channel), reply_to: '1' });
51
+ }
52
+ }
53
+ if (!sources.length) throw new Error('No matching configured IM channel/account; check the selected OpenClaw profile or --source-channel/--source-account');
54
+ return sources;
55
+ }
56
+ function diagnosticTarget(channel) {
57
+ if (channel === 'telegram') return '1';
58
+ if (channel === 'discord') return 'channel:100000000000000001';
59
+ if (channel === 'slack') return 'channel:C00000000000';
60
+ if (channel === 'whatsapp' || channel === 'signal') return '+12025550100';
61
+ if (channel === 'feishu') return 'user:loop-diagnostic-dry-run';
62
+ return 'loop-diagnostic-dry-run';
63
+ }
64
+
65
+ // Diagnostic subprocesses must not inherit a stale higher-precedence route.
66
+ export function diagnosticEnvironment(env = process.env) {
67
+ const clean = { ...env };
68
+ delete clean.LOOP_HUMAN_INPUT_SOURCE;
69
+ delete clean.LOOP_NOTIFICATION_SOURCE;
70
+ return clean;
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-loop-engineering",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "private": false,
5
5
  "description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
6
6
  "type": "module",
@@ -26,11 +26,11 @@
26
26
  "demo:adapter": "node examples/adapter-sdk-demo.mjs",
27
27
  "check:production-trust": "node --check lib/runtime-adapter-v1.mjs && node --check lib/durable-journal.mjs && node --check lib/execution-ledger.mjs && node --check lib/production-evidence.mjs && node --check lib/upgrade-planner.mjs && node scripts/production-acceptance.mjs",
28
28
  "check:config-drift": "node scripts/distribution-skill-self-test.mjs && node --check scripts/config-drift-self-test.mjs && node scripts/config-drift-self-test.mjs",
29
- "check:openclaw-install": "node --check scripts/openclaw-install.mjs && node --check scripts/openclaw-doctor.mjs && node --check scripts/openclaw-smoke.mjs && node --check scripts/openclaw-manage.mjs && node scripts/openclaw-install-self-test.mjs",
29
+ "check:openclaw-install": "node --check scripts/openclaw-install.mjs && node --check scripts/openclaw-doctor.mjs && node --check scripts/openclaw-smoke.mjs && node --check scripts/openclaw-manage.mjs && node scripts/openclaw-install-self-test.mjs && node scripts/openclaw-diagnostic-source-self-test.mjs && DIAGNOSTIC_TEST_CHANNEL=telegram node scripts/openclaw-install-self-test.mjs && DIAGNOSTIC_TEST_CHANNEL=slack node scripts/openclaw-install-self-test.mjs",
30
30
  "check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node scripts/hermes-install-self-test.mjs",
31
31
  "check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
32
32
  "check:human-gates": "node --check lib/human-gate-command.mjs && node --check lib/human-gate-channel-adapter.mjs && node scripts/human-gate-command-self-test.mjs && node scripts/human-gate-final-judgement.mjs",
33
- "check": "npm run check:project-gates && node scripts/safety-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
33
+ "check": "node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
34
34
  "pack:dry": "npm pack --dry-run"
35
35
  },
36
36
  "exports": {
@@ -0,0 +1,249 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { contextPolicy, contextRotation, openClawContextUsage, readBoundedJson } from '../lib/context-budget.mjs';
7
+ import { dispatchFailureClassification, enqueueTask, runQueueOnce, queueCancel } from '../lib/core.mjs';
8
+
9
+ const policy = contextPolicy();
10
+ assert.equal(contextRotation(null, 2, policy).rotate, false);
11
+ assert.equal(contextRotation(null, 3, policy).reason, 'bounded_tick_limit');
12
+ for (const [usedTokens, reason] of [[59, null], [60, 'context_soft_limit'], [75, 'context_hard_limit'], [110, 'context_hard_limit']]) {
13
+ assert.equal(contextRotation({ usedTokens, windowTokens: 100 }, 1, policy).reason, reason);
14
+ }
15
+ assert.equal(contextRotation({ usedTokens: NaN, windowTokens: 100 }, 3, policy).reason, 'bounded_tick_limit');
16
+ assert.throws(() => contextPolicy({ contextBudget: { softRatio: 0.8, hardRatio: 0.7 } }));
17
+ assert.throws(() => contextPolicy({ sessionMaxTicks: 0 }));
18
+ assert.equal(openClawContextUsage({ result: { meta: { agentMeta: { contextTokens: 100, usage: { input: 90 } } } } }), null, 'aggregate usage is not context occupancy');
19
+ const usage = openClawContextUsage({ result: { meta: { agentMeta: { contextTokens: 100, lastCallUsage: { input: 20, cacheRead: 40, cacheWrite: 15 } } } } });
20
+ assert.equal(usage.usedTokens, 60, 'cache reads count once; writes are not added again');
21
+ assert.equal(dispatchFailureClassification({ exitCode: 0, stdout: 'Implemented context_length_exceeded handling' }).category, 'ok');
22
+ assert.equal(dispatchFailureClassification({ exitCode: 1, stderr: 'context_length_exceeded' }).category, 'context_overflow');
23
+ assert.equal(dispatchFailureClassification({ exitCode: 1, stderr: 'Permission denied; context_length_exceeded' }).requiresHumanAction, true);
24
+
25
+ const roots = [];
26
+ try {
27
+ for (const scenario of ['yield', 'stale', 'malformed', 'missing-checkpoint', 'checkpoint-gate', 'pending-action', 'overflow', 'human-error', 'oversized', 'project-soft', 'project-hard', 'project-no-usage', 'terminal', 'pending-action-overflow', 'checkpoint-gate-overflow', 'stale-overflow', 'malformed-overflow', 'yield-overflow', 'yield-human-error', 'pending-action-failure']) {
28
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-context-'));
29
+ roots.push(root);
30
+ const worker = path.join(root, 'worker.mjs');
31
+ await writeFile(worker, `import { mkdir, readFile, writeFile } from 'node:fs/promises';
32
+ import path from 'node:path';
33
+ const e = process.env;
34
+ const original = ${JSON.stringify(scenario)};
35
+ const scenario = original.replace(/-(overflow|human-error|failure)$/, '');
36
+ if (scenario === 'overflow' || scenario === 'human-error') {
37
+ console.error(scenario === 'human-error' ? 'Permission denied; context_length_exceeded' : 'context_length_exceeded');
38
+ process.exit(1);
39
+ }
40
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
41
+ const checkpoint = path.join(e.LOOP_CHECKPOINTS_DIR, e.LOOP_RUN_ID + '.json');
42
+ if (scenario.startsWith('project-') || scenario === 'terminal') {
43
+ const plan = JSON.parse(await readFile(e.LOOP_DEV_PLAN_FILE, 'utf8'));
44
+ for (const cp of plan.checkpoints) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, cp.id + '.json'), JSON.stringify({ version: 1, task_id: e.LOOP_TASK_ID, checkpoint_id: cp.id, status: 'ready_for_acceptance', summary: 'Read-only inspection verified', files_changed: [], verification: [{ command: 'read-only inspection', outcome: 'passed' }], blockers: [], risks: [], next_action: 'continue local inspection', ...(scenario === 'terminal' ? {} : { project_completion: { status: 'in_progress' } }) }));
45
+ if (scenario !== 'project-no-usage') await writeFile(e.LOOP_CONTEXT_USAGE_FILE, JSON.stringify({ version: 1, taskId: e.LOOP_TASK_ID, runId: e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), usage: { usedTokens: scenario === 'project-soft' ? 60 : 80, windowTokens: 100 } }));
46
+ process.exit(0);
47
+ }
48
+
49
+ if (scenario !== 'missing-checkpoint') await writeFile(checkpoint, JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: e.LOOP_RUN_ID, status: scenario === 'checkpoint-gate' ? 'needs_human_input' : 'in_progress', summary: 'bounded progress', blockers: scenario === 'checkpoint-gate' ? ['Need approval'] : [], verification: [], risks: [], next_action: 'continue' }));
50
+ const handoff = { version: 1, taskId: e.LOOP_TASK_ID, runId: scenario === 'stale' ? 'old-run' : e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), reason: 'context_budget', checkpoint, summary: 'progress', completed: ['read source'], remaining: ['verify changes'], evidence: [checkpoint], nextAction: 'inspect test', authority: 'local only', pendingActions: scenario === 'pending-action' ? ['unknown payment outcome'] : [], blockers: [] };
51
+ await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, scenario === 'malformed' ? '{' : scenario === 'oversized' ? ' '.repeat(17000) : JSON.stringify(handoff));
52
+ if (original !== scenario) { console.error(original.endsWith('-human-error') ? 'Permission denied; context_length_exceeded' : original.endsWith('-failure') ? 'generic failure' : 'context_length_exceeded'); process.exitCode = 1; }
53
+ `);
54
+ await enqueueTask(root, { queue: 'test', title: scenario, task: 'Inspect a local file, then continue verification.' });
55
+ const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3, runtimeRecoveryMaxAttempts: 2 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
56
+ const first = await runQueueOnce(root, options);
57
+ assert.equal(first.run.dispatchAttempts.length, 1, 'context failures must not retry the old session');
58
+ if (scenario.startsWith('project-')) {
59
+ assert.equal(first.status, 'project_in_progress', JSON.stringify(first.run.finalJudgement));
60
+ const task = JSON.parse(await readFile(path.join(root, first.taskPath), 'utf8'));
61
+ if (scenario === 'project-no-usage') {
62
+ assert.equal(task.runtimeSessionGeneration ?? 0, 0);
63
+ await runQueueOnce(root, options);
64
+ const third = await runQueueOnce(root, options);
65
+ const rotated = JSON.parse(await readFile(path.join(root, third.taskPath), 'utf8'));
66
+ assert.equal(rotated.runtimeSessionGeneration, 1);
67
+ assert.equal(rotated.sessionRotationReason, 'bounded_tick_limit');
68
+ } else {
69
+ assert.equal(task.runtimeSessionGeneration, 1);
70
+ assert.equal(task.sessionRotationReason, scenario === 'project-soft' ? 'context_soft_limit' : 'context_hard_limit');
71
+ }
72
+ } else if (scenario === 'terminal') {
73
+ assert.equal(first.status, 'completed');
74
+ assert.equal((await runQueueOnce(root, options)).processed, false, 'high token usage cannot replay completed work');
75
+ } else if (['yield', 'overflow', 'yield-overflow'].includes(scenario)) {
76
+ assert.equal(first.status, 'runtime_interrupted', scenario);
77
+ const task = JSON.parse(await readFile(path.join(root, first.taskPath), 'utf8'));
78
+ assert.equal(task.runtimeSessionGeneration, 1);
79
+ assert.equal(task.sessionTickCount, 0);
80
+ if (scenario === 'yield') assert.ok(task.contextHandoffFile);
81
+ const second = await runQueueOnce(root, options);
82
+ assert.equal(second.status, 'runtime_interrupted');
83
+ const third = await runQueueOnce(root, options);
84
+ assert.equal(third.status, 'runtime_blocked', 'recovery is bounded');
85
+ } else if (['pending-action', 'checkpoint-gate', 'human-error', 'pending-action-overflow', 'checkpoint-gate-overflow', 'yield-human-error', 'pending-action-failure'].includes(scenario)) {
86
+ assert.equal(first.status, 'needs_human_input', scenario);
87
+ assert.equal((await runQueueOnce(root, options)).processed, false, 'blocked work cannot auto-replay');
88
+ } else assert.equal(first.status, 'runtime_blocked', scenario);
89
+ if (scenario !== 'terminal') assert.notEqual(first.status, 'completed');
90
+ if (scenario === 'oversized') assert.equal(await readBoundedJson(path.join(root, 'nonexistent')), null);
91
+ }
92
+ // A durable blocker must survive the window before handoff creation.
93
+ for (const chronology of ['single', 'arbitrary-id', 'id-restart', 'missing', 'conflict', 'terminal']) {
94
+ for (const failure of ['overflow', 'abandoned', 'exhausted', 'ordinary', 'ordinary-single']) {
95
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-context-no-handoff-'));
96
+ roots.push(root);
97
+ const worker = path.join(root, 'worker.mjs');
98
+ await writeFile(worker, `import { mkdir, readFile, writeFile } from 'node:fs/promises';
99
+ import path from 'node:path';
100
+ const e = process.env;
101
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
102
+ const plan = JSON.parse(await readFile(e.LOOP_DEV_PLAN_FILE, 'utf8'));
103
+ const chronology = ${JSON.stringify(chronology)};
104
+ const oldId = chronology === 'id-restart' ? 'cp99' : 'cp1';
105
+ const newId = chronology === 'id-restart' ? 'cp1' : 'progress-latest';
106
+ if (chronology !== 'single') await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, oldId + '.json'), JSON.stringify({ task_id: e.LOOP_TASK_ID, checkpoint_id: oldId, sequence: chronology === 'missing' ? undefined : chronology === 'conflict' ? 3 : 1, created_at: chronology === 'missing' ? undefined : '2026-10-23T00:00:00Z', status: chronology === 'terminal' ? 'ready_for_acceptance' : 'in_progress', project_completion: chronology === 'terminal' ? { status: 'complete' } : undefined, summary: 'Old progress', blockers: [], risks: [], verification: chronology === 'terminal' ? [{ command: 'mock check', outcome: 'passed' }] : [] }));
107
+ for (const cp of plan.checkpoints) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, (chronology === 'single' ? cp.id : newId) + '.json'), JSON.stringify({ version: 1, task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: chronology === 'single' ? cp.id : newId, sequence: chronology === 'missing' ? undefined : 2, created_at: chronology === 'missing' ? undefined : '2026-10-23T00:01:00Z', project_completion: chronology === 'terminal' ? { status: 'needs_human_acceptance' } : undefined, status: 'needs_human_input', summary: 'External outcome unknown', files_changed: [], verification: [], blockers: ['Payment outcome unknown; reconcile before replay'], risks: [], next_action: 'Wait for human confirmation' }));
108
+ console.error(${JSON.stringify(failure === 'abandoned' ? '"kind": "incomplete_turn"' : failure.startsWith('ordinary') ? 'generic worker failure' : 'context_length_exceeded')});
109
+ process.exitCode = ${failure === 'abandoned' ? 0 : 1};`);
110
+ await enqueueTask(root, { queue: 'test', title: 'blocker before handoff', task: 'Inspect local mocked data' });
111
+ const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: failure === 'ordinary-single' ? 1 : 3, runtimeRecoveryMaxAttempts: failure === 'exhausted' ? 0 : 2 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
112
+ const result = await runQueueOnce(root, options);
113
+ assert.equal(result.run.acceptanceReviews.blocked, 1);
114
+ assert.equal(result.run.finalJudgement.outcome, 'blocked');
115
+ assert.equal(result.status, 'needs_human_input', failure);
116
+ assert.equal(result.run.revisionRequest, null, 'human blockers must not create development revisions');
117
+ assert.equal(result.run.dispatchAttempts.length, 1);
118
+ const task = JSON.parse(await readFile(path.join(root, result.taskPath), 'utf8'));
119
+ assert.equal(task.runtimeSessionGeneration ?? 0, 0, 'blocked work must not rotate');
120
+ assert.equal(task.runtimeRecoveryCount ?? 0, 0, 'blocked work must not consume recovery');
121
+ assert.equal((await runQueueOnce(root, options)).processed, false, 'no replay without a handoff either');
122
+ }
123
+ }
124
+ // After one legitimate recovery, newly durable blockers stop the next run.
125
+ for (const failure of ['ordinary', 'overflow']) {
126
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-recovered-blocker-'));
127
+ roots.push(root);
128
+ const worker = path.join(root, 'worker.mjs');
129
+ await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
130
+ import path from 'node:path';
131
+ const e = process.env;
132
+ if (Number(e.LOOP_SESSION_GENERATION) > 0) {
133
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
134
+ for (const [id, sequence, blockers] of [['cp99', 1, []], ['progress-latest', 2, ['Unknown payment outcome']]]) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, id + '.json'), JSON.stringify({task_id:e.LOOP_TASK_ID, checkpoint_id:id, sequence, status:blockers.length ? 'needs_human_input' : 'in_progress', blockers, risks:[], verification:[]}));
135
+ }
136
+ console.error(Number(e.LOOP_SESSION_GENERATION) > 0 && ${JSON.stringify(failure)} === 'ordinary' ? 'generic failure' : 'context_length_exceeded');
137
+ process.exitCode = 1;`);
138
+ await enqueueTask(root, { queue: 'test', title: 'recovered blocker', task: 'Inspect mocked local data' });
139
+ const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
140
+ assert.equal((await runQueueOnce(root, options)).status, 'runtime_interrupted');
141
+ const result = await runQueueOnce(root, options);
142
+ assert.equal(result.status, 'needs_human_input');
143
+ assert.equal(result.run.dispatchAttempts.length, 1);
144
+ assert.equal(result.run.revisionRequest, null);
145
+ const task = JSON.parse(await readFile(path.join(root, result.taskPath), 'utf8'));
146
+ assert.equal(task.runtimeSessionGeneration, 1);
147
+ assert.equal(task.runtimeRecoveryCount, 1);
148
+ assert.equal((await runQueueOnce(root, options)).processed, false);
149
+ }
150
+ // Cancellation takes precedence even with a blocker and invalid handoff.
151
+ {
152
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-cancel-blocker-'));
153
+ roots.push(root);
154
+ const worker = path.join(root, 'worker.mjs');
155
+ const marker = path.join(root, 'ready');
156
+ await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
157
+ import path from 'node:path';
158
+ const e = process.env;
159
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, {recursive:true});
160
+ await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, 'pending.json'), JSON.stringify({ task_id:e.LOOP_TASK_ID, checkpoint_id:'pending', status:'needs_human_input', blockers:['Unknown outcome'] }));
161
+ await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, '{}');
162
+ await writeFile(${JSON.stringify(marker)}, 'ready');
163
+ setInterval(() => {}, 1000);`);
164
+ const queued = await enqueueTask(root, { queue: 'test', title: 'cancel blocker', task: 'Inspect mocked local data' });
165
+ const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, timeoutMs: 5000, checkpointPollMs: 0, progressHeartbeatMs: 0 };
166
+ const running = runQueueOnce(root, options);
167
+ let ready = false;
168
+ for (let i = 0; i < 200 && !ready; i++) {
169
+ ready = await readFile(marker, 'utf8').then(() => true, () => false);
170
+ if (!ready) await new Promise(resolve => setTimeout(resolve, 10));
171
+ }
172
+ assert.equal(ready, true);
173
+ await queueCancel(root, 'test', queued.task.id, { includeActive: true, reason: 'cancel regression' });
174
+ const result = await running;
175
+ assert.equal(result.status, 'superseded');
176
+ assert.equal(result.run.dispatchAttempts.length, 1);
177
+ assert.equal(result.run.revisionRequest, null);
178
+ assert.equal((await runQueueOnce(root, options)).processed, false);
179
+ }
180
+ // Ordinary failures still retry without blockers, or after a later snapshot
181
+ // resolves a historical blocker. Test through the real dispatch loop.
182
+ for (const scenario of ['absent', 'resolved']) {
183
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-retry-control-'));
184
+ roots.push(root);
185
+ const worker = path.join(root, 'worker.mjs');
186
+ await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
187
+ import path from 'node:path';
188
+ const e = process.env;
189
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
190
+ if (${JSON.stringify(scenario)} === 'resolved') {
191
+ for (const [id, blockers] of [['cp1', ['Await approval']], ['cp2', []]]) {
192
+ await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, id + '.json'), JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: id, sequence: id === 'cp1' ? 1 : 2, status: blockers.length ? 'needs_human_input' : 'in_progress', summary: 'Local progress', blockers, verification: [], risks: [], next_action: 'Continue local verification' }));
193
+ }
194
+ }
195
+ console.error('generic worker failure');
196
+ process.exitCode = 1;`);
197
+ await enqueueTask(root, { queue: 'test', title: scenario, task: 'Inspect local mocked data' });
198
+ const result = await runQueueOnce(root, { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 });
199
+ assert.equal(result.run.dispatchAttempts.length, 3, scenario);
200
+ assert.equal(result.status, 'failed', scenario);
201
+ assert.equal(result.run.finalJudgement.outcome, 'needs_revision', scenario);
202
+ }
203
+ // Exercise the real output observer in a subprocess: no unbounded parse
204
+ // buffer, byte-for-byte full logs, bound usage report and clipped runner tail.
205
+ for (const scenario of ['json', 'oversized-output']) {
206
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-context-output-'));
207
+ roots.push(root);
208
+ const observer = path.join(root, 'observer.mjs');
209
+ const output = scenario === 'json' ? JSON.stringify({ result: { meta: { agentMeta: { contextTokens: 100, lastCallUsage: { input: 20, cacheRead: 40 } } } } }) : 'x'.repeat(2 * 1024 * 1024 + 1);
210
+ const outputFile = path.join(root, 'output.txt');
211
+ await writeFile(outputFile, output);
212
+ await writeFile(observer, `import { spawn } from 'node:child_process';
213
+ import { observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
214
+ const child = spawn(process.execPath, ['-e', 'process.stdout.write(require("node:fs").readFileSync(process.argv[1]))', ${JSON.stringify(outputFile)}], { stdio: ['ignore', 'pipe', 'pipe'] });
215
+ process.exitCode = await observeOpenClawWorker(child);`);
216
+ const usageFile = path.join(root, 'usage.json');
217
+ const result = spawnSync(process.execPath, [observer], { encoding: 'utf8', env: { ...process.env, LOOP_CONTEXT_USAGE_FILE: usageFile, LOOP_WORKER_OUTPUT_PREFIX: path.join(root, 'worker'), LOOP_TASK_ID: 't', LOOP_RUN_ID: 'r', LOOP_SESSION_GENERATION: '2', LOOP_ATTEMPT: '1' } });
218
+ assert.equal(result.status, 0, result.stderr);
219
+ assert.equal(await readFile(path.join(root, 'worker.stdout.log'), 'utf8'), output);
220
+ assert.ok(Buffer.byteLength(result.stdout) <= 16384);
221
+ const report = JSON.parse(await readFile(usageFile, 'utf8'));
222
+ assert.equal(report.generation, 2);
223
+ assert.equal(report.attempt, 1);
224
+ assert.equal(report.usage?.usedTokens ?? null, scenario === 'json' ? 60 : null);
225
+ }
226
+ // Real observer + real queue: early human signals cannot be lost to tail
227
+ // clipping, even across chunks/UTF-8 boundaries or with custom retry policy.
228
+ for (const [signal, channel, retry] of [
229
+ ['Permission denied', 'stderr', {}],
230
+ ['需要用户确认', 'stdout', {}],
231
+ ['CUSTOM_APPROVAL', 'stderr', { requiresHumanActionPatterns: ['CUSTOM_APPROVAL'] }],
232
+ ['context_length_exceeded', 'stderr', {}]
233
+ ]) {
234
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-context-signals-'));
235
+ roots.push(root);
236
+ const worker = path.join(root, 'worker.mjs');
237
+ await writeFile(worker, `import { spawn } from 'node:child_process';
238
+ import { observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
239
+ const child = spawn(process.execPath, ['-e', ${JSON.stringify(`const bytes = Buffer.from(${JSON.stringify(signal)}); (async () => { for (const byte of bytes) { process.${channel}.write(Buffer.from([byte])); await new Promise(r => setTimeout(r, 2)); } process.${channel}.write('x'.repeat(100000)); process.stderr.write('context_length_exceeded'); process.exitCode = 1; })();`)}], { stdio: ['ignore', 'pipe', 'pipe'] });
240
+ process.exitCode = await observeOpenClawWorker(child);`);
241
+ await enqueueTask(root, { queue: 'test', title: 'signal preservation', task: 'Inspect local source' });
242
+ const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3, ...retry }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
243
+ const result = await runQueueOnce(root, options);
244
+ assert.equal(result.status, signal === 'context_length_exceeded' ? 'runtime_interrupted' : 'needs_human_input');
245
+ assert.equal(result.run.dispatchAttempts.length, 1);
246
+ if (signal !== 'context_length_exceeded') assert.equal((await runQueueOnce(root, options)).processed, false);
247
+ }
248
+ console.log('Context budget: thresholds, telemetry, handoff binding, gates, overflow and bounded recovery passed.');
249
+ } finally { await Promise.all(roots.map(root => rm(root, { recursive: true, force: true }))); }
@@ -239,11 +239,11 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
239
239
  const devPlan = { checkpoints: [{ id: 'cp1' }] };
240
240
  const reviews = {
241
241
  reviews: [
242
- { checkpointId: 'cp5', milestoneId: 'G-01-retry', sequence: 5, createdAt: '2026-08-07T04:00:00.000Z', status: 'accepted' },
243
- { checkpointId: 'cp14', milestoneId: 'G-01-auth', sequence: 3, createdAt: '2026-08-07T12:00:00.000Z', status: 'blocked' }
242
+ { checkpointId: 'cp5', milestoneId: 'G-01-retry', sequence: 5, checkpointCreatedAt: '2026-08-07T04:00:00.000Z', status: 'accepted' },
243
+ { checkpointId: 'cp14', milestoneId: 'G-01-auth', sequence: 3, checkpointCreatedAt: '2026-08-07T12:00:00.000Z', status: 'blocked' }
244
244
  ]
245
245
  };
246
- assert.equal(selectEffectiveAcceptanceReviews(devPlan, reviews)[0].checkpointId, 'cp14');
246
+ assert.equal(selectEffectiveAcceptanceReviews(devPlan, reviews).some(review => review.checkpointId === 'cp14'), true, 'conflicting clocks retain the blocker');
247
247
  }
248
248
 
249
249
  {
@@ -344,7 +344,7 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
344
344
  projectCompletion: { status: 'complete' }, checkpointRisks: []
345
345
  },
346
346
  {
347
- checkpointId: 'cp21', sequence: 21, status: 'blocked',
347
+ checkpointId: 'cp21', sequence: 21, status: 'accepted',
348
348
  projectCompletion: { status: 'needs_human_acceptance' },
349
349
  checkpointNextAction: 'owner accepts broader OpenReel v4 project'
350
350
  }
@@ -359,4 +359,92 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
359
359
  assert.equal(judgement.requires_human_gate, false);
360
360
  }
361
361
 
362
+
363
+ // Recovery uses effective blockers, never a resolved historical checkpoint.
364
+ for (const dispatchStatus of ['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed']) {
365
+ const unblockedOutcome = ['failed', 'verify_failed'].includes(dispatchStatus) ? 'needs_revision' : dispatchStatus;
366
+ const judge = reviews => buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'cp1' }] }, { count: reviews.length }, { reviews }, { dispatchStatus });
367
+ assert.equal(judge([{ checkpointId: 'cp1', status: 'blocked' }]).outcome, 'blocked');
368
+ assert.equal(judge([{ checkpointId: 'cp1', sequence: 1, status: 'blocked' }, { checkpointId: 'cp2', sequence: 2, status: 'accepted' }]).outcome, unblockedOutcome);
369
+ assert.equal(judge([]).outcome, unblockedOutcome);
370
+ }
371
+
362
372
  console.log('final judgement self-test passed');
373
+
374
+ // IDs carry no ordering authority; exercise both input orders and all scopes.
375
+ for (const checkpoints of [[{ id: 'm' }], [{ id: 'm' }, { id: 'other' }]]) {
376
+ const select = reviews => selectEffectiveAcceptanceReviews({ checkpoints }, { reviews });
377
+ for (const [oldId, newId] of [['cp1', 'progress-latest'], ['cp99', 'cp1'], ['alpha', 'omega']]) {
378
+ for (const clocks of [
379
+ [{ sequence: 1 }, { sequence: 2 }],
380
+ [{ checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { checkpointCreatedAt: '2026-10-23T00:01:00Z' }]
381
+ ]) {
382
+ for (const resolved of [false, true]) {
383
+ const pair = [
384
+ { checkpointId: oldId, milestoneId: 'm', ...clocks[0], status: resolved ? 'blocked' : 'accepted' },
385
+ { checkpointId: newId, milestoneId: 'm', ...clocks[1], status: resolved ? 'accepted' : 'blocked' }
386
+ ];
387
+ for (const input of [pair, [...pair].reverse()]) assert.deepEqual(select(input).map(r => r.checkpointId), [newId]);
388
+ }
389
+ }
390
+ }
391
+ for (const clocks of [
392
+ [{}, {}], [{ checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { checkpointCreatedAt: '' }], [{ sequence: 1 }, {}], [{ sequence: 1 }, { sequence: 1 }],
393
+ [{ sequence: '2', checkpointCreatedAt: 'invalid' }, { sequence: null }],
394
+ [{ sequence: 2, checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { sequence: 1, checkpointCreatedAt: '2026-10-23T00:01:00Z' }]
395
+ ]) {
396
+ const pair = [
397
+ { checkpointId: 'unknown', milestoneId: 'm', ...clocks[0], status: 'blocked' },
398
+ { checkpointId: 'cp999', milestoneId: 'm', ...clocks[1], status: 'accepted' }
399
+ ];
400
+ for (const input of [pair, [...pair].reverse()]) assert.equal(select(input).some(r => r.status === 'blocked'), true);
401
+ }
402
+ }
403
+ {
404
+ const terminal = { checkpointId: 'done', status: 'accepted', taskTerminal: true };
405
+ const blocker = { checkpointId: 'pending', status: 'blocked' };
406
+ assert.equal(selectEffectiveAcceptanceReviews({}, { reviews: [terminal, blocker] }).some(r => r.status === 'blocked'), true);
407
+ const judgement = buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'm' }, { id: 'missing' }] }, { count: 2 }, { reviews: [
408
+ { checkpointId: 'a', milestoneId: 'm', status: 'accepted' },
409
+ { checkpointId: 'b', milestoneId: 'm', status: 'accepted' }
410
+ ] }, { dispatchStatus: 'completed' });
411
+ assert.equal(judgement.outcome, 'needs_revision', 'ambiguous snapshots cannot count as multiple milestones');
412
+ }
413
+
414
+ {
415
+ // A disconnected latest snapshot must not hide a contradictory clock cycle.
416
+ const reviews = [
417
+ { checkpointId: 'a', sequence: 1, status: 'blocked' },
418
+ { checkpointId: 'b', sequence: 2, checkpointCreatedAt: '2026-10-23T00:00:00Z', status: 'accepted' },
419
+ { checkpointId: 'c', checkpointCreatedAt: '2026-10-23T00:01:00Z', status: 'accepted' },
420
+ { checkpointId: 'd', sequence: 0, checkpointCreatedAt: '2026-10-23T00:02:00Z', status: 'accepted' },
421
+ { checkpointId: 'isolated', status: 'accepted' }
422
+ ];
423
+ assert.equal(selectEffectiveAcceptanceReviews({}, { reviews }).some(r => r.status === 'blocked'), true);
424
+ assert.equal(selectEffectiveAcceptanceReviews({}, { reviews: [
425
+ { checkpointId: 'done', sequence: 1, status: 'accepted', taskTerminal: true },
426
+ { checkpointId: 'pending', sequence: 2, status: 'blocked' }
427
+ ] }).some(r => r.status === 'blocked'), true, 'terminal cannot swallow a later task blocker');
428
+ }
429
+
430
+ // A broader-project label must never launder a failed/blocked task review.
431
+ for (const status of ['blocked', 'revise']) {
432
+ for (const dispatchStatus of ['completed', 'failed', 'verify_failed', 'runtime_interrupted', 'runtime_blocked']) {
433
+ const terminal = { checkpointId: 'done', sequence: 1, status: 'accepted', projectCompletion: { status: 'complete' } };
434
+ const later = { checkpointId: 'progress', sequence: 2, status, projectCompletion: { status: 'needs_human_acceptance' } };
435
+ for (const reviews of [[terminal, later], [later, terminal]]) {
436
+ const judgement = buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'cp1' }] }, { count: 2 }, { reviews }, { dispatchStatus });
437
+ assert.deepEqual(judgement.coverage.effective_review_ids, ['progress']);
438
+ assert.equal(judgement.coverage.terminal_lock, false);
439
+ if (status === 'blocked') assert.equal(judgement.outcome, 'blocked');
440
+ }
441
+ }
442
+ }
443
+ // Even accepted governance cannot hide a materializable deferred gate.
444
+ {
445
+ const reviews = [
446
+ { checkpointId: 'done', sequence: 1, status: 'accepted', projectCompletion: 'complete' },
447
+ { checkpointId: 'gate', sequence: 2, status: 'accepted', projectCompletion: 'needs_human_acceptance', deferredGates: [{ action: 'send' }] }
448
+ ];
449
+ assert.deepEqual(selectEffectiveAcceptanceReviews({ checkpoints: [{ id: 'cp1' }] }, { reviews }).map(r => r.checkpointId), ['gate']);
450
+ }
@@ -0,0 +1,27 @@
1
+ import assert from 'node:assert/strict';
2
+ import { diagnosticSources } from '../lib/openclaw-diagnostic-source.mjs';
3
+ const args = { root: '/tmp', openclawBin: 'profile-cli' };
4
+ const inventory = { telegram: ['personal'], feishu: { accounts: ['main', 'other'] }, slack: { accounts: ['team'] }, discord: [], signal: { accounts: ['phone'] } };
5
+ const run = async (bin, argv) => {
6
+ assert.equal(bin, 'profile-cli');
7
+ assert.deepEqual(argv, ['channels', 'list', '--json']);
8
+ return { code: 0, stdout: JSON.stringify({ chat: inventory }) };
9
+ };
10
+ assert.equal((await diagnosticSources(args, run)).length, 5);
11
+ assert.deepEqual(await diagnosticSources({ ...args, sourceChannel: 'telegram' }, run), [{ channel: 'telegram', account: 'personal', target: '1', reply_to: '1' }]);
12
+ assert.equal((await diagnosticSources({ ...args, sourceAccount: 'other', sourceTarget: 'custom-target' }, run))[0].target, 'custom-target');
13
+ for (const selection of [{ sourceChannel: 'absent' }, { sourceAccount: 'missing' }]) await assert.rejects(diagnosticSources({ ...args, ...selection }, run), /No matching/);
14
+ for (const result of [{ code: 1 }, { code: 0, stdout: 'not json' }, { code: 0, stdout: '{}' }, { code: 0, stdout: '{"chat":{}}' }]) await assert.rejects(diagnosticSources(args, async () => result));
15
+ console.log('diagnostic source selection: passed');
16
+
17
+ for (const broken of [null, {}, 'accounts', { accounts: 'bad' }, ['personal', 42], ['personal', ''], ['personal', ' '], ['personal', null]]) {
18
+ const mixed = async () => ({ code: 0, stdout: JSON.stringify({ chat: { telegram: ['personal'], slack: broken } }) });
19
+ await assert.rejects(diagnosticSources(args, mixed), /Malformed/);
20
+ await assert.rejects(diagnosticSources({ ...args, sourceAccount: 'personal' }, mixed), /Malformed/);
21
+ assert.equal((await diagnosticSources({ ...args, sourceChannel: 'telegram' }, mixed)).length, 1);
22
+ await assert.rejects(diagnosticSources({ ...args, sourceChannel: 'slack' }, mixed), /Malformed/);
23
+ }
24
+ const empty = async () => ({ code: 0, stdout: JSON.stringify({ chat: { telegram: ['personal'], slack: [] } }) });
25
+ assert.equal((await diagnosticSources(args, empty)).length, 1);
26
+ await assert.rejects(diagnosticSources({ ...args, sourceChannel: 'slack' }, empty), /No matching/);
27
+ console.log('mixed-validity inventory regression: passed');