taskforce-loop-engineering 0.16.8 → 0.16.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.16.9 - 2026-11-29
6
+
7
+ Checkpoint clock preflight and release install check. Publication does not upgrade installed CLIs or generated integrations. OpenClaw picks up the new worker instruction with the package upgrade (re-run `loop-engineering-openclaw-manage --action upgrade --confirm-upgrade` as usual). Hermes needs its generated dispatcher regenerated: run `loop-engineering-hermes-doctor`, which reports it as out of date, then rerun the installer with `--confirm-install --force` and the same `--queue` and `--language`; this also rewrites the queue config, scheduler units and managed `AGENTS.md` block, so back up local changes first.
8
+
9
+ - Add a read-only checkpoint clock preflight and shared OpenClaw/Hermes worker instructions to catch contradictory sequence/timestamp ordering before submission. Validate only the current run, including progress handoffs, preserve historical evidence, and keep clock validation distinct from acceptance. A record from an earlier run dated in the future is reported as `needsHuman` (exit 3) instead of failing every new record, and a missing checkpoints directory reports `checked: 0`. Installed Hermes dispatchers receive the instruction only after rerunning the installer with `--confirm-install --force`; until then `loop-engineering-hermes-doctor` reports them as out of date. OpenClaw picks it up with the package upgrade.
10
+ - Add a release install check, `npm run check:release-install` (`scripts/release-install-e2e.mjs`). It packs the package as npm would ship it, installs it and the previous npm release, and checks fresh install, upgrade from the previous release, doctor, smoke and uninstall for OpenClaw and Hermes. Platform CLIs and `systemctl` are mocks; generated units must pass `systemd-analyze verify` without diagnostics. CI runs it on every push and pull request, and the Release workflow runs it before anything is tagged or published.
11
+ - Pin install commands to 0.16.9.
12
+
5
13
  ## 0.16.8 - 2026-11-29
6
14
 
7
15
  Skill consent and Hermes uninstall release.
package/README.md CHANGED
@@ -108,13 +108,13 @@ isolated git worktree.
108
108
  From npm:
109
109
 
110
110
  ```bash
111
- npm install -g taskforce-loop-engineering@0.16.8
111
+ npm install -g taskforce-loop-engineering@0.16.9
112
112
  ```
113
113
 
114
114
  Or run without installing:
115
115
 
116
116
  ```bash
117
- npx -p taskforce-loop-engineering@0.16.8 loop-engineering --help
117
+ npx -p taskforce-loop-engineering@0.16.9 loop-engineering --help
118
118
  ```
119
119
 
120
120
  ## OpenClaw conversation installer
@@ -0,0 +1,89 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ // This is a submission preflight, not an acceptance reviewer or history repair.
6
+ // Validate only this run; old incomplete clocks must remain repairable by a new
7
+ // truthful revision instead of being normalized in place.
8
+ export function checkpointClockErrors(checkpoint, history, nowMs = Date.now()) {
9
+ const errors = [];
10
+ for (const key of ['task_id', 'checkpoint_id']) {
11
+ if (typeof checkpoint[key] !== 'string' || !checkpoint[key].trim()) errors.push(`${key} is required to scope clock validation`);
12
+ }
13
+ const sequence = checkpoint.sequence;
14
+ const at = typeof checkpoint.created_at === 'string'
15
+ && /(?:Z|[+-]\d{2}:\d{2})$/.test(checkpoint.created_at)
16
+ ? Date.parse(checkpoint.created_at) : NaN;
17
+ if (!Number.isSafeInteger(sequence) || sequence < 0) errors.push('sequence must be a nonnegative safe integer');
18
+ if (!Number.isFinite(at)) errors.push('created_at must be an actual ISO timestamp with timezone');
19
+ else if (at > nowMs + 1000) errors.push('created_at is in the future; use the actual machine clock');
20
+ for (const other of history) {
21
+ if (other === checkpoint || other.task_id !== checkpoint.task_id) continue;
22
+ if (other.checkpoint_id === checkpoint.checkpoint_id) errors.push(`duplicate checkpoint_id: ${checkpoint.checkpoint_id}`);
23
+ // A historical record dated in the future (for example clock skew on
24
+ // another host) can never be exceeded by a truthful clock. It is reported
25
+ // once as needing human repair by checkCheckpointClocks; ordering against
26
+ // its timestamp is skipped so new records are not failed forever.
27
+ const parsedOtherAt = Date.parse(other.created_at);
28
+ const otherAt = other.loop_run_id !== checkpoint.loop_run_id && parsedOtherAt > nowMs + 1000 ? NaN : parsedOtherAt;
29
+ if (other.loop_run_id !== checkpoint.loop_run_id && Number.isFinite(at) && Number.isFinite(otherAt) && at <= otherAt)
30
+ errors.push(`created_at must exceed historical checkpoint ${other.checkpoint_id}`);
31
+ if (!Number.isSafeInteger(sequence) || !Number.isSafeInteger(other.sequence)) continue;
32
+ if (sequence === other.sequence) errors.push(`sequence duplicates checkpoint ${other.checkpoint_id}`);
33
+ if (other.loop_run_id !== checkpoint.loop_run_id && sequence <= other.sequence)
34
+ errors.push(`sequence must exceed historical checkpoint ${other.checkpoint_id} (${other.sequence})`);
35
+ if (!Number.isFinite(at) || !Number.isFinite(otherAt)) continue;
36
+ if ((sequence > other.sequence && at <= otherAt)
37
+ || (other.loop_run_id === checkpoint.loop_run_id && sequence < other.sequence && at >= otherAt))
38
+ errors.push(`created_at and sequence disagree with checkpoint ${other.checkpoint_id}`);
39
+ }
40
+ return errors;
41
+ }
42
+
43
+ export async function checkCheckpointClocks(dir, runId, { nowMs = Date.now() } = {}) {
44
+ if (typeof runId !== 'string' || !runId.trim()) throw new Error('A current run id is required');
45
+ const records = [];
46
+ const errors = [];
47
+ let names;
48
+ try {
49
+ names = await readdir(dir);
50
+ } catch (error) {
51
+ // No checkpoints written yet: nothing to validate, which is not progress.
52
+ if (error?.code === 'ENOENT') return { ok: true, checked: 0, errors, needsHuman: [] };
53
+ throw error;
54
+ }
55
+ for (const file of names.filter(name => name.endsWith('.json'))) {
56
+ try {
57
+ const value = JSON.parse(await readFile(path.join(dir, file), 'utf8'));
58
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object');
59
+ records.push({ file, value });
60
+ } catch {
61
+ errors.push({ file, errors: ['unreadable or invalid checkpoint; preserve evidence and repair explicitly'] });
62
+ }
63
+ }
64
+ let checked = 0;
65
+ const history = records.map(record => record.value);
66
+ const needsHuman = records
67
+ .filter(({ value }) => value.loop_run_id !== runId && Date.parse(value.created_at) > nowMs + 1000)
68
+ .map(({ file, value }) => ({ file, checkpoint_id: value.checkpoint_id, created_at: value.created_at,
69
+ error: 'historical created_at is in the future; a human must repair the clock or the record' }));
70
+ for (const { file, value } of records) {
71
+ if (value.loop_run_id !== runId) continue;
72
+ checked++;
73
+ const found = checkpointClockErrors(value, history, nowMs);
74
+ if (found.length) errors.push({ file, errors: found });
75
+ }
76
+ return { ok: errors.length === 0 && needsHuman.length === 0, checked, errors, needsHuman };
77
+ }
78
+
79
+ export function checkpointClockInstructions(env = process.env) {
80
+ const instructions = ['CHECKPOINT CLOCKS: At write time get created_at from the actual machine clock (for example new Date().toISOString()), never guess or copy a timestamp. Choose sequence above this task\'s historical maximum. Both clocks must order a new revision after its predecessors. Preserve old bytes; repair conflicting history with a new same-milestone revision and fresh evidence, not by editing timestamps or acceptance.'];
81
+ if (env.LOOP_CHECKPOINTS_DIR && env.LOOP_RUN_ID) {
82
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
83
+ const script = fileURLToPath(new URL('../scripts/checkpoint-preflight.mjs', import.meta.url));
84
+ instructions.push('Before returning run the read-only clock preflight and fix errors in your own new records: '
85
+ + [process.execPath, script, env.LOOP_CHECKPOINTS_DIR, env.LOOP_RUN_ID].map(quote).join(' ')
86
+ + '. This validates clocks only: zero checked records is not progress and passing is not business acceptance. Never rewrite historical files to make it pass. If it reports needsHuman, an earlier record has a future clock: do not retry or edit it; stop and report it as a blocker needing human repair.');
87
+ }
88
+ return instructions.join('\n');
89
+ }
@@ -1,3 +1,4 @@
1
+ import { checkpointClockInstructions } from './checkpoint-clocks.mjs';
1
2
  import { StringDecoder } from 'node:string_decoder';
