taskforce-loop-engineering 0.16.4 → 0.16.6

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.
@@ -162,7 +162,7 @@ def resolve_failed_process_alias(raw_name, cwd):
162
162
  Keep the suffix raw so missing ancestors and trailing slash semantics are
163
163
  still checked by available_project_attempt, not erased by normpath.
164
164
  """
165
- alias = r'/proc/(self|thread-self|[0-9]+)/(cwd|root|fd)(?=/|$)|/dev/fd(?=/|$)'
165
+ alias = r'/proc/(self|thread-self|[0-9]+)(/task/[0-9]+)?/(cwd|root|fd)(?=/|$)|/dev/fd(?=/|$)'
166
166
  value = '/' + raw_name.lstrip('/')
167
167
  for _ in range(8):
168
168
  match = re.match(alias, value)
@@ -170,9 +170,11 @@ def resolve_failed_process_alias(raw_name, cwd):
170
170
  if re.match(alias, '/' + posixpath.normpath(value).lstrip('/')):
171
171
  raise ValueError('unresolved dynamic alias traversal')
172
172
  return value
173
- if match[1] not in ('self', 'thread-self') or match[2] == 'fd':
173
+ # /proc/<pid>/task/<tid>/... names another thread's view; it cannot be
174
+ # proven to be this process's cwd/root, so it fails closed.
175
+ if match[1] not in ('self', 'thread-self') or match[2] or match[3] == 'fd':
174
176
  raise ValueError('unresolved dynamic fd or process alias')
175
- base = cwd if match[2] == 'cwd' else '/'
177
+ base = cwd if match[3] == 'cwd' else '/'
176
178
  if base is None:
177
179
  raise ValueError('unknown cwd for process alias')
178
180
  value = base.rstrip('/') + value[match.end():]
@@ -181,20 +183,62 @@ def resolve_failed_process_alias(raw_name, cwd):
181
183
  raise ValueError('recursive process alias traversal')
182
184
 
183
185
 
186
+ def resolve_recorded_symlinks(raw_name, symlinks):
187
+ """Rewrite a path through symlinks the sandbox created itself.
188
+
189
+ /tmp and /out start empty, so every symlink there was made by a traced
190
+ symlink/symlinkat call. Without this, `ln -s /work /tmp/w; cat
191
+ /tmp/w/hidden.txt` would probe an undeclared input unseen.
192
+ """
193
+ value = '/' + posixpath.normpath(raw_name).lstrip('/')
194
+ rewritten = False
195
+ for _ in range(16):
196
+ for link in sorted(symlinks, key=len, reverse=True):
197
+ if value == link or value.startswith(link + '/'):
198
+ value = '/' + posixpath.normpath(symlinks[link] + value[len(link):]).lstrip('/')
199
+ rewritten = True
200
+ break
201
+ else:
202
+ # Untouched paths keep their raw form, so missing-ancestor and
203
+ # trailing-slash semantics are still checked by the walk.
204
+ return value if rewritten else raw_name
205
+ raise ValueError('recursive symlink traversal')
206
+
207
+
208
+ # Calls that may legitimately never complete when their process is killed
209
+ # (its own exit, or waiting on children during PID-namespace teardown).
210
+ NON_FILE_TERMINAL_CALLS = ('exit', 'exit_group', 'wait4', 'waitid')
211
+
212
+
184
213
  def trace_verdict(trace, declared, root, runtime_files):
185
214
  if not trace.exists() or trace.stat().st_size == 0:
186
215
  return False, ['missing read trace']
187
216
  violations, pending, events = [], {}, []
188
- written, cwds = set(), {}
217
+ written, cwds, symlinks = set(), {}, {}
189
218
  # Keep syscall entry order: a child can execute before clone's resumed line.
190
219
  for line in trace.read_text(errors='surrogateescape').splitlines():
191
220
  pid = line.split(maxsplit=1)[0] if line.strip() else ''
221
+ # A process killed while a call that touches no file was returning is
222
+ # logged as "<... wait4 resumed> <unfinished ...>) = ?"; that closes
223
+ # the pending call rather than starting an overlapping one.
224
+ killed_resume = re.search(r'<\.\.\. (\w+) resumed> <unfinished \.\.\.>', line)
225
+ if killed_resume and killed_resume.group(1) in NON_FILE_TERMINAL_CALLS and pid in pending:
226
+ pending.pop(pid)
227
+ continue
192
228
  if '<unfinished ...>' in line:
193
229
  if pid in pending:
194
230
  violations.append('overlapping file syscall')
195
231
  pending[pid] = (len(events), line.split('<unfinished ...>', 1)[0])
196
232
  events.append(None)
197
233
  continue
234
+ # A process killed while blocked in a call that never returns (its own
235
+ # exit, or waiting for a child when the PID namespace is torn down)
236
+ # leaves that call unfinished. Those calls touch no file; an unfinished
237
+ # file syscall still fails below.
238
+ if re.match(r'^\S+\s+\+\+\+ (exited|killed)', line) and pid in pending:
239
+ name = re.match(r'^\S+\s+(\w+)\(', pending[pid][1])
240
+ if name and name.group(1) in NON_FILE_TERMINAL_CALLS:
241
+ pending.pop(pid)
198
242
  resumed = re.search(r'<\.\.\. \w+ resumed>', line)
199
243
  if resumed:
200
244
  prior = pending.pop(pid, None)
@@ -218,6 +262,28 @@ def trace_verdict(trace, declared, root, runtime_files):
218
262
  if not cwds:
219
263
  cwds[pid] = [str(root)]
220
264
  state = cwds.setdefault(pid, [None])
265
+ if syscall in ('symlink', 'symlinkat', 'rename', 'renameat', 'renameat2') and result == 0:
266
+ # Record symlinks the sandbox creates (and moves) so failed probes
267
+ # through them are audited at their real target.
268
+ try:
269
+ strings = [decode_trace_string(item) for item in re.findall(r'"((?:[^"\\]|\\.)*)"', args)]
270
+ directories = [decode_trace_string(item) for item in re.findall(r'(?:AT_FDCWD|\d+)<([^<>]+)>', args)]
271
+ def absolute(path, base):
272
+ return '/' + posixpath.normpath(path if path.startswith('/') else posixpath.join(base or state[0] or '/', path)).lstrip('/')
273
+ if syscall.startswith('symlink'):
274
+ link = absolute(strings[-1], directories[-1] if directories else None)
275
+ if link == '/newroot' or link.startswith('/newroot/'):
276
+ continue # bwrap building the sandbox, before /work exists
277
+ target = strings[0] if strings[0].startswith('/') else posixpath.join(posixpath.dirname(link), strings[0])
278
+ symlinks[link] = '/' + posixpath.normpath(target).lstrip('/')
279
+ else:
280
+ old = absolute(strings[0], directories[0] if directories else None)
281
+ new = absolute(strings[1], directories[-1] if directories else None)
282
+ for link in [key for key in symlinks if key == old or key.startswith(old + '/')]:
283
+ symlinks[new + link[len(old):]] = symlinks.pop(link)
284
+ except (ValueError, UnicodeError, IndexError):
285
+ violations.append('unresolved symlink bookkeeping')
286
+ continue
221
287
  if syscall in ('clone', 'clone3', 'fork', 'vfork') and result > 0:
222
288
  host_pid = re.search(r"=\s+\d+ /\* (\d+) in strace's PID NS \*/", line)
223
289
  child_pid = host_pid[1] if host_pid else str(result)
@@ -261,6 +327,8 @@ def trace_verdict(trace, declared, root, runtime_files):
261
327
  if raw_name:
262
328
  try:
263
329
  raw_name = resolve_failed_process_alias(raw_name, state[0])
330
+ if symlinks:
331
+ raw_name = resolve_recorded_symlinks(raw_name, symlinks)
264
332
  name = '/' + posixpath.normpath(raw_name).lstrip('/')
265
333
  except ValueError as exc:
266
334
  violations.append(str(exc))
@@ -300,6 +368,21 @@ def trace_verdict(trace, declared, root, runtime_files):
300
368
  return not violations, violations[:30]
301
369
 
302
370
 
371
+ # Root-only secrets in the read-only /etc bind. A root supervisor masks them,
372
+ # because the sandbox identity owns root's files even without capabilities.
373
+ SECRET_SYSTEM_PATHS = ("/etc/shadow", "/etc/shadow-", "/etc/gshadow", "/etc/gshadow-", "/etc/sudoers",
374
+ "/etc/sudoers.d", "/etc/ssl/private", "/etc/ssh/ssh_host_rsa_key", "/etc/ssh/ssh_host_ecdsa_key",
375
+ "/etc/ssh/ssh_host_ed25519_key", "/etc/ssh/ssh_host_dsa_key")
376
+
377
+
378
+ class SupervisorTerminated(Exception):
379
+ pass
380
+
381
+
382
+ def _terminated(signum, frame):
383
+ raise SupervisorTerminated("supervisor terminated by signal %d" % signum)
384
+
385
+
303
386
  def main():
304
387
  parser = argparse.ArgumentParser()
305
388
  parser.add_argument("--root", required=True)
@@ -309,6 +392,12 @@ def main():
309
392
  parser.add_argument("--evidence", required=True)
310
393
  parser.add_argument("--timeout", type=int, default=300)
311
394
  args = parser.parse_args()
395
+ # The budget covers the whole run, freezing included, so the caller's own
396
+ # timeout (a little longer) never fires first. If it is killed anyway,
397
+ # SIGTERM still tears down the traced sandbox, which runs in its own
398
+ # session and would otherwise be orphaned.
399
+ deadline = time.monotonic() + args.timeout
400
+ signal.signal(signal.SIGTERM, _terminated)
312
401
  root = Path(args.root).resolve(strict=True)
313
402
  evidence = Path(args.evidence).resolve()
314
403
  if evidence.exists():
@@ -354,18 +443,36 @@ def main():
354
443
  os.chmod(dest, before[name]["mode"])
355
444
  if inventory(snapshot, names) != before or inventory(root, names) != before:
356
445
  raise ValueError("inputs changed during freeze")
446
+ if time.monotonic() >= deadline:
447
+ raise TimeoutError("timeout expired while freezing inputs")
357
448
  record["snapshot_unchanged"] = True
358
449
  trace = evidence / "trace.log"
359
450
  output = evidence / "output"
360
451
  output.mkdir()
452
+ # bwrap started by root keeps every capability in its user namespace,
453
+ # so a command could remount the read-only system binds and write the
454
+ # host /usr or /etc. As root, drop them all (bwrap still configures the
455
+ # namespaces first). Running bwrap as an unprivileged identity instead
456
+ # is not portable: hosts that restrict unprivileged user namespaces
457
+ # (Ubuntu 23.10+) deny it the capabilities to set up loopback.
458
+ privileged = os.geteuid() == 0
459
+ record["sandbox_capabilities"] = "dropped" if privileged else "unprivileged"
361
460
  sandbox = [tools["bwrap"]["path"], "--die-with-parent", "--unshare-user", "--unshare-net",
362
- "--unshare-pid", "--unshare-ipc", "--unshare-uts",
461
+ "--unshare-pid", "--unshare-ipc", "--unshare-uts", *(["--cap-drop", "ALL"] if privileged else []),
363
462
  "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp",
364
463
  "--ro-bind", str(snapshot), "/work", "--bind", str(output), "/out",
365
464
  "--dir", "/home", "--setenv", "HOME", "/tmp", "--chdir", "/work"]
366
465
  for system in ("/usr", "/bin", "/lib", "/lib64", "/etc"):
367
466
  if Path(system).exists():
368
467
  sandbox += ["--ro-bind", system, system]
468
+ if privileged:
469
+ # Root-owned host files still belong to the sandbox identity, so
470
+ # mask the usual root-only secrets of the bound /etc.
471
+ for secret in SECRET_SYSTEM_PATHS:
472
+ candidate = Path(secret)
473
+ if candidate.is_symlink() or not candidate.exists():
474
+ continue
475
+ sandbox += ["--tmpfs", secret] if candidate.is_dir() else ["--ro-bind", "/dev/null", secret]
369
476
  if any(name.startswith("/opt/") for name in runtime_files):
370
477
  sandbox += ["--dir", "/opt"]
371
478
  for name in runtime_files:
@@ -379,12 +486,18 @@ def main():
379
486
  child = subprocess.Popen(invocation, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr,
380
487
  start_new_session=True, cwd=root, env={"PATH": "/usr/bin:/bin", "HOME": "/tmp", "LANG": "C.UTF-8"})
381
488
  try:
382
- record["exit_code"] = child.wait(timeout=args.timeout)
383
- except subprocess.TimeoutExpired:
489
+ record["exit_code"] = child.wait(timeout=max(0.1, deadline - time.monotonic()))
490
+ except (subprocess.TimeoutExpired, SupervisorTerminated) as exc:
384
491
  record["timed_out"] = True
385
- os.killpg(child.pid, signal.SIGTERM)
492
+ if isinstance(exc, SupervisorTerminated):
493
+ record["error"] = str(exc)
494
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
495
+ try:
496
+ os.killpg(child.pid, signal.SIGTERM)
497
+ except ProcessLookupError:
498
+ pass
386
499
  try:
387
- child.wait(timeout=5)
500
+ child.wait(timeout=0.5 if isinstance(exc, SupervisorTerminated) else 5)
388
501
  except subprocess.TimeoutExpired:
389
502
  os.killpg(child.pid, signal.SIGKILL)
390
503
  child.wait()
@@ -37,8 +37,19 @@ const firstDevPlan = await writeDevPlan(root, queue, checkpointTask, checkpointC
37
37
  assert.equal(firstDevPlan.plan.checkpoints[0].id, 'cp1');
38
38
  await writeJson(path.join(taskRuntimeDirFor(root, queue, checkpointTask.id), 'checkpoints', 'cp1.json'), { checkpoint_id: 'cp1' });
39
39
  const secondDevPlan = await writeDevPlan(root, queue, checkpointTask, checkpointContract, checkpointAcceptance);
40
- assert.equal(secondDevPlan.plan.checkpoints[0].id, 'cp2');
41
40
  assert.equal(secondDevPlan.plan.checkpoint_schema.checkpoint_id, 'cp2');
41
+ assert.equal(secondDevPlan.plan.checkpoints[0].output_file, 'checkpoints/cp2.json');
42
+ // The milestone identity survives replanning (revision, recovery, requeue), so
43
+ // the new checkpoint continues the same review chain...
44
+ assert.equal(secondDevPlan.plan.checkpoints[0].id, 'cp1');
45
+ assert.equal(secondDevPlan.plan.checkpoint_schema.milestone_id, 'cp1');
46
+ assert.equal(secondDevPlan.plan.checkpoint_schema.revises_checkpoint_id, 'cp1');
47
+ // ...and only moves on once the project continued after an accepted milestone.
48
+ await writeJson(path.join(taskRuntimeDirFor(root, queue, checkpointTask.id), 'checkpoints', 'cp2.json'), { checkpoint_id: 'cp2' });
49
+ const continuedDevPlan = await writeDevPlan(root, queue, { ...checkpointTask, projectContinuedAt: new Date().toISOString() }, checkpointContract, checkpointAcceptance);
50
+ assert.equal(continuedDevPlan.plan.checkpoints[0].id, 'cp3');
51
+ assert.equal(continuedDevPlan.plan.checkpoint_schema.milestone_id, 'cp3');
52
+ assert.equal(continuedDevPlan.plan.checkpoint_schema.revises_checkpoint_id, null);
42
53
 
43
54
  assert.equal(normalizeGoalDecision({ verdict: 'revise' }).decision, 'change_strategy');
44
55
  assert.deepEqual(goalLoopTransition({ decision: 'change_strategy' }, { round: 1, maxRounds: 3 }), {
@@ -128,7 +128,7 @@ The confirmed Hermes install creates the same Dashboard service and couples it t
128
128
  The generated worker uses `hermes -z` (`--oneshot`); the notifier uses `hermes send` without
129
129
  an LLM call. Preserve source metadata and pass `--source-target` in Hermes
130
130
  `platform:chat_id[:thread_id]` format. The managed systemd scheduler owns wakeups
131
- so durable queue continuity does not depend on resuming a Hermes Cron session.
131
+ so durable queue continuity does not depend on resuming a Hermes Cron session. After a package upgrade, rerun the Hermes doctor: it warns when a generated dispatcher, wrapper or notifier is out of date or was edited, and names the installer command that regenerates it (`--force` also rewrites the queue config, scheduler units and managed `AGENTS.md` block). Workers receive the dispatch timeout as `LOOP_TURN_TIMEOUT_MS` and should checkpoint and finish or hand off by about 80% of it.
132
132
 
133
133
  ## Cross-interface Human Gates
134
134
 
@@ -166,7 +166,7 @@ Pass the original request faithfully. Preserve source channel, target, account,
166
166
 
167
167
  ## Context Budget and Durable Handoff
168
168
 
169
- For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Keep one bounded objective per turn, read bounded file ranges, and save checkpoints instead of replaying transcripts. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
169
+ For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Finish as much of the current milestone per turn as fits, read bounded file ranges, and save checkpoints after verified sub-steps instead of replaying transcripts; splitting work into many tiny turns is slow, because each turn repeats planning, acceptance and scheduling. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
170
170
 
171
171
  ## Task vs Project Classification
172
172
 
@@ -250,7 +250,7 @@ Timeouts must terminate the spawned process group. After instrumentation timeout
250
250
  2. Classify task vs project and define the correct contract before execution.
251
251
  3. Use `route-message` or the installed conversation wrapper to preserve source metadata and apply immediate/queue-only/amend/supersede semantics.
252
252
  4. Run preflight before mutable work.
253
- 5. Execute one bounded tick or the project’s next actionable backlog item.
253
+ 5. Execute one tick for the task or the project’s next actionable backlog item, completing that item within the tick where possible.
254
254
  6. Emit ordered progress: planning, preflight, worker start, checkpoints, verification, acceptance, final judgement.
255
255
  7. Inspect run artifacts; never infer success only from dispatcher exit code.
256
256
  8. If acceptance fails, write a revision request with changed diagnosis/tactic/evidence/verification.
@@ -309,7 +309,7 @@ For L2 code-changing tasks, prefer isolated worktrees. The runner prepares revie
309
309
 
310
310
  Before enabling or diagnosing this backend, follow [frozen-input verification](references/frozen-input-verification.md) for prerequisites, receipt checks and compatibility boundaries.
311
311
 
312
- 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`.
312
+ 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 (including probes through symlinks the command creates), changed input digests between commands, or unsupported host isolation as `verify_failed`; a zero command exit alone is not acceptance evidence. The sandbox holds no capabilities (under a root supervisor bwrap gets `--cap-drop ALL` and root-only `/etc` secrets are masked; prefer a non-root supervisor for full separation); read the failure `reason` in the verification artifact before retrying. 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`.
313
313
 
314
314
  Safe review flow:
315
315
 
@@ -354,7 +354,7 @@ Summaries must cite the latest run/task/project evidence, verification performed
354
354
 
355
355
  ## Scheduler Policy
356
356
 
357
- Use scheduler ticks only after manual verification. Adaptive schedules may speed up with successful queued work and back off on empty queues, failures, long runs, or human gates.
357
+ Use scheduler ticks only after manual verification. Adaptive schedules may speed up with successful queued work and back off on empty queues, failures, long runs, or human gates. A project milestone that was accepted and continues, or a validated context handoff, is scheduled again the minimum interval after its run ends, without long-run headroom.
358
358
 
359
359
  `queue-scheduler-tick` is adaptive cadence logic, not a resident daemon. A cron, systemd timer, or equivalent external scheduler must wake it regularly. For project queues that promise automatic continuation, set `scheduler.required=true` and a bounded `scheduler.heartbeatMaxAge`; `doctor` must fail with `scheduler_missing` whenever queued work exists without a fresh scheduler heartbeat.
360
360
 
@@ -382,7 +382,7 @@ Pre-dispatch review treats malformed JSON and non-object checkpoint roots as exp
382
382
 
383
383
  ### Normal context handoff versus runtime recovery
384
384
 
385
- A valid successful handoff with nonempty, previously unseen checkpoint verification rotates the session without consuming or resetting runtimeRecoveryCount. Repeated verification (even with renamed checkpoints/new run IDs), empty verification and invalid handoffs stop; unresolved authority or external outcomes remain human blockers. Exception recovery remains capped independently. Verification fingerprints are cooperative progress evidence, not independent semantic proof: final task acceptance is still required. Keep checkpoint verification concrete and tied to the completed unit. When hotfixing an installed runner under explicit authority, stage/test the narrow patch separately, back up originals, and note existing processes retain already imported modules.
385
+ A valid successful handoff with nonempty, previously unseen checkpoint verification rotates the session without consuming or resetting runtimeRecoveryCount. Repeated verification (even with renamed checkpoints/new run IDs), empty verification and invalid handoffs stop, and consecutive handoffs stop at `retry.maxContextHandoffs` (default 10, reset when a milestone is accepted); unresolved authority or external outcomes remain human blockers and are copied into the final judgement and terminal notification. Exception recovery remains capped independently. Verification fingerprints are cooperative progress evidence, not independent semantic proof: final task acceptance is still required. Keep checkpoint verification concrete and tied to the completed unit. When hotfixing an installed runner under explicit authority, stage/test the narrow patch separately, back up originals, and note existing processes retain already imported modules.
386
386
 
387
387
 
388
388
  ### Explicit closure of unordered phase checkpoints
@@ -1,9 +1,9 @@
1
1
  # Context budget and recovery
2
2
 
3
3
  1. Inspect the installed OpenClaw dispatcher and queue `retry` configuration. New installations use `sessionMaxTicks: 3` and `contextBudget: { softRatio: 0.60, hardRatio: 0.75 }`. Existing explicit tick limits are retained until a reviewed integration upgrade. A package/skill update alone does not update generated workspace files. Hermes does not yet expose the OpenClaw telemetry adapter; do not claim equivalent telemetry protection there.
4
- 2. Keep one bounded objective per worker turn. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
4
+ 2. Complete as much of the current milestone as one worker turn allows, checkpointing after each verified sub-step; do not stop after a single small step, because every extra turn repeats planning, acceptance review and scheduling. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
5
5
  3. Read `LOOP_RESUME_FILE`, the task contract/plans, latest amendment and latest relevant checkpoint. Resolve relative references against its `workspaceRoot`. Read a previous handoff only for outstanding context; newer checkpoints and amendments take precedence. Do not reload complete transcripts or all historical checkpoints.
6
- 4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, use a small work unit rather than inventing a percentage. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
6
+ 4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, keep working through the milestone with frequent checkpoints and hand off only when the remaining work clearly will not fit the turn; never invent a percentage. The runner passes the dispatch timeout as `LOOP_TURN_TIMEOUT_MS`; by about 80% of it, stop starting new sub-steps, checkpoint and hand off, because a killed turn loses unsaved work and consumes a runtime recovery attempt while a validated handoff does not. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
7
7
  5. For unfinished work requiring a new session, write a normal progress checkpoint with `task_id`, `loop_run_id`, and `blockers`, then the bounded JSON handoff at `LOOP_CONTEXT_HANDOFF_FILE` using the schema provided in the worker prompt. Include task/run/generation/attempt binding, the checkpoint path, summary, completed and remaining work, evidence, next action, authority, pending external actions and blockers. Keep it under 16 KiB and omit secrets. The runner validates binding and a real checkpoint inside this task's checkpoint directory; missing/malformed/stale evidence stops recovery rather than accepting the task.
8
8
  6. Verify pending external, paid or destructive actions against durable receipts/reservations before replay. Uncertain outcomes and authority blockers stop automatic continuation, including when the worker exits nonzero. An existing handoff is checked before any retry; malformed or stale handoffs fail closed. A clean handoff never overrides a permission failure. Effective blocked checkpoint reviews are checked before each ordinary dispatch retry and also veto runtime recovery when interruption happens before handoff creation. Ordinary and verification failures with effective blockers remain `needs_human_input`, not development revisions; resolved historical blockers do not. Record checkpoint `created_at` (UTC) and, when known, a task-monotonic numeric `sequence`; checkpoint IDs and regenerated review timestamps are not ordering evidence. Conflicting or missing chronology preserves unresolved reviews rather than guessing from names. A newer unblocked snapshot with unambiguous chronology can resolve historical blockers. Multi-milestone plans use the same rule within each milestone and count each planned milestone only once. Terminal acceptance may ignore a chronologically later `needs_human_acceptance` project snapshot only if that review independently passes acceptance and carries no materializable deferred gates. The project label alone cannot hide a blocked/revise review; missing blocker details are not proof of broader-project-only governance. Test accepted terminal + later unknown external outcome under ordinary failure (one and multiple attempts), overflow, incomplete turn and exhausted recovery, including the generated dispatcher. The veto must prevent queue re-entry, not merely change the judgement report. A handoff cannot authorize an action. The runner preserves the task id and increments the session generation on a validated handoff or recognized context overflow; it never retries a known runtime interruption in the same session. Exception recoveries use `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Successful validated handoffs with nonempty, previously unseen checkpoint verification rotate without consuming or resetting this counter. Repeated or empty verification stops even if checkpoint/run IDs change. Verification fingerprints are cooperative evidence, not independent semantic proof. Accepted project progress resets the exception recovery counter.
9
9
  7. Inspect task/run artifacts after each tick. Accepted unfinished project milestones rotate at the soft/hard threshold or tick limit, whichever occurs first; completed tasks are never requeued just because usage is high. Handoffs remain `runtime_interrupted`, not completed. Full worker stdout/stderr stay in per-run/per-attempt logs; bounded tails plus deduplicated diagnostic signatures reach the runner. Signatures are matched across the complete stream before clipping (including split UTF-8 chunks), using the queue's configured patterns; human-action classification retains priority over runtime recovery. CLI JSON parsing is capped at 2 MiB. No protection here guarantees that one tool-heavy turn cannot overflow: worker discipline and the underlying runtime's compaction remain necessary.