taskforce-loop-engineering 0.16.3 → 0.16.5

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.
@@ -7,6 +7,16 @@ import { execFileSync } from 'node:child_process';
7
7
  import { enqueueTask, runCommand, runQueueOnce } from '../lib/core.mjs';
8
8
  import { runIsolatedVerification, validateIsolatedVerification } from '../lib/isolated-verification.mjs';
9
9
 
10
+ // These tests drive the real sandbox. Say what is missing instead of failing
11
+ // later on an unrelated file read.
12
+ const missingTools = process.platform !== 'linux' ? ['Linux'] : ['bwrap', 'strace', 'python3'].filter((tool) => {
13
+ try { execFileSync('sh', ['-c', `command -v ${tool}`], { stdio: 'ignore' }); return false; } catch { return true; }
14
+ });
15
+ if (missingTools.length) {
16
+ console.error(`isolated verification self-test needs ${missingTools.join(', ')} (Debian/Ubuntu: apt-get install bubblewrap strace python3). Set LOOP_SKIP_ISOLATION_TESTS=1 to skip it on machines that cannot run the sandbox.`);
17
+ process.exit(process.env.LOOP_SKIP_ISOLATION_TESTS === '1' ? 0 : 1);
18
+ }
19
+
10
20
  const base = await mkdtemp(path.join(tmpdir(), 'loop-isolation-self-test-'));
11
21
  const quote = (value) => "'" + String(value).replaceAll("'", "'\"'\"'") + "'";
12
22
  const run = async (project, command, inputs, label, runtimeFiles = []) => {
@@ -28,7 +38,7 @@ await writeFile(path.join(pythonProject, 'input.txt'), 'hello\n');
28
38
  await writeFile(path.join(pythonProject, 'hidden.txt'), 'private\n');
29
39
  const python = await run(pythonProject, 'cat input.txt > /out/result.txt', ['input.txt'], 'python-pass');
30
40
  assert.equal(python.result.exitCode, 0, JSON.stringify(python.terminal) + '\n' +
31
- (await readFile(path.join(base, 'python-pass', 'stderr.log'), 'utf8')).slice(0, 500));
41
+ (await readFile(path.join(base, 'python-pass', 'stderr.log'), 'utf8').catch(() => '')).slice(0, 500));
32
42
  assert.equal(python.terminal.status, 'passed');
33
43
  assert.equal((await readFile(path.join(base, 'python-pass', 'output', 'result.txt'), 'utf8')).trim(), 'hello');
34
44
 
