taskforce-loop-engineering 0.16.4 → 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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.16.5 - 2026-11-02
6
+
7
+ Security and correctness release for 0.16.1–0.16.4. Publication does not upgrade installed CLIs or generated integrations; re-run `loop-engineering-openclaw-manage --action upgrade --confirm-upgrade` (Hermes: rerun the installer with `--confirm-install --force`).
8
+
9
+ - Keep a task's milestone identity across revision rounds, runtime and orphan recovery and operator requeues; it only advances after an accepted milestone continues the project. The 0.16.1–0.16.4 template renamed the milestone on every dispatch, so a bounded task revised along the template could never be accepted and a resolved historical blocker vetoed it. Checkpoints that declare `revises_checkpoint_id` now join the chain they revise, which also repairs records written by those versions.
10
+ - A project run recovered after a runtime interruption no longer fails as "no new accepted milestone" or "accepted checkpoints do not cover required": work written by the interrupted run counts as progress (recovery stays bounded by `retry.runtimeRecoveryMaxAttempts`).
11
+ - Cap consecutive context handoffs (`retry.maxContextHandoffs`, default 10, reset when a milestone is accepted): a worker whose verification evidence differed every turn (e.g. a run-specific log path) could hand off forever, starting a new paid session each tick.
12
+ - Blockers and uncertain external actions written only in a context handoff are now recorded in the final judgement (`handoff_blockers`, `handoff_pending_actions`, reasons and next actions) and listed in the terminal notification. A handoff is passed only to the session right after it, so a later session is no longer shown an out-of-date `nextAction`.
13
+ - Scope inference ignores 不/别 inside ordinary words (特别, 不同, 区别 ...), does not treat "第一步之后" as a bounded cue, and splits clauses at " - " and "without X, complete Y"; real negations ("不要只处理", "不仅是有界里程碑") still mark a project.
14
+ - A checkpoint whose `verification` is not an array no longer crashes acceptance through revision coverage (the task used to stick in `active/` and be re-dispatched); with several planned milestones a review counts only for the milestone it names, so one accepted revision cannot cover two milestones; an unreadable gate, task or checkpoint is skipped during gate reconciliation instead of failing every run of the queue.
15
+ - **Security:** isolated verification started by root now passes `--cap-drop ALL` to bwrap and masks root-only secrets of the bound `/etc` (`shadow`, `gshadow`, `sudoers`, SSH host keys, `ssl/private`); previously a root host gave the sandbox full capabilities, so a verification command could remount `/usr` or `/etc` read-write, modify host binaries and still pass, and could read `/etc/shadow`. Run the supervisor as a non-root user for full identity separation.
16
+ - The undeclared-input audit follows symlinks the command creates (including renamed and relative ones) and rejects another thread's `/proc/.../task/<tid>/` aliases, so `ln -s /work /tmp/w; cat /tmp/w/hidden.txt` no longer passes unnoticed.
17
+ - Fix intermittent false failures of isolated verification when processes are killed in `exit_group` or `wait4` during PID-namespace teardown (`unfinished`/`overlapping file syscall`).
18
+ - The isolation supervisor's timeout now covers input freezing, and SIGTERM tears down the traced sandbox, so a caller timeout no longer orphans strace, bwrap and the command.
19
+ - A failed isolated verification reports its `reason`; the live isolation self-test names missing tools (`LOOP_SKIP_ISOLATION_TESTS=1` skips it) instead of failing on an unrelated `stderr.log` read.
20
+
5
21
  ## 0.16.4 - 2026-10-29
6
22
 
7
23
  - Measure project continuation by newly accepted, evidence-bound milestone identities, preserving explicit and inferred project plans; renamed plans and duplicate snapshots no longer count as progress.
@@ -42,8 +42,22 @@ same input digest. Failed file accesses are checked against the recorded working
42
42
  directory or directory descriptor, including nested paths and resumed calls.
43
43
  Swallowing a missing undeclared input error does not make verification pass.
44
44
  Missing, malformed, stale, or red receipts fail verification.
45
- The queue run records the evidence directory and digest in its verification
46
- artifact. `code-task-run` repeats isolated verification after applying a
45
+ The queue run records the evidence directory, digest and, for a failed run, a
46
+ short `reason` (supervisor error, read-audit violation, timeout or failed
47
+ receipt check) in its verification artifact.
48
+
49
+ The sandboxed command holds no capabilities. When the supervisor runs as root,
50
+ bwrap is started with `--cap-drop ALL`, so the command can neither remount the
51
+ read-only system binds nor write the host `/usr` or `/etc`; the usual root-only
52
+ secrets of the bound `/etc` (`shadow`, `gshadow`, `sudoers`, SSH host keys,
53
+ `ssl/private`) are masked. The sandbox identity still maps to host root, so
54
+ other root-only files in the bound system directories remain readable: run the
55
+ supervisor as a non-root user when that matters. (Running the sandbox as an
56
+ unprivileged identity under root is not portable: hosts that restrict
57
+ unprivileged user namespaces, such as Ubuntu 23.10+, deny it the capabilities
58
+ bwrap needs to set up the sandbox network.) The supervisor's `--timeout` covers freezing as well as the
59
+ command, and a SIGTERM to the supervisor tears down the traced sandbox, which
60
+ runs in its own session. `code-task-run` repeats isolated verification after applying a
47
61
  reviewed patch; its evidence lives beside the project root in
48
62
  `.loop-isolation-evidence/<task-id>/`.
49
63
 
@@ -74,8 +88,21 @@ The supervisor models its explicit mount roots and runtime-file ancestors;
74
88
  unresolved traversal through dynamic external mounts or symlink ancestors fails
75
89
  closed. This is bounded trace auditing, not unrestricted syscall emulation.
76
90
 