2
3
  import { DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS, DEFAULT_RECOVERABLE_RUNTIME_PATTERNS } from './dispatch-classification.mjs';
3
4
  import path from 'node:path';
@@ -76,6 +77,7 @@ export function contextWorkerInstructions(env = process.env) {
76
77
  'Read the resume manifest at ' + (env.LOOP_RESUME_FILE || '(unavailable)') + ' and only the latest relevant checkpoint; never reload entire session transcripts or all historical checkpoints.',
77
78
  'At approximately ' + Math.round(policy.softRatio * 100) + '% of the model context window, save a checkpoint and prepare handoff. At ' + Math.round(policy.hardRatio * 100) + '% stop new work and hand off. If live usage is unavailable, keep working through the milestone, checkpoint after each verified sub-step, and hand off only when the remaining work clearly will not fit this turn; do not invent token measurements.',
78
79
  ...turnTimeoutInstruction(env.LOOP_TURN_TIMEOUT_MS),
80
+ checkpointClockInstructions(env),
79
81
  'Before repeating an external/paid/destructive operation, verify its previous outcome using durable receipts/reservations; an uncertain outcome is a blocker, never permission to replay. Preserve existing human gates and amendment versions.',
80
82
  'If unfinished work needs a fresh session, first write a normal progress checkpoint (not ready_for_acceptance) with task_id and loop_run_id matching this run, then write JSON to ' + (env.LOOP_CONTEXT_HANDOFF_FILE || '(unavailable)') + ' and finish the turn. Never claim completion merely because you handed off.',
81
83
  'Handoff schema (max 16 KiB): ' + JSON.stringify({ version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID, generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), reason: 'context_budget', checkpoint: 'path to the current progress checkpoint', summary: 'brief current state', completed: ['completed work'], remaining: ['remaining work'], evidence: ['checkpoint and verification paths'], nextAction: 'one concrete next step', authority: 'authorized scope and gates', pendingActions: ['uncertain external action receipts to reconcile, if any'], blockers: [] }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-loop-engineering",
3
- "version": "0.16.8",
3
+ "version": "0.16.9",
4
4
  "private": false,
5
5
  "description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
6
6
  "type": "module",
@@ -32,8 +32,9 @@
32
32
  "check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node --check scripts/hermes-manage.mjs && node scripts/hermes-install-self-test.mjs",
33
33
  "check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
34
34
  "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",
35
- "check": "node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && node scripts/continuation-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/revision-coverage-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
36
- "pack:dry": "npm pack --dry-run"
35
+ "check": "node scripts/checkpoint-clock-self-test.mjs && node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && node scripts/continuation-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/revision-coverage-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
36
+ "pack:dry": "npm pack --dry-run",
37
+ "check:release-install": "node scripts/release-install-e2e.mjs"
37
38
  },
