taskforce-loop-engineering 0.15.21 → 0.16.0

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 (40) hide show
  1. package/CHANGELOG.md +54 -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/core.mjs +643 -109
  13. package/lib/durable-journal.mjs +23 -6
  14. package/lib/execution-ledger.mjs +4 -4
  15. package/lib/file-mutex.mjs +102 -0
  16. package/lib/human-gate-channel-adapter.mjs +4 -2
  17. package/lib/human-gate-command.mjs +5 -3
  18. package/lib/operator-dashboard.mjs +72 -10
  19. package/lib/production-evidence.mjs +37 -15
  20. package/lib/quota-runtime-decision.mjs +11 -6
  21. package/lib/redaction.mjs +34 -0
  22. package/lib/todo-control-plane.mjs +12 -16
  23. package/lib/transactional-state-kernel.mjs +96 -18
  24. package/package.json +2 -3
  25. package/scripts/dashboard-autostart-install.mjs +33 -8
  26. package/scripts/dashboard-autostart-self-test.mjs +12 -3
  27. package/scripts/final-judgement-self-test.mjs +21 -0
  28. package/scripts/hermes-install-self-test.mjs +8 -1
  29. package/scripts/hermes-install.mjs +29 -8
  30. package/scripts/hermes-smoke.mjs +2 -1
  31. package/scripts/human-gate-command-self-test.mjs +34 -5
  32. package/scripts/install-shared.mjs +61 -0
  33. package/scripts/openclaw-install-self-test.mjs +47 -1
  34. package/scripts/openclaw-install.mjs +42 -17
  35. package/scripts/openclaw-manage.mjs +22 -3
  36. package/scripts/openclaw-smoke.mjs +2 -1
  37. package/scripts/project-relay-self-test.mjs +145 -1
  38. package/scripts/run-loop-cron.sh +22 -7
  39. package/scripts/safety-regression-self-test.mjs +349 -0
  40. package/skills/taskforce-loop-engineering/SKILL.md +1 -1
@@ -0,0 +1,349 @@
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: 50 });
310
+ const packet = await handoffTodo(root, { todo_id: 't1', agent_id: 'A', target_agent_id: 'B', fencing_token: claimA.fencing_token });
311
+ await new Promise((resolve) => setTimeout(resolve, 80));
312
+ await recoverTodos(root);
313
+ const claimC = await claimTodo(root, { agent_id: 'C' });
314
+ await releaseTodo(root, { todo_id: 't1', agent_id: 'C', fencing_token: claimC.fencing_token, completed: true, evidence: 'done' });
315
+ await assert.rejects(() => decideHandoff(root, { handoff_id: packet.id, agent_id: 'B', accept: true }), /Pending handoff not found/);
316
+
317
+ // Concurrent verified spend is never lost.
318
+ await Promise.all(Array.from({ length: 10 }, (_, index) => recordVerifiedSliceSpend(root, { status: 'completed', verified: true, slice_id: `slice-${index}`, spend: { tokens: 100 } })));
319
+ assert.equal((await readQuotaLedger(root)).spend.tokens, 1000);
320
+
321
+ // Redaction catches camelCase credentials but keeps counters visible.
322
+ for (const key of ['accessToken', 'Authorization', 'openaiApiKey', 'client_secret', 'api_token']) assert.equal(sensitiveKey(key), true, key);
323
+ for (const key of ['fencing_token', 'stale_fencing_tokens_accepted', 'max_tokens', 'token_count']) assert.equal(sensitiveKey(key), false, key);
324
+
325
+ // Evidence verdicts are derived, and a keyed seal cannot be forged.
326
+ 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: [] } };
327
+ const sealed = sealEvidence(draft);
328
+ assert.equal(sealed.passed, false, 'failing thresholds cannot be sealed as passed');
329
+ assert.equal(publicEvidenceSummary(sealed).passed, false);
330
+ assert.equal(evaluateEvidence(sealed).passed, false);
331
+ const keyed = sealEvidence({ ...draft, metrics: { error_rate: 0 } }, { key: 'secret-key' });
332
+ assert.equal(keyed.integrity.algorithm, 'hmac-sha256');
333
+ assert.equal(verifyEvidence(keyed, { key: 'secret-key' }).valid, true);
334
+ assert.equal(verifyEvidence(keyed).reason, 'hmac_key_required');
335
+ const forged = { ...keyed, metrics: { error_rate: 0.9 } };
336
+ assert.equal(verifyEvidence(forged, { key: 'secret-key' }).valid, false);
337
+
338
+ // A Feishu reply names the generation it answers.
339
+ 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' }] });
340
+ 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 });
341
+ assert.equal((await handleChannelGateEvent(root, reply('/approve gate_reply', 'e1'))).outcome, 'generation_required');
342
+ assert.equal((await handleChannelGateEvent(root, reply('/approve gate_reply@1', 'e2'))).outcome, 'approved');
343
+ assert.equal((await getHumanGate(root, 'gate_reply')).status, 'approved');
344
+ }
345
+
346
+ console.log('safety regression self-test passed');
347
+ } finally {
348
+ for (const root of roots) await rm(root, { recursive: true, force: true });
349
+ }
@@ -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