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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.16.2 - 2026-10-24
6
+
7
+ - Discover OpenClaw diagnostic channel/account pairs from the selected CLI, with explicit source channel, account and target filters. Doctor covers all matching accounts; smoke covers one source per run.
8
+ - Fail closed on malformed account inventories, missing installation records, executable mismatch and managed notifier/dispatcher drift.
9
+ - Preserve the installed CLI invocation for profile-sensitive wrappers and isolate inherited human-input/notification sources in diagnostic subprocesses, preventing wrong-route false positives without changing production notification precedence.
10
+ - Add Feishu, Telegram and Slack regression coverage with actual CLI/source/dry-run assertions; synchronize distributed skill instructions and acceptance boundaries. Dry-run diagnostics do not prove real message delivery, and publishing does not upgrade existing integrations.
11
+
12
+ ## 0.16.1 - 2026-10-23
13
+
14
+ - Restrict terminal-lock governance exemptions to accepted, gate-free later reviews. A `needs_human_acceptance` project label no longer hides current blockers or failed acceptance; protect ordinary retries and context recovery with terminal-checkpoint regressions through both core and installed mock dispatchers.
15
+
16
+ - Select effective checkpoint reviews using explicit numeric sequence and checkpoint timestamps, never ID suffixes or review-generation order. Preserve unresolved blockers under missing/conflicting chronology in both task and milestone paths; count milestone coverage once and keep terminal acceptance from hiding unordered/current-task blockers.
17
+
18
+ - Check effective blocked checkpoints before each ordinary dispatch retry, even without a handoff. Preserve human-blocked classification for ordinary/verification failures without creating development revisions; resolved historical blockers still allow retries.
19
+
20
+ - Stop runtime recovery and requeueing when an effective checkpoint review is blocked, including interruption before handoff creation; retain recovery after historical blockers are resolved.
21
+
22
+ - Fix nonzero-exit handoff adjudication before retries and preserve human/runtime diagnostic signatures before worker output clipping; add combined failure, custom-policy and split UTF-8 regression coverage.
23
+
24
+ - Add OpenClaw context-budget protection: default three-tick session rotation, final-prompt telemetry-based rotation at 60%/75%, bounded worker output capture, and durable run-bound handoffs. Missing telemetry falls back to the tick limit; in-turn thresholds and tool-output budgets are cooperative, not runtime interrupts.
25
+ - Classify explicit context overflow as bounded session recovery and never retry a known runtime interruption in the same session. Validate handoff checkpoints and stop for unresolved authority/action outcomes; completed work is not replayed for high usage.
26
+ - Update the skill's background lock-wait and context-budget procedures. Existing integrations require a reviewed upgrade to activate generated dispatcher/config changes.
27
+
5
28
  ## 0.16.0 - 2026-10-10
6
29
 
7
30
  ### Upgrade notes
package/README.md CHANGED
@@ -1423,3 +1423,15 @@ https://clawhub.ai/ambitioncn/skills/taskforce-loop-engineering
1423
1423
  # P2 multi-agent control plane
1424
1424
 
1425
1425
  Loop Engineering includes typed executable todos with capability/authority-aware atomic claim, lease and fencing, deterministic dependency/quota scheduling, durable peer handoff, orphan recovery, and P0/P1 safety integration. See [docs/multi-agent-control-plane.md](docs/multi-agent-control-plane.md) for the data contract, CLI, and migration path.