@@ -188,6 +198,11 @@ for (const [label, command, expected] of [
188
198
  ['double-slash', 'cat //work/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
189
199
  ['missing-alias', 'cat //work/../work/missing.txt 2>/dev/null || true', 'passed'],
190
200
  ['file-alias', 'cat ../work/input.txt/../hidden.txt 2>/dev/null || true', 'passed'],
201
+ ['symlink-tmp', 'ln -s /work /tmp/w; cat /tmp/w/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
202
+ ['symlink-out', 'ln -s /work /out/w; cat /out/w/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
203
+ ['symlink-renamed', 'ln -s /work /tmp/a; mv /tmp/a /tmp/b; cat /tmp/b/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
204
+ ['symlink-missing', 'ln -s /work /tmp/w; cat /tmp/w/missing.txt 2>/dev/null || true', 'passed'],
205
+ ['task-alias', 'cat /proc/self/task/$$/cwd/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
191
206
  ]) {
192
207
  await enqueueTask(queueProject, { queue: 'path-' + label, title: label, task: 'Verify path semantics' });
193
208
  const outcome = await runQueueOnce(queueProject, { queue: 'path-' + label, dispatcher: 'true',
@@ -198,4 +213,18 @@ for (const [label, command, expected] of [
198
213
  if (expected !== 'passed') assert.equal(outcome.status, 'verify_failed');
199
214
  }
200
215
 
201
- console.log('isolated verification: two projects passed; undeclared input and forged trace rejected');
216
+ // The sandbox holds no capabilities even when the host runs as root: it can
217
+ // neither remount the read-only system binds nor read root-only host files.
218
+ const privileges = await run(pythonProject, "grep CapEff /proc/self/status > /out/caps.txt; " +
219
+ "mount -o remount,rw,bind /usr 2>/dev/null && touch /usr/.loop-isolation-probe 2>/dev/null; " +
220
+ "cat /etc/shadow > /out/shadow.txt 2>/dev/null; true", ['input.txt'], 'privileges');
221
+ assert.equal(privileges.terminal.status, 'passed', JSON.stringify(privileges.terminal));
222
+ assert.match(await readFile(path.join(base, 'privileges', 'output', 'caps.txt'), 'utf8'), /CapEff:\s+0+\s*$/);
223
+ assert.equal(await readFile('/usr/.loop-isolation-probe').then(() => true, () => false), false, 'the sandbox wrote the host /usr');
224
+ assert.equal((await readFile(path.join(base, 'privileges', 'output', 'shadow.txt'), 'utf8').catch(() => '')).length, 0, 'the sandbox read /etc/shadow');
225
+
226
+ // A failed isolation says why.
227
+ const reasoned = await run(pythonProject, 'cat hidden.txt >/dev/null 2>&1 || true', ['input.txt'], 'reason');
228
+ assert.match(reasoned.result.isolation.reason, /read audit failed: undeclared available project input/);
229
+
230
+ console.log('isolated verification: two projects passed; undeclared input, aliases, forged trace and privileges rejected');
@@ -131,3 +131,35 @@ with tempfile.TemporaryDirectory() as tmp:
131
131
  trace.write_text(f'1 access("{name}", R_OK) = -1 ENOENT (missing)\n')
132
132
  assert not module.trace_verdict(trace, {}, root, {})[0]
133
133
  print('self cwd/root aliases and unknown fd/process alias regressions passed')
134
+
135
+ with tempfile.TemporaryDirectory() as tmp:
136
+ root = Path(tmp)
137
+ (root / 'hidden.txt').write_text('hidden')
138
+ (root / 'sub').mkdir()
139
+ trace = root / 'trace'
140
+ # Symlinks the sandbox creates in /tmp or /out are followed by the audit,
141
+ # including after a rename and with relative targets.
142
+ for setup, probe, allowed in [
143
+ ('1 symlink("/work", "/tmp/w") = 0\n', '/tmp/w/hidden.txt', False),
144
+ ('1 symlinkat("../work", AT_FDCWD</tmp>, "rel") = 0\n', '/tmp/rel/hidden.txt', False),
145
+ ('1 symlink("/work", "/out/w") = 0\n1 rename("/out/w", "/tmp/moved") = 0\n', '/tmp/moved/hidden.txt', False),
146
+ ('1 symlink("/work", "/tmp/w") = 0\n', '/tmp/w/missing.txt', True),
147
+ ('1 symlink("/usr", "/tmp/u") = 0\n', '/tmp/u/hidden.txt', True),
148
+ ]:
149
+ trace.write_text('1 chdir("/work") = 0\n' + setup + f'1 access("{probe}", R_OK) = -1 ENOENT (missing)\n')
150
+ ok, errors = module.trace_verdict(trace, {}, root, {})
151
+ assert ok == allowed, (setup, probe, errors)
152
+ # Another thread's view cannot be proven to be this process's cwd/root.
153
+ for name in ['/proc/self/task/7/cwd/hidden.txt', '/proc/self/task/7/root/work/hidden.txt']:
154
+ trace.write_text(f'1 chdir("/work") = 0\n1 access("{name}", R_OK) = -1 ENOENT (missing)\n')
155
+ assert not module.trace_verdict(trace, {}, root, {})[0], name
156
+ # Calls that never return when the PID namespace is torn down are not
157
+ # unfinished file syscalls; an unfinished open still fails.
158
+ teardown = ('1 chdir("/work") = 0\n2 wait4(-1, <unfinished ...>\n3 exit_group(0) = ?\n'
159
+ '2 <... wait4 resumed> <unfinished ...>) = ?\n2 +++ killed by SIGKILL +++\n'
160
+ '4 exit_group(0 <unfinished ...>\n4 +++ killed by SIGKILL +++\n')
161
+ trace.write_text(teardown)
162
+ assert module.trace_verdict(trace, {}, root, {}) == (True, []), module.trace_verdict(trace, {}, root, {})
163
+ trace.write_text('1 chdir("/work") = 0\n5 openat(AT_FDCWD</work>, "hidden.txt", O_RDONLY <unfinished ...>\n5 +++ killed by SIGKILL +++\n')
164
+ assert not module.trace_verdict(trace, {}, root, {})[0]
165
+ print('created symlinks, task aliases and namespace teardown regressions passed')
@@ -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()
@@ -0,0 +1,105 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { writeAcceptanceReviews, buildFinalJudgement, enqueueTask, runQueueOnce } from '../lib/core.mjs';
7
+
8
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-revision-coverage-'));
9
+ const contract = { task_id: 'coverage-task', task_scope: 'project', requires_human_gate: false };
10
+ const plan = { checkpoints: [{ id: 'stable' }] };
11
+ const acceptance = { functional_checks: [], regression_checks: [], negative_tests: [], edge_cases: [], manual_review: [], automation: [], rubric: [] };
12
+ const phase = id => ({ task_id: contract.task_id, checkpoint_id: id, milestone_id: 'stable', status: 'in_progress', summary: 'Phase completed; integration pending', verification: ['phase test passed'], risks: ['integration pending'], blockers: [], project_completion: { status: 'in_progress' } });
13
+ const history = [phase('p1'), phase('p2'), phase('p3')];
14
+ const bytes = cp => JSON.stringify(cp);
15
+ const digest = cp => createHash('sha256').update(bytes(cp)).digest('hex');
16
+ const final = () => ({ ...phase('done'), sequence: 4, status: 'ready_for_acceptance', summary: 'Integration completed', risks: [], verification: ['integration test passed'], project_completion: { status: 'accepted' }, revises_checkpoint_id: 'p3', revision_coverage: history.map(cp => ({ checkpoint_id: cp.checkpoint_id, checkpoint_sha256: digest(cp), resolution: 'Integrated and verified this phase', verification: ['integration test passed'] })) });
17
+ let cases = 0;
18
+ try {
19
+ async function judge(name, records) {
20
+ const dir = path.join(root, name);
21
+ await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
22
+ await mkdir(path.join(dir, 'reviews'));
23
+ for (const [i, cp] of records.entries()) await writeFile(path.join(dir, 'checkpoints', `${i}.json`), typeof cp === 'string' ? cp : bytes(cp));
24
+ const reviews = await writeAcceptanceReviews(dir, 'disposable', { id: contract.task_id }, { contract }, { plan: acceptance }, { plan, checkpointsDir: 'checkpoints', reviewsDir: 'reviews' }, { persist: false });
25
+ cases++;
26
+ return buildFinalJudgement(contract, acceptance, plan, { count: records.length }, reviews, { dispatchStatus: 'completed' });
27
+ }
28
+ assert.equal((await judge('complete', [...history, final()])).outcome, 'ready_to_apply');
29
+ assert.equal((await judge('reverse-order', [final(), ...history.toReversed()])).outcome, 'ready_to_apply');
30
+ for (const [name, mutate] of [
31
+ ['no-coverage', cp => { delete cp.revision_coverage; }],
32
+ ['partial', cp => { cp.revision_coverage.pop(); }],
33
+ ['stale-digest', cp => { cp.revision_coverage[0].checkpoint_sha256 = 'old'; }],
34
+ ['unknown-target', cp => { cp.revision_coverage[0].checkpoint_id = 'missing'; }],
35
+ ['no-resolution', cp => { cp.revision_coverage[0].resolution = ''; }],
36
+ ['no-evidence', cp => { cp.revision_coverage[0].verification = []; }],
37
+ ['unbound-evidence', cp => { cp.revision_coverage[0].verification = ['invented verification']; }],
38
+ ['rename', cp => { cp.milestone_id = 'renamed'; }],
39
+ ['different-task', cp => { cp.task_id = 'other'; }],
40
+ ['duplicate-coverage', cp => { cp.revision_coverage.push(cp.revision_coverage[0]); }],
41
+ ['malformed-coverage', cp => { cp.revision_coverage = {}; }]
42
+ ]) {
43
+ const cp = final(); mutate(cp);
44
+ assert.equal((await judge(name, [...history, cp])).outcome, 'needs_revision', name);
45
+ }
46
+ for (const [name, patch, expected] of [
47
+ ['real-defect', { status: 'needs_revision' }, 'needs_revision'],
48
+ ['invalid-phase-coverage', { revision_coverage: [{ checkpoint_id: 'missing' }] }, 'needs_revision'],
49
+ ['missing-verification', { verification: [] }, 'needs_revision'],
50
+ ['missing-summary', { summary: '' }, 'needs_revision'],
51
+ ['different-milestone', { milestone_id: 'other' }, 'needs_revision'],
52
+ ['human-gate', { status: 'needs_human_input', blockers: ['Owner approval required'] }, 'blocked'],
53
+ ['reversed-clock', { sequence: 5 }, 'needs_revision']
54
+ ]) {
55
+ const records = structuredClone(history); Object.assign(records[0], patch);
56
+ const cp = final(); cp.revision_coverage[0].checkpoint_sha256 = digest(records[0]);
57
+ assert.equal((await judge(name, [...records, cp])).outcome, expected, name);
58
+ }
59
+ assert.equal((await judge('corruption', [...history, '{', final()])).outcome, 'needs_revision');
60
+ assert.equal((await judge('duplicate-id', [...history, history[0], final()])).outcome, 'needs_revision');
61
+ // Ordered unrelated failure must survive even without the coverage protocol.
62
+ const unrelated = { ...phase('unrelated'), milestone_id: 'other', sequence: 1, status: 'needs_revision' };
63
+ const done = final(); delete done.revision_coverage;
64
+ assert.equal((await judge('ordered-cross-scope', [unrelated, done])).outcome, 'needs_revision');
65
+ const renamed = { ...done, milestone_id: 'renamed' };
66
+ assert.equal((await judge('renamed-terminal', [renamed])).outcome, 'needs_revision');
67
+ // Invalid coverage must not silently use clocks instead.
68
+ const ordered = history.map((cp, i) => ({ ...cp, sequence: i + 1 }));
69
+ assert.equal((await judge('invalid-coverage-with-clocks', [...ordered, final()])).outcome, 'needs_revision');
70
+ console.log(`revision coverage self-test passed (${cases} cases)`);
71
+ } finally {
72
+ await rm(root, { recursive: true, force: true });
73
+ }
74
+
75
+
76
+ // Exercise the same protocol through dispatch, final judgement and queue state.
77
+ for (const scenario of ['covered', 'uncovered', 'cross-scope', 'invalid-phase-coverage', 'blocked']) {
78
+ const queueRoot = await mkdtemp(path.join(tmpdir(), 'loop-coverage-queue-'));
79
+ try {
80
+ const { task } = await enqueueTask(queueRoot, { queue: 'probe', title: scenario, task: '开发完整项目并完成整体目标' });
81
+ const dir = path.join(queueRoot, 'runtime/loops/probe/tasks', task.id);
82
+ await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
83
+ const records = history.map(cp => ({ ...cp, task_id: task.id }));
84
+ if (scenario === 'cross-scope') records[0].milestone_id = 'unrelated';
85
+ if (scenario === 'invalid-phase-coverage') records[0].revision_coverage = [{ checkpoint_id: 'missing' }];
86
+ if (scenario === 'blocked') Object.assign(records[0], { status: 'needs_human_input', blockers: ['Owner approval required'] });
87
+ for (const cp of records) await writeFile(path.join(dir, 'checkpoints', cp.checkpoint_id + '.json'), bytes(cp));
88
+ await writeFile(path.join(dir, 'dev_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...plan }));
89
+ await writeFile(path.join(dir, 'acceptance_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...acceptance }));
90
+ const cp = { ...final(), task_id: task.id };
91
+ cp.revision_coverage.forEach((entry, i) => { entry.checkpoint_sha256 = digest(records[i]); });
92
+ if (scenario === 'uncovered') delete cp.revision_coverage;
93
+ const worker = path.join(queueRoot, 'worker.mjs');
94
+ await writeFile(worker, `import {writeFile} from 'node:fs/promises'; import path from 'node:path'; await writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, 'done.json'), ${JSON.stringify(bytes(cp))});`);
95
+ const options = { queue: 'probe', dispatcher: `${process.execPath} '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
96
+ const result = await runQueueOnce(queueRoot, options);
97
+ const effectiveContract = JSON.parse(await readFile(path.join(dir, 'task_contract.json'), 'utf8'));
98
+ const expected = scenario === 'covered' ? (effectiveContract.requires_human_gate ? 'ready_for_human_review' : 'ready_to_apply') : scenario === 'blocked' ? 'blocked' : 'needs_revision';
99
+ assert.equal(result.run.finalJudgement.outcome, expected, scenario);
100
+ assert.equal((await runQueueOnce(queueRoot, options)).processed, false, 'terminal or revision queue must not replay');
101
+ console.log(JSON.stringify({ test: 'revision-coverage-queue', scenario, outcome: expected, node: process.version, replay: false }));
102
+ } finally {
103
+ await rm(queueRoot, { recursive: true, force: true });
104
+ }
105
+ }
@@ -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 }), {
@@ -189,6 +189,8 @@ For a project-level objective:
189
189
  5. Continue through implementation, verification, revisions, and the next actionable backlog item within the authorized safety boundary.
190
190
  6. Stop only when total project acceptance passes, or a genuine human authorization/product decision/external-state blocker prevents meaningful progress.
191
191
 
192
+ For project continuations (explicit or inferred scope), preserve worker-authored plans and reread durable plans after dispatch. Progress means a committed milestone newly passes acceptance, including repairing an existing failed milestone; extra checkpoint files or re-emitting accepted milestones do not count. Accepted progress must match durable checkpoint/milestone identity even for a single planned milestone; changing only the plan ID cannot transfer old acceptance to new work. A no-progress continuation stops for revision instead of requeueing. Acceptance refresh re-evaluates changed plans and rebuilds legacy judgements missing coverage once.
193
+
192
194
  Never silently narrow a complete-project request into “first milestone” and call that the Loop complete. A single queue task or milestone may be complete while the project remains active.
193
195
 
194
196
  Recommended commands:
@@ -307,7 +309,7 @@ For L2 code-changing tasks, prefer isolated worktrees. The runner prepares revie
307
309
 
308
310
  Before enabling or diagnosing this backend, follow [frozen-input verification](references/frozen-input-verification.md) for prerequisites, receipt checks and compatibility boundaries.
309
311
 
310
- For Linux code queues whose verification must not read the shared project tree, use the opt-in `worktree.isolatedVerification` backend described in [isolated verification](../../docs/isolated-verification.md). Declare the exact project inputs and any user-local runtime files before running the gate. Frozen project files preserve permission bits, which are included in input identity; mode-only changes invalidate stability. Failed undeclared file accesses remain failures from nested working directories even if the command swallows the error. Treat missing/failed receipts, undeclared reads, changed input digests between commands, or unsupported host isolation as `verify_failed`; a zero command exit alone is not acceptance evidence. This generic backend does not cover browser profiles, Docker/Git replay, networked checks, or undeclared dynamic dependencies. Keep those on a separately reviewed project-specific gate until explicitly enrolled and proven; do not silently fall back to ordinary `verifyCommands`.
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`.
311
313
 
312
314
  Safe review flow:
313
315
 
@@ -373,3 +375,18 @@ Before saying a loop is finished, verify:
373
375
  - Are evidence paths and next actions included?
374
376
 
375
377
  If any project requirement remains, report a phase/task result and continue with the next authorized item; do not claim the project or Loop is complete.
378
+
379
+ ### Invalid checkpoint baseline repair
380
+
381
+ Pre-dispatch review treats malformed JSON and non-object checkpoint roots as explicit invalid evidence, not empty accepted coverage. A bounded worker may repair the local record, but an unknown dispatch baseline is persisted as `invalid_checkpoint_baseline` and prevents automatic acceptance/continuation, including after acceptance refresh. Repair success is not proof of new milestone progress: use an explicit revision from validated history. Unrepaired invalid evidence cannot be superseded by a terminal snapshot. Human blockers take precedence; gate reconciliation leaves all gates unchanged while any checkpoint is invalid. Filesystem/permission failures are not classified as repairable JSON corruption. This conservative path may require an additional explicit revision even after a successful repair; it must not replay automatically.
382
+
383
+ ### Normal context handoff versus runtime recovery
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, 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
+
387
+
388
+ ### Explicit closure of unordered phase checkpoints
389
+
390
+ New checkpoints must carry stable `task_id`/`milestone_id`, a monotonic `sequence` and checkpoint-owned `created_at`; do not invent clocks for historical records. `revises_checkpoint_id` is lineage only, not proof that every older snapshot is resolved. A final accepted checkpoint can close unordered, status-only `in_progress` records with `revision_coverage`: one entry per old record containing `checkpoint_id`, SHA-256 of the exact checkpoint bytes in `checkpoint_sha256`, a concrete `resolution`, and nonempty `verification` strings also present in the final checkpoint's verification array. Same-task and same-planned-milestone identity must match. Preserve historical files.
391
+
392
+ Coverage cannot close real failed checks, missing evidence, corruption, duplicate identities, human blockers or deferred gates. A phase that itself declares revision coverage is not a plain status-only target: its invalid declaration cannot be laundered away by a later coverage edge. Invalid coverage remains a revision failure even if clocks otherwise order the records. Uncovered unordered history remains effective. Different explicit milestone identities never supersede each other by time alone; legacy unlabelled single-plan chronology remains supported. Evidence references are cooperative claims, not independent proof of test execution: review the actual artifacts before emitting final coverage.
@@ -5,7 +5,7 @@
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
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.
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
- 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. Consecutive runtime recoveries (including voluntary handoffs) share `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Accepted project progress resets that recovery counter.
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.
10
10
 
11
11
  Validate with `node scripts/context-budget-self-test.mjs` and `node scripts/openclaw-install-self-test.mjs` in a source checkout. Use disposable queues and mocked workers; do not probe production queues or paid providers for these tests.
@@ -9,7 +9,7 @@ For example, “Complete the project-level objective, not just the first bounded
9
9
  ## Inspect effective reviews and gates
10
10
 
11
11
  - Read checkpoint reviews, task gates and `final_judgement.json` together. Checkpoint sequence and creation time establish chronology; filename numbering and regenerated review timestamps do not. Missing or conflicting ordering must not erase a live blocker.
12
- - For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews. Multiple planned milestones still require their effective reviews.
12
+ - For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews unless explicit validated revision coverage closes status-only phases as described below. Different explicit milestone identities never supersede each other by chronology. Multiple planned milestones still require their effective reviews.
13
13
  - A task terminal result is not project completion or deployment authorization. Inspect the original completion contract and project backlog independently.
14
14
  - Reconcile a consumed gate only through the recorded same-task successor link, `revises_checkpoint_id`. A satisfied gate records the successor, not proof that the successor passed acceptance. Check the effective review and final queue state separately.
15
15
  - Effective human/authority blockers and uncertain external outcomes remain `needs_human_input`, including after ordinary worker failure; do not turn them into development revisions or automatic retries. Resolved historical blockers do not permanently veto continuation.
@@ -17,3 +17,13 @@ For example, “Complete the project-level objective, not just the first bounded
17
17
  ## Evidence boundaries
18
18
 
19
19
  Inspect artifacts rather than dispatcher exit status. A checkpoint accepted by the worker is not the outer queue's final judgement; `ready_to_apply` is not applied. For multiple PRs, test each exact candidate and a correctly constructed combined tree separately. Local tests, exact-HEAD remote CI, package installation and live-instance acceptance are distinct claims.
20
+
21
+ ## Explicit status-only phase closure
22
+
23
+ An accepted final checkpoint may close unordered `in_progress` phases through `revision_coverage`: each entry binds `checkpoint_id`, `checkpoint_sha256` (exact historical bytes), concrete `resolution`, and nonempty verification strings present in the final checkpoint. Require unique same-task, same-planned-milestone records, and reject reversed known clocks. Keep historical files unchanged. `revises_checkpoint_id` alone is lineage, not this coverage proof.
24
+
25
+ Coverage cannot close real defects, missing evidence, corruption, duplicate identities, human blockers, deferred gates, or a phase that itself declares coverage. Invalid coverage remains a failure regardless of chronological ordering. Inspect actual verification artifacts; references are cooperative claims.
26
+
27
+ ## Continuation and invalid history
28
+
29
+ Progress is newly accepted durable milestone identity, not renamed plans, extra files or repeated accepted snapshots. Preserve explicit and inferred project plans. Malformed/non-object checkpoints may receive a bounded repairing dispatch, but unknown pre-dispatch history persists as `invalid_checkpoint_baseline`, blocks automatic acceptance, and requires explicit revision from validated history. Gate reconciliation leaves gates unchanged while any checkpoint is invalid. Filesystem errors are not JSON corruption.