taskforce-loop-engineering 0.15.21 → 0.16.1

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/MIGRATING.md +80 -0
  3. package/README.md +37 -8
  4. package/bin/loop-engineering.mjs +142 -114
  5. package/docs/architecture.md +3 -2
  6. package/docs/human-gate-command.md +1 -1
  7. package/docs/operator-dashboard.md +16 -5
  8. package/docs/operator-workspace-project.md +2 -2
  9. package/docs/production-trust-contract.md +9 -2
  10. package/docs/transactional-kernel-and-goal-api.md +3 -1
  11. package/lib/action-reservations.mjs +21 -23
  12. package/lib/context-budget.mjs +147 -0
  13. package/lib/core.mjs +746 -241
  14. package/lib/dispatch-classification.mjs +114 -0
  15. package/lib/durable-journal.mjs +23 -6
  16. package/lib/execution-ledger.mjs +4 -4
  17. package/lib/file-mutex.mjs +102 -0
  18. package/lib/human-gate-channel-adapter.mjs +4 -2
  19. package/lib/human-gate-command.mjs +5 -3
  20. package/lib/operator-dashboard.mjs +72 -10
  21. package/lib/production-evidence.mjs +37 -15
  22. package/lib/quota-runtime-decision.mjs +11 -6
  23. package/lib/redaction.mjs +34 -0
  24. package/lib/todo-control-plane.mjs +12 -16
  25. package/lib/transactional-state-kernel.mjs +96 -18
  26. package/package.json +2 -3
  27. package/scripts/context-budget-self-test.mjs +249 -0
  28. package/scripts/dashboard-autostart-install.mjs +33 -8
  29. package/scripts/dashboard-autostart-self-test.mjs +12 -3
  30. package/scripts/final-judgement-self-test.mjs +113 -4
  31. package/scripts/hermes-install-self-test.mjs +8 -1
  32. package/scripts/hermes-install.mjs +29 -8
  33. package/scripts/hermes-smoke.mjs +2 -1
  34. package/scripts/human-gate-command-self-test.mjs +34 -5
  35. package/scripts/install-shared.mjs +61 -0
  36. package/scripts/openclaw-install-self-test.mjs +158 -2
  37. package/scripts/openclaw-install.mjs +105 -30
  38. package/scripts/openclaw-manage.mjs +22 -3
  39. package/scripts/openclaw-smoke.mjs +2 -1
  40. package/scripts/project-relay-self-test.mjs +145 -1
  41. package/scripts/run-loop-cron.sh +22 -7
  42. package/scripts/safety-regression-self-test.mjs +350 -0
  43. package/skills/taskforce-loop-engineering/SKILL.md +7 -1
  44. package/skills/taskforce-loop-engineering/references/context-budget.md +11 -0
@@ -2,7 +2,8 @@ import assert from 'node:assert/strict';
2
2
  import { mkdtemp, mkdir, readFile, rm, writeFile, unlink } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { ensureQueueDirs, projectRelayNext, projectRelayReconcile, queueSchedulerTick, queueStatus } from '../lib/core.mjs';
5
+ import { readdir } from 'node:fs/promises';
6
+ import { ensureQueueDirs, projectRelayNext, projectRelayReconcile, projectRelayResume, queueSchedulerTick, queueStatus } from '../lib/core.mjs';
6
7
 
7
8
  const root = await mkdtemp(path.join(os.tmpdir(), 'loop-project-relay-'));
8
9
  const queue = 'relay-test';
@@ -105,4 +106,147 @@ await rm(path.join(root, result.file));
105
106
  const tick = await queueSchedulerTick(root, { queue });
106
107
  assert.deepEqual(tick.relayReconciliation, [{ project, changed: 1 }], 'idle scheduler repairs interrupted status writes');
107
108
  assert.equal((await readFile(backlogFile, 'utf8')).includes('"status": "completed"'), true);