1426
+
1427
+ ### Multi-IM diagnostic probes
1428
+
1429
+ OpenClaw doctor discovers channels/accounts using `openclaw channels list --json`
1430
+ in the selected CLI/profile environment and dry-runs each configured account. It
1431
+ does not assume Feishu. Smoke uses the first successfully checked source; choose
1432
+ a specific route with `--source-channel telegram --source-account personal`. Both
1433
+ commands accept `--source-target` for channel plugins requiring a special target
1434
+ format. Targets are synthetic by default and notification probes always use
1435
+ dry-run; success does not prove real delivery. Missing/invalid inventories and
1436
+ unmatched explicit selections fail rather than silently falling back to Feishu.
1437
+ Smoke still executes a real isolated worker task and cleans its temporary queue.
@@ -0,0 +1,147 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS, DEFAULT_RECOVERABLE_RUNTIME_PATTERNS } from './dispatch-classification.mjs';
3
+ import path from 'node:path';
4
+ import { createWriteStream } from 'node:fs';
5
+ import { finished } from 'node:stream/promises';
6
+ import { open, realpath, writeFile } from 'node:fs/promises';
7
+
8
+ export const DEFAULT_CONTEXT_POLICY = Object.freeze({ softRatio: 0.60, hardRatio: 0.75, maxTicks: 3, maxHandoffBytes: 16384 });
9
+ export function contextPolicy(retry = {}) {
10
+ const c = retry.contextBudget ?? {};
11
+ const softRatio = c.softRatio ?? DEFAULT_CONTEXT_POLICY.softRatio;
12
+ const hardRatio = c.hardRatio ?? DEFAULT_CONTEXT_POLICY.hardRatio;
13
+ const maxTicks = retry.sessionMaxTicks ?? DEFAULT_CONTEXT_POLICY.maxTicks;
14
+ if (![softRatio, hardRatio].every(x => typeof x === 'number' && Number.isFinite(x)) || !(0 < softRatio && softRatio < hardRatio && hardRatio < 1)) throw new Error('Invalid context budget ratios');
15
+ if (!Number.isSafeInteger(maxTicks) || maxTicks < 1) throw new Error('Invalid sessionMaxTicks');
16
+ return { ...DEFAULT_CONTEXT_POLICY, softRatio, hardRatio, maxTicks };
17
+ }
18
+
19
+ // lastCallUsage is the final model request, never aggregate run usage. OpenClaw
20
+ // input excludes cacheRead; cacheWrite is not added (it may overlap input).
21
+ export function openClawContextUsage(envelope) {
22
+ const meta = envelope?.result?.meta?.agentMeta ?? envelope?.meta?.agentMeta;
23
+ const last = meta?.lastCallUsage;
24
+ const capacity = meta?.contextTokens;
25
+ const input = last?.input;
26
+ const cacheRead = last?.cacheRead ?? 0;
27
+ if (![capacity, input, cacheRead].every(x => Number.isSafeInteger(x) && x >= 0) || capacity === 0 || input + cacheRead === 0) return null;
28
+ return { usedTokens: input + cacheRead, windowTokens: capacity, source: 'openclaw.lastCallUsage.input+cacheRead', measurement: 'last_prompt' };
29
+ }
30
+ export function contextRotation(usage, ticks, policy) {
31
+ const known = usage && Number.isSafeInteger(usage.usedTokens) && usage.usedTokens > 0 && Number.isSafeInteger(usage.windowTokens) && usage.windowTokens > 0;
32
+ const ratio = known ? usage.usedTokens / usage.windowTokens : null;
33
+ const reason = ratio !== null && ratio >= policy.hardRatio ? 'context_hard_limit'
34
+ : ratio !== null && ratio >= policy.softRatio ? 'context_soft_limit'
35
+ : ticks >= policy.maxTicks ? 'bounded_tick_limit' : null;
36
+ return { rotate: reason !== null, reason, ratio, telemetry: known ? 'last_prompt' : 'unavailable' };
37
+ }
38
+
39
+ export async function readBoundedJson(file, maxBytes = 16384) {
40
+ if (!file) return null;
41
+ let handle;
42
+ try {
43
+ handle = await open(file, 'r');
44
+ if (!(await handle.stat()).isFile()) return null;
45
+ const buffer = Buffer.alloc(maxBytes + 1);
46
+ let bytes = 0;
47
+ while (bytes < buffer.length) {
48
+ const { bytesRead } = await handle.read(buffer, bytes, buffer.length - bytes, bytes);
49
+ if (!bytesRead) break;
50
+ bytes += bytesRead;
51
+ }
52
+ return bytes <= maxBytes ? JSON.parse(buffer.subarray(0, bytes).toString('utf8')) : null;
53
+ } catch { return null; }
54
+ finally { await handle?.close(); }
55
+ }
56
+ export function validHandoff(value, { taskId, runId, generation, attempt }) {
57
+ if (value?.version !== 1 || value.taskId !== taskId || value.runId !== runId || value.generation !== generation || value.attempt !== attempt || value.reason !== 'context_budget') return false;
58
+ if (!['summary', 'nextAction', 'authority', 'checkpoint'].every(k => typeof value[k] === 'string' && value[k].trim())) return false;
59
+ if (!['completed', 'remaining', 'evidence', 'pendingActions', 'blockers'].every(k => Array.isArray(value[k]) && value[k].every(x => typeof x === 'string'))) return false;
60
+ return value.remaining.length > 0 && value.evidence.length > 0;
61
+ }
62
+ export function contextWorkerInstructions(env = process.env) {
63
+ const policy = JSON.parse(env.LOOP_CONTEXT_POLICY || JSON.stringify(DEFAULT_CONTEXT_POLICY));
64
+ return [
65
+ 'CONTEXT BUDGET: Work on one bounded objective this turn. Read only necessary file ranges. Keep each tool response around 8 KiB or less; put full logs in task artifacts and return paths plus short excerpts. This is a cooperative tool-output budget, not runtime enforcement.',
66
+ 'Read the resume manifest at ' + (env.LOOP_RESUME_FILE || '(unavailable)') + ' and only the latest relevant checkpoint; never reload entire session transcripts or all historical checkpoints.',
67
+ 'At approximately ' + Math.round(policy.softRatio * 100) + '% of the model context window, save a checkpoint and prepare handoff. At ' + Math.round(policy.hardRatio * 100) + '% stop new work and hand off. If live usage is unavailable, finish one small objective and checkpoint; do not invent token measurements.',
68
+ 'Before repeating an external/paid/destructive operation, verify its previous outcome using durable receipts/reservations; an uncertain outcome is a blocker, never permission to replay. Preserve existing human gates and amendment versions.',
69
+ 'If unfinished work needs a fresh session, first write a normal progress checkpoint (not ready_for_acceptance) with task_id and loop_run_id matching this run, then write JSON to ' + (env.LOOP_CONTEXT_HANDOFF_FILE || '(unavailable)') + ' and finish the turn. Never claim completion merely because you handed off.',
70
+ 'Handoff schema (max 16 KiB): ' + JSON.stringify({ version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID, generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), reason: 'context_budget', checkpoint: 'path to the current progress checkpoint', summary: 'brief current state', completed: ['completed work'], remaining: ['remaining work'], evidence: ['checkpoint and verification paths'], nextAction: 'one concrete next step', authority: 'authorized scope and gates', pendingActions: ['uncertain external action receipts to reconcile, if any'], blockers: [] }),
71
+ 'Use blockers for missing authority or unresolved external actions; these must stop automatic continuation. Do not put secrets or full logs in handoff files.'
72
+ ].join('\n');
73
+ }
74
+
75
+ // Capture CLI output outside the model conversation. The JSON parse buffer is
76
+ // bounded; oversized/non-JSON responses fall back to tick-based rotation.
77
+ export async function observeOpenClawWorker(child, env = process.env) {
78
+ const prefix = env.LOOP_WORKER_OUTPUT_PREFIX;
79
+ let capture = Buffer.alloc(0), overflow = false;
80
+ let outTail = Buffer.alloc(0), errTail = Buffer.alloc(0);
81
+ const streams = [];
82
+ const retry = JSON.parse(env.LOOP_DISPATCH_RETRY_JSON || '{}');
83
+ const patterns = [...(retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS),
84
+ ...(retry.recoverableRuntimePatterns ?? DEFAULT_RECOVERABLE_RUNTIME_PATTERNS).map(entry => typeof entry === 'string' ? entry : entry.pattern)]
85
+ .map(String).filter(Boolean);
86
+ const matched = new Set();
87
+ const overlap = Math.max(1, ...patterns.map(pattern => pattern.length));
88
+ for (const [name, stream] of [['stdout', child.stdout], ['stderr', child.stderr]]) {
89
+ if (prefix) {
90
+ const log = createWriteStream(prefix + '.' + name + '.log', { mode: 0o600 });
91
+ stream.pipe(log);
92
+ log.on('error', () => { stream.unpipe(log); stream.resume(); });
93
+ streams.push(finished(log).catch(error => error));
94
+ }
95
+ const decoder = new StringDecoder('utf8');
96
+ let scanTail = '';
97
+ stream.on('data', chunk => {
98
+ // Match the entire stream before clipping. Retain only enough overlap for
99
+ // split signatures (including UTF-8), and emit each signature once. The
100
+ // parent applies exit-code rules and configured human-before-runtime priority.
101
+ const scan = scanTail + decoder.write(chunk).toLowerCase();
102
+ for (const pattern of patterns) {
103
+ if (!matched.has(pattern) && scan.includes(pattern.toLowerCase())) {
104
+ matched.add(pattern);
105
+ process.stderr.write('\n[worker diagnostic] ' + pattern + '\n');
106
+ }
107
+ }
108
+ scanTail = scan.slice(-overlap);
109
+
110
+ if (name === 'stdout') {
111
+ outTail = Buffer.concat([outTail, chunk]).subarray(-16384);
112
+ if (!overflow && capture.length + chunk.length <= 2 * 1024 * 1024) capture = Buffer.concat([capture, chunk]);
113
+ else { overflow = true; capture = Buffer.alloc(0); }
114
+ } else errTail = Buffer.concat([errTail, chunk]).subarray(-16384);
115
+ });
116
+ }
117
+ const result = await new Promise(resolve => {
118
+ child.on('error', error => resolve({ code: 1, error: error.message }));
119
+ child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 128 : 1) }));
120
+ });
121
+ const logErrors = (await Promise.all(streams)).filter(Boolean);
122
+ if (logErrors.length) throw logErrors[0];
123
+ let usage = null;
124
+ if (!overflow) {
125
+ try { usage = openClawContextUsage(JSON.parse(capture.toString('utf8'))); } catch { /* unknown */ }
126
+ }
127
+ if (env.LOOP_CONTEXT_USAGE_FILE) await writeFile(env.LOOP_CONTEXT_USAGE_FILE, JSON.stringify({
128
+ version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID,
129
+ generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), usage
130
+ }) + '\n', { mode: 0o600 });
131
+ process.stdout.write(outTail);
132
+ process.stderr.write(errTail);
133
+ if (result.error) process.stderr.write(result.error + '\n');
134
+ return result.code;
135
+ }
136
+
137
+ export async function handoffCheckpoint(value, { root, checkpointsDir, taskId, runId }) {
138
+ try {
139
+ const base = await realpath(checkpointsDir);
140
+ const file = await realpath(path.resolve(root, value.checkpoint));
141
+ const relative = path.relative(base, file);
142
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return { valid: false };
143
+ const cp = await readBoundedJson(file);
144
+ if (!cp || cp.task_id !== taskId || cp.loop_run_id !== runId || !Array.isArray(cp.blockers)) return { valid: false };
145
+ return { valid: true, blocked: cp.blockers.length > 0 || ['blocked', 'needs_human_input'].includes(cp.status) };
146
+ } catch { return { valid: false }; }
147
+ }
package/lib/core.mjs CHANGED
@@ -1,9 +1,12 @@
1
+ import { dispatchFailureClassification } from './dispatch-classification.mjs';
2
+ export { dispatchFailureClassification } from './dispatch-classification.mjs';
1
3
  import { access, copyFile, link, mkdir, mkdtemp, open, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from 'node:fs/promises';
2
4
  import path from 'node:path';
3
5
  import { spawn } from 'node:child_process';
4
6
  import { fileURLToPath } from 'node:url';
5
7
  import { tmpdir } from 'node:os';
6
8
  import { createHash, randomUUID } from 'node:crypto';
9
+ import { contextPolicy, contextRotation, readBoundedJson, validHandoff, handoffCheckpoint } from './context-budget.mjs';
7
10
  import { listSteps } from './execution-ledger.mjs';
8
11
  import { readAndVerifyEvidence } from './production-evidence.mjs';
9
12
 
@@ -4209,7 +4212,7 @@ export async function writeAcceptanceReviews(root, queue, task, taskContract, ac
4209
4212
  checkpointId: review.checkpoint_id,
4210
4213
  milestoneId: checkpoint.milestone_id ?? null,
4211
4214
  revisesCheckpointId: checkpoint.revises_checkpoint_id ?? null,
4212
- sequence: Number(checkpoint.sequence ?? String(checkpoint.checkpoint_id ?? '').match(/(\d+)$/)?.[1] ?? 0),
4215
+ sequence: checkpoint.sequence ?? null,
4213
4216
  checkpointCreatedAt: checkpoint.created_at ?? null,
4214
4217
  createdAt: checkpoint.created_at ?? review.created_at,
4215
4218
  projectCompletion: checkpoint.project_completion ?? null,
@@ -4233,24 +4236,31 @@ export async function writeAcceptanceReviews(root, queue, task, taskContract, ac
4233
4236
  };
4234
4237
  }
4235
4238
 
4236
- function compareReviewSequence(a, b) {
4237
- const sequenceDelta = Number(a.sequence ?? 0) - Number(b.sequence ?? 0);
4238
- if (sequenceDelta !== 0) return sequenceDelta;
4239
- return String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? ''));
4239
+ // IDs and review-generation timestamps are not chronology. A comparison is
4240
+ // conclusive only when checkpoint-owned clocks agree; missing/conflicting
4241
+ // evidence leaves both snapshots live (especially unresolved blockers).
4242
+ function compareReviewRecency(a, b) {
4243
+ const sequence = value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
4244
+ const timestamp = value => typeof value === 'string' && value.trim().length > 0 && Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;
4245
+ const signs = [];
4246
+ for (const [left, right] of [
4247
+ [sequence(a.sequence), sequence(b.sequence)],
4248
+ [timestamp(a.checkpointCreatedAt), timestamp(b.checkpointCreatedAt)]
4249
+ ]) {
4250
+ if (left !== null && right !== null && left !== right) signs.push(Math.sign(left - right));
4251
+ }
4252
+ if (signs.length && signs.every(sign => sign === signs[0])) return signs[0];
4253
+ return 0;
4240
4254
  }