91
+ Symlinks the command creates (in `/tmp` or `/out`, which start empty) are
92
+ recorded from the trace, followed through renames, and resolved before a failed
93
+ access is audited, so probing an undeclared input through such a link is still
94
+ rejected. Process exits and child waits that never return during PID-namespace
95
+ teardown are not treated as unfinished file syscalls.
96
+
77
97
  Failed `/proc/self/cwd`, `/proc/thread-self/cwd` and self `root` probes are
78
98
  resolved using the traced process cwd or the sandbox root before source-input
79
99
  auditing. Raw suffix components are retained. Unresolved process/fd aliases
80
- (including `/dev/fd`) fail closed; optional accesses via unknown dynamic aliases
100
+ (including `/dev/fd` and another thread's `/proc/.../task/<tid>/` view) fail closed; optional accesses via unknown dynamic aliases
81
101
  may therefore be rejected. This does not claim general procfs emulation.
102
+
103
+ ## Running the self-tests
104
+
105
+ `npm test` starts with the live sandbox tests and needs Linux with bubblewrap,
106
+ strace and Python 3 (`apt-get install bubblewrap strace python3`). Without them
107
+ the test names the missing tools and fails; set `LOOP_SKIP_ISOLATION_TESTS=1`
108
+ to skip only those live tests on a machine that cannot run the sandbox.
package/lib/core.mjs CHANGED
@@ -1366,17 +1366,29 @@ export async function reconcileProjectGates(root, options = {}) {
1366
1366
  : [...new Set((await projectSpecs(root)).flatMap((spec) => (spec.queues ?? []).map((item) => item.queue)))];
1367
1367
  const specs = new Map((await projectSpecs(root)).map((spec) => [spec.project, spec]));
1368
1368
  const results = [];
1369
+ const skipped = [];
1369
1370
  for (const queue of queues) {
1370
1371
  await ensureQueueDirs(root, queue);
1371
1372
  const gatesDir = path.join(queueDirFor(root, queue), 'human-input', 'gates');
1372
1373
  for (const file of await listJson(gatesDir)) {
1373
1374
  const full = path.join(gatesDir, file);
1374
- let gate = await readJson(full);
1375
- if (gate.status !== 'waiting_for_human') continue;
1376
- const found = await findTaskFile(root, queue, gate.task_id);
1377
- const task = found ? await readJson(found.file) : null;
1378
- const checkpointFile = path.join(taskRuntimeDirFor(root, queue, gate.task_id), 'checkpoints', `${gate.checkpoint_id}.json`);
1379
- const checkpoint = await exists(checkpointFile) ? await readJson(checkpointFile) : null;
1375
+ // One unreadable gate, task or checkpoint must not stop reconciliation
1376
+ // (and so every run) for the whole queue. Leave that gate waiting.
1377
+ let gate;
1378
+ let found;
1379
+ let task;
1380
+ let checkpoint;
1381
+ try {
1382
+ gate = await readJson(full);
1383
+ if (gate?.status !== 'waiting_for_human') continue;
1384
+ found = await findTaskFile(root, queue, gate.task_id);
1385
+ task = found ? await readJson(found.file) : null;
1386
+ const checkpointFile = path.join(taskRuntimeDirFor(root, queue, gate.task_id), 'checkpoints', `${gate.checkpoint_id}.json`);
1387
+ checkpoint = await exists(checkpointFile) ? await readJson(checkpointFile) : null;
1388
+ } catch (error) {
1389
+ skipped.push({ queue, gateId: gate?.gate_id ?? file, outcome: 'skipped_unreadable', reason: error instanceof Error ? error.message : String(error) });
1390
+ continue;
1391
+ }
1380
1392
  if (!gate.project_id || !Array.isArray(gate.requirement_ids) || !gate.contract_hash) {
1381
1393
  gate = { ...gate, ...await gateProjectMetadata(root, task, checkpoint) };
1382
1394
  await writeJson(full, gate);
@@ -1423,7 +1435,7 @@ export async function reconcileProjectGates(root, options = {}) {
1423
1435
  results.push({ queue, gateId: gate.gate_id, projectId: gate.project_id, outcome: invalid.status, reason: invalid.code });
1424
1436
  }
1425
1437
  }
1426
- return { inspectedQueues: queues.length, reconciled: results.length, results };
1438
+ return { inspectedQueues: queues.length, reconciled: results.length, results, ...(skipped.length ? { skipped } : {}) };
1427
1439
  }
1428
1440
 
1429
1441
  function projectLatestIntakePath(root, project) {
@@ -2352,7 +2364,11 @@ async function terminalNotificationMessage(root, queue, task, language = 'en') {
2352
2364
  const needsHuman = ['needs_human_input', 'blocked', 'ready_for_human_review'].includes(task.status);
2353
2365
  const summary = compactNotificationText(checkpoint?.summary);
2354
2366
  const verificationCount = Array.isArray(checkpoint?.verification) ? checkpoint.verification.length : 0;
2355
- const blockers = Array.isArray(checkpoint?.blockers) ? checkpoint.blockers.filter(Boolean) : [];
2367
+ const blockers = [
2368
+ ...(Array.isArray(checkpoint?.blockers) ? checkpoint.blockers.filter(Boolean) : []),
2369
+ ...(Array.isArray(judgement?.handoff_blockers) ? judgement.handoff_blockers : []),
2370
+ ...(Array.isArray(judgement?.handoff_pending_actions) ? judgement.handoff_pending_actions.map((item) => (language === 'zh' ? '结果未知的外部操作:' : 'unknown external outcome: ') + item) : [])
2371
+ ];
2356
2372
  const outcome = judgement?.outcome;
2357
2373
  const nextAction = compactNotificationText(judgement?.next_actions?.[0] ?? checkpoint?.next_action, 300);
2358
2374
  if (language === 'zh') return [
@@ -3500,7 +3516,7 @@ export function inferTaskScope(task) {
3500
3516
  // Apply the same object-local negation rule to EVERY local-scope cue.
3501
3517
  // Removing a negated cue also prevents a nested cue ("backlog item" or
3502
3518
  // "第一步") from overriding the project objective.
3503
- const cue = /有界.{0,20}?里程碑|bounded.{0,30}?milestone|(?:only\s*|仅|只)(?:推进|处理|执行|完成|验证)|阶段完成|任务完成|第\s*(?:\d+|一)\s*(?:项|步)|选项\s*\d+|boundary item|backlog item|(?:取消|撤销|移除).{0,40}(?:功能|范围|计划|必做|门槛)|(?:cancel|remove|drop|withdraw).{0,40}(?:feature|scope|requirement|backlog item|completion gate)|(?:product[-_ ]scope|产品范围).{0,20}(?:decision|amendment|决策|修订)/g;
3519
+ const cue = /有界.{0,20}?里程碑|bounded.{0,30}?milestone|(?:only\s*|仅|只)(?:推进|处理|执行|完成|验证)|阶段完成|任务完成|第\s*(?:\d+|一)\s*(?:项|步)(?!\s*(?:之后|以后|完成后|结束后|后))|选项\s*\d+|boundary item|backlog item|(?:取消|撤销|移除).{0,40}(?:功能|范围|计划|必做|门槛)|(?:cancel|remove|drop|withdraw).{0,40}(?:feature|scope|requirement|backlog item|completion gate)|(?:product[-_ ]scope|产品范围).{0,20}(?:decision|amendment|决策|修订)/g;
3504
3520
  // Negation governs the following object phrase, including arbitrary modifiers.
3505
3521
  // End its scope at clause/contrast boundaries or an explicit context object,
3506
3522
  // not at a whitelist of adjectives (first/initial/one/etc.). Coordinated
@@ -3509,14 +3525,16 @@ export function inferTaskScope(task) {
3509
3525
  // Explicit double-negative obligations are affirmative. Do not count every
3510
3526
  // negative word: unrelated prohibitions can coexist in the same clause.
3511
3527
  prefix = prefix.replace(/(?:\b(?:not|never)|n['’]t)\s+(?:fail\s+to|avoid(?:\s+doing)?)\b|\bwithout\s+failing\s+to\b|(?:不能不|不得不|不是不)/g, ' ');
3528
+ // 不/别 inside ordinary words (特别, 不同, 区别, 别的 ...) is not negation.
3529
+ prefix = prefix.replace(/特别|区别|分别|差别|级别|类别|识别|个别|告别|别的|别人|别处|不同|不管|不论|不过|不少|不断|不错|不止|不久/g, ' ');
3512
3530
  const negations = [...prefix.matchAll(/(?:不|勿|别)|\b(?:not|never|no|without|neither|nor)\b|n['’]t\b/g)];
3513
3531
  if (!negations.length) return false;
3514
3532
  const tail = prefix.slice(negations.at(-1).index);
3515
3533
  // These boundaries introduce a separate affirmative instruction after a
3516
3534
  // negated context, e.g. without deploying the project ... implement X.
3517
- return !/(?:project[-_ ]level\b[^,;.!?]*\b(?:implement|complete|do|execute)\b)|(?:前提下|情况下)|,\s*(?:and|or)\s+(?:implement|complete|execute|do)\b|\bwithout\s+\w+ing\b[^,;.!?]*\b(?:implement|complete|execute|do)\b|\b(?:while|then|however|instead)\b/.test(tail);
3535
+ return !/(?:project[-_ ]level\b[^,;.!?]*\b(?:implement|complete|do|execute)\b)|(?:前提下|情况下)|\bwithout\s+(?!\w+ing\b)[^,;.!?]*?\b(?:complete|implement|execute|finish)\b|,\s*(?:and|or)\s+(?:implement|complete|execute|do)\b|\bwithout\s+\w+ing\b[^,;.!?]*\b(?:implement|complete|execute|do)\b|\b(?:while|then|however|instead)\b/.test(tail);
3518
3536
  };
3519
- const boundedMilestone = requestText.split(/[,,](?!\s*(?:or\b|and\b|nor\b|或|以及))|[。;;.!?\n]|\bbut\b|而是|但是/).some((clause) => {
3537
+ const boundedMilestone = requestText.split(/[,,](?!\s*(?:or\b|and\b|nor\b|或|以及))|[。;;.!?\n]|\s[-–—]\s|\bbut\b|而是|但是/).some((clause) => {
3520
3538
  let prefix = '';
3521
3539
  let offset = 0;
3522
3540
  for (const match of clause.matchAll(cue)) {
@@ -3908,7 +3926,7 @@ export async function writeAcceptancePlan(root, queue, task, taskContract, optio
3908
3926
  };
3909
3927
  }
3910
3928
 
3911
- function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3929
+ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1', milestoneId = firstCheckpointId, revisesCheckpointId = null) {
3912
3930
  const gated = contract.requires_human_gate;
3913
3931
  return {
3914
3932
  version: 1,
@@ -3928,7 +3946,7 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3928
3946
  },
3929
3947
  checkpoints: [
3930
3948
  {
3931
- id: firstCheckpointId,
3949
+ id: milestoneId,
3932
3950
  goal: 'Produce the first complete development result for acceptance review.',
3933
3951
  required_evidence: [
3934
3952
  'Summary of files changed or artifacts created',
@@ -3943,8 +3961,8 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3943
3961
  version: 1,
3944
3962
  task_id: contract.task_id,
3945
3963
  checkpoint_id: firstCheckpointId,
3946
- milestone_id: firstCheckpointId,
3947
- revises_checkpoint_id: null,
3964
+ milestone_id: milestoneId,
3965
+ revises_checkpoint_id: revisesCheckpointId,
3948
3966
  revision_coverage: null,
3949
3967
  status: 'ready_for_acceptance | blocked | needs_human_input',
3950
3968
  summary: 'What changed and why.',
@@ -3972,6 +3990,19 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3972
3990
  };
3973
3991
  }
3974
3992
 
3993
+ // What last put this task back in the queue: a judged and accepted project
3994
+ // milestone (project_continued), a runtime or orphan recovery of an
3995
+ // unfinished run (recovered), an operator requeue, or nothing (first run).
3996
+ function lastTaskTransition(task) {
3997
+ const at = (field) => Date.parse(task?.[field] ?? '') || 0;
3998
+ const transitions = [
3999
+ ['project_continued', at('projectContinuedAt')],
4000
+ ['recovered', Math.max(at('runtimeInterruptedAt'), at('orphanRecoveredAt'))],
4001
+ ['requeued', task?.orphanRecoveredAt && at('requeuedAt') === at('orphanRecoveredAt') ? 0 : at('requeuedAt')]
4002
+ ].filter(([, time]) => time > 0).sort((a, b) => b[1] - a[1]);
4003
+ return transitions[0]?.[0] ?? 'first_run';
4004
+ }
4005
+
3975
4006
  export async function writeDevPlan(root, queue, task, taskContract, acceptancePlan) {
3976
4007
  const dir = taskRuntimeDirFor(root, queue, task.id);
3977
4008
  const checkpointsDir = path.join(dir, 'checkpoints');
@@ -3986,7 +4017,20 @@ export async function writeDevPlan(root, queue, task, taskContract, acceptancePl
3986
4017
  let checkpointNumber = 1;
3987
4018
  while (usedCheckpointNumbers.has(checkpointNumber)) checkpointNumber += 1;
3988
4019
  const nextCheckpointId = `cp${checkpointNumber}`;
3989
- let plan = buildDevPlan(taskContract.contract, acceptancePlan.plan, nextCheckpointId);
4020
+ // Each dispatch writes a new checkpoint file, but the milestone it serves
4021
+ // only changes once that milestone was judged accepted and the project
4022
+ // continued. A revision round, runtime recovery, orphan recovery or operator
4023
+ // requeue keeps the milestone, so its reviews stay one chain: otherwise the
4024
+ // new id splits them and the old review (or blocker) stays live forever, or
4025
+ // an already-written accepted checkpoint no longer counts after recovery.
4026
+ const previousPlan = await readJson(file).catch(() => null);
4027
+ const previousMilestone = previousPlan?.task_id === task.id && previousPlan.generated_by === 'deterministic_dev_planner_v1'
4028
+ && Array.isArray(previousPlan.checkpoints) && previousPlan.checkpoints.length === 1
4029
+ ? previousPlan.checkpoints[0]?.id ?? null : null;
4030
+ const milestoneId = previousMilestone && lastTaskTransition(task) !== 'project_continued' ? previousMilestone : nextCheckpointId;
4031
+ const latestCheckpoint = milestoneId === nextCheckpointId ? null
4032
+ : [...usedCheckpointNumbers].sort((a, b) => b - a).map((number) => `cp${number}`)[0] ?? null;
4033
+ let plan = buildDevPlan(taskContract.contract, acceptancePlan.plan, nextCheckpointId, milestoneId, latestCheckpoint);
3990
4034
  if (taskContract.contract.task_scope === 'project') {
3991
4035
  const existing = await readJson(file).catch(() => null);
3992
4036
  if (existing?.task_id === task.id &&
@@ -4420,7 +4464,10 @@ function applyRevisionCoverage(reviews, planned, contract) {
4420
4464
  || !old.checkpointDigest || entry.checkpoint_sha256 !== old.checkpointDigest
4421
4465
  || typeof entry.resolution !== 'string' || !entry.resolution.trim()
4422
4466
  || !Array.isArray(evidence) || !evidence.length
4423
- || !evidence.every(item => typeof item === 'string' && item.trim() && review.verification?.includes(item))
4467
+ // verification may be malformed (an object or a string); only an array
4468
+ // of exact entries can bind coverage evidence, and it must not throw.
4469
+ || !Array.isArray(review.verification)
4470
+ || !evidence.every(item => typeof item === 'string' && item.trim() && review.verification.includes(item))
4424
4471
  || reversedClock) valid = false;
4425
4472
  if (old) { seen.add(old.checkpointId); targets.push(old); }
4426
4473
  }
@@ -4439,10 +4486,25 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4439
4486
  const allReviews = applyRevisionCoverage(acceptanceReviews?.reviews ?? [], planned, contract);
4440
4487
  const protectedReviews = allReviews.filter(review => review.invalidCheckpoint || review.invalidRevisionCoverage);
4441
4488
  const groups = new Map();
4442
- for (const review of allReviews.filter(review => !protectedReviews.includes(review))) {
4489
+ const candidates = allReviews.filter(review => !protectedReviews.includes(review));
4490
+ const byCheckpoint = new Map(candidates.map(review => [review.checkpointId, review]));
4491
+ const baseKey = (review) => review.milestoneId ?? (planned.length <= 1 ? planned[0]?.id ?? '__legacy__' : review.checkpointId);
4492
+ // A checkpoint that declares revises_checkpoint_id continues that
4493
+ // checkpoint's milestone even when it carries a different milestone id
4494
+ // (plans written by 0.16.1-0.16.4 renamed the milestone on every dispatch).
4495
+ const chainKey = (review) => {
4496
+ let current = review;
4497
+ const seen = new Set();
4498
+ while (current.revisesCheckpointId && byCheckpoint.has(current.revisesCheckpointId) && !seen.has(current.checkpointId)) {
4499
+ seen.add(current.checkpointId);
4500
+ current = byCheckpoint.get(current.revisesCheckpointId);
4501
+ }
4502
+ return baseKey(current);
4503
+ };
4504
+ for (const review of candidates) {
4443
4505
  // Explicit identities never inherit another milestone's clocks. Legacy
4444
4506
  // unlabelled snapshots retain the single-plan chronology compatibility.
4445
- const key = review.milestoneId ?? (planned.length <= 1 ? planned[0]?.id ?? '__legacy__' : review.checkpointId);
4507
+ const key = chainKey(review);
4446
4508
  const group = groups.get(key) ?? [];
4447
4509
  group.push(review);
4448
4510
  groups.set(key, group);
@@ -4461,6 +4523,15 @@ export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, con
4461
4523
  return selected;
4462
4524
  }
4463
4525
 
4526
+ // With several planned milestones a review covers only the milestone it
4527
+ // names (legacy reviews without one fall back to their checkpoint id), so a
4528
+ // revision written as checkpoint "cp2" for milestone "cp1" cannot also count
4529
+ // as milestone cp2. A single-milestone plan is one review chain, as before.
4530
+ function reviewCoversMilestone(review, milestoneId, plannedCount) {
4531
+ if (plannedCount <= 1) return review.milestoneId === milestoneId || review.checkpointId === milestoneId;
4532
+ return review.milestoneId != null ? review.milestoneId === milestoneId : review.checkpointId === milestoneId;
4533
+ }
4534
+
4464
4535
  function acceptedMilestoneIds(devPlan, acceptanceReviews, contract) {
4465
4536
  const effective = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4466
4537
  const planned = devPlan?.checkpoints ?? [];
@@ -4469,7 +4540,7 @@ function acceptedMilestoneIds(devPlan, acceptanceReviews, contract) {
4469
4540
  // that does not bind those snapshots to a newly named milestone. Progress
4470
4541
  // needs a durable checkpoint/milestone identity, never just the plan label.
4471
4542
  const reviews = effective.filter(r =>
4472
- r.milestoneId === cp.id || r.checkpointId === cp.id);
4543
+ reviewCoversMilestone(r, cp.id, planned.length));
4473
4544
  return reviews.length > 0 && reviews.every(r => r.status === 'accepted');
4474
4545
  }).map(cp => cp.id);
4475
4546
  }
@@ -4487,7 +4558,7 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4487
4558
  const reviewCount = effectiveReviews.length;
4488
4559
  const acceptedCount = requiredCheckpoints > 0
4489
4560
  ? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
4490
- && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id
4561
+ && (reviewCoversMilestone(review, checkpoint.id, requiredCheckpoints)
4491
4562
  || (requiredCheckpoints === 1 && review.milestoneId == null)))).length
4492
4563
  : effectiveReviews.filter((item) => item.status === 'accepted').length;
4493
4564
  const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
@@ -10278,9 +10349,13 @@ export async function runQueueOnce(root, options) {
10278
10349
  devPlan = await writeDevPlan(root, queue, task, taskContract, acceptancePlan);
10279
10350
  const priorReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, { persist: false });
10280
10351
  invalidCheckpointBaseline = priorReviews.reviews.some(review => review.invalidCheckpoint === true);
10281
- priorAcceptedMilestoneIds = invalidCheckpointBaseline ? null
10352
+ // A recovered run resumes work whose checkpoints were never judged: what
10353
+ // the interrupted run wrote is this run's progress, not its baseline.
10354
+ // Recovery is bounded by retry.runtimeRecoveryMaxAttempts.
10355
+ const resumingUnjudgedRun = lastTaskTransition(task) === 'recovered';
10356
+ priorAcceptedMilestoneIds = invalidCheckpointBaseline || resumingUnjudgedRun ? null
10282
10357
  : acceptedMilestoneIds(devPlan.plan, priorReviews, taskContract.contract);
10283
- priorCheckpointCount = (await checkpointSummary(root, devPlan)).count;
10358
+ priorCheckpointCount = resumingUnjudgedRun ? null : (await checkpointSummary(root, devPlan)).count;
10284
10359
  priorPlannedCheckpointCount = devPlan.plan.checkpoints?.length ?? null;
10285
10360
  progress.emit('planning', 'dev_plan', 'Wrote development plan', {
10286
10361
  taskId: task.id,
@@ -10390,7 +10465,12 @@ export async function runQueueOnce(root, options) {
10390
10465
  if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
10391
10466
  else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
10392
10467
  handoffProgressFingerprint = proof.progressFingerprint;
10393
- if (!handoffProgressFingerprint || (task.contextHandoffProgress ?? []).includes(handoffProgressFingerprint)) {
10468
+ // The fingerprint only catches exact repeats; a worker that
10469
+ // varies a log path or timestamp each turn would otherwise
10470
+ // start a new paid session every tick forever.
10471
+ const maxHandoffs = Number(options.retry?.maxContextHandoffs ?? 10);
10472
+ if (!handoffProgressFingerprint || (task.contextHandoffProgress ?? []).includes(handoffProgressFingerprint)
10473
+ || Number(task.contextHandoffCount ?? 0) >= maxHandoffs) {
10394
10474
  finalStatus = 'runtime_blocked';
10395
10475
  }
10396
10476
  dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
@@ -10524,6 +10604,21 @@ export async function runQueueOnce(root, options) {
10524
10604
  });
10525
10605
  finalStatus = queueStatusFromFinalJudgement(finalStatus, finalJudgement);
10526
10606
  }
10607
+ // Blockers and uncertain external actions reported only in a handoff
10608
+ // must reach the person who has to resolve them.
10609
+ if (finalJudgement?.judgement && contextHandoff && (contextHandoff.blockers?.length || contextHandoff.pendingActions?.length)) {
10610
+ const judgement = finalJudgement.judgement;
10611
+ judgement.handoff_blockers = contextHandoff.blockers;
10612
+ judgement.handoff_pending_actions = contextHandoff.pendingActions;
10613
+ judgement.reasons = [...(judgement.reasons ?? []),
10614
+ ...contextHandoff.blockers.map((item) => `Context handoff blocker: ${item}`),
10615
+ ...contextHandoff.pendingActions.map((item) => `External action with unknown outcome: ${item}`)];
10616
+ judgement.next_actions = [
10617
+ ...(contextHandoff.pendingActions.length ? [`Verify the outcome of ${contextHandoff.pendingActions.join('; ')} before any retry; never replay it blindly.`] : []),
10618
+ ...(contextHandoff.blockers.length ? [`Resolve: ${contextHandoff.blockers.join('; ')}.`] : []),
10619
+ ...(judgement.next_actions ?? [])];
10620
+ await writeJson(path.join(root, finalJudgement.file), judgement);
10621
+ }
10527
10622
  if (!revisionRequest) {
10528
10623
  revisionRequest = await writeRevisionRequest(root, queue, task, taskContract, acceptancePlan, devPlan, finalJudgement, acceptanceReviews);
10529
10624
  }
@@ -10554,6 +10649,8 @@ export async function runQueueOnce(root, options) {
10554
10649
  completedTask.projectContinuedAt = finishedAt;
10555
10650
  completedTask.projectContinuationCount = (task.projectContinuationCount ?? 0) + 1;
10556
10651
  completedTask.runtimeRecoveryCount = 0;
10652
+ completedTask.contextHandoffCount = 0;
10653
+ completedTask.contextHandoffProgress = [];
10557
10654
  completedTask.sessionTickCount = Number(task.sessionTickCount ?? 0) + 1;
10558
10655
  const rotation = contextRotation(contextUsage, completedTask.sessionTickCount, budgetPolicy);
10559
10656
  completedTask.contextBudget = rotation;
@@ -10573,10 +10670,13 @@ export async function runQueueOnce(root, options) {
10573
10670
  }
10574
10671
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10575
10672
  completedTask.sessionTickCount = 0;
10576
- if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
10577
10673
  completedTask.runtimeInterruptedAt = finishedAt;
10578
10674
  completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10579
10675
  }
10676
+ // A handoff only describes the run that wrote it. Clear it otherwise, so
10677
+ // a later session is never pointed at an out-of-date nextAction.
10678
+ if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
10679
+ else delete completedTask.contextHandoffFile;
10580
10680
  const completedFile = path.join(destination, path.basename(activeFile));
10581
10681
  // Claim the active file by moving it. If an operator canceled or parked
10582
10682
  // the task meanwhile, the file is gone and their copy stays authoritative
@@ -38,10 +38,23 @@ export async function runIsolatedVerification({ cwd, command, inputs, runtimeFil
38
38
  ...result,
39
39
  exitCode: accepted ? 0 : 1,
40
40
  isolation: { status: accepted ? 'passed' : 'failed_or_unknown', evidenceDir,
41
- inputDigest: terminal?.input_digest ?? null, runnerSha256: runnerHash }
41
+ inputDigest: terminal?.input_digest ?? null, runnerSha256: runnerHash,
42
+ // Say why, so an operator does not have to open terminal.json.
43
+ ...(accepted ? {} : { reason: isolationFailureReason(result, terminal, runnerHash === afterHash) }) }
42
44
  };
43
45
  }
44
46
 
47
+ function isolationFailureReason(result, terminal, runnerUnchanged) {
48
+ if (!runnerUnchanged) return 'isolation supervisor changed during verification';
49
+ if (!terminal) return result.timedOut ? 'isolation supervisor timed out before writing a receipt' : `no isolation receipt (supervisor exit ${result.exitCode}): ${String(result.stderr ?? '').trim().slice(-300)}`;
50
+ if (terminal.error) return terminal.error;
51
+ if (terminal.timed_out) return 'verification command timed out';
52
+ if (terminal.read_violations?.length) return `read audit failed: ${terminal.read_violations.slice(0, 3).join('; ')}`;
53
+ if (terminal.exit_code !== 0) return `verification command exited ${terminal.exit_code}`;
54
+ const failed = ['snapshot_unchanged', 'source_unchanged', 'host_tools_unchanged', 'runtime_files_unchanged', 'process_group_gone'].filter((key) => terminal[key] !== true);
55
+ return failed.length ? `receipt check failed: ${failed.join(', ')}` : 'receipt did not match the requested command';
56
+ }
57
+
45
58
  export function isolatedEvidenceDir(base, index) {
46
59
  return path.join(base, `isolation-${index + 1}-${randomUUID()}`);
47
60
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-loop-engineering",
3
- "version": "0.16.4",
3
+ "version": "0.16.5",
4
4
  "private": false,
5
5
  "description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
6
6
  "type": "module",
@@ -31,7 +31,7 @@
31
31
  "check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node scripts/hermes-install-self-test.mjs",
32
32
  "check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
33
33
  "check:human-gates": "node --check lib/human-gate-command.mjs && node --check lib/human-gate-channel-adapter.mjs && node scripts/human-gate-command-self-test.mjs && node scripts/human-gate-final-judgement.mjs",
34
- "check": "node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/revision-coverage-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
34
+ "check": "node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && node scripts/continuation-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/revision-coverage-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
35
35
  "pack:dry": "npm pack --dry-run"
36
36
  },
37
37
  "exports": {
@@ -0,0 +1,175 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { mkdir } from 'node:fs/promises';
6
+ import { buildFinalJudgement, enqueueTask, inferTaskScope, notifyTerminalTasks, queueRequeue, runQueueOnce, writeJson } from '../lib/core.mjs';
7
+
8
+ // A worker that follows the dev plan's checkpoint template exactly. `script`
9
+ // receives the tick number and returns { status, exit } decisions.
10
+ async function templateWorker(root, body) {
11
+ const worker = path.join(root, 'worker.mjs');
12
+ await writeFile(worker, `import { readFile, writeFile } from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ const dir = path.join(process.env.LOOP_CHECKPOINTS_DIR, '..');
15
+ const plan = JSON.parse(await readFile(path.join(dir, 'dev_plan.json'), 'utf8'));
16
+ const schema = plan.checkpoint_schema;
17
+ const marker = ${JSON.stringify(path.join(root, 'tick'))};
18
+ let tick = 0; try { tick = Number(await readFile(marker, 'utf8')); } catch {}
19
+ await writeFile(marker, String(tick + 1));
20
+ const n = Number(schema.checkpoint_id.slice(2));
21
+ const write = (fields) => writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, schema.checkpoint_id + '.json'), JSON.stringify({
22
+ task_id: plan.task_id, checkpoint_id: schema.checkpoint_id, milestone_id: schema.milestone_id,
23
+ revises_checkpoint_id: schema.revises_checkpoint_id, sequence: n, created_at: new Date(Date.UTC(2026, 0, n)).toISOString(),
24
+ summary: 'work', files_changed: [], verification: ['npm test passed (' + schema.checkpoint_id + ')'], blockers: [], risks: [], deferred_gates: [], ...fields }));
25
+ ${body}`);
26
+ return { queue: 'regress', dispatcher: `node '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
27
+ }
28
+
29
+ const roots = [];
30
+ try {
31
+ // A bounded task revised once along the template is accepted; before, the
32
+ // revision got a new milestone id and the first review stayed live.
33
+ {
34
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-revise-')); roots.push(root);
35
+ const { task } = await enqueueTask(root, { queue: 'regress', title: 'fix bug', task: 'Fix the login redirect bug in the auth module.' });
36
+ const options = await templateWorker(root, `await write({ status: tick === 0 ? 'in_progress' : 'ready_for_acceptance' });`);
37
+ const first = await runQueueOnce(root, options);
38
+ assert.equal(first.run.finalJudgement.outcome, 'needs_revision');
39
+ await queueRequeue(root, 'regress', task.id);
40
+ const second = await runQueueOnce(root, options);
41
+ assert.notEqual(second.run.finalJudgement.outcome, 'needs_revision', JSON.stringify(second.run.finalJudgement.reasons));
42
+ }
43
+
44
+ // A project interrupted after writing an accepted checkpoint continues
45
+ // after recovery instead of failing as "no progress" or "not covered".
46
+ {
47
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-recover-')); roots.push(root);
48
+ await enqueueTask(root, { queue: 'regress', title: 'project', task: '开发完整项目并完成整体目标' });
49
+ const options = await templateWorker(root, `if (tick === 2) process.exit(0);
50
+ await write({ status: 'ready_for_acceptance', project_completion: { status: 'in_progress' } });
51
+ if (tick === 1) { console.error('gateway is draining for restart'); process.exit(1); }`);
52
+ const statuses = [];
53
+ for (let i = 0; i < 4; i += 1) statuses.push((await runQueueOnce(root, options)).run?.status ?? 'not_processed');
54
+ assert.deepEqual(statuses, ['project_in_progress', 'runtime_interrupted', 'project_in_progress', 'project_in_progress']);
55
+ }
56
+
57
+ // Checkpoints written by the 0.16.1-0.16.4 template carry a new milestone
58
+ // id per revision; an explicit revises_checkpoint_id keeps them one chain,
59
+ // so a resolved historical blocker does not veto the accepted revision.
60
+ {
61
+ const contract = { task_id: 't', task_scope: 'scoped_task', requires_human_gate: false };
62
+ const reviews = { reviews: [
63
+ { checkpointId: 'cp1', milestoneId: 'cp1', sequence: 1, checkpointCreatedAt: '2026-01-01T00:00:00Z', status: 'blocked' },
64
+ { checkpointId: 'cp2', milestoneId: 'cp2', revisesCheckpointId: 'cp1', sequence: 2, checkpointCreatedAt: '2026-01-02T00:00:00Z', status: 'accepted', taskTerminal: true }
65
+ ] };
66
+ const judgement = buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp2' }] }, { count: 2 }, reviews, { dispatchStatus: 'completed' });
67
+ assert.equal(judgement.outcome, 'ready_to_apply');
68
+ assert.deepEqual(judgement.coverage.effective_review_ids, ['cp2']);
69
+ // Without the revision link a different milestone's blocker stays live.
70
+ const unlinked = { reviews: [reviews.reviews[0], { ...reviews.reviews[1], revisesCheckpointId: null }] };
71
+ assert.equal(buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp2' }] }, { count: 2 }, unlinked, { dispatchStatus: 'completed' }).outcome, 'blocked');
72
+ }
73
+ // Context handoffs: capped, blockers surfaced, and never stale.
74
+ {
75
+ const handoffWorker = async (root, extra) => {
76
+ const worker = path.join(root, 'handoff-worker.mjs');
77
+ await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
78
+ import path from 'node:path';
79
+ const e = process.env;
80
+ await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
81
+ const checkpoint = path.join(e.LOOP_CHECKPOINTS_DIR, e.LOOP_RUN_ID + '.json');
82
+ await writeFile(checkpoint, JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: e.LOOP_RUN_ID, status: 'in_progress', summary: 'still working', blockers: [], verification: [{ command: 'npm test', outcome: 'failed', log: e.LOOP_WORKER_OUTPUT_PREFIX + '.stdout.log' }], risks: [], next_action: 'continue' }));
83
+ const handoff = { version: 1, taskId: e.LOOP_TASK_ID, runId: e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), reason: 'context_budget', checkpoint, summary: 's', completed: [], remaining: ['fix tests'], evidence: [checkpoint], nextAction: 'fix', authority: 'local', pendingActions: [], blockers: [] };
84
+ ${extra}
85
+ await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, JSON.stringify(handoff));
86
+ `);
87
+ return { queue: 'regress', dispatcher: `node '${worker}'`, retry: { maxAttempts: 1, runtimeRecoveryMaxAttempts: 2, maxContextHandoffs: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
88
+ };
89
+ // A worker whose evidence differs every turn (a run-specific log path)
90
+ // still stops after maxContextHandoffs instead of looping forever.
91
+ {
92
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-loop-')); roots.push(root);
93
+ await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.' });
94
+ const options = await handoffWorker(root, '');
95
+ const statuses = [];
96
+ for (let i = 0; i < 6; i += 1) {
97
+ const result = await runQueueOnce(root, options);
98
+ if (!result.processed) break;
99
+ statuses.push(result.status);
100
+ }
101
+ assert.deepEqual(statuses, ['runtime_interrupted', 'runtime_interrupted', 'runtime_interrupted', 'runtime_blocked']);
102
+ }
103
+ // Handoff blockers and pending external actions reach the human.
104
+ {
105
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-blocker-')); roots.push(root);
106
+ await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.', sourceChannel: 'telegram', sourceTarget: '1' });
107
+ const options = await handoffWorker(root, "handoff.blockers = ['NEED_PROD_DB_PASSWORD']; handoff.pendingActions = ['payment request 42'];");
108
+ const result = await runQueueOnce(root, options);
109
+ assert.equal(result.status, 'needs_human_input');
110
+ const judgement = JSON.parse(await readFile(path.join(root, result.run.finalJudgement.path), 'utf8'));
111
+ assert.match(judgement.reasons.join(' '), /NEED_PROD_DB_PASSWORD/);
112
+ assert.match(judgement.next_actions[0], /payment request 42/);
113
+ const notice = await notifyTerminalTasks(root, { queue: 'regress', dryRun: true });
114
+ assert.match(notice.results[0].message, /NEED_PROD_DB_PASSWORD/);
115
+ assert.match(notice.results[0].message, /payment request 42/);
116
+ }
117
+ // A later session is not pointed at an earlier session's handoff.
118
+ {
119
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-stale-')); roots.push(root);
120
+ const { task } = await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.' });
121
+ const options = await handoffWorker(root, "if (Number(e.LOOP_SESSION_GENERATION) > 0) { console.error('maximum context length exceeded'); process.exit(1); }");
122
+ await runQueueOnce(root, options);
123
+ await runQueueOnce(root, options);
124
+ const inbox = JSON.parse(await readFile(path.join(root, 'runtime/loops/regress/inbox', `${task.id}.json`), 'utf8'));
125
+ assert.equal(inbox.contextHandoffFile, undefined, 'a run without a handoff clears the previous one');
126
+ }
127
+ }
128
+
129
+ // Scope inference: ordinary words containing 不/别 and temporal "after the
130
+ // first step" are not bounded-scope negations or cues.
131
+ for (const [body, expected] of [
132
+ ['继续整体项目,特别要求只处理第 3 项', 'scoped_task'],
133
+ ['继续整体项目:在不同模块中只处理第 2 项', 'scoped_task'],
134
+ ['Continue the project-level plan: no UI changes needed - only complete backlog item 2', 'scoped_task'],
135
+ ['Continue the project-level work. Without network access complete backlog item 2', 'scoped_task'],
136
+ ['项目级任务:完成第一步之后不要停,继续完成完整项目', 'project'],
137
+ ['继续整体项目,不要只处理第 3 项', 'project'],
138
+ ['完成完整项目,不仅是有界里程碑,而且不是仅完成第一步', 'project']
139
+ ]) assert.equal(inferTaskScope({ body }), expected, body);
140
+
141
+ // Malformed coverage evidence and id collisions do not crash or overcount.
142
+ {
143
+ const contract = { task_id: 't', task_scope: 'scoped_task', requires_human_gate: false };
144
+ const plan = { checkpoints: [{ id: 'cp1' }, { id: 'cp2' }] };
145
+ const collision = { reviews: [
146
+ { checkpointId: 'cp1', milestoneId: 'cp1', sequence: 1, checkpointCreatedAt: '2026-01-01T00:00:00Z', status: 'revise' },
147
+ { checkpointId: 'cp2', milestoneId: 'cp1', revisesCheckpointId: 'cp1', sequence: 2, checkpointCreatedAt: '2026-01-02T00:00:00Z', status: 'accepted' }
148
+ ] };
149
+ const judged = buildFinalJudgement(contract, { rubric: [], automation: [] }, plan, { count: 2 }, collision, { dispatchStatus: 'completed' });
150
+ assert.equal(judged.outcome, 'needs_revision', 'one review cannot cover two milestones');
151
+ const malformed = { reviews: [
152
+ { checkpointId: 'cp1', milestoneId: 'cp1', taskId: 't', sequence: 1, status: 'revise', phaseOnly: true, checkpointDigest: 'a'.repeat(64) },
153
+ { checkpointId: 'cp2', milestoneId: 'cp1', taskId: 't', sequence: 2, status: 'accepted', verification: { commands: ['npm test'] },
154
+ revisionCoverage: [{ checkpoint_id: 'cp1', checkpoint_sha256: 'a'.repeat(64), resolution: 'fixed', verification: ['npm test'] }] }
155
+ ] };
156
+ assert.doesNotThrow(() => buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp1' }] }, { count: 2 }, malformed, { dispatchStatus: 'completed' }));
157
+ }
158
+
159
+ // An unreadable gate checkpoint does not stop the queue.
160
+ {
161
+ const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-gate-')); roots.push(root);
162
+ const gates = path.join(root, 'runtime/loops/regress/human-input/gates');
163
+ await mkdir(gates, { recursive: true });
164
+ await writeJson(path.join(gates, 'broken.json'), { gate_id: 'broken', status: 'waiting_for_human', task_id: 'ghost', checkpoint_id: 'cp1', project_id: 'p' });
165
+ await mkdir(path.join(root, 'runtime/loops/regress/tasks/ghost/checkpoints'), { recursive: true });
166
+ await writeFile(path.join(root, 'runtime/loops/regress/tasks/ghost/checkpoints/cp1.json'), '{"truncated');
167
+ await enqueueTask(root, { queue: 'regress', title: 'healthy', task: 'Fix the login redirect bug.' });
168
+ const result = await runQueueOnce(root, { queue: 'regress', dispatcher: 'true', checkpointPollMs: 0, progressHeartbeatMs: 0 });
169
+ assert.equal(result.processed, true);
170
+ }
171
+
172
+ console.log('continuation regression self-test passed');
173
+ } finally {
174
+ for (const root of roots) await rm(root, { recursive: true, force: true });
175
+ }
@@ -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()
@@ -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 }), {
@@ -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
 
@@ -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