taskforce-loop-engineering 0.16.2 → 0.16.4

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
@@ -9,6 +9,7 @@ import { createHash, randomUUID } from 'node:crypto';
9
9
  import { contextPolicy, contextRotation, readBoundedJson, validHandoff, handoffCheckpoint } from './context-budget.mjs';
10
10
  import { listSteps } from './execution-ledger.mjs';
11
11
  import { readAndVerifyEvidence } from './production-evidence.mjs';
12
+ import { validateIsolatedVerification, runIsolatedVerification, isolatedEvidenceDir } from './isolated-verification.mjs';
12
13
 
13
14
  export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
14
15
 
@@ -1335,7 +1336,12 @@ async function gateProjectMetadata(root, task, checkpoint) {
1335
1336
  }
1336
1337
 
1337
1338
  function gateInvalidity(gate, spec) {
1338
- if (!spec) return { code: 'project_not_found', status: 'superseded' };
1339
+ // Human-input gates may be task-scoped and intentionally have no project
1340
+ // binding. Project reconciliation must leave those gates alone; only a gate
1341
+ // that explicitly names a missing project is stale project state.
1342
+ if (!spec) return gate.project_id
1343
+ ? { code: 'project_not_found', status: 'superseded' }
1344
+ : null;
1339
1345
  const backlog = new Map((spec.backlog ?? []).map((item) => [String(item.id), item]));
1340
1346
  for (const id of gate.requirement_ids ?? []) {
1341
1347
  const requirement = backlog.get(String(id));
@@ -2515,18 +2521,22 @@ export async function refreshTaskAcceptance(root, options = {}) {
2515
2521
  const checkpointFiles = await listJson(checkpointsDir);
2516
2522
  if (checkpointFiles.length === 0) return { queue, taskId: task.id, outcome: 'no_checkpoints' };
2517
2523
  const judgementFile = path.join(dir, 'final_judgement.json');
2518
- const newestCheckpointMs = Math.max(...await Promise.all(checkpointFiles.map(async (file) => (await stat(path.join(checkpointsDir, file))).mtimeMs)));
2519
- if (await exists(judgementFile) && (await stat(judgementFile)).mtimeMs >= newestCheckpointMs) {
2520
- return { queue, taskId: task.id, outcome: 'already_current', judgement: path.relative(root, judgementFile) };
2521
- }
2522
-
2523
2524
  const contractFile = path.join(dir, 'task_contract.json');
2524
2525
  const acceptanceFile = path.join(dir, 'acceptance_plan.json');
2525
2526
  const devFile = path.join(dir, 'dev_plan.json');
2527
+ // Plan amendments change required coverage even without a new checkpoint.
2528
+ const evidenceFiles = [...checkpointFiles.map((file) => path.join(checkpointsDir, file)), contractFile, acceptanceFile, devFile];
2529
+ const newestEvidenceMs = Math.max(...await Promise.all(evidenceFiles.map(async (file) => (await stat(file)).mtimeMs)));
2530
+ const currentDevPlan = await readJson(devFile);
2531
+ const priorJudgement = await readJson(judgementFile).catch(() => null);
2532
+ const coverageMatchesPlan = priorJudgement?.coverage?.planned_checkpoints === currentDevPlan.checkpoints?.length;
2533
+ if (priorJudgement && coverageMatchesPlan && (await stat(judgementFile)).mtimeMs >= newestEvidenceMs) {
2534
+ return { queue, taskId: task.id, outcome: 'already_current', judgement: path.relative(root, judgementFile) };
2535
+ }
2526
2536
  const taskContract = { contract: await readJson(contractFile), file: path.relative(root, contractFile) };
2527
2537
  const acceptancePlan = { plan: await readJson(acceptanceFile), file: path.relative(root, acceptanceFile) };
2528
2538
  const devPlan = {
2529
- plan: await readJson(devFile),
2539
+ plan: currentDevPlan,
2530
2540
  file: path.relative(root, devFile),
2531
2541
  checkpointsDir: path.relative(root, checkpointsDir),
2532
2542
  reviewsDir: path.relative(root, path.join(dir, 'reviews'))
@@ -2534,7 +2544,14 @@ export async function refreshTaskAcceptance(root, options = {}) {
2534
2544
  const checkpoints = await checkpointSummary(root, devPlan);
2535
2545
  const acceptanceReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan);
2536
2546
  const finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
2537
- dispatchStatus: 'completed'
2547
+ dispatchStatus: 'completed',
2548
+ invalidCheckpointBaseline: priorJudgement?.invalid_checkpoint_baseline === true,
2549
+ priorAcceptedMilestoneIds: priorJudgement?.no_progress_continuation === true
2550
+ ? priorJudgement.no_progress_accepted_milestone_baseline : null,
2551
+ priorCheckpointCount: priorJudgement?.no_progress_continuation === true
2552
+ ? priorJudgement.coverage?.produced_checkpoints : null,
2553
+ priorPlannedCheckpointCount: priorJudgement?.no_progress_continuation === true
2554
+ ? (priorJudgement.no_progress_plan_baseline ?? priorJudgement.coverage?.planned_checkpoints) : null
2538
2555
  });
2539
2556
  const status = queueStatusFromFinalJudgement('completed', finalJudgement);
2540
2557
  const destinationName = status === 'completed' ? 'done' : status === 'project_in_progress' ? 'inbox' : 'failed';
@@ -3290,7 +3307,17 @@ async function reconcileHumanInputGates(root, queue, taskId) {
3290
3307
  const gatesDir = path.join(queueDirFor(root, queue), 'human-input', 'gates');
3291
3308
  const checkpointsDir = path.join(taskRuntimeDirFor(root, queue, taskId), 'checkpoints');
3292
3309
  const checkpoints = [];
3293
- for (const file of await listJson(checkpointsDir)) checkpoints.push(await readJson(path.join(checkpointsDir, file)));
3310
+ for (const file of await listJson(checkpointsDir)) {
3311
+ let checkpoint;
3312
+ try { checkpoint = await readJson(path.join(checkpointsDir, file)); }
3313
+ catch (error) {
3314
+ if (!(error instanceof SyntaxError)) throw error;
3315
+ // Unknown evidence cannot satisfy a consumed gate. Preserve all gates.
3316
+ return;
3317
+ }
3318
+ if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) return;
3319
+ checkpoints.push(checkpoint);
3320
+ }
3294
3321
  for (const file of await listJson(gatesDir)) {
3295
3322
  const full = path.join(gatesDir, file);
3296
3323
  const gate = await readJson(full);
@@ -3463,13 +3490,43 @@ async function taskProjectAuthorization(root, task) {
3463
3490
  }
3464
3491
 
3465
3492
  export function inferTaskScope(task) {
3493
+ if (task?.taskScope === 'project' || task?.taskScope === 'scoped_task') return task.taskScope;
3466
3494
  const requestText = `${task?.title ?? ''}\n${task?.body ?? ''}`.toLowerCase();
3467
3495
  // A project can be referenced as context while the routed task is explicitly
3468
3496
  // bounded to one milestone or backlog item. Those bounded instructions must
3469
3497
  // win; otherwise phrases such as "do not call the overall project complete"
3470
3498
  // incorrectly turn an accepted milestone into an endlessly requeued project
3471
3499
  // task.
3472
- const boundedMilestone = /(?:only|仅|只)(?:推进|处理|执行|完成|验证)|阶段完成|任务完成|第\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|决策|修订)/.test(requestText);
3500
+ // Apply the same object-local negation rule to EVERY local-scope cue.
3501
+ // Removing a negated cue also prevents a nested cue ("backlog item" or
3502
+ // "第一步") 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;
3504
+ // Negation governs the following object phrase, including arbitrary modifiers.
3505
+ // End its scope at clause/contrast boundaries or an explicit context object,
3506
+ // not at a whitelist of adjectives (first/initial/one/etc.). Coordinated
3507
+ // comma + or/and phrases share the governing negation.
3508
+ const negatedPrefix = (prefix) => {
3509
+ // Explicit double-negative obligations are affirmative. Do not count every
3510
+ // negative word: unrelated prohibitions can coexist in the same clause.
3511
+ prefix = prefix.replace(/(?:\b(?:not|never)|n['’]t)\s+(?:fail\s+to|avoid(?:\s+doing)?)\b|\bwithout\s+failing\s+to\b|(?:不能不|不得不|不是不)/g, ' ');
3512
+ const negations = [...prefix.matchAll(/(?:不|勿|别)|\b(?:not|never|no|without|neither|nor)\b|n['’]t\b/g)];
3513
+ if (!negations.length) return false;
3514
+ const tail = prefix.slice(negations.at(-1).index);
3515
+ // These boundaries introduce a separate affirmative instruction after a
3516
+ // 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);
3518
+ };
3519
+ const boundedMilestone = requestText.split(/[,,](?!\s*(?:or\b|and\b|nor\b|或|以及))|[。;;.!?\n]|\bbut\b|而是|但是/).some((clause) => {
3520
+ let prefix = '';
3521
+ let offset = 0;
3522
+ for (const match of clause.matchAll(cue)) {
3523
+ prefix += clause.slice(offset, match.index);
3524
+ if (!negatedPrefix(prefix)) return true;
3525
+ // Keep the governing negation for coordinated/nested local cues.
3526
+ offset = match.index + match[0].length;
3527
+ }
3528
+ return false;
3529
+ });
3473
3530
  if (boundedMilestone) return 'scoped_task';
3474
3531
  return /project[-_ ]level|项目级|完整项目|整体项目|single milestone|单(?:一)?里程碑/.test(requestText)
3475
3532
  ? 'project'
@@ -3610,6 +3667,13 @@ export async function writeTaskContract(root, queue, task, options = {}) {
3610
3667
  historicalPatterns,
3611
3668
  projectAuthorization: options.projectAuthorization ?? await taskProjectAuthorization(root, task)
3612
3669
  });
3670
+ if (contract.task_scope === 'project') {
3671
+ const existing = await readJson(file).catch(() => null);
3672
+ if (existing?.task_id === task.id && existing.task_scope === 'project') {
3673
+ contract.deliverables = existing.deliverables ?? contract.deliverables;
3674
+ contract.acceptance_summary = existing.acceptance_summary ?? contract.acceptance_summary;
3675
+ }
3676
+ }
3613
3677
  contract = await mergeLiveAmendments(root, queue, task.id, contract, 'supplemental_requirements');
3614
3678
  await writeJson(file, contract);
3615
3679
  return {
@@ -3829,6 +3893,13 @@ export async function writeAcceptancePlan(root, queue, task, taskContract, optio
3829
3893
  const dir = taskRuntimeDirFor(root, queue, task.id);
3830
3894
  const file = path.join(dir, 'acceptance_plan.json');
3831
3895
  let plan = buildAcceptancePlan(taskContract.contract, options);
3896
+ if (taskContract.contract.task_scope === 'project') {
3897
+ const existing = await readJson(file).catch(() => null);
3898
+ if (existing?.task_id === task.id &&
3899
+ existing.generated_by === 'project_scope_worker_revision_after_deterministic_planner_v1') {
3900
+ plan = existing;
3901
+ }
3902
+ }
3832
3903
  plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_checks');
3833
3904
  await writeJson(file, plan);
3834
3905
  return {
@@ -3874,6 +3945,7 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
3874
3945
  checkpoint_id: firstCheckpointId,
3875
3946
  milestone_id: firstCheckpointId,
3876
3947
  revises_checkpoint_id: null,
3948
+ revision_coverage: null,
3877
3949
  status: 'ready_for_acceptance | blocked | needs_human_input',
3878
3950
  summary: 'What changed and why.',
3879
3951
  files_changed: [],
@@ -3915,6 +3987,21 @@ export async function writeDevPlan(root, queue, task, taskContract, acceptancePl
3915
3987
  while (usedCheckpointNumbers.has(checkpointNumber)) checkpointNumber += 1;
3916
3988
  const nextCheckpointId = `cp${checkpointNumber}`;
3917
3989
  let plan = buildDevPlan(taskContract.contract, acceptancePlan.plan, nextCheckpointId);
3990
+ if (taskContract.contract.task_scope === 'project') {
3991
+ const existing = await readJson(file).catch(() => null);
3992
+ if (existing?.task_id === task.id &&
3993
+ existing.generated_by === 'project_scope_worker_revision_after_deterministic_planner_v1' &&
3994
+ Array.isArray(existing.checkpoints)) {
3995
+ plan = {
3996
+ ...existing,
3997
+ // A continuation candidate is not a committed milestone. The worker
3998
+ // adds a concrete checkpoint only after choosing its bounded batch;
3999
+ // otherwise final judgement mistakes N accepted for N/N+1 required.
4000
+ checkpoints: existing.checkpoints,
4001
+ checkpoint_schema: plan.checkpoint_schema
4002
+ };
4003
+ }
4004
+ }
3918
4005
  plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_instructions');
3919
4006
  await writeJson(file, plan);
3920
4007
  return {
@@ -4197,21 +4284,47 @@ function summarizeCriticReviews(reviews) {
4197
4284
  return byCritic;
4198
4285
  }
4199
4286
 
4200
- export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan) {
4287
+ export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, options = {}) {
4201
4288
  if (!devPlan?.reviewsDir || !devPlan?.checkpointsDir) return null;
4202
4289
  const checkpointFiles = await listJson(path.join(root, devPlan.checkpointsDir));
4203
4290
  const reviews = [];
4204
4291
  const reviewArtifacts = [];
4205
4292
  for (const file of checkpointFiles) {
4206
4293
  const checkpointFile = path.join(root, devPlan.checkpointsDir, file);
4207
- const checkpoint = await readJson(checkpointFile);
4294
+ let checkpoint;
4295
+ let checkpointBytes;
4296
+ try {
4297
+ checkpointBytes = await readFile(checkpointFile, 'utf8');
4298
+ checkpoint = JSON.parse(checkpointBytes);
4299
+ if (!checkpoint || typeof checkpoint !== 'object' || Array.isArray(checkpoint)) {
4300
+ throw new SyntaxError('Checkpoint must be a JSON object');
4301
+ }
4302
+ } catch (error) {
4303
+ // Invalid evidence is not an absent checkpoint. Keep it explicit and
4304
+ // fail acceptance closed, while allowing a bounded repairing dispatch.
4305
+ // Filesystem/permission errors are infrastructure failures, not corruption.
4306
+ if (!(error instanceof SyntaxError)) throw error;
4307
+ reviews.push({ checkpointId: path.basename(file, '.json'), status: 'revise',
4308
+ invalidCheckpoint: true, file: path.relative(root, checkpointFile),
4309
+ finding: 'Checkpoint is invalid JSON or not an object.' });
4310
+ continue;
4311
+ }
4208
4312
  const review = buildCheckpointReview(taskContract.contract, acceptancePlan.plan, checkpoint);
4209
4313
  const reviewFile = path.join(root, devPlan.reviewsDir, `${checkpoint.checkpoint_id ?? path.basename(file, '.json')}.json`);
4210
- await writeJson(reviewFile, review);
4314
+ if (options.persist !== false) await writeJson(reviewFile, review);
4211
4315
  reviews.push({
4212
4316
  checkpointId: review.checkpoint_id,
4213
4317
  milestoneId: checkpoint.milestone_id ?? null,
4214
4318
  revisesCheckpointId: checkpoint.revises_checkpoint_id ?? null,
4319
+ taskId: checkpoint.task_id ?? null,
4320
+ checkpointDigest: createHash('sha256').update(checkpointBytes).digest('hex'),
4321
+ // Only status-only phase records may be closed without ordered clocks.
4322
+ // A real failed check or human gate needs its own repair/resolution.
4323
+ phaseOnly: checkpoint.status === 'in_progress' && review.status === 'revise'
4324
+ && review.failed.length === 1 && review.failed[0].check === 'checkpoint_status'
4325
+ && review.blocked.length === 0,
4326
+ revisionCoverage: checkpoint.revision_coverage ?? null,
4327
+ verification: checkpoint.verification ?? [],
4215
4328
  sequence: checkpoint.sequence ?? null,
4216
4329
  checkpointCreatedAt: checkpoint.created_at ?? null,
4217
4330
  createdAt: checkpoint.created_at ?? review.created_at,
@@ -4269,35 +4382,98 @@ function terminalTaskReview(review, contract = {}) {
4269
4382
  || review.taskTerminal === true;
4270
4383
  }
4271
4384
 
4385
+ // Explicit phase closure is an evidence-bound edge, not a fabricated clock.
4386
+ // Require every target to be unique, unchanged, same-task/same-milestone and
4387
+ // status-only. Coverage is cooperative evidence, not proof of test execution.
4388
+ function applyRevisionCoverage(reviews, planned, contract) {
4389
+ const byId = new Map();
4390
+ for (const review of reviews) {
4391
+ const entries = byId.get(review.checkpointId) ?? [];
4392
+ entries.push(review);
4393
+ byId.set(review.checkpointId, entries);
4394
+ }
4395
+ const covered = new Set();
4396
+ const invalid = new Set();
4397
+ for (const review of reviews) {
4398
+ if (review.revisionCoverage == null) continue;
4399
+ const coverage = review.revisionCoverage;
4400
+ const targets = [];
4401
+ const seen = new Set();
4402
+ let valid = review.status === 'accepted' && !review.invalidCheckpoint
4403
+ && byId.get(review.checkpointId)?.length === 1
4404
+ && review.taskId === contract.task_id && typeof review.taskId === 'string'
4405
+ && planned.some(cp => cp.id === review.milestoneId)
4406
+ && Array.isArray(coverage) && coverage.length > 0;
4407
+ for (const entry of Array.isArray(coverage) ? coverage : []) {
4408
+ const target = byId.get(entry?.checkpoint_id);
4409
+ const old = target?.length === 1 ? target[0] : null;
4410
+ const evidence = entry?.verification;
4411
+ // Any known backward/conflicting clock invalidates the explicit edge.
4412
+ const reversedClock = old && (
4413
+ (Number.isSafeInteger(old.sequence) && Number.isSafeInteger(review.sequence) && old.sequence >= review.sequence)
4414
+ || (Number.isFinite(Date.parse(old.checkpointCreatedAt)) && Number.isFinite(Date.parse(review.checkpointCreatedAt))
4415
+ && Date.parse(old.checkpointCreatedAt) >= Date.parse(review.checkpointCreatedAt)));
4416
+ if (!old || old === review || seen.has(old.checkpointId) || old.invalidCheckpoint
4417
+ || old.phaseOnly !== true || old.status !== 'revise' || old.revisionCoverage != null
4418
+ || (old.deferredGates?.length ?? 0) > 0
4419
+ || old.taskId !== review.taskId || !old.milestoneId || old.milestoneId !== review.milestoneId
4420
+ || !old.checkpointDigest || entry.checkpoint_sha256 !== old.checkpointDigest
4421
+ || typeof entry.resolution !== 'string' || !entry.resolution.trim()
4422
+ || !Array.isArray(evidence) || !evidence.length
4423
+ || !evidence.every(item => typeof item === 'string' && item.trim() && review.verification?.includes(item))
4424
+ || reversedClock) valid = false;
4425
+ if (old) { seen.add(old.checkpointId); targets.push(old); }
4426
+ }
4427
+ if (valid) targets.forEach(target => covered.add(target));
4428
+ else invalid.add(review);
4429
+ }
4430
+ // Invalid declarations remain an effective failure, never falling back to
4431
+ // chronological supersession or terminal locking.
4432
+ return reviews.filter(review => !covered.has(review)).map(review => invalid.has(review)
4433
+ ? { ...review, status: review.status === 'blocked' ? 'blocked' : 'revise', invalidRevisionCoverage: true }
4434
+ : review);
4435
+ }
4436
+
4272
4437
  export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract = {}) {
4273
- const allReviews = acceptanceReviews?.reviews ?? [];
4274
4438
  const planned = Array.isArray(devPlan?.checkpoints) ? devPlan.checkpoints : [];
4275
- if (planned.length <= 1) {
4276
- // Terminal acceptance remains monotonic only with known chronology.
4277
- // An unordered blocker cannot be dismissed as later project governance.
4278
- const terminal = allReviews.find(review => terminalTaskReview(review, contract)
4279
- && allReviews.every(other => other === review
4439
+ const allReviews = applyRevisionCoverage(acceptanceReviews?.reviews ?? [], planned, contract);
4440
+ const protectedReviews = allReviews.filter(review => review.invalidCheckpoint || review.invalidRevisionCoverage);
4441
+ const groups = new Map();
4442
+ for (const review of allReviews.filter(review => !protectedReviews.includes(review))) {
4443
+ // Explicit identities never inherit another milestone's clocks. Legacy
4444
+ // unlabelled snapshots retain the single-plan chronology compatibility.
4445
+ const key = review.milestoneId ?? (planned.length <= 1 ? planned[0]?.id ?? '__legacy__' : review.checkpointId);
4446
+ const group = groups.get(key) ?? [];
4447
+ group.push(review);
4448
+ groups.set(key, group);
4449
+ }
4450
+ const selected = [...protectedReviews];
4451
+ for (const reviews of groups.values()) {
4452
+ const terminal = planned.length <= 1 && reviews.find(review => terminalTaskReview(review, contract)
4453
+ && reviews.every(other => other === review
4280
4454
  || compareReviewRecency(review, other) > 0
4281
4455
  || (compareReviewRecency(review, other) < 0
4282
4456
  && projectCompletionStatus(other.projectCompletion) === 'needs_human_acceptance'
4283
- // A project label is not proof that a failed review is out of scope.
4284
- // Only independently accepted, gate-free governance can be ignored.
4285
4457
  && other.status === 'accepted'
4286
4458
  && (other.deferredGates?.length ?? 0) === 0)));
4287
- return terminal ? [terminal] : effectiveReviewFrontier(allReviews);
4288
- }
4289
- const selected = [];
4290
- for (const checkpoint of planned) {
4291
- const milestoneId = checkpoint.id;
4292
- const candidates = allReviews.filter((review) =>
4293
- review.milestoneId === milestoneId || review.checkpointId === milestoneId
4294
- );
4295
- if (candidates.length === 0) continue;
4296
- selected.push(...effectiveReviewFrontier(candidates));
4459
+ selected.push(...(terminal ? [terminal] : effectiveReviewFrontier(reviews)));
4297
4460
  }
4298
4461
  return selected;
4299
4462
  }
4300
4463
 
4464
+ function acceptedMilestoneIds(devPlan, acceptanceReviews, contract) {
4465
+ const effective = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4466
+ const planned = devPlan?.checkpoints ?? [];
4467
+ return planned.filter(cp => {
4468
+ // Single-plan frontier selection supports legacy revision snapshots, but
4469
+ // that does not bind those snapshots to a newly named milestone. Progress
4470
+ // needs a durable checkpoint/milestone identity, never just the plan label.
4471
+ const reviews = effective.filter(r =>
4472
+ r.milestoneId === cp.id || r.checkpointId === cp.id);
4473
+ return reviews.length > 0 && reviews.every(r => r.status === 'accepted');
4474
+ }).map(cp => cp.id);
4475
+ }
4476
+
4301
4477
  export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, context = {}) {
4302
4478
  const reasons = [];
4303
4479
  const nextActions = [];
@@ -4309,9 +4485,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4309
4485
  // resolved historical blocker does not permanently poison the task.
4310
4486
  const effectiveReviews = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
4311
4487
  const reviewCount = effectiveReviews.length;
4312
- const acceptedCount = requiredCheckpoints > 1
4488
+ const acceptedCount = requiredCheckpoints > 0
4313
4489
  ? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
4314
- && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id))).length
4490
+ && (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id
4491
+ || (requiredCheckpoints === 1 && review.milestoneId == null)))).length
4315
4492
  : effectiveReviews.filter((item) => item.status === 'accepted').length;
4316
4493
  const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
4317
4494
  const blockedCount = effectiveReviews.filter((item) => item.status === 'blocked').length;
@@ -4324,6 +4501,16 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4324
4501
  );
4325
4502
  const effectiveResidualRisks = [...new Set(effectiveReviews.flatMap((review) => review.checkpointRisks ?? []))];
4326
4503
  const deferredGateCount = effectiveReviews.reduce((count, review) => count + (review.deferredGates?.length ?? 0), 0);
4504
+ const acceptedMilestones = acceptedMilestoneIds(devPlan, acceptanceReviews, contract);
4505
+ // Count files neither proves acceptance nor distinguishes a repair from a
4506
+ // duplicate snapshot. Compare committed milestone acceptance at dispatch.
4507
+ const priorAccepted = context.priorAcceptedMilestoneIds;
4508
+ const noProgressContinuation = contract.task_scope === 'project' && !projectCompletionAccepted && dispatchStatus === 'completed' &&
4509
+ (Array.isArray(priorAccepted)
4510
+ ? Number.isInteger(context.priorCheckpointCount) && context.priorCheckpointCount > 0 &&
4511
+ !acceptedMilestones.some(id => !priorAccepted.includes(id))
4512
+ : Number.isInteger(context.priorCheckpointCount) && context.priorCheckpointCount > 0 &&
4513
+ checkpointCount <= context.priorCheckpointCount);
4327
4514
  let outcome = 'needs_revision';
4328
4515
 
4329
4516
  // A worker can stop after persisting a blocker but before writing a handoff.
@@ -4372,6 +4559,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4372
4559
  outcome = 'blocked';
4373
4560
  reasons.push(`${blockedCount} acceptance review(s) are blocked.`);
4374
4561
  nextActions.push('Resolve blockers or request the required human/external input.');
4562
+ } else if (allReviews.some(review => review.invalidCheckpoint === true) || context.invalidCheckpointBaseline === true) {
4563
+ outcome = 'needs_revision';
4564
+ reasons.push('Invalid checkpoint evidence or unknown pre-dispatch baseline prevents automatic acceptance.');
4565
+ nextActions.push('Repair invalid records and explicitly revise from a validated baseline; unknown history is not new accepted progress.');
4375
4566
  } else if (reviseCount > 0) {
4376
4567
  outcome = 'needs_revision';
4377
4568
  reasons.push(`${reviseCount} acceptance review(s) require development revision.`);
@@ -4380,6 +4571,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4380
4571
  outcome = 'needs_revision';
4381
4572
  reasons.push(`Accepted checkpoints (${acceptedCount}) do not cover required checkpoints (${Math.max(requiredCheckpoints, 1)}).`);
4382
4573
  nextActions.push('Complete and review the remaining planned checkpoints.');
4574
+ } else if (noProgressContinuation) {
4575
+ outcome = 'needs_revision';
4576
+ reasons.push('Project dispatch produced no new committed and accepted milestone.');
4577
+ nextActions.push('Select and commit a concrete next batch before automatic continuation.');
4383
4578
  } else if ((contract.task_scope === 'project' || projectCompletionInProgress || explicitContinuationReviews.length > 0 || deferredGateCount > 0) && !projectCompletionAccepted) {
4384
4579
  outcome = 'project_in_progress';
4385
4580
  reasons.push('The latest milestone is accepted, but the project terminal contract is not accepted.');
@@ -4405,6 +4600,12 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
4405
4600
  risk_level: contract.risk_level,
4406
4601
  requires_human_gate: contract.requires_human_gate,
4407
4602
  dispatch_status: dispatchStatus,
4603
+ invalid_checkpoint_baseline: context.invalidCheckpointBaseline === true,
4604
+ no_progress_continuation: noProgressContinuation && outcome === 'needs_revision',
4605
+ no_progress_accepted_milestone_baseline: noProgressContinuation
4606
+ ? (Array.isArray(priorAccepted) ? priorAccepted : acceptedMilestones) : null,
4607
+ no_progress_plan_baseline: noProgressContinuation && Number.isInteger(context.priorPlannedCheckpointCount)
4608
+ ? context.priorPlannedCheckpointCount : null,
4408
4609
  reasons,
4409
4610
  next_actions: nextActions,
4410
4611
  sources: {
@@ -5212,6 +5413,10 @@ function validateWorktreeConfig(worktree) {
5212
5413
  throw new Error('worktree.verifyCommands must be an array of non-empty strings.');
5213
5414
  }
5214
5415
  }
5416
+ validateIsolatedVerification(worktree.isolatedVerification);
5417
+ if (worktree.isolatedVerification && !worktree.verifyCommands?.length) {
5418
+ throw new Error('worktree.isolatedVerification requires verifyCommands.');
5419
+ }
5215
5420
  }
5216
5421
 
5217
5422
  function validateRetryConfig(retry) {
@@ -8002,7 +8207,11 @@ export async function codeTaskRun(root, queue, options = {}) {
8002
8207
  root,
8003
8208
  options.timeoutMs ?? options.config?.timeoutMs,
8004
8209
  progress,
8005
- 'final-verification'
8210
+ 'final-verification',
8211
+ options.config?.worktree?.isolatedVerification ? {
8212
+ ...options.config.worktree.isolatedVerification,
8213
+ evidenceBase: path.join(path.dirname(root), '.loop-isolation-evidence', taskId)
8214
+ } : null
8006
8215
  );
8007
8216
  finalVerification.ok = finalVerification.commands.every((entry) => entry.result.exitCode === 0);
8008
8217
  finalVerification.status = finalVerification.ok ? 'passed' : 'failed';
@@ -9849,9 +10058,10 @@ async function inspectWorktree(worktree) {
9849
10058
  };
9850
10059
  }
9851
10060
 
9852
- async function runVerifyCommands(commands, cwd, timeoutMs, progress = null, phase = 'verification') {
10061
+ async function runVerifyCommands(commands, cwd, timeoutMs, progress = null, phase = 'verification', isolation = null) {
9853
10062
  const results = [];
9854
10063
  const list = commands ?? [];
10064
+ let sharedInputDigest = null;
9855
10065
  for (let index = 0; index < list.length; index++) {
9856
10066
  const cmd = list[index];
9857
10067
  progress?.emit(phase, 'running', `Running verification ${index + 1}/${list.length}`, {
@@ -9860,12 +10070,24 @@ async function runVerifyCommands(commands, cwd, timeoutMs, progress = null, phas
9860
10070
  cmd
9861
10071
  });
9862
10072
  const startedAt = new Date().toISOString();
9863
- const result = await runCommand(cmd, { cwd, timeoutMs });
10073
+ const result = isolation ? await runIsolatedVerification({ cwd, command: cmd,
10074
+ inputs: isolation.inputs, runtimeFiles: isolation.runtimeFiles,
10075
+ evidenceDir: isolatedEvidenceDir(isolation.evidenceBase, index),
10076
+ timeoutMs, runCommand, shellQuote }) : await runCommand(cmd, { cwd, timeoutMs });
10077
+ if (isolation && result.exitCode === 0) {
10078
+ if (sharedInputDigest !== null && sharedInputDigest !== result.isolation.inputDigest) {
10079
+ result.exitCode = 1;
10080
+ result.isolation.status = 'failed_or_unknown';
10081
+ result.isolation.reason = 'verification input digest changed between commands';
10082
+ } else {
10083
+ sharedInputDigest = result.isolation.inputDigest;
10084
+ }
10085
+ }
9864
10086
  results.push({
9865
10087
  cmd,
9866
10088
  startedAt,
9867
10089
  finishedAt: new Date().toISOString(),
9868
- result: compactCommandResult(result)
10090
+ result: { ...compactCommandResult(result), ...(result.isolation ? { isolation: result.isolation } : {}) }
9869
10091
  });
9870
10092
  progress?.emit(phase, result.exitCode === 0 ? 'passed' : 'failed', `Verification ${index + 1}/${list.length} exited ${result.exitCode}`, {
9871
10093
  commandIndex: index + 1,
@@ -10023,7 +10245,12 @@ export async function runQueueOnce(root, options) {
10023
10245
  let finalJudgement = null;
10024
10246
  let revisionRequest = null;
10025
10247
  let contextUsage = null;
10248
+ let priorAcceptedMilestoneIds = null;
10249
+ let invalidCheckpointBaseline = false;
10250
+ let priorCheckpointCount = null;
10251
+ let priorPlannedCheckpointCount = null;
10026
10252
  let contextHandoff = null;
10253
+ let handoffProgressFingerprint = null;
10027
10254
  const contextPrefix = path.join(taskRuntimeDirFor(root, queue, task.id), runId);
10028
10255
 
10029
10256
  try {
@@ -10049,6 +10276,12 @@ export async function runQueueOnce(root, options) {
10049
10276
  manualChecks: acceptancePlan.plan.manual_review.length
10050
10277
  });
10051
10278
  devPlan = await writeDevPlan(root, queue, task, taskContract, acceptancePlan);
10279
+ const priorReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, { persist: false });
10280
+ invalidCheckpointBaseline = priorReviews.reviews.some(review => review.invalidCheckpoint === true);
10281
+ priorAcceptedMilestoneIds = invalidCheckpointBaseline ? null
10282
+ : acceptedMilestoneIds(devPlan.plan, priorReviews, taskContract.contract);
10283
+ priorCheckpointCount = (await checkpointSummary(root, devPlan)).count;
10284
+ priorPlannedCheckpointCount = devPlan.plan.checkpoints?.length ?? null;
10052
10285
  progress.emit('planning', 'dev_plan', 'Wrote development plan', {
10053
10286
  taskId: task.id,
10054
10287
  artifact: devPlan.file,
@@ -10156,6 +10389,10 @@ export async function runQueueOnce(root, options) {
10156
10389
  contextHandoff = handoff;
10157
10390
  if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
10158
10391
  else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
10392
+ handoffProgressFingerprint = proof.progressFingerprint;
10393
+ if (!handoffProgressFingerprint || (task.contextHandoffProgress ?? []).includes(handoffProgressFingerprint)) {
10394
+ finalStatus = 'runtime_blocked';
10395
+ }
10159
10396
  dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
10160
10397
  dispatchAttempts[dispatchAttempts.length - 1].failureClassification = dispatchClassification;
10161
10398
  }
@@ -10170,9 +10407,13 @@ export async function runQueueOnce(root, options) {
10170
10407
  } else if (dispatchClassification?.recoverableRuntime) {
10171
10408
  const recoveryCount = Number(task.runtimeRecoveryCount ?? 0);
10172
10409
  const recoveryMax = Number(options.retry?.runtimeRecoveryMaxAttempts ?? 2);
10173
- finalStatus = recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
10410
+ finalStatus = dispatchClassification.category === 'context_handoff' || recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
10174
10411
  } else if (dispatch?.exitCode === 0 && worktreeEnabled(options)) {
10175
- verification = await runVerifyCommands(options.worktree?.verifyCommands ?? [], worktree.path, timeoutMs, progress);
10412
+ verification = await runVerifyCommands(options.worktree?.verifyCommands ?? [], worktree.path, timeoutMs, progress,
10413
+ 'verification', options.worktree?.isolatedVerification ? {
10414
+ ...options.worktree.isolatedVerification,
10415
+ evidenceBase: path.join(taskRuntimeDirFor(root, queue, task.id), 'verification-evidence')
10416
+ } : null);
10176
10417
  const verifyOk = verification.every((entry) => entry.result.exitCode === 0);
10177
10418
  finalStatus = verifyOk ? 'completed' : 'verify_failed';
10178
10419
  } else {
@@ -10193,6 +10434,10 @@ export async function runQueueOnce(root, options) {
10193
10434
  });
10194
10435
  }
10195
10436
  }
10437
+ // Judge durable post-dispatch plans, not cached launch-time objects.
10438
+ taskContract = { ...taskContract, contract: await readJson(path.join(root, taskContract.file)) };
10439
+ acceptancePlan = { ...acceptancePlan, plan: await readJson(path.join(root, acceptancePlan.file)) };
10440
+ devPlan = { ...devPlan, plan: await readJson(path.join(root, devPlan.file)) };
10196
10441
  checkpoints = await checkpointSummary(root, devPlan);
10197
10442
  await reconcileHumanInputGates(root, queue, task.id);
10198
10443
  progress.emit('acceptance', 'checkpoint_summary', `Collected ${checkpoints.count} checkpoint(s)`, {
@@ -10229,6 +10474,10 @@ export async function runQueueOnce(root, options) {
10229
10474
  });
10230
10475
  if (!finalJudgement) finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
10231
10476
  dispatchStatus: finalStatus,
10477
+ priorAcceptedMilestoneIds,
10478
+ invalidCheckpointBaseline,
10479
+ priorCheckpointCount,
10480
+ priorPlannedCheckpointCount,
10232
10481
  dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
10233
10482
  verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
10234
10483
  });
@@ -10266,6 +10515,10 @@ export async function runQueueOnce(root, options) {
10266
10515
  if (!finalJudgement) {
10267
10516
  finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
10268
10517
  dispatchStatus: finalStatus,
10518
+ priorAcceptedMilestoneIds,
10519
+ invalidCheckpointBaseline,
10520
+ priorCheckpointCount,
10521
+ priorPlannedCheckpointCount,
10269
10522
  dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
10270
10523
  verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
10271
10524
  });
@@ -10312,7 +10565,12 @@ export async function runQueueOnce(root, options) {
10312
10565
  }
10313
10566
  }
10314
10567
  if (finalStatus === 'runtime_interrupted') {
10315
- completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + 1;
10568
+ const normalHandoff = dispatchAttempts.at(-1)?.failureClassification?.category === 'context_handoff';
10569
+ completedTask.runtimeRecoveryCount = Number(task.runtimeRecoveryCount ?? 0) + (normalHandoff ? 0 : 1);
10570
+ if (normalHandoff) {
10571
+ completedTask.contextHandoffCount = Number(task.contextHandoffCount ?? 0) + 1;
10572
+ completedTask.contextHandoffProgress = [...(task.contextHandoffProgress ?? []), handoffProgressFingerprint];
10573
+ }
10316
10574
  completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
10317
10575
  completedTask.sessionTickCount = 0;
10318
10576
  if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
@@ -0,0 +1,47 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const runner = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../scripts/isolated-verify.py');
7
+
8
+ export function validateIsolatedVerification(config) {
9
+ if (config === undefined) return;
10
+ if (!config || typeof config !== 'object' || Array.isArray(config) ||
11
+ !Array.isArray(config.inputs) || !config.inputs.length ||
12
+ config.inputs.some((name) => typeof name !== 'string' || !name || path.isAbsolute(name) || name.split(/[\\/]/).includes('..'))) {
13
+ throw new Error('worktree.isolatedVerification.inputs must be nonempty safe relative paths.');
14
+ }
15
+ if (config.runtimeFiles !== undefined && (!Array.isArray(config.runtimeFiles) ||
16
+ config.runtimeFiles.some((name) => typeof name !== 'string' || !/^\/(home|opt)\//.test(name) ||
17
+ name.split('/').includes('..') || path.normalize(name) !== name))) {
18
+ throw new Error('worktree.isolatedVerification.runtimeFiles must be absolute /home or /opt files.');
19
+ }
20
+ }
21
+
22
+ export async function runIsolatedVerification({ cwd, command, inputs, runtimeFiles = [], evidenceDir, timeoutMs, runCommand, shellQuote }) {
23
+ const runnerHash = createHash('sha256').update(await readFile(runner)).digest('hex');
24
+ const commandLine = ['python3', runner, '--root', cwd, '--inputs-json', JSON.stringify(inputs),
25
+ '--runtime-files-json', JSON.stringify(runtimeFiles), '--command', command, '--evidence', evidenceDir,
26
+ '--timeout', String(Math.max(1, Math.ceil((timeoutMs ?? 300000) / 1000)))].map(shellQuote).join(' ');
27
+ const result = await runCommand(commandLine, { cwd, timeoutMs: (timeoutMs ?? 300000) + 10000 });
28
+ let terminal = null;
29
+ try { terminal = JSON.parse(await readFile(path.join(evidenceDir, 'terminal.json'), 'utf8')); } catch { /* no receipt is failure */ }
30
+ const afterHash = createHash('sha256').update(await readFile(runner)).digest('hex');
31
+ const accepted = result.exitCode === 0 && !result.timedOut && runnerHash === afterHash &&
32
+ terminal?.version === 1 && terminal.status === 'passed' && terminal.command === command &&
33
+ /^[0-9a-f]{64}$/.test(terminal.input_digest ?? '') && terminal.exit_code === 0 &&
34
+ terminal.read_trace_verified === true && terminal.snapshot_unchanged === true &&
35
+ terminal.source_unchanged === true && terminal.process_group_gone === true &&
36
+ terminal.host_tools_unchanged === true && terminal.runtime_files_unchanged === true;
37
+ return {
38
+ ...result,
39
+ exitCode: accepted ? 0 : 1,
40
+ isolation: { status: accepted ? 'passed' : 'failed_or_unknown', evidenceDir,
41
+ inputDigest: terminal?.input_digest ?? null, runnerSha256: runnerHash }
42
+ };
43
+ }
44
+
45
+ export function isolatedEvidenceDir(base, index) {
46
+ return path.join(base, `isolation-${index + 1}-${randomUUID()}`);
47
+ }