109
+ // A relay item that needed a revision round is still reconcilable through
110
+ // its lineage: the revision body has no leading marker, but its revisionOf
111
+ // chain ends at the bound relay task.
112
+ const revisedItem = { ...item, id: 'local-2' };
113
+ const doneDir = path.join(root, 'runtime/loops', queue, 'done');
114
+ const judgementFor = (id) => path.join(root, 'runtime/loops', queue, 'tasks', id, 'final_judgement.json');
115
+ const relayRootTask = { ...queued, id: 'relay-root', backlogItemId: revisedItem.id, status: 'completed',
116
+ body: `[project-relay:${project}/${revisedItem.id}]\nVerify the local entry` };
117
+ const revisionTask = { ...relayRootTask, id: 'relay-revision', revisionOf: relayRootTask.id, revisionRound: 1,
118
+ body: `Revision round for a loop-managed task.\n\nOriginal task body:\n${relayRootTask.body}` };
119
+ await writeJson(backlogFile, { items: [revisedItem] });
120
+ await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), relayRootTask);
121
+ await writeJson(judgementFor(relayRootTask.id), { outcome: 'needs_revision', requires_human_gate: false });
122
+ await writeJson(path.join(doneDir, `${revisionTask.id}.json`), revisionTask);
123
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a lineage without an accepted round is not evidence');
124
+ await writeJson(judgementFor(revisionTask.id), { outcome: 'ready_to_apply', requires_human_gate: true });
125
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a gated revision is not evidence');
126
+ await writeJson(path.join(doneDir, `${revisionTask.id}.json`), { ...revisionTask, revisionOf: 'unknown-task' });
127
+ await writeJson(judgementFor(revisionTask.id), { outcome: 'ready_to_apply', requires_human_gate: false });
128
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a revision without a relay root is not evidence');
129
+ await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), { ...relayRootTask, backlogItemId: 'other-item' });
130
+ await writeJson(path.join(doneDir, `${revisionTask.id}.json`), revisionTask);
131
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a lineage with a different binding is not evidence');
132
+ await writeJson(path.join(doneDir, `${relayRootTask.id}.json`), relayRootTask);
133
+ await writeJson(path.join(doneDir, 'second-root.json'), { ...relayRootTask, id: 'second-root' });
134
+ await writeJson(judgementFor('second-root'), { outcome: 'needs_revision', requires_human_gate: false });
135
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'two independent relay lineages fail closed');
136
+ await unlink(path.join(doneDir, 'second-root.json'));
137
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 1, 'an accepted revision round completes its relay item');
138
+ assert.equal(JSON.parse(await readFile(backlogFile, 'utf8')).items[0].status, 'completed');
139
+ // Reconciliation must not overwrite a backlog edited after it was read.
140
+ await writeJson(backlogFile, { items: [revisedItem] });
141
+ const concurrentEdit = { items: [{ ...revisedItem, note: 'edited by an agent' }] };
142
+ const raced = await projectRelayReconcile(root, { queue, project, beforeWrite: () => writeJson(backlogFile, concurrentEdit) });
143
+ assert.deepEqual(raced, { changed: 0, conflict: true }, 'a concurrent backlog edit aborts reconciliation');
144
+ assert.deepEqual(JSON.parse(await readFile(backlogFile, 'utf8')), concurrentEdit, 'the concurrent edit survives');
145
+ assert.deepEqual((await readdir(path.dirname(backlogFile))).filter((name) => name.endsWith('.tmp')), [], 'no temporary backlog is left behind');
146
+
147
+ // Fresh workspace for relay retry, duplicate ids, and scheduler locking.
148
+ {
149
+ const root = await mkdtemp(path.join(os.tmpdir(), 'loop-project-relay-resume-'));
150
+ const queueDir = path.join(root, 'runtime/loops', queue);
151
+ const backlogFile = path.join(root, 'project/backlog.json');
152
+ await ensureQueueDirs(root, queue);
153
+ await writeJson(path.join(root, 'configs/loops/projects', `${project}.json`), spec);
154
+ await writeJson(path.join(root, 'project/ledger.json'), { status: 'in_progress' });
155
+ const next = { ...item, id: 'local-2' };
156
+
157
+ // Duplicate or malformed rows can neither prove a predecessor nor be relayed.
158
+ await writeJson(backlogFile, { items: [null, predecessor, { ...predecessor, status: 'ready' }, next] });
159
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'duplicate predecessor ids fail closed');
160
+ await writeJson(backlogFile, { items: [null, predecessor, next, { ...next, title: 'Shadow' }] });
161
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'duplicate candidate ids are not relayed');
162
+ await writeJson(backlogFile, { items: [predecessor, next, { ...next, title: 'Shadow' }, { ...item, id: 'local-3', dependsOn: ['local-2'] }] });
163
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'a duplicated dependency is never complete');
164
+
165
+ // The accepted predecessor finished while the queue was busy, so the
166
+ // completion-time relay was skipped. An idle scheduler tick resumes it.
167
+ await writeJson(backlogFile, { items: [predecessor, next] });
168
+ const accepted = { ...task, title: 'Accepted', body: 'Accepted work', status: 'completed', finishedAt: '2026-10-01T00:00:00.000Z' };
169
+ await writeJson(path.join(queueDir, 'done', `${accepted.id}.json`), accepted);
170
+ await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), finalJudgement);
171
+ const older = { ...accepted, id: 'older-task', backlogItemId: 'local-0', finishedAt: '2026-09-01T00:00:00.000Z' };
172
+ await writeJson(path.join(queueDir, 'done', `${older.id}.json`), older);
173
+ await writeJson(path.join(queueDir, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
174
+
175
+ await writeJson(path.join(queueDir, 'inbox', 'busy.json'), { id: 'busy', title: 'Busy', body: 'User work', status: 'queued' });
176
+ assert.equal(await projectRelayResume(root, { queue, project }), null, 'a busy queue still defers the relay');
177
+ await unlink(path.join(queueDir, 'inbox', 'busy.json'));
178
+
179
+ const lockFile = path.join(queueDir, 'queue.lock');
180
+ await writeFile(lockFile, JSON.stringify({ version: 1, queue, pid: process.pid,
181
+ acquiredAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 60000).toISOString() }));
182
+ const locked = await queueSchedulerTick(root, { queue });
183
+ assert.equal(locked.relayMaintenance, 'queue_locked');
184
+ assert.deepEqual(locked.projectRelay, [], 'a tick without the queue lock cannot relay');
185
+ assert.equal((await queueStatus(root, queue)).queued, 0);
186
+ await unlink(lockFile);
187
+
188
+ await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), { outcome: 'needs_revision', requires_human_gate: false });
189
+ const rejected = await queueSchedulerTick(root, { queue });
190
+ assert.equal(rejected.relayMaintenance, 'completed');
191
+ assert.deepEqual(rejected.projectRelay, [], 'the newest bound task must be accepted');
192
+ assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'unchanged', 'an unchanged queue skips the full relay scan');
193
+
194
+ // An in-place judgement edit is invisible to the cheap fingerprint: it is
195
+ // picked up by the periodic full pass, never acted on from stale state.
196
+ await writeJson(path.join(queueDir, 'tasks', accepted.id, 'final_judgement.json'), finalJudgement);
197
+ const skipped = await queueSchedulerTick(root, { queue });
198
+ assert.equal(skipped.relayMaintenance, 'unchanged');
199
+ assert.deepEqual(skipped.projectRelay, []);
200
+ const maintenanceFile = path.join(queueDir, 'scheduler/relay-maintenance.json');
201
+ const lastPass = JSON.parse(await readFile(maintenanceFile, 'utf8'));
202
+ await writeJson(maintenanceFile, { ...lastPass, fullPassAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() });
203
+ const resumed = await queueSchedulerTick(root, { queue });
204
+ assert.equal(resumed.relayMaintenance, 'completed', 'the periodic full pass runs despite an unchanged fingerprint');
205
+ assert.equal(resumed.projectRelay.length, 1);
206
+ assert.equal(resumed.projectRelay[0].itemId, 'local-2');
207
+ const relayed = JSON.parse(await readFile(path.join(root, resumed.projectRelay[0].file), 'utf8'));
208
+ assert.equal(relayed.backlogItemId, 'local-2');
209
+ assert.equal(relayed.source.message_id, 'message-1');
210
+ const afterRelay = await queueSchedulerTick(root, { queue });
211
+ assert.equal(afterRelay.relayMaintenance, 'completed', 'a queue change during a pass triggers another full pass');
212
+ assert.deepEqual(afterRelay.projectRelay, [], 'a resumed relay is not enqueued twice');
213
+ assert.equal((await queueStatus(root, queue)).queued, 1);
214
+ assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'unchanged');
215
+ await writeFile(backlogFile, `${await readFile(backlogFile, 'utf8')}\n`);
216
+ assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'completed', 'a backlog edit invalidates the fingerprint');
217
+ assert.equal((await queueSchedulerTick(root, { queue, relayMaintenanceFullIntervalMs: 0 })).relayMaintenance, 'completed',
218
+ 'a zero interval always runs the full pass');
219
+ // An unreadable task file fails the pass without throwing from the tick,
220
+ // and the pass is not recorded, so it is retried on the next tick.
221
+ await writeFile(path.join(queueDir, 'done', 'corrupt.json'), '{');
222
+ const broken = await queueSchedulerTick(root, { queue });
223
+ assert.equal(broken.relayMaintenance, 'error');
224
+ assert.equal(typeof broken.projectRelay[0].error, 'string');
225
+ assert.equal((await queueSchedulerTick(root, { queue })).relayMaintenance, 'error', 'a failed pass is retried');
226
+ await unlink(path.join(queueDir, 'done', 'corrupt.json'));
227
+ await rm(root, { recursive: true, force: true });
228
+ }
229
+ // A failed or canceled relay task stops the chain: an idle tick must not skip
230
+ // it and relay the next independent item. Ambiguous ordering fails closed.
231
+ for (const stop of ['canceled', 'failed', 'tied']) {
232
+ const root = await mkdtemp(path.join(os.tmpdir(), `loop-project-relay-stop-${stop}-`));
233
+ const queueDir = path.join(root, 'runtime/loops', queue);
234
+ await ensureQueueDirs(root, queue);
235
+ await writeJson(path.join(root, 'configs/loops/projects', `${project}.json`), spec);
236
+ await writeJson(path.join(root, 'project/ledger.json'), { status: 'in_progress' });
237
+ await writeJson(path.join(root, 'project/backlog.json'), { items: [predecessor, { ...item, id: 'local-1' }, { ...item, id: 'local-2' }] });
238
+ await writeJson(path.join(queueDir, 'done', `${task.id}.json`), { ...task, status: 'completed', body: 'Accepted work',
239
+ enqueuedAt: '2026-10-01T00:00:00.000Z', finishedAt: '2026-10-01T01:00:00.000Z' });
240
+ await writeJson(path.join(queueDir, 'tasks', task.id, 'final_judgement.json'), finalJudgement);
241
+ const stopped = { ...task, id: 'relay-local-1', backlogItemId: 'local-1', body: `[project-relay:${project}/local-1]\nVerify`,
242
+ status: stop === 'tied' ? 'completed' : stop,
243
+ enqueuedAt: stop === 'tied' ? '2026-10-01T00:00:00.000Z' : '2026-10-01T01:00:01.000Z' };
244
+ await writeJson(path.join(queueDir, stop === 'tied' ? 'done' : stop, `${stopped.id}.json`), stopped);
245
+ await writeJson(path.join(queueDir, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
246
+ const tick = await queueSchedulerTick(root, { queue });
247
+ assert.equal(tick.relayMaintenance, 'completed');
248
+ assert.deepEqual(tick.projectRelay, [], `a ${stop} relay task stops the relay chain`);
249
+ assert.equal((await queueStatus(root, queue)).queued, 0);
250
+ await rm(root, { recursive: true, force: true });
251
+ }
108
252
  console.log('project relay self-test passed');
@@ -14,7 +14,20 @@ fi
14
14
  mkdir -p "$LOG_DIR"
15
15
  cd "$WORKDIR"
16
16
 
17
- loop_id="$(node -e '
17
+ # LOOP_ALERT_COMMAND may include arguments ("openclaw message send --target x");
18
+ # the message is passed as one extra argument, never interpolated.
19
+ alert() {
20
+ local message="$1" log="$2"
21
+ if [[ -n "$SEND_CMD" ]]; then
22
+ if ! sh -c "$SEND_CMD \"\$1\"" loop-alert "$message"; then
23
+ printf '[%s] alert command failed: %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$SEND_CMD" >> "$log"
24
+ fi
25
+ else
26
+ printf '%s\n' "$message" >&2
27
+ fi
28
+ }
29
+
30
+ if ! loop_id="$(node -e '
18
31
  const fs = require("fs");
19
32
  const config = process.argv[1];
20
33
  try {
@@ -24,7 +37,13 @@ try {
24
37
  } catch {
25
38
  process.exit(2);
26
39
  }
27
- ' "$CONFIG")"
40
+ ' "$CONFIG")"; then
41
+ stamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
42
+ log_file="$LOG_DIR/loop-cron-invalid-config.log"
43
+ printf '[%s] %s: unreadable config or invalid id\n' "$stamp" "$CONFIG" >> "$log_file"
44
+ alert "Loop escalation ($stamp): $CONFIG is unreadable or has an invalid id; the loop did not run." "$log_file"
45
+ exit 2
46
+ fi
28
47
 
29
48
  stamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
30
49
  log_file="$LOG_DIR/loop-cron-${loop_id}.log"
@@ -74,11 +93,7 @@ process.stdout.write(latest || "runner failed before writing a run artifact");
74
93
  ' "$loop_id")"
75
94
 
76
95
  message="Loop escalation ($stamp): $loop_id exit=$exit_code. $summary"
77
- if [[ -n "$SEND_CMD" ]]; then
78
- "$SEND_CMD" "$message" || true
79
- else
80
- printf '%s\n' "$message" >&2
81
- fi
96
+ alert "$message" "$log_file"
82
97
 
83
98
  rm -f "$tmp_out"
84
99
  exit "$exit_code"
@@ -0,0 +1,350 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync, spawnSync } from 'node:child_process';
3
+ import { mkdtemp, mkdir, readFile, readdir, rm, utimes, writeFile } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { appendFile, utimes as touch } from 'node:fs/promises';
6
+ import { claimAction, reserveAction, settleAction } from '../lib/action-reservations.mjs';
7
+ import { DurableJournal } from '../lib/durable-journal.mjs';
8
+ import { handleChannelGateEvent, normalizeFeishuGateEvent } from '../lib/human-gate-channel-adapter.mjs';
9
+ import { createHumanGate, getHumanGate } from '../lib/human-gate-command.mjs';
10
+ import { evaluateEvidence, publicEvidenceSummary, sealEvidence, verifyEvidence } from '../lib/production-evidence.mjs';
11
+ import { readQuotaLedger, recordVerifiedSliceSpend } from '../lib/quota-runtime-decision.mjs';
12
+ import { sensitiveKey } from '../lib/redaction.mjs';
13
+ import { claimTodo, createTodo, decideHandoff, handoffTodo, recoverTodos, registerAgent, releaseTodo } from '../lib/todo-control-plane.mjs';
14
+ import { TransactionalStateKernel } from '../lib/transactional-state-kernel.mjs';
15
+ import { enqueueTask, ensureQueueDirs, queueCancel, queueRequeue, runCommand, runQueueOnce, queueStatus } from '../lib/core.mjs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const cli = fileURLToPath(new URL('../bin/loop-engineering.mjs', import.meta.url));
21
+ const loop = (root, ...args) => spawnSync(process.execPath, [cli, ...args, '--root', root], { cwd: root, encoding: 'utf8' });
22
+ const loopJson = (root, ...args) => {
23
+ const result = loop(root, ...args, '--json');
24
+ assert.equal(result.status, 0, `${args[0]} failed: ${result.stderr || result.stdout}`);
25
+ return JSON.parse(result.stdout);
26
+ };
27
+ const writeJson = async (file, value) => {
28
+ await mkdir(path.dirname(file), { recursive: true });
29
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
30
+ };
31
+ const roots = [];
32
+ const tempRoot = async (name) => {
33
+ const root = await mkdtemp(path.join(os.tmpdir(), `loop-safety-${name}-`));
34
+ roots.push(root);
35
+ return root;
36
+ };
37
+
38
+ try {
39
+ // --task-id must never resolve outside the queue directories.
40
+ {
41
+ const parent = await tempRoot('traversal');
42
+ const root = path.join(parent, 'ws');
43
+ await writeJson(path.join(parent, 'outside', 'secret.json'), { keep: true });
44
+ await mkdir(root, { recursive: true });
45
+ for (const command of ['queue-cancel', 'queue-requeue']) {
46
+ const result = loop(root, command, '--queue', 'q', '--task-id', '../../../../../outside/secret');
47
+ assert.notEqual(result.status, 0, `${command} rejects a traversing task id`);
48
+ assert.match(result.stderr, /Invalid task id/);
49
+ }
50
+ assert.deepEqual(JSON.parse(await readFile(path.join(parent, 'outside', 'secret.json'), 'utf8')), { keep: true });
51
+ }
52
+
53
+ // A human gate for a task outside any project survives read-only status.
54
+ {
55
+ const root = await tempRoot('gate');
56
+ loop(root, 'queue-init', '--queue', 'q');
57
+ const queueDir = path.join(root, 'runtime/loops/q');
58
+ await writeJson(path.join(queueDir, 'failed', 't1.json'), { version: 1, id: 't1', queue: 'q', title: 'Deploy fix', body: 'needs approval',
59
+ status: 'needs_human_input', source: { channel: 'slack', target: 'C1', account: 'acct' } });
60
+ await writeJson(path.join(queueDir, 'tasks', 't1', 'checkpoints', 'cp1.json'),
61
+ { checkpoint_id: 'cp1', sequence: 1, status: 'needs_human_input', blockers: ['Need the production API key'] });
62
+ const notified = loop(root, 'queue-human-input-notify', '--queue', 'q', '--notify-command', 'true', '--json');
63
+ assert.equal(notified.status, 0, notified.stderr);
64
+ assert.deepEqual(await readdir(path.join(queueDir, 'waiting')), ['t1.json']);
65
+ for (const args of [['queue-status', '--queue', 'q'], ['queue-status', '--queue', 'q', '--json']]) {
66
+ assert.equal(loop(root, ...args).status, 0);
67
+ assert.deepEqual(await readdir(path.join(queueDir, 'waiting')), ['t1.json'], 'a non-project gate is not superseded by status');
68
+ assert.deepEqual(await readdir(path.join(queueDir, 'canceled')), []);
69
+ }
70
+ }
71
+
72
+ // A code-queue export is complete, and a dirty worktree is force-removed
73
+ // only while it still matches that export.
74
+ {
75
+ const root = await tempRoot('export');
76
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' });
77
+ git('init', '-q'); git('config', 'user.email', 'loop@example.invalid'); git('config', 'user.name', 'loop');
78
+ for (const index of [1, 2, 3]) await writeFile(path.join(root, `big${index}.txt`), `${Array.from({ length: 20000 }, (_, i) => i).join('\n')}\n`);
79
+ await writeFile(path.join(root, 'small.txt'), 'hi\n');
80
+ await writeFile(path.join(root, '.gitignore'), 'runtime/\nconfigs/\n');
81
+ git('add', '-A'); git('commit', '-qm', 'init');
82
+ loop(root, 'code-queue-init', '--queue', 'cq');
83
+ const configFile = path.join(root, 'configs/loops/queues/cq.json');
84
+ const config = JSON.parse(await readFile(configFile, 'utf8'));
85
+ config.worktree.verifyCommands = [];
86
+ delete config.preflightConfig;
87
+ await writeJson(configFile, config);
88
+ loop(root, 'enqueue', '--queue', 'cq', '--title', 'Change', '--task', 'do it');
89
+ loop(root, 'run-queue', '--queue', 'cq', '--config', 'configs/loops/queues/cq.json',
90
+ '--dispatcher', 'sed -i s/^/X/ big1.txt big2.txt big3.txt; echo changed >> small.txt; echo 新文件 > NEW_FILE.txt');
91
+ const queueDir = path.join(root, 'runtime/loops/cq');
92
+ const taskId = [...await readdir(path.join(queueDir, 'done')), ...await readdir(path.join(queueDir, 'failed'))][0].replace(/\.json$/, '');
93
+
94
+ const exported = loopJson(root, 'code-worktree-export', '--queue', 'cq', '--task-id', taskId);
95
+ assert.equal(exported.complete, true);
96
+ assert.equal(exported.untrackedIncluded, 1);
97
+ const patch = await readFile(path.join(root, exported.patchFile), 'utf8');
98
+ assert.equal((patch.match(/^diff --git /gm) ?? []).length, 5, 'every tracked edit and the new file are exported');
99
+ assert.equal(loopJson(root, 'code-patch-verify', '--patch', exported.patchFile).status, 'applies');
100
+
101
+ loopJson(root, 'code-review-bundle', '--queue', 'cq', '--task-id', taskId);
102
+ const worktreeDir = path.join(root, exported.worktree.path);
103
+ await writeFile(path.join(worktreeDir, 'LATE_EDIT.txt'), 'written after export\n');
104
+ let cleanup = loopJson(root, 'code-worktree-cleanup', '--queue', 'cq', '--confirm-cleanup');
105
+ assert.equal(JSON.stringify(cleanup).includes('dirty_worktree_changed_since_export'), true, 'edits after export block cleanup');
106
+ assert.equal((await readdir(worktreeDir)).includes('LATE_EDIT.txt'), true);
107
+
108
+ await rm(path.join(worktreeDir, 'LATE_EDIT.txt'));
109
+ const manifestFile = path.join(root, `${exported.patchFile}.json`);
110
+ const manifest = JSON.parse(await readFile(manifestFile, 'utf8'));
111
+ await writeJson(manifestFile, { ...manifest, complete: undefined, contentSha256: undefined });
112
+ cleanup = loopJson(root, 'code-worktree-cleanup', '--queue', 'cq', '--confirm-cleanup');
113
+ assert.equal(JSON.stringify(cleanup).includes('dirty_export_incomplete_reexport_required'), true, 'a legacy export blocks cleanup');
114
+
115
+ await writeJson(manifestFile, manifest);
116
+ cleanup = loopJson(root, 'code-worktree-cleanup', '--queue', 'cq', '--confirm-cleanup');
117
+ assert.equal(cleanup.removedWorktrees.length, 1, 'an unchanged, completely exported worktree is removed');
118
+ const applied = loopJson(root, 'code-patch-apply', '--patch', exported.patchFile, '--confirm-apply');
119
+ assert.equal(applied.applied, true);
120
+ assert.equal(await readFile(path.join(root, 'NEW_FILE.txt'), 'utf8'), '新文件\n', 'the exported new file round-trips');
121
+ assert.equal((await readFile(path.join(root, 'big3.txt'), 'utf8')).startsWith('X0\n'), true, 'edits before the truncation window survive');
122
+ assert.equal((await readFile(path.join(root, 'NEW_FILE.txt'), 'utf8')), '新文件\n', 'the exported new file round-trips');
123
+ }
124
+ // Queue engine crash safety and exactly-once execution.
125
+ {
126
+ const spawnFailure = await runCommand('echo hi', { cwd: '/nonexistent-loop-dir' });
127
+ assert.equal(spawnFailure.exitCode, 127, 'a spawn failure is a failed command, not a crash');
128
+ assert.equal((await runCommand('echo \0')).exitCode, 127);
129
+
130
+ const root = await tempRoot('queue');
131
+ const queue = 'q';
132
+ const queueDir = path.join(root, 'runtime/loops', queue);
133
+ await ensureQueueDirs(root, queue);
134
+ const log = path.join(root, 'exec.log');
135
+ const list = async (subdir) => (await readdir(path.join(queueDir, subdir))).filter((name) => name.endsWith('.json')).sort();
136
+ const executions = async () => (await readFile(log, 'utf8').catch(() => '')).split('\n').filter(Boolean);
137
+
138
+ // Concurrent enqueues with the same (non-ASCII) title never overwrite.
139
+ const enqueued = await Promise.all(Array.from({ length: 6 }, () => enqueueTask(root, { queue, title: '部署', task: 'x' })));
140
+ assert.equal(new Set(enqueued.map((entry) => entry.task.id)).size, 6);
141
+ assert.equal((await list('inbox')).length, 6);
142
+ for (const name of await list('inbox')) await rm(path.join(queueDir, 'inbox', name));
143
+
144
+ // A truncated queued task is quarantined instead of blocking the queue.
145
+ await writeFile(path.join(queueDir, 'inbox', '0000_partial.json'), '{"id":"0000_par');
146
+ const good = await enqueueTask(root, { queue, title: 'good', task: 'x' });
147
+ let result = await runQueueOnce(root, { queue, dispatcher: `echo "$LOOP_TASK_ID" >> ${JSON.stringify(log)}` });
148
+ assert.equal(result.processed, true);
149
+ assert.deepEqual(await executions(), [good.task.id]);
150
+ assert.equal((await readdir(path.join(queueDir, 'quarantine'))).some((name) => name.endsWith('0000_partial.json')), true);
151
+
152
+ // An empty lock is respected while fresh and reclaimed once stale.
153
+ const lockFile = path.join(queueDir, 'queue.lock');
154
+ await writeFile(lockFile, '');
155
+ await enqueueTask(root, { queue, title: 'after-lock', task: 'x' });
156
+ assert.equal((await runQueueOnce(root, { queue, dispatcher: 'true' })).status, 'locked');
157
+ const old = new Date(Date.now() - 120000);
158
+ await utimes(lockFile, old, old);
159
+ assert.equal((await runQueueOnce(root, { queue, dispatcher: 'true' })).processed, true, 'a stale unreadable lock is reclaimed');
160
+
161
+ // A stale active copy of a finished task is quarantined, not re-run, and
162
+ // a task that keeps crashing its runner stops being recovered.
163
+ const finished = (await list('failed'))[0] ?? (await list('done'))[0];
164
+ const finishedDir = (await list('failed')).includes(finished) ? 'failed' : 'done';
165
+ await writeFile(path.join(queueDir, 'active', finished), await readFile(path.join(queueDir, finishedDir, finished)));
166
+ await writeFile(path.join(queueDir, 'active', 'crashy.json'), JSON.stringify({ version: 1, id: 'crashy', queue, title: 'crashy', body: 'x', status: 'active', orphanRecoveryCount: 3 }));
167
+ result = await runQueueOnce(root, { queue, dispatcher: `echo "$LOOP_TASK_ID" >> ${JSON.stringify(log)}` });
168
+ assert.deepEqual(result.orphanRecovered.map((entry) => entry.outcome).sort(), ['orphan_recovery_exhausted', 'quarantined_duplicate']);
169
+ assert.equal((await executions()).includes('crashy'), false);
170
+ assert.equal((await list('failed')).includes('crashy.json'), true);
171
+
172
+ // The lease is renewed while a dispatch outlasts leaseMs, so a second
173
+ // runner cannot reclaim the lock and execute the same task again.
174
+ const slow = await enqueueTask(root, { queue, title: 'slow', task: 'x' });
175
+ const first = runQueueOnce(root, { queue, leaseMs: 300, dispatcher: `echo "$LOOP_TASK_ID" >> ${JSON.stringify(log)}; sleep 1.5` });
176
+ await new Promise((resolve) => setTimeout(resolve, 900));
177
+ assert.equal((await runQueueOnce(root, { queue, leaseMs: 300, dispatcher: `echo "$LOOP_TASK_ID" >> ${JSON.stringify(log)}` })).status, 'locked');
178
+ await first;
179
+ assert.equal((await executions()).filter((id) => id === slow.task.id).length, 1);
180
+
181
+ // Canceling an active task stops its dispatcher and leaves one copy.
182
+ const victim = await enqueueTask(root, { queue, title: 'victim', task: 'x' });
183
+ const running = runQueueOnce(root, { queue, dispatcher: `sleep 1.5; echo "$LOOP_TASK_ID finished" >> ${JSON.stringify(log)}` });
184
+ await new Promise((resolve) => setTimeout(resolve, 500));
185
+ await queueCancel(root, queue, victim.task.id, { includeActive: true, reason: 'test' });
186
+ const canceledRun = await running;
187
+ assert.equal((await executions()).includes(`${victim.task.id} finished`), false, 'the dispatcher was stopped');
188
+ assert.equal(canceledRun.run?.movedByOperator ?? JSON.parse(await readFile(path.join(root, canceledRun.runPath), 'utf8')).movedByOperator, true);
189
+ assert.deepEqual([...await list('done'), ...await list('failed')].filter((name) => name.startsWith(victim.task.id)), []);
190
+ assert.equal(JSON.parse(await readFile(path.join(queueDir, 'canceled', `${victim.task.id}.json`), 'utf8')).cancelReason, 'test');
191
+
192
+ // Its stop marker must not supersede the task again after a requeue.
193
+ await queueRequeue(root, queue, victim.task.id, { from: 'canceled' });
194
+ await runQueueOnce(root, { queue, dispatcher: `echo "$LOOP_TASK_ID rerun" >> ${JSON.stringify(log)}` });
195
+ assert.equal((await executions()).includes(`${victim.task.id} rerun`), true, 'a requeued task runs despite an old stop marker');
196
+ assert.equal((await queueStatus(root, queue)).active, 0);
197
+ }
198
+
199
+ // Control-plane primitives: one idempotency key, one request; fenced and
200
+ // zero-or-one kernel effects; a journal that survives torn and concurrent
201
+ // appends.
202
+ {
203
+ const root = await tempRoot('primitives');
204
+ for (let trial = 0; trial < 10; trial += 1) {
205
+ const key = `charge:${trial}`;
206
+ // A mutex left behind by a crashed process is what several waiters
207
+ // used to break simultaneously.
208
+ const crashedLock = path.join(root, 'runtime/loops/action-reservations', `${createHash('sha256').update(key).digest('hex')}.lock`);
209
+ await mkdir(crashedLock, { recursive: true });
210
+ const old = new Date(Date.now() - 60000);
211
+ await touch(crashedLock, old, old);
212
+ const results = await Promise.allSettled(Array.from({ length: 8 }, (_, amount) =>
213
+ reserveAction(root, { idempotencyKey: key, kind: 'paid_api', authorizationScope: 'scope', request: { amount } })));
214
+ assert.equal(results.filter((entry) => entry.status === 'fulfilled' && entry.value.created === true).length, 1, 'one key is granted to one request');
215
+ }
216
+ await reserveAction(root, { idempotencyKey: 'late', kind: 'paid_api', authorizationScope: 'scope', request: { amount: 1 } });
217
+ const claim = await claimAction(root, { idempotencyKey: 'late', owner: 'w', leaseMs: 50 });
218
+ await new Promise((resolve) => setTimeout(resolve, 80));
219
+ const late = await settleAction(root, { idempotencyKey: 'late', fencingToken: claim.fencingToken, evidence: 'upstream-1' });
220
+ assert.equal(late.settled, false); assert.equal(late.record.state, 'unknown', 'a settle after lease expiry needs reconciliation');
221
+ assert.equal(late.record.reconciliation.late_report.evidence, 'upstream-1');
222
+
223
+ const kernel = new TransactionalStateKernel(path.join(root, 'kernel'));
224
+ const a = await kernel.acquire(); await kernel.release(a);
225
+ const b = await kernel.acquire();
226
+ assert.notEqual(a.fencingToken, b.fencingToken);
227
+ await assert.rejects(() => kernel.transact({ lease: a, effects: [{ type: 'state_transition', key: 'stale', payload: {} }] }), /Stale fencing token/);
228
+ await kernel.transact({ lease: b, effects: [{ type: 'state_transition', key: 'fresh', payload: {} }] });
229
+ await kernel.release(b);
230
+ let executions = 0;
231
+ const effect = { type: 'external_action', key: 'charge-42', payload: { amount: 100 } };
232
+ await Promise.all([1, 2, 3].map(() => kernel.replayEffect(effect, async () => { executions += 1; await new Promise((resolve) => setTimeout(resolve, 20)); return 'charged'; })));
233
+ assert.equal(executions, 1, 'concurrent replayEffect executes once');
234
+ const crashing = { type: 'external_action', key: 'crash-1', payload: {} };
235
+ await assert.rejects(() => kernel.replayEffect(crashing, async () => { throw new Error('crashed after upstream accepted'); }));
236
+ assert.equal((await kernel.replayEffect(crashing, async () => { executions += 1; })).reconcileRequired, true, 'an interrupted effect is not re-run');
237
+ assert.equal(executions, 1);
238
+ await kernel.reconcileEffect(crashing, { executed: true, outcome: 'accepted' });
239
+ assert.equal((await kernel.replayEffect(crashing, async () => { executions += 1; })).replayed, true);
240
+ assert.equal((await kernel.verifyReceiptChain()).ok, true);
241
+
242
+ const journal = new DurableJournal(path.join(root, 'journal'));
243
+ await journal.append('a', 1);
244
+ await Promise.all(['b', 'c', 'd'].map((type, index) => journal.append(type, index)));
245
+ assert.equal((await journal.replay()).count, 4, 'concurrent appends keep the chain valid');
246
+ await appendFile(journal.logFile, '{"version":1,"transactionId":"x","ty');
247
+ await journal.append('e', 5);
248
+ assert.equal((await journal.replay()).count, 5, 'a torn tail is discarded, not buried');
249
+ }
250
+
251
+ // Medium and low severity regressions.
252
+ {
253
+ const root = await tempRoot('medium');
254
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' });
255
+
256
+ // CLI flags reject missing, swallowed and malformed values.
257
+ for (const [args, message] of [[['queue-status', '--queue'], /--queue requires a value/], [['enqueue', '--queue', 'q', '--title', '--task', 'x'], /--title requires a value/], [['queue-status', '--queue', 'q', '--timeout-ms', '10m'], /--timeout-ms must be an integer/]]) {
258
+ const result = spawnSync(process.execPath, [cli, ...args], { cwd: root, encoding: 'utf8' });
259
+ assert.notEqual(result.status, 0); assert.match(result.stderr, message);
260
+ }
261
+
262
+ // json-value equality ignores key order.
263
+ await writeJson(path.join(root, 'cfg.json'), { port: 8080, host: '0.0.0.0' });
264
+ await writeJson(path.join(root, 'kv.json'), { id: 'kv', goal: 'Keep the service configuration stable', level: 'L1', mode: 'report-only', checks: [{ id: 'cfg', type: 'json-value', file: 'cfg.json', pointer: '', expected: { host: '0.0.0.0', port: 8080 } }] });
265
+ assert.match(loop(root, 'run', '--config', 'kv.json').stdout, /kv: success/);
266
+
267
+ // Project names match whole tokens only ("ui" is not in "build").
268
+ await writeJson(path.join(root, 'configs/loops/projects/ui.json'), { schemaVersion: 1, project: 'ui', type: 'code_project', queues: [{ queue: 'rq', kind: 'standard' }], backlog: [] });
269
+ const routed = (message) => JSON.parse(loop(root, 'route-message', '--message', message, '--route', '--confirm-execute', '--queue', 'rq', '--json').stdout);
270
+ assert.equal(routed('use loop engineering to build the billing export').task?.projectId ?? null, null);
271
+ assert.equal(routed('use loop engineering to fix the ui bug').task?.projectId, 'ui');
272
+
273
+ // A revision plan applied twice enqueues one revision.
274
+ await writeJson(path.join(root, 'plan.json'), { queue: 'rq', sourceTaskId: 'source-1', plannedTask: { title: 'Revise', body: 'Revise it', revisionOf: 'source-1' } });
275
+ assert.equal(loop(root, 'queue-revision-apply-plan', '--plan', 'plan.json').status, 0);
276
+ const second = loop(root, 'queue-revision-apply-plan', '--plan', 'plan.json');
277
+ assert.notEqual(second.status, 0); assert.match(second.stderr, /already enqueued/);
278
+
279
+ // A worktree task that is requeued reuses its branch and worktree.
280
+ git('init', '-q'); git('config', 'user.email', 'loop@example.invalid'); git('config', 'user.name', 'loop');
281
+ await writeFile(path.join(root, '.gitignore'), 'runtime/\nconfigs/\n*.json\n');
282
+ await writeFile(path.join(root, 'file.txt'), 'one\n');
283
+ git('add', '-A'); git('commit', '-qm', 'init');
284
+ loop(root, 'code-queue-init', '--queue', 'wq');
285
+ const wqConfig = path.join(root, 'configs/loops/queues/wq.json');
286
+ const config = JSON.parse(await readFile(wqConfig, 'utf8')); config.worktree.verifyCommands = []; delete config.preflightConfig; await writeJson(wqConfig, config);
287
+ loop(root, 'enqueue', '--queue', 'wq', '--title', 'Rerun', '--task', 'x');
288
+ loop(root, 'run-queue', '--queue', 'wq', '--config', 'configs/loops/queues/wq.json', '--dispatcher', 'echo two >> file.txt; exit 1');
289
+ const failedTask = (await readdir(path.join(root, 'runtime/loops/wq/failed')))[0].replace(/\.json$/, '');
290
+ loop(root, 'queue-requeue', '--queue', 'wq', '--task-id', failedTask);
291
+ loop(root, 'run-queue', '--queue', 'wq', '--config', 'configs/loops/queues/wq.json', '--dispatcher', 'echo three >> file.txt');
292
+ const runs = await readdir(path.join(root, 'runtime/loops/wq/runs'));
293
+ const rerun = JSON.parse(await readFile(path.join(root, 'runtime/loops/wq/runs', runs.sort().at(-1)), 'utf8'));
294
+ assert.equal(rerun.worktree.setup.exitCode, 0, 'a requeued worktree task can run again');
295
+ assert.equal(rerun.worktree.reused, true);
296
+ assert.equal(await readFile(path.join(root, rerun.worktree.path, 'file.txt'), 'utf8'), 'one\ntwo\nthree\n', 'the rerun continues in the same worktree');
297
+
298
+ // Patch headers with git-quoted (non-ASCII) paths are recognised.
299
+ await writeFile(path.join(root, '项目.txt'), 'a\n'); git('add', '项目.txt'); git('commit', '-qm', 'cn');
300
+ await writeFile(path.join(root, '项目.txt'), 'b\n');
301
+ await writeFile(path.join(root, 'cn.patch'), git('diff'));
302
+ const planned = JSON.parse(loop(root, 'code-patch-apply-plan', '--patch', 'cn.patch', '--json').stdout);
303
+ assert.deepEqual(planned.diffFiles.map((file) => file.newPath), ['项目.txt']);
304
+ assert.equal(planned.dirtyAffected, true, 'the dirty-target check covers quoted paths');
305
+
306
+ // A stale handoff cannot take back a recovered and completed todo.
307
+ for (const id of ['A', 'B', 'C']) await registerAgent(root, { id, quota_grants: { default: 100 }, authority_grants: ['local'] });
308
+ await createTodo(root, { id: 't1', title: 'x', acceptance_contract: { c: 1 }, evidence_requirements: ['e'] });
309
+ const claimA = await claimTodo(root, { agent_id: 'A', lease_ms: 60_000 });
310
+ const packet = await handoffTodo(root, { todo_id: 't1', agent_id: 'A', target_agent_id: 'B', fencing_token: claimA.fencing_token });
311
+ // Expire deterministically through the recovery clock, not a 50 ms race
312
+ // between filesystem operations on a shared CI runner.
313
+ await recoverTodos(root, { now: Date.parse(claimA.todo.claim.lease_expires_at) + 1 });
314
+ const claimC = await claimTodo(root, { agent_id: 'C' });
315
+ await releaseTodo(root, { todo_id: 't1', agent_id: 'C', fencing_token: claimC.fencing_token, completed: true, evidence: 'done' });
316
+ await assert.rejects(() => decideHandoff(root, { handoff_id: packet.id, agent_id: 'B', accept: true }), /Pending handoff not found/);
317
+
318
+ // Concurrent verified spend is never lost.
319
+ await Promise.all(Array.from({ length: 10 }, (_, index) => recordVerifiedSliceSpend(root, { status: 'completed', verified: true, slice_id: `slice-${index}`, spend: { tokens: 100 } })));
320
+ assert.equal((await readQuotaLedger(root)).spend.tokens, 1000);
321
+
322
+ // Redaction catches camelCase credentials but keeps counters visible.
323
+ for (const key of ['accessToken', 'Authorization', 'openaiApiKey', 'client_secret', 'api_token']) assert.equal(sensitiveKey(key), true, key);
324
+ for (const key of ['fencing_token', 'stale_fencing_tokens_accepted', 'max_tokens', 'token_count']) assert.equal(sensitiveKey(key), false, key);
325
+
326
+ // Evidence verdicts are derived, and a keyed seal cannot be forged.
327
+ const draft = { generated_at: '2026-10-10T00:00:00.000Z', passed: true, metrics: { error_rate: 0.5 }, thresholds: { error_rate: { max: 0 } }, scenarios: [{ status: 'passed' }], compatibility: [{ status: 'passed', runtime: 'x', contract_version: 1 }], limitations: [], evaluation: { checks: [] } };
328
+ const sealed = sealEvidence(draft);
329
+ assert.equal(sealed.passed, false, 'failing thresholds cannot be sealed as passed');
330
+ assert.equal(publicEvidenceSummary(sealed).passed, false);
331
+ assert.equal(evaluateEvidence(sealed).passed, false);
332
+ const keyed = sealEvidence({ ...draft, metrics: { error_rate: 0 } }, { key: 'secret-key' });
333
+ assert.equal(keyed.integrity.algorithm, 'hmac-sha256');
334
+ assert.equal(verifyEvidence(keyed, { key: 'secret-key' }).valid, true);
335
+ assert.equal(verifyEvidence(keyed).reason, 'hmac_key_required');
336
+ const forged = { ...keyed, metrics: { error_rate: 0.9 } };
337
+ assert.equal(verifyEvidence(forged, { key: 'secret-key' }).valid, false);
338
+
339
+ // A Feishu reply names the generation it answers.
340
+ await createHumanGate(root, { gate_id: 'gate_reply', project: 'p', task: 't', action: 'deploy', reason: 'r', impact: 'i', risk: { level: 'low' }, cost: { amount: 0, currency: 'CNY', budget: null }, evidence: [], dashboard_url: null, expiry: '2099-01-01T00:00:00.000Z', allowed_actors: ['ou_owner'], confirmation_required: false, source_bindings: [{ channel: 'feishu', message_id: 'card-9', reply_to: 'card-9', adapter: 'feishu' }] });
341
+ const reply = (text, eventId) => normalizeFeishuGateEvent({ header: { event_id: eventId }, event: { sender: { sender_id: { open_id: 'ou_owner' } }, message: { root_id: 'card-9', parent_id: 'card-9', content: JSON.stringify({ text }) } } }, { signatureVerified: true });
342
+ assert.equal((await handleChannelGateEvent(root, reply('/approve gate_reply', 'e1'))).outcome, 'generation_required');
343
+ assert.equal((await handleChannelGateEvent(root, reply('/approve gate_reply@1', 'e2'))).outcome, 'approved');
344
+ assert.equal((await getHumanGate(root, 'gate_reply')).status, 'approved');
345
+ }
346
+
347
+ console.log('safety regression self-test passed');
348
+ } finally {
349
+ for (const root of roots) await rm(root, { recursive: true, force: true });
350
+ }
@@ -122,7 +122,7 @@ so durable queue continuity does not depend on resuming a Hermes Cron session.
122
122
 
123
123
  ## Cross-interface Human Gates
124
124
 
125
- Dashboard and chat approvals use one Gate Command core and one authoritative gate artifact. Cards must show project/task, Gate ID, action, reason, impact, risk, cost/budget, evidence, Dashboard URL, expiry and generation; processed cards are refreshed disabled. Only card buttons or exact card-bound `/approve gate_<id>`, `/reject gate_<id>` and `/request_revision gate_<id> <reason>` replies may mutate a gate. Ordinary chat, quotes, forwards, screenshots and ordinal phrases fail closed as `ignored_untrusted_chat`; `/show_gate gate_<id>` is display-only.
125
+ Dashboard and chat approvals use one Gate Command core and one authoritative gate artifact. Cards must show project/task, Gate ID, action, reason, impact, risk, cost/budget, evidence, Dashboard URL, expiry and generation; processed cards are refreshed disabled. Only card buttons or exact card-bound `/approve gate_<id>@<generation>`, `/reject gate_<id>@<generation>` and `/request_revision gate_<id>@<generation> <reason>` replies may mutate a gate. Ordinary chat, quotes, forwards, screenshots and ordinal phrases fail closed as `ignored_untrusted_chat`; `/show_gate gate_<id>` is display-only.
126
126
 
127
127
  The OpenClaw installer generates `scripts/loops/openclaw-loop-gate.mjs`. A trusted Feishu callback/plugin transport must verify the official signature or encrypted-event envelope, timestamp/nonce and secret before invoking it with `LOOP_GATE_CHANNEL=feishu` and `LOOP_FEISHU_SIGNATURE_VERIFIED=1`; missing verification fails with `feishu_signature_unverified`. The bridge itself performs no delivery. Other channel transports pass normalized, source-bound events. Dashboard and chat commands share actor/source binding, generation fencing, idempotency receipts, confirmation escalation and synchronized card state.
128
128
 
@@ -138,6 +138,8 @@ Interpret explicit loop language as follows:
138
138
  - `继续当前 loop,补充要求:…`: amend the active task in place. Preserve the task id and worker session, write a versioned amendment, update the task contract/dev plan/acceptance plan, and require the worker to reread the latest amendment before checkpoints and completion.
139
139
  - A new explicit `走 loop` request while another task is active is a correction/replacement, not ordinary backlog. Supersede the active task at a safe boundary, retain its evidence and lineage, then start the replacement after the lock is released.
140
140
  - Status, progress, evidence, or failure questions are read-only and must not start another tick unless the user explicitly asks to continue/run.
141
+ - For status questions, read the latest checkpoint, verification result and worker liveness, then reply before doing further work. A failed check is a result to report, not authorization to edit files, rebuild images or rerun tests in the chat session. Send authorized follow-up execution to the task's independent worker session; never adopt its implementation into the conversation session.
142
+ - Conversation routing starts a background worker and returns a launch receipt; it must not await the full worker tick. A receipt proves process launch only, not lock acquisition, task execution, or acceptance. The background entry waits for a confirmed queue-lock conflict for up to five minutes by default; only exit code 2 with JSON status=locked and processed=false is retried. Read the launch log and queue state after timeout; do not start a duplicate worker from the chat. Keep scheduler/manual `run-once` execution synchronous and inspect its final artifacts separately.
141
143
 
142
144
  Do not infer a queue or dispatcher from this skill. Use the integration installed in the current workspace. For OpenClaw, inspect the generated queue configuration under `configs/loops/queues/` and use the managed wrapper when present. A default installation uses queue `agent-tasks` and the generic wrapper below; an operator may choose another queue or worker during installation.
143
145
 
@@ -152,6 +154,10 @@ If the managed wrapper or queue configuration is absent, stop and run the platfo
152
154
 
153
155
  Pass the original request faithfully. Preserve source channel, target, account, message id, and reply-to metadata so progress, human gates, and terminal results return to the originating conversation. Missing delivery routing must fail closed.
154
156
 
157
+ ## Context Budget and Durable Handoff
158
+
159
+ For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Keep one bounded objective per turn, read bounded file ranges, and save checkpoints instead of replaying transcripts. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
160
+
155
161
  ## Task vs Project Classification
156
162
 
157
163
  Classify scope before enqueueing.
@@ -0,0 +1,11 @@
1
+ # Context budget and recovery
2
+
3
+ 1. Inspect the installed OpenClaw dispatcher and queue `retry` configuration. New installations use `sessionMaxTicks: 3` and `contextBudget: { softRatio: 0.60, hardRatio: 0.75 }`. Existing explicit tick limits are retained until a reviewed integration upgrade. A package/skill update alone does not update generated workspace files. Hermes does not yet expose the OpenClaw telemetry adapter; do not claim equivalent telemetry protection there.
4
+ 2. Keep one bounded objective per worker turn. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
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
+ 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
+ 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. Consecutive runtime recoveries (including voluntary handoffs) share `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Accepted project progress resets that recovery counter.
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
+
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.