4241
4255
 
4242
- function compareReviewRecency(a, b) {
4243
- const aCheckpoint = Number(String(a.checkpointId ?? '').match(/(\d+)$/)?.[1] ?? 0);
4244
- const bCheckpoint = Number(String(b.checkpointId ?? '').match(/(\d+)$/)?.[1] ?? 0);
4245
- if (aCheckpoint !== bCheckpoint) return aCheckpoint - bCheckpoint;
4246
- // Review artifacts are regenerated as a batch. Their generated_at values
4247
- // therefore describe directory traversal order, not checkpoint recency.
4248
- // Only trust a timestamp that came from the checkpoint itself.
4249
- const checkpointCreatedDelta = String(a.checkpointCreatedAt ?? '').localeCompare(String(b.checkpointCreatedAt ?? ''));
4250
- if (checkpointCreatedDelta !== 0 && a.checkpointCreatedAt && b.checkpointCreatedAt) return checkpointCreatedDelta;
4251
- const sequenceDelta = Number(a.sequence ?? 0) - Number(b.sequence ?? 0);
4252
- if (sequenceDelta !== 0) return sequenceDelta;
4253
- return compareReviewSequence(a, b);
4256
+ function effectiveReviewFrontier(reviews) {
4257
+ const frontier = reviews.filter(review => !reviews.some(other => compareReviewRecency(other, review) > 0));
4258
+ // Partial clocks can form a cycle when different pairs expose different
4259
+ // clocks. Never turn contradictory evidence into an empty acceptance set.
4260
+ return frontier.length
4261
+ ? reviews.filter(review => frontier.includes(review)
4262
+ || !frontier.some(latest => compareReviewRecency(latest, review) > 0))
4263
+ : reviews;
4254
4264
  }
4255
4265
 
4256
4266
  function terminalTaskReview(review, contract = {}) {
@@ -4263,12 +4273,18 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4263
4273
  const allReviews = acceptanceReviews?.reviews ?? [];
4264
4274
  const planned = Array.isArray(devPlan?.checkpoints) ? devPlan.checkpoints : [];
4265
4275
  if (planned.length <= 1) {
4266
- const ordered = [...allReviews].sort(compareReviewRecency);
4267
- // A task-level terminal acceptance is monotonic. Later checkpoints may
4268
- // report broader project governance, but they cannot reopen or overwrite
4269
- // the completed task. Broader work belongs to the project ledger/gates.
4270
- const terminal = ordered.find((review) => terminalTaskReview(review, contract));
4271
- return terminal ? [terminal] : ordered.slice(-1);
4276
+ // Terminal acceptance remains monotonic only with known chronology.
4277
+ // An unordered blocker cannot be dismissed as later project governance.
4278
+ const terminal = allReviews.find(review => terminalTaskReview(review, contract)
4279
+ && allReviews.every(other => other === review
4280
+ || compareReviewRecency(review, other) > 0
4281
+ || (compareReviewRecency(review, other) < 0
4282
+ && projectCompletionStatus(other.projectCompletion) === 'needs_human_acceptance'
4283
+ // A project label is not proof that a failed review is out of scope.
4284
+ // Only independently accepted, gate-free governance can be ignored.
4285
+ && other.status === 'accepted'
4286
+ && (other.deferredGates?.length ?? 0) === 0)));
4287
+ return terminal ? [terminal] : effectiveReviewFrontier(allReviews);
4272
4288
  }
4273
4289
  const selected = [];
4274
4290
  for (const checkpoint of planned) {
@@ -4277,7 +4293,7 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4277
4293
  review.milestoneId === milestoneId || review.checkpointId === milestoneId
4278
4294
  );
4279
4295
  if (candidates.length === 0) continue;
4280
- selected.push([...candidates].sort(compareReviewSequence).at(-1));
4296
+ selected.push(...effectiveReviewFrontier(candidates));
4281
4297
  }
4282
4298
  return selected;
4283
4299
  }
