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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, open, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { mkdir, open, readFile, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
|
|
@@ -56,29 +56,65 @@ export class TransactionalStateKernel {
|
|
|
56
56
|
});
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// Take the single-writer lease. Each lease receives a fencing token that is
|
|
60
|
+
// persisted immediately (fencing_issued), so two leases never share a token
|
|
61
|
+
// and a released or superseded lease can no longer commit.
|
|
59
62
|
async acquire(owner = `pid:${process.pid}`) {
|
|
60
63
|
await mkdir(this.directory, { recursive: true });
|
|
61
64
|
let handle;
|
|
62
65
|
try { handle = await open(this.lockFile, 'wx'); }
|
|
63
66
|
catch (error) {
|
|
64
67
|
if (error.code !== 'EEXIST') throw error;
|
|
65
|
-
const stale = await readJson(this.lockFile, null);
|
|
68
|
+
const stale = await readJson(this.lockFile, null).catch(() => null);
|
|
66
69
|
const pid = Number(String(stale?.owner ?? '').match(/^pid:(\d+)$/)?.[1]);
|
|
67
70
|
let alive = Number.isInteger(pid) && pid > 0;
|
|
68
71
|
if (alive) { try { process.kill(pid, 0); } catch (probe) { if (probe.code === 'ESRCH') alive = false; else throw probe; } }
|
|
69
72
|
if (alive || !pid) throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
73
|
+
// Serialize reclaim so two writers cannot both delete the dead lease.
|
|
74
|
+
const guard = `${this.lockFile}.reclaim`;
|
|
75
|
+
try { await mkdir(guard); } catch (guardError) {
|
|
76
|
+
if (guardError.code !== 'EEXIST') throw guardError;
|
|
77
|
+
const info = await stat(guard).catch(() => null);
|
|
78
|
+
if (info && Date.now() - info.mtimeMs > 10_000) await rmdir(guard).catch(() => {});
|
|
79
|
+
throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const again = await readJson(this.lockFile, null).catch(() => null);
|
|
83
|
+
if (again?.owner !== stale?.owner || again?.fencing_token !== stale?.fencing_token) throw new Error('Transactional writer lease is active or has an unverifiable owner.');
|
|
84
|
+
await rm(this.lockFile, { force: true });
|
|
85
|
+
handle = await open(this.lockFile, 'wx');
|
|
86
|
+
} finally { await rmdir(guard).catch(() => {}); }
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const current = await this.inspect();
|
|
90
|
+
const fencingToken = Math.max(Number(current.fencing_token ?? 0), Number(current.fencing_issued ?? 0)) + 1;
|
|
91
|
+
await handle.writeFile(JSON.stringify({ owner, fencing_token: fencingToken }));
|
|
92
|
+
await atomicWrite(this.stateFile, { ...current, fencing_issued: fencingToken });
|
|
93
|
+
return { owner, fencingToken, generation: current.generation, handle, released: false };
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await handle.close();
|
|
70
96
|
await rm(this.lockFile, { force: true });
|
|
71
|
-
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async acquireWithin(owner, timeoutMs = 10_000) {
|
|
102
|
+
const deadline = Date.now() + timeoutMs;
|
|
103
|
+
while (true) {
|
|
104
|
+
try { return await this.acquire(owner); }
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (!/lease is active/.test(String(error?.message)) || Date.now() >= deadline) throw error;
|
|
107
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
108
|
+
}
|
|
72
109
|
}
|
|
73
|
-
const current = await this.inspect();
|
|
74
|
-
const lease = { owner, fencingToken: current.fencing_token + 1, generation: current.generation, handle };
|
|
75
|
-
await handle.writeFile(JSON.stringify({ owner, fencing_token: lease.fencingToken }));
|
|
76
|
-
return lease;
|
|
77
110
|
}
|
|
78
111
|
|
|
79
112
|
async release(lease) {
|
|
113
|
+
if (lease.released) return;
|
|
114
|
+
lease.released = true;
|
|
80
115
|
await lease.handle.close();
|
|
81
|
-
await
|
|
116
|
+
const holder = await readJson(this.lockFile, null).catch(() => null);
|
|
117
|
+
if (holder?.fencing_token === lease.fencingToken) await rm(this.lockFile, { force: true });
|
|
82
118
|
}
|
|
83
119
|
|
|
84
120
|
async transact(input) {
|
|
@@ -86,7 +122,8 @@ export class TransactionalStateKernel {
|
|
|
86
122
|
const owned = !input.lease;
|
|
87
123
|
try {
|
|
88
124
|
const current = await this.inspect();
|
|
89
|
-
if (lease.fencingToken <= current.fencing_token
|
|
125
|
+
if (lease.released || lease.fencingToken <= current.fencing_token
|
|
126
|
+
|| (current.fencing_issued !== undefined && lease.fencingToken !== current.fencing_issued)) throw new Error('Stale fencing token.');
|
|
90
127
|
if (input.expectedGeneration !== undefined && input.expectedGeneration !== current.generation) {
|
|
91
128
|
throw new Error(`CAS generation mismatch: expected ${input.expectedGeneration}, actual ${current.generation}.`);
|
|
92
129
|
}
|
|
@@ -102,6 +139,10 @@ export class TransactionalStateKernel {
|
|
|
102
139
|
applied_effects: { ...current.applied_effects },
|
|
103
140
|
updated_at: new Date().toISOString()
|
|
104
141
|
};
|
|
142
|
+
if (input.clearPending && next.pending_effects?.[input.clearPending]) {
|
|
143
|
+
next.pending_effects = { ...next.pending_effects };
|
|
144
|
+
delete next.pending_effects[input.clearPending];
|
|
145
|
+
}
|
|
105
146
|
const receipts = [];
|
|
106
147
|
let previous = current.last_receipt;
|
|
107
148
|
for (const effect of fresh) {
|
|
@@ -130,18 +171,55 @@ export class TransactionalStateKernel {
|
|
|
130
171
|
} finally { if (owned) await this.release(lease); }
|
|
131
172
|
}
|
|
132
173
|
|
|
133
|
-
|
|
174
|
+
// Execute an external effect zero or one times. The writer lease is held
|
|
175
|
+
// from the applied-check through the commit, so concurrent callers wait and
|
|
176
|
+
// then observe the receipt. An intent is persisted before execute(); if a
|
|
177
|
+
// crash leaves it uncommitted, the effect is never re-run automatically and
|
|
178
|
+
// must be settled with reconcileEffect().
|
|
179
|
+
async replayEffect(effect, execute, options = {}) {
|
|
134
180
|
const normalized = typedEffect(effect.type, effect.payload, { key: effect.key });
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
181
|
+
const lease = await this.acquireWithin(options.owner, options.timeoutMs);
|
|
182
|
+
try {
|
|
183
|
+
const current = await this.inspect();
|
|
184
|
+
const existing = current.applied_effects[normalized.key];
|
|
185
|
+
if (existing) return { executed: false, replayed: true, receipt: existing.receipt };
|
|
186
|
+
const pending = current.pending_effects?.[normalized.key];
|
|
187
|
+
if (pending) return { executed: false, replayed: false, reconcileRequired: true, pending };
|
|
188
|
+
await atomicWrite(this.stateFile, { ...current, pending_effects: { ...(current.pending_effects ?? {}), [normalized.key]: { effect: normalized, started_at: new Date().toISOString(), fencing_token: lease.fencingToken } } });
|
|
189
|
+
const outcome = await execute(normalized);
|
|
190
|
+
const committed = await this.#commitEffect(lease, normalized, outcome);
|
|
191
|
+
return { executed: true, replayed: false, outcome, receipt: committed.receipts[0]?.receipt };
|
|
192
|
+
} finally { await this.release(lease); }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Settle an effect left pending by a crash: executed=true records the
|
|
196
|
+
// supplied outcome as applied; executed=false clears the intent so the
|
|
197
|
+
// effect may be replayed.
|
|
198
|
+
async reconcileEffect(effect, { executed, outcome = null, owner } = {}) {
|
|
199
|
+
const normalized = typedEffect(effect.type, effect.payload, { key: effect.key });
|
|
200
|
+
const lease = await this.acquireWithin(owner);
|
|
201
|
+
try {
|
|
202
|
+
const current = await this.inspect();
|
|
203
|
+
if (!current.pending_effects?.[normalized.key]) throw new Error(`No pending effect to reconcile: ${normalized.key}`);
|
|
204
|
+
if (executed === true) {
|
|
205
|
+
const committed = await this.#commitEffect(lease, normalized, outcome);
|
|
206
|
+
return { reconciled: 'applied', receipt: committed.receipts[0]?.receipt };
|
|
207
|
+
}
|
|
208
|
+
if (executed !== false) throw new Error('reconcileEffect requires executed: true or false.');
|
|
209
|
+
const pending = { ...current.pending_effects };
|
|
210
|
+
delete pending[normalized.key];
|
|
211
|
+
await atomicWrite(this.stateFile, { ...current, pending_effects: pending });
|
|
212
|
+
return { reconciled: 'cleared' };
|
|
213
|
+
} finally { await this.release(lease); }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async #commitEffect(lease, normalized, outcome) {
|
|
217
|
+
return this.transact({
|
|
218
|
+
lease,
|
|
141
219
|
effects: [normalized],
|
|
142
|
-
reduce: (state) => ({ ...state, effect_outcomes: { ...(state.effect_outcomes ?? {}), [normalized.key]: outcome } })
|
|
220
|
+
reduce: (state) => ({ ...state, effect_outcomes: { ...(state.effect_outcomes ?? {}), [normalized.key]: outcome } }),
|
|
221
|
+
clearPending: normalized.key
|
|
143
222
|
});
|
|
144
|
-
return { executed: true, replayed: false, outcome, receipt: committed.receipts[0]?.receipt };
|
|
145
223
|
}
|
|
146
224
|
|
|
147
225
|
async verifyReceiptChain() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "taskforce-loop-engineering",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
|
|
6
6
|
"type": "module",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node scripts/hermes-install-self-test.mjs",
|
|
31
31
|
"check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
|
|
32
32
|
"check:human-gates": "node --check lib/human-gate-command.mjs && node --check lib/human-gate-channel-adapter.mjs && node scripts/human-gate-command-self-test.mjs && node scripts/human-gate-final-judgement.mjs",
|
|
33
|
-
"check": "npm run check:project-gates && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
|
|
33
|
+
"check": "npm run check:project-gates && node scripts/safety-regression-self-test.mjs && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
|
|
34
34
|
"pack:dry": "npm pack --dry-run"
|
|
35
35
|
},
|
|
36
36
|
"exports": {
|
|
@@ -76,7 +76,6 @@
|
|
|
76
76
|
},
|
|
77
77
|
"homepage": "https://github.com/ambitioncn/taskforce-loop-engineering#readme",
|
|
78
78
|
"license": "Apache-2.0",
|
|
79
|
-
"main": "index.js",
|
|
80
79
|
"directories": {
|
|
81
80
|
"doc": "docs",
|
|
82
81
|
"example": "examples",
|
|
@@ -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,
|
|
@@ -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
|
+
}
|