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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Operator Dashboard and projection API
|
|
2
2
|
|
|
3
|
-
P3 provides a local-first
|
|
3
|
+
P3 provides a local-first view over durable Loop Engineering artifacts. The projection itself is read-only; the only mutation is the authenticated Human Gate command endpoint described below. It does not maintain a database, lock queue state, or write beneath `runtime/loops`. Every live request rebuilds a normalized projection; static export writes only to the explicitly selected output directory.
|
|
4
4
|
|
|
5
5
|
## Commands
|
|
6
6
|
|
|
@@ -12,9 +12,20 @@ loop-engineering dashboard-export --output-dir /tmp/loop-dashboard --root /path/
|
|
|
12
12
|
loop-engineering dashboard-serve --root /path/to/workspace
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
`dashboard-serve` binds to `127.0.0.1` and an ephemeral port by default. A wider bind is rejected unless `--allow-non-loopback` is explicit.
|
|
15
|
+
`dashboard-serve` binds to `127.0.0.1` and an ephemeral port by default. A wider bind is rejected unless `--allow-non-loopback` is explicit. Read endpoints have no login and are intended for trusted local or Tailnet use. On a loopback bind the server answers only requests whose `Host` is `127.0.0.1`, `localhost` or `[::1]` with its port, so a DNS-rebinding web page cannot read or drive it; add other names with `--allowed-host name:port`.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
### Human Gate commands
|
|
18
|
+
|
|
19
|
+
`POST /api/v1/gate-commands` approves, rejects or requests revision of a Human Gate through `executeGateCommand`. It is disabled until an operator is registered:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
loop-engineering dashboard-operator-add --actor-id alice --root /path/to/workspace
|
|
23
|
+
loop-engineering dashboard-operator-remove --actor-id alice --root /path/to/workspace
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`dashboard-operator-add` prints a random token once and stores only its SHA-256 digest in `configs/loops/dashboard-operators.json`; running it again rotates the token. Requests must send `Content-Type: application/json` and `Authorization: Bearer <token>`. The acting identity is the operator bound to the token; any `actor_id` in the request body is ignored, so the gate's `allowed_actors` check applies to the authenticated operator. Gate evidence returned by `/api/v1/gates` is redacted like the rest of the projection.
|
|
27
|
+
|
|
28
|
+
The OpenClaw and Hermes integration installers also install a Dashboard service on port `4174` and systemd gateway drop-ins. Starting `openclaw-gateway.service` or `hermes-gateway.service` therefore starts the Dashboard. The default `localhost` mode binds only `127.0.0.1`. Optional `tailscale` mode resolves `tailscale ip -4` at install time and binds only that Tailnet address; it never binds `0.0.0.0`. Tailnet access to the read endpoints is governed by Tailscale ACLs/Grants; Human Gate commands additionally require an operator token.
|
|
18
29
|
|
|
19
30
|
```bash
|
|
20
31
|
loop-engineering-dashboard-autostart-install --root /path/to/workspace
|
|
@@ -33,11 +44,11 @@ This creates `loop-engineering-dashboard.service` on fixed port `4174` and syste
|
|
|
33
44
|
|
|
34
45
|
The platform installers expose the same choice as `--dashboard-listen localhost|tailscale` and accept `--tailscale-bin` when the CLI is outside `PATH`.
|
|
35
46
|
|
|
36
|
-
Endpoints are `GET /api/v1/overview`, `/api/v1/health`, `/api/v1/projects`, `/api/v1/projects/:id`, `/api/v1/todos`, `/api/v1/todos/:id`,
|
|
47
|
+
Endpoints are `GET /api/v1/overview`, `/api/v1/health`, `/api/v1/projects`, `/api/v1/projects/:id`, `/api/v1/todos`, `/api/v1/todos/:id`, `/api/v1/actions`, `/api/v1/gates`, and the authenticated `POST /api/v1/gate-commands`. Overview and todo lists support `q` and `state` filters. Private raw files are not served.
|
|
37
48
|
|
|
38
49
|
The browser workspace leads with projects rather than queue rows. A project card keeps milestone progress separate from terminal acceptance; project detail exposes the terminal outcome/rules, milestone acceptance, checkpoint revision lineage, human gates, reservations, acceptance reviews, and the independent final-judge event. Task workspaces are linked to a project only by explicit `checkpoint.project_id`, so the projection does not guess ownership from names. Unlinked tasks remain available in `task_workspaces` and the operational queue.
|
|
39
50
|
|
|
40
|
-
The interface is responsive down to a narrow phone viewport, keyboard-operable for project selection, dependency-free, and safe for static export.
|
|
51
|
+
The interface is responsive down to a narrow phone viewport, keyboard-operable for project selection, dependency-free, and safe for static export. Apart from operator-token Human Gate decisions, it has no retry, settle, resume, or other mutation controls.
|
|
41
52
|
|
|
42
53
|
## Projection and security rules
|
|
43
54
|
|
|
@@ -17,13 +17,13 @@ No single page, milestone, checkpoint, or passing test subset completes this pro
|
|
|
17
17
|
- Terminal contract, milestone and project status: milestone 1 projection/API/UI tests.
|
|
18
18
|
- Revision lineage and acceptance/final-judge timeline: milestone 1 task workspace fixtures.
|
|
19
19
|
- Human gates and external-action reservations: milestones 1–2 projection and inspection views.
|
|
20
|
-
- Safe read-only
|
|
20
|
+
- Safe boundary: read-only projection; the only mutation is operator-token Human Gate commands through `executeGateCommand`; loopback default with Host checking, explicit non-loopback override, redaction, XSS/path traversal checks.
|
|
21
21
|
- Information architecture, interaction and responsive UI: milestones 1–2.
|
|
22
22
|
- Tests, documentation and release-level acceptance: milestones 1–3.
|
|
23
23
|
|
|
24
24
|
## Explicit boundaries
|
|
25
25
|
|
|
26
|
-
The workspace does not
|
|
26
|
+
The workspace approves or rejects Human Gates only for an authenticated operator (see `docs/operator-dashboard.md`). It does not resume tasks, settle reservations, modify contracts, repair artifacts, or serve arbitrary evidence files. Those actions remain in governed CLI/control-plane workflows. A future authenticated mutation product would require a separate authority model and project contract.
|
|
27
27
|
|
|
28
28
|
## Project completion rule
|
|
29
29
|
|
|
@@ -27,8 +27,15 @@ error rate, and recovery time remain independently reviewable.
|
|
|
27
27
|
simulated I/O. The boundary is explicit: fixtures prove adapter compatibility,
|
|
28
28
|
not availability of a real gateway or provider.
|
|
29
29
|
4. Evidence schema v1 supports baselines and metric deltas, threshold failures
|
|
30
|
-
with attribution,
|
|
31
|
-
|
|
30
|
+
with attribution, an integrity seal, credential-shaped field redaction
|
|
31
|
+
(including camelCase keys such as `accessToken` and `Authorization`), and a
|
|
32
|
+
minimized public summary. Offline reruns require no network or secret. The
|
|
33
|
+
`passed` verdict is recomputed from thresholds, scenarios and compatibility
|
|
34
|
+
when sealing and when summarizing, so it cannot be asserted by hand. Without a
|
|
35
|
+
key the seal is a plain SHA-256 digest: it detects accidental corruption, but
|
|
36
|
+
anyone who can edit the file can recompute it. Set `LOOP_EVIDENCE_HMAC_KEY`
|
|
37
|
+
(or pass `{ key }`) to seal with HMAC-SHA-256; verifying such a report then
|
|
38
|
+
requires the same key and a forged report cannot be re-sealed without it.
|
|
32
39
|
5. GitHub CI template/artifact upload and badge markup are release candidates;
|
|
33
40
|
no workflow is published in this local task. Doctor and dashboard project the
|
|
34
41
|
latest evidence state without mutating it.
|
|
@@ -12,7 +12,9 @@ loop-engineering doctor --id demo
|
|
|
12
12
|
|
|
13
13
|
## Transaction model
|
|
14
14
|
|
|
15
|
-
Every mutation enters `TransactionalStateKernel.transact` with typed effects. Writers hold an exclusive lease, receive a monotonically increasing fencing token, and may provide `expectedGeneration` for compare-and-swap. Each new effect produces a receipt containing its digest and the previous receipt hash. State records the receipt head and exact effect keys, so replay applies the same logical effect zero or one times.
|
|
15
|
+
Every mutation enters `TransactionalStateKernel.transact` with typed effects. Writers hold an exclusive lease, receive a monotonically increasing fencing token, and may provide `expectedGeneration` for compare-and-swap. Each new effect produces a receipt containing its digest and the previous receipt hash. State records the receipt head and exact effect keys, so replay applies the same logical effect zero or one times. Fencing tokens are persisted when a lease is issued, so no two leases share a token and a released lease cannot commit.
|
|
16
|
+
|
|
17
|
+
`replayEffect(effect, execute)` holds the writer lease from the applied-effect check through the commit, so concurrent callers wait and then receive the existing receipt. Before `execute` runs, an intent is stored in `pending_effects`; if the process dies before the commit, a later `replayEffect` returns `reconcileRequired: true` instead of executing again. Settle it with `reconcileEffect(effect, { executed: true, outcome })` once the upstream result is known, or `{ executed: false }` to allow a retry.
|
|
16
18
|
|
|
17
19
|
Completion is fenced. Its validator must accept the complete terminal contract; a successful milestone alone cannot set `completed`. Human gates, revisions, action reservations, evidence, and completion are effect types rather than replacement state machines, so existing queue and reservation artifacts remain compatible.
|
|
18
20
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, 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 { createHash, randomUUID } from 'node:crypto';
|
|
4
5
|
import { migrateActionReservation } from './execution-ledger.mjs';
|
|
5
6
|
|
|
@@ -44,35 +45,15 @@ async function atomicWrite(file, value) {
|
|
|
44
45
|
await rename(temp, file);
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
async function acquireMutex(lock, timeoutMs = 5000) {
|
|
48
|
-
const deadline = Date.now() + timeoutMs;
|
|
49
|
-
while (true) {
|
|
50
|
-
try {
|
|
51
|
-
await mkdir(lock);
|
|
52
|
-
await writeFile(path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, created_at: new Date().toISOString() }));
|
|
53
|
-
return;
|
|
54
|
-
} catch (error) {
|
|
55
|
-
if (error.code !== 'EEXIST') throw error;
|
|
56
|
-
const info = await stat(lock).catch(() => null);
|
|
57
|
-
if (info && Date.now() - info.mtimeMs > 30_000) await rm(lock, { recursive: true, force: true });
|
|
58
|
-
else if (Date.now() >= deadline) throw new Error('Timed out acquiring action reservation mutex.');
|
|
59
|
-
else await new Promise((resolve) => setTimeout(resolve, 10));
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
48
|
async function mutate(root, key, operation) {
|
|
65
49
|
const location = paths(root, key);
|
|
66
50
|
await mkdir(location.dir, { recursive: true });
|
|
67
|
-
|
|
68
|
-
try {
|
|
51
|
+
return withFileMutex(location.lock, { label: 'action reservation mutex' }, async () => {
|
|
69
52
|
const record = await readJson(location.file).catch((error) => error.code === 'ENOENT' ? null : Promise.reject(error));
|
|
70
53
|
const result = await operation(record, location.file);
|
|
71
54
|
if (result.write) await atomicWrite(location.file, result.record);
|
|
72
55
|
return result.output ?? result.record;
|
|
73
|
-
}
|
|
74
|
-
await rm(location.lock, { recursive: true, force: true });
|
|
75
|
-
}
|
|
56
|
+
});
|
|
76
57
|
}
|
|
77
58
|
|
|
78
59
|
export async function reserveAction(root, input) {
|
|
@@ -129,6 +110,17 @@ function assertFence(record, token) {
|
|
|
129
110
|
if (record.state !== 'claimed' || record.claim?.fencing_token !== Number(token)) throw new Error('Stale or invalid fencing token.');
|
|
130
111
|
}
|
|
131
112
|
|
|
113
|
+
// A claim whose lease has lapsed no longer proves exclusive execution, so a
|
|
114
|
+
// late settle or release becomes an unknown outcome for an operator to
|
|
115
|
+
// reconcile. The worker's report is kept as evidence.
|
|
116
|
+
function lateOutcome(record, type, input) {
|
|
117
|
+
if (Date.parse(record.claim?.lease_expires_at ?? '') > Date.now()) return null;
|
|
118
|
+
const at = new Date().toISOString();
|
|
119
|
+
const report = { type, evidence: input.evidence ?? null, reason: input.reason ?? null, fencing_token: Number(input.fencingToken), reported_at: at };
|
|
120
|
+
const unknown = { ...record, state: 'unknown', updated_at: at, reconciliation: { required: true, reason: 'lease_expired_before_report', marked_at: at, late_report: report }, events: [...record.events, { type: 'outcome_unknown', reason: 'lease_expired_before_report', late_report: type, at }] };
|
|
121
|
+
return { write: true, record: unknown, output: { [type === 'settle' ? 'settled' : 'released']: false, reason: 'reconcile_required', record: unknown } };
|
|
122
|
+
}
|
|
123
|
+
|
|
132
124
|
export async function markActionUnknown(root, input) {
|
|
133
125
|
return mutate(root, input.idempotencyKey, async (record) => {
|
|
134
126
|
if (!record) throw new Error('Action reservation not found.');
|
|
@@ -144,6 +136,8 @@ export async function settleAction(root, input) {
|
|
|
144
136
|
if (!record) throw new Error('Action reservation not found.');
|
|
145
137
|
if (record.state === 'settled') return { write: false, output: { settled: false, duplicate: true, record } };
|
|
146
138
|
assertFence(record, input.fencingToken);
|
|
139
|
+
const late = lateOutcome(record, 'settle', input);
|
|
140
|
+
if (late) return late;
|
|
147
141
|
const at = new Date().toISOString();
|
|
148
142
|
const next = { ...record, state: 'settled', updated_at: at, authorization: { ...record.authorization, state: 'consumed', consumed_at: at }, settlement: { status: 'succeeded', evidence: input.evidence ?? null, settled_at: at, fencing_token: Number(input.fencingToken) }, reconciliation: null, events: [...record.events, { type: 'settled', fencing_token: Number(input.fencingToken), at }] };
|
|
149
143
|
return { write: true, record: next, output: { settled: true, duplicate: false, record: next } };
|
|
@@ -155,7 +149,11 @@ export async function releaseAction(root, input) {
|
|
|
155
149
|
if (!record) throw new Error('Action reservation not found.');
|
|
156
150
|
if (record.state === 'settled') throw new Error('Consumed authorization cannot be released.');
|
|
157
151
|
if (record.state === 'released') return { write: false, output: { released: false, duplicate: true, record } };
|
|
158
|
-
if (record.state === 'claimed')
|
|
152
|
+
if (record.state === 'claimed') {
|
|
153
|
+
assertFence(record, input.fencingToken);
|
|
154
|
+
const late = lateOutcome(record, 'release', input);
|
|
155
|
+
if (late) return late;
|
|
156
|
+
}
|
|
159
157
|
if (record.state === 'unknown') throw new Error('Unknown upstream outcome must be reconciled before release.');
|
|
160
158
|
const at = new Date().toISOString();
|
|
161
159
|
const next = { ...record, state: 'released', updated_at: at, authorization: { ...record.authorization, state: 'released', released_at: at }, release: { reason: requireText(input.reason, 'reason'), evidence: input.evidence ?? null, released_at: at }, events: [...record.events, { type: 'released', at }] };
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
import { DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS, DEFAULT_RECOVERABLE_RUNTIME_PATTERNS } from './dispatch-classification.mjs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createWriteStream } from 'node:fs';
|
|
5
|
+
import { finished } from 'node:stream/promises';
|
|
6
|
+
import { open, realpath, writeFile } from 'node:fs/promises';
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_CONTEXT_POLICY = Object.freeze({ softRatio: 0.60, hardRatio: 0.75, maxTicks: 3, maxHandoffBytes: 16384 });
|
|
9
|
+
export function contextPolicy(retry = {}) {
|
|
10
|
+
const c = retry.contextBudget ?? {};
|
|
11
|
+
const softRatio = c.softRatio ?? DEFAULT_CONTEXT_POLICY.softRatio;
|
|
12
|
+
const hardRatio = c.hardRatio ?? DEFAULT_CONTEXT_POLICY.hardRatio;
|
|
13
|
+
const maxTicks = retry.sessionMaxTicks ?? DEFAULT_CONTEXT_POLICY.maxTicks;
|
|
14
|
+
if (![softRatio, hardRatio].every(x => typeof x === 'number' && Number.isFinite(x)) || !(0 < softRatio && softRatio < hardRatio && hardRatio < 1)) throw new Error('Invalid context budget ratios');
|
|
15
|
+
if (!Number.isSafeInteger(maxTicks) || maxTicks < 1) throw new Error('Invalid sessionMaxTicks');
|
|
16
|
+
return { ...DEFAULT_CONTEXT_POLICY, softRatio, hardRatio, maxTicks };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// lastCallUsage is the final model request, never aggregate run usage. OpenClaw
|
|
20
|
+
// input excludes cacheRead; cacheWrite is not added (it may overlap input).
|
|
21
|
+
export function openClawContextUsage(envelope) {
|
|
22
|
+
const meta = envelope?.result?.meta?.agentMeta ?? envelope?.meta?.agentMeta;
|
|
23
|
+
const last = meta?.lastCallUsage;
|
|
24
|
+
const capacity = meta?.contextTokens;
|
|
25
|
+
const input = last?.input;
|
|
26
|
+
const cacheRead = last?.cacheRead ?? 0;
|
|
27
|
+
if (![capacity, input, cacheRead].every(x => Number.isSafeInteger(x) && x >= 0) || capacity === 0 || input + cacheRead === 0) return null;
|
|
28
|
+
return { usedTokens: input + cacheRead, windowTokens: capacity, source: 'openclaw.lastCallUsage.input+cacheRead', measurement: 'last_prompt' };
|
|
29
|
+
}
|
|
30
|
+
export function contextRotation(usage, ticks, policy) {
|
|
31
|
+
const known = usage && Number.isSafeInteger(usage.usedTokens) && usage.usedTokens > 0 && Number.isSafeInteger(usage.windowTokens) && usage.windowTokens > 0;
|
|
32
|
+
const ratio = known ? usage.usedTokens / usage.windowTokens : null;
|
|
33
|
+
const reason = ratio !== null && ratio >= policy.hardRatio ? 'context_hard_limit'
|
|
34
|
+
: ratio !== null && ratio >= policy.softRatio ? 'context_soft_limit'
|
|
35
|
+
: ticks >= policy.maxTicks ? 'bounded_tick_limit' : null;
|
|
36
|
+
return { rotate: reason !== null, reason, ratio, telemetry: known ? 'last_prompt' : 'unavailable' };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function readBoundedJson(file, maxBytes = 16384) {
|
|
40
|
+
if (!file) return null;
|
|
41
|
+
let handle;
|
|
42
|
+
try {
|
|
43
|
+
handle = await open(file, 'r');
|
|
44
|
+
if (!(await handle.stat()).isFile()) return null;
|
|
45
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
46
|
+
let bytes = 0;
|
|
47
|
+
while (bytes < buffer.length) {
|
|
48
|
+
const { bytesRead } = await handle.read(buffer, bytes, buffer.length - bytes, bytes);
|
|
49
|
+
if (!bytesRead) break;
|
|
50
|
+
bytes += bytesRead;
|
|
51
|
+
}
|
|
52
|
+
return bytes <= maxBytes ? JSON.parse(buffer.subarray(0, bytes).toString('utf8')) : null;
|
|
53
|
+
} catch { return null; }
|
|
54
|
+
finally { await handle?.close(); }
|
|
55
|
+
}
|
|
56
|
+
export function validHandoff(value, { taskId, runId, generation, attempt }) {
|
|
57
|
+
if (value?.version !== 1 || value.taskId !== taskId || value.runId !== runId || value.generation !== generation || value.attempt !== attempt || value.reason !== 'context_budget') return false;
|
|
58
|
+
if (!['summary', 'nextAction', 'authority', 'checkpoint'].every(k => typeof value[k] === 'string' && value[k].trim())) return false;
|
|
59
|
+
if (!['completed', 'remaining', 'evidence', 'pendingActions', 'blockers'].every(k => Array.isArray(value[k]) && value[k].every(x => typeof x === 'string'))) return false;
|
|
60
|
+
return value.remaining.length > 0 && value.evidence.length > 0;
|
|
61
|
+
}
|
|
62
|
+
export function contextWorkerInstructions(env = process.env) {
|
|
63
|
+
const policy = JSON.parse(env.LOOP_CONTEXT_POLICY || JSON.stringify(DEFAULT_CONTEXT_POLICY));
|
|
64
|
+
return [
|
|
65
|
+
'CONTEXT BUDGET: Work on one bounded objective this turn. Read only necessary file ranges. Keep each tool response around 8 KiB or less; put full logs in task artifacts and return paths plus short excerpts. This is a cooperative tool-output budget, not runtime enforcement.',
|
|
66
|
+
'Read the resume manifest at ' + (env.LOOP_RESUME_FILE || '(unavailable)') + ' and only the latest relevant checkpoint; never reload entire session transcripts or all historical checkpoints.',
|
|
67
|
+
'At approximately ' + Math.round(policy.softRatio * 100) + '% of the model context window, save a checkpoint and prepare handoff. At ' + Math.round(policy.hardRatio * 100) + '% stop new work and hand off. If live usage is unavailable, finish one small objective and checkpoint; do not invent token measurements.',
|
|
68
|
+
'Before repeating an external/paid/destructive operation, verify its previous outcome using durable receipts/reservations; an uncertain outcome is a blocker, never permission to replay. Preserve existing human gates and amendment versions.',
|
|
69
|
+
'If unfinished work needs a fresh session, first write a normal progress checkpoint (not ready_for_acceptance) with task_id and loop_run_id matching this run, then write JSON to ' + (env.LOOP_CONTEXT_HANDOFF_FILE || '(unavailable)') + ' and finish the turn. Never claim completion merely because you handed off.',
|
|
70
|
+
'Handoff schema (max 16 KiB): ' + JSON.stringify({ version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID, generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), reason: 'context_budget', checkpoint: 'path to the current progress checkpoint', summary: 'brief current state', completed: ['completed work'], remaining: ['remaining work'], evidence: ['checkpoint and verification paths'], nextAction: 'one concrete next step', authority: 'authorized scope and gates', pendingActions: ['uncertain external action receipts to reconcile, if any'], blockers: [] }),
|
|
71
|
+
'Use blockers for missing authority or unresolved external actions; these must stop automatic continuation. Do not put secrets or full logs in handoff files.'
|
|
72
|
+
].join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Capture CLI output outside the model conversation. The JSON parse buffer is
|
|
76
|
+
// bounded; oversized/non-JSON responses fall back to tick-based rotation.
|
|
77
|
+
export async function observeOpenClawWorker(child, env = process.env) {
|
|
78
|
+
const prefix = env.LOOP_WORKER_OUTPUT_PREFIX;
|
|
79
|
+
let capture = Buffer.alloc(0), overflow = false;
|
|
80
|
+
let outTail = Buffer.alloc(0), errTail = Buffer.alloc(0);
|
|
81
|
+
const streams = [];
|
|
82
|
+
const retry = JSON.parse(env.LOOP_DISPATCH_RETRY_JSON || '{}');
|
|
83
|
+
const patterns = [...(retry.requiresHumanActionPatterns ?? DEFAULT_REQUIRES_HUMAN_ACTION_PATTERNS),
|
|
84
|
+
...(retry.recoverableRuntimePatterns ?? DEFAULT_RECOVERABLE_RUNTIME_PATTERNS).map(entry => typeof entry === 'string' ? entry : entry.pattern)]
|
|
85
|
+
.map(String).filter(Boolean);
|
|
86
|
+
const matched = new Set();
|
|
87
|
+
const overlap = Math.max(1, ...patterns.map(pattern => pattern.length));
|
|
88
|
+
for (const [name, stream] of [['stdout', child.stdout], ['stderr', child.stderr]]) {
|
|
89
|
+
if (prefix) {
|
|
90
|
+
const log = createWriteStream(prefix + '.' + name + '.log', { mode: 0o600 });
|
|
91
|
+
stream.pipe(log);
|
|
92
|
+
log.on('error', () => { stream.unpipe(log); stream.resume(); });
|
|
93
|
+
streams.push(finished(log).catch(error => error));
|
|
94
|
+
}
|
|
95
|
+
const decoder = new StringDecoder('utf8');
|
|
96
|
+
let scanTail = '';
|
|
97
|
+
stream.on('data', chunk => {
|
|
98
|
+
// Match the entire stream before clipping. Retain only enough overlap for
|
|
99
|
+
// split signatures (including UTF-8), and emit each signature once. The
|
|
100
|
+
// parent applies exit-code rules and configured human-before-runtime priority.
|
|
101
|
+
const scan = scanTail + decoder.write(chunk).toLowerCase();
|
|
102
|
+
for (const pattern of patterns) {
|
|
103
|
+
if (!matched.has(pattern) && scan.includes(pattern.toLowerCase())) {
|
|
104
|
+
matched.add(pattern);
|
|
105
|
+
process.stderr.write('\n[worker diagnostic] ' + pattern + '\n');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
scanTail = scan.slice(-overlap);
|
|
109
|
+
|
|
110
|
+
if (name === 'stdout') {
|
|
111
|
+
outTail = Buffer.concat([outTail, chunk]).subarray(-16384);
|
|
112
|
+
if (!overflow && capture.length + chunk.length <= 2 * 1024 * 1024) capture = Buffer.concat([capture, chunk]);
|
|
113
|
+
else { overflow = true; capture = Buffer.alloc(0); }
|
|
114
|
+
} else errTail = Buffer.concat([errTail, chunk]).subarray(-16384);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const result = await new Promise(resolve => {
|
|
118
|
+
child.on('error', error => resolve({ code: 1, error: error.message }));
|
|
119
|
+
child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 128 : 1) }));
|
|
120
|
+
});
|
|
121
|
+
const logErrors = (await Promise.all(streams)).filter(Boolean);
|
|
122
|
+
if (logErrors.length) throw logErrors[0];
|
|
123
|
+
let usage = null;
|
|
124
|
+
if (!overflow) {
|
|
125
|
+
try { usage = openClawContextUsage(JSON.parse(capture.toString('utf8'))); } catch { /* unknown */ }
|
|
126
|
+
}
|
|
127
|
+
if (env.LOOP_CONTEXT_USAGE_FILE) await writeFile(env.LOOP_CONTEXT_USAGE_FILE, JSON.stringify({
|
|
128
|
+
version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID,
|
|
129
|
+
generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), usage
|
|
130
|
+
}) + '\n', { mode: 0o600 });
|
|
131
|
+
process.stdout.write(outTail);
|
|
132
|
+
process.stderr.write(errTail);
|
|
133
|
+
if (result.error) process.stderr.write(result.error + '\n');
|
|
134
|
+
return result.code;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function handoffCheckpoint(value, { root, checkpointsDir, taskId, runId }) {
|
|
138
|
+
try {
|
|
139
|
+
const base = await realpath(checkpointsDir);
|
|
140
|
+
const file = await realpath(path.resolve(root, value.checkpoint));
|
|
141
|
+
const relative = path.relative(base, file);
|
|
142
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return { valid: false };
|
|
143
|
+
const cp = await readBoundedJson(file);
|
|
144
|
+
if (!cp || cp.task_id !== taskId || cp.loop_run_id !== runId || !Array.isArray(cp.blockers)) return { valid: false };
|
|
145
|
+
return { valid: true, blocked: cp.blockers.length > 0 || ['blocked', 'needs_human_input'].includes(cp.status) };
|
|
146
|
+
} catch { return { valid: false }; }
|
|
147
|
+
}
|