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.
- package/CHANGELOG.md +54 -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/core.mjs +643 -109
- 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/dashboard-autostart-install.mjs +33 -8
- package/scripts/dashboard-autostart-self-test.mjs +12 -3
- package/scripts/final-judgement-self-test.mjs +21 -0
- 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 +47 -1
- package/scripts/openclaw-install.mjs +42 -17
- 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 +349 -0
- package/skills/taskforce-loop-engineering/SKILL.md +1 -1
package/lib/durable-journal.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { appendFile, copyFile, mkdir, open, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { withFileMutex } from './file-mutex.mjs';
|
|
4
5
|
|
|
5
6
|
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
6
7
|
const canonical = (value) => JSON.stringify(sortValue(value));
|
|
@@ -17,14 +18,30 @@ export class DurableJournal {
|
|
|
17
18
|
this.snapshotFile = path.join(directory, 'snapshot.json');
|
|
18
19
|
}
|
|
19
20
|
|
|
21
|
+
// Appends are serialized so each event chains to the true previous head. A
|
|
22
|
+
// torn final line is an event whose write never completed (append only
|
|
23
|
+
// returns after fsync), so it is cut off before the next event is written;
|
|
24
|
+
// otherwise it would end up mid-file and break every later replay.
|
|
20
25
|
async append(type, payload, transactionId = randomUUID()) {
|
|
21
26
|
await mkdir(this.directory, { recursive: true });
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
27
|
+
return withFileMutex(`${this.logFile}.lock`, { label: 'journal append mutex' }, async () => {
|
|
28
|
+
await this.#truncateTornTail();
|
|
29
|
+
const previous = (await this.replay()).lastChecksum ?? null;
|
|
30
|
+
const event = { version: 1, transactionId, type, payload, previous };
|
|
31
|
+
event.checksum = digest(canonical(event));
|
|
32
|
+
const handle = await open(this.logFile, 'a');
|
|
33
|
+
try { await handle.write(`${JSON.stringify(event)}\n`); await handle.sync(); } finally { await handle.close(); }
|
|
34
|
+
return event;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async #truncateTornTail() {
|
|
39
|
+
let raw;
|
|
40
|
+
try { raw = await readFile(this.logFile); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
41
|
+
if (!raw.length || raw[raw.length - 1] === 0x0a) return;
|
|
42
|
+
const keep = raw.lastIndexOf(0x0a) + 1;
|
|
43
|
+
const handle = await open(this.logFile, 'r+');
|
|
44
|
+
try { await handle.truncate(keep); await handle.sync(); } finally { await handle.close(); }
|
|
28
45
|
}
|
|
29
46
|
|
|
30
47
|
async replay(reducer = (state, event) => ({ ...state, [event.type]: event.payload }), initial = {}) {
|
package/lib/execution-ledger.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { withFileMutex } from './file-mutex.mjs';
|
|
5
|
+
import { redact as redactShared } from './redaction.mjs';
|
|
4
6
|
|
|
5
7
|
export const EXECUTION_LEDGER_VERSION = 2;
|
|
6
8
|
const KINDS = new Set(['llm', 'tool', 'effect']);
|
|
7
9
|
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled']);
|
|
8
|
-
const SENSITIVE = /(^|_)(secret|token|password|credential|api[_-]?key|private[_-]?key)(_|$)/i;
|
|
9
10
|
const canonicalValue = (value) => Array.isArray(value) ? value.map(canonicalValue) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalValue(value[key])])) : value;
|
|
10
11
|
const hash = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(canonicalValue(value))).digest('hex');
|
|
11
12
|
export const stepInputFingerprint = (input) => hash(input);
|
|
12
13
|
function text(value, name) { if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} must be a non-empty string.`); return value; }
|
|
13
14
|
function safeId(value, name = 'stepId') { text(value, name); if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,299}$/.test(value)) throw new Error(`${name} contains unsafe characters or is too long.`); return value; }
|
|
14
|
-
function redact(value
|
|
15
|
+
function redact(value) { return redactShared(value, { sortKeys: true }); }
|
|
15
16
|
function locations(root, stepId) { const directory = path.join(path.resolve(root), 'runtime', 'loops', 'execution-ledger'); const key = hash(safeId(stepId)); return { file: path.join(directory, 'steps', `${key}.json`), lock: path.join(directory, 'locks', key) }; }
|
|
16
17
|
async function atomicWrite(file, value) { await mkdir(path.dirname(file), { recursive: true }); const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`; await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx', mode: 0o600 }); await rename(temporary, file); }
|
|
17
|
-
async function
|
|
18
|
-
async function mutate(root, stepId, operation) { const loc = locations(root, stepId); await mkdir(path.dirname(loc.file), { recursive: true }); await mutex(loc.lock); try { const record = await readFile(loc.file, 'utf8').then(JSON.parse).catch((error) => error.code === 'ENOENT' ? null : Promise.reject(error)); const result = await operation(record); if (result.write) await atomicWrite(loc.file, result.record); return result.output ?? result.record; } finally { await rm(loc.lock, { recursive: true, force: true }); } }
|
|
18
|
+
async function mutate(root, stepId, operation) { const loc = locations(root, stepId); await mkdir(path.dirname(loc.file), { recursive: true }); return withFileMutex(loc.lock, { label: 'execution ledger mutex' }, async () => { const record = await readFile(loc.file, 'utf8').then(JSON.parse).catch((error) => error.code === 'ENOENT' ? null : Promise.reject(error)); const result = await operation(record); if (result.write) await atomicWrite(loc.file, result.record); return result.output ?? result.record; }); }
|
|
19
19
|
function event(record, type, data = {}) { const entry = { sequence: record.events.length + 1, type, at: new Date().toISOString(), ...redact(data), previous: record.events.at(-1)?.checksum ?? null }; entry.checksum = hash(entry); return entry; }
|
|
20
20
|
function assertFence(record, token) { if (record.status !== 'running' || record.lease?.fencing_token !== Number(token)) throw new Error('Stale or invalid fencing token.'); }
|
|
21
21
|
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rm, rmdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// A directory mutex shared by the control-plane modules.
|
|
6
|
+
//
|
|
7
|
+
// Holding the lock means owning the directory created by mkdir. Each holder
|
|
8
|
+
// records a random token, and release only removes a lock that still carries
|
|
9
|
+
// that token. A lock whose owner process is gone, or that is older than
|
|
10
|
+
// staleMs, may be reclaimed — but only inside a second, short-lived reclaim
|
|
11
|
+
// mutex that re-checks the token, so two waiters can never both delete a lock
|
|
12
|
+
// and both enter the critical section.
|
|
13
|
+
|
|
14
|
+
function processAlive(pid) {
|
|
15
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
16
|
+
try {
|
|
17
|
+
process.kill(pid, 0);
|
|
18
|
+
return true;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
return error?.code === 'EPERM';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function readOwner(lock) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(await readFile(path.join(lock, 'owner.json'), 'utf8'));
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function lockAgeMs(lock) {
|
|
33
|
+
const info = await stat(lock).catch(() => null);
|
|
34
|
+
return info ? Date.now() - info.mtimeMs : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function isStale(lock, staleMs) {
|
|
38
|
+
const age = await lockAgeMs(lock);
|
|
39
|
+
if (age === null) return { stale: false, gone: true };
|
|
40
|
+
const owner = await readOwner(lock);
|
|
41
|
+
// The owner file is written right after mkdir; give it a moment to appear.
|
|
42
|
+
if (!owner) return { stale: age > Math.min(staleMs, 5000), owner: null };
|
|
43
|
+
return { stale: age > staleMs || !processAlive(owner.pid), owner };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function reclaim(lock, observedOwner, staleMs) {
|
|
47
|
+
const guard = `${lock}.reclaim`;
|
|
48
|
+
try {
|
|
49
|
+
await mkdir(guard);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
52
|
+
const age = await lockAgeMs(guard);
|
|
53
|
+
if (age !== null && age > 10_000) await rmdir(guard).catch(() => {});
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const current = await isStale(lock, staleMs);
|
|
58
|
+
if (current.gone || !current.stale) return;
|
|
59
|
+
if ((current.owner?.token ?? null) !== (observedOwner?.token ?? null)) return;
|
|
60
|
+
await rm(lock, { recursive: true, force: true });
|
|
61
|
+
} finally {
|
|
62
|
+
await rmdir(guard).catch(() => {});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function acquireFileMutex(lock, { timeoutMs = 5000, staleMs = 30_000, label = 'mutex' } = {}) {
|
|
67
|
+
await mkdir(path.dirname(lock), { recursive: true });
|
|
68
|
+
const deadline = Date.now() + timeoutMs;
|
|
69
|
+
const token = randomUUID();
|
|
70
|
+
while (true) {
|
|
71
|
+
try {
|
|
72
|
+
await mkdir(lock);
|
|
73
|
+
await writeFile(path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, token, created_at: new Date().toISOString() }));
|
|
74
|
+
return { lock, token };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
77
|
+
}
|
|
78
|
+
const state = await isStale(lock, staleMs);
|
|
79
|
+
if (state.stale) {
|
|
80
|
+
await reclaim(lock, state.owner, staleMs);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (Date.now() >= deadline) throw new Error(`Timed out acquiring ${label}.`);
|
|
84
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function releaseFileMutex(handle) {
|
|
89
|
+
if (!handle) return;
|
|
90
|
+
const owner = await readOwner(handle.lock);
|
|
91
|
+
if (owner?.token !== handle.token) return;
|
|
92
|
+
await rm(handle.lock, { recursive: true, force: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function withFileMutex(lock, options, operation) {
|
|
96
|
+
const handle = await acquireFileMutex(lock, options);
|
|
97
|
+
try {
|
|
98
|
+
return await operation();
|
|
99
|
+
} finally {
|
|
100
|
+
await releaseFileMutex(handle);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -14,8 +14,10 @@ export async function handleChannelGateEvent(root, event, options = {}) {
|
|
|
14
14
|
}
|
|
15
15
|
if (event.kind === 'message_reply' && event.reply_to) {
|
|
16
16
|
const parsed = parseBoundReply(event.text); if (!parsed) return { outcome: 'ignored_untrusted_chat' };
|
|
17
|
+
const expectedGeneration = parsed.expected_generation ?? event.expected_generation;
|
|
18
|
+
if (expectedGeneration === undefined || expectedGeneration === null) return { outcome: 'generation_required', message: `Reply with the generation shown on the card, e.g. /${parsed.decision} ${parsed.gate_id}@<generation>.` };
|
|
17
19
|
const receipt = await executeGateCommand(root, {
|
|
18
|
-
...parsed, expected_generation:
|
|
20
|
+
...parsed, expected_generation: expectedGeneration, actor_id: event.actor_id,
|
|
19
21
|
source_channel: event.channel, source_message_id: event.card_message_id,
|
|
20
22
|
reply_to: event.reply_to, event_type: 'bound_reply', idempotency_key: event.event_id
|
|
21
23
|
}, options);
|
|
@@ -33,5 +35,5 @@ export function normalizeFeishuGateEvent(payload, options = {}) {
|
|
|
33
35
|
const message = payload?.event?.message;
|
|
34
36
|
let text = message?.content;
|
|
35
37
|
try { const parsed = JSON.parse(text); text = typeof parsed?.text === 'string' ? parsed.text : ''; } catch {}
|
|
36
|
-
return { kind: message?.parent_id ? 'message_reply' : 'ordinary_message', event_id: payload.header?.event_id, actor_id: payload.event?.sender?.sender_id?.open_id, channel: 'feishu', card_message_id: message?.root_id, reply_to: message?.parent_id, text
|
|
38
|
+
return { kind: message?.parent_id ? 'message_reply' : 'ordinary_message', event_id: payload.header?.event_id, actor_id: payload.event?.sender?.sender_id?.open_id, channel: 'feishu', card_message_id: message?.root_id, reply_to: message?.parent_id, text };
|
|
37
39
|
}
|
|
@@ -143,15 +143,17 @@ export async function executeGateCommand(root, command, options = {}) {
|
|
|
143
143
|
});
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
// Replies name the generation they answer (`/approve gate_x@2`), because a
|
|
147
|
+
// chat reply carries no other proof of which card version the person saw.
|
|
146
148
|
export function parseBoundReply(text) {
|
|
147
|
-
const match = String(text ?? '').trim().match(/^\/(approve|reject|request_revision)\s+(gate_[a-zA-Z0-9._:-]+)(?:\s+(.+))?$/);
|
|
149
|
+
const match = String(text ?? '').trim().match(/^\/(approve|reject|request_revision)\s+(gate_[a-zA-Z0-9._:-]+?)(?:@(\d+))?(?:\s+(.+))?$/);
|
|
148
150
|
if (!match) return null;
|
|
149
|
-
return { decision: match[1], gate_id: match[2],
|
|
151
|
+
return { decision: match[1], gate_id: match[2], expected_generation: match[3] === undefined ? undefined : Number(match[3]), reason: match[4] ?? null };
|
|
150
152
|
}
|
|
151
153
|
|
|
152
154
|
export function gateCard(gate) {
|
|
153
155
|
const g = publicGate(gate);
|
|
154
|
-
return { type: 'human_gate_card', title: `${g.project} · Human Gate`, fields: g, buttons: [...DECISIONS].map((decision) => ({ decision, gate_id: g.gate_id, expected_generation: g.generation, disabled: !['pending', 'awaiting_confirmation'].includes(g.status) })) };
|
|
156
|
+
return { type: 'human_gate_card', title: `${g.project} · Human Gate`, fields: g, buttons: [...DECISIONS].map((decision) => ({ decision, gate_id: g.gate_id, expected_generation: g.generation, reply_command: `/${decision} ${g.gate_id}@${g.generation}${decision === 'request_revision' ? ' <reason>' : ''}`, disabled: !['pending', 'awaiting_confirmation'].includes(g.status) })) };
|
|
155
157
|
}
|
|
156
158
|
|
|
157
159
|
export async function listHumanGates(root) {
|
|
@@ -1,14 +1,15 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
1
2
|
import { createServer } from 'node:http';
|
|
2
|
-
import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, readFile, readdir, rename, stat, writeFile } from 'node:fs/promises';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { executeGateCommand, listHumanGates } from './human-gate-command.mjs';
|
|
6
|
+
import { sensitiveKey } from './redaction.mjs';
|
|
5
7
|
|
|
6
8
|
export const DASHBOARD_SCHEMA_VERSION = '1.0.0';
|
|
7
|
-
const SENSITIVE = /(^|_)(secret|token|password|credential|api[_-]?key|private[_-]?key|provider)(_|$)/i;
|
|
8
9
|
const STATES = new Set(['runnable', 'active', 'parked', 'waiting_for_human', 'waiting_for_external_condition', 'timed_out_or_escalated', 'reconciliation_required', 'blocked', 'completed', 'failed']);
|
|
9
10
|
|
|
10
11
|
function clean(value, key = '') {
|
|
11
|
-
if (
|
|
12
|
+
if (sensitiveKey(key, ['provider'])) return '[REDACTED]';
|
|
12
13
|
if (Array.isArray(value)) return value.map((item) => clean(item));
|
|
13
14
|
if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((name) => [name, clean(value[name], name)]));
|
|
14
15
|
return value;
|
|
@@ -224,31 +225,92 @@ function legacyHtml(dataUrl = '/api/v1/overview?') {
|
|
|
224
225
|
|
|
225
226
|
function gateHtml(dataUrl = '/api/v1/overview?') {
|
|
226
227
|
if (dataUrl.startsWith('./')) return legacyHtml(dataUrl);
|
|
227
|
-
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Loop Engineering Human Gates</title><style>:root{color-scheme:dark}body{font:14px system-ui;max-width:1100px;margin:auto;padding:24px;background:#091018;color:#eef6fb}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px}.card{background:#111c28;border:1px solid #30465b;border-radius:14px;padding:16px}.meta{color:#9db0c2;white-space:pre-wrap}button,input{padding:9px;margin:4px;border-radius:8px;border:1px solid #4c657b;background:#162737;color:inherit}button:disabled{opacity:.45}.approve{border-color:#55bd82}.reject{border-color:#db6e74}.revision{border-color:#d8ad55}</style></head><body><h1>Loop Engineering</h1><p id="health">Loading authoritative artifacts…</p><label>
|
|
228
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Loop Engineering Human Gates</title><style>:root{color-scheme:dark}body{font:14px system-ui;max-width:1100px;margin:auto;padding:24px;background:#091018;color:#eef6fb}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px}.card{background:#111c28;border:1px solid #30465b;border-radius:14px;padding:16px}.meta{color:#9db0c2;white-space:pre-wrap}button,input{padding:9px;margin:4px;border-radius:8px;border:1px solid #4c657b;background:#162737;color:inherit}button:disabled{opacity:.45}.approve{border-color:#55bd82}.reject{border-color:#db6e74}.revision{border-color:#d8ad55}</style></head><body><h1>Loop Engineering</h1><p id="health">Loading authoritative artifacts…</p><label>Operator token <input id="actor" type="password" autocomplete="off" placeholder="from dashboard-operator-add"></label><h2>Human Gates</h2><div id="gates" class="grid"></div><h2>Workspace</h2><div id="workspace" class="grid"></div><script>const node=(tag,text,cls)=>{const n=document.createElement(tag);n.textContent=text;if(cls)n.className=cls;return n};async function decide(g,d){const binding=(g.source_bindings||[]).find(x=>x.channel==='dashboard');if(!binding)return alert('This gate has no registered Dashboard binding.');if(!actor.value)return alert('Operator token is required.');const reason=d==='request_revision'?prompt('Revision reason (required)'):null;if(d==='request_revision'&&!reason)return;const body={gate_id:g.gate_id,decision:d,expected_generation:g.generation,source_message_id:binding.message_id,reply_to:binding.reply_to,idempotency_key:crypto.randomUUID(),reason};const r=await fetch('/api/v1/gate-commands',{method:'POST',headers:{'content-type':'application/json',authorization:'Bearer '+actor.value},body:JSON.stringify(body)});const out=await r.json();if(!r.ok)return alert(out.message||out.error);alert(out.outcome+(out.outcome==='confirmation_required'?' — confirm again on generation '+out.resulting_generation:''));await draw()}async function draw(){const [overview,gs]=await Promise.all([fetch('/api/v1/overview').then(r=>r.json()),fetch('/api/v1/gates').then(r=>r.json())]);health.textContent=overview.health.status+' · Loop artifacts remain the only source of truth';workspace.replaceChildren(...[['Projects',overview.overview.project_count],['Tasks',overview.overview.task_workspace_count],['Reservations',overview.overview.action_count]].map(([k,v])=>{const n=node('div','', 'card');n.append(node('h3',k),node('strong',String(v)));return n}));gates.replaceChildren(...gs.map(g=>{const n=node('article','', 'card'),active=['pending','awaiting_confirmation'].includes(g.status);n.append(node('h3',g.project+' · '+g.task),node('p','Gate ID: '+g.gate_id+' · generation '+g.generation+' · '+g.status,'meta'),node('p','Action: '+g.action+'\nReason: '+g.reason+'\nImpact: '+g.impact+'\nRisk: '+JSON.stringify(g.risk)+'\nCost/budget: '+JSON.stringify(g.cost)+'\nEvidence: '+JSON.stringify(g.evidence)+'\nDashboard: '+(g.dashboard_url||location.href)+'\nExpiry: '+g.expiry,'meta'));for(const d of ['approve','reject','request_revision']){const b=node('button',d,d==='request_revision'?'revision':d);b.disabled=!active;b.onclick=()=>decide(g,d);n.append(b)}return n}));if(!gs.length)gates.append(node('p','No Human Gates.','card'))}draw()</script></body></html>`;
|
|
228
229
|
}
|
|
229
230
|
|
|
230
231
|
function html(dataUrl = '/api/v1/overview?') {
|
|
231
232
|
if (dataUrl.startsWith('./')) return legacyHtml(dataUrl);
|
|
232
|
-
const panel = `<section aria-labelledby="human-gates-title"><h2 id="human-gates-title">Human Gates</h2><p class="muted">Only exact card actions or card-bound commands can decide a gate.</p><label>
|
|
233
|
-
const behavior = `<script>async function gateDecision(g,d){const binding=(g.source_bindings||[]).find(x=>x.channel==='dashboard');if(!binding)return alert('No registered Dashboard binding.');if(!gateactor.value)return alert('
|
|
233
|
+
const panel = `<section aria-labelledby="human-gates-title"><h2 id="human-gates-title">Human Gates</h2><p class="muted">Only exact card actions or card-bound commands can decide a gate.</p><label>Operator token <input id="gateactor" type="password" autocomplete="off" placeholder="from dashboard-operator-add"></label><div class="projects" id="gatecards"></div></section>`;
|
|
234
|
+
const behavior = `<script>async function gateDecision(g,d){const binding=(g.source_bindings||[]).find(x=>x.channel==='dashboard');if(!binding)return alert('No registered Dashboard binding.');if(!gateactor.value)return alert('Operator token is required.');const reason=d==='request_revision'?prompt('Revision reason (required)'):null;if(d==='request_revision'&&!reason)return;const r=await fetch('/api/v1/gate-commands',{method:'POST',headers:{'content-type':'application/json',authorization:'Bearer '+gateactor.value},body:JSON.stringify({gate_id:g.gate_id,decision:d,expected_generation:g.generation,source_message_id:binding.message_id,reply_to:binding.reply_to,idempotency_key:crypto.randomUUID(),reason})}),out=await r.json();if(!r.ok)return alert(out.message||out.error);await drawHumanGates()}async function drawHumanGates(){const gs=await fetch('/api/v1/gates').then(r=>r.json());gatecards.replaceChildren(...gs.map(g=>{const n=el('article',null,'card'),active=['pending','awaiting_confirmation'].includes(g.status);n.append(el('h3',g.project+' · '+g.task),el('p','Gate ID: '+g.gate_id+' · generation '+g.generation+' · '+g.status,'muted'),el('p','Action: '+g.action+' | Reason: '+g.reason+' | Impact: '+g.impact+' | Risk: '+JSON.stringify(g.risk)+' | Cost/budget: '+JSON.stringify(g.cost)+' | Evidence: '+JSON.stringify(g.evidence)+' | Dashboard: '+(g.dashboard_url||location.href)+' | Expiry: '+g.expiry,'muted'));for(const d of ['approve','reject','request_revision']){const b=el('button',d);b.type='button';b.setAttribute('aria-pressed','false');b.disabled=!active;b.onclick=()=>gateDecision(g,d);n.append(b)}return n}));if(!gs.length)gatecards.append(el('p','No pending gates.','card empty'))}drawHumanGates()</script>`;
|
|
234
235
|
return legacyHtml(dataUrl).replace('READ-ONLY OPERATOR WORKSPACE', 'GOVERNED OPERATOR WORKSPACE').replace('</main>', `${panel}</main>`).replace('</body>', `${behavior}</body>`);
|
|
235
236
|
}
|
|
236
237
|
|
|
237
238
|
function loopback(host) { return host === '127.0.0.1' || host === '::1' || host === 'localhost'; }
|
|
238
239
|
|
|
240
|
+
// Dashboard gate commands are a mutation boundary. They are disabled unless an
|
|
241
|
+
// operator token has been registered, and the acting identity always comes
|
|
242
|
+
// from the token, never from the request body.
|
|
243
|
+
export const DASHBOARD_OPERATORS_FILE = 'configs/loops/dashboard-operators.json';
|
|
244
|
+
const tokenDigest = (token) => createHash('sha256').update(String(token)).digest('hex');
|
|
245
|
+
function operatorsPath(root, options = {}) { return path.resolve(root, options.operatorsFile ?? DASHBOARD_OPERATORS_FILE); }
|
|
246
|
+
async function readOperators(root, options) {
|
|
247
|
+
try {
|
|
248
|
+
const value = JSON.parse(await readFile(operatorsPath(root, options), 'utf8'));
|
|
249
|
+
return Array.isArray(value?.operators) ? value.operators.filter((entry) => typeof entry?.actor_id === 'string' && /^[a-f0-9]{64}$/.test(entry?.token_sha256 ?? '')) : [];
|
|
250
|
+
} catch { return []; }
|
|
251
|
+
}
|
|
252
|
+
async function writeOperators(root, options, operators) {
|
|
253
|
+
const file = operatorsPath(root, options);
|
|
254
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
255
|
+
const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
256
|
+
await writeFile(temporary, `${JSON.stringify({ version: 1, operators }, null, 2)}\n`, { mode: 0o600 });
|
|
257
|
+
await rename(temporary, file);
|
|
258
|
+
}
|
|
259
|
+
export async function addDashboardOperator(root, { actorId, ...options } = {}) {
|
|
260
|
+
const actor = safeId(actorId);
|
|
261
|
+
const token = randomBytes(32).toString('base64url');
|
|
262
|
+
const operators = (await readOperators(root, options)).filter((entry) => entry.actor_id !== actor);
|
|
263
|
+
operators.push({ actor_id: actor, token_sha256: tokenDigest(token), created_at: new Date().toISOString() });
|
|
264
|
+
await writeOperators(root, options, operators);
|
|
265
|
+
return { actor_id: actor, token, operators_file: path.relative(root, operatorsPath(root, options)) };
|
|
266
|
+
}
|
|
267
|
+
export async function removeDashboardOperator(root, { actorId, ...options } = {}) {
|
|
268
|
+
const actor = safeId(actorId);
|
|
269
|
+
const operators = await readOperators(root, options);
|
|
270
|
+
const remaining = operators.filter((entry) => entry.actor_id !== actor);
|
|
271
|
+
if (remaining.length !== operators.length) await writeOperators(root, options, remaining);
|
|
272
|
+
return { actor_id: actor, removed: remaining.length !== operators.length };
|
|
273
|
+
}
|
|
274
|
+
async function authenticatedOperator(root, options, request) {
|
|
275
|
+
const match = /^Bearer\s+(\S+)$/i.exec(String(request.headers.authorization ?? ''));
|
|
276
|
+
if (!match) return null;
|
|
277
|
+
const presented = Buffer.from(tokenDigest(match[1]), 'hex');
|
|
278
|
+
for (const entry of await readOperators(root, options)) {
|
|
279
|
+
if (timingSafeEqual(presented, Buffer.from(entry.token_sha256, 'hex'))) return entry.actor_id;
|
|
280
|
+
}
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
function sendJson(response, status, body) {
|
|
284
|
+
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
285
|
+
response.end(`${JSON.stringify(body)}\n`);
|
|
286
|
+
}
|
|
287
|
+
|
|
239
288
|
export async function createDashboardServer(root, options = {}) {
|
|
240
289
|
const host = options.host ?? '127.0.0.1'; const port = Number(options.port ?? 0);
|
|
241
290
|
if (!loopback(host) && options.allowNonLoopback !== true) throw new Error('Non-loopback dashboard bind requires --allow-non-loopback.');
|
|
291
|
+
// A loopback server must only answer requests addressed to loopback, so a
|
|
292
|
+
// DNS-rebinding page cannot read it or drive it from a victim's browser.
|
|
293
|
+
const allowedHosts = new Set((options.allowedHosts ?? []).map((value) => String(value).toLowerCase()));
|
|
294
|
+
const hostAllowed = (header) => {
|
|
295
|
+
const value = String(header ?? '').toLowerCase();
|
|
296
|
+
if (allowedHosts.has(value)) return true;
|
|
297
|
+
if (!loopback(host)) return true;
|
|
298
|
+
const port = server.address()?.port;
|
|
299
|
+
return ['127.0.0.1', 'localhost', '[::1]'].some((name) => value === `${name}:${port}`);
|
|
300
|
+
};
|
|
242
301
|
const server = createServer(async (request, response) => {
|
|
243
302
|
try {
|
|
244
303
|
const url = new URL(request.url, 'http://localhost');
|
|
245
304
|
if (url.pathname.includes('..') || /%2e/i.test(request.url)) { response.writeHead(400); return response.end('unsafe path'); }
|
|
305
|
+
if (!hostAllowed(request.headers.host)) return sendJson(response, 421, { error: 'host_not_allowed' });
|
|
246
306
|
if (request.method === 'POST' && url.pathname === '/api/v1/gate-commands') {
|
|
307
|
+
if (!/^application\/json(\s*;|$)/i.test(String(request.headers['content-type'] ?? ''))) return sendJson(response, 415, { error: 'json_required' });
|
|
308
|
+
const actor = await authenticatedOperator(root, options, request);
|
|
309
|
+
if (!actor) return sendJson(response, 401, { error: 'operator_authentication_required', message: 'Register an operator with dashboard-operator-add and send its token as a Bearer credential.' });
|
|
247
310
|
let raw = ''; for await (const chunk of request) { raw += chunk; if (raw.length > 65536) throw new Error('request_too_large'); }
|
|
248
311
|
const command = JSON.parse(raw || '{}');
|
|
249
|
-
const receipt = await executeGateCommand(root, { ...command, event_type: 'card_button', source_channel: 'dashboard' });
|
|
250
|
-
response
|
|
251
|
-
return response.end(`${JSON.stringify(receipt)}\n`);
|
|
312
|
+
const receipt = await executeGateCommand(root, { ...command, actor_id: actor, event_type: 'card_button', source_channel: 'dashboard' });
|
|
313
|
+
return sendJson(response, 200, receipt);
|
|
252
314
|
}
|
|
253
315
|
if (request.method !== 'GET' && request.method !== 'HEAD') { response.writeHead(405, { Allow: 'GET, HEAD, POST' }); return response.end(); }
|
|
254
316
|
if (url.pathname === '/') { response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; object-src 'none'; base-uri 'none'", 'x-content-type-options': 'nosniff' }); return response.end(request.method === 'HEAD' ? '' : html().replace('<p id="health">', '<p id="health" role="status" aria-live="polite">')); }
|
|
@@ -260,7 +322,7 @@ export async function createDashboardServer(root, options = {}) {
|
|
|
260
322
|
else if (url.pathname.startsWith('/api/v1/todos/')) body = projection.todos.find((item) => item.id === safeId(decodeURIComponent(url.pathname.slice('/api/v1/todos/'.length)))) ?? null;
|
|
261
323
|
else if (url.pathname === '/api/v1/actions') body = projection.actions;
|
|
262
324
|
else if (url.pathname === '/api/v1/projects') body = projection.projects;
|
|
263
|
-
else if (url.pathname === '/api/v1/gates') body = await listHumanGates(root);
|
|
325
|
+
else if (url.pathname === '/api/v1/gates') body = clean(await listHumanGates(root));
|
|
264
326
|
else if (url.pathname.startsWith('/api/v1/projects/')) body = projection.projects.find((item) => item.id === safeId(decodeURIComponent(url.pathname.slice('/api/v1/projects/'.length)))) ?? null;
|
|
265
327
|
else { response.writeHead(404); return response.end('not found'); }
|
|
266
328
|
response.writeHead(body === null ? 404 : 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); response.end(request.method === 'HEAD' ? '' : `${JSON.stringify(body)}\n`);
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { redact } from './redaction.mjs';
|
|
4
5
|
|
|
5
6
|
export const PRODUCTION_EVIDENCE_VERSION = 1;
|
|
6
|
-
const SECRET = /(^|_)(secret|token|password|credential|api[_-]?key|private[_-]?key)(_|$)/i;
|
|
7
7
|
const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])) : value;
|
|
8
8
|
const digest = (value) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
9
|
-
export const redactEvidence = (value
|
|
9
|
+
export const redactEvidence = (value) => redact(value);
|
|
10
10
|
export const evidenceDigest = (value) => digest(value);
|
|
11
11
|
|
|
12
12
|
export function evaluateEvidence(report, baseline = null) {
|
|
@@ -19,30 +19,52 @@ export function evaluateEvidence(report, baseline = null) {
|
|
|
19
19
|
});
|
|
20
20
|
const previous = baseline?.metrics ?? {};
|
|
21
21
|
const trend = Object.fromEntries(Object.keys(metrics).sort().filter((key) => Number.isFinite(Number(metrics[key])) && Number.isFinite(Number(previous[key]))).map((key) => [key, { baseline: Number(previous[key]), current: Number(metrics[key]), delta: Number(metrics[key]) - Number(previous[key]) }]));
|
|
22
|
-
return { checks, trend, passed: checks.every((item) => item.passed) && report.scenarios.every((item) => item.status === 'passed') && report.compatibility.every((item) => item.status === 'passed') };
|
|
22
|
+
return { checks, trend, passed: checks.every((item) => item.passed) && (report.scenarios ?? []).every((item) => item.status === 'passed') && (report.compatibility ?? []).every((item) => item.status === 'passed') };
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
// A plain SHA-256 digest detects accidental corruption only: anyone who can
|
|
26
|
+
// edit the report can recompute it. With a key (option or
|
|
27
|
+
// LOOP_EVIDENCE_HMAC_KEY) the seal is an HMAC that cannot be forged without it.
|
|
28
|
+
const sealKey = (options) => options.key ?? process.env.LOOP_EVIDENCE_HMAC_KEY ?? null;
|
|
29
|
+
const hmac = (key, value) => createHmac('sha256', key).update(JSON.stringify(canonical(value))).digest('hex');
|
|
30
|
+
const sameHex = (left, right) => typeof left === 'string' && typeof right === 'string' && left.length === right.length
|
|
31
|
+
&& timingSafeEqual(Buffer.from(left, 'hex'), Buffer.from(right, 'hex'));
|
|
32
|
+
|
|
33
|
+
export function sealEvidence(input, options = {}) {
|
|
26
34
|
const report = redactEvidence({ ...input, schema: 'loop.production_trust_evidence', schema_version: PRODUCTION_EVIDENCE_VERSION });
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
35
|
+
// The verdict is derived from the evidence, never taken on trust: a report
|
|
36
|
+
// whose metrics fail their thresholds cannot be sealed as passed.
|
|
37
|
+
if (Array.isArray(report.scenarios) && Array.isArray(report.compatibility)) {
|
|
38
|
+
report.evaluation = evaluateEvidence(report, options.baseline ?? null);
|
|
39
|
+
report.passed = report.passed !== false && report.evaluation.passed;
|
|
40
|
+
}
|
|
41
|
+
const unsigned = { ...report }; delete unsigned.integrity;
|
|
42
|
+
const key = sealKey(options);
|
|
43
|
+
return { ...report, integrity: key ? { algorithm: 'hmac-sha256', digest: hmac(key, unsigned) } : { algorithm: 'sha256', digest: digest(unsigned) } };
|
|
30
44
|
}
|
|
31
45
|
|
|
32
|
-
export function verifyEvidence(report) {
|
|
46
|
+
export function verifyEvidence(report, options = {}) {
|
|
33
47
|
if (report?.schema !== 'loop.production_trust_evidence' || report.schema_version !== PRODUCTION_EVIDENCE_VERSION) return { valid: false, reason: 'unsupported_schema' };
|
|
34
48
|
const unsigned = { ...report }; delete unsigned.integrity;
|
|
35
|
-
const
|
|
36
|
-
|
|
49
|
+
const expected = report.integrity?.digest;
|
|
50
|
+
if (report.integrity?.algorithm === 'hmac-sha256') {
|
|
51
|
+
const key = sealKey(options);
|
|
52
|
+
if (!key) return { valid: false, reason: 'hmac_key_required', expected, actual: null };
|
|
53
|
+
const actual = hmac(key, unsigned);
|
|
54
|
+
return { valid: sameHex(actual, expected), reason: sameHex(actual, expected) ? null : 'digest_mismatch', expected, actual, keyed: true };
|
|
55
|
+
}
|
|
56
|
+
const actual = digest(unsigned);
|
|
57
|
+
return { valid: actual === expected, reason: actual === expected ? null : 'digest_mismatch', expected, actual, keyed: false };
|
|
37
58
|
}
|
|
38
59
|
|
|
39
60
|
export function publicEvidenceSummary(report) {
|
|
40
61
|
const verification = verifyEvidence(report);
|
|
41
|
-
|
|
62
|
+
const evaluated = evaluateEvidence(report).passed;
|
|
63
|
+
return redactEvidence({ schema: 'loop.production_trust_public_summary', schema_version: 1, evidence_digest: report.integrity?.digest, integrity_algorithm: report.integrity?.algorithm ?? null, generated_at: report.generated_at, passed: Boolean(report.passed && evaluated && verification.valid), fixtures: report.compatibility.map(({ runtime, contract_version, status }) => ({ runtime, contract_version, status })), metrics: report.metrics, thresholds: report.thresholds, failures: report.evaluation.checks.filter((item) => !item.passed).map(({ metric, attribution }) => ({ metric, attribution })), limitations: report.limitations });
|
|
42
64
|
}
|
|
43
65
|
|
|
44
|
-
export async function writeEvidenceBundle(directory, report) {
|
|
45
|
-
const sealed = sealEvidence(report); const summary = publicEvidenceSummary(sealed);
|
|
66
|
+
export async function writeEvidenceBundle(directory, report, options = {}) {
|
|
67
|
+
const sealed = sealEvidence(report, options); const summary = publicEvidenceSummary(sealed);
|
|
46
68
|
await mkdir(directory, { recursive: true });
|
|
47
69
|
for (const [name, value] of [['evidence.json', sealed], ['public-summary.json', summary]]) {
|
|
48
70
|
const file = path.join(directory, name); const temporary = `${file}.${process.pid}.tmp`;
|
|
@@ -51,4 +73,4 @@ export async function writeEvidenceBundle(directory, report) {
|
|
|
51
73
|
return { report: sealed, summary };
|
|
52
74
|
}
|
|
53
75
|
|
|
54
|
-
export async function readAndVerifyEvidence(file) { const report = JSON.parse(await readFile(file, 'utf8')); return { report, verification: verifyEvidence(report) }; }
|
|
76
|
+
export async function readAndVerifyEvidence(file, options = {}) { const report = JSON.parse(await readFile(file, 'utf8')); return { report, verification: verifyEvidence(report, options) }; }
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { withFileMutex } from './file-mutex.mjs';
|
|
4
5
|
|
|
5
6
|
export const QUOTA_DECISIONS = Object.freeze(['execute', 'wait', 'ask', 'self-repair', 'silent']);
|
|
6
7
|
export const BUDGET_DIMENSIONS = Object.freeze(['tokens', 'time_ms', 'money_minor', 'rounds']);
|
|
@@ -50,13 +51,17 @@ export async function readQuotaLedger(root) { return readLedger(root); }
|
|
|
50
51
|
export async function recordVerifiedSliceSpend(root, input = {}) {
|
|
51
52
|
if (input.status !== 'completed' || input.verified !== true) return { recorded: false, reason: 'slice_not_completed_and_verified' };
|
|
52
53
|
const amount = vector(input.spend);
|
|
53
|
-
const ledger = await readLedger(root);
|
|
54
54
|
const sliceId = String(input.slice_id ?? '').trim();
|
|
55
55
|
if (!sliceId) throw new Error('slice_id is required.');
|
|
56
|
-
if (ledger.entries.some((entry) => entry.slice_id === sliceId)) return { recorded: false, reason: 'slice_already_recorded', ledger };
|
|
57
|
-
const entry = { id: randomUUID(), slice_id: sliceId, spend: amount, completed_at: input.completed_at ?? new Date().toISOString(), evidence: input.evidence ?? null };
|
|
58
|
-
ledger.spend = plus(vector(ledger.spend), amount); ledger.entries.push(entry);
|
|
59
56
|
const file = ledgerPath(root); await mkdir(path.dirname(file), { recursive: true });
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
// Read-modify-write under a mutex so concurrent slices neither lose spend
|
|
58
|
+
// nor both pass the duplicate check.
|
|
59
|
+
return withFileMutex(`${file}.lock`, { label: 'quota ledger mutex' }, async () => {
|
|
60
|
+
const ledger = await readLedger(root);
|
|
61
|
+
if (ledger.entries.some((entry) => entry.slice_id === sliceId)) return { recorded: false, reason: 'slice_already_recorded', ledger };
|
|
62
|
+
const entry = { id: randomUUID(), slice_id: sliceId, spend: amount, completed_at: input.completed_at ?? new Date().toISOString(), evidence: input.evidence ?? null };
|
|
63
|
+
ledger.spend = plus(vector(ledger.spend), amount); ledger.entries.push(entry);
|
|
64
|
+
const temp = `${file}.${process.pid}.${randomUUID()}.tmp`; await writeFile(temp, `${JSON.stringify(ledger, null, 2)}\n`, { flag: 'wx' }); await rename(temp, file);
|
|
65
|
+
return { recorded: true, entry, ledger };
|
|
66
|
+
});
|
|
62
67
|
}
|
|
@@ -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 });
|