taskforce-loop-engineering 0.16.3 → 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/CHANGELOG.md +8 -0
- package/lib/context-budget.mjs +9 -1
- package/lib/core.mjs +231 -33
- package/package.json +2 -2
- package/scripts/async-acceptance-refresh-self-test.mjs +3 -0
- package/scripts/context-budget-self-test.mjs +25 -7
- package/scripts/final-judgement-self-test.mjs +243 -1
- package/scripts/revision-coverage-self-test.mjs +105 -0
- package/skills/taskforce-loop-engineering/SKILL.md +17 -0
- package/skills/taskforce-loop-engineering/references/context-budget.md +1 -1
- package/skills/taskforce-loop-engineering/references/scope-task-acceptance.md +11 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.16.4 - 2026-10-29
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- Allow bounded repair of malformed checkpoint history without treating unknown baselines as empty acceptance. Preserve human gates and require an explicit validated revision before continuation.
|
|
9
|
+
- Separate successful evidence-bearing context handoffs from capped exception recovery; repeated or empty verification still stops and human blockers remain authoritative.
|
|
10
|
+
- Close unordered status-only phases with explicit same-scope, hash-bound revision coverage. Preserve history, real defects, corrupt evidence and cross-milestone boundaries; reject invalid coverage laundering.
|
|
11
|
+
- Add Node 22/24 regression coverage and synchronize the distributed skill. Publication does not upgrade installed CLIs or integrations.
|
|
12
|
+
|
|
5
13
|
## 0.16.3 - 2026-10-27
|
|
6
14
|
|
|
7
15
|
- Preserve task-scoped human-input gates during reconciliation; keep task acceptance distinct from project completion and unresolved authority blockers.
|
package/lib/context-budget.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { StringDecoder } from 'node:string_decoder';
|
|
2
2
|
import { DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS, DEFAULT_RECOVERABLE_RUNTIME_PATTERNS } from './dispatch-classification.mjs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
4
5
|
import { createWriteStream } from 'node:fs';
|
|
5
6
|
import { finished } from 'node:stream/promises';
|
|
6
7
|
import { open, realpath, writeFile } from 'node:fs/promises';
|
|
@@ -142,6 +143,13 @@ export async function handoffCheckpoint(value, { root, checkpointsDir, taskId, r
|
|
|
142
143
|
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return { valid: false };
|
|
143
144
|
const cp = await readBoundedJson(file);
|
|
144
145
|
if (!cp || cp.task_id !== taskId || cp.loop_run_id !== runId || !Array.isArray(cp.blockers)) return { valid: false };
|
|
145
|
-
|
|
146
|
+
// Exclude transport IDs, prose and timestamps: rotating sessions or merely
|
|
147
|
+
// renaming a checkpoint cannot constitute progress. Require recorded checks.
|
|
148
|
+
const checks = Array.isArray(cp.verification) ? cp.verification.filter(x =>
|
|
149
|
+
(typeof x === 'string' && x.trim()) || (x && typeof x === 'object' && Object.keys(x).length)) : [];
|
|
150
|
+
const canonical = x => Array.isArray(x) ? x.map(canonical) : x && typeof x === 'object'
|
|
151
|
+
? Object.fromEntries(Object.keys(x).sort().map(k => [k, canonical(x[k])])) : x;
|
|
152
|
+
const progressFingerprint = checks.length ? createHash('sha256').update(JSON.stringify(canonical(checks))).digest('hex') : null;
|
|
153
|
+
return { valid: true, progressFingerprint, blocked: cp.blockers.length > 0 || ['blocked', 'needs_human_input'].includes(cp.status) };
|
|
146
154
|
} catch { return { valid: false }; }
|
|
147
155
|
}
|
package/lib/core.mjs
CHANGED
|
@@ -2521,18 +2521,22 @@ export async function refreshTaskAcceptance(root, options = {}) {
|
|
|
2521
2521
|
const checkpointFiles = await listJson(checkpointsDir);
|
|
2522
2522
|
if (checkpointFiles.length === 0) return { queue, taskId: task.id, outcome: 'no_checkpoints' };
|
|
2523
2523
|
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
2524
|
const contractFile = path.join(dir, 'task_contract.json');
|
|
2530
2525
|
const acceptanceFile = path.join(dir, 'acceptance_plan.json');
|
|
2531
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
|
+
}
|
|
2532
2536
|
const taskContract = { contract: await readJson(contractFile), file: path.relative(root, contractFile) };
|
|
2533
2537
|
const acceptancePlan = { plan: await readJson(acceptanceFile), file: path.relative(root, acceptanceFile) };
|
|
2534
2538
|
const devPlan = {
|
|
2535
|
-
plan:
|
|
2539
|
+
plan: currentDevPlan,
|
|
2536
2540
|
file: path.relative(root, devFile),
|
|
2537
2541
|
checkpointsDir: path.relative(root, checkpointsDir),
|
|
2538
2542
|
reviewsDir: path.relative(root, path.join(dir, 'reviews'))
|
|
@@ -2540,7 +2544,14 @@ export async function refreshTaskAcceptance(root, options = {}) {
|
|
|
2540
2544
|
const checkpoints = await checkpointSummary(root, devPlan);
|
|
2541
2545
|
const acceptanceReviews = await writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan);
|
|
2542
2546
|
const finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
|
|
2543
|
-
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
|
|
2544
2555
|
});
|
|
2545
2556
|
const status = queueStatusFromFinalJudgement('completed', finalJudgement);
|
|
2546
2557
|
const destinationName = status === 'completed' ? 'done' : status === 'project_in_progress' ? 'inbox' : 'failed';
|
|
@@ -3296,7 +3307,17 @@ async function reconcileHumanInputGates(root, queue, taskId) {
|
|
|
3296
3307
|
const gatesDir = path.join(queueDirFor(root, queue), 'human-input', 'gates');
|
|
3297
3308
|
const checkpointsDir = path.join(taskRuntimeDirFor(root, queue, taskId), 'checkpoints');
|
|
3298
3309
|
const checkpoints = [];
|
|
3299
|
-
for (const file of await listJson(checkpointsDir))
|
|
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
|
+
}
|
|
3300
3321
|
for (const file of await listJson(gatesDir)) {
|
|
3301
3322
|
const full = path.join(gatesDir, file);
|
|
3302
3323
|
const gate = await readJson(full);
|
|
@@ -3469,6 +3490,7 @@ async function taskProjectAuthorization(root, task) {
|
|
|
3469
3490
|
}
|
|
3470
3491
|
|
|
3471
3492
|
export function inferTaskScope(task) {
|
|
3493
|
+
if (task?.taskScope === 'project' || task?.taskScope === 'scoped_task') return task.taskScope;
|
|
3472
3494
|
const requestText = `${task?.title ?? ''}\n${task?.body ?? ''}`.toLowerCase();
|
|
3473
3495
|
// A project can be referenced as context while the routed task is explicitly
|
|
3474
3496
|
// bounded to one milestone or backlog item. Those bounded instructions must
|
|
@@ -3645,6 +3667,13 @@ export async function writeTaskContract(root, queue, task, options = {}) {
|
|
|
3645
3667
|
historicalPatterns,
|
|
3646
3668
|
projectAuthorization: options.projectAuthorization ?? await taskProjectAuthorization(root, task)
|
|
3647
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
|
+
}
|
|
3648
3677
|
contract = await mergeLiveAmendments(root, queue, task.id, contract, 'supplemental_requirements');
|
|
3649
3678
|
await writeJson(file, contract);
|
|
3650
3679
|
return {
|
|
@@ -3864,6 +3893,13 @@ export async function writeAcceptancePlan(root, queue, task, taskContract, optio
|
|
|
3864
3893
|
const dir = taskRuntimeDirFor(root, queue, task.id);
|
|
3865
3894
|
const file = path.join(dir, 'acceptance_plan.json');
|
|
3866
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
|
+
}
|
|
3867
3903
|
plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_checks');
|
|
3868
3904
|
await writeJson(file, plan);
|
|
3869
3905
|
return {
|
|
@@ -3909,6 +3945,7 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1') {
|
|
|
3909
3945
|
checkpoint_id: firstCheckpointId,
|
|
3910
3946
|
milestone_id: firstCheckpointId,
|
|
3911
3947
|
revises_checkpoint_id: null,
|
|
3948
|
+
revision_coverage: null,
|
|
3912
3949
|
status: 'ready_for_acceptance | blocked | needs_human_input',
|
|
3913
3950
|
summary: 'What changed and why.',
|
|
3914
3951
|
files_changed: [],
|
|
@@ -3950,6 +3987,21 @@ export async function writeDevPlan(root, queue, task, taskContract, acceptancePl
|
|
|
3950
3987
|
while (usedCheckpointNumbers.has(checkpointNumber)) checkpointNumber += 1;
|
|
3951
3988
|
const nextCheckpointId = `cp${checkpointNumber}`;
|
|
3952
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
|
+
}
|
|
3953
4005
|
plan = await mergeLiveAmendments(root, queue, task.id, plan, 'supplemental_instructions');
|
|
3954
4006
|
await writeJson(file, plan);
|
|
3955
4007
|
return {
|
|
@@ -4232,21 +4284,47 @@ function summarizeCriticReviews(reviews) {
|
|
|
4232
4284
|
return byCritic;
|
|
4233
4285
|
}
|
|
4234
4286
|
|
|
4235
|
-
export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan) {
|
|
4287
|
+
export async function writeAcceptanceReviews(root, queue, task, taskContract, acceptancePlan, devPlan, options = {}) {
|
|
4236
4288
|
if (!devPlan?.reviewsDir || !devPlan?.checkpointsDir) return null;
|
|
4237
4289
|
const checkpointFiles = await listJson(path.join(root, devPlan.checkpointsDir));
|
|
4238
4290
|
const reviews = [];
|
|
4239
4291
|
const reviewArtifacts = [];
|
|
4240
4292
|
for (const file of checkpointFiles) {
|
|
4241
4293
|
const checkpointFile = path.join(root, devPlan.checkpointsDir, file);
|
|
4242
|
-
|
|
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
|
+
}
|
|
4243
4312
|
const review = buildCheckpointReview(taskContract.contract, acceptancePlan.plan, checkpoint);
|
|
4244
4313
|
const reviewFile = path.join(root, devPlan.reviewsDir, `${checkpoint.checkpoint_id ?? path.basename(file, '.json')}.json`);
|
|
4245
|
-
await writeJson(reviewFile, review);
|
|
4314
|
+
if (options.persist !== false) await writeJson(reviewFile, review);
|
|
4246
4315
|
reviews.push({
|
|
4247
4316
|
checkpointId: review.checkpoint_id,
|
|
4248
4317
|
milestoneId: checkpoint.milestone_id ?? null,
|
|
4249
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 ?? [],
|
|
4250
4328
|
sequence: checkpoint.sequence ?? null,
|
|
4251
4329
|
checkpointCreatedAt: checkpoint.created_at ?? null,
|
|
4252
4330
|
createdAt: checkpoint.created_at ?? review.created_at,
|
|
@@ -4304,35 +4382,98 @@ function terminalTaskReview(review, contract = {}) {
|
|
|
4304
4382
|
|| review.taskTerminal === true;
|
|
4305
4383
|
}
|
|
4306
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
|
+
|
|
4307
4437
|
export function selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract = {}) {
|
|
4308
|
-
const allReviews = acceptanceReviews?.reviews ?? [];
|
|
4309
4438
|
const planned = Array.isArray(devPlan?.checkpoints) ? devPlan.checkpoints : [];
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
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
|
|
4315
4454
|
|| compareReviewRecency(review, other) > 0
|
|
4316
4455
|
|| (compareReviewRecency(review, other) < 0
|
|
4317
4456
|
&& 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
4457
|
&& other.status === 'accepted'
|
|
4321
4458
|
&& (other.deferredGates?.length ?? 0) === 0)));
|
|
4322
|
-
|
|
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));
|
|
4459
|
+
selected.push(...(terminal ? [terminal] : effectiveReviewFrontier(reviews)));
|
|
4332
4460
|
}
|
|
4333
4461
|
return selected;
|
|
4334
4462
|
}
|
|
4335
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
|
+
|
|
4336
4477
|
export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, context = {}) {
|
|
4337
4478
|
const reasons = [];
|
|
4338
4479
|
const nextActions = [];
|
|
@@ -4344,9 +4485,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
|
|
|
4344
4485
|
// resolved historical blocker does not permanently poison the task.
|
|
4345
4486
|
const effectiveReviews = selectEffectiveAcceptanceReviews(devPlan, acceptanceReviews, contract);
|
|
4346
4487
|
const reviewCount = effectiveReviews.length;
|
|
4347
|
-
const acceptedCount = requiredCheckpoints >
|
|
4488
|
+
const acceptedCount = requiredCheckpoints > 0
|
|
4348
4489
|
? devPlan.checkpoints.filter(checkpoint => effectiveReviews.some(review => review.status === 'accepted'
|
|
4349
|
-
&& (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id
|
|
4490
|
+
&& (review.milestoneId === checkpoint.id || review.checkpointId === checkpoint.id
|
|
4491
|
+
|| (requiredCheckpoints === 1 && review.milestoneId == null)))).length
|
|
4350
4492
|
: effectiveReviews.filter((item) => item.status === 'accepted').length;
|
|
4351
4493
|
const reviseCount = effectiveReviews.filter((item) => item.status === 'revise').length;
|
|
4352
4494
|
const blockedCount = effectiveReviews.filter((item) => item.status === 'blocked').length;
|
|
@@ -4359,6 +4501,16 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
|
|
|
4359
4501
|
);
|
|
4360
4502
|
const effectiveResidualRisks = [...new Set(effectiveReviews.flatMap((review) => review.checkpointRisks ?? []))];
|
|
4361
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);
|
|
4362
4514
|
let outcome = 'needs_revision';
|
|
4363
4515
|
|
|
4364
4516
|
// A worker can stop after persisting a blocker but before writing a handoff.
|
|
@@ -4407,6 +4559,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
|
|
|
4407
4559
|
outcome = 'blocked';
|
|
4408
4560
|
reasons.push(`${blockedCount} acceptance review(s) are blocked.`);
|
|
4409
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.');
|
|
4410
4566
|
} else if (reviseCount > 0) {
|
|
4411
4567
|
outcome = 'needs_revision';
|
|
4412
4568
|
reasons.push(`${reviseCount} acceptance review(s) require development revision.`);
|
|
@@ -4415,6 +4571,10 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
|
|
|
4415
4571
|
outcome = 'needs_revision';
|
|
4416
4572
|
reasons.push(`Accepted checkpoints (${acceptedCount}) do not cover required checkpoints (${Math.max(requiredCheckpoints, 1)}).`);
|
|
4417
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.');
|
|
4418
4578
|
} else if ((contract.task_scope === 'project' || projectCompletionInProgress || explicitContinuationReviews.length > 0 || deferredGateCount > 0) && !projectCompletionAccepted) {
|
|
4419
4579
|
outcome = 'project_in_progress';
|
|
4420
4580
|
reasons.push('The latest milestone is accepted, but the project terminal contract is not accepted.');
|
|
@@ -4440,6 +4600,12 @@ export function buildFinalJudgement(contract, acceptancePlan, devPlan, checkpoin
|
|
|
4440
4600
|
risk_level: contract.risk_level,
|
|
4441
4601
|
requires_human_gate: contract.requires_human_gate,
|
|
4442
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,
|
|
4443
4609
|
reasons,
|
|
4444
4610
|
next_actions: nextActions,
|
|
4445
4611
|
sources: {
|
|
@@ -10079,7 +10245,12 @@ export async function runQueueOnce(root, options) {
|
|
|
10079
10245
|
let finalJudgement = null;
|
|
10080
10246
|
let revisionRequest = null;
|
|
10081
10247
|
let contextUsage = null;
|
|
10248
|
+
let priorAcceptedMilestoneIds = null;
|
|
10249
|
+
let invalidCheckpointBaseline = false;
|
|
10250
|
+
let priorCheckpointCount = null;
|
|
10251
|
+
let priorPlannedCheckpointCount = null;
|
|
10082
10252
|
let contextHandoff = null;
|
|
10253
|
+
let handoffProgressFingerprint = null;
|
|
10083
10254
|
const contextPrefix = path.join(taskRuntimeDirFor(root, queue, task.id), runId);
|
|
10084
10255
|
|
|
10085
10256
|
try {
|
|
@@ -10105,6 +10276,12 @@ export async function runQueueOnce(root, options) {
|
|
|
10105
10276
|
manualChecks: acceptancePlan.plan.manual_review.length
|
|
10106
10277
|
});
|
|
10107
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;
|
|
10108
10285
|
progress.emit('planning', 'dev_plan', 'Wrote development plan', {
|
|
10109
10286
|
taskId: task.id,
|
|
10110
10287
|
artifact: devPlan.file,
|
|
@@ -10212,6 +10389,10 @@ export async function runQueueOnce(root, options) {
|
|
|
10212
10389
|
contextHandoff = handoff;
|
|
10213
10390
|
if (proof.blocked || handoff.blockers.length || handoff.pendingActions.length) finalStatus = 'needs_human_input';
|
|
10214
10391
|
else if (dispatch?.exitCode === 0 && !dispatchClassification?.requiresHumanAction) {
|
|
10392
|
+
handoffProgressFingerprint = proof.progressFingerprint;
|
|
10393
|
+
if (!handoffProgressFingerprint || (task.contextHandoffProgress ?? []).includes(handoffProgressFingerprint)) {
|
|
10394
|
+
finalStatus = 'runtime_blocked';
|
|
10395
|
+
}
|
|
10215
10396
|
dispatchClassification = { category: 'context_handoff', recoverableRuntime: true, requiresHumanAction: false };
|
|
10216
10397
|
dispatchAttempts[dispatchAttempts.length - 1].failureClassification = dispatchClassification;
|
|
10217
10398
|
}
|
|
@@ -10226,7 +10407,7 @@ export async function runQueueOnce(root, options) {
|
|
|
10226
10407
|
} else if (dispatchClassification?.recoverableRuntime) {
|
|
10227
10408
|
const recoveryCount = Number(task.runtimeRecoveryCount ?? 0);
|
|
10228
10409
|
const recoveryMax = Number(options.retry?.runtimeRecoveryMaxAttempts ?? 2);
|
|
10229
|
-
finalStatus = recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
|
|
10410
|
+
finalStatus = dispatchClassification.category === 'context_handoff' || recoveryCount < recoveryMax ? 'runtime_interrupted' : 'runtime_blocked';
|
|
10230
10411
|
} else if (dispatch?.exitCode === 0 && worktreeEnabled(options)) {
|
|
10231
10412
|
verification = await runVerifyCommands(options.worktree?.verifyCommands ?? [], worktree.path, timeoutMs, progress,
|
|
10232
10413
|
'verification', options.worktree?.isolatedVerification ? {
|
|
@@ -10253,6 +10434,10 @@ export async function runQueueOnce(root, options) {
|
|
|
10253
10434
|
});
|
|
10254
10435
|
}
|
|
10255
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)) };
|
|
10256
10441
|
checkpoints = await checkpointSummary(root, devPlan);
|
|
10257
10442
|
await reconcileHumanInputGates(root, queue, task.id);
|
|
10258
10443
|
progress.emit('acceptance', 'checkpoint_summary', `Collected ${checkpoints.count} checkpoint(s)`, {
|
|
@@ -10289,6 +10474,10 @@ export async function runQueueOnce(root, options) {
|
|
|
10289
10474
|
});
|
|
10290
10475
|
if (!finalJudgement) finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
|
|
10291
10476
|
dispatchStatus: finalStatus,
|
|
10477
|
+
priorAcceptedMilestoneIds,
|
|
10478
|
+
invalidCheckpointBaseline,
|
|
10479
|
+
priorCheckpointCount,
|
|
10480
|
+
priorPlannedCheckpointCount,
|
|
10292
10481
|
dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
|
|
10293
10482
|
verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
|
|
10294
10483
|
});
|
|
@@ -10326,6 +10515,10 @@ export async function runQueueOnce(root, options) {
|
|
|
10326
10515
|
if (!finalJudgement) {
|
|
10327
10516
|
finalJudgement = await writeFinalJudgement(root, queue, task, taskContract, acceptancePlan, devPlan, checkpoints, acceptanceReviews, {
|
|
10328
10517
|
dispatchStatus: finalStatus,
|
|
10518
|
+
priorAcceptedMilestoneIds,
|
|
10519
|
+
invalidCheckpointBaseline,
|
|
10520
|
+
priorCheckpointCount,
|
|
10521
|
+
priorPlannedCheckpointCount,
|
|
10329
10522
|
dispatchFailureClassification: dispatchAttempts[dispatchAttempts.length - 1]?.failureClassification ?? null,
|
|
10330
10523
|
verificationFailed: verification.some((entry) => entry.result.exitCode !== 0)
|
|
10331
10524
|
});
|
|
@@ -10372,7 +10565,12 @@ export async function runQueueOnce(root, options) {
|
|
|
10372
10565
|
}
|
|
10373
10566
|
}
|
|
10374
10567
|
if (finalStatus === 'runtime_interrupted') {
|
|
10375
|
-
|
|
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
|
+
}
|
|
10376
10574
|
completedTask.runtimeSessionGeneration = Number(task.runtimeSessionGeneration ?? 0) + 1;
|
|
10377
10575
|
completedTask.sessionTickCount = 0;
|
|
10378
10576
|
if (contextHandoff) completedTask.contextHandoffFile = path.relative(root, contextPrefix + '.handoff.json');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "taskforce-loop-engineering",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.4",
|
|
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/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 && 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": {
|
|
@@ -27,6 +27,9 @@ try {
|
|
|
27
27
|
status: 'blocked', summary: 'Soak still running.', files_changed: ['soak.json'], verification: ['pending'], blockers: ['pending'], risks: [], project_completion: { status: 'in_progress' }
|
|
28
28
|
});
|
|
29
29
|
await writeJson(path.join(runtimeDir, 'final_judgement.json'), { version: 1, task_id: taskId, outcome: 'blocked' });
|
|
30
|
+
// Legacy judgements without coverage must be rebuilt once, then stay current.
|
|
31
|
+
assert.equal((await refreshTaskAcceptance(root, { queue, taskId })).outcome, 'refreshed');
|
|
32
|
+
assert.equal((await readJson(path.join(runtimeDir, 'final_judgement.json'))).coverage.planned_checkpoints, 1);
|
|
30
33
|
assert.equal((await refreshTaskAcceptance(root, { queue, taskId })).outcome, 'already_current');
|
|
31
34
|
|
|
32
35
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
@@ -24,7 +24,7 @@ assert.equal(dispatchFailureClassification({ exitCode: 1, stderr: 'Permission de
|
|
|
24
24
|
|
|
25
25
|
const roots = [];
|
|
26
26
|
try {
|
|
27
|
-
for (const scenario of ['yield', 'stale', 'malformed', 'missing-checkpoint', 'checkpoint-gate', 'pending-action', 'overflow', 'human-error', 'oversized', 'project-soft', 'project-hard', 'project-no-usage', 'terminal', 'pending-action-overflow', 'checkpoint-gate-overflow', 'stale-overflow', 'malformed-overflow', 'yield-overflow', 'yield-human-error', 'pending-action-failure']) {
|
|
27
|
+
for (const scenario of ['yield', 'repeat-yield', 'empty-yield', 'stale', 'malformed', 'missing-checkpoint', 'checkpoint-gate', 'pending-action', 'overflow', 'human-error', 'oversized', 'project-soft', 'project-hard', 'project-no-usage', 'terminal', 'pending-action-overflow', 'checkpoint-gate-overflow', 'stale-overflow', 'malformed-overflow', 'yield-overflow', 'yield-human-error', 'pending-action-failure']) {
|
|
28
28
|
const root = await mkdtemp(path.join(tmpdir(), 'loop-context-'));
|
|
29
29
|
roots.push(root);
|
|
30
30
|
const worker = path.join(root, 'worker.mjs');
|
|
@@ -46,7 +46,7 @@ if (scenario.startsWith('project-') || scenario === 'terminal') {
|
|
|
46
46
|
process.exit(0);
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
if (scenario !== 'missing-checkpoint') 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: scenario === 'checkpoint-gate' ? 'needs_human_input' : 'in_progress', summary: 'bounded progress', blockers: scenario === 'checkpoint-gate' ? ['Need approval'] : [], verification: [], risks: [], next_action: 'continue' }));
|
|
49
|
+
if (scenario !== 'missing-checkpoint') 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: scenario === 'checkpoint-gate' ? 'needs_human_input' : 'in_progress', summary: 'bounded progress', blockers: scenario === 'checkpoint-gate' ? ['Need approval'] : [], verification: scenario === 'empty-yield' ? [] : ['verified unit ' + (scenario === 'repeat-yield' ? 'same' : e.LOOP_SESSION_GENERATION)], risks: [], next_action: 'continue' }));
|
|
50
50
|
const handoff = { version: 1, taskId: e.LOOP_TASK_ID, runId: scenario === 'stale' ? 'old-run' : e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), reason: 'context_budget', checkpoint, summary: 'progress', completed: ['read source'], remaining: ['verify changes'], evidence: [checkpoint], nextAction: 'inspect test', authority: 'local only', pendingActions: scenario === 'pending-action' ? ['unknown payment outcome'] : [], blockers: [] };
|
|
51
51
|
await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, scenario === 'malformed' ? '{' : scenario === 'oversized' ? ' '.repeat(17000) : JSON.stringify(handoff));
|
|
52
52
|
if (original !== scenario) { console.error(original.endsWith('-human-error') ? 'Permission denied; context_length_exceeded' : original.endsWith('-failure') ? 'generic failure' : 'context_length_exceeded'); process.exitCode = 1; }
|
|
@@ -72,16 +72,34 @@ if (original !== scenario) { console.error(original.endsWith('-human-error') ? '
|
|
|
72
72
|
} else if (scenario === 'terminal') {
|
|
73
73
|
assert.equal(first.status, 'completed');
|
|
74
74
|
assert.equal((await runQueueOnce(root, options)).processed, false, 'high token usage cannot replay completed work');
|
|
75
|
-
} else if (['yield', 'overflow', 'yield-overflow'].includes(scenario)) {
|
|
75
|
+
} else if (['yield', 'repeat-yield', 'overflow', 'yield-overflow'].includes(scenario)) {
|
|
76
76
|
assert.equal(first.status, 'runtime_interrupted', scenario);
|
|
77
77
|
const task = JSON.parse(await readFile(path.join(root, first.taskPath), 'utf8'));
|
|
78
78
|
assert.equal(task.runtimeSessionGeneration, 1);
|
|
79
79
|
assert.equal(task.sessionTickCount, 0);
|
|
80
80
|
if (scenario === 'yield') assert.ok(task.contextHandoffFile);
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
81
|
+
if (scenario === 'yield') {
|
|
82
|
+
// Normal progress can rotate beyond the exception budget, even with
|
|
83
|
+
// an already exhausted exception counter. It must not reset it either.
|
|
84
|
+
task.runtimeRecoveryCount = 2;
|
|
85
|
+
await writeFile(path.join(root, first.taskPath), JSON.stringify(task));
|
|
86
|
+
for (let tick = 0; tick < 4; tick++) {
|
|
87
|
+
const next = await runQueueOnce(root, options);
|
|
88
|
+
assert.equal(next.status, 'runtime_interrupted');
|
|
89
|
+
const saved = JSON.parse(await readFile(path.join(root, next.taskPath), 'utf8'));
|
|
90
|
+
assert.equal(saved.runtimeRecoveryCount, 2);
|
|
91
|
+
assert.equal(saved.contextHandoffCount, tick + 2);
|
|
92
|
+
assert.equal(saved.runtimeSessionGeneration, tick + 2);
|
|
93
|
+
}
|
|
94
|
+
} else if (scenario === 'repeat-yield') {
|
|
95
|
+
assert.equal((await runQueueOnce(root, options)).status, 'runtime_blocked');
|
|
96
|
+
assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
97
|
+
} else {
|
|
98
|
+
const second = await runQueueOnce(root, options);
|
|
99
|
+
assert.equal(second.status, 'runtime_interrupted');
|
|
100
|
+
const third = await runQueueOnce(root, options);
|
|
101
|
+
assert.equal(third.status, 'runtime_blocked', 'exception recovery is bounded');
|
|
102
|
+
}
|
|
85
103
|
} else if (['pending-action', 'checkpoint-gate', 'human-error', 'pending-action-overflow', 'checkpoint-gate-overflow', 'yield-human-error', 'pending-action-failure'].includes(scenario)) {
|
|
86
104
|
assert.equal(first.status, 'needs_human_input', scenario);
|
|
87
105
|
assert.equal((await runQueueOnce(root, options)).processed, false, 'blocked work cannot auto-replay');
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
|
-
import {
|
|
2
|
+
import { mkdtemp, mkdir, readFile, rm, utimes, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { enqueueTask, queueRequeue, runQueueOnce, buildFinalJudgement, dispatchFailureClassification, inferTaskScope, refreshTaskAcceptance, selectEffectiveAcceptanceReviews, writeAcceptancePlan, writeDevPlan, writeTaskContract } from '../lib/core.mjs';
|
|
3
6
|
|
|
4
7
|
const basePlan = { rubric: [], automation: [] };
|
|
5
8
|
const baseContract = { task_id: 't1', risk_level: 'L1', requires_human_gate: false, task_scope: 'scoped_task' };
|
|
6
9
|
|
|
7
10
|
assert.equal(inferTaskScope({ body: '开发完整项目并完成整体目标' }), 'project');
|
|
11
|
+
assert.equal(inferTaskScope({ body: '承接项目并先开始首个批次', taskScope: 'project' }), 'project');
|
|
12
|
+
assert.equal(inferTaskScope({ body: '开发完整项目并完成整体目标', taskScope: 'scoped_task' }), 'scoped_task');
|
|
13
|
+
assert.equal(inferTaskScope({ body: '开发完整项目并完成整体目标', taskScope: 'invalid' }), 'project');
|
|
8
14
|
assert.equal(inferTaskScope({ body: '继续同一整体项目,仅推进 T-01 第 2 项;阶段完成后不能称整体项目完成' }), 'scoped_task');
|
|
9
15
|
assert.equal(inferTaskScope({ body: 'Continue the project, only complete boundary item 2' }), 'scoped_task');
|
|
10
16
|
assert.equal(inferTaskScope({ body: '继续同一整体项目,取消团队功能并从项目完成门槛中移除,其他 backlog 不变' }), 'scoped_task');
|
|
@@ -12,6 +18,113 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
|
|
|
12
18
|
assert.equal(inferTaskScope({ body: '把外部证据列为项目级 deferred gates。本轮作为有界本地工程里程碑,完成 TECH-01030;不宣称整体项目完成。' }), 'scoped_task');
|
|
13
19
|
assert.equal(inferTaskScope({ body: 'Project-level evidence remains deferred; this round is a bounded local engineering milestone.' }), 'scoped_task');
|
|
14
20
|
|
|
21
|
+
for (const explicitScope of [true, false]) {
|
|
22
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-project-plan-'));
|
|
23
|
+
try {
|
|
24
|
+
const task = {
|
|
25
|
+
id: 'project-scope-probe', title: 'First batch',
|
|
26
|
+
body: '开发完整项目并完成整体目标', queue: 'agent-tasks',
|
|
27
|
+
...(explicitScope ? { taskScope: 'project' } : {}), projectId: 'probe', riskAssessment: 'model_assessed'
|
|
28
|
+
};
|
|
29
|
+
const dir = path.join(root, 'runtime/loops/agent-tasks/tasks', task.id);
|
|
30
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
31
|
+
await writeFile(path.join(dir, 'checkpoints/cp1.json'), '{}\n');
|
|
32
|
+
await writeFile(path.join(dir, 'task_contract.json'), JSON.stringify({
|
|
33
|
+
task_id: task.id, task_scope: 'project',
|
|
34
|
+
deliverables: ['preserved-project-deliverable'],
|
|
35
|
+
acceptance_summary: 'preserved-project-acceptance'
|
|
36
|
+
}));
|
|
37
|
+
await writeFile(path.join(dir, 'acceptance_plan.json'), JSON.stringify({
|
|
38
|
+
task_id: task.id,
|
|
39
|
+
generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1',
|
|
40
|
+
functional_checks: ['preserved-project-check'],
|
|
41
|
+
regression_checks: [], negative_tests: [], manual_review: [], automation: [], rubric: []
|
|
42
|
+
}));
|
|
43
|
+
await writeFile(path.join(dir, 'dev_plan.json'), JSON.stringify({
|
|
44
|
+
task_id: task.id,
|
|
45
|
+
generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1',
|
|
46
|
+
approach: 'preserved-project-approach',
|
|
47
|
+
checkpoints: [{ id: 'cp1', goal: 'preserved milestone', output_file: 'checkpoints/cp1.json' }]
|
|
48
|
+
}));
|
|
49
|
+
const contract = await writeTaskContract(root, 'agent-tasks', task, {
|
|
50
|
+
projectAuthorization: { project: 'probe', source: 'test',
|
|
51
|
+
production_authorized: false, paid_action_authorized: false }
|
|
52
|
+
});
|
|
53
|
+
const acceptance = await writeAcceptancePlan(root, 'agent-tasks', task, contract);
|
|
54
|
+
const dev = await writeDevPlan(root, 'agent-tasks', task, contract, acceptance);
|
|
55
|
+
assert.equal(contract.contract.task_scope, 'project');
|
|
56
|
+
assert.deepEqual(contract.contract.deliverables, ['preserved-project-deliverable']);
|
|
57
|
+
assert.deepEqual(acceptance.plan.functional_checks, ['preserved-project-check']);
|
|
58
|
+
assert.deepEqual(dev.plan.checkpoints.map((entry) => entry.id), ['cp1']);
|
|
59
|
+
assert.equal(dev.plan.approach, 'preserved-project-approach');
|
|
60
|
+
assert.equal(dev.plan.checkpoint_schema.checkpoint_id, 'cp2');
|
|
61
|
+
const acceptedReviews = { reviews: [{ checkpointId: 'cp1', sequence: 1, status: 'accepted', projectCompletion: { status: 'in_progress' } }] };
|
|
62
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, dev.plan, { count: 1 }, acceptedReviews, { dispatchStatus: 'completed' }).outcome, 'project_in_progress');
|
|
63
|
+
const noProgress = buildFinalJudgement(contract.contract, acceptance.plan, dev.plan, { count: 1 }, acceptedReviews, { dispatchStatus: 'completed', priorCheckpointCount: 1 });
|
|
64
|
+
assert.equal(noProgress.outcome, 'needs_revision');
|
|
65
|
+
assert.equal(noProgress.no_progress_continuation, true);
|
|
66
|
+
assert.match(noProgress.reasons[0], /no new committed and accepted milestone/);
|
|
67
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, dev.plan, { count: 1 }, acceptedReviews, { dispatchStatus: 'completed', priorCheckpointCount: 0 }).outcome, 'project_in_progress');
|
|
68
|
+
|
|
69
|
+
const repairedPlan = { checkpoints: [{ id: 'cp1' }, { id: 'cp2' }] };
|
|
70
|
+
const repairedReviews = { reviews: [
|
|
71
|
+
{ checkpointId: 'cp1', sequence: 1, status: 'accepted' },
|
|
72
|
+
{ checkpointId: 'cp2', sequence: 2, status: 'revise' },
|
|
73
|
+
{ checkpointId: 'cp3', milestoneId: 'cp2', sequence: 3, status: 'accepted', projectCompletion: { status: 'in_progress' } }
|
|
74
|
+
] };
|
|
75
|
+
const repairContext = { dispatchStatus: 'completed', priorCheckpointCount: 2, priorPlannedCheckpointCount: 2, priorAcceptedMilestoneIds: ['cp1'] };
|
|
76
|
+
assert.equal(buildFinalJudgement(contract.contract, basePlan, repairedPlan, { count: 3 }, repairedReviews, repairContext).outcome, 'project_in_progress');
|
|
77
|
+
// Re-emitting already accepted work is not progress, even with a new file.
|
|
78
|
+
assert.equal(buildFinalJudgement(contract.contract, basePlan, repairedPlan, { count: 3 }, repairedReviews, { ...repairContext, priorAcceptedMilestoneIds: ['cp1', 'cp2'] }).outcome, 'needs_revision');
|
|
79
|
+
// In-place repair also advances acceptance without increasing file count.
|
|
80
|
+
assert.equal(buildFinalJudgement(contract.contract, basePlan, repairedPlan, { count: 2 }, repairedReviews, repairContext).outcome, 'project_in_progress');
|
|
81
|
+
const completedReviews = { reviews: [{ checkpointId: 'cp1', sequence: 1, status: 'accepted', projectCompletion: { status: 'accepted' } }] };
|
|
82
|
+
assert.notEqual(buildFinalJudgement(contract.contract, acceptance.plan, dev.plan, { count: 1 }, completedReviews, { dispatchStatus: 'completed', priorCheckpointCount: 1 }).outcome, 'needs_revision');
|
|
83
|
+
const committedMissing = { ...dev.plan, checkpoints: [...dev.plan.checkpoints, { id: 'cp2', goal: 'specific committed batch', output_file: 'checkpoints/cp2.json' }] };
|
|
84
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, committedMissing, { count: 1 }, acceptedReviews, { dispatchStatus: 'completed' }).outcome, 'needs_revision');
|
|
85
|
+
const accepted170 = Array.from({ length: 170 }, (_, index) => ({ id: `cp${index + 1}`, goal: `bounded batch ${index + 1}` }));
|
|
86
|
+
const reviews170 = { reviews: accepted170.map((entry, index) => ({ checkpointId: entry.id, sequence: index + 1, status: 'accepted', projectCompletion: { status: 'in_progress' } })) };
|
|
87
|
+
const exact170 = { ...dev.plan, checkpoints: accepted170 };
|
|
88
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, exact170, { count: 170 }, reviews170, { dispatchStatus: 'completed' }).outcome, 'project_in_progress');
|
|
89
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, exact170, { count: 170 }, reviews170, { dispatchStatus: 'completed', priorCheckpointCount: 170 }).outcome, 'needs_revision');
|
|
90
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, exact170, { count: 171 }, reviews170, { dispatchStatus: 'completed', priorCheckpointCount: 170, priorPlannedCheckpointCount: 170, priorAcceptedMilestoneIds: accepted170.map(cp => cp.id) }).outcome, 'needs_revision');
|
|
91
|
+
const progressed171 = { ...exact170, checkpoints: [...accepted170, { id: 'cp171', goal: 'selected batch' }] };
|
|
92
|
+
const accepted171 = { reviews: [...reviews170.reviews, { checkpointId: 'cp171', sequence: 171, status: 'accepted', projectCompletion: { status: 'in_progress' } }] };
|
|
93
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, progressed171, { count: 171 }, accepted171, { dispatchStatus: 'completed', priorCheckpointCount: 170 }).outcome, 'project_in_progress');
|
|
94
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, progressed171, { count: 171 }, accepted171, { dispatchStatus: 'completed', priorCheckpointCount: 170, priorPlannedCheckpointCount: 170 }).outcome, 'project_in_progress');
|
|
95
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, progressed171, { count: 171 }, accepted171, { dispatchStatus: 'completed', priorCheckpointCount: 170, priorPlannedCheckpointCount: 171 }).outcome, 'project_in_progress');
|
|
96
|
+
assert.equal(buildFinalJudgement(contract.contract, acceptance.plan, { ...exact170, checkpoints: [...accepted170, { id: 'cp171', goal: 'unexecuted placeholder' }] }, { count: 170 }, reviews170, { dispatchStatus: 'completed' }).outcome, 'needs_revision');
|
|
97
|
+
await writeFile(path.join(dir, 'checkpoints/cp1.json'), JSON.stringify({
|
|
98
|
+
task_id: task.id, checkpoint_id: 'cp1', status: 'ready_for_acceptance', summary: 'Accepted local slice',
|
|
99
|
+
files_changed: [], verification: ['focused test passed'], blockers: [], risks: [],
|
|
100
|
+
project_completion: { status: 'in_progress' }
|
|
101
|
+
}));
|
|
102
|
+
await mkdir(path.join(root, 'runtime/loops/agent-tasks/failed'), { recursive: true });
|
|
103
|
+
await writeFile(path.join(root, 'runtime/loops/agent-tasks/failed', `${task.id}.json`), JSON.stringify({ ...task, status: 'needs_revision' }));
|
|
104
|
+
await writeFile(path.join(dir, 'final_judgement.json'), JSON.stringify(noProgress));
|
|
105
|
+
await writeFile(path.join(dir, 'dev_plan.json'), JSON.stringify(dev.plan));
|
|
106
|
+
const newer = new Date(Date.now() + 2000);
|
|
107
|
+
await utimes(path.join(dir, 'dev_plan.json'), newer, newer);
|
|
108
|
+
const refreshed = await refreshTaskAcceptance(root, { queue: 'agent-tasks', taskId: task.id });
|
|
109
|
+
assert.equal(refreshed.status, 'needs_revision');
|
|
110
|
+
assert.equal(JSON.parse(await readFile(path.join(dir, 'final_judgement.json'), 'utf8')).no_progress_continuation, true);
|
|
111
|
+
await writeFile(path.join(dir, 'checkpoints/cp2.json'), JSON.stringify({
|
|
112
|
+
task_id: task.id, checkpoint_id: 'cp2', status: 'ready_for_acceptance', summary: 'Selected next batch',
|
|
113
|
+
files_changed: [], verification: ['next batch test passed'], blockers: [], risks: [],
|
|
114
|
+
project_completion: { status: 'in_progress' }
|
|
115
|
+
}));
|
|
116
|
+
await writeFile(path.join(dir, 'dev_plan.json'), JSON.stringify({
|
|
117
|
+
...dev.plan, checkpoints: [...dev.plan.checkpoints, { id: 'cp2', goal: 'Selected next batch', output_file: 'checkpoints/cp2.json' }]
|
|
118
|
+
}));
|
|
119
|
+
const latest = new Date(Date.now() + 4000);
|
|
120
|
+
await utimes(path.join(dir, 'dev_plan.json'), latest, latest);
|
|
121
|
+
const resumed = await refreshTaskAcceptance(root, { queue: 'agent-tasks', taskId: task.id });
|
|
122
|
+
assert.equal(resumed.status, 'project_in_progress');
|
|
123
|
+
} finally {
|
|
124
|
+
await rm(root, { recursive: true, force: true });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
15
128
|
{
|
|
16
129
|
const devPlan = { checkpoints: [{ id: 'cp1' }] };
|
|
17
130
|
const reviews = {
|
|
@@ -773,3 +886,132 @@ for (const [body, expected] of [
|
|
|
773
886
|
"project"
|
|
774
887
|
]
|
|
775
888
|
]) assert.equal(inferTaskScope({ body }), expected, body);
|
|
889
|
+
|
|
890
|
+
// Plan labels cannot transfer accepted evidence to a different milestone.
|
|
891
|
+
for (const oldAccepted of [['cp1'], []]) {
|
|
892
|
+
for (const renamedId of ['cp1-renamed', 'cp1-renamed-again', 'cp1-third-name']) {
|
|
893
|
+
const result = buildFinalJudgement(
|
|
894
|
+
{ ...baseContract, task_scope: 'project' }, basePlan,
|
|
895
|
+
{ checkpoints: [{ id: renamedId }] }, { count: 1 },
|
|
896
|
+
{ reviews: [{ checkpointId: 'cp1', milestoneId: 'cp1', sequence: 1, status: 'accepted', projectCompletion: { status: 'in_progress' } }] },
|
|
897
|
+
{ dispatchStatus: 'completed', priorCheckpointCount: 1, priorAcceptedMilestoneIds: oldAccepted }
|
|
898
|
+
);
|
|
899
|
+
assert.equal(result.outcome, 'needs_revision', 'plan-only rename: ' + renamedId);
|
|
900
|
+
assert.equal(result.no_progress_continuation, true);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// A real queue must stop the renaming worker and never replay it on later ticks.
|
|
905
|
+
{
|
|
906
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-rename-queue-'));
|
|
907
|
+
try {
|
|
908
|
+
const { task } = await enqueueTask(root, { queue: 'probe', title: 'rename-only', task: '开发完整项目并完成整体目标' });
|
|
909
|
+
const dir = path.join(root, 'runtime/loops/probe/tasks', task.id);
|
|
910
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
911
|
+
const cp = JSON.stringify({ task_id: task.id, checkpoint_id: 'cp1', milestone_id: 'cp1', sequence: 1, status: 'ready_for_acceptance', summary: 'Accepted local work', verification: ['passed'], blockers: [], risks: [], project_completion: { status: 'in_progress' } });
|
|
912
|
+
await writeFile(path.join(dir, 'checkpoints/cp1.json'), cp);
|
|
913
|
+
await writeFile(path.join(dir, 'dev_plan.json'), JSON.stringify({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', checkpoints: [{ id: 'cp1' }] }));
|
|
914
|
+
await writeFile(path.join(dir, 'acceptance_plan.json'), JSON.stringify({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', functional_checks: [], regression_checks: [], negative_tests: [], edge_cases: [], manual_review: [], automation: [], rubric: [] }));
|
|
915
|
+
const worker = path.join(root, 'worker.mjs');
|
|
916
|
+
await writeFile(worker, `import { readFile, writeFile, appendFile } from 'node:fs/promises';
|
|
917
|
+
const file = ${JSON.stringify(path.join(dir, 'dev_plan.json'))};
|
|
918
|
+
const p = JSON.parse(await readFile(file, 'utf8')); p.checkpoints[0].id += '-renamed';
|
|
919
|
+
await writeFile(file, JSON.stringify(p));
|
|
920
|
+
await appendFile(${JSON.stringify(path.join(root, 'dispatches'))}, 'dispatch\\n');`);
|
|
921
|
+
const options = { queue: 'probe', dispatcher: `node '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
922
|
+
assert.equal((await runQueueOnce(root, options)).run.finalJudgement.outcome, 'needs_revision');
|
|
923
|
+
for (let tick = 0; tick < 3; tick++) assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
924
|
+
assert.equal(await readFile(path.join(root, 'dispatches'), 'utf8'), 'dispatch\n');
|
|
925
|
+
assert.equal(await readFile(path.join(dir, 'checkpoints/cp1.json'), 'utf8'), cp);
|
|
926
|
+
} finally {
|
|
927
|
+
await rm(root, { recursive: true, force: true });
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// Exercise the dispatch-time baseline through real disposable queue runs.
|
|
932
|
+
for (const plannedCount of [1, 2]) for (const scenario of ['repair', 'in-place', 'duplicate', 'empty', 'blocked']) {
|
|
933
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-progress-queue-'));
|
|
934
|
+
try {
|
|
935
|
+
const { task } = await enqueueTask(root, { queue: 'probe', title: scenario, task: '开发完整项目并完成整体目标' });
|
|
936
|
+
const dir = path.join(root, 'runtime/loops/probe/tasks', task.id);
|
|
937
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
938
|
+
const checkpoint = (id, sequence, status) => ({ task_id: task.id, checkpoint_id: id, milestone_id: id, sequence, status, summary: 'Local validation', files_changed: [], verification: ['passed'], blockers: [], risks: [], project_completion: { status: 'in_progress' } });
|
|
939
|
+
if (plannedCount === 2) await writeFile(path.join(dir, 'checkpoints/cp1.json'), JSON.stringify(checkpoint('cp1', 1, 'ready_for_acceptance')));
|
|
940
|
+
await writeFile(path.join(dir, 'checkpoints/cp2.json'), JSON.stringify(checkpoint('cp2', 2, ['repair', 'in-place', 'blocked'].includes(scenario) ? 'in_progress' : 'ready_for_acceptance')));
|
|
941
|
+
await writeFile(path.join(dir, 'dev_plan.json'), JSON.stringify({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', checkpoints: plannedCount === 2 ? [{ id: 'cp1' }, { id: 'cp2' }] : [{ id: 'cp2' }] }));
|
|
942
|
+
await writeFile(path.join(dir, 'acceptance_plan.json'), JSON.stringify({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', functional_checks: [], regression_checks: [], negative_tests: [], edge_cases: [], manual_review: [], automation: [], rubric: [] }));
|
|
943
|
+
const worker = path.join(root, 'worker.mjs');
|
|
944
|
+
const cp = { ...checkpoint(scenario === 'in-place' ? 'cp2' : 'cp3', 3, scenario === 'blocked' ? 'blocked' : 'ready_for_acceptance'), milestone_id: 'cp2', revises_checkpoint_id: 'cp2', blockers: scenario === 'blocked' ? ['Need human approval'] : [] };
|
|
945
|
+
await writeFile(worker, `import { writeFile } from 'node:fs/promises';
|
|
946
|
+
import path from 'node:path';
|
|
947
|
+
if (${JSON.stringify(scenario)} !== 'empty') await writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, ${JSON.stringify(cp.checkpoint_id + '.json')}), ${JSON.stringify(JSON.stringify(cp))});`);
|
|
948
|
+
const options = { queue: 'probe', dispatcher: `node '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
949
|
+
const result = await runQueueOnce(root, options);
|
|
950
|
+
const expected = ['repair', 'in-place'].includes(scenario) ? 'project_in_progress' : scenario === 'blocked' ? 'blocked' : 'needs_revision';
|
|
951
|
+
assert.equal(result.run.finalJudgement.outcome, expected, scenario + JSON.stringify(result.run.finalJudgement));
|
|
952
|
+
if (expected === 'project_in_progress') {
|
|
953
|
+
const second = await runQueueOnce(root, options);
|
|
954
|
+
assert.equal(second.run.finalJudgement.outcome, 'needs_revision', 'repeated accepted milestone must stop');
|
|
955
|
+
} else {
|
|
956
|
+
assert.equal((await runQueueOnce(root, options)).processed, false, 'no automatic replay');
|
|
957
|
+
}
|
|
958
|
+
} finally {
|
|
959
|
+
await rm(root, { recursive: true, force: true });
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
console.log('project continuation queue regressions passed');
|
|
963
|
+
|
|
964
|
+
// Invalid history is an unknown baseline, not empty accepted coverage. Permit
|
|
965
|
+
// one repairing dispatch, then stop for explicit revision even if it repairs.
|
|
966
|
+
for (const scenario of ['repair', 'unchanged', 'new-terminal', 'blocked', 'invalid-shape', 'shape-unchanged']) {
|
|
967
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-invalid-baseline-'));
|
|
968
|
+
try {
|
|
969
|
+
const { task } = await enqueueTask(root, { queue: 'probe', title: scenario, task: '开发完整项目并完成整体目标' });
|
|
970
|
+
const dir = path.join(root, 'runtime/loops/probe/tasks', task.id);
|
|
971
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
972
|
+
await writeFile(path.join(dir, 'checkpoints/cp1.json'), ['invalid-shape', 'shape-unchanged'].includes(scenario) ? 'null' : '{');
|
|
973
|
+
const cp = { task_id: task.id, checkpoint_id: 'cp1', milestone_id: 'cp1', status: scenario === 'blocked' ? 'blocked' : 'ready_for_acceptance', summary: 'Repair', verification: ['passed'], blockers: scenario === 'blocked' ? ['Need human approval'] : [], risks: [], project_completion: { status: 'in_progress' } };
|
|
974
|
+
const worker = path.join(root, 'worker.mjs');
|
|
975
|
+
const marker = path.join(root, 'worker-ran');
|
|
976
|
+
await writeFile(worker, `import { writeFile } from 'node:fs/promises';
|
|
977
|
+
await writeFile(${JSON.stringify(marker)}, 'yes');
|
|
978
|
+
${['repair', 'blocked', 'invalid-shape'].includes(scenario) ? `await writeFile(${JSON.stringify(path.join(dir, 'checkpoints/cp1.json'))}, ${JSON.stringify(JSON.stringify(cp))});` : ''}
|
|
979
|
+
${scenario === 'new-terminal' ? `await writeFile(${JSON.stringify(path.join(dir, 'checkpoints/cp2.json'))}, ${JSON.stringify(JSON.stringify({ ...cp, checkpoint_id: 'cp2', sequence: 99, project_completion: { status: 'accepted' } }))});` : ''}`);
|
|
980
|
+
// A consumed authorization is still not satisfied by unknown history, even
|
|
981
|
+
// with an apparently valid successor beside the corrupt record.
|
|
982
|
+
const gateFile = path.join(root, 'runtime/loops/probe/human-input/gates/consumed.json');
|
|
983
|
+
const gate = { task_id: task.id, checkpoint_id: 'cp1', status: 'consumed', authorization: { state: 'consumed' } };
|
|
984
|
+
await mkdir(path.dirname(gateFile), { recursive: true });
|
|
985
|
+
await writeFile(gateFile, JSON.stringify(gate));
|
|
986
|
+
const preserveGate = ['unchanged', 'new-terminal', 'shape-unchanged'].includes(scenario);
|
|
987
|
+
if (preserveGate) await writeFile(path.join(dir, 'checkpoints/successor.json'), JSON.stringify({ ...cp, checkpoint_id: 'cp-successor', revises_checkpoint_id: 'cp1', sequence: 2 }));
|
|
988
|
+
const options = { queue: 'probe', dispatcher: `node '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
989
|
+
const result = await runQueueOnce(root, options);
|
|
990
|
+
if (preserveGate) assert.deepEqual(JSON.parse(await readFile(gateFile, 'utf8')), gate, 'corrupt history must preserve consumed gate byte semantics');
|
|
991
|
+
assert.equal(await readFile(marker, 'utf8'), 'yes', scenario + ': repair worker launches');
|
|
992
|
+
if (result.run.finalJudgement.outcome !== (scenario === 'blocked' ? 'blocked' : 'needs_revision')) console.error(JSON.stringify(result.run));
|
|
993
|
+
assert.equal(result.run.finalJudgement.outcome, scenario === 'blocked' ? 'blocked' : 'needs_revision', scenario);
|
|
994
|
+
assert.equal(JSON.parse(await readFile(path.join(dir, 'final_judgement.json'), 'utf8')).invalid_checkpoint_baseline, true, scenario);
|
|
995
|
+
assert.equal((await runQueueOnce(root, options)).processed, false, 'invalid baseline must not replay');
|
|
996
|
+
await refreshTaskAcceptance(root, { queue: 'probe', taskId: task.id });
|
|
997
|
+
const refreshed = JSON.parse(await readFile(path.join(dir, 'final_judgement.json'), 'utf8'));
|
|
998
|
+
assert.equal(refreshed.outcome, scenario === 'blocked' ? 'blocked' : 'needs_revision', 'refresh retains unknown baseline');
|
|
999
|
+
if (preserveGate) assert.deepEqual(JSON.parse(await readFile(gateFile, 'utf8')), gate, 'refresh must preserve consumed gate');
|
|
1000
|
+
if (scenario === 'repair') {
|
|
1001
|
+
// Explicit operator revision only after validated history: do not erase
|
|
1002
|
+
// the marker by refresh or count repairing JSON as new milestone work.
|
|
1003
|
+
await queueRequeue(root, 'probe', task.id, { from: 'failed' });
|
|
1004
|
+
const terminal = { ...cp, checkpoint_id: 'cp2', revises_checkpoint_id: 'cp1', sequence: 2, summary: 'New verified terminal revision', project_completion: { status: 'accepted' } };
|
|
1005
|
+
await writeFile(worker, `import { writeFile } from 'node:fs/promises'; await writeFile(${JSON.stringify(path.join(dir, 'checkpoints/cp2.json'))}, ${JSON.stringify(JSON.stringify(terminal))});`);
|
|
1006
|
+
const revised = await runQueueOnce(root, options);
|
|
1007
|
+
const contract = JSON.parse(await readFile(path.join(dir, 'task_contract.json'), 'utf8'));
|
|
1008
|
+
assert.equal(revised.run.finalJudgement.outcome, contract.requires_human_gate ? 'ready_for_human_review' : 'ready_to_apply', 'explicit revision restores acceptance without bypassing contract gate: ' + JSON.stringify({ judgement: revised.run.finalJudgement, plan: JSON.parse(await readFile(path.join(dir, 'dev_plan.json'), 'utf8')).checkpoints }));
|
|
1009
|
+
assert.equal(JSON.parse(await readFile(path.join(dir, 'final_judgement.json'), 'utf8')).invalid_checkpoint_baseline, false);
|
|
1010
|
+
assert.equal(JSON.parse(await readFile(gateFile, 'utf8')).status, 'satisfied', 'valid successor can satisfy consumed gate after repair');
|
|
1011
|
+
}
|
|
1012
|
+
} finally { await rm(root, { recursive: true, force: true }); }
|
|
1013
|
+
}
|
|
1014
|
+
console.log('invalid baseline controlled repair regressions passed');
|
|
1015
|
+
|
|
1016
|
+
// Durable phase closure protocol and conservative negative cases.
|
|
1017
|
+
await import('./revision-coverage-self-test.mjs');
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { writeAcceptanceReviews, buildFinalJudgement, enqueueTask, runQueueOnce } from '../lib/core.mjs';
|
|
7
|
+
|
|
8
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-revision-coverage-'));
|
|
9
|
+
const contract = { task_id: 'coverage-task', task_scope: 'project', requires_human_gate: false };
|
|
10
|
+
const plan = { checkpoints: [{ id: 'stable' }] };
|
|
11
|
+
const acceptance = { functional_checks: [], regression_checks: [], negative_tests: [], edge_cases: [], manual_review: [], automation: [], rubric: [] };
|
|
12
|
+
const phase = id => ({ task_id: contract.task_id, checkpoint_id: id, milestone_id: 'stable', status: 'in_progress', summary: 'Phase completed; integration pending', verification: ['phase test passed'], risks: ['integration pending'], blockers: [], project_completion: { status: 'in_progress' } });
|
|
13
|
+
const history = [phase('p1'), phase('p2'), phase('p3')];
|
|
14
|
+
const bytes = cp => JSON.stringify(cp);
|
|
15
|
+
const digest = cp => createHash('sha256').update(bytes(cp)).digest('hex');
|
|
16
|
+
const final = () => ({ ...phase('done'), sequence: 4, status: 'ready_for_acceptance', summary: 'Integration completed', risks: [], verification: ['integration test passed'], project_completion: { status: 'accepted' }, revises_checkpoint_id: 'p3', revision_coverage: history.map(cp => ({ checkpoint_id: cp.checkpoint_id, checkpoint_sha256: digest(cp), resolution: 'Integrated and verified this phase', verification: ['integration test passed'] })) });
|
|
17
|
+
let cases = 0;
|
|
18
|
+
try {
|
|
19
|
+
async function judge(name, records) {
|
|
20
|
+
const dir = path.join(root, name);
|
|
21
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
22
|
+
await mkdir(path.join(dir, 'reviews'));
|
|
23
|
+
for (const [i, cp] of records.entries()) await writeFile(path.join(dir, 'checkpoints', `${i}.json`), typeof cp === 'string' ? cp : bytes(cp));
|
|
24
|
+
const reviews = await writeAcceptanceReviews(dir, 'disposable', { id: contract.task_id }, { contract }, { plan: acceptance }, { plan, checkpointsDir: 'checkpoints', reviewsDir: 'reviews' }, { persist: false });
|
|
25
|
+
cases++;
|
|
26
|
+
return buildFinalJudgement(contract, acceptance, plan, { count: records.length }, reviews, { dispatchStatus: 'completed' });
|
|
27
|
+
}
|
|
28
|
+
assert.equal((await judge('complete', [...history, final()])).outcome, 'ready_to_apply');
|
|
29
|
+
assert.equal((await judge('reverse-order', [final(), ...history.toReversed()])).outcome, 'ready_to_apply');
|
|
30
|
+
for (const [name, mutate] of [
|
|
31
|
+
['no-coverage', cp => { delete cp.revision_coverage; }],
|
|
32
|
+
['partial', cp => { cp.revision_coverage.pop(); }],
|
|
33
|
+
['stale-digest', cp => { cp.revision_coverage[0].checkpoint_sha256 = 'old'; }],
|
|
34
|
+
['unknown-target', cp => { cp.revision_coverage[0].checkpoint_id = 'missing'; }],
|
|
35
|
+
['no-resolution', cp => { cp.revision_coverage[0].resolution = ''; }],
|
|
36
|
+
['no-evidence', cp => { cp.revision_coverage[0].verification = []; }],
|
|
37
|
+
['unbound-evidence', cp => { cp.revision_coverage[0].verification = ['invented verification']; }],
|
|
38
|
+
['rename', cp => { cp.milestone_id = 'renamed'; }],
|
|
39
|
+
['different-task', cp => { cp.task_id = 'other'; }],
|
|
40
|
+
['duplicate-coverage', cp => { cp.revision_coverage.push(cp.revision_coverage[0]); }],
|
|
41
|
+
['malformed-coverage', cp => { cp.revision_coverage = {}; }]
|
|
42
|
+
]) {
|
|
43
|
+
const cp = final(); mutate(cp);
|
|
44
|
+
assert.equal((await judge(name, [...history, cp])).outcome, 'needs_revision', name);
|
|
45
|
+
}
|
|
46
|
+
for (const [name, patch, expected] of [
|
|
47
|
+
['real-defect', { status: 'needs_revision' }, 'needs_revision'],
|
|
48
|
+
['invalid-phase-coverage', { revision_coverage: [{ checkpoint_id: 'missing' }] }, 'needs_revision'],
|
|
49
|
+
['missing-verification', { verification: [] }, 'needs_revision'],
|
|
50
|
+
['missing-summary', { summary: '' }, 'needs_revision'],
|
|
51
|
+
['different-milestone', { milestone_id: 'other' }, 'needs_revision'],
|
|
52
|
+
['human-gate', { status: 'needs_human_input', blockers: ['Owner approval required'] }, 'blocked'],
|
|
53
|
+
['reversed-clock', { sequence: 5 }, 'needs_revision']
|
|
54
|
+
]) {
|
|
55
|
+
const records = structuredClone(history); Object.assign(records[0], patch);
|
|
56
|
+
const cp = final(); cp.revision_coverage[0].checkpoint_sha256 = digest(records[0]);
|
|
57
|
+
assert.equal((await judge(name, [...records, cp])).outcome, expected, name);
|
|
58
|
+
}
|
|
59
|
+
assert.equal((await judge('corruption', [...history, '{', final()])).outcome, 'needs_revision');
|
|
60
|
+
assert.equal((await judge('duplicate-id', [...history, history[0], final()])).outcome, 'needs_revision');
|
|
61
|
+
// Ordered unrelated failure must survive even without the coverage protocol.
|
|
62
|
+
const unrelated = { ...phase('unrelated'), milestone_id: 'other', sequence: 1, status: 'needs_revision' };
|
|
63
|
+
const done = final(); delete done.revision_coverage;
|
|
64
|
+
assert.equal((await judge('ordered-cross-scope', [unrelated, done])).outcome, 'needs_revision');
|
|
65
|
+
const renamed = { ...done, milestone_id: 'renamed' };
|
|
66
|
+
assert.equal((await judge('renamed-terminal', [renamed])).outcome, 'needs_revision');
|
|
67
|
+
// Invalid coverage must not silently use clocks instead.
|
|
68
|
+
const ordered = history.map((cp, i) => ({ ...cp, sequence: i + 1 }));
|
|
69
|
+
assert.equal((await judge('invalid-coverage-with-clocks', [...ordered, final()])).outcome, 'needs_revision');
|
|
70
|
+
console.log(`revision coverage self-test passed (${cases} cases)`);
|
|
71
|
+
} finally {
|
|
72
|
+
await rm(root, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
// Exercise the same protocol through dispatch, final judgement and queue state.
|
|
77
|
+
for (const scenario of ['covered', 'uncovered', 'cross-scope', 'invalid-phase-coverage', 'blocked']) {
|
|
78
|
+
const queueRoot = await mkdtemp(path.join(tmpdir(), 'loop-coverage-queue-'));
|
|
79
|
+
try {
|
|
80
|
+
const { task } = await enqueueTask(queueRoot, { queue: 'probe', title: scenario, task: '开发完整项目并完成整体目标' });
|
|
81
|
+
const dir = path.join(queueRoot, 'runtime/loops/probe/tasks', task.id);
|
|
82
|
+
await mkdir(path.join(dir, 'checkpoints'), { recursive: true });
|
|
83
|
+
const records = history.map(cp => ({ ...cp, task_id: task.id }));
|
|
84
|
+
if (scenario === 'cross-scope') records[0].milestone_id = 'unrelated';
|
|
85
|
+
if (scenario === 'invalid-phase-coverage') records[0].revision_coverage = [{ checkpoint_id: 'missing' }];
|
|
86
|
+
if (scenario === 'blocked') Object.assign(records[0], { status: 'needs_human_input', blockers: ['Owner approval required'] });
|
|
87
|
+
for (const cp of records) await writeFile(path.join(dir, 'checkpoints', cp.checkpoint_id + '.json'), bytes(cp));
|
|
88
|
+
await writeFile(path.join(dir, 'dev_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...plan }));
|
|
89
|
+
await writeFile(path.join(dir, 'acceptance_plan.json'), bytes({ task_id: task.id, generated_by: 'project_scope_worker_revision_after_deterministic_planner_v1', ...acceptance }));
|
|
90
|
+
const cp = { ...final(), task_id: task.id };
|
|
91
|
+
cp.revision_coverage.forEach((entry, i) => { entry.checkpoint_sha256 = digest(records[i]); });
|
|
92
|
+
if (scenario === 'uncovered') delete cp.revision_coverage;
|
|
93
|
+
const worker = path.join(queueRoot, 'worker.mjs');
|
|
94
|
+
await writeFile(worker, `import {writeFile} from 'node:fs/promises'; import path from 'node:path'; await writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, 'done.json'), ${JSON.stringify(bytes(cp))});`);
|
|
95
|
+
const options = { queue: 'probe', dispatcher: `${process.execPath} '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
96
|
+
const result = await runQueueOnce(queueRoot, options);
|
|
97
|
+
const effectiveContract = JSON.parse(await readFile(path.join(dir, 'task_contract.json'), 'utf8'));
|
|
98
|
+
const expected = scenario === 'covered' ? (effectiveContract.requires_human_gate ? 'ready_for_human_review' : 'ready_to_apply') : scenario === 'blocked' ? 'blocked' : 'needs_revision';
|
|
99
|
+
assert.equal(result.run.finalJudgement.outcome, expected, scenario);
|
|
100
|
+
assert.equal((await runQueueOnce(queueRoot, options)).processed, false, 'terminal or revision queue must not replay');
|
|
101
|
+
console.log(JSON.stringify({ test: 'revision-coverage-queue', scenario, outcome: expected, node: process.version, replay: false }));
|
|
102
|
+
} finally {
|
|
103
|
+
await rm(queueRoot, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -189,6 +189,8 @@ For a project-level objective:
|
|
|
189
189
|
5. Continue through implementation, verification, revisions, and the next actionable backlog item within the authorized safety boundary.
|
|
190
190
|
6. Stop only when total project acceptance passes, or a genuine human authorization/product decision/external-state blocker prevents meaningful progress.
|
|
191
191
|
|
|
192
|
+
For project continuations (explicit or inferred scope), preserve worker-authored plans and reread durable plans after dispatch. Progress means a committed milestone newly passes acceptance, including repairing an existing failed milestone; extra checkpoint files or re-emitting accepted milestones do not count. Accepted progress must match durable checkpoint/milestone identity even for a single planned milestone; changing only the plan ID cannot transfer old acceptance to new work. A no-progress continuation stops for revision instead of requeueing. Acceptance refresh re-evaluates changed plans and rebuilds legacy judgements missing coverage once.
|
|
193
|
+
|
|
192
194
|
Never silently narrow a complete-project request into “first milestone” and call that the Loop complete. A single queue task or milestone may be complete while the project remains active.
|
|
193
195
|
|
|
194
196
|
Recommended commands:
|
|
@@ -373,3 +375,18 @@ Before saying a loop is finished, verify:
|
|
|
373
375
|
- Are evidence paths and next actions included?
|
|
374
376
|
|
|
375
377
|
If any project requirement remains, report a phase/task result and continue with the next authorized item; do not claim the project or Loop is complete.
|
|
378
|
+
|
|
379
|
+
### Invalid checkpoint baseline repair
|
|
380
|
+
|
|
381
|
+
Pre-dispatch review treats malformed JSON and non-object checkpoint roots as explicit invalid evidence, not empty accepted coverage. A bounded worker may repair the local record, but an unknown dispatch baseline is persisted as `invalid_checkpoint_baseline` and prevents automatic acceptance/continuation, including after acceptance refresh. Repair success is not proof of new milestone progress: use an explicit revision from validated history. Unrepaired invalid evidence cannot be superseded by a terminal snapshot. Human blockers take precedence; gate reconciliation leaves all gates unchanged while any checkpoint is invalid. Filesystem/permission failures are not classified as repairable JSON corruption. This conservative path may require an additional explicit revision even after a successful repair; it must not replay automatically.
|
|
382
|
+
|
|
383
|
+
### Normal context handoff versus runtime recovery
|
|
384
|
+
|
|
385
|
+
A valid successful handoff with nonempty, previously unseen checkpoint verification rotates the session without consuming or resetting runtimeRecoveryCount. Repeated verification (even with renamed checkpoints/new run IDs), empty verification and invalid handoffs stop; 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.
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
### Explicit closure of unordered phase checkpoints
|
|
389
|
+
|
|
390
|
+
New checkpoints must carry stable `task_id`/`milestone_id`, a monotonic `sequence` and checkpoint-owned `created_at`; do not invent clocks for historical records. `revises_checkpoint_id` is lineage only, not proof that every older snapshot is resolved. A final accepted checkpoint can close unordered, status-only `in_progress` records with `revision_coverage`: one entry per old record containing `checkpoint_id`, SHA-256 of the exact checkpoint bytes in `checkpoint_sha256`, a concrete `resolution`, and nonempty `verification` strings also present in the final checkpoint's verification array. Same-task and same-planned-milestone identity must match. Preserve historical files.
|
|
391
|
+
|
|
392
|
+
Coverage cannot close real failed checks, missing evidence, corruption, duplicate identities, human blockers or deferred gates. A phase that itself declares revision coverage is not a plain status-only target: its invalid declaration cannot be laundered away by a later coverage edge. Invalid coverage remains a revision failure even if clocks otherwise order the records. Uncovered unordered history remains effective. Different explicit milestone identities never supersede each other by time alone; legacy unlabelled single-plan chronology remains supported. Evidence references are cooperative claims, not independent proof of test execution: review the actual artifacts before emitting final coverage.
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
3. Read `LOOP_RESUME_FILE`, the task contract/plans, latest amendment and latest relevant checkpoint. Resolve relative references against its `workspaceRoot`. Read a previous handoff only for outstanding context; newer checkpoints and amendments take precedence. Do not reload complete transcripts or all historical checkpoints.
|
|
6
6
|
4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, use a small work unit rather than inventing a percentage. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
|
|
7
7
|
5. For unfinished work requiring a new session, write a normal progress checkpoint with `task_id`, `loop_run_id`, and `blockers`, then the bounded JSON handoff at `LOOP_CONTEXT_HANDOFF_FILE` using the schema provided in the worker prompt. Include task/run/generation/attempt binding, the checkpoint path, summary, completed and remaining work, evidence, next action, authority, pending external actions and blockers. Keep it under 16 KiB and omit secrets. The runner validates binding and a real checkpoint inside this task's checkpoint directory; missing/malformed/stale evidence stops recovery rather than accepting the task.
|
|
8
|
-
6. Verify pending external, paid or destructive actions against durable receipts/reservations before replay. Uncertain outcomes and authority blockers stop automatic continuation, including when the worker exits nonzero. An existing handoff is checked before any retry; malformed or stale handoffs fail closed. A clean handoff never overrides a permission failure. Effective blocked checkpoint reviews are checked before each ordinary dispatch retry and also veto runtime recovery when interruption happens before handoff creation. Ordinary and verification failures with effective blockers remain `needs_human_input`, not development revisions; resolved historical blockers do not. Record checkpoint `created_at` (UTC) and, when known, a task-monotonic numeric `sequence`; checkpoint IDs and regenerated review timestamps are not ordering evidence. Conflicting or missing chronology preserves unresolved reviews rather than guessing from names. A newer unblocked snapshot with unambiguous chronology can resolve historical blockers. Multi-milestone plans use the same rule within each milestone and count each planned milestone only once. Terminal acceptance may ignore a chronologically later `needs_human_acceptance` project snapshot only if that review independently passes acceptance and carries no materializable deferred gates. The project label alone cannot hide a blocked/revise review; missing blocker details are not proof of broader-project-only governance. Test accepted terminal + later unknown external outcome under ordinary failure (one and multiple attempts), overflow, incomplete turn and exhausted recovery, including the generated dispatcher. The veto must prevent queue re-entry, not merely change the judgement report. A handoff cannot authorize an action. The runner preserves the task id and increments the session generation on a validated handoff or recognized context overflow; it never retries a known runtime interruption in the same session.
|
|
8
|
+
6. Verify pending external, paid or destructive actions against durable receipts/reservations before replay. Uncertain outcomes and authority blockers stop automatic continuation, including when the worker exits nonzero. An existing handoff is checked before any retry; malformed or stale handoffs fail closed. A clean handoff never overrides a permission failure. Effective blocked checkpoint reviews are checked before each ordinary dispatch retry and also veto runtime recovery when interruption happens before handoff creation. Ordinary and verification failures with effective blockers remain `needs_human_input`, not development revisions; resolved historical blockers do not. Record checkpoint `created_at` (UTC) and, when known, a task-monotonic numeric `sequence`; checkpoint IDs and regenerated review timestamps are not ordering evidence. Conflicting or missing chronology preserves unresolved reviews rather than guessing from names. A newer unblocked snapshot with unambiguous chronology can resolve historical blockers. Multi-milestone plans use the same rule within each milestone and count each planned milestone only once. Terminal acceptance may ignore a chronologically later `needs_human_acceptance` project snapshot only if that review independently passes acceptance and carries no materializable deferred gates. The project label alone cannot hide a blocked/revise review; missing blocker details are not proof of broader-project-only governance. Test accepted terminal + later unknown external outcome under ordinary failure (one and multiple attempts), overflow, incomplete turn and exhausted recovery, including the generated dispatcher. The veto must prevent queue re-entry, not merely change the judgement report. A handoff cannot authorize an action. The runner preserves the task id and increments the session generation on a validated handoff or recognized context overflow; it never retries a known runtime interruption in the same session. Exception recoveries use `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Successful validated handoffs with nonempty, previously unseen checkpoint verification rotate without consuming or resetting this counter. Repeated or empty verification stops even if checkpoint/run IDs change. Verification fingerprints are cooperative evidence, not independent semantic proof. Accepted project progress resets the exception recovery counter.
|
|
9
9
|
7. Inspect task/run artifacts after each tick. Accepted unfinished project milestones rotate at the soft/hard threshold or tick limit, whichever occurs first; completed tasks are never requeued just because usage is high. Handoffs remain `runtime_interrupted`, not completed. Full worker stdout/stderr stay in per-run/per-attempt logs; bounded tails plus deduplicated diagnostic signatures reach the runner. Signatures are matched across the complete stream before clipping (including split UTF-8 chunks), using the queue's configured patterns; human-action classification retains priority over runtime recovery. CLI JSON parsing is capped at 2 MiB. No protection here guarantees that one tool-heavy turn cannot overflow: worker discipline and the underlying runtime's compaction remain necessary.
|
|
10
10
|
|
|
11
11
|
Validate with `node scripts/context-budget-self-test.mjs` and `node scripts/openclaw-install-self-test.mjs` in a source checkout. Use disposable queues and mocked workers; do not probe production queues or paid providers for these tests.
|
|
@@ -9,7 +9,7 @@ For example, “Complete the project-level objective, not just the first bounded
|
|
|
9
9
|
## Inspect effective reviews and gates
|
|
10
10
|
|
|
11
11
|
- Read checkpoint reviews, task gates and `final_judgement.json` together. Checkpoint sequence and creation time establish chronology; filename numbering and regenerated review timestamps do not. Missing or conflicting ordering must not erase a live blocker.
|
|
12
|
-
- For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews. Multiple planned milestones still require their effective reviews.
|
|
12
|
+
- For a task with at most one planned checkpoint, an accepted terminal task review can remain terminal despite a later project `needs_human_acceptance` snapshot only when chronology is established and that later review is independently accepted with no materializable deferred gates. Preserve blocked, revise and unordered reviews unless explicit validated revision coverage closes status-only phases as described below. Different explicit milestone identities never supersede each other by chronology. Multiple planned milestones still require their effective reviews.
|
|
13
13
|
- A task terminal result is not project completion or deployment authorization. Inspect the original completion contract and project backlog independently.
|
|
14
14
|
- Reconcile a consumed gate only through the recorded same-task successor link, `revises_checkpoint_id`. A satisfied gate records the successor, not proof that the successor passed acceptance. Check the effective review and final queue state separately.
|
|
15
15
|
- Effective human/authority blockers and uncertain external outcomes remain `needs_human_input`, including after ordinary worker failure; do not turn them into development revisions or automatic retries. Resolved historical blockers do not permanently veto continuation.
|
|
@@ -17,3 +17,13 @@ For example, “Complete the project-level objective, not just the first bounded
|
|
|
17
17
|
## Evidence boundaries
|
|
18
18
|
|
|
19
19
|
Inspect artifacts rather than dispatcher exit status. A checkpoint accepted by the worker is not the outer queue's final judgement; `ready_to_apply` is not applied. For multiple PRs, test each exact candidate and a correctly constructed combined tree separately. Local tests, exact-HEAD remote CI, package installation and live-instance acceptance are distinct claims.
|
|
20
|
+
|
|
21
|
+
## Explicit status-only phase closure
|
|
22
|
+
|
|
23
|
+
An accepted final checkpoint may close unordered `in_progress` phases through `revision_coverage`: each entry binds `checkpoint_id`, `checkpoint_sha256` (exact historical bytes), concrete `resolution`, and nonempty verification strings present in the final checkpoint. Require unique same-task, same-planned-milestone records, and reject reversed known clocks. Keep historical files unchanged. `revises_checkpoint_id` alone is lineage, not this coverage proof.
|
|
24
|
+
|
|
25
|
+
Coverage cannot close real defects, missing evidence, corruption, duplicate identities, human blockers, deferred gates, or a phase that itself declares coverage. Invalid coverage remains a failure regardless of chronological ordering. Inspect actual verification artifacts; references are cooperative claims.
|
|
26
|
+
|
|
27
|
+
## Continuation and invalid history
|
|
28
|
+
|
|
29
|
+
Progress is newly accepted durable milestone identity, not renamed plans, extra files or repeated accepted snapshots. Preserve explicit and inferred project plans. Malformed/non-object checkpoints may receive a bounded repairing dispatch, but unknown pre-dispatch history persists as `invalid_checkpoint_baseline`, blocks automatic acceptance, and requires explicit revision from validated history. Gate reconciliation leaves gates unchanged while any checkpoint is invalid. Filesystem errors are not JSON corruption.
|