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,5 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
5
|
import path from 'node:path';
|
|
4
6
|
import { spawn } from 'node:child_process';
|
|
5
7
|
|
|
@@ -14,6 +16,7 @@ function parseArgs(argv) {
|
|
|
14
16
|
else if (arg === '--tailscale-bin') out.tailscaleBin = argv[++i];
|
|
15
17
|
else if (arg === '--systemctl-bin') out.systemctlBin = argv[++i];
|
|
16
18
|
else if (arg === '--confirm-install') out.confirmInstall = true;
|
|
19
|
+
else if (arg === '--force') out.force = true;
|
|
17
20
|
else if (arg === '--json') out.json = true;
|
|
18
21
|
else if (arg === '--help') out.help = true;
|
|
19
22
|
else throw new Error(`Unknown argument: ${arg}`);
|
|
@@ -25,11 +28,22 @@ function parseArgs(argv) {
|
|
|
25
28
|
return out;
|
|
26
29
|
}
|
|
27
30
|
|
|
31
|
+
// WorkingDirectory= takes the path literally (systemd does not decode C
|
|
32
|
+
// escapes there); only specifiers need escaping. Newlines cannot be encoded.
|
|
33
|
+
function systemdWorkingDirectory(value) {
|
|
34
|
+
const text = String(value);
|
|
35
|
+
if (/[\n\r]/.test(text)) throw new Error('Workspace path must not contain a newline.');
|
|
36
|
+
return text.replace(/%/g, '%%');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ExecStart= decodes C escapes, so escape every byte of the UTF-8 encoding
|
|
40
|
+
// outside a safe set (a code point above 0xff is not a single \\x escape).
|
|
28
41
|
function systemdEscapePath(value) {
|
|
29
|
-
return [...
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
42
|
+
return [...Buffer.from(String(value))]
|
|
43
|
+
.map((byte) => /[A-Za-z0-9/_.:-]/.test(String.fromCharCode(byte))
|
|
44
|
+
? String.fromCharCode(byte)
|
|
45
|
+
: `\\x${byte.toString(16).padStart(2, '0')}`)
|
|
46
|
+
.join('');
|
|
33
47
|
}
|
|
34
48
|
|
|
35
49
|
function run(command, args) {
|
|
@@ -45,11 +59,11 @@ function run(command, args) {
|
|
|
45
59
|
|
|
46
60
|
const args = parseArgs(process.argv.slice(2));
|
|
47
61
|
if (args.help) {
|
|
48
|
-
console.log('Usage: loop-engineering-dashboard-autostart-install --root <workspace> [--listen localhost|tailscale] [--port 4174] [--tailscale-bin tailscale] [--confirm-install] [--json]');
|
|
62
|
+
console.log('Usage: loop-engineering-dashboard-autostart-install --root <workspace> [--listen localhost|tailscale] [--port 4174] [--tailscale-bin tailscale] [--confirm-install] [--force] [--json]');
|
|
49
63
|
process.exit(0);
|
|
50
64
|
}
|
|
51
65
|
|
|
52
|
-
const packageRoot = path.resolve(new URL('..', import.meta.url)
|
|
66
|
+
const packageRoot = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
53
67
|
const cli = path.join(packageRoot, 'bin', 'loop-engineering.mjs');
|
|
54
68
|
const userSystemdDir = path.join(process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || '', '.config'), 'systemd', 'user');
|
|
55
69
|
const dashboardUnit = 'loop-engineering-dashboard.service';
|
|
@@ -63,20 +77,31 @@ const host = args.listen === 'localhost' ? (args.host || '127.0.0.1') : await (a
|
|
|
63
77
|
return addresses[0];
|
|
64
78
|
})();
|
|
65
79
|
const nonLoopback = args.listen === 'tailscale' ? ' --allow-non-loopback' : '';
|
|
66
|
-
const service = `[Unit]\nDescription=Taskforce Loop Engineering
|
|
80
|
+
const service = `[Unit]\nDescription=Taskforce Loop Engineering project workspace\nAfter=network.target\n\n[Service]\nType=simple\nWorkingDirectory=${systemdWorkingDirectory(args.root)}\nExecStart=${systemdEscapePath(process.execPath)} ${systemdEscapePath(cli)} dashboard-serve --root ${systemdEscapePath(args.root)} --host ${host} --port ${args.port}${nonLoopback}\nRestart=on-failure\nRestartSec=3s\nNoNewPrivileges=true\nPrivateTmp=true\n\n[Install]\nWantedBy=default.target\n`;
|
|
67
81
|
const dropIn = `[Unit]\nWants=${dashboardUnit}\nAfter=${dashboardUnit}\n`;
|
|
82
|
+
const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
83
|
+
// There is one dashboard unit per user. Never silently repoint another
|
|
84
|
+
// workspace's dashboard at this one.
|
|
85
|
+
const existingService = await readFile(servicePath, 'utf8').catch(() => null);
|
|
86
|
+
const servesThisRoot = (text) => text.includes(` --root ${systemdEscapePath(args.root)} `);
|
|
87
|
+
const conflict = existingService !== null && existingService !== service && !servesThisRoot(existingService);
|
|
68
88
|
const report = {
|
|
69
89
|
status: args.confirmInstall ? 'installed' : 'plan_only',
|
|
70
90
|
listen: args.listen,
|
|
71
91
|
host,
|
|
92
|
+
root: args.root,
|
|
72
93
|
dashboard: `http://${host}:${args.port}/`,
|
|
73
94
|
readOnly: true,
|
|
95
|
+
conflict: conflict ? 'dashboard service already serves another workspace' : null,
|
|
74
96
|
service: servicePath,
|
|
97
|
+
serviceSha256: sha256(service),
|
|
98
|
+
dropInSha256: sha256(dropIn),
|
|
75
99
|
gatewayDropIns: gatewayUnits.map((unit) => path.join(userSystemdDir, `${unit}.d`, 'loop-engineering-dashboard.conf')),
|
|
76
100
|
writesEnabled: args.confirmInstall
|
|
77
101
|
};
|
|
78
102
|
|
|
79
103
|
if (args.confirmInstall) {
|
|
104
|
+
if (conflict && !args.force) throw new Error(`Refusing to overwrite ${servicePath}: it serves another workspace. Use --force after review.`);
|
|
80
105
|
await mkdir(userSystemdDir, { recursive: true });
|
|
81
106
|
await writeFile(servicePath, service);
|
|
82
107
|
for (const unit of gatewayUnits) {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { chmod, cp, mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
3
4
|
import { spawn } from 'node:child_process';
|
|
4
5
|
import { tmpdir } from 'node:os';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
|
|
7
|
-
const root = await mkdtemp(path.join(tmpdir(), 'loop
|
|
8
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop dashboard 项目-'));
|
|
8
9
|
const mockSystemctl = path.join(root, 'systemctl.mjs');
|
|
9
10
|
const mockTailscale = path.join(root, 'tailscale.mjs');
|
|
10
11
|
const calls = path.join(root, 'calls.jsonl');
|
|
@@ -14,7 +15,12 @@ await writeFile(mockSystemctl, `#!/usr/bin/env node\nimport { appendFile } from
|
|
|
14
15
|
await chmod(mockSystemctl, 0o755);
|
|
15
16
|
await writeFile(mockTailscale, `#!/usr/bin/env node\nif (process.argv.slice(2).join(' ') !== 'ip -4') process.exit(2);\nconsole.log('100.64.10.20');\n`);
|
|
16
17
|
await chmod(mockTailscale, 0o755);
|
|
17
|
-
|
|
18
|
+
// Run the installer from a package copy whose path contains a space, as an
|
|
19
|
+
// npm prefix under a user directory can.
|
|
20
|
+
const packageCopy = path.join(root, 'npm pkg');
|
|
21
|
+
for (const dir of ['bin', 'lib', 'scripts']) await cp(fileURLToPath(new URL(`../${dir}`, import.meta.url)), path.join(packageCopy, dir), { recursive: true });
|
|
22
|
+
await writeFile(path.join(packageCopy, 'package.json'), await readFile(fileURLToPath(new URL('../package.json', import.meta.url))));
|
|
23
|
+
const installer = path.join(packageCopy, 'scripts', 'dashboard-autostart-install.mjs');
|
|
18
24
|
const result = await new Promise((resolve) => {
|
|
19
25
|
const child = spawn(process.execPath, [installer, '--root', root, '--port', '4174', '--systemctl-bin', mockSystemctl, '--confirm-install', '--json'], { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
20
26
|
let stdout = ''; let stderr = '';
|
|
@@ -27,6 +33,9 @@ if (report.status !== 'installed' || report.dashboard !== 'http://127.0.0.1:4174
|
|
|
27
33
|
const unitDir = path.join(process.env.XDG_CONFIG_HOME, 'systemd', 'user');
|
|
28
34
|
const service = await readFile(path.join(unitDir, 'loop-engineering-dashboard.service'), 'utf8');
|
|
29
35
|
if (!service.includes('dashboard-serve') || !service.includes('--port 4174') || !service.includes('NoNewPrivileges=true')) throw new Error('dashboard service is incomplete');
|
|
36
|
+
// systemd does not decode escapes in WorkingDirectory=, but does in ExecStart=.
|
|
37
|
+
if (service.match(/^WorkingDirectory=(.*)$/m)?.[1] !== root) throw new Error('WorkingDirectory must be the literal workspace path');
|
|
38
|
+
if (!service.includes('\\xe9\\xa1\\xb9\\xe7\\x9b\\xae') || !service.includes('npm\\x20pkg') || service.includes('%20')) throw new Error('ExecStart paths must be UTF-8 byte escaped and decoded from file URLs');
|
|
30
39
|
for (const gateway of ['openclaw-gateway.service', 'hermes-gateway.service']) {
|
|
31
40
|
const dropIn = await readFile(path.join(unitDir, `${gateway}.d`, 'loop-engineering-dashboard.conf'), 'utf8');
|
|
32
41
|
if (!dropIn.includes('Wants=loop-engineering-dashboard.service') || !dropIn.includes('After=loop-engineering-dashboard.service')) throw new Error(`${gateway} is not wired to dashboard`);
|
|
@@ -47,6 +47,27 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
|
|
|
47
47
|
assert.equal(classification.recoverableRuntime, true);
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
{
|
|
51
|
+
// Successful answers can legitimately mention runtime failure vocabulary.
|
|
52
|
+
// Free-text signatures must not turn exitCode=0 into a replayed task.
|
|
53
|
+
for (const stdout of [
|
|
54
|
+
'Done. Added rate limit middleware and tests pass.',
|
|
55
|
+
'Fixed the connection reset bug in client.js.',
|
|
56
|
+
'Handled socket hang up and network error retries.',
|
|
57
|
+
'Documented what happens when compaction timed out or transcript compaction failed.',
|
|
58
|
+
'Explained the "stopped before confirming the turn was complete" message.'
|
|
59
|
+
]) {
|
|
60
|
+
const classification = dispatchFailureClassification({ exitCode: 0, timedOut: false, stderr: '', stdout });
|
|
61
|
+
assert.equal(classification.category, 'ok', stdout);
|
|
62
|
+
assert.equal(classification.recoverableRuntime, undefined, stdout);
|
|
63
|
+
}
|
|
64
|
+
for (const [stderr, category] of [['429 rate limit exceeded', 'rate_limit'], ['read ECONNRESET: connection reset', 'transport_error']]) {
|
|
65
|
+
const classification = dispatchFailureClassification({ exitCode: 1, timedOut: false, stderr, stdout: '' });
|
|
66
|
+
assert.equal(classification.category, category);
|
|
67
|
+
assert.equal(classification.recoverableRuntime, true);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
50
71
|
{
|
|
51
72
|
const classification = dispatchFailureClassification({
|
|
52
73
|
exitCode: 0,
|
|
@@ -218,11 +239,11 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
|
|
|
218
239
|
const devPlan = { checkpoints: [{ id: 'cp1' }] };
|
|
219
240
|
const reviews = {
|
|
220
241
|
reviews: [
|
|
221
|
-
{ checkpointId: 'cp5', milestoneId: 'G-01-retry', sequence: 5,
|
|
222
|
-
{ checkpointId: 'cp14', milestoneId: 'G-01-auth', sequence: 3,
|
|
242
|
+
{ checkpointId: 'cp5', milestoneId: 'G-01-retry', sequence: 5, checkpointCreatedAt: '2026-08-07T04:00:00.000Z', status: 'accepted' },
|
|
243
|
+
{ checkpointId: 'cp14', milestoneId: 'G-01-auth', sequence: 3, checkpointCreatedAt: '2026-08-07T12:00:00.000Z', status: 'blocked' }
|
|
223
244
|
]
|
|
224
245
|
};
|
|
225
|
-
assert.equal(selectEffectiveAcceptanceReviews(devPlan, reviews)
|
|
246
|
+
assert.equal(selectEffectiveAcceptanceReviews(devPlan, reviews).some(review => review.checkpointId === 'cp14'), true, 'conflicting clocks retain the blocker');
|
|
226
247
|
}
|
|
227
248
|
|
|
228
249
|
{
|
|
@@ -323,7 +344,7 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
|
|
|
323
344
|
projectCompletion: { status: 'complete' }, checkpointRisks: []
|
|
324
345
|
},
|
|
325
346
|
{
|
|
326
|
-
checkpointId: 'cp21', sequence: 21, status: '
|
|
347
|
+
checkpointId: 'cp21', sequence: 21, status: 'accepted',
|
|
327
348
|
projectCompletion: { status: 'needs_human_acceptance' },
|
|
328
349
|
checkpointNextAction: 'owner accepts broader OpenReel v4 project'
|
|
329
350
|
}
|
|
@@ -338,4 +359,92 @@ assert.equal(inferTaskScope({ body: 'Continue the overall project with a product
|
|
|
338
359
|
assert.equal(judgement.requires_human_gate, false);
|
|
339
360
|
}
|
|
340
361
|
|
|
362
|
+
|
|
363
|
+
// Recovery uses effective blockers, never a resolved historical checkpoint.
|
|
364
|
+
for (const dispatchStatus of ['runtime_interrupted', 'runtime_blocked', 'failed', 'verify_failed']) {
|
|
365
|
+
const unblockedOutcome = ['failed', 'verify_failed'].includes(dispatchStatus) ? 'needs_revision' : dispatchStatus;
|
|
366
|
+
const judge = reviews => buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'cp1' }] }, { count: reviews.length }, { reviews }, { dispatchStatus });
|
|
367
|
+
assert.equal(judge([{ checkpointId: 'cp1', status: 'blocked' }]).outcome, 'blocked');
|
|
368
|
+
assert.equal(judge([{ checkpointId: 'cp1', sequence: 1, status: 'blocked' }, { checkpointId: 'cp2', sequence: 2, status: 'accepted' }]).outcome, unblockedOutcome);
|
|
369
|
+
assert.equal(judge([]).outcome, unblockedOutcome);
|
|
370
|
+
}
|
|
371
|
+
|
|
341
372
|
console.log('final judgement self-test passed');
|
|
373
|
+
|
|
374
|
+
// IDs carry no ordering authority; exercise both input orders and all scopes.
|
|
375
|
+
for (const checkpoints of [[{ id: 'm' }], [{ id: 'm' }, { id: 'other' }]]) {
|
|
376
|
+
const select = reviews => selectEffectiveAcceptanceReviews({ checkpoints }, { reviews });
|
|
377
|
+
for (const [oldId, newId] of [['cp1', 'progress-latest'], ['cp99', 'cp1'], ['alpha', 'omega']]) {
|
|
378
|
+
for (const clocks of [
|
|
379
|
+
[{ sequence: 1 }, { sequence: 2 }],
|
|
380
|
+
[{ checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { checkpointCreatedAt: '2026-10-23T00:01:00Z' }]
|
|
381
|
+
]) {
|
|
382
|
+
for (const resolved of [false, true]) {
|
|
383
|
+
const pair = [
|
|
384
|
+
{ checkpointId: oldId, milestoneId: 'm', ...clocks[0], status: resolved ? 'blocked' : 'accepted' },
|
|
385
|
+
{ checkpointId: newId, milestoneId: 'm', ...clocks[1], status: resolved ? 'accepted' : 'blocked' }
|
|
386
|
+
];
|
|
387
|
+
for (const input of [pair, [...pair].reverse()]) assert.deepEqual(select(input).map(r => r.checkpointId), [newId]);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
for (const clocks of [
|
|
392
|
+
[{}, {}], [{ checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { checkpointCreatedAt: '' }], [{ sequence: 1 }, {}], [{ sequence: 1 }, { sequence: 1 }],
|
|
393
|
+
[{ sequence: '2', checkpointCreatedAt: 'invalid' }, { sequence: null }],
|
|
394
|
+
[{ sequence: 2, checkpointCreatedAt: '2026-10-23T00:00:00Z' }, { sequence: 1, checkpointCreatedAt: '2026-10-23T00:01:00Z' }]
|
|
395
|
+
]) {
|
|
396
|
+
const pair = [
|
|
397
|
+
{ checkpointId: 'unknown', milestoneId: 'm', ...clocks[0], status: 'blocked' },
|
|
398
|
+
{ checkpointId: 'cp999', milestoneId: 'm', ...clocks[1], status: 'accepted' }
|
|
399
|
+
];
|
|
400
|
+
for (const input of [pair, [...pair].reverse()]) assert.equal(select(input).some(r => r.status === 'blocked'), true);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
{
|
|
404
|
+
const terminal = { checkpointId: 'done', status: 'accepted', taskTerminal: true };
|
|
405
|
+
const blocker = { checkpointId: 'pending', status: 'blocked' };
|
|
406
|
+
assert.equal(selectEffectiveAcceptanceReviews({}, { reviews: [terminal, blocker] }).some(r => r.status === 'blocked'), true);
|
|
407
|
+
const judgement = buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'm' }, { id: 'missing' }] }, { count: 2 }, { reviews: [
|
|
408
|
+
{ checkpointId: 'a', milestoneId: 'm', status: 'accepted' },
|
|
409
|
+
{ checkpointId: 'b', milestoneId: 'm', status: 'accepted' }
|
|
410
|
+
] }, { dispatchStatus: 'completed' });
|
|
411
|
+
assert.equal(judgement.outcome, 'needs_revision', 'ambiguous snapshots cannot count as multiple milestones');
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
{
|
|
415
|
+
// A disconnected latest snapshot must not hide a contradictory clock cycle.
|
|
416
|
+
const reviews = [
|
|
417
|
+
{ checkpointId: 'a', sequence: 1, status: 'blocked' },
|
|
418
|
+
{ checkpointId: 'b', sequence: 2, checkpointCreatedAt: '2026-10-23T00:00:00Z', status: 'accepted' },
|
|
419
|
+
{ checkpointId: 'c', checkpointCreatedAt: '2026-10-23T00:01:00Z', status: 'accepted' },
|
|
420
|
+
{ checkpointId: 'd', sequence: 0, checkpointCreatedAt: '2026-10-23T00:02:00Z', status: 'accepted' },
|
|
421
|
+
{ checkpointId: 'isolated', status: 'accepted' }
|
|
422
|
+
];
|
|
423
|
+
assert.equal(selectEffectiveAcceptanceReviews({}, { reviews }).some(r => r.status === 'blocked'), true);
|
|
424
|
+
assert.equal(selectEffectiveAcceptanceReviews({}, { reviews: [
|
|
425
|
+
{ checkpointId: 'done', sequence: 1, status: 'accepted', taskTerminal: true },
|
|
426
|
+
{ checkpointId: 'pending', sequence: 2, status: 'blocked' }
|
|
427
|
+
] }).some(r => r.status === 'blocked'), true, 'terminal cannot swallow a later task blocker');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// A broader-project label must never launder a failed/blocked task review.
|
|
431
|
+
for (const status of ['blocked', 'revise']) {
|
|
432
|
+
for (const dispatchStatus of ['completed', 'failed', 'verify_failed', 'runtime_interrupted', 'runtime_blocked']) {
|
|
433
|
+
const terminal = { checkpointId: 'done', sequence: 1, status: 'accepted', projectCompletion: { status: 'complete' } };
|
|
434
|
+
const later = { checkpointId: 'progress', sequence: 2, status, projectCompletion: { status: 'needs_human_acceptance' } };
|
|
435
|
+
for (const reviews of [[terminal, later], [later, terminal]]) {
|
|
436
|
+
const judgement = buildFinalJudgement(baseContract, basePlan, { checkpoints: [{ id: 'cp1' }] }, { count: 2 }, { reviews }, { dispatchStatus });
|
|
437
|
+
assert.deepEqual(judgement.coverage.effective_review_ids, ['progress']);
|
|
438
|
+
assert.equal(judgement.coverage.terminal_lock, false);
|
|
439
|
+
if (status === 'blocked') assert.equal(judgement.outcome, 'blocked');
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// Even accepted governance cannot hide a materializable deferred gate.
|
|
444
|
+
{
|
|
445
|
+
const reviews = [
|
|
446
|
+
{ checkpointId: 'done', sequence: 1, status: 'accepted', projectCompletion: 'complete' },
|
|
447
|
+
{ checkpointId: 'gate', sequence: 2, status: 'accepted', projectCompletion: 'needs_human_acceptance', deferredGates: [{ action: 'send' }] }
|
|
448
|
+
];
|
|
449
|
+
assert.deepEqual(selectEffectiveAcceptanceReviews({ checkpoints: [{ id: 'cp1' }] }, { reviews }).map(r => r.checkpointId), ['gate']);
|
|
450
|
+
}
|
|
@@ -37,10 +37,17 @@ if (!wrapper.includes('process.exitCode = tickCode;') || wrapper.includes('proce
|
|
|
37
37
|
const dispatcher = await readFile(path.join(root, 'scripts/loops/hermes-loop-dispatch.mjs'), 'utf8'); if (!dispatcher.includes("'-z', prompt")) throw new Error('Hermes one-shot dispatcher missing');
|
|
38
38
|
const notifier = path.join(root, 'scripts/loops/hermes-loop-notify.mjs'); const notify = await run(process.execPath, [notifier, 'hello from loop'], { env: { ...process.env, HERMES_SEND_CAPTURE: sendCapture, LOOP_NOTIFICATION_SOURCE: JSON.stringify({ channel: 'telegram', target: 'telegram:12345' }) } }); if (notify.code !== 0) throw new Error(`Hermes notifier failed: ${notify.stderr}`);
|
|
39
39
|
const sent = JSON.parse(await readFile(sendCapture, 'utf8')); if (!sent.includes('telegram:12345') || !sent.includes('hello from loop')) throw new Error('Hermes notifier did not preserve delivery target/message');
|
|
40
|
-
const serviceFile = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/hermes-loop-hermes-tasks-scheduler.service'); const timerFile = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/hermes-loop-hermes-tasks-scheduler.timer'); const service = await readFile(serviceFile, 'utf8'); if (service.includes('WorkingDirectory="') || !service.includes('\\x20') || !service.includes('\\xe5\\xae\\x89\\xe8\\xa3\\x85')) throw new Error('Hermes systemd paths were not escaped');
|
|
40
|
+
const serviceFile = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/hermes-loop-hermes-tasks-scheduler.service'); const timerFile = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/hermes-loop-hermes-tasks-scheduler.timer'); const service = await readFile(serviceFile, 'utf8'); if (service.includes('WorkingDirectory="') || !service.includes('\\x20') || !service.includes('\\xe5\\xae\\x89\\xe8\\xa3\\x85')) throw new Error('Hermes systemd paths were not escaped'); if (service.match(/^WorkingDirectory=(.*)$/m)?.[1] !== root) throw new Error('WorkingDirectory must be the literal workspace path');
|
|
41
41
|
const dashboardServiceFile = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/loop-engineering-dashboard.service'); const dashboardDropIn = path.join(process.env.XDG_CONFIG_HOME, 'systemd/user/hermes-gateway.service.d/loop-engineering-dashboard.conf'); if (!(await readFile(dashboardServiceFile, 'utf8')).includes('dashboard-serve') || !(await readFile(dashboardDropIn, 'utf8')).includes('Wants=loop-engineering-dashboard.service')) throw new Error('Hermes installer did not install Dashboard gateway autostart');
|
|
42
42
|
const verify = await run('systemd-analyze', ['verify', serviceFile, timerFile]); if (verify.code !== 0) throw new Error(`Hermes systemd units invalid: ${verify.stderr || verify.stdout}`);
|
|
43
43
|
const doctorResult = await run(process.execPath, [doctor, '--root', root, '--queue', 'hermes-tasks', '--hermes-bin', mockHermes, '--json']); if (doctorResult.code !== 0 || JSON.parse(doctorResult.stdout).status !== 'ok') throw new Error(`Hermes doctor failed: ${doctorResult.stderr || doctorResult.stdout}`);
|
|
44
44
|
const smokeResult = await run(process.execPath, [smoke, '--root', root, '--queue', 'hermes-tasks', '--hermes-bin', mockHermes, '--loop-bin', loopBin, '--json']); if (smokeResult.code !== 0 || JSON.parse(smokeResult.stdout).status !== 'ok') throw new Error(`Hermes smoke failed: ${smokeResult.stderr || smokeResult.stdout}`);
|
|
45
45
|
const calls = await readFile(systemctlCapture, 'utf8'); if (!calls.includes('["--user","enable","--now","hermes-loop-hermes-tasks-scheduler.timer"]')) throw new Error('Hermes scheduler timer was not enabled');
|
|
46
|
+
// Reinstalling in another language replaces the managed AGENTS.md block.
|
|
47
|
+
const reinstall = await run(process.execPath, [installer, ...base, '--language', 'zh', '--confirm-install', '--force', '--json']);
|
|
48
|
+
if (reinstall.code !== 0) throw new Error(`Hermes reinstall failed: ${reinstall.stderr}`);
|
|
49
|
+
const hermesInstructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
|
|
50
|
+
if (hermesInstructions.split('<!-- loop-engineering:hermes:start -->').length !== 2 || !hermesInstructions.includes('Loop Engineering 会话路由(Hermes)') || hermesInstructions.includes('conversation routing (Hermes)')) throw new Error('Hermes reinstall did not replace the managed AGENTS.md block');
|
|
51
|
+
const hermesManifest = JSON.parse(await readFile(path.join(root, 'runtime/loop-engineering-hermes-install.json'), 'utf8'));
|
|
52
|
+
if ((hermesManifest.status !== 'installed' || hermesManifest.managedInstructions?.content !== hermesInstructions.slice(hermesInstructions.indexOf('\n<!-- loop-engineering:hermes:start -->')))) throw new Error('Hermes manifest does not record the managed block');
|
|
46
53
|
console.log('hermes installer self-test passed');
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
4
|
import { createHash } from 'node:crypto';
|
|
4
5
|
import { spawn } from 'node:child_process';
|
|
5
6
|
import path from 'node:path';
|
|
7
|
+
import { applyManagedInstructions, installDashboardUnlessShared } from './install-shared.mjs';
|
|
6
8
|
|
|
7
9
|
function parseArgs(argv) {
|
|
8
10
|
const out = { root: process.cwd(), queue: 'agent-tasks', hermesBin: 'hermes', systemctlBin: 'systemctl', dashboardListen: 'localhost', tailscaleBin: 'tailscale', language: 'auto', json: false, confirmInstall: false, force: false };
|
|
@@ -33,6 +35,14 @@ function resolveLanguage(requested = 'auto', env = process.env) {
|
|
|
33
35
|
const text = (language, en, zh) => language === 'zh' ? zh : en;
|
|
34
36
|
|
|
35
37
|
function safeId(value, label) { if (!/^[a-zA-Z0-9._-]+$/.test(value)) throw new Error(`${label} contains unsupported characters.`); return value; }
|
|
38
|
+
// WorkingDirectory= takes the path literally (systemd does not decode C
|
|
39
|
+
// escapes there); only specifiers need escaping. Newlines cannot be encoded.
|
|
40
|
+
function systemdWorkingDirectory(value) {
|
|
41
|
+
const text = String(value);
|
|
42
|
+
if (/[\n\r]/.test(text)) throw new Error('Workspace path must not contain a newline.');
|
|
43
|
+
return text.replace(/%/g, '%%');
|
|
44
|
+
}
|
|
45
|
+
|
|
36
46
|
function systemdEscapePath(value) {
|
|
37
47
|
return [...Buffer.from(String(value))].map((byte) => /[A-Za-z0-9/_.:-]/.test(String.fromCharCode(byte)) ? String.fromCharCode(byte) : `\\x${byte.toString(16).padStart(2, '0')}`).join('');
|
|
38
48
|
}
|
|
@@ -138,7 +148,7 @@ else { const child = spawn(${JSON.stringify(hermesBin)}, args, { cwd: process.cw
|
|
|
138
148
|
`;
|
|
139
149
|
}
|
|
140
150
|
|
|
141
|
-
function schedulerServiceSource({ root, queue }) { return `[Unit]\nDescription=Taskforce Loop Engineering Hermes scheduler for ${queue}\nAfter=default.target\n\n[Service]\nType=oneshot\nWorkingDirectory=${
|
|
151
|
+
function schedulerServiceSource({ root, queue }) { return `[Unit]\nDescription=Taskforce Loop Engineering Hermes scheduler for ${queue}\nAfter=default.target\n\n[Service]\nType=oneshot\nWorkingDirectory=${systemdWorkingDirectory(root)}\nExecStart=${systemdEscapePath(process.execPath)} ${systemdEscapePath(path.join(root, 'scripts', 'loops', 'hermes-loop.mjs'))} scheduler-tick --json\n`; }
|
|
142
152
|
function schedulerTimerSource({ queue }) { return `[Unit]\nDescription=Wake Taskforce Loop Engineering Hermes scheduler for ${queue}\n\n[Timer]\nOnBootSec=30s\nOnUnitActiveSec=1min\nAccuracySec=10s\nPersistent=true\nUnit=hermes-loop-${queue}-scheduler.service\n\n[Install]\nWantedBy=timers.target\n`; }
|
|
143
153
|
function instructionsBlock({ queue, language }) {
|
|
144
154
|
if (language === 'zh') return `\n<!-- loop-engineering:hermes:start -->\n## Loop Engineering 会话路由(Hermes)\n\n- 仅路由明确的 Loop Engineering 请求。已管理的任务不能再次路由。\n- 运行 \`node scripts/loops/hermes-loop.mjs route --message "<完整用户消息>"\` 并传入来源 channel 和 target,使通知返回原始 Hermes 会话。\n- \`走 loop\` 立即执行;只有 \`只入队\` 或 \`只排队\` 才不立即执行。高风险动作仍需单独门禁。\n- 队列:\`${queue}\`。\n<!-- loop-engineering:hermes:end -->\n`;
|
|
@@ -153,7 +163,7 @@ async function main() {
|
|
|
153
163
|
args.hermesBin = await resolveExecutable(args.hermesBin);
|
|
154
164
|
const hermes = await run(args.hermesBin, ['--version'], { cwd: args.root });
|
|
155
165
|
if (hermes.code !== 0) throw new Error(`Cannot run Hermes CLI with ${args.hermesBin}: ${(hermes.stderr || hermes.stdout).trim() || `exit ${hermes.code}`}`);
|
|
156
|
-
const loopBin = new URL('../bin/loop-engineering.mjs', import.meta.url)
|
|
166
|
+
const loopBin = fileURLToPath(new URL('../bin/loop-engineering.mjs', import.meta.url));
|
|
157
167
|
const systemdUserDir = path.join(process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || '', '.config'), 'systemd', 'user');
|
|
158
168
|
const unit = `hermes-loop-${args.queue}-scheduler.service`; const timer = `hermes-loop-${args.queue}-scheduler.timer`;
|
|
159
169
|
const files = { workspaceHealth: path.join(args.root, 'configs/loops/workspace-health.json'), queueConfig: path.join(args.root, 'configs/loops/queues', `${args.queue}.json`), dispatcher: path.join(args.root, 'scripts/loops/hermes-loop-dispatch.mjs'), wrapper: path.join(args.root, 'scripts/loops/hermes-loop.mjs'), notifier: path.join(args.root, 'scripts/loops/hermes-loop-notify.mjs'), manifest: path.join(args.root, 'runtime/loop-engineering-hermes-install.json'), instructions: path.join(args.root, 'AGENTS.md'), schedulerService: path.join(systemdUserDir, unit), schedulerTimer: path.join(systemdUserDir, timer) };
|
|
@@ -170,13 +180,24 @@ async function main() {
|
|
|
170
180
|
const contents = { queueConfig: queueContent, dispatcher: dispatcherSource(args), wrapper: wrapperSource({ queue: args.queue, loopBin, language: args.language }), notifier: notifierSource(args), schedulerService: schedulerServiceSource({ root: args.root, queue: args.queue }), schedulerTimer: schedulerTimerSource({ queue: args.queue }) };
|
|
171
181
|
await mkdir(systemdUserDir, { recursive: true });
|
|
172
182
|
for (const [kind, content] of Object.entries(contents)) await writeFile(files[kind], content);
|
|
183
|
+
// Record ownership before enabling anything, so a later failure still
|
|
184
|
+
// leaves a manifest describing what was installed.
|
|
185
|
+
const previousManifest = await readFile(files.manifest, 'utf8').then(JSON.parse).catch(() => null);
|
|
186
|
+
const managedInstructions = await applyManagedInstructions(files.instructions, instructionsBlock({ queue: args.queue, language: args.language }), {
|
|
187
|
+
previousBlock: previousManifest?.managedInstructions?.content,
|
|
188
|
+
force: args.force,
|
|
189
|
+
startMarker: '<!-- loop-engineering:hermes:start -->',
|
|
190
|
+
endMarker: '<!-- loop-engineering:hermes:end -->'
|
|
191
|
+
});
|
|
192
|
+
const manifest = { version: 3, status: 'installing', platform: 'hermes', language: args.language, installedAt: new Date().toISOString(), root: args.root, queue: args.queue, hermesBin: args.hermesBin, files: Object.entries(contents).map(([kind, content]) => ({ kind, path: files[kind], sha256: sha256(content) })), scheduler: { unit, timer }, managedInstructions: { path: 'AGENTS.md', sha256: sha256(managedInstructions), content: managedInstructions }, dashboard: { listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, installed: false } };
|
|
193
|
+
const writeManifest = async () => { await mkdir(path.dirname(files.manifest), { recursive: true }); await writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`); };
|
|
194
|
+
await writeManifest();
|
|
173
195
|
const reload = await run(args.systemctlBin, ['--user', 'daemon-reload'], { cwd: args.root }); if (reload.code !== 0) throw new Error(`Cannot reload user systemd units: ${(reload.stderr || reload.stdout).trim()}`);
|
|
174
196
|
const enable = await run(args.systemctlBin, ['--user', 'enable', '--now', timer], { cwd: args.root }); if (enable.code !== 0) throw new Error(`Cannot enable Hermes Loop scheduler ${timer}: ${(enable.stderr || enable.stdout).trim()}`);
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
await mkdir(path.dirname(files.manifest), { recursive: true }); await writeFile(files.manifest, `${JSON.stringify({ version: 2, platform: 'hermes', language: args.language, installedAt: new Date().toISOString(), root: args.root, queue: args.queue, hermesBin: args.hermesBin, files: Object.entries(contents).map(([kind, content]) => ({ kind, path: files[kind], sha256: sha256(content) })), scheduler: { unit, timer } }, null, 2)}\n`);
|
|
197
|
+
manifest.dashboard = await installDashboardUnlessShared({ root: args.root, listen: args.dashboardListen, tailscaleBin: args.tailscaleBin, systemctlBin: args.systemctlBin, run });
|
|
198
|
+
if (manifest.dashboard.skipped) report.dashboardAutostart = { ...(report.dashboardAutostart ?? {}), skipped: manifest.dashboard.skipped };
|
|
199
|
+
manifest.status = 'installed';
|
|
200
|
+
await writeManifest();
|
|
180
201
|
}
|
|
181
202
|
console.log(args.json ? JSON.stringify(report, null, 2) : text(args.language, `Hermes Loop installer: ${report.status}\nnext: ${args.confirmInstall ? 'Run loop-engineering-hermes-doctor, then route a harmless smoke task.' : 'Review this summary, then rerun with --confirm-install.'}`, `Hermes Loop 安装器:${report.status}\n下一步:${args.confirmInstall ? '运行 loop-engineering-hermes-doctor,然后路由一个无害的冒烟任务。' : '检查此摘要,然后使用 --confirm-install 重新运行。'}`));
|
|
182
203
|
}
|
package/scripts/hermes-smoke.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
2
3
|
import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
4
|
import { spawn } from 'node:child_process';
|
|
4
5
|
import path from 'node:path';
|
|
@@ -16,7 +17,7 @@ async function main() {
|
|
|
16
17
|
const args = parseArgs(process.argv.slice(2));
|
|
17
18
|
if (args.help) { console.log('Usage: loop-engineering-hermes-smoke [--root workspace] [--queue agent-tasks] [--hermes-bin hermes] [--loop-bin loop-engineering] [--keep-artifacts] [--json]'); return; }
|
|
18
19
|
safeId(args.queue); const runToken = `${Date.now()}-${process.pid}`; const smokeQueue = `smoke-${args.queue}-${runToken}`;
|
|
19
|
-
const baseConfig = path.join(args.root, `configs/loops/queues/${args.queue}.json`); const smokeConfig = path.join(args.root, `configs/loops/queues/${smokeQueue}.json`); const smokeRuntime = path.join(args.root, 'runtime', 'loops', smokeQueue); const doctorScript = new URL('./hermes-doctor.mjs', import.meta.url)
|
|
20
|
+
const baseConfig = path.join(args.root, `configs/loops/queues/${args.queue}.json`); const smokeConfig = path.join(args.root, `configs/loops/queues/${smokeQueue}.json`); const smokeRuntime = path.join(args.root, 'runtime', 'loops', smokeQueue); const doctorScript = fileURLToPath(new URL('./hermes-doctor.mjs', import.meta.url));
|
|
20
21
|
const steps = []; let taskId = null;
|
|
21
22
|
try {
|
|
22
23
|
const doctor = await run(process.execPath, [doctorScript, '--root', args.root, '--queue', args.queue, '--hermes-bin', args.hermesBin, '--json'], { cwd: args.root }); steps.push({ id: 'doctor', ok: doctor.code === 0 }); if (doctor.code !== 0) throw new Error(`doctor failed: ${doctor.stderr || doctor.stdout}`);
|
|
@@ -4,7 +4,8 @@ import { tmpdir } from 'node:os';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { createHumanGate, executeGateCommand, getHumanGate, parseBoundReply } from '../lib/human-gate-command.mjs';
|
|
6
6
|
import { handleChannelGateEvent, normalizeFeishuGateEvent, renderGateForChannel } from '../lib/human-gate-channel-adapter.mjs';
|
|
7
|
-
import {
|
|
7
|
+
import { request as httpRequest } from 'node:http';
|
|
8
|
+
import { addDashboardOperator, createDashboardServer, removeDashboardOperator } from '../lib/operator-dashboard.mjs';
|
|
8
9
|
|
|
9
10
|
const root = await mkdtemp(path.join(tmpdir(), 'loop-gate-command-'));
|
|
10
11
|
const base = { project: 'p', task: 't', action: 'deploy', reason: 'release', impact: 'production', risk: { level: 'high' }, cost: { amount: 10, currency: 'CNY', budget: 100 }, evidence: ['test'], dashboard_url: 'http://127.0.0.1:4174/', expiry: '2030-01-01T00:00:00.000Z', allowed_actors: ['owner'], source_bindings: [{ channel: 'feishu', message_id: 'card-1', reply_to: 'card-1', adapter: 'feishu' }, { channel: 'dashboard', message_id: 'gate-panel', reply_to: 'gate-panel', adapter: 'dashboard' }] };
|
|
@@ -40,13 +41,41 @@ try {
|
|
|
40
41
|
executeGateCommand(root, { ...command, gate_id: 'gate_cross', source_channel: 'dashboard', source_message_id: 'gate-panel', idempotency_key: 'cross-dashboard' })
|
|
41
42
|
]);
|
|
42
43
|
assert.equal(cross.filter((x) => x.status === 'fulfilled').length, 1);
|
|
43
|
-
await createHumanGate(root, { ...base, gate_id: 'gate_http', confirmation_required: false
|
|
44
|
+
await createHumanGate(root, { ...base, gate_id: 'gate_http', confirmation_required: false,
|
|
45
|
+
evidence: [{ accessToken: 'SECRET-ACCESS', Authorization: 'Bearer SECRET', api_token: 'SECRET-API', fencing_token: 7 }] });
|
|
44
46
|
const server = await createDashboardServer(root, { host: '127.0.0.1', port: 0 });
|
|
45
47
|
try {
|
|
46
48
|
const address = server.address();
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
const endpoint = `http://127.0.0.1:${address.port}/api/v1/gate-commands`;
|
|
50
|
+
const body = (key, extra = {}) => JSON.stringify({ gate_id: 'gate_http', decision: 'approve', expected_generation: 1, source_message_id: 'gate-panel', idempotency_key: key, ...extra });
|
|
51
|
+
// Gate commands are disabled until an operator is registered, and the
|
|
52
|
+
// body's actor_id is never trusted.
|
|
53
|
+
let response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: body('http-anon', { actor_id: 'owner' }) });
|
|
54
|
+
assert.equal(response.status, 401, 'anonymous dashboard approval is rejected');
|
|
55
|
+
const intruder = await addDashboardOperator(root, { actorId: 'intruder' });
|
|
56
|
+
response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${intruder.token}` }, body: body('http-intruder', { actor_id: 'owner' }) });
|
|
57
|
+
assert.equal((await response.json()).outcome !== 'approved', true, 'a token cannot claim another actor');
|
|
58
|
+
assert.equal((await getHumanGate(root, 'gate_http')).status, 'pending');
|
|
59
|
+
await removeDashboardOperator(root, { actorId: 'intruder' });
|
|
60
|
+
response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${intruder.token}` }, body: body('http-removed') });
|
|
61
|
+
assert.equal(response.status, 401, 'a removed operator token is rejected');
|
|
62
|
+
const owner = await addDashboardOperator(root, { actorId: 'owner' });
|
|
63
|
+
response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'text/plain', authorization: `Bearer ${owner.token}` }, body: body('http-plain') });
|
|
64
|
+
assert.equal(response.status, 415, 'a CORS-simple text/plain POST is rejected');
|
|
65
|
+
const rebound = await new Promise((resolve, reject) => {
|
|
66
|
+
const req = httpRequest({ host: '127.0.0.1', port: address.port, path: '/api/v1/gates', headers: { host: `attacker.example:${address.port}` } }, (res) => { res.resume(); resolve(res.statusCode); });
|
|
67
|
+
req.on('error', reject); req.end();
|
|
68
|
+
});
|
|
69
|
+
assert.equal(rebound, 421, 'a DNS-rebinding Host header is rejected');
|
|
70
|
+
response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${owner.token}` }, body: body('http-1') });
|
|
71
|
+
assert.equal(response.status, 200);
|
|
72
|
+
const receipt = await response.json();
|
|
73
|
+
assert.equal(receipt.outcome, 'approved'); assert.equal(receipt.actor_id, 'owner');
|
|
74
|
+
const gatesResponse = await fetch(`http://127.0.0.1:${address.port}/api/v1/gates`); assert.equal(gatesResponse.status, 200);
|
|
75
|
+
const gatesText = await gatesResponse.text();
|
|
76
|
+
assert.ok(JSON.parse(gatesText).some((g) => g.gate_id === 'gate_http'));
|
|
77
|
+
assert.equal(/SECRET/.test(gatesText), false, 'gate evidence credentials are redacted');
|
|
78
|
+
assert.match(gatesText, /"fencing_token":7/, 'fencing tokens remain visible');
|
|
50
79
|
} finally { await new Promise((resolve) => server.close(resolve)); }
|
|
51
80
|
console.log('human-gate-command self-test: ok (unit, integration, replay, expiry, authorization, misrecognition, Feishu mapping, concurrency)');
|
|
52
81
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
|
|
4
|
+
// Helpers shared by the OpenClaw and Hermes integration installers.
|
|
5
|
+
|
|
6
|
+
function locateBlock(text, startMarker, endMarker) {
|
|
7
|
+
const start = text.indexOf(startMarker);
|
|
8
|
+
if (start === -1) return null;
|
|
9
|
+
const endIndex = text.indexOf(endMarker, start);
|
|
10
|
+
if (endIndex === -1) throw new Error(`AGENTS.md has ${startMarker} without ${endMarker}; fix it by hand.`);
|
|
11
|
+
const blockStart = text[start - 1] === '\n' ? start - 1 : start;
|
|
12
|
+
let blockEnd = endIndex + endMarker.length;
|
|
13
|
+
if (text[blockEnd] === '\n') blockEnd += 1;
|
|
14
|
+
return { blockStart, blockEnd, existing: text.slice(blockStart, blockEnd) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Write the managed AGENTS.md block and return the exact block left in the
|
|
18
|
+
// file, which the manifest records so uninstall can remove it.
|
|
19
|
+
// - previousBlock: what this installer wrote last time (from its manifest).
|
|
20
|
+
// An existing block that differs from it was edited by hand and is only
|
|
21
|
+
// replaced with force.
|
|
22
|
+
// - Without a previous manifest, an existing block is kept unless force.
|
|
23
|
+
export async function applyManagedInstructions(file, block, { previousBlock, force = false, startMarker, endMarker }) {
|
|
24
|
+
const text = await readFile(file, 'utf8').catch((error) => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
25
|
+
const found = locateBlock(text, startMarker, endMarker);
|
|
26
|
+
if (!found) {
|
|
27
|
+
await writeFile(file, `${text}${block}`);
|
|
28
|
+
return block;
|
|
29
|
+
}
|
|
30
|
+
if (!force && previousBlock === undefined) return found.existing;
|
|
31
|
+
if (!force && found.existing !== previousBlock) {
|
|
32
|
+
throw new Error('The managed Loop Engineering block in AGENTS.md was edited by hand; restore it, remove it, or rerun with --force.');
|
|
33
|
+
}
|
|
34
|
+
await writeFile(file, `${text.slice(0, found.blockStart)}${block}${text.slice(found.blockEnd)}`);
|
|
35
|
+
return block;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Install the per-user dashboard unit unless it already serves another
|
|
39
|
+
// workspace. Returns the manifest record, including what to remove on
|
|
40
|
+
// uninstall.
|
|
41
|
+
export async function installDashboardUnlessShared({ root, listen, tailscaleBin, systemctlBin, run }) {
|
|
42
|
+
const installer = fileURLToPath(new URL('./dashboard-autostart-install.mjs', import.meta.url));
|
|
43
|
+
const args = [installer, '--root', root, '--listen', listen, '--tailscale-bin', tailscaleBin, '--systemctl-bin', systemctlBin, '--json'];
|
|
44
|
+
const planned = await run(process.execPath, args, { cwd: root });
|
|
45
|
+
if (planned.code !== 0) throw new Error(`Cannot plan Dashboard gateway autostart: ${(planned.stderr || planned.stdout).trim()}`);
|
|
46
|
+
const plan = JSON.parse(planned.stdout);
|
|
47
|
+
if (plan.conflict) return { listen, tailscaleBin, installed: false, skipped: plan.conflict };
|
|
48
|
+
const installed = await run(process.execPath, [...args, '--confirm-install'], { cwd: root });
|
|
49
|
+
if (installed.code !== 0) throw new Error(`Cannot install Dashboard gateway autostart: ${(installed.stderr || installed.stdout).trim()}`);
|
|
50
|
+
const report = JSON.parse(installed.stdout);
|
|
51
|
+
return {
|
|
52
|
+
listen,
|
|
53
|
+
tailscaleBin,
|
|
54
|
+
installed: true,
|
|
55
|
+
unit: 'loop-engineering-dashboard.service',
|
|
56
|
+
service: report.service,
|
|
57
|
+
serviceSha256: report.serviceSha256,
|
|
58
|
+
dropIns: report.gatewayDropIns,
|
|
59
|
+
dropInSha256: report.dropInSha256
|
|
60
|
+
};
|
|
61
|
+
}
|