38
39
  "exports": {
39
40
  ".": "./lib/goal-api.mjs",
@@ -0,0 +1,116 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { checkpointClockErrors, checkCheckpointClocks, checkpointClockInstructions } from '../lib/checkpoint-clocks.mjs';
8
+ import { contextWorkerInstructions } from '../lib/context-budget.mjs';
9
+ import { dispatcherSource } from './hermes-sources.mjs';
10
+ import { selectEffectiveAcceptanceReviews } from '../lib/core.mjs';
11
+
12
+ const root = await mkdtemp(path.join(tmpdir(), "loop-clock space'$-"));
13
+ const nowMs = Date.parse('2024-06-01T12:00:00Z');
14
+ const old = { task_id: 'task', checkpoint_id: 'phase', milestone_id: 'unit', loop_run_id: 'previous',
15
+ sequence: 7, created_at: '2024-06-01T10:10:00Z', status: 'in_progress' };
16
+ const accepted = { ...old, checkpoint_id: 'done', loop_run_id: 'intermediate', sequence: 8,
17
+ created_at: '2024-06-01T10:06:00Z', status: 'ready_for_acceptance', revises_checkpoint_id: 'phase' };
18
+ const repair = { ...accepted, checkpoint_id: 'repair', loop_run_id: 'current', sequence: 9, created_at: '2024-06-01T11:00:00Z' };
19
+ const cli = fileURLToPath(new URL('./checkpoint-preflight.mjs', import.meta.url));
20
+ const put = (file, value) => writeFile(path.join(root, file), JSON.stringify(value) + '\n');
21
+ const check = () => checkCheckpointClocks(root, 'current', { nowMs });
22
+ try {
23
+ await put('old.json', old);
24
+ const oldBytes = await readFile(path.join(root, 'old.json'));
25
+ await put('new.json', { ...accepted, loop_run_id: 'current' });
26
+ let report = await check();
27
+ assert.equal(report.ok, false);
28
+ assert(report.errors.some(entry => entry.errors.some(error => error.includes('disagree'))));
29
+ const red = spawnSync(process.execPath, [cli, root, 'current'], { encoding: 'utf8' });
30
+ assert.equal(red.status, 1);
31
+ assert.equal(JSON.parse(red.stdout).checked, 1);
32
+
33
+ // Historical conflicts are left untouched: the later real revision can pass.
34
+ await put('intermediate.json', accepted);
35
+ await put('new.json', repair);
36
+ report = await check();
37
+ assert.equal(report.ok, true);
38
+ assert.deepEqual(await readFile(path.join(root, 'old.json')), oldBytes);
39
+ const review = (checkpoint, status) => ({ checkpointId: checkpoint.checkpoint_id,
40
+ milestoneId: checkpoint.milestone_id, taskId: checkpoint.task_id, sequence: checkpoint.sequence,
41
+ checkpointCreatedAt: checkpoint.created_at, revisesCheckpointId: checkpoint.revises_checkpoint_id, status });
42
+ const plan = { checkpoints: [{ id: 'unit' }] }, contract = { task_id: 'task' };
43
+ const before = [review(old, 'revise'), review(accepted, 'accepted')];
44
+ assert.equal(selectEffectiveAcceptanceReviews(plan, { reviews: before }, contract).length, 2);
45
+ assert.deepEqual(selectEffectiveAcceptanceReviews(plan, { reviews: [...before, review(repair, 'accepted')] }, contract)
46
+ .map(item => item.checkpointId), ['repair']);
47
+
48
+ for (const patch of [{ created_at: undefined }, { created_at: 'not-a-date' },
49
+ { created_at: '2024-06-01T11:00:00' }, { created_at: '2024-06-01T13:00:00Z' },
50
+ { task_id: undefined }, { checkpoint_id: undefined },
51
+ { sequence: undefined }, { sequence: -1 }, { sequence: 1.5 }, { sequence: 8 },
52
+ { sequence: Number.MAX_SAFE_INTEGER + 1 }]) {
53
+ await put('new.json', { ...repair, ...patch });
54
+ assert.equal((await check()).ok, false, JSON.stringify(patch));
55
+ }
56
+ // Progress/handoff records get the same check, not only ready-for-acceptance.
57
+ await put('new.json', { ...repair, status: 'in_progress', created_at: '2024-06-01T10:01:00Z' });
58
+ assert.equal((await check()).ok, false);
59
+ await put('new.json', repair);
60
+ await put('same-turn.json', { ...repair, checkpoint_id: 'later', sequence: 10, created_at: repair.created_at });
61
+ assert.equal((await check()).ok, false);
62
+ await put('same-turn.json', { ...repair, checkpoint_id: 'later', sequence: 10, created_at: '2024-06-01T11:01:00Z' });
63
+ assert.equal((await check()).ok, true);
64
+ assert(checkpointClockErrors({ ...repair, checkpoint_id: 'phase' }, [old]).some(error => error.includes('duplicate checkpoint_id')));
65
+ assert.deepEqual(checkpointClockErrors(repair, [{ ...old, task_id: 'other-task', sequence: 999 }], nowMs), []);
66
+ assert.deepEqual(checkpointClockErrors(repair, [{ ...old, sequence: undefined, created_at: undefined }], nowMs), []);
67
+ assert(checkpointClockErrors(repair, [{ ...old, sequence: undefined, created_at: '2024-06-01T11:30:00Z' }], nowMs).length);
68
+ assert.equal((await checkCheckpointClocks(root, 'absent', { nowMs })).checked, 0);
69
+ await assert.rejects(checkCheckpointClocks(root, ''), /run id/);
70
+ await put('bad.json', []);
71
+ assert.equal((await check()).ok, false);
72
+ await writeFile(path.join(root, 'bad.json'), '{');
73
+ assert.equal((await check()).ok, false);
74
+ await rm(path.join(root, 'bad.json'));
75
+
76
+ // A missing checkpoints directory has nothing to check, and that is not progress.
77
+ assert.deepEqual(await checkCheckpointClocks(path.join(root, 'not-created-yet'), 'current', { nowMs }), { ok: true, checked: 0, errors: [], needsHuman: [] });
78
+ const missingCli = spawnSync(process.execPath, [cli, path.join(root, 'not-created-yet'), 'current'], { encoding: 'utf8' });
79
+ assert.equal(missingCli.status, 0, missingCli.stderr);
80
+ assert.equal(JSON.parse(missingCli.stdout).checked, 0);
81
+
82
+ // A historical record dated in the future cannot be exceeded by a truthful
83
+ // clock: report it once as needing human repair instead of failing every
84
+ // new record, keep its bytes, and keep checking the current run's own clocks.
85
+ const skewed = { ...old, checkpoint_id: 'skewed', loop_run_id: 'skewed-host', sequence: 3, created_at: new Date(Date.now() + 86_400_000).toISOString() };
86
+ await put('skewed.json', skewed);
87
+ const skewedBytes = await readFile(path.join(root, 'skewed.json'));
88
+ report = await check();
89
+ assert.equal(report.ok, false);
90
+ assert.deepEqual(report.needsHuman.map(item => item.file), ['skewed.json']);
91
+ assert.deepEqual(report.errors, [], JSON.stringify(report.errors));
92
+ const skewedCli = spawnSync(process.execPath, [cli, root, 'current'], { encoding: 'utf8' });
93
+ assert.equal(skewedCli.status, 3, skewedCli.stdout);
94
+ await put('same-turn.json', { ...repair, checkpoint_id: 'later', sequence: 10, created_at: repair.created_at });
95
+ report = await check();
96
+ assert(report.errors.some(entry => entry.file === 'same-turn.json'), 'own-run clock errors are still reported next to needsHuman');
97
+ await put('same-turn.json', { ...repair, checkpoint_id: 'later', sequence: 10, created_at: '2024-06-01T11:01:00Z' });
98
+ assert.deepEqual(await readFile(path.join(root, 'skewed.json')), skewedBytes);
99
+ await rm(path.join(root, 'skewed.json'));
100
+ assert.equal((await check()).ok, true);
101
+
102
+ const instructions = checkpointClockInstructions({ LOOP_CHECKPOINTS_DIR: root, LOOP_RUN_ID: 'current' });
103
+ assert.match(instructions, /actual machine clock/);
104
+ assert.match(instructions, /passing is not business acceptance/);
105
+ assert.match(instructions, /needsHuman/);
106
+ const command = instructions.split('records: ')[1].split('. This validates')[0];
107
+ const green = spawnSync('/bin/sh', ['-c', command], { encoding: 'utf8' });
108
+ assert.equal(green.status, 0, green.stderr); // paths with spaces, apostrophes and $ stay literal
109
+ assert.equal(JSON.parse(green.stdout).checked, 2);
110
+ assert.equal(spawnSync(process.execPath, [cli], { env: {}, encoding: 'utf8' }).status, 2);
111
+ assert.match(contextWorkerInstructions({ LOOP_CHECKPOINTS_DIR: root, LOOP_RUN_ID: 'current' }), /checkpoint-preflight\.mjs/);
112
+ assert.match(dispatcherSource({ hermesBin: '/bin/true', language: 'en' }), /checkpointClockInstructions\(\)/);
113
+ console.log('Checkpoint clocks: contradictory revisions, truthful recovery, immutable history, progress, future/missing/duplicate clocks, CLI exit codes and worker wiring passed.');
114
+ } finally {
115
+ await rm(root, { recursive: true, force: true });
116
+ }
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { checkCheckpointClocks } from '../lib/checkpoint-clocks.mjs';
3
+ const [dir = process.env.LOOP_CHECKPOINTS_DIR, runId = process.env.LOOP_RUN_ID] = process.argv.slice(2);
4
+ if (!dir || !runId) {
5
+ console.error('Usage: node scripts/checkpoint-preflight.mjs <checkpoints-dir> <current-run-id>');
6
+ process.exitCode = 2;
7
+ } else {
8
+ try {
9
+ const result = await checkCheckpointClocks(dir, runId);
10
+ console.log(JSON.stringify(result, null, 2));
11
+ // 1: fix your own new records; 3: an earlier record needs human repair.
12
+ process.exitCode = result.needsHuman.length ? 3 : result.ok ? 0 : 1;
13
+ } catch (error) {
14
+ console.error(error.message);
15
+ process.exitCode = 2;
16
+ }
17
+ }
@@ -12,6 +12,7 @@ export function dispatcherSource({ hermesBin, language }) {
12
12
  return `#!/usr/bin/env node
13
13
  import { readFile } from 'node:fs/promises';
14
14
  import { spawn } from 'node:child_process';
15
+ import { checkpointClockInstructions } from ${JSON.stringify(new URL('../lib/checkpoint-clocks.mjs', import.meta.url).href)};
15
16
  const task = JSON.parse(await readFile(process.env.LOOP_TASK_FILE, 'utf8'));
16
17
  const prompt = [
17
18
  ${intro.map((line) => JSON.stringify(line)).join(',\n ')},
@@ -23,6 +24,7 @@ const prompt = [
23
24
  \`Checkpoints dir: \${process.env.LOOP_CHECKPOINTS_DIR || 'not provided'}\`,
24
25
  '', task.body, '',
25
26
  ...(Number(process.env.LOOP_TURN_TIMEOUT_MS) > 0 ? [${JSON.stringify(timeBudget)}.replace('MINUTES', String(Math.max(1, Math.floor(Number(process.env.LOOP_TURN_TIMEOUT_MS) / 60000)))).replace('BUDGET', String(Math.max(1, Math.floor(Number(process.env.LOOP_TURN_TIMEOUT_MS) * 0.8 / 60000))))] : []),
27
+ checkpointClockInstructions(),
26
28
  ${JSON.stringify(finish)}
27
29
  ].join('\\n');
28
30
  const child = spawn(${JSON.stringify(hermesBin)}, ['-z', prompt], { cwd: process.cwd(), env: process.env, stdio: 'inherit' });
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+ // Release check: install the package exactly as npm would ship it, and the
3
+ // previous published release from npm, then exercise fresh install, upgrade
4
+ // from the previous release, doctor, smoke and uninstall for OpenClaw and
5
+ // Hermes. The platform CLIs and systemctl are local mocks that record calls;
6
+ // generated systemd units are validated with systemd-analyze when available.
7
+ //
8
+ // Usage: node scripts/release-install-e2e.mjs [--candidate <package.tgz>] [--previous <version>|auto|none]
9
+ // Needs network access to the npm registry unless --previous none.
10
+ import { chmod, mkdir, mkdtemp, readFile, rm, writeFile, access } from 'node:fs/promises';
11
+ import { spawn } from 'node:child_process';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { tmpdir } from 'node:os';
14
+ import path from 'node:path';
15
+
16
+ const repo = fileURLToPath(new URL('..', import.meta.url));
17
+ const { name: packageName, version: candidateVersion } = JSON.parse(await readFile(path.join(repo, 'package.json'), 'utf8'));
18
+
19
+ function parseArgs(argv) {
20
+ const out = { candidate: null, previous: 'auto', keep: false };
21
+ for (let i = 0; i < argv.length; i++) {
22
+ const arg = argv[i];
23
+ if (arg === '--candidate') out.candidate = path.resolve(argv[++i]);
24
+ else if (arg === '--previous') out.previous = argv[++i];
25
+ else if (arg === '--keep') out.keep = true;
26
+ else if (arg === '--help' || arg === '-h') out.help = true;
27
+ else throw new Error(`Unknown argument: ${arg}`);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ const results = [];
33
+ const check = (name, ok, detail = '') => { results.push({ name, ok: Boolean(ok), detail: ok ? '' : String(detail).slice(0, 800) }); };
34
+ const exists = (f) => access(f).then(() => true, () => false);
35
+ function run(cmd, args, { env = process.env, cwd } = {}) {
36
+ return new Promise((resolve) => {
37
+ const child = spawn(cmd, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'] });
38
+ let stdout = ''; let stderr = '';
39
+ child.stdout.on('data', (c) => { stdout += c; }); child.stderr.on('data', (c) => { stderr += c; });
40
+ child.on('error', (e) => resolve({ code: 127, stdout, stderr: e.message }));
41
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
42
+ });
43
+ }
44
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
45
+ const json = (r) => { try { return JSON.parse(r.stdout); } catch { return {}; } };
46
+ const semverParts = (v) => v.split('.').map(Number);
47
+ const semverLess = (a, b) => { const [x, y] = [semverParts(a), semverParts(b)]; for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i]; return false; };
48
+
49
+ async function resolvePrevious(requested) {
50
+ if (requested === 'none') return null;
51
+ if (requested !== 'auto') return requested;
52
+ const r = await run(npm, ['view', packageName, 'versions', '--json']);
53
+ if (r.code !== 0) throw new Error(`Cannot list published versions of ${packageName}: ${r.stderr.trim()}`);
54
+ const versions = [].concat(JSON.parse(r.stdout)).filter((v) => /^\d+\.\d+\.\d+$/.test(v) && semverLess(v, candidateVersion));
55
+ return versions.sort((a, b) => (semverLess(a, b) ? -1 : 1)).at(-1) ?? null;
56
+ }
57
+
58
+ async function installPackage(spec, dir) {
59
+ await mkdir(dir, { recursive: true });
60
+ await writeFile(path.join(dir, 'package.json'), '{"private":true}\n');
61
+ const r = await run(npm, ['install', '--no-audit', '--no-fund', '--ignore-scripts', '--no-save', spec], { cwd: dir });
62
+ if (r.code !== 0) throw new Error(`npm install ${spec} failed: ${r.stderr.trim()}`);
63
+ return path.join(dir, 'node_modules', packageName);
64
+ }
65
+
66
+ const checkpointWriter = `if (process.env.LOOP_CHECKPOINTS_DIR) { const dir = path.resolve(process.cwd(), process.env.LOOP_CHECKPOINTS_DIR); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, 'cp1.json'), JSON.stringify({ version: 1, task_id: process.env.LOOP_TASK_ID, checkpoint_id: 'cp1', status: 'ready_for_acceptance', summary: 'Read-only smoke completed.', files_changed: [], verification: [{ command: 'mock smoke', outcome: 'passed' }], blockers: [], risks: [], next_action: 'acceptance_review' })); }`;
67
+ const mockSources = {
68
+ openclaw: `#!/usr/bin/env node
69
+ import { mkdir, writeFile } from 'node:fs/promises';
70
+ import path from 'node:path';
71
+ const args = process.argv.slice(2);
72
+ if (args[0] === '--version') console.log('OpenClaw mock 1.0');
73
+ else if (args[0] === 'channels' && args[1] === 'list') console.log(JSON.stringify({ chat: { feishu: ['main'] } }));
74
+ else if (args[0] === 'agents' && args[1] === 'list') console.log(JSON.stringify([{ id: 'builder' }]));
75
+ else { if (args[0] === 'agent') { ${checkpointWriter} } console.log(JSON.stringify({ ok: true, dryRun: args.includes('--dry-run') })); }
76
+ `,
77
+ hermes: `#!/usr/bin/env node
78
+ import { mkdir, writeFile } from 'node:fs/promises';
79
+ import path from 'node:path';
80
+ const args = process.argv.slice(2);
81
+ if (args[0] === '--version') console.log('Hermes Agent v0.20.0');
82
+ else if (args[0] === 'send' && args.includes('--help')) console.log('hermes send --to TARGET MESSAGE');
83
+ else if (args[0] === 'send') console.log('sent');
84
+ else if (args.includes('-z')) { ${checkpointWriter} console.log('SMOKE_OK'); }
85
+ else process.exitCode = 2;
86
+ `,
87
+ systemctl: `#!/usr/bin/env node
88
+ import { appendFile } from 'node:fs/promises';
89
+ if (process.env.SYSTEMCTL_CAPTURE) await appendFile(process.env.SYSTEMCTL_CAPTURE, JSON.stringify(process.argv.slice(2)) + '\\n');
90
+ `
91
+ };
92
+
93
+ let scratch;
94
+ async function workspace(label) {
95
+ // Spaces and non-ASCII characters exercise systemd path escaping.
96
+ const root = await mkdtemp(path.join(scratch, `${label} 安装-`));
97
+ const env = { ...process.env, XDG_CONFIG_HOME: path.join(root, 'xdg'), SYSTEMCTL_CAPTURE: path.join(root, 'systemctl.jsonl') };
98
+ await writeFile(path.join(root, 'AGENTS.md'), '# Workspace\n\nKeep this line.\n');
99
+ const mocks = {};
100
+ for (const [kind, source] of Object.entries(mockSources)) { mocks[kind] = path.join(root, `mock-${kind}.mjs`); await writeFile(mocks[kind], source); await chmod(mocks[kind], 0o755); }
101
+ return { root, env, mocks, calls: () => readFile(env.SYSTEMCTL_CAPTURE, 'utf8').catch(() => '') };
102
+ }
103
+ const node = (pkg, script, args, w) => run(process.execPath, [path.join(pkg, 'scripts', script), ...args], { env: w.env });
104
+ const agentsText = (w) => readFile(path.join(w.root, 'AGENTS.md'), 'utf8');
105
+
106
+ let haveSystemdAnalyze = false;
107
+ async function verifyUnits(label, w, prefix) {
108
+ if (!haveSystemdAnalyze) return;
109
+ const dir = path.join(w.env.XDG_CONFIG_HOME, 'systemd', 'user');
110
+ const r = await run('systemd-analyze', ['verify', `${dir}/${prefix}-scheduler.service`, `${dir}/${prefix}-scheduler.timer`, `${dir}/loop-engineering-dashboard.service`], { env: w.env });
111
+ // verify exits 0 for settings it cannot parse and ignores, so any
112
+ // diagnostic output counts as a failure.
113
+ const diagnostics = `${r.stderr}${r.stdout}`.trim();
114
+ check(`${label}: systemd-analyze verify scheduler and Dashboard units`, r.code === 0 && diagnostics === '', diagnostics || `exit ${r.code}`);
115
+ }
116
+
117
+ const platforms = {
118
+ openclaw: {
119
+ title: 'OpenClaw',
120
+ unitPrefix: 'openclaw-loop-e2e-tasks',
121
+ wrapper: 'scripts/loops/openclaw-loop.mjs',
122
+ marker: 'loop-engineering:openclaw:start',
123
+ manifest: 'runtime/loop-engineering-openclaw-install.json',
124
+ installer: 'openclaw-install.mjs',
125
+ installArgs: (w) => ['--root', w.root, '--queue', 'e2e-tasks', '--openclaw-bin', w.mocks.openclaw, '--systemctl-bin', w.mocks.systemctl, '--worker-agent', 'builder', '--language', 'en'],
126
+ doctor: (pkg, w) => node(pkg, 'openclaw-doctor.mjs', ['--root', w.root, '--queue', 'e2e-tasks', '--worker-agent', 'builder', '--openclaw-bin', w.mocks.openclaw, '--json'], w),
127
+ smoke: (pkg, w) => node(pkg, 'openclaw-smoke.mjs', ['--root', w.root, '--queue', 'e2e-tasks', '--worker-agent', 'builder', '--openclaw-bin', w.mocks.openclaw, '--loop-bin', path.join(pkg, 'bin/loop-engineering.mjs'), '--json'], w),
128
+ manage: (pkg, w, args) => node(pkg, 'openclaw-manage.mjs', ['--root', w.root, ...args, '--json'], w),
129
+ async upgrade(pkg, w, L) {
130
+ const plan = await this.manage(pkg, w, ['--action', 'upgrade-plan']);
131
+ check(`${L}: upgrade-plan is ready and read-only`, plan.code === 0 && json(plan).status === 'ready' && json(plan).readOnly === true, plan.stderr || plan.stdout);
132
+ return this.manage(pkg, w, ['--action', 'upgrade', '--confirm-upgrade']);
133
+ },
134
+ upgradedStatus: 'upgraded'
135
+ },
136
+ hermes: {
137
+ title: 'Hermes',
138
+ unitPrefix: 'hermes-loop-e2e-tasks',
139
+ wrapper: 'scripts/loops/hermes-loop.mjs',
140
+ marker: 'loop-engineering:hermes:start',
141
+ manifest: 'runtime/loop-engineering-hermes-install.json',
142
+ installer: 'hermes-install.mjs',
143
+ installArgs: (w) => ['--root', w.root, '--queue', 'e2e-tasks', '--hermes-bin', w.mocks.hermes, '--systemctl-bin', w.mocks.systemctl, '--language', 'en'],
144
+ doctor: (pkg, w) => node(pkg, 'hermes-doctor.mjs', ['--root', w.root, '--queue', 'e2e-tasks', '--hermes-bin', w.mocks.hermes, '--json'], w),
145
+ smoke: (pkg, w) => node(pkg, 'hermes-smoke.mjs', ['--root', w.root, '--queue', 'e2e-tasks', '--hermes-bin', w.mocks.hermes, '--loop-bin', path.join(pkg, 'bin/loop-engineering.mjs'), '--json'], w),
146
+ // Installs from releases that did not record systemctlBin fall back to
147
+ // `systemctl`, so the mock is passed explicitly.
148
+ manage: (pkg, w, args) => node(pkg, 'hermes-manage.mjs', ['--root', w.root, ...args, '--systemctl-bin', w.mocks.systemctl, '--json'], w),
149
+ // Hermes upgrades by rerunning the installer with --force.
150
+ upgrade(pkg, w) { return node(pkg, this.installer, [...this.installArgs(w), '--confirm-install', '--force', '--json'], w); },
151
+ upgradedStatus: 'installed'
152
+ }
153
+ };
154
+
155
+ async function checkInstalled(p, pkg, w, L) {
156
+ check(`${L}: scheduler timer enabled`, (await w.calls()).includes(`"enable","--now","${p.unitPrefix}-scheduler.timer"`), await w.calls());
157
+ check(`${L}: generated wrapper runs this package's CLI`, (await readFile(path.join(w.root, p.wrapper), 'utf8')).includes(path.join(pkg, 'bin')));
158
+ check(`${L}: exactly one managed AGENTS.md block`, (await agentsText(w)).split(p.marker).length === 2);
159
+ await verifyUnits(L, w, p.unitPrefix);
160
+ const doctor = await p.doctor(pkg, w);
161
+ check(`${L}: doctor ok without warnings`, doctor.code === 0 && json(doctor).status === 'ok' && (json(doctor).warnings ?? []).length === 0, doctor.stderr || doctor.stdout);
162
+ const smoke = await p.smoke(pkg, w);
163
+ check(`${L}: smoke ok`, smoke.code === 0 && json(smoke).status === 'ok', smoke.stderr || smoke.stdout);
164
+ }
165
+ async function checkUninstall(p, pkg, w, L) {
166
+ const plan = await p.manage(pkg, w, ['--action', 'uninstall-plan']);
167
+ check(`${L}: uninstall-plan ready`, plan.code === 0 && json(plan).status === 'ready', plan.stderr || plan.stdout);
168
+ const removed = await p.manage(pkg, w, ['--action', 'uninstall', '--confirm-uninstall']);
169
+ check(`${L}: uninstall`, removed.code === 0 && json(removed).status === 'uninstalled', removed.stderr || removed.stdout);
170
+ check(`${L}: uninstall removed wrapper, timer and manifest`, !await exists(path.join(w.root, p.wrapper)) && !await exists(path.join(w.env.XDG_CONFIG_HOME, 'systemd/user', `${p.unitPrefix}-scheduler.timer`)) && !await exists(path.join(w.root, p.manifest)));
171
+ check(`${L}: uninstall disabled the scheduler timer`, (await w.calls()).includes(`"disable","--now","${p.unitPrefix}-scheduler.timer"`));
172
+ const agents = await agentsText(w);
173
+ check(`${L}: uninstall kept the user's AGENTS.md content and removed the managed block`, agents.includes('Keep this line.') && !agents.includes(p.marker));
174
+ }
175
+
176
+ async function fresh(p, pkg) {
177
+ const L = `${p.title} fresh ${candidateVersion}`; const w = await workspace(`${p.title}-fresh`);
178
+ const plan = await node(pkg, p.installer, [...p.installArgs(w), '--json'], w);
179
+ check(`${L}: plan is plan_only`, plan.code === 0 && json(plan).status === 'plan_only', plan.stderr || plan.stdout);
180
+ check(`${L}: plan wrote nothing`, !await exists(path.join(w.root, 'scripts/loops')) && !await exists(path.join(w.root, p.manifest)) && !await w.calls());
181
+ const install = await node(pkg, p.installer, [...p.installArgs(w), '--confirm-install', '--json'], w);
182
+ check(`${L}: confirmed install`, install.code === 0 && json(install).status === 'installed', install.stderr || install.stdout);
183
+ await checkInstalled(p, pkg, w, L);
184
+ await checkUninstall(p, pkg, w, L);
185
+ }
186
+
187
+ async function upgrade(p, oldPkg, newPkg, previous) {
188
+ const L = `${p.title} upgrade ${previous}→${candidateVersion}`; const w = await workspace(`${p.title}-upgrade`);
189
+ const install = await node(oldPkg, p.installer, [...p.installArgs(w), '--confirm-install', '--json'], w);
190
+ check(`${L}: install with ${previous}`, install.code === 0 && json(install).status === 'installed', install.stderr || install.stdout);
191
+ check(`${L}: ${previous} wrapper runs the ${previous} CLI`, (await readFile(path.join(w.root, p.wrapper), 'utf8')).includes(path.join(oldPkg, 'bin')));
192
+ const before = JSON.parse(await readFile(path.join(w.root, p.manifest), 'utf8'));
193
+ const evidence = path.join(w.root, 'runtime/loops/e2e-tasks/evidence-keep.json');
194
+ await mkdir(path.dirname(evidence), { recursive: true }); await writeFile(evidence, '{"keep":true}\n');
195
+ const doctorBefore = await p.doctor(newPkg, w);
196
+ check(`${L}: ${candidateVersion} doctor accepts the ${previous} install`, doctorBefore.code === 0 && json(doctorBefore).status === 'ok', doctorBefore.stderr || doctorBefore.stdout);
197
+ const upgraded = await p.upgrade(newPkg, w, L);
198
+ check(`${L}: upgrade`, upgraded.code === 0 && json(upgraded).status === p.upgradedStatus, upgraded.stderr || upgraded.stdout);
199
+ const after = JSON.parse(await readFile(path.join(w.root, p.manifest), 'utf8'));
200
+ check(`${L}: manifest installed with the same queue and language`, after.status === 'installed' && after.queue === before.queue && after.language === before.language && (before.workerAgent === undefined || after.workerAgent === before.workerAgent), JSON.stringify({ before: [before.queue, before.language, before.workerAgent], after: [after.status, after.queue, after.language, after.workerAgent] }));
201
+ check(`${L}: queue runtime evidence kept`, await exists(evidence));
202
+ await checkInstalled(p, newPkg, w, L);
203
+ await checkUninstall(p, newPkg, w, L);
204
+ check(`${L}: queue runtime evidence kept after uninstall`, await exists(evidence));
205
+ }
206
+
207
+ async function main() {
208
+ const args = parseArgs(process.argv.slice(2));
209
+ if (args.help) { console.log('Usage: node scripts/release-install-e2e.mjs [--candidate <package.tgz>] [--previous <version>|auto|none] [--keep]'); return; }
210
+ scratch = await mkdtemp(path.join(tmpdir(), 'loop release check-'));
211
+ try {
212
+ haveSystemdAnalyze = (await run('systemd-analyze', ['--version'])).code === 0;
213
+ let candidate = args.candidate;
214
+ if (!candidate) {
215
+ const packed = await run(npm, ['pack', '--json', '--pack-destination', scratch], { cwd: repo });
216
+ if (packed.code !== 0) throw new Error(`npm pack failed: ${packed.stderr.trim()}`);
217
+ candidate = path.join(scratch, JSON.parse(packed.stdout)[0].filename);
218
+ }
219
+ const previous = await resolvePrevious(args.previous);
220
+ console.log(`candidate: ${path.basename(candidate)} (${candidateVersion})\nprevious: ${previous ?? 'none'}\nsystemd-analyze: ${haveSystemdAnalyze ? 'yes' : 'not available, unit verification skipped'}\n`);
221
+ const newPkg = await installPackage(candidate, path.join(scratch, 'candidate'));
222
+ const installedVersion = JSON.parse(await readFile(path.join(newPkg, 'package.json'), 'utf8')).version;
223
+ check('candidate package version matches package.json', installedVersion === candidateVersion, `${installedVersion} != ${candidateVersion}`);
224
+ const oldPkg = previous ? await installPackage(`${packageName}@${previous}`, path.join(scratch, 'previous')) : null;
225
+ for (const p of Object.values(platforms)) {
226
+ for (const step of [() => fresh(p, newPkg), ...(oldPkg ? [() => upgrade(p, oldPkg, newPkg, previous)] : [])]) {
227
+ try { await step(); } catch (error) { check(`${p.title}: crashed`, false, error.stack); }
228
+ }
229
+ }
230
+ } finally {
231
+ if (!args.keep) await rm(scratch, { recursive: true, force: true });
232
+ }
233
+ for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name}${r.detail ? `\n ${r.detail.replace(/\n/g, '\n ')}` : ''}`);
234
+ const failed = results.filter((r) => !r.ok).length;
235
+ console.log(`\n${results.length - failed}/${results.length} release install checks passed`);
236
+ if (failed || results.length === 0) process.exitCode = 1;
237
+ }
238
+ main().catch((error) => { console.error(error instanceof Error ? error.stack : String(error)); process.exitCode = 1; });
@@ -26,26 +26,26 @@ Official distribution:
26
26
  - license: Apache-2.0
27
27
  - runtime requirement: Node.js 22 or newer
28
28
 
29
- Every install command below pins the exact package version this skill was released with, `0.16.8`, which is built from the `v0.16.8` tag of the official repository (`https://github.com/ambitioncn/taskforce-loop-engineering/tree/v0.16.8`). Review that source before installing. Do not drop the version, and do not switch to `@latest` or an unpinned `npx`, which download and run whatever version is newest when the command runs. To use a newer version, install the version a newer release of this skill pins, after reviewing its source.
29
+ Every install command below pins the exact package version this skill was released with, `0.16.9`, which is built from the `v0.16.9` tag of the official repository (`https://github.com/ambitioncn/taskforce-loop-engineering/tree/v0.16.9`). Review that source before installing. Do not drop the version, and do not switch to `@latest` or an unpinned `npx`, which download and run whatever version is newest when the command runs. To use a newer version, install the version a newer release of this skill pins, after reviewing its source.
30
30
 