@@ -4293,7 +4309,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4293
4309
  // resolved historical blocker does not permanently poison the task.
4294
4310
  const effectiveReviews = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4295
4311
  const reviewCount = effectiveReviews.length;
4296
- const acceptedCount = effectiveReviews.filter((item) => item.status === 'accepted').length;
4312
+ const acceptedCount = requiredCheckpoints > 1
4313
+ ? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
4314
+ && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id))).length
4315
+ : effectiveReviews.filter((item) => item.status === 'accepted').length;
4297
4316
  const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
4298
4317
  const blockedCount = effectiveReviews.filter((item) => item.status === 'blocked').length;
4299
4318
  const dispatchStatus = context.dispatchStatus ?? 'unknown';
@@ -4307,7 +4326,13 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4307
4326
  const deferredGateCount = effectiveReviews.reduce((count, review) => count + (review.deferredGates?.length ?? 0), 0);
4308
4327
  let outcome = 'needs_revision';
4309
4328
 
4310
- if (dispatchStatus === 'runtime_interrupted') {
4329
+ // A worker can stop after persisting a blocker but before writing a handoff.
4330
+ // Use effective reviews, not historical blockers, before permitting recovery.
4331
+ if (['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed'].includes(dispatchStatus) && blockedCount > 0) {
4332
+ outcome = 'blocked';
4333
+ reasons.push(`${blockedCount} effective acceptance review(s) block automatic continuation.`);
4334
+ nextActions.push('Resolve the recorded human/external blocker before any continuation.');
4335
+ } else if (dispatchStatus === 'runtime_interrupted') {
4311
4336
  outcome = 'runtime_interrupted';
4312
4337
  reasons.push(`A recoverable runtime interruption stopped the worker${dispatchFailure?.category ? ` (${dispatchFailure.category})` : ''}.`);
4313
4338
  nextActions.push('Rotate the worker session and resume from the latest durable checkpoint without creating a development revision.');
@@ -4434,8 +4459,10 @@ export async function writeFinalJudgement(root, queue, task, taskContract, accep
4434
4459
 
4435
4460
  function queueStatusFromFinalJudgement(currentStatus, finalJudgement) {
4436
4461
  if (!finalJudgement?.judgement) return currentStatus;
4437
- if (currentStatus !== 'completed') return currentStatus;
4438
4462
  const outcome = finalJudgement.judgement.outcome;
4463
+ // Carry the recovery veto through to queue placement, not just the report.
4464
+ if (['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed'].includes(currentStatus) && outcome === 'blocked') return 'needs_human_input';
4465
+ if (currentStatus !== 'completed') return currentStatus;
4439
4466
  if (outcome === 'ready_to_apply') return currentStatus;
4440
4467
  if (outcome === 'project_in_progress') return outcome;
4441
4468
  if (outcome === 'runtime_interrupted') return outcome;
@@ -9597,120 +9624,13 @@ function buildQueueEnv(root, queue, task, taskFile, runId, extra = {}) {
9597
9624
  };
9598
9625
  }
9599
9626
 
9600
- const DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS = [
9601
- 'INSTALL_FAILED_USER_RESTRICTED',
9602
- 'device unauthorized',
9603
- 'unauthorized',
9604
- 'offline',
9605
- 'more than one device',
9606
- 'no devices/emulators found',
9607
- 'Permission denied',
9608
- 'Operation not permitted',
9609
- 'user restricted',
9610
- 'requires human',
9611
- 'needs human',
9612
- '需要人工',
9613
- '需要用户确认',
9614
- '等待人工',
9615
- '权限未开',
9616
- '用户取消',
9617
- '用户限制'
9618
- ];
9619
-
9620
- const DEFAULT_RECOVERABLE_RUNTIME_PATTERNS = [
9621
- { category: 'incomplete_turn', pattern: '"kind": "incomplete_turn"' },
9622
- { category: 'incomplete_turn', pattern: '"livenessState": "abandoned"' },
9623
- // Free-text signatures can also appear in a successful task's own answer
9624
- // (for example a task that implements rate limiting). Only the structured
9625
- // runtime trailers above may override exitCode=0.
9626
- { category: 'incomplete_turn', pattern: 'stopped before confirming the turn was complete', nonZeroOnly: true },
9627
- // The OpenClaw embedded runner injects a recovery prompt when an assistant
9628
- // turn completes its tool calls without a user-visible answer. A dispatch
9629
- // that exits non-zero with this signature hit a session protocol failure,
9630
- // not a task defect: classify it as a recoverable incomplete turn so the
9631
- // runtime recovery path rotates the worker session and resumes.
9632
- { category: 'incomplete_turn', pattern: 'did not produce a user-visible answer', nonZeroOnly: true },
9633
- // OpenClaw closes websocket admission while the Gateway drains for a
9634
- // restart. A worker launched inside that short window receives HTTP 503
9635
- // before task execution begins. Exact non-zero admission/drain signatures
9636
- // are runtime interruptions, not development failures.
9637
- { category: 'gateway_restart', pattern: 'gateway websocket admission closed', nonZeroOnly: true },
9638
- { category: 'gateway_restart', pattern: 'gateway is draining for restart', nonZeroOnly: true },
9639
- { category: 'gateway_restart', pattern: 'unavailable during gateway restart', nonZeroOnly: true },
9640
- { category: 'compaction_timeout', pattern: 'compaction timed out', nonZeroOnly: true },
9641
- { category: 'compaction_timeout', pattern: 'transcript compaction failed', nonZeroOnly: true },
9642
- { category: 'transport_error', pattern: 'connection reset', nonZeroOnly: true },
9643
- { category: 'transport_error', pattern: 'socket hang up', nonZeroOnly: true },
9644
- { category: 'transport_error', pattern: 'network error', nonZeroOnly: true },
9645
- { category: 'rate_limit', pattern: 'rate limit', nonZeroOnly: true }
9646
- ];
9647
-
9648
- export function dispatchFailureClassification(result, retry = {}) {
9649
- if (!result) {
9650
- return {
9651
- category: 'ok',
9652
- requiresHumanAction: false,
9653
- matchedPattern: null
9654
- };
9655
- }
9656
- // Some embedded runtimes exit their wrapper successfully after the model
9657
- // turn itself was abandoned. Inspect the structured trailer before trusting
9658
- // exitCode=0 or the queue may accept partial work and replay a stale gate.
9659
- const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`.toLowerCase();
9660
- const runtimePatterns = retry.recoverableRuntimePatterns ?? DEFAULT_RECOVERABLE_RUNTIME_PATTERNS;
9661
- const runtimeMatch = runtimePatterns.find((entry) => {
9662
- const pattern = typeof entry === 'string' ? entry : entry.pattern;
9663
- const nonZeroOnly = typeof entry === 'object' && entry !== null && entry.nonZeroOnly === true;
9664
- return (!nonZeroOnly || result.exitCode !== 0)
9665
- && output.includes(String(pattern ?? entry).toLowerCase());
9666
- });
9667
- if (runtimeMatch) {
9668
- return {
9669
- category: runtimeMatch.category ?? 'runtime_interruption',
9670
- requiresHumanAction: false,
9671
- recoverableRuntime: true,
9672
- matchedPattern: runtimeMatch.pattern ?? runtimeMatch
9673
- };
9674
- }
9675
- if (result.exitCode === 0) {
9676
- return {
9677
- category: 'ok',
9678
- requiresHumanAction: false,
9679
- matchedPattern: null
9680
- };
9681
- }
9682
- if (result.timedOut) {
9683
- return {
9684
- category: 'timeout',
9685
- requiresHumanAction: false,
9686
- recoverableRuntime: true,
9687
- matchedPattern: null
9688
- };
9689
- }
9690
- const patterns = retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS;
9691
- const matched = patterns.find((pattern) => output.includes(pattern.toLowerCase()));
9692
- if (matched) {
9693
- return {
9694
- category: 'requires_human_action',
9695
- requiresHumanAction: true,
9696
- recoverableRuntime: false,
9697
- matchedPattern: matched
9698
- };
9699
- }
9700
- return {
9701
- category: 'retryable_failure',
9702
- requiresHumanAction: false,
9703
- recoverableRuntime: false,
9704
- matchedPattern: null
9705
- };
9706
- }
9707
-
9708
9627
  function shouldRetryDispatch(result, retry, attempt) {
9709
9628
  const maxAttempts = retry?.maxAttempts ?? 1;
9710
9629
  if (attempt >= maxAttempts) return false;
9711
9630
  if (!result || result.exitCode === 0) return false;
9712
9631
  if (result.canceled) return false;
9713
- if (dispatchFailureClassification(result, retry).requiresHumanAction) return false;
9632
+ const classification = dispatchFailureClassification(result, retry);
9633
+ if (classification.requiresHumanAction || classification.recoverableRuntime) return false;
9714
9634
  const retryExitCodes = retry?.retryExitCodes;
9715
9635
  return !retryExitCodes || retryExitCodes.includes(result.exitCode);
9716
9636
  }
@@ -9811,6 +9731,8 @@ async function runDispatchWithRetry(root, options, queue, task, activeFile, runI
9811
9731
  cwd: runContext.cwd ?? root,
9812
9732
  env: {
9813
9733
  ...buildQueueEnv(root, queue, task, activeFile, runId, runContext.env ?? {}),
9734
+ ...(runContext.env?.LOOP_WORKER_OUTPUT_PREFIX ? { LOOP_WORKER_OUTPUT_PREFIX: runContext.env.LOOP_WORKER_OUTPUT_PREFIX + '.attempt' + attempt } : {}),
9735
+ LOOP_DISPATCH_RETRY_JSON: JSON.stringify(retry),
9814
9736
  LOOP_ATTEMPT: String(attempt),
9815
9737
  LOOP_MAX_ATTEMPTS: String(maxAttempts)
9816
9738
  },
@@ -9841,7 +9763,11 @@ async function runDispatchWithRetry(root, options, queue, task, activeFile, runI
9841
9763
  failureCategory: failureClassification.category,
9842
9764
  matchedPattern: failureClassification.matchedPattern
9843
9765
  });
9844
- if (!shouldRetryDispatch(result, retry, attempt)) break;
9766
+ // A handoff must be adjudicated before any retry, including nonzero exits.
9767
+ if (await exists(runContext.env?.LOOP_CONTEXT_HANDOFF_FILE ?? '') || !shouldRetryDispatch(result, retry, attempt)) break;
9768
+ // A checkpoint may precede its handoff. Reuse final judgement's effective
9769
+ // review selection so resolved historical blockers do not veto retries.
9770
+ if (await runContext.hasBlockingCheckpoints?.()) break;
9845
9771
  runContext.progress?.emit('dispatch', 'retry_wait', `Waiting ${retryDelayMs}ms before retry`, {
9846
9772
  attempt,
9847
9773
  retryDelayMs
@@ -9964,6 +9890,7 @@ async function runPreflight(root, config, timeoutMs) {
9964
9890
 
9965
9891
  export async function runQueueOnce(root, options) {
9966
9892
  const queue = normalizeLoopId(options.queue);
9893
+ const budgetPolicy = contextPolicy(options.retry);
9967
9894
  await ensureQueueDirs(root, queue);
9968
9895
  await reconcileProjectGates(root, { queue });
9969
9896
  let progressTask = null;
@@ -10095,6 +10022,9 @@ export async function runQueueOnce(root, options) {
10095
10022
  let acceptanceReviews = null;
10096
10023
  let finalJudgement = null;
10097
10024
  let revisionRequest = null;
10025
+ let contextUsage = null;
10026
+ let contextHandoff = null;
10027
+ const contextPrefix = path.join(taskRuntimeDirFor(root, queue, task.id), runId);
10098
10028
 
10099
10029
  try {
10100
10030
  taskContract = await writeTaskContract(root, queue, task, {
@@ -10152,10 +10082,17 @@ export async function runQueueOnce(root, options) {
10152
10082
  exitCode = 2;
10153
10083
  } else {
10154
10084
  const humanInputContextFile = await prepareHumanInputContext(root, queue, task.id);
10085
+ const resumeFile = contextPrefix + '.resume.json';
10086
+ await writeJson(resumeFile, { version: 1, workspaceRoot: root, taskId: task.id, generation: task.runtimeSessionGeneration ?? 0, previousRun: task.runPath ?? null, previousHandoff: task.contextHandoffFile ?? null, contract: taskContract.file, devPlan: devPlan.file, acceptancePlan: acceptancePlan.file, checkpointsDir: devPlan.checkpointsDir, instruction: 'Read only the latest relevant checkpoint and handoff. Verify pending external action outcomes before replay; preserve authority and amendments.' });
10155
10087
  const runContext = {
10156
10088
  env: {
10157
10089
  ...taskPlanningEnv(root, taskContract, acceptancePlan, devPlan),
10158
10090
  LOOP_SESSION_GENERATION: String(task.runtimeSessionGeneration ?? 0),
10091
+ LOOP_CONTEXT_POLICY: JSON.stringify(budgetPolicy),
10092
+ LOOP_RESUME_FILE: resumeFile,
10093
+ LOOP_CONTEXT_HANDOFF_FILE: contextPrefix + '.handoff.json',
10094
+ LOOP_CONTEXT_USAGE_FILE: contextPrefix + '.usage.json',
10095
+ LOOP_WORKER_OUTPUT_PREFIX: contextPrefix,
10159
10096
  LOOP_EXECUTION_TARGET_JSON: options.executionTarget
10160
10097
  ? JSON.stringify(options.executionTarget)
10161
10098
  : '',
@@ -10196,12 +10133,40 @@ export async function runQueueOnce(root, options) {
10196
10133
  finalStatus = 'superseded';
10197
10134
  }
10198
10135
  if (finalStatus === 'unknown') {
10199
- dispatchAttempts = await runDispatchWithRetry(root, options, queue, task, activeFile, runId, timeoutMs, runContext);
10136
+ dispatchAttempts = await runDispatchWithRetry(root, options, queue, task, activeFile, runId, timeoutMs, {
10137
+ ...runContext,
10138
+ hasBlockingCheckpoints: async () => {
10139
+ const reviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan);
10140
+ return selectEffectiveAcceptanceReviews(devPlan.plan, reviews, taskContract.contract)
10141
+ .some((review) => review.status === 'blocked');
10142
+ }
10143
+ });
10200
10144
  dispatch = dispatchAttempts[dispatchAttempts.length - 1]?.result ?? null;
10201
10145
  await destroyConsumedHumanInputSecrets(root, queue, task.id);
10202
- const dispatchClassification = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10146
+ let dispatchClassification = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10147
+ const usageReport = await readBoundedJson(contextPrefix + '.usage.json');
10148
+ if (usageReport?.taskId === task.id && usageReport.runId === runId && usageReport.generation === (task.runtimeSessionGeneration ?? 0) && usageReport.attempt === dispatchAttempts.at(-1)?.attempt) contextUsage = usageReport.usage;
10149
+ const handoff = await readBoundedJson(contextPrefix + '.handoff.json');
10150
+ if (!dispatch?.canceled && await exists(contextPrefix + '.handoff.json')) {
10151
+ const handoffValid = validHandoff(handoff, { taskId: task.id, runId, generation: task.runtimeSessionGeneration ?? 0, attempt: dispatchAttempts.at(-1)?.attempt });
10152
+ const proof = handoffValid ? await handoffCheckpoint(handoff, { root, checkpointsDir: path.join(root, devPlan.checkpointsDir), taskId: task.id, runId }) : { valid: false };
10153
+ if (!handoffValid || !proof.valid) {
10154
+ finalStatus = 'runtime_blocked';
10155
+ } else {
10156
+ contextHandoff = handoff;
10157
+ if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
10158
+ else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
10159
+ dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
10160
+ dispatchAttempts[dispatchAttempts.length - 1].failureClassification = dispatchClassification;
10161
+ }
10162
+ }
10163
+ }
10203
10164
  if (dispatch?.canceled) {
10204
10165
  finalStatus = 'superseded';
10166
+ } else if (finalStatus !== 'unknown') {
10167
+ // Invalid handoffs or unresolved authority/actions fail closed.
10168
+ } else if (dispatchClassification?.requiresHumanAction) {
10169
+ finalStatus = 'needs_human_input';
10205
10170
  } else if (dispatchClassification?.recoverableRuntime) {
10206
10171
  const recoveryCount = Number(task.runtimeRecoveryCount ?? 0);
10207
10172
  const recoveryMax = Number(options.retry?.runtimeRecoveryMaxAttempts ?? 2);
@@ -10336,16 +10301,21 @@ export async function runQueueOnce(root, options) {
10336
10301
  completedTask.projectContinuedAt = finishedAt;
10337
10302
  completedTask.projectContinuationCount = (task.projectContinuationCount ?? 0) + 1;
10338
10303
  completedTask.runtimeRecoveryCount = 0;
10339
- const sessionMaxTicks = Math.max(1, Number(options.retry?.sessionMaxTicks ?? 10));
10340
- if (completedTask.projectContinuationCount % sessionMaxTicks === 0) {
10304
+ completedTask.sessionTickCount = Number(task.sessionTickCount ?? 0) + 1;
10305
+ const rotation = contextRotation(contextUsage, completedTask.sessionTickCount, budgetPolicy);
10306
+ completedTask.contextBudget = rotation;
10307
+ if (rotation.rotate) {
10341
10308
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10309
+ completedTask.sessionTickCount = 0;
10342
10310
  completedTask.sessionRotatedAt = finishedAt;
10343
- completedTask.sessionRotationReason = 'bounded_tick_limit';
10311
+ completedTask.sessionRotationReason = rotation.reason;
10344
10312
  }
10345
10313
  }
10346
10314
  if (finalStatus === 'runtime_interrupted') {
10347
10315
  completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + 1;
10348
10316
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10317
+ completedTask.sessionTickCount = 0;
10318
+ if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
10349
10319
  completedTask.runtimeInterruptedAt = finishedAt;
10350
10320
  completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10351
10321
  }
@@ -10373,6 +10343,7 @@ export async function runQueueOnce(root, options) {
10373
10343
  status: finalStatus,
10374
10344
  ...(movedByOperator ? { movedByOperator: true } : {}),
10375
10345
  retry: options.retry ?? null,
10346
+ contextBudget: { policy: budgetPolicy, usage: contextUsage, handoff: contextHandoff ? path.relative(root, contextPrefix + '.handoff.json') : null },
10376
10347
  taskContract: taskContract ? {
10377
10348
  path: taskContract.file,
10378
10349
  riskLevel: taskContract.contract.risk_level,