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.
- package/CHANGELOG.md +70 -0
- package/MIGRATING.md +80 -0
- package/README.md +37 -8
- package/bin/loop-engineering.mjs +142 -114
- package/docs/architecture.md +3 -2
- package/docs/human-gate-command.md +1 -1
- package/docs/operator-dashboard.md +16 -5
- package/docs/operator-workspace-project.md +2 -2
- package/docs/production-trust-contract.md +9 -2
- package/docs/transactional-kernel-and-goal-api.md +3 -1
- package/lib/action-reservations.mjs +21 -23
- package/lib/context-budget.mjs +147 -0
- package/lib/core.mjs +746 -241
- package/lib/dispatch-classification.mjs +114 -0
- package/lib/durable-journal.mjs +23 -6
- package/lib/execution-ledger.mjs +4 -4
- package/lib/file-mutex.mjs +102 -0
- package/lib/human-gate-channel-adapter.mjs +4 -2
- package/lib/human-gate-command.mjs +5 -3
- package/lib/operator-dashboard.mjs +72 -10
- package/lib/production-evidence.mjs +37 -15
- package/lib/quota-runtime-decision.mjs +11 -6
- package/lib/redaction.mjs +34 -0
- package/lib/todo-control-plane.mjs +12 -16
- package/lib/transactional-state-kernel.mjs +96 -18
- package/package.json +2 -3
- package/scripts/context-budget-self-test.mjs +249 -0
- package/scripts/dashboard-autostart-install.mjs +33 -8
- package/scripts/dashboard-autostart-self-test.mjs +12 -3
- package/scripts/final-judgement-self-test.mjs +113 -4
- package/scripts/hermes-install-self-test.mjs +8 -1
- package/scripts/hermes-install.mjs +29 -8
- package/scripts/hermes-smoke.mjs +2 -1
- package/scripts/human-gate-command-self-test.mjs +34 -5
- package/scripts/install-shared.mjs +61 -0
- package/scripts/openclaw-install-self-test.mjs +158 -2
- package/scripts/openclaw-install.mjs +105 -30
- package/scripts/openclaw-manage.mjs +22 -3
- package/scripts/openclaw-smoke.mjs +2 -1
- package/scripts/project-relay-self-test.mjs +145 -1
- package/scripts/run-loop-cron.sh +22 -7
- package/scripts/safety-regression-self-test.mjs +350 -0
- package/skills/taskforce-loop-engineering/SKILL.md +7 -1
- package/skills/taskforce-loop-engineering/references/context-budget.md +11 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Shared credential redaction for evidence, ledgers and dashboard output.
|
|
2
|
+
// Keys are split into words (snake_case, kebab-case and camelCase), so
|
|
3
|
+
// accessToken, Authorization and openaiApiKey are caught.
|
|
4
|
+
// Words that mark a credential wherever they appear in a key.
|
|
5
|
+
const SENSITIVE_WORDS = new Set(['secret', 'secrets', 'password', 'passwd', 'passphrase', 'credential', 'credentials', 'authorization', 'cookie', 'cookies', 'apikey', 'privatekey']);
|
|
6
|
+
|
|
7
|
+
function keyWords(key) {
|
|
8
|
+
return String(key).replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// "token" is a credential only as the final word (access_token, accessToken,
|
|
12
|
+
// id_token); counters and metrics such as max_tokens, token_count or
|
|
13
|
+
// stale_fencing_tokens_accepted are not, and fencing_token is an ordering
|
|
14
|
+
// counter that must stay visible.
|
|
15
|
+
export function sensitiveKey(key, extraWords = []) {
|
|
16
|
+
const words = keyWords(key);
|
|
17
|
+
if (!words.length) return false;
|
|
18
|
+
if (words.length === 2 && words[0] === 'fencing' && words[1] === 'token') return false;
|
|
19
|
+
if (words.at(-1) === 'token') return true;
|
|
20
|
+
return words.some((word, index) => SENSITIVE_WORDS.has(word) || extraWords.includes(word)
|
|
21
|
+
|| (['api', 'private'].includes(word) && words[index + 1] === 'key'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Replace values under sensitive keys. Object keys are sorted when sortKeys
|
|
25
|
+
// is set, matching callers that hash the result.
|
|
26
|
+
export function redact(value, { key = '', sortKeys = false, extraWords = [] } = {}) {
|
|
27
|
+
if (sensitiveKey(key, extraWords)) return '[REDACTED]';
|
|
28
|
+
if (Array.isArray(value)) return value.map((item) => redact(item, { sortKeys, extraWords }));
|
|
29
|
+
if (value && typeof value === 'object') {
|
|
30
|
+
const names = sortKeys ? Object.keys(value).sort() : Object.keys(value);
|
|
31
|
+
return Object.fromEntries(names.map((name) => [name, redact(value[name], { key: name, sortKeys, extraWords })]));
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { withFileMutex } from './file-mutex.mjs';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
4
5
|
import { inspectAction } from './action-reservations.mjs';
|
|
5
6
|
import { decideQuota } from './quota-runtime-decision.mjs';
|
|
@@ -43,24 +44,10 @@ async function atomicWrite(file, value) {
|
|
|
43
44
|
await rename(temp, file);
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
async function acquire(lock, timeoutMs = 5000) {
|
|
47
|
-
const deadline = Date.now() + timeoutMs;
|
|
48
|
-
while (true) {
|
|
49
|
-
try { await mkdir(lock); return; } catch (error) {
|
|
50
|
-
if (error.code !== 'EEXIST') throw error;
|
|
51
|
-
const info = await stat(lock).catch(() => null);
|
|
52
|
-
if (info && Date.now() - info.mtimeMs > 30_000) await rm(lock, { recursive: true, force: true });
|
|
53
|
-
else if (Date.now() >= deadline) throw new Error('Timed out acquiring control-plane mutex.');
|
|
54
|
-
else await new Promise((resolve) => setTimeout(resolve, 10));
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
47
|
async function transaction(root, operation) {
|
|
60
48
|
const place = location(root);
|
|
61
49
|
await mkdir(place.dir, { recursive: true });
|
|
62
|
-
|
|
63
|
-
try {
|
|
50
|
+
return withFileMutex(place.lock, { label: 'control-plane mutex' }, async () => {
|
|
64
51
|
const state = await readState(place.file);
|
|
65
52
|
state.version = Math.max(Number(state.version ?? 1), 3); state.agents ??= {}; state.todos ??= {}; state.handoffs ??= {}; state.peer_messages ??= {}; state.conflicts ??= {}; state.wake_events ??= {}; state.quotas ??= {};
|
|
66
53
|
const result = await operation(state);
|
|
@@ -70,7 +57,7 @@ async function transaction(root, operation) {
|
|
|
70
57
|
if (result.event) await writeFile(place.audit, `${JSON.stringify(result.event)}\n`, { flag: 'a' });
|
|
71
58
|
}
|
|
72
59
|
return result.output;
|
|
73
|
-
}
|
|
60
|
+
});
|
|
74
61
|
}
|
|
75
62
|
|
|
76
63
|
function event(type, todo, extra = {}) {
|
|
@@ -330,6 +317,12 @@ export async function decideHandoff(root, input) {
|
|
|
330
317
|
const target = id(input.agent_id ?? input.agentId, 'agent id');
|
|
331
318
|
if (packet.to_agent_id !== target) throw new Error('Only the target agent can decide a handoff.');
|
|
332
319
|
const todo = state.todos[packet.todo_id];
|
|
320
|
+
// The packet is only live while its todo is still waiting on it. After
|
|
321
|
+
// recovery or completion it is stale and must not move ownership.
|
|
322
|
+
if (!todo || todo.state !== 'handoff_pending' || todo.handoff_id !== packet.id) {
|
|
323
|
+
packet.state = 'expired'; packet.decided_at = new Date().toISOString(); packet.reason = 'todo_no_longer_awaiting_handoff';
|
|
324
|
+
return { changed: true, output: { handoff: packet, todo: todo ?? null, outcome: 'expired' }, event: { version: 1, event_id: randomUUID(), type: 'handoff_expired', handoff_id: packet.id, todo_id: packet.todo_id, at: packet.decided_at } };
|
|
325
|
+
}
|
|
333
326
|
if (input.accept) {
|
|
334
327
|
const check = await eligibility(root, { ...state, todos: { ...state.todos, [todo.id]: { ...todo, state: 'runnable' } } }, { ...todo, state: 'runnable' }, state.agents[target]);
|
|
335
328
|
if (!check.eligible) throw new Error(`Target agent is no longer eligible: ${check.reasons.join(', ')}`);
|
|
@@ -357,6 +350,9 @@ export async function recoverTodos(root, input = {}) {
|
|
|
357
350
|
const previous = todo.claim;
|
|
358
351
|
if (actionBlocks.length) { todo.state = 'blocked'; todo.blocked_reasons = actionBlocks.map((key) => `action_reconciliation:${key}`); }
|
|
359
352
|
else { todo.state = 'runnable'; todo.blocked_reasons = []; }
|
|
353
|
+
if (todo.handoff_id && state.handoffs[todo.handoff_id]?.state === 'pending') {
|
|
354
|
+
Object.assign(state.handoffs[todo.handoff_id], { state: 'expired', decided_at: new Date(now).toISOString(), reason: 'lease_expired_before_decision' });
|
|
355
|
+
}
|
|
360
356
|
todo.claim = null; todo.handoff_id = null; todo.updated_at = new Date(now).toISOString();
|
|
361
357
|
const audit = event('todo_orphan_recovered', todo, { previous_owner: previous.owner, previous_fencing_token: previous.fencing_token, outcome: todo.state }); todo.ownership_events.push(audit); audits.push(audit);
|
|
362
358
|
results.push({ todo_id: todo.id, outcome: todo.state, blocked_reasons: todo.blocked_reasons });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, open, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { mkdir, open, readFile, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
|
|
@@ -56,29 +56,65 @@ export class TransactionalStateKernel {
|
|
|
56
56
|
});
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// Take the single-writer lease. Each lease receives a fencing token that is
|
|
60
|
+
// persisted immediately (fencing_issued), so two leases never share a token
|
|
61
|
+
// and a released or superseded lease can no longer commit.
|
|
59
62
|
async acquire(owner = `pid:${process.pid}`) {
|
|
60
63
|
await mkdir(this.directory, { recursive: true });
|
|
61
64
|
let handle;
|
|
62
65
|
try { handle = await open(this.lockFile, 'wx'); }
|
|
63
66
|
catch (error) {
|
|
64
67
|
if (error.code !== 'EEXIST') throw error;
|
|
65
|
-
const stale = await readJson(this.lockFile, null);
|
|
68
|
+
const stale = await readJson(this.lockFile, null).catch(() => null);
|
|
66
69
|
const pid = Number(String(stale?.owner ?? '').match(/^pid:(\d+)$/)?.[1]);
|
|
67
70
|
let alive = Number.isInteger(pid) && pid > 0;
|
|
68
71
|
if (alive) { try { process.kill(pid, 0); } catch (probe) { if (probe.code === 'ESRCH') alive = false; else throw probe; } }
|
|
69
72
|
if (alive || !pid) throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
73
|
+
// Serialize reclaim so two writers cannot both delete the dead lease.
|
|
74
|
+
const guard = `${this.lockFile}.reclaim`;
|
|
75
|
+
try { await mkdir(guard); } catch (guardError) {
|
|
76
|
+
if (guardError.code !== 'EEXIST') throw guardError;
|
|
77
|
+
const info = await stat(guard).catch(() => null);
|
|
78
|
+
if (info && Date.now() - info.mtimeMs > 10_000) await rmdir(guard).catch(() => {});
|
|
79
|
+
throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const again = await readJson(this.lockFile, null).catch(() => null);
|
|
83
|
+
if (again?.owner !== stale?.owner || again?.fencing_token !== stale?.fencing_token) throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
84
|
+
await rm(this.lockFile, { force: true });
|
|
85
|
+
handle = await open(this.lockFile, 'wx');
|
|
86
|
+
} finally { await rmdir(guard).catch(() => {}); }
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const current = await this.inspect();
|
|
90
|
+
const fencingToken = Math.max(Number(current.fencing_token ?? 0), Number(current.fencing_issued ?? 0)) + 1;
|
|
91
|
+
await handle.writeFile(JSON.stringify({ owner, fencing_token: fencingToken }));
|
|
92
|
+
await atomicWrite(this.stateFile, { ...current, fencing_issued: fencingToken });
|
|
93
|
+
return { owner, fencingToken, generation: current.generation, handle, released: false };
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await handle.close();
|
|
70
96
|
await rm(this.lockFile, { force: true });
|
|
71
|
-
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async acquireWithin(owner, timeoutMs = 10_000) {
|
|
102
|
+
const deadline = Date.now() + timeoutMs;
|
|
103
|
+
while (true) {
|
|
104
|
+
try { return await this.acquire(owner); }
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (!/lease is active/.test(String(error?.message)) || Date.now() >= deadline) throw error;
|
|
107
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
108
|
+
}
|
|
72
109
|
}
|
|
73
|
-
const current = await this.inspect();
|
|
74
|
-
const lease = { owner, fencingToken: current.fencing_token + 1, generation: current.generation, handle };
|
|
75
|
-
await handle.writeFile(JSON.stringify({ owner, fencing_token: lease.fencingToken }));
|
|
76
|
-
return lease;
|
|
77
110
|
}
|
|
78
111
|
|
|
79
112
|
async release(lease) {
|
|
113
|
+
if (lease.released) return;
|
|
114
|
+
lease.released = true;
|
|
80
115
|
await lease.handle.close();
|
|
81
|
-
await
|
|
116
|
+
const holder = await readJson(this.lockFile, null).catch(() => null);
|
|
117
|
+
if (holder?.fencing_token === lease.fencingToken) await rm(this.lockFile, { force: true });
|
|
82
118
|
}
|
|
83
119
|
|
|
84
120
|
async transact(input) {
|
|
@@ -86,7 +122,8 @@ export class TransactionalStateKernel {
|
|
|
86
122
|
const owned = !input.lease;
|
|
87
123
|
try {
|
|
88
124
|
const current = await this.inspect();
|
|
89
|
-
if (lease.fencingToken <= current.fencing_token
|
|
125
|
+
if (lease.released || lease.fencingToken <= current.fencing_token
|
|
126
|
+
|| (current.fencing_issued !== undefined && lease.fencingToken !== current.fencing_issued)) throw new Error('Stale fencing token.');
|
|
90
127
|
if (input.expectedGeneration !== undefined && input.expectedGeneration !== current.generation) {
|
|
91
128
|
throw new Error(`CAS generation mismatch: expected ${input.expectedGeneration}, actual ${current.generation}.`);
|
|
92
129
|
}
|
|
@@ -102,6 +139,10 @@ export class TransactionalStateKernel {
|
|
|
102
139
|
applied_effects: { ...current.applied_effects },
|
|
103
140
|
updated_at: new Date().toISOString()
|
|
104
141
|
};
|
|
142
|
+
if (input.clearPending && next.pending_effects?.[input.clearPending]) {
|
|
143
|
+
next.pending_effects = { ...next.pending_effects };
|
|
144
|
+
delete next.pending_effects[input.clearPending];
|
|
145
|
+
}
|
|
105
146
|
const receipts = [];
|
|
106
147
|
let previous = current.last_receipt;
|
|
107
148
|
for (const effect of fresh) {
|
|
@@ -130,18 +171,55 @@ export class TransactionalStateKernel {
|
|
|
130
171
|
} finally { if (owned) await this.release(lease); }
|
|
131
172
|
}
|
|
132
173
|
|
|
133
|
-
|
|
174
|
+
// Execute an external effect zero or one times. The writer lease is held
|
|
175
|
+
// from the applied-check through the commit, so concurrent callers wait and
|
|
176
|
+
// then observe the receipt. An intent is persisted before execute(); if a
|
|
177
|
+
// crash leaves it uncommitted, the effect is never re-run automatically and
|
|
178
|
+
// must be settled with reconcileEffect().
|
|
179
|
+
async replayEffect(effect, execute, options = {}) {
|
|
134
180
|
const normalized = typedEffect(effect.type, effect.payload, { key: effect.key });
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
181
|
+
const lease = await this.acquireWithin(options.owner, options.timeoutMs);
|
|
182
|
+
try {
|
|
183
|
+
const current = await this.inspect();
|
|
184
|
+
const existing = current.applied_effects[normalized.key];
|
|
185
|
+
if (existing) return { executed: false, replayed: true, receipt: existing.receipt };
|
|
186
|
+
const pending = current.pending_effects?.[normalized.key];
|
|
187
|
+
if (pending) return { executed: false, replayed: false, reconcileRequired: true, pending };
|
|
188
|
+
await atomicWrite(this.stateFile, { ...current, pending_effects: { ...(current.pending_effects ?? {}), [normalized.key]: { effect: normalized, started_at: new Date().toISOString(), fencing_token: lease.fencingToken } } });
|
|
189
|
+
const outcome = await execute(normalized);
|
|
190
|
+
const committed = await this.#commitEffect(lease, normalized, outcome);
|
|
191
|
+
return { executed: true, replayed: false, outcome, receipt: committed.receipts[0]?.receipt };
|
|
192
|
+
} finally { await this.release(lease); }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Settle an effect left pending by a crash: executed=true records the
|
|
196
|
+
// supplied outcome as applied; executed=false clears the intent so the
|
|
197
|
+
// effect may be replayed.
|
|
198
|
+
async reconcileEffect(effect, { executed, outcome = null, owner } = {}) {
|
|
199
|
+
const normalized = typedEffect(effect.type, effect.payload, { key: effect.key });
|
|
200
|
+
const lease = await this.acquireWithin(owner);
|
|
201
|
+
try {
|
|
202
|
+
const current = await this.inspect();
|
|
203
|
+
if (!current.pending_effects?.[normalized.key]) throw new Error(`No pending effect to reconcile: ${normalized.key}`);
|
|
204
|
+
if (executed === true) {
|
|
205
|
+
const committed = await this.#commitEffect(lease, normalized, outcome);
|
|
206
|
+
return { reconciled: 'applied', receipt: committed.receipts[0]?.receipt };
|
|
207
|
+
}
|
|
208
|
+
if (executed !== false) throw new Error('reconcileEffect requires executed: true or false.');
|
|
209
|
+
const pending = { ...current.pending_effects };
|
|
210
|
+
delete pending[normalized.key];
|
|
211
|
+
await atomicWrite(this.stateFile, { ...current, pending_effects: pending });
|
|
212
|
+
return { reconciled: 'cleared' };
|
|
213
|
+
} finally { await this.release(lease); }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async #commitEffect(lease, normalized, outcome) {
|
|
217
|
+
return this.transact({
|
|
218
|
+
lease,
|
|
141
219
|
effects: [normalized],
|
|
142
|
-
reduce: (state) => ({ ...state, effect_outcomes: { ...(state.effect_outcomes ?? {}), [normalized.key]: outcome } })
|
|
220
|
+
reduce: (state) => ({ ...state, effect_outcomes: { ...(state.effect_outcomes ?? {}), [normalized.key]: outcome } }),
|
|
221
|
+
clearPending: normalized.key
|
|
143
222
|
});
|
|
144
|
-
return { executed: true, replayed: false, outcome, receipt: committed.receipts[0]?.receipt };
|
|
145
223
|
}
|
|
146
224
|
|
|
147
225
|
async verifyReceiptChain() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "taskforce-loop-engineering",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
|
|
6
6
|
"type": "module",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node scripts/hermes-install-self-test.mjs",
|
|
31
31
|
"check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
|
|
32
32
|
"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",
|
|
33
|
-
"check": "npm run check:project-gates && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
|
|
33
|
+
"check": "node scripts/context-budget-self-test.mjs && npm run check:project-gates && node scripts/safety-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
|
|
34
34
|
"pack:dry": "npm pack --dry-run"
|
|
35
35
|
},
|
|
36
36
|
"exports": {
|
|
@@ -76,7 +76,6 @@
|
|
|
76
76
|
},
|
|
77
77
|
"homepage": "https://github.com/ambitioncn/taskforce-loop-engineering#readme",
|
|
78
78
|
"license": "Apache-2.0",
|
|
79
|
-
"main": "index.js",
|
|
80
79
|
"directories": {
|
|
81
80
|
"doc": "docs",
|
|
82
81
|
"example": "examples",
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { contextPolicy, contextRotation, openClawContextUsage, readBoundedJson } from '../lib/context-budget.mjs';
|
|
7
|
+
import { dispatchFailureClassification, enqueueTask, runQueueOnce, queueCancel } from '../lib/core.mjs';
|
|
8
|
+
|
|
9
|
+
const policy = contextPolicy();
|
|
10
|
+
assert.equal(contextRotation(null, 2, policy).rotate, false);
|
|
11
|
+
assert.equal(contextRotation(null, 3, policy).reason, 'bounded_tick_limit');
|
|
12
|
+
for (const [usedTokens, reason] of [[59, null], [60, 'context_soft_limit'], [75, 'context_hard_limit'], [110, 'context_hard_limit']]) {
|
|
13
|
+
assert.equal(contextRotation({ usedTokens, windowTokens: 100 }, 1, policy).reason, reason);
|
|
14
|
+
}
|
|
15
|
+
assert.equal(contextRotation({ usedTokens: NaN, windowTokens: 100 }, 3, policy).reason, 'bounded_tick_limit');
|
|
16
|
+
assert.throws(() => contextPolicy({ contextBudget: { softRatio: 0.8, hardRatio: 0.7 } }));
|
|
17
|
+
assert.throws(() => contextPolicy({ sessionMaxTicks: 0 }));
|
|
18
|
+
assert.equal(openClawContextUsage({ result: { meta: { agentMeta: { contextTokens: 100, usage: { input: 90 } } } } }), null, 'aggregate usage is not context occupancy');
|
|
19
|
+
const usage = openClawContextUsage({ result: { meta: { agentMeta: { contextTokens: 100, lastCallUsage: { input: 20, cacheRead: 40, cacheWrite: 15 } } } } });
|
|
20
|
+
assert.equal(usage.usedTokens, 60, 'cache reads count once; writes are not added again');
|
|
21
|
+
assert.equal(dispatchFailureClassification({ exitCode: 0, stdout: 'Implemented context_length_exceeded handling' }).category, 'ok');
|
|
22
|
+
assert.equal(dispatchFailureClassification({ exitCode: 1, stderr: 'context_length_exceeded' }).category, 'context_overflow');
|
|
23
|
+
assert.equal(dispatchFailureClassification({ exitCode: 1, stderr: 'Permission denied; context_length_exceeded' }).requiresHumanAction, true);
|
|
24
|
+
|
|
25
|
+
const roots = [];
|
|
26
|
+
try {
|
|
27
|
+
for (const scenario of ['yield', 'stale', 'malformed', 'missing-checkpoint', 'checkpoint-gate', 'pending-action', 'overflow', 'human-error', 'oversized', 'project-soft', 'project-hard', 'project-no-usage', 'terminal', 'pending-action-overflow', 'checkpoint-gate-overflow', 'stale-overflow', 'malformed-overflow', 'yield-overflow', 'yield-human-error', 'pending-action-failure']) {
|
|
28
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-context-'));
|
|
29
|
+
roots.push(root);
|
|
30
|
+
const worker = path.join(root, 'worker.mjs');
|
|
31
|
+
await writeFile(worker, `import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
32
|
+
import path from 'node:path';
|
|
33
|
+
const e = process.env;
|
|
34
|
+
const original = ${JSON.stringify(scenario)};
|
|
35
|
+
const scenario = original.replace(/-(overflow|human-error|failure)$/, '');
|
|
36
|
+
if (scenario === 'overflow' || scenario === 'human-error') {
|
|
37
|
+
console.error(scenario === 'human-error' ? 'Permission denied; context_length_exceeded' : 'context_length_exceeded');
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
|
|
41
|
+
const checkpoint = path.join(e.LOOP_CHECKPOINTS_DIR, e.LOOP_RUN_ID + '.json');
|
|
42
|
+
if (scenario.startsWith('project-') || scenario === 'terminal') {
|
|
43
|
+
const plan = JSON.parse(await readFile(e.LOOP_DEV_PLAN_FILE, 'utf8'));
|
|
44
|
+
for (const cp of plan.checkpoints) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, cp.id + '.json'), JSON.stringify({ version: 1, task_id: e.LOOP_TASK_ID, checkpoint_id: cp.id, status: 'ready_for_acceptance', summary: 'Read-only inspection verified', files_changed: [], verification: [{ command: 'read-only inspection', outcome: 'passed' }], blockers: [], risks: [], next_action: 'continue local inspection', ...(scenario === 'terminal' ? {} : { project_completion: { status: 'in_progress' } }) }));
|
|
45
|
+
if (scenario !== 'project-no-usage') await writeFile(e.LOOP_CONTEXT_USAGE_FILE, JSON.stringify({ version: 1, taskId: e.LOOP_TASK_ID, runId: e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), usage: { usedTokens: scenario === 'project-soft' ? 60 : 80, windowTokens: 100 } }));
|
|
46
|
+
process.exit(0);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (scenario !== 'missing-checkpoint') await writeFile(checkpoint, JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: e.LOOP_RUN_ID, status: scenario === 'checkpoint-gate' ? 'needs_human_input' : 'in_progress', summary: 'bounded progress', blockers: scenario === 'checkpoint-gate' ? ['Need approval'] : [], verification: [], risks: [], next_action: 'continue' }));
|
|
50
|
+
const handoff = { version: 1, taskId: e.LOOP_TASK_ID, runId: scenario === 'stale' ? 'old-run' : e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), reason: 'context_budget', checkpoint, summary: 'progress', completed: ['read source'], remaining: ['verify changes'], evidence: [checkpoint], nextAction: 'inspect test', authority: 'local only', pendingActions: scenario === 'pending-action' ? ['unknown payment outcome'] : [], blockers: [] };
|
|
51
|
+
await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, scenario === 'malformed' ? '{' : scenario === 'oversized' ? ' '.repeat(17000) : JSON.stringify(handoff));
|
|
52
|
+
if (original !== scenario) { console.error(original.endsWith('-human-error') ? 'Permission denied; context_length_exceeded' : original.endsWith('-failure') ? 'generic failure' : 'context_length_exceeded'); process.exitCode = 1; }
|
|
53
|
+
`);
|
|
54
|
+
await enqueueTask(root, { queue: 'test', title: scenario, task: 'Inspect a local file, then continue verification.' });
|
|
55
|
+
const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3, runtimeRecoveryMaxAttempts: 2 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
56
|
+
const first = await runQueueOnce(root, options);
|
|
57
|
+
assert.equal(first.run.dispatchAttempts.length, 1, 'context failures must not retry the old session');
|
|
58
|
+
if (scenario.startsWith('project-')) {
|
|
59
|
+
assert.equal(first.status, 'project_in_progress', JSON.stringify(first.run.finalJudgement));
|
|
60
|
+
const task = JSON.parse(await readFile(path.join(root, first.taskPath), 'utf8'));
|
|
61
|
+
if (scenario === 'project-no-usage') {
|
|
62
|
+
assert.equal(task.runtimeSessionGeneration ?? 0, 0);
|
|
63
|
+
await runQueueOnce(root, options);
|
|
64
|
+
const third = await runQueueOnce(root, options);
|
|
65
|
+
const rotated = JSON.parse(await readFile(path.join(root, third.taskPath), 'utf8'));
|
|
66
|
+
assert.equal(rotated.runtimeSessionGeneration, 1);
|
|
67
|
+
assert.equal(rotated.sessionRotationReason, 'bounded_tick_limit');
|
|
68
|
+
} else {
|
|
69
|
+
assert.equal(task.runtimeSessionGeneration, 1);
|
|
70
|
+
assert.equal(task.sessionRotationReason, scenario === 'project-soft' ? 'context_soft_limit' : 'context_hard_limit');
|
|
71
|
+
}
|
|
72
|
+
} else if (scenario === 'terminal') {
|
|
73
|
+
assert.equal(first.status, 'completed');
|
|
74
|
+
assert.equal((await runQueueOnce(root, options)).processed, false, 'high token usage cannot replay completed work');
|
|
75
|
+
} else if (['yield', 'overflow', 'yield-overflow'].includes(scenario)) {
|
|
76
|
+
assert.equal(first.status, 'runtime_interrupted', scenario);
|
|
77
|
+
const task = JSON.parse(await readFile(path.join(root, first.taskPath), 'utf8'));
|
|
78
|
+
assert.equal(task.runtimeSessionGeneration, 1);
|
|
79
|
+
assert.equal(task.sessionTickCount, 0);
|
|
80
|
+
if (scenario === 'yield') assert.ok(task.contextHandoffFile);
|
|
81
|
+
const second = await runQueueOnce(root, options);
|
|
82
|
+
assert.equal(second.status, 'runtime_interrupted');
|
|
83
|
+
const third = await runQueueOnce(root, options);
|
|
84
|
+
assert.equal(third.status, 'runtime_blocked', 'recovery is bounded');
|
|
85
|
+
} else if (['pending-action', 'checkpoint-gate', 'human-error', 'pending-action-overflow', 'checkpoint-gate-overflow', 'yield-human-error', 'pending-action-failure'].includes(scenario)) {
|
|
86
|
+
assert.equal(first.status, 'needs_human_input', scenario);
|
|
87
|
+
assert.equal((await runQueueOnce(root, options)).processed, false, 'blocked work cannot auto-replay');
|
|
88
|
+
} else assert.equal(first.status, 'runtime_blocked', scenario);
|
|
89
|
+
if (scenario !== 'terminal') assert.notEqual(first.status, 'completed');
|
|
90
|
+
if (scenario === 'oversized') assert.equal(await readBoundedJson(path.join(root, 'nonexistent')), null);
|
|
91
|
+
}
|
|
92
|
+
// A durable blocker must survive the window before handoff creation.
|
|
93
|
+
for (const chronology of ['single', 'arbitrary-id', 'id-restart', 'missing', 'conflict', 'terminal']) {
|
|
94
|
+
for (const failure of ['overflow', 'abandoned', 'exhausted', 'ordinary', 'ordinary-single']) {
|
|
95
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-context-no-handoff-'));
|
|
96
|
+
roots.push(root);
|
|
97
|
+
const worker = path.join(root, 'worker.mjs');
|
|
98
|
+
await writeFile(worker, `import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
99
|
+
import path from 'node:path';
|
|
100
|
+
const e = process.env;
|
|
101
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
|
|
102
|
+
const plan = JSON.parse(await readFile(e.LOOP_DEV_PLAN_FILE, 'utf8'));
|
|
103
|
+
const chronology = ${JSON.stringify(chronology)};
|
|
104
|
+
const oldId = chronology === 'id-restart' ? 'cp99' : 'cp1';
|
|
105
|
+
const newId = chronology === 'id-restart' ? 'cp1' : 'progress-latest';
|
|
106
|
+
if (chronology !== 'single') await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, oldId + '.json'), JSON.stringify({ task_id: e.LOOP_TASK_ID, checkpoint_id: oldId, sequence: chronology === 'missing' ? undefined : chronology === 'conflict' ? 3 : 1, created_at: chronology === 'missing' ? undefined : '2026-10-23T00:00:00Z', status: chronology === 'terminal' ? 'ready_for_acceptance' : 'in_progress', project_completion: chronology === 'terminal' ? { status: 'complete' } : undefined, summary: 'Old progress', blockers: [], risks: [], verification: chronology === 'terminal' ? [{ command: 'mock check', outcome: 'passed' }] : [] }));
|
|
107
|
+
for (const cp of plan.checkpoints) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, (chronology === 'single' ? cp.id : newId) + '.json'), JSON.stringify({ version: 1, task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: chronology === 'single' ? cp.id : newId, sequence: chronology === 'missing' ? undefined : 2, created_at: chronology === 'missing' ? undefined : '2026-10-23T00:01:00Z', project_completion: chronology === 'terminal' ? { status: 'needs_human_acceptance' } : undefined, status: 'needs_human_input', summary: 'External outcome unknown', files_changed: [], verification: [], blockers: ['Payment outcome unknown; reconcile before replay'], risks: [], next_action: 'Wait for human confirmation' }));
|
|
108
|
+
console.error(${JSON.stringify(failure === 'abandoned' ? '"kind": "incomplete_turn"' : failure.startsWith('ordinary') ? 'generic worker failure' : 'context_length_exceeded')});
|
|
109
|
+
process.exitCode = ${failure === 'abandoned' ? 0 : 1};`);
|
|
110
|
+
await enqueueTask(root, { queue: 'test', title: 'blocker before handoff', task: 'Inspect local mocked data' });
|
|
111
|
+
const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: failure === 'ordinary-single' ? 1 : 3, runtimeRecoveryMaxAttempts: failure === 'exhausted' ? 0 : 2 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
112
|
+
const result = await runQueueOnce(root, options);
|
|
113
|
+
assert.equal(result.run.acceptanceReviews.blocked, 1);
|
|
114
|
+
assert.equal(result.run.finalJudgement.outcome, 'blocked');
|
|
115
|
+
assert.equal(result.status, 'needs_human_input', failure);
|
|
116
|
+
assert.equal(result.run.revisionRequest, null, 'human blockers must not create development revisions');
|
|
117
|
+
assert.equal(result.run.dispatchAttempts.length, 1);
|
|
118
|
+
const task = JSON.parse(await readFile(path.join(root, result.taskPath), 'utf8'));
|
|
119
|
+
assert.equal(task.runtimeSessionGeneration ?? 0, 0, 'blocked work must not rotate');
|
|
120
|
+
assert.equal(task.runtimeRecoveryCount ?? 0, 0, 'blocked work must not consume recovery');
|
|
121
|
+
assert.equal((await runQueueOnce(root, options)).processed, false, 'no replay without a handoff either');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// After one legitimate recovery, newly durable blockers stop the next run.
|
|
125
|
+
for (const failure of ['ordinary', 'overflow']) {
|
|
126
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-recovered-blocker-'));
|
|
127
|
+
roots.push(root);
|
|
128
|
+
const worker = path.join(root, 'worker.mjs');
|
|
129
|
+
await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
|
|
130
|
+
import path from 'node:path';
|
|
131
|
+
const e = process.env;
|
|
132
|
+
if (Number(e.LOOP_SESSION_GENERATION) > 0) {
|
|
133
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
|
|
134
|
+
for (const [id, sequence, blockers] of [['cp99', 1, []], ['progress-latest', 2, ['Unknown payment outcome']]]) await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, id + '.json'), JSON.stringify({task_id:e.LOOP_TASK_ID, checkpoint_id:id, sequence, status:blockers.length ? 'needs_human_input' : 'in_progress', blockers, risks:[], verification:[]}));
|
|
135
|
+
}
|
|
136
|
+
console.error(Number(e.LOOP_SESSION_GENERATION) > 0 && ${JSON.stringify(failure)} === 'ordinary' ? 'generic failure' : 'context_length_exceeded');
|
|
137
|
+
process.exitCode = 1;`);
|
|
138
|
+
await enqueueTask(root, { queue: 'test', title: 'recovered blocker', task: 'Inspect mocked local data' });
|
|
139
|
+
const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
140
|
+
assert.equal((await runQueueOnce(root, options)).status, 'runtime_interrupted');
|
|
141
|
+
const result = await runQueueOnce(root, options);
|
|
142
|
+
assert.equal(result.status, 'needs_human_input');
|
|
143
|
+
assert.equal(result.run.dispatchAttempts.length, 1);
|
|
144
|
+
assert.equal(result.run.revisionRequest, null);
|
|
145
|
+
const task = JSON.parse(await readFile(path.join(root, result.taskPath), 'utf8'));
|
|
146
|
+
assert.equal(task.runtimeSessionGeneration, 1);
|
|
147
|
+
assert.equal(task.runtimeRecoveryCount, 1);
|
|
148
|
+
assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
149
|
+
}
|
|
150
|
+
// Cancellation takes precedence even with a blocker and invalid handoff.
|
|
151
|
+
{
|
|
152
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-cancel-blocker-'));
|
|
153
|
+
roots.push(root);
|
|
154
|
+
const worker = path.join(root, 'worker.mjs');
|
|
155
|
+
const marker = path.join(root, 'ready');
|
|
156
|
+
await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
|
|
157
|
+
import path from 'node:path';
|
|
158
|
+
const e = process.env;
|
|
159
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, {recursive:true});
|
|
160
|
+
await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, 'pending.json'), JSON.stringify({ task_id:e.LOOP_TASK_ID, checkpoint_id:'pending', status:'needs_human_input', blockers:['Unknown outcome'] }));
|
|
161
|
+
await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, '{}');
|
|
162
|
+
await writeFile(${JSON.stringify(marker)}, 'ready');
|
|
163
|
+
setInterval(() => {}, 1000);`);
|
|
164
|
+
const queued = await enqueueTask(root, { queue: 'test', title: 'cancel blocker', task: 'Inspect mocked local data' });
|
|
165
|
+
const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, timeoutMs: 5000, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
166
|
+
const running = runQueueOnce(root, options);
|
|
167
|
+
let ready = false;
|
|
168
|
+
for (let i = 0; i < 200 && !ready; i++) {
|
|
169
|
+
ready = await readFile(marker, 'utf8').then(() => true, () => false);
|
|
170
|
+
if (!ready) await new Promise(resolve => setTimeout(resolve, 10));
|
|
171
|
+
}
|
|
172
|
+
assert.equal(ready, true);
|
|
173
|
+
await queueCancel(root, 'test', queued.task.id, { includeActive: true, reason: 'cancel regression' });
|
|
174
|
+
const result = await running;
|
|
175
|
+
assert.equal(result.status, 'superseded');
|
|
176
|
+
assert.equal(result.run.dispatchAttempts.length, 1);
|
|
177
|
+
assert.equal(result.run.revisionRequest, null);
|
|
178
|
+
assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
179
|
+
}
|
|
180
|
+
// Ordinary failures still retry without blockers, or after a later snapshot
|
|
181
|
+
// resolves a historical blocker. Test through the real dispatch loop.
|
|
182
|
+
for (const scenario of ['absent', 'resolved']) {
|
|
183
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-retry-control-'));
|
|
184
|
+
roots.push(root);
|
|
185
|
+
const worker = path.join(root, 'worker.mjs');
|
|
186
|
+
await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
|
|
187
|
+
import path from 'node:path';
|
|
188
|
+
const e = process.env;
|
|
189
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
|
|
190
|
+
if (${JSON.stringify(scenario)} === 'resolved') {
|
|
191
|
+
for (const [id, blockers] of [['cp1', ['Await approval']], ['cp2', []]]) {
|
|
192
|
+
await writeFile(path.join(e.LOOP_CHECKPOINTS_DIR, id + '.json'), JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: id, sequence: id === 'cp1' ? 1 : 2, status: blockers.length ? 'needs_human_input' : 'in_progress', summary: 'Local progress', blockers, verification: [], risks: [], next_action: 'Continue local verification' }));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
console.error('generic worker failure');
|
|
196
|
+
process.exitCode = 1;`);
|
|
197
|
+
await enqueueTask(root, { queue: 'test', title: scenario, task: 'Inspect local mocked data' });
|
|
198
|
+
const result = await runQueueOnce(root, { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 });
|
|
199
|
+
assert.equal(result.run.dispatchAttempts.length, 3, scenario);
|
|
200
|
+
assert.equal(result.status, 'failed', scenario);
|
|
201
|
+
assert.equal(result.run.finalJudgement.outcome, 'needs_revision', scenario);
|
|
202
|
+
}
|
|
203
|
+
// Exercise the real output observer in a subprocess: no unbounded parse
|
|
204
|
+
// buffer, byte-for-byte full logs, bound usage report and clipped runner tail.
|
|
205
|
+
for (const scenario of ['json', 'oversized-output']) {
|
|
206
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-context-output-'));
|
|
207
|
+
roots.push(root);
|
|
208
|
+
const observer = path.join(root, 'observer.mjs');
|
|
209
|
+
const output = scenario === 'json' ? JSON.stringify({ result: { meta: { agentMeta: { contextTokens: 100, lastCallUsage: { input: 20, cacheRead: 40 } } } } }) : 'x'.repeat(2 * 1024 * 1024 + 1);
|
|
210
|
+
const outputFile = path.join(root, 'output.txt');
|
|
211
|
+
await writeFile(outputFile, output);
|
|
212
|
+
await writeFile(observer, `import { spawn } from 'node:child_process';
|
|
213
|
+
import { observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
|
|
214
|
+
const child = spawn(process.execPath, ['-e', 'process.stdout.write(require("node:fs").readFileSync(process.argv[1]))', ${JSON.stringify(outputFile)}], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
215
|
+
process.exitCode = await observeOpenClawWorker(child);`);
|
|
216
|
+
const usageFile = path.join(root, 'usage.json');
|
|
217
|
+
const result = spawnSync(process.execPath, [observer], { encoding: 'utf8', env: { ...process.env, LOOP_CONTEXT_USAGE_FILE: usageFile, LOOP_WORKER_OUTPUT_PREFIX: path.join(root, 'worker'), LOOP_TASK_ID: 't', LOOP_RUN_ID: 'r', LOOP_SESSION_GENERATION: '2', LOOP_ATTEMPT: '1' } });
|
|
218
|
+
assert.equal(result.status, 0, result.stderr);
|
|
219
|
+
assert.equal(await readFile(path.join(root, 'worker.stdout.log'), 'utf8'), output);
|
|
220
|
+
assert.ok(Buffer.byteLength(result.stdout) <= 16384);
|
|
221
|
+
const report = JSON.parse(await readFile(usageFile, 'utf8'));
|
|
222
|
+
assert.equal(report.generation, 2);
|
|
223
|
+
assert.equal(report.attempt, 1);
|
|
224
|
+
assert.equal(report.usage?.usedTokens ?? null, scenario === 'json' ? 60 : null);
|
|
225
|
+
}
|
|
226
|
+
// Real observer + real queue: early human signals cannot be lost to tail
|
|
227
|
+
// clipping, even across chunks/UTF-8 boundaries or with custom retry policy.
|
|
228
|
+
for (const [signal, channel, retry] of [
|
|
229
|
+
['Permission denied', 'stderr', {}],
|
|
230
|
+
['需要用户确认', 'stdout', {}],
|
|
231
|
+
['CUSTOM_APPROVAL', 'stderr', { requiresHumanActionPatterns: ['CUSTOM_APPROVAL'] }],
|
|
232
|
+
['context_length_exceeded', 'stderr', {}]
|
|
233
|
+
]) {
|
|
234
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-context-signals-'));
|
|
235
|
+
roots.push(root);
|
|
236
|
+
const worker = path.join(root, 'worker.mjs');
|
|
237
|
+
await writeFile(worker, `import { spawn } from 'node:child_process';
|
|
238
|
+
import { observeOpenClawWorker } from ${JSON.stringify(new URL('../lib/context-budget.mjs', import.meta.url).href)};
|
|
239
|
+
const child = spawn(process.execPath, ['-e', ${JSON.stringify(`const bytes = Buffer.from(${JSON.stringify(signal)}); (async () => { for (const byte of bytes) { process.${channel}.write(Buffer.from([byte])); await new Promise(r => setTimeout(r, 2)); } process.${channel}.write('x'.repeat(100000)); process.stderr.write('context_length_exceeded'); process.exitCode = 1; })();`)}], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
240
|
+
process.exitCode = await observeOpenClawWorker(child);`);
|
|
241
|
+
await enqueueTask(root, { queue: 'test', title: 'signal preservation', task: 'Inspect local source' });
|
|
242
|
+
const options = { queue: 'test', dispatcher: `node '${worker}'`, retry: { maxAttempts: 3, ...retry }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
243
|
+
const result = await runQueueOnce(root, options);
|
|
244
|
+
assert.equal(result.status, signal === 'context_length_exceeded' ? 'runtime_interrupted' : 'needs_human_input');
|
|
245
|
+
assert.equal(result.run.dispatchAttempts.length, 1);
|
|
246
|
+
if (signal !== 'context_length_exceeded') assert.equal((await runQueueOnce(root, options)).processed, false);
|
|
247
|
+
}
|
|
248
|
+
console.log('Context budget: thresholds, telemetry, handoff binding, gates, overflow and bounded recovery passed.');
|
|
249
|
+
} finally { await Promise.all(roots.map(root => rm(root, { recursive: true, force: true }))); }
|