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.
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 [
@@ -2521,18 +2537,22 @@ export async function refreshTaskAcceptance(root, options = {}) {
2521
2537
  const checkpointFiles = await listJson(checkpointsDir);
2522
2538
  if (checkpointFiles.length === 0) return { queue, taskId: task.id, outcome: 'no_checkpoints' };
2523
2539
  const judgementFile = path.join(dir, 'final_judgement.json');
2524
- const newestCheckpointMs = Math.max(...await Promise.all(checkpointFiles.map(async (file) => (await stat(path.join(checkpointsDir, file))).mtimeMs)));
2525
- if (await exists(judgementFile) && (await stat(judgementFile)).mtimeMs >= newestCheckpointMs) {
2526
- return { queue, taskId: task.id, outcome: 'already_current', judgement: path.relative(root, judgementFile) };
2527
- }
2528
-
2529
2540
  const contractFile = path.join(dir, 'task_contract.json');
2530
2541
  const acceptanceFile = path.join(dir, 'acceptance_plan.json');
2531
2542
  const devFile = path.join(dir, 'dev_plan.json');
2543
+ // Plan amendments change required coverage even without a new checkpoint.
2544
+ const evidenceFiles = [...checkpointFiles.map((file) => path.join(checkpointsDir, file)), contractFile, acceptanceFile, devFile];
2545
+ const newestEvidenceMs = Math.max(...await Promise.all(evidenceFiles.map(async (file) => (await stat(file)).mtimeMs)));
2546
+ const currentDevPlan = await readJson(devFile);
2547
+ const priorJudgement = await readJson(judgementFile).catch(() => null);
2548
+ const coverageMatchesPlan = priorJudgement?.coverage?.planned_checkpoints === currentDevPlan.checkpoints?.length;
2549
+ if (priorJudgement && coverageMatchesPlan && (await stat(judgementFile)).mtimeMs >= newestEvidenceMs) {
2550
+ return { queue, taskId: task.id, outcome: 'already_current', judgement: path.relative(root, judgementFile) };
2551
+ }
2532
2552
  const taskContract = { contract: await readJson(contractFile), file: path.relative(root, contractFile) };
2533
2553
  const acceptancePlan = { plan: await readJson(acceptanceFile), file: path.relative(root, acceptanceFile) };
2534
2554
  const devPlan = {
2535
- plan: await readJson(devFile),
2555
+ plan: currentDevPlan,
2536
2556
  file: path.relative(root, devFile),
2537
2557
  checkpointsDir: path.relative(root, checkpointsDir),
2538
2558
  reviewsDir: path.relative(root, path.join(dir, 'reviews'))
@@ -2540,7 +2560,14 @@ export async function refreshTaskAcceptance(root, options = {}) {
2540
2560
  const checkpoints = await checkpointSummary(root, devPlan);
2541
2561
  const acceptanceReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan);
2542
2562
  const finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
2543
- dispatchStatus: 'completed'
2563
+ dispatchStatus: 'completed',
2564
+ invalidCheckpointBaseline: priorJudgement?.invalid_checkpoint_baseline === true,
2565
+ priorAcceptedMilestoneIds: priorJudgement?.no_progress_continuation === true
2566
+ ? priorJudgement.no_progress_accepted_milestone_baseline : null,
2567
+ priorCheckpointCount: priorJudgement?.no_progress_continuation === true
2568
+ ? priorJudgement.coverage?.produced_checkpoints : null,
2569
+ priorPlannedCheckpointCount: priorJudgement?.no_progress_continuation === true
2570
+ ? (priorJudgement.no_progress_plan_baseline ?? priorJudgement.coverage?.planned_checkpoints) : null
2544
2571
  });
2545
2572
  const status = queueStatusFromFinalJudgement('completed', finalJudgement);
2546
2573
  const destinationName = status === 'completed' ? 'done' : status === 'project_in_progress' ? 'inbox' : 'failed';
@@ -3296,7 +3323,17 @@ async function reconcileHumanInputGates(root, queue, taskId) {
3296
3323
  const gatesDir = path.join(queueDirFor(root, queue), 'human-input', 'gates');
3297
3324
  const checkpointsDir = path.join(taskRuntimeDirFor(root, queue, taskId), 'checkpoints');
3298
3325
  const checkpoints = [];
3299
- for (const file of await listJson(checkpointsDir)) checkpoints.push(await readJson(path.join(checkpointsDir, file)));
3326
+ for (const file of await listJson(checkpointsDir)) {
3327
+ let checkpoint;
3328
+ try { checkpoint = await readJson(path.join(checkpointsDir, file)); }
3329
+ catch (error) {
3330
+ if (!(error instanceof SyntaxError)) throw error;
3331
+ // Unknown evidence cannot satisfy a consumed gate. Preserve all gates.
3332
+ return;
3333
+ }
3334
+ if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) return;
3335
+ checkpoints.push(checkpoint);
3336
+ }
3300
3337
  for (const file of await listJson(gatesDir)) {
3301
3338
  const full = path.join(gatesDir, file);
3302
3339
  const gate = await readJson(full);
@@ -3469,6 +3506,7 @@ async function taskProjectAuthorization(root, task) {
3469
3506
  }
3470
3507
 
3471
3508
  export function inferTaskScope(task) {
3509
+ if (task?.taskScope === 'project' || task?.taskScope === 'scoped_task') return task.taskScope;
3472
3510
  const requestText = `${task?.title ?? ''}\n${task?.body ?? ''}`.toLowerCase();
3473
3511
  // A project can be referenced as context while the routed task is explicitly
3474
3512
  // bounded to one milestone or backlog item. Those bounded instructions must
@@ -3478,7 +3516,7 @@ export function inferTaskScope(task) {
3478
3516
  // Apply the same object-local negation rule to EVERY local-scope cue.
3479
3517
  // Removing a negated cue also prevents a nested cue ("backlog item" or
3480
3518
  // "第一步") from overriding the project objective.
3481
- 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;
3482
3520
  // Negation governs the following object phrase, including arbitrary modifiers.
3483
3521
  // End its scope at clause/contrast boundaries or an explicit context object,
3484
3522
  // not at a whitelist of adjectives (first/initial/one/etc.). Coordinated
@@ -3487,14 +3525,16 @@ export function inferTaskScope(task) {
3487
3525
  // Explicit double-negative obligations are affirmative. Do not count every
3488
3526
  // negative word: unrelated prohibitions can coexist in the same clause.
3489
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, ' ');
3490
3530
  const negations = [...prefix.matchAll(/(?:不|勿|别)|\b(?:not|never|no|without|neither|nor)\b|n['’]t\b/g)];
3491
3531
  if (!negations.length) return false;
3492
3532
  const tail = prefix.slice(negations.at(-1).index);
3493
3533
  // These boundaries introduce a separate affirmative instruction after a
3494
3534
  // negated context, e.g. without deploying the project ... implement X.
3495
- 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);
3496
3536
  };
3497
- 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) => {
3498
3538
  let prefix = '';
3499
3539
  let offset = 0;
3500
3540
  for (const match of clause.matchAll(cue)) {
@@ -3645,6 +3685,13 @@ export async function writeTaskContract(root, queue, task, options = {}) {
3645
3685
  historicalPatterns,
3646
3686
  projectAuthorization: options.projectAuthorization ?? await taskProjectAuthorization(root, task)
3647
3687
  });
3688
+ if (contract.task_scope === 'project') {
3689
+ const existing = await readJson(file).catch(() => null);
3690
+ if (existing?.task_id === task.id && existing.task_scope === 'project') {
3691
+ contract.deliverables = existing.deliverables ?? contract.deliverables;
3692
+ contract.acceptance_summary = existing.acceptance_summary ?? contract.acceptance_summary;
3693
+ }
3694
+ }
3648
3695
  contract = await mergeLiveAmendments(root, queue, task.id, contract, 'supplemental_requirements');
3649
3696
  await writeJson(file, contract);
3650
3697
  return {
@@ -3864,6 +3911,13 @@ export async function writeAcceptancePlan(root, queue, task, taskContract, optio
3864
3911
  const dir = taskRuntimeDirFor(root, queue, task.id);
3865
3912
  const file = path.join(dir, 'acceptance_plan.json');
3866
3913
  let plan = buildAcceptancePlan(taskContract.contract, options);
3914
+ if (taskContract.contract.task_scope === 'project') {
3915
+ const existing = await readJson(file).catch(() => null);
3916
+ if (existing?.task_id === task.id &&
3917
+ existing.generated_by === 'project_scope_worker_revision_after_deterministic_planner_v1') {
3918
+ plan = existing;
3919
+ }
3920
+ }
3867
3921
  plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_checks');
3868
3922
  await writeJson(file, plan);
3869
3923
  return {
@@ -3872,7 +3926,7 @@ export async function writeAcceptancePlan(root, queue, task, taskContract, optio
3872
3926
  };
3873
3927
  }
3874
3928
 
3875
- function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3929
+ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1', milestoneId = firstCheckpointId, revisesCheckpointId = null) {
3876
3930
  const gated = contract.requires_human_gate;
3877
3931
  return {
3878
3932
  version: 1,
@@ -3892,7 +3946,7 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3892
3946
  },
3893
3947
  checkpoints: [
3894
3948
  {
3895
- id: firstCheckpointId,
3949
+ id: milestoneId,
3896
3950
  goal: 'Produce the first complete development result for acceptance review.',
3897
3951
  required_evidence: [
3898
3952
  'Summary of files changed or artifacts created',
@@ -3907,8 +3961,9 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3907
3961
  version: 1,
3908
3962
  task_id: contract.task_id,
3909
3963
  checkpoint_id: firstCheckpointId,
3910
- milestone_id: firstCheckpointId,
3911
- revises_checkpoint_id: null,
3964
+ milestone_id: milestoneId,
3965
+ revises_checkpoint_id: revisesCheckpointId,
3966
+ revision_coverage: null,
3912
3967
  status: 'ready_for_acceptance | blocked | needs_human_input',
3913
3968
  summary: 'What changed and why.',
3914
3969
  files_changed: [],
@@ -3935,6 +3990,19 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3935
3990
  };
3936
3991
  }
3937
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
+
3938
4006
  export async function writeDevPlan(root, queue, task, taskContract, acceptancePlan) {
3939
4007
  const dir = taskRuntimeDirFor(root, queue, task.id);
3940
4008
  const checkpointsDir = path.join(dir, 'checkpoints');
@@ -3949,7 +4017,35 @@ export async function writeDevPlan(root, queue, task, taskContract, acceptancePl
3949
4017
  let checkpointNumber = 1;
3950
4018
  while (usedCheckpointNumbers.has(checkpointNumber)) checkpointNumber += 1;
3951
4019
  const nextCheckpointId = `cp${checkpointNumber}`;
3952
- 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);
4034
+ if (taskContract.contract.task_scope === 'project') {
4035
+ const existing = await readJson(file).catch(() => null);
4036
+ if (existing?.task_id === task.id &&
4037
+ existing.generated_by === 'project_scope_worker_revision_after_deterministic_planner_v1' &&
4038
+ Array.isArray(existing.checkpoints)) {
4039
+ plan = {
4040
+ ...existing,
4041
+ // A continuation candidate is not a committed milestone. The worker
4042
+ // adds a concrete checkpoint only after choosing its bounded batch;
4043
+ // otherwise final judgement mistakes N accepted for N/N+1 required.
4044
+ checkpoints: existing.checkpoints,
4045
+ checkpoint_schema: plan.checkpoint_schema
4046
+ };
4047
+ }
4048
+ }
3953
4049
  plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_instructions');
3954
4050
  await writeJson(file, plan);
3955
4051
  return {
@@ -4232,21 +4328,47 @@ function summarizeCriticReviews(reviews) {
4232
4328
  return byCritic;
4233
4329
  }
4234
4330
 
4235
- export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan) {
4331
+ export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, options = {}) {
4236
4332
  if (!devPlan?.reviewsDir || !devPlan?.checkpointsDir) return null;
4237
4333
  const checkpointFiles = await listJson(path.join(root, devPlan.checkpointsDir));
4238
4334
  const reviews = [];
4239
4335
  const reviewArtifacts = [];
4240
4336
  for (const file of checkpointFiles) {
4241
4337
  const checkpointFile = path.join(root, devPlan.checkpointsDir, file);
4242
- const checkpoint = await readJson(checkpointFile);
4338
+ let checkpoint;
4339
+ let checkpointBytes;
4340
+ try {
4341
+ checkpointBytes = await readFile(checkpointFile, 'utf8');
4342
+ checkpoint = JSON.parse(checkpointBytes);
4343
+ if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) {
4344
+ throw new SyntaxError('Checkpoint must be a JSON object');
4345
+ }
4346
+ } catch (error) {
4347
+ // Invalid evidence is not an absent checkpoint. Keep it explicit and
4348
+ // fail acceptance closed, while allowing a bounded repairing dispatch.
4349
+ // Filesystem/permission errors are infrastructure failures, not corruption.
4350
+ if (!(error instanceof SyntaxError)) throw error;
4351
+ reviews.push({ checkpointId: path.basename(file, '.json'), status: 'revise',
4352
+ invalidCheckpoint: true, file: path.relative(root, checkpointFile),
4353
+ finding: 'Checkpoint is invalid JSON or not an object.' });
4354
+ continue;
4355
+ }
4243
4356
  const review = buildCheckpointReview(taskContract.contract, acceptancePlan.plan, checkpoint);
4244
4357
  const reviewFile = path.join(root, devPlan.reviewsDir, `${checkpoint.checkpoint_id ?? path.basename(file, '.json')}.json`);
4245
- await writeJson(reviewFile, review);
4358
+ if (options.persist !== false) await writeJson(reviewFile, review);
4246
4359
  reviews.push({
4247
4360
  checkpointId: review.checkpoint_id,
4248
4361
  milestoneId: checkpoint.milestone_id ?? null,
4249
4362
  revisesCheckpointId: checkpoint.revises_checkpoint_id ?? null,
4363
+ taskId: checkpoint.task_id ?? null,
4364
+ checkpointDigest: createHash('sha256').update(checkpointBytes).digest('hex'),
4365
+ // Only status-only phase records may be closed without ordered clocks.
4366
+ // A real failed check or human gate needs its own repair/resolution.
4367
+ phaseOnly: checkpoint.status === 'in_progress' && review.status === 'revise'
4368
+ && review.failed.length === 1 && review.failed[0].check === 'checkpoint_status'
4369
+ && review.blocked.length === 0,
4370
+ revisionCoverage: checkpoint.revision_coverage ?? null,
4371
+ verification: checkpoint.verification ?? [],
4250
4372
  sequence: checkpoint.sequence ?? null,
4251
4373
  checkpointCreatedAt: checkpoint.created_at ?? null,
4252
4374
  createdAt: checkpoint.created_at ?? review.created_at,
@@ -4304,35 +4426,125 @@ function terminalTaskReview(review, contract = {}) {
4304
4426
  || review.taskTerminal === true;
4305
4427
  }
4306
4428
 
4429
+ // Explicit phase closure is an evidence-bound edge, not a fabricated clock.
4430
+ // Require every target to be unique, unchanged, same-task/same-milestone and
4431
+ // status-only. Coverage is cooperative evidence, not proof of test execution.
4432
+ function applyRevisionCoverage(reviews, planned, contract) {
4433
+ const byId = new Map();
4434
+ for (const review of reviews) {
4435
+ const entries = byId.get(review.checkpointId) ?? [];
4436
+ entries.push(review);
4437
+ byId.set(review.checkpointId, entries);
4438
+ }
4439
+ const covered = new Set();
4440
+ const invalid = new Set();
4441
+ for (const review of reviews) {
4442
+ if (review.revisionCoverage == null) continue;
4443
+ const coverage = review.revisionCoverage;
4444
+ const targets = [];
4445
+ const seen = new Set();
4446
+ let valid = review.status === 'accepted' && !review.invalidCheckpoint
4447
+ && byId.get(review.checkpointId)?.length === 1
4448
+ && review.taskId === contract.task_id && typeof review.taskId === 'string'
4449
+ && planned.some(cp => cp.id === review.milestoneId)
4450
+ && Array.isArray(coverage) && coverage.length > 0;
4451
+ for (const entry of Array.isArray(coverage) ? coverage : []) {
4452
+ const target = byId.get(entry?.checkpoint_id);
4453
+ const old = target?.length === 1 ? target[0] : null;
4454
+ const evidence = entry?.verification;
4455
+ // Any known backward/conflicting clock invalidates the explicit edge.
4456
+ const reversedClock = old && (
4457
+ (Number.isSafeInteger(old.sequence) && Number.isSafeInteger(review.sequence) && old.sequence >= review.sequence)
4458
+ || (Number.isFinite(Date.parse(old.checkpointCreatedAt)) && Number.isFinite(Date.parse(review.checkpointCreatedAt))
4459
+ && Date.parse(old.checkpointCreatedAt) >= Date.parse(review.checkpointCreatedAt)));
4460
+ if (!old || old === review || seen.has(old.checkpointId) || old.invalidCheckpoint
4461
+ || old.phaseOnly !== true || old.status !== 'revise' || old.revisionCoverage != null
4462
+ || (old.deferredGates?.length ?? 0) > 0
4463
+ || old.taskId !== review.taskId || !old.milestoneId || old.milestoneId !== review.milestoneId
4464
+ || !old.checkpointDigest || entry.checkpoint_sha256 !== old.checkpointDigest
4465
+ || typeof entry.resolution !== 'string' || !entry.resolution.trim()
4466
+ || !Array.isArray(evidence) || !evidence.length
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))
4471
+ || reversedClock) valid = false;
4472
+ if (old) { seen.add(old.checkpointId); targets.push(old); }
4473
+ }
4474
+ if (valid) targets.forEach(target => covered.add(target));
4475
+ else invalid.add(review);
4476
+ }
4477
+ // Invalid declarations remain an effective failure, never falling back to
4478
+ // chronological supersession or terminal locking.
4479
+ return reviews.filter(review => !covered.has(review)).map(review => invalid.has(review)
4480
+ ? { ...review, status: review.status === 'blocked' ? 'blocked' : 'revise', invalidRevisionCoverage: true }
4481
+ : review);
4482
+ }
4483
+
4307
4484
  export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract = {}) {
4308
- const allReviews = acceptanceReviews?.reviews ?? [];
4309
4485
  const planned = Array.isArray(devPlan?.checkpoints) ? devPlan.checkpoints : [];
4310
- if (planned.length <= 1) {
4311
- // Terminal acceptance remains monotonic only with known chronology.
4312
- // An unordered blocker cannot be dismissed as later project governance.
4313
- const terminal = allReviews.find(review => terminalTaskReview(review, contract)
4314
- && allReviews.every(other => other === review
4486
+ const allReviews = applyRevisionCoverage(acceptanceReviews?.reviews ?? [], planned, contract);
4487
+ const protectedReviews = allReviews.filter(review => review.invalidCheckpoint || review.invalidRevisionCoverage);
4488
+ const groups = new Map();
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) {
4505
+ // Explicit identities never inherit another milestone's clocks. Legacy
4506
+ // unlabelled snapshots retain the single-plan chronology compatibility.
4507
+ const key = chainKey(review);
4508
+ const group = groups.get(key) ?? [];
4509
+ group.push(review);
4510
+ groups.set(key, group);
4511
+ }
4512
+ const selected = [...protectedReviews];
4513
+ for (const reviews of groups.values()) {
4514
+ const terminal = planned.length <= 1 && reviews.find(review => terminalTaskReview(review, contract)
4515
+ && reviews.every(other => other === review
4315
4516
  || compareReviewRecency(review, other) > 0
4316
4517
  || (compareReviewRecency(review, other) < 0
4317
4518
  && projectCompletionStatus(other.projectCompletion) === 'needs_human_acceptance'
4318
- // A project label is not proof that a failed review is out of scope.
4319
- // Only independently accepted, gate-free governance can be ignored.
4320
4519
  && other.status === 'accepted'
4321
4520
  && (other.deferredGates?.length ?? 0) === 0)));
4322
- return terminal ? [terminal] : effectiveReviewFrontier(allReviews);
4323
- }
4324
- const selected = [];
4325
- for (const checkpoint of planned) {
4326
- const milestoneId = checkpoint.id;
4327
- const candidates = allReviews.filter((review) =>
4328
- review.milestoneId === milestoneId || review.checkpointId === milestoneId
4329
- );
4330
- if (candidates.length === 0) continue;
4331
- selected.push(...effectiveReviewFrontier(candidates));
4521
+ selected.push(...(terminal ? [terminal] : effectiveReviewFrontier(reviews)));
4332
4522
  }
4333
4523
  return selected;
4334
4524
  }
4335
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
+
4535
+ function acceptedMilestoneIds(devPlan, acceptanceReviews, contract) {
4536
+ const effective = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4537
+ const planned = devPlan?.checkpoints ?? [];
4538
+ return planned.filter(cp => {
4539
+ // Single-plan frontier selection supports legacy revision snapshots, but
4540
+ // that does not bind those snapshots to a newly named milestone. Progress
4541
+ // needs a durable checkpoint/milestone identity, never just the plan label.
4542
+ const reviews = effective.filter(r =>
4543
+ reviewCoversMilestone(r, cp.id, planned.length));
4544
+ return reviews.length > 0 && reviews.every(r => r.status === 'accepted');
4545
+ }).map(cp => cp.id);
4546
+ }
4547
+
4336
4548
  export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, context = {}) {
4337
4549
  const reasons = [];
4338
4550
  const nextActions = [];
@@ -4344,9 +4556,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4344
4556
  // resolved historical blocker does not permanently poison the task.
4345
4557
  const effectiveReviews = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4346
4558
  const reviewCount = effectiveReviews.length;
4347
- const acceptedCount = requiredCheckpoints > 1
4559
+ const acceptedCount = requiredCheckpoints > 0
4348
4560
  ? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
4349
- && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id))).length
4561
+ && (reviewCoversMilestone(review, checkpoint.id, requiredCheckpoints)
4562
+ || (requiredCheckpoints === 1 && review.milestoneId == null)))).length
4350
4563
  : effectiveReviews.filter((item) => item.status === 'accepted').length;
4351
4564
  const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
4352
4565
  const blockedCount = effectiveReviews.filter((item) => item.status === 'blocked').length;
@@ -4359,6 +4572,16 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4359
4572
  );
4360
4573
  const effectiveResidualRisks = [...new Set(effectiveReviews.flatMap((review) => review.checkpointRisks ?? []))];
4361
4574
  const deferredGateCount = effectiveReviews.reduce((count, review) => count + (review.deferredGates?.length ?? 0), 0);
4575
+ const acceptedMilestones = acceptedMilestoneIds(devPlan, acceptanceReviews, contract);
4576
+ // Count files neither proves acceptance nor distinguishes a repair from a
4577
+ // duplicate snapshot. Compare committed milestone acceptance at dispatch.
4578
+ const priorAccepted = context.priorAcceptedMilestoneIds;
4579
+ const noProgressContinuation = contract.task_scope === 'project' && !projectCompletionAccepted && dispatchStatus === 'completed' &&
4580
+ (Array.isArray(priorAccepted)
4581
+ ? Number.isInteger(context.priorCheckpointCount) && context.priorCheckpointCount > 0 &&
4582
+ !acceptedMilestones.some(id => !priorAccepted.includes(id))
4583
+ : Number.isInteger(context.priorCheckpointCount) && context.priorCheckpointCount > 0 &&
4584
+ checkpointCount <= context.priorCheckpointCount);
4362
4585
  let outcome = 'needs_revision';
4363
4586
 
4364
4587
  // A worker can stop after persisting a blocker but before writing a handoff.
@@ -4407,6 +4630,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4407
4630
  outcome = 'blocked';
4408
4631
  reasons.push(`${blockedCount} acceptance review(s) are blocked.`);
4409
4632
  nextActions.push('Resolve blockers or request the required human/external input.');
4633
+ } else if (allReviews.some(review => review.invalidCheckpoint === true) || context.invalidCheckpointBaseline === true) {
4634
+ outcome = 'needs_revision';
4635
+ reasons.push('Invalid checkpoint evidence or unknown pre-dispatch baseline prevents automatic acceptance.');
4636
+ nextActions.push('Repair invalid records and explicitly revise from a validated baseline; unknown history is not new accepted progress.');
4410
4637
  } else if (reviseCount > 0) {
4411
4638
  outcome = 'needs_revision';
4412
4639
  reasons.push(`${reviseCount} acceptance review(s) require development revision.`);
@@ -4415,6 +4642,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4415
4642
  outcome = 'needs_revision';
4416
4643
  reasons.push(`Accepted checkpoints (${acceptedCount}) do not cover required checkpoints (${Math.max(requiredCheckpoints, 1)}).`);
4417
4644
  nextActions.push('Complete and review the remaining planned checkpoints.');
4645
+ } else if (noProgressContinuation) {
4646
+ outcome = 'needs_revision';
4647
+ reasons.push('Project dispatch produced no new committed and accepted milestone.');
4648
+ nextActions.push('Select and commit a concrete next batch before automatic continuation.');
4418
4649
  } else if ((contract.task_scope === 'project' || projectCompletionInProgress || explicitContinuationReviews.length > 0 || deferredGateCount > 0) && !projectCompletionAccepted) {
4419
4650
  outcome = 'project_in_progress';
4420
4651
  reasons.push('The latest milestone is accepted, but the project terminal contract is not accepted.');
@@ -4440,6 +4671,12 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4440
4671
  risk_level: contract.risk_level,
4441
4672
  requires_human_gate: contract.requires_human_gate,
4442
4673
  dispatch_status: dispatchStatus,
4674
+ invalid_checkpoint_baseline: context.invalidCheckpointBaseline === true,
4675
+ no_progress_continuation: noProgressContinuation && outcome === 'needs_revision',
4676
+ no_progress_accepted_milestone_baseline: noProgressContinuation
4677
+ ? (Array.isArray(priorAccepted) ? priorAccepted : acceptedMilestones) : null,
4678
+ no_progress_plan_baseline: noProgressContinuation && Number.isInteger(context.priorPlannedCheckpointCount)
4679
+ ? context.priorPlannedCheckpointCount : null,
4443
4680
  reasons,
4444
4681
  next_actions: nextActions,
4445
4682
  sources: {
@@ -10079,7 +10316,12 @@ export async function runQueueOnce(root, options) {
10079
10316
  let finalJudgement = null;
10080
10317
  let revisionRequest = null;
10081
10318
  let contextUsage = null;
10319
+ let priorAcceptedMilestoneIds = null;
10320
+ let invalidCheckpointBaseline = false;
10321
+ let priorCheckpointCount = null;
10322
+ let priorPlannedCheckpointCount = null;
10082
10323
  let contextHandoff = null;
10324
+ let handoffProgressFingerprint = null;
10083
10325
  const contextPrefix = path.join(taskRuntimeDirFor(root, queue, task.id), runId);
10084
10326
 
10085
10327
  try {
@@ -10105,6 +10347,16 @@ export async function runQueueOnce(root, options) {
10105
10347
  manualChecks: acceptancePlan.plan.manual_review.length
10106
10348
  });
10107
10349
  devPlan = await writeDevPlan(root, queue, task, taskContract, acceptancePlan);
10350
+ const priorReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, { persist: false });
10351
+ invalidCheckpointBaseline = priorReviews.reviews.some(review => review.invalidCheckpoint === true);
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
10357
+ : acceptedMilestoneIds(devPlan.plan, priorReviews, taskContract.contract);
10358
+ priorCheckpointCount = resumingUnjudgedRun ? null : (await checkpointSummary(root, devPlan)).count;
10359
+ priorPlannedCheckpointCount = devPlan.plan.checkpoints?.length ?? null;
10108
10360
  progress.emit('planning', 'dev_plan', 'Wrote development plan', {
10109
10361
  taskId: task.id,
10110
10362
  artifact: devPlan.file,
@@ -10212,6 +10464,15 @@ export async function runQueueOnce(root, options) {
10212
10464
  contextHandoff = handoff;
10213
10465
  if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
10214
10466
  else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
10467
+ handoffProgressFingerprint = proof.progressFingerprint;
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) {
10474
+ finalStatus = 'runtime_blocked';
10475
+ }
10215
10476
  dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
10216
10477
  dispatchAttempts[dispatchAttempts.length - 1].failureClassification = dispatchClassification;
10217
10478
  }
@@ -10226,7 +10487,7 @@ export async function runQueueOnce(root, options) {
10226
10487
  } else if (dispatchClassification?.recoverableRuntime) {
10227
10488
  const recoveryCount = Number(task.runtimeRecoveryCount ?? 0);
10228
10489
  const recoveryMax = Number(options.retry?.runtimeRecoveryMaxAttempts ?? 2);
10229
- finalStatus = recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
10490
+ finalStatus = dispatchClassification.category === 'context_handoff' || recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
10230
10491
  } else if (dispatch?.exitCode === 0 && worktreeEnabled(options)) {
10231
10492
  verification = await runVerifyCommands(options.worktree?.verifyCommands ?? [], worktree.path, timeoutMs, progress,
10232
10493
  'verification', options.worktree?.isolatedVerification ? {
@@ -10253,6 +10514,10 @@ export async function runQueueOnce(root, options) {
10253
10514
  });
10254
10515
  }
10255
10516
  }
10517
+ // Judge durable post-dispatch plans, not cached launch-time objects.
10518
+ taskContract = { ...taskContract, contract: await readJson(path.join(root, taskContract.file)) };
10519
+ acceptancePlan = { ...acceptancePlan, plan: await readJson(path.join(root, acceptancePlan.file)) };
10520
+ devPlan = { ...devPlan, plan: await readJson(path.join(root, devPlan.file)) };
10256
10521
  checkpoints = await checkpointSummary(root, devPlan);
10257
10522
  await reconcileHumanInputGates(root, queue, task.id);
10258
10523
  progress.emit('acceptance', 'checkpoint_summary', `Collected ${checkpoints.count} checkpoint(s)`, {
@@ -10289,6 +10554,10 @@ export async function runQueueOnce(root, options) {
10289
10554
  });
10290
10555
  if (!finalJudgement) finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
10291
10556
  dispatchStatus: finalStatus,
10557
+ priorAcceptedMilestoneIds,
10558
+ invalidCheckpointBaseline,
10559
+ priorCheckpointCount,
10560
+ priorPlannedCheckpointCount,
10292
10561
  dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
10293
10562
  verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
10294
10563
  });
@@ -10326,11 +10595,30 @@ export async function runQueueOnce(root, options) {
10326
10595
  if (!finalJudgement) {
10327
10596
  finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
10328
10597
  dispatchStatus: finalStatus,
10598
+ priorAcceptedMilestoneIds,
10599
+ invalidCheckpointBaseline,
10600
+ priorCheckpointCount,
10601
+ priorPlannedCheckpointCount,
10329
10602
  dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
10330
10603
  verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
10331
10604
  });
10332
10605
  finalStatus = queueStatusFromFinalJudgement(finalStatus, finalJudgement);
10333
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
+ }
10334
10622
  if (!revisionRequest) {
10335
10623
  revisionRequest = await writeRevisionRequest(root, queue, task, taskContract, acceptancePlan, devPlan, finalJudgement, acceptanceReviews);
10336
10624
  }
@@ -10361,6 +10649,8 @@ export async function runQueueOnce(root, options) {
10361
10649
  completedTask.projectContinuedAt = finishedAt;
10362
10650
  completedTask.projectContinuationCount = (task.projectContinuationCount ?? 0) + 1;
10363
10651
  completedTask.runtimeRecoveryCount = 0;
10652
+ completedTask.contextHandoffCount = 0;
10653
+ completedTask.contextHandoffProgress = [];
10364
10654
  completedTask.sessionTickCount = Number(task.sessionTickCount ?? 0) + 1;
10365
10655
  const rotation = contextRotation(contextUsage, completedTask.sessionTickCount, budgetPolicy);
10366
10656
  completedTask.contextBudget = rotation;
@@ -10372,13 +10662,21 @@ export async function runQueueOnce(root, options) {
10372
10662
  }
10373
10663
  }
10374
10664
  if (finalStatus === 'runtime_interrupted') {
10375
- completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + 1;
10665
+ const normalHandoff = dispatchAttempts.at(-1)?.failureClassification?.category === 'context_handoff';
10666
+ completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + (normalHandoff ? 0 : 1);
10667
+ if (normalHandoff) {
10668
+ completedTask.contextHandoffCount = Number(task.contextHandoffCount ?? 0) + 1;
10669
+ completedTask.contextHandoffProgress = [...(task.contextHandoffProgress ?? []), handoffProgressFingerprint];
10670
+ }
10376
10671
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10377
10672
  completedTask.sessionTickCount = 0;
10378
- if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
10379
10673
  completedTask.runtimeInterruptedAt = finishedAt;
10380
10674
  completedTask.runtimeInterruption = dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null;
10381
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;
10382
10680
  const completedFile = path.join(destination, path.basename(activeFile));
10383
10681
  // Claim the active file by moving it. If an operator canceled or parked
10384
10682
  // the task meanwhile, the file is gone and their copy stays authoritative