31
31
  Install the CLI globally from npm:
32
32
 
33
33
  ```bash
34
34
  node --version
35
- npm install -g taskforce-loop-engineering@0.16.8
35
+ npm install -g taskforce-loop-engineering@0.16.9
36
36
  loop-engineering --help
37
37
  ```
38
38
 
39
39
  For a temporary read-only invocation without a global install:
40
40
 
41
41
  ```bash
42
- npx -p taskforce-loop-engineering@0.16.8 loop-engineering --help
42
+ npx -p taskforce-loop-engineering@0.16.9 loop-engineering --help
43
43
  ```
44
44
 
45
45
  For source-based development, clone the official repository and install its dependencies:
46
46
 
47
47
  ```bash
48
- git clone --branch v0.16.8 --depth 1 https://github.com/ambitioncn/taskforce-loop-engineering.git
48
+ git clone --branch v0.16.9 --depth 1 https://github.com/ambitioncn/taskforce-loop-engineering.git
49
49
  cd taskforce-loop-engineering
50
50
  npm install
51
51
  npm run check
@@ -5,7 +5,37 @@
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, keep working through the milestone with frequent checkpoints and hand off only when the remaining work clearly will not fit the turn; never invent a percentage. The runner passes the dispatch timeout as `LOOP_TURN_TIMEOUT_MS`; by about 80% of it, stop starting new sub-steps, checkpoint and hand off, because a killed turn loses unsaved work and consumes a runtime recovery attempt while a validated handoff does not. 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. 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.
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. For new checkpoints, record `created_at` from the actual machine clock (UTC) and a task-monotonic safe-integer `sequence` above the known historical maximum; 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.
12
+
13
+ ### Checkpoint clock preflight
14
+
15
+ Write `created_at` from the actual machine clock when creating a checkpoint and
16
+ choose a task-monotonic safe-integer `sequence` above the historical maximum.
17
+ A higher sequence with an earlier timestamp is ambiguous: acceptance intentionally
18
+ keeps unresolved reviews effective rather than guessing which clock is right.
19
+ The worker prompt includes a package-owned command:
20
+
21
+ ```bash
22
+ node /path/to/taskforce-loop-engineering/scripts/checkpoint-preflight.mjs "$LOOP_CHECKPOINTS_DIR" "$LOOP_RUN_ID"
23
+ ```
24
+
25
+ This read-only submission check rejects future/missing clocks, repeated sequences
26
+ and contradictory ordering in the current run (including unfinished handoffs).
27
+ It never rewrites old checkpoints or changes review status. A new truthful
28
+ same-milestone revision can close older conflicting snapshots after verification;
29
+ never invent or normalize historical timestamps. Passing this preflight is not
30
+ business acceptance; `checked=0` is not evidence of progress. Custom adapters can
31
+ call `checkCheckpointClocks` from `lib/checkpoint-clocks.mjs`.
32
+
33
+ Exit codes: `0` clocks are consistent (a missing checkpoints directory reports
34
+ `checked: 0`), `1` fix the current run's own new records, `2` usage or read
35
+ error, `3` `needsHuman`: an earlier run's record is dated in the future, for
36
+ example from clock skew on another host. No truthful new clock can come after
37
+ it, so the check skips ordering against it instead of failing every new record.
38
+ Do not retry or edit that record; stop and report it as a blocker needing human
39
+ repair. Legacy acceptance
40
+ semantics and existing human/authority gates are unchanged. Hermes users must
41
+ regenerate their installed dispatcher to receive the new instruction.
@@ -13,7 +13,7 @@ for capability checks, channel/account selection, and acceptance boundaries.
13
13
  Install from npm:
14
14
 
15
15
  ```bash
16
- npm install -g taskforce-loop-engineering@0.16.8
16
+ npm install -g taskforce-loop-engineering@0.16.9
17
17
  ```
18
18
 
19
19
  Hermes Agent integration commands: