taskforce-loop-engineering 0.16.4 → 0.16.6
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 +28 -0
- package/README.md +11 -1
- package/docs/isolated-verification.md +30 -3
- package/lib/context-budget.mjs +12 -2
- package/lib/core.mjs +151 -30
- package/lib/isolated-verification.mjs +14 -1
- package/package.json +2 -2
- package/scripts/continuation-regression-self-test.mjs +210 -0
- package/scripts/hermes-doctor.mjs +41 -2
- package/scripts/hermes-install-self-test.mjs +24 -0
- package/scripts/hermes-install.mjs +1 -70
- package/scripts/hermes-sources.mjs +77 -0
- package/scripts/isolated-verification-self-test.mjs +31 -2
- package/scripts/isolated-verify-self-test.py +32 -0
- package/scripts/isolated-verify.py +122 -9
- package/scripts/route-notify-self-test.mjs +12 -1
- package/skills/taskforce-loop-engineering/SKILL.md +6 -6
- package/skills/taskforce-loop-engineering/references/context-budget.md +2 -2
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { mkdir } from 'node:fs/promises';
|
|
6
|
+
import { buildFinalJudgement, enqueueTask, inferTaskScope, notifyTerminalTasks, queueRequeue, queueSchedulerTick, runQueueOnce, writeJson } from '../lib/core.mjs';
|
|
7
|
+
import { contextWorkerInstructions } from '../lib/context-budget.mjs';
|
|
8
|
+
|
|
9
|
+
// A worker that follows the dev plan's checkpoint template exactly. `script`
|
|
10
|
+
// receives the tick number and returns { status, exit } decisions.
|
|
11
|
+
async function templateWorker(root, body) {
|
|
12
|
+
const worker = path.join(root, 'worker.mjs');
|
|
13
|
+
await writeFile(worker, `import { readFile, writeFile } from 'node:fs/promises';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
const dir = path.join(process.env.LOOP_CHECKPOINTS_DIR, '..');
|
|
16
|
+
const plan = JSON.parse(await readFile(path.join(dir, 'dev_plan.json'), 'utf8'));
|
|
17
|
+
const schema = plan.checkpoint_schema;
|
|
18
|
+
const marker = ${JSON.stringify(path.join(root, 'tick'))};
|
|
19
|
+
let tick = 0; try { tick = Number(await readFile(marker, 'utf8')); } catch {}
|
|
20
|
+
await writeFile(marker, String(tick + 1));
|
|
21
|
+
const n = Number(schema.checkpoint_id.slice(2));
|
|
22
|
+
const write = (fields) => writeFile(path.join(process.env.LOOP_CHECKPOINTS_DIR, schema.checkpoint_id + '.json'), JSON.stringify({
|
|
23
|
+
task_id: plan.task_id, checkpoint_id: schema.checkpoint_id, milestone_id: schema.milestone_id,
|
|
24
|
+
revises_checkpoint_id: schema.revises_checkpoint_id, sequence: n, created_at: new Date(Date.UTC(2026, 0, n)).toISOString(),
|
|
25
|
+
summary: 'work', files_changed: [], verification: ['npm test passed (' + schema.checkpoint_id + ')'], blockers: [], risks: [], deferred_gates: [], ...fields }));
|
|
26
|
+
${body}`);
|
|
27
|
+
return { queue: 'regress', dispatcher: `node '${worker}'`, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const roots = [];
|
|
31
|
+
try {
|
|
32
|
+
// A bounded task revised once along the template is accepted; before, the
|
|
33
|
+
// revision got a new milestone id and the first review stayed live.
|
|
34
|
+
{
|
|
35
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-revise-')); roots.push(root);
|
|
36
|
+
const { task } = await enqueueTask(root, { queue: 'regress', title: 'fix bug', task: 'Fix the login redirect bug in the auth module.' });
|
|
37
|
+
const options = await templateWorker(root, `await write({ status: tick === 0 ? 'in_progress' : 'ready_for_acceptance' });`);
|
|
38
|
+
const first = await runQueueOnce(root, options);
|
|
39
|
+
assert.equal(first.run.finalJudgement.outcome, 'needs_revision');
|
|
40
|
+
await queueRequeue(root, 'regress', task.id);
|
|
41
|
+
const second = await runQueueOnce(root, options);
|
|
42
|
+
assert.notEqual(second.run.finalJudgement.outcome, 'needs_revision', JSON.stringify(second.run.finalJudgement.reasons));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// A project interrupted after writing an accepted checkpoint continues
|
|
46
|
+
// after recovery instead of failing as "no progress" or "not covered".
|
|
47
|
+
{
|
|
48
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-recover-')); roots.push(root);
|
|
49
|
+
await enqueueTask(root, { queue: 'regress', title: 'project', task: '开发完整项目并完成整体目标' });
|
|
50
|
+
const options = await templateWorker(root, `if (tick === 2) process.exit(0);
|
|
51
|
+
await write({ status: 'ready_for_acceptance', project_completion: { status: 'in_progress' } });
|
|
52
|
+
if (tick === 1) { console.error('gateway is draining for restart'); process.exit(1); }`);
|
|
53
|
+
const statuses = [];
|
|
54
|
+
for (let i = 0; i < 4; i += 1) statuses.push((await runQueueOnce(root, options)).run?.status ?? 'not_processed');
|
|
55
|
+
assert.deepEqual(statuses, ['project_in_progress', 'runtime_interrupted', 'project_in_progress', 'project_in_progress']);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Checkpoints written by the 0.16.1-0.16.4 template carry a new milestone
|
|
59
|
+
// id per revision; an explicit revises_checkpoint_id keeps them one chain,
|
|
60
|
+
// so a resolved historical blocker does not veto the accepted revision.
|
|
61
|
+
{
|
|
62
|
+
const contract = { task_id: 't', task_scope: 'scoped_task', requires_human_gate: false };
|
|
63
|
+
const reviews = { reviews: [
|
|
64
|
+
{ checkpointId: 'cp1', milestoneId: 'cp1', sequence: 1, checkpointCreatedAt: '2026-01-01T00:00:00Z', status: 'blocked' },
|
|
65
|
+
{ checkpointId: 'cp2', milestoneId: 'cp2', revisesCheckpointId: 'cp1', sequence: 2, checkpointCreatedAt: '2026-01-02T00:00:00Z', status: 'accepted', taskTerminal: true }
|
|
66
|
+
] };
|
|
67
|
+
const judgement = buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp2' }] }, { count: 2 }, reviews, { dispatchStatus: 'completed' });
|
|
68
|
+
assert.equal(judgement.outcome, 'ready_to_apply');
|
|
69
|
+
assert.deepEqual(judgement.coverage.effective_review_ids, ['cp2']);
|
|
70
|
+
// Without the revision link a different milestone's blocker stays live.
|
|
71
|
+
const unlinked = { reviews: [reviews.reviews[0], { ...reviews.reviews[1], revisesCheckpointId: null }] };
|
|
72
|
+
assert.equal(buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp2' }] }, { count: 2 }, unlinked, { dispatchStatus: 'completed' }).outcome, 'blocked');
|
|
73
|
+
}
|
|
74
|
+
// Context handoffs: capped, blockers surfaced, and never stale.
|
|
75
|
+
{
|
|
76
|
+
const handoffWorker = async (root, extra) => {
|
|
77
|
+
const worker = path.join(root, 'handoff-worker.mjs');
|
|
78
|
+
await writeFile(worker, `import { mkdir, writeFile } from 'node:fs/promises';
|
|
79
|
+
import path from 'node:path';
|
|
80
|
+
const e = process.env;
|
|
81
|
+
await mkdir(e.LOOP_CHECKPOINTS_DIR, { recursive: true });
|
|
82
|
+
const checkpoint = path.join(e.LOOP_CHECKPOINTS_DIR, e.LOOP_RUN_ID + '.json');
|
|
83
|
+
await writeFile(checkpoint, JSON.stringify({ task_id: e.LOOP_TASK_ID, loop_run_id: e.LOOP_RUN_ID, checkpoint_id: e.LOOP_RUN_ID, status: 'in_progress', summary: 'still working', blockers: [], verification: [{ command: 'npm test', outcome: 'failed', log: e.LOOP_WORKER_OUTPUT_PREFIX + '.stdout.log' }], risks: [], next_action: 'continue' }));
|
|
84
|
+
const handoff = { version: 1, taskId: e.LOOP_TASK_ID, runId: e.LOOP_RUN_ID, generation: Number(e.LOOP_SESSION_GENERATION), attempt: Number(e.LOOP_ATTEMPT), reason: 'context_budget', checkpoint, summary: 's', completed: [], remaining: ['fix tests'], evidence: [checkpoint], nextAction: 'fix', authority: 'local', pendingActions: [], blockers: [] };
|
|
85
|
+
${extra}
|
|
86
|
+
await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, JSON.stringify(handoff));
|
|
87
|
+
`);
|
|
88
|
+
return { queue: 'regress', dispatcher: `node '${worker}'`, retry: { maxAttempts: 1, runtimeRecoveryMaxAttempts: 2, maxContextHandoffs: 3 }, checkpointPollMs: 0, progressHeartbeatMs: 0 };
|
|
89
|
+
};
|
|
90
|
+
// A worker whose evidence differs every turn (a run-specific log path)
|
|
91
|
+
// still stops after maxContextHandoffs instead of looping forever.
|
|
92
|
+
{
|
|
93
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-loop-')); roots.push(root);
|
|
94
|
+
await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.' });
|
|
95
|
+
const options = await handoffWorker(root, '');
|
|
96
|
+
const statuses = [];
|
|
97
|
+
for (let i = 0; i < 6; i += 1) {
|
|
98
|
+
const result = await runQueueOnce(root, options);
|
|
99
|
+
if (!result.processed) break;
|
|
100
|
+
statuses.push(result.status);
|
|
101
|
+
}
|
|
102
|
+
assert.deepEqual(statuses, ['runtime_interrupted', 'runtime_interrupted', 'runtime_interrupted', 'runtime_blocked']);
|
|
103
|
+
}
|
|
104
|
+
// Handoff blockers and pending external actions reach the human.
|
|
105
|
+
{
|
|
106
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-blocker-')); roots.push(root);
|
|
107
|
+
await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.', sourceChannel: 'telegram', sourceTarget: '1' });
|
|
108
|
+
const options = await handoffWorker(root, "handoff.blockers = ['NEED_PROD_DB_PASSWORD']; handoff.pendingActions = ['payment request 42'];");
|
|
109
|
+
const result = await runQueueOnce(root, options);
|
|
110
|
+
assert.equal(result.status, 'needs_human_input');
|
|
111
|
+
const judgement = JSON.parse(await readFile(path.join(root, result.run.finalJudgement.path), 'utf8'));
|
|
112
|
+
assert.match(judgement.reasons.join(' '), /NEED_PROD_DB_PASSWORD/);
|
|
113
|
+
assert.match(judgement.next_actions[0], /payment request 42/);
|
|
114
|
+
const notice = await notifyTerminalTasks(root, { queue: 'regress', dryRun: true });
|
|
115
|
+
assert.match(notice.results[0].message, /NEED_PROD_DB_PASSWORD/);
|
|
116
|
+
assert.match(notice.results[0].message, /payment request 42/);
|
|
117
|
+
}
|
|
118
|
+
// A later session is not pointed at an earlier session's handoff.
|
|
119
|
+
{
|
|
120
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-handoff-stale-')); roots.push(root);
|
|
121
|
+
const { task } = await enqueueTask(root, { queue: 'regress', title: 't', task: 'Fix the failing test.' });
|
|
122
|
+
const options = await handoffWorker(root, "if (Number(e.LOOP_SESSION_GENERATION) > 0) { console.error('maximum context length exceeded'); process.exit(1); }");
|
|
123
|
+
await runQueueOnce(root, options);
|
|
124
|
+
await runQueueOnce(root, options);
|
|
125
|
+
const inbox = JSON.parse(await readFile(path.join(root, 'runtime/loops/regress/inbox', `${task.id}.json`), 'utf8'));
|
|
126
|
+
assert.equal(inbox.contextHandoffFile, undefined, 'a run without a handoff clears the previous one');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Scope inference: ordinary words containing 不/别 and temporal "after the
|
|
131
|
+
// first step" are not bounded-scope negations or cues.
|
|
132
|
+
for (const [body, expected] of [
|
|
133
|
+
['继续整体项目,特别要求只处理第 3 项', 'scoped_task'],
|
|
134
|
+
['继续整体项目:在不同模块中只处理第 2 项', 'scoped_task'],
|
|
135
|
+
['Continue the project-level plan: no UI changes needed - only complete backlog item 2', 'scoped_task'],
|
|
136
|
+
['Continue the project-level work. Without network access complete backlog item 2', 'scoped_task'],
|
|
137
|
+
['项目级任务:完成第一步之后不要停,继续完成完整项目', 'project'],
|
|
138
|
+
['继续整体项目,不要只处理第 3 项', 'project'],
|
|
139
|
+
['完成完整项目,不仅是有界里程碑,而且不是仅完成第一步', 'project']
|
|
140
|
+
]) assert.equal(inferTaskScope({ body }), expected, body);
|
|
141
|
+
|
|
142
|
+
// Malformed coverage evidence and id collisions do not crash or overcount.
|
|
143
|
+
{
|
|
144
|
+
const contract = { task_id: 't', task_scope: 'scoped_task', requires_human_gate: false };
|
|
145
|
+
const plan = { checkpoints: [{ id: 'cp1' }, { id: 'cp2' }] };
|
|
146
|
+
const collision = { reviews: [
|
|
147
|
+
{ checkpointId: 'cp1', milestoneId: 'cp1', sequence: 1, checkpointCreatedAt: '2026-01-01T00:00:00Z', status: 'revise' },
|
|
148
|
+
{ checkpointId: 'cp2', milestoneId: 'cp1', revisesCheckpointId: 'cp1', sequence: 2, checkpointCreatedAt: '2026-01-02T00:00:00Z', status: 'accepted' }
|
|
149
|
+
] };
|
|
150
|
+
const judged = buildFinalJudgement(contract, { rubric: [], automation: [] }, plan, { count: 2 }, collision, { dispatchStatus: 'completed' });
|
|
151
|
+
assert.equal(judged.outcome, 'needs_revision', 'one review cannot cover two milestones');
|
|
152
|
+
const malformed = { reviews: [
|
|
153
|
+
{ checkpointId: 'cp1', milestoneId: 'cp1', taskId: 't', sequence: 1, status: 'revise', phaseOnly: true, checkpointDigest: 'a'.repeat(64) },
|
|
154
|
+
{ checkpointId: 'cp2', milestoneId: 'cp1', taskId: 't', sequence: 2, status: 'accepted', verification: { commands: ['npm test'] },
|
|
155
|
+
revisionCoverage: [{ checkpoint_id: 'cp1', checkpoint_sha256: 'a'.repeat(64), resolution: 'fixed', verification: ['npm test'] }] }
|
|
156
|
+
] };
|
|
157
|
+
assert.doesNotThrow(() => buildFinalJudgement(contract, { rubric: [], automation: [] }, { checkpoints: [{ id: 'cp1' }] }, { count: 2 }, malformed, { dispatchStatus: 'completed' }));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// An unreadable gate checkpoint does not stop the queue.
|
|
161
|
+
{
|
|
162
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-gate-')); roots.push(root);
|
|
163
|
+
const gates = path.join(root, 'runtime/loops/regress/human-input/gates');
|
|
164
|
+
await mkdir(gates, { recursive: true });
|
|
165
|
+
await writeJson(path.join(gates, 'broken.json'), { gate_id: 'broken', status: 'waiting_for_human', task_id: 'ghost', checkpoint_id: 'cp1', project_id: 'p' });
|
|
166
|
+
await mkdir(path.join(root, 'runtime/loops/regress/tasks/ghost/checkpoints'), { recursive: true });
|
|
167
|
+
await writeFile(path.join(root, 'runtime/loops/regress/tasks/ghost/checkpoints/cp1.json'), '{"truncated');
|
|
168
|
+
await enqueueTask(root, { queue: 'regress', title: 'healthy', task: 'Fix the login redirect bug.' });
|
|
169
|
+
const result = await runQueueOnce(root, { queue: 'regress', dispatcher: 'true', checkpointPollMs: 0, progressHeartbeatMs: 0 });
|
|
170
|
+
assert.equal(result.processed, true);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Work is not split into needlessly small turns: the worker is told to
|
|
174
|
+
// finish the milestone, and a continuation is scheduled right after the run
|
|
175
|
+
// instead of idling for a quarter of every long turn.
|
|
176
|
+
{
|
|
177
|
+
const instructions = contextWorkerInstructions({});
|
|
178
|
+
assert.doesNotMatch(instructions, /one small objective|one bounded objective this turn/);
|
|
179
|
+
assert.match(instructions, /Complete as much of the current milestone as this turn allows/);
|
|
180
|
+
// Larger turns are told the dispatch timeout so they hand off before it.
|
|
181
|
+
assert.doesNotMatch(instructions, /TIME BUDGET/);
|
|
182
|
+
assert.match(contextWorkerInstructions({ LOOP_TURN_TIMEOUT_MS: '1800000' }), /stopped after about 30 minutes\. By about 24 minutes in/);
|
|
183
|
+
|
|
184
|
+
const scheduler = { initialIntervalMs: 200, minIntervalMs: 200, maxIntervalMs: 3600000, jitterMs: 0 };
|
|
185
|
+
const tickOnce = async (root, options) => {
|
|
186
|
+
const nowMs = Date.now();
|
|
187
|
+
const tick = await queueSchedulerTick(root, { ...options, scheduler, nowMs, forceDue: true });
|
|
188
|
+
return { tick, idleAfterRunMs: Date.parse(tick.nextRunAt) - (nowMs + (tick.run?.run?.durationMs ?? Date.parse(tick.run?.run?.finishedAt) - Date.parse(tick.run?.run?.startedAt))) };
|
|
189
|
+
};
|
|
190
|
+
const root = await mkdtemp(path.join(tmpdir(), 'loop-continuation-schedule-')); roots.push(root);
|
|
191
|
+
await enqueueTask(root, { queue: 'regress', title: 'project', task: '开发完整项目并完成整体目标' });
|
|
192
|
+
const options = await templateWorker(root, `if (process.env.LOOP_TURN_TIMEOUT_MS !== '1800000') process.exit(3);
|
|
193
|
+
await new Promise((resolve) => setTimeout(resolve, 3000));
|
|
194
|
+
await write({ status: 'ready_for_acceptance', project_completion: { status: 'in_progress' } });
|
|
195
|
+
if (tick === 1) { console.error('gateway is draining for restart'); process.exit(1); }`);
|
|
196
|
+
const continued = await tickOnce(root, options);
|
|
197
|
+
assert.equal(continued.tick.status, 'project_in_progress');
|
|
198
|
+
assert.equal(continued.tick.outcomeGroup, 'continuation');
|
|
199
|
+
assert.deepEqual(continued.tick.reasons, ['continuation_after_progress']);
|
|
200
|
+
assert.ok(continued.idleAfterRunMs >= 150 && continued.idleAfterRunMs < 600, `continuation waits only the minimum interval after the run (${continued.idleAfterRunMs} ms)`);
|
|
201
|
+
// A real runtime interruption keeps its recovery headroom.
|
|
202
|
+
const interrupted = await tickOnce(root, options);
|
|
203
|
+
assert.equal(interrupted.tick.status, 'runtime_interrupted');
|
|
204
|
+
assert.notEqual(interrupted.tick.outcomeGroup, 'continuation');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
console.log('continuation regression self-test passed');
|
|
208
|
+
} finally {
|
|
209
|
+
for (const root of roots) await rm(root, { recursive: true, force: true });
|
|
210
|
+
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { access, readFile } from 'node:fs/promises';
|
|
3
3
|
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
4
5
|
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { dispatcherSource, notifierSource, wrapperSource } from './hermes-sources.mjs';
|
|
5
8
|
|
|
6
9
|
function parseArgs(argv) {
|
|
7
10
|
const out = { root: process.cwd(), queue: 'agent-tasks', hermesBin: 'hermes', json: false };
|
|
@@ -9,6 +12,41 @@ function parseArgs(argv) {
|
|
|
9
12
|
return out;
|
|
10
13
|
}
|
|
11
14
|
function run(command, args, options = {}) { return new Promise((resolve) => { const child = spawn(command, args, { cwd: options.cwd, env: options.env || process.env, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk) => { stdout += chunk; }); child.stderr.on('data', (chunk) => { stderr += chunk; }); child.on('error', (error) => resolve({ code: 127, stdout, stderr: `${stderr}${error.message}` })); child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 128 : 1), stdout, stderr })); }); }
|
|
15
|
+
const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
16
|
+
|
|
17
|
+
// Generated scripts only change when the installer is rerun. Compare each
|
|
18
|
+
// installed copy with what this package would write, so an npm upgrade that
|
|
19
|
+
// changes them is not silently missed. Warnings, not failures: the old copies
|
|
20
|
+
// still run.
|
|
21
|
+
async function generatedFileWarnings(root, queue) {
|
|
22
|
+
const manifest = await readFile(path.join(root, 'runtime/loop-engineering-hermes-install.json'), 'utf8').then(JSON.parse).catch(() => null);
|
|
23
|
+
if (!manifest?.hermesBin) return [];
|
|
24
|
+
const loopBin = fileURLToPath(new URL('../bin/loop-engineering.mjs', import.meta.url));
|
|
25
|
+
// Manifests written before the language was recorded fall back to the queue config.
|
|
26
|
+
const queueName = manifest.queue ?? queue;
|
|
27
|
+
const queueLanguage = manifest.language ?? await readFile(path.join(root, `configs/loops/queues/${queueName}.json`), 'utf8').then((value) => JSON.parse(value).language).catch(() => undefined);
|
|
28
|
+
const options = { hermesBin: manifest.hermesBin, language: queueLanguage === 'zh' ? 'zh' : 'en', queue: queueName, loopBin };
|
|
29
|
+
const expected = { dispatcher: dispatcherSource(options), wrapper: wrapperSource(options), notifier: notifierSource(options) };
|
|
30
|
+
const relative = { dispatcher: 'scripts/loops/hermes-loop-dispatch.mjs', wrapper: 'scripts/loops/hermes-loop.mjs', notifier: 'scripts/loops/hermes-loop-notify.mjs' };
|
|
31
|
+
const upgrade = `rerun loop-engineering-hermes-install --queue ${options.queue} --language ${options.language} --confirm-install --force to regenerate it (this also rewrites the queue config, the scheduler units and the managed AGENTS.md block)`;
|
|
32
|
+
const warnings = [];
|
|
33
|
+
for (const [kind, content] of Object.entries(expected)) {
|
|
34
|
+
const installed = await readFile(path.join(root, relative[kind]), 'utf8').catch(() => null);
|
|
35
|
+
if (installed === null) continue;
|
|
36
|
+
const installedSha = sha256(installed);
|
|
37
|
+
if (installedSha === sha256(content)) continue;
|
|
38
|
+
const recorded = Array.isArray(manifest.files) ? manifest.files.find((file) => file.kind === kind)?.sha256 : undefined;
|
|
39
|
+
const edited = recorded !== undefined && recorded !== installedSha;
|
|
40
|
+
warnings.push({
|
|
41
|
+
id: `generated_file_${edited ? 'edited' : 'outdated'}:${relative[kind]}`,
|
|
42
|
+
detail: edited
|
|
43
|
+
? `${relative[kind]} was edited after installation and differs from what this package generates; ${upgrade}, which overwrites the edits.`
|
|
44
|
+
: `${relative[kind]} was generated by another Loop Engineering version or package location (the wrapper runs the CLI it was generated for); ${upgrade}.`
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return warnings;
|
|
48
|
+
}
|
|
49
|
+
|
|
12
50
|
async function present(file) { try { await access(file); return true; } catch { return false; } }
|
|
13
51
|
|
|
14
52
|
async function main() {
|
|
@@ -23,7 +61,8 @@ async function main() {
|
|
|
23
61
|
if (await present(queueFile)) { try { const queue = JSON.parse(await readFile(queueFile, 'utf8')); checks.push({ id: 'queue_config', ok: queue.queue === args.queue && queue.dispatcher === 'node scripts/loops/hermes-loop-dispatch.mjs' }); } catch (error) { checks.push({ id: 'queue_config', ok: false, detail: error.message }); } }
|
|
24
62
|
const notifier = path.join(args.root, 'scripts/loops/hermes-loop-notify.mjs');
|
|
25
63
|
if (await present(notifier)) { const dry = await run(process.execPath, [notifier, 'Loop Engineering notification dry-run'], { cwd: args.root, env: { ...process.env, LOOP_NOTIFICATION_DRY_RUN: '1', LOOP_NOTIFICATION_SOURCE: JSON.stringify({ channel: 'telegram', target: 'telegram:loop-doctor-dry-run' }) } }); checks.push({ id: 'notification_dry_run', ok: dry.code === 0 && dry.stdout.includes('"dryRun":true'), detail: (dry.stdout || dry.stderr).trim().slice(0, 500) }); }
|
|
26
|
-
const
|
|
27
|
-
|
|
64
|
+
const warnings = await generatedFileWarnings(args.root, args.queue);
|
|
65
|
+
const failed = checks.filter((check) => !check.ok); const report = { version: 1, platform: 'hermes', status: failed.length ? 'fail' : 'ok', readOnly: true, externalWrite: false, root: args.root, queue: args.queue, checks, failed: failed.map((check) => check.id), warnings };
|
|
66
|
+
console.log(args.json ? JSON.stringify(report, null, 2) : [`Hermes Loop doctor: ${report.status}`, `checks: ${checks.length - failed.length}/${checks.length}`, `failed: ${report.failed.join(', ') || 'none'}`, ...warnings.map((warning) => `warning: ${warning.detail}`)].join('\n')); if (failed.length) process.exitCode = 1;
|
|
28
67
|
}
|
|
29
68
|
main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
4
5
|
import { tmpdir } from 'node:os';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
|
|
@@ -16,6 +17,7 @@ if (args[0] === '--version') console.log('Hermes Agent v0.20.0');
|
|
|
16
17
|
else if (args[0] === 'send' && args.includes('--help')) console.log('hermes send --to TARGET MESSAGE');
|
|
17
18
|
else if (args[0] === 'send') { if (process.env.HERMES_SEND_CAPTURE) await writeFile(process.env.HERMES_SEND_CAPTURE, JSON.stringify(args)); console.log('sent'); }
|
|
18
19
|
else if (args.includes('-z')) {
|
|
20
|
+
if (process.env.HERMES_PROMPT_CAPTURE) await writeFile(process.env.HERMES_PROMPT_CAPTURE, args[args.indexOf('-z') + 1]);
|
|
19
21
|
if (process.env.LOOP_CHECKPOINTS_DIR) { const dir = path.resolve(process.cwd(), process.env.LOOP_CHECKPOINTS_DIR); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, 'cp1.json'), JSON.stringify({ version: 1, task_id: process.env.LOOP_TASK_ID, checkpoint_id: 'cp1', status: 'ready_for_acceptance', summary: 'Hermes read-only smoke completed.', files_changed: [], verification: [{ command: 'mock hermes smoke', outcome: 'passed' }], blockers: [], risks: [], next_action: 'acceptance_review' })); }
|
|
20
22
|
console.log('SMOKE_OK');
|
|
21
23
|
} else process.exitCode = 2;
|
|
@@ -35,12 +37,34 @@ const instructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8'); if (!
|
|
|
35
37
|
const wrapper = await readFile(path.join(root, 'scripts/loops/hermes-loop.mjs'), 'utf8'); if (!wrapper.includes('queue') || !wrapper.includes('continue') || /只入队|只排队|继续当前/.test(wrapper)) throw new Error('Hermes English wrapper routing was not fully localized');
|
|
36
38
|
if (!wrapper.includes('process.exitCode = tickCode;') || wrapper.includes('process.exitCode = tickCode || humanCode || terminalCode;')) throw new Error('Hermes scheduler health still depends on notification delivery');
|
|
37
39
|
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');
|
|
40
|
+
{
|
|
41
|
+
// The one-shot worker is told the dispatch timeout so it checkpoints and finishes before the runner kills it.
|
|
42
|
+
const taskFile = path.join(root, 'prompt-task.json'); const promptCapture = path.join(root, 'prompt.txt'); await writeFile(taskFile, JSON.stringify({ id: 'prompt-task', body: 'Do the work.' }));
|
|
43
|
+
const dispatch = (extra) => run(process.execPath, [path.join(root, 'scripts/loops/hermes-loop-dispatch.mjs')], { env: { ...process.env, LOOP_TASK_FILE: taskFile, HERMES_PROMPT_CAPTURE: promptCapture, ...extra } });
|
|
44
|
+
if ((await dispatch({ LOOP_TURN_TIMEOUT_MS: '1800000' })).code !== 0 || !/stopped after about 30 minutes: by about 24 minutes in/.test(await readFile(promptCapture, 'utf8'))) throw new Error('Hermes dispatcher does not pass the turn time budget');
|
|
45
|
+
if ((await dispatch({ LOOP_TURN_TIMEOUT_MS: '' })).code !== 0 || /stopped after about/.test(await readFile(promptCapture, 'utf8'))) throw new Error('Hermes dispatcher invents a time budget without LOOP_TURN_TIMEOUT_MS');
|
|
46
|
+
}
|
|
38
47
|
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
48
|
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
49
|
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
50
|
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
51
|
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
52
|
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}`);
|
|
53
|
+
{
|
|
54
|
+
// The doctor warns, without failing, when a generated script is out of date or was edited.
|
|
55
|
+
if (JSON.parse(doctorResult.stdout).warnings?.length !== 0) throw new Error(`fresh Hermes install reports warnings: ${doctorResult.stdout}`);
|
|
56
|
+
const dispatcherFile = path.join(root, 'scripts/loops/hermes-loop-dispatch.mjs'); const manifestFile = path.join(root, 'runtime/loop-engineering-hermes-install.json');
|
|
57
|
+
const current = await readFile(dispatcherFile, 'utf8'); const manifestText = await readFile(manifestFile, 'utf8');
|
|
58
|
+
const doctorWarnings = async () => { const result = await run(process.execPath, [doctor, '--root', root, '--queue', 'hermes-tasks', '--hermes-bin', mockHermes, '--json']); if (result.code !== 0 || JSON.parse(result.stdout).status !== 'ok') throw new Error(`Hermes doctor failed on a stale file: ${result.stdout}`); return JSON.parse(result.stdout).warnings; };
|
|
59
|
+
const older = current.replace('Do not route or enqueue this task again.', 'Do not route this task again.');
|
|
60
|
+
await writeFile(dispatcherFile, older);
|
|
61
|
+
const manifest = JSON.parse(manifestText); manifest.files.find((file) => file.kind === 'dispatcher').sha256 = createHash('sha256').update(older).digest('hex'); await writeFile(manifestFile, JSON.stringify(manifest));
|
|
62
|
+
const outdated = await doctorWarnings(); if (outdated.length !== 1 || outdated[0].id !== 'generated_file_outdated:scripts/loops/hermes-loop-dispatch.mjs' || !outdated[0].detail.includes('--queue hermes-tasks --language en --confirm-install --force')) throw new Error(`Hermes doctor missed an outdated dispatcher: ${JSON.stringify(outdated)}`);
|
|
63
|
+
await writeFile(manifestFile, manifestText);
|
|
64
|
+
const edited = await doctorWarnings(); if (edited.length !== 1 || edited[0].id !== 'generated_file_edited:scripts/loops/hermes-loop-dispatch.mjs') throw new Error(`Hermes doctor missed an edited dispatcher: ${JSON.stringify(edited)}`);
|
|
65
|
+
await writeFile(dispatcherFile, current);
|
|
66
|
+
if ((await doctorWarnings()).length !== 0) throw new Error('Hermes doctor still warns after the dispatcher is restored');
|
|
67
|
+
}
|
|
44
68
|
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
69
|
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
70
|
// Reinstalling in another language replaces the managed AGENTS.md block.
|
|
@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto';
|
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { applyManagedInstructions, installDashboardUnlessShared } from './install-shared.mjs';
|
|
8
|
+
import { dispatcherSource, notifierSource, text, wrapperSource } from './hermes-sources.mjs';
|
|
8
9
|
|
|
9
10
|
function parseArgs(argv) {
|
|
10
11
|
const out = { root: process.cwd(), queue: 'agent-tasks', hermesBin: 'hermes', systemctlBin: 'systemctl', dashboardListen: 'localhost', tailscaleBin: 'tailscale', language: 'auto', json: false, confirmInstall: false, force: false };
|
|
@@ -32,7 +33,6 @@ function resolveLanguage(requested = 'auto', env = process.env) {
|
|
|
32
33
|
if (requested !== 'auto') return requested;
|
|
33
34
|
return String(env.LC_ALL || env.LC_MESSAGES || env.LANG || '').toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
|
34
35
|
}
|
|
35
|
-
const text = (language, en, zh) => language === 'zh' ? zh : en;
|
|
36
36
|
|
|
37
37
|
function safeId(value, label) { if (!/^[a-zA-Z0-9._-]+$/.test(value)) throw new Error(`${label} contains unsupported characters.`); return value; }
|
|
38
38
|
// WorkingDirectory= takes the path literally (systemd does not decode C
|
|
@@ -79,75 +79,6 @@ function formatConfirmationSummary(summary, language) {
|
|
|
79
79
|
].join('\n');
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
function dispatcherSource({ hermesBin, language }) {
|
|
83
|
-
const intro = language === 'zh' ? ['你收到的是一个已经由 Loop Engineering 管理的任务。', '不要再次路由或入队。', '实施前阅读任务合同、开发计划、验收计划和实时补充要求。'] : ['You are receiving an already loop-managed task.', 'Do not route or enqueue this task again.', 'Read the task contract, development plan, acceptance plan, and live amendments before implementation.'];
|
|
84
|
-
const finish = text(language, 'Before each checkpoint and final completion, reread the live amendment file. Write a checkpoint when possible and finish with status, evidence, verification, blockers, and next action.', '每次写检查点和最终完成前都重新读取实时补充要求文件。尽可能写检查点,并以状态、证据、验证、阻塞和下一步结束。');
|
|
85
|
-
return `#!/usr/bin/env node
|
|
86
|
-
import { readFile } from 'node:fs/promises';
|
|
87
|
-
import { spawn } from 'node:child_process';
|
|
88
|
-
const task = JSON.parse(await readFile(process.env.LOOP_TASK_FILE, 'utf8'));
|
|
89
|
-
const prompt = [
|
|
90
|
-
${intro.map((line) => JSON.stringify(line)).join(',\n ')},
|
|
91
|
-
\`Task id: \${task.id}\`,
|
|
92
|
-
\`Task contract: \${process.env.LOOP_TASK_CONTRACT_FILE || 'not provided'}\`,
|
|
93
|
-
\`Development plan: \${process.env.LOOP_DEV_PLAN_FILE || 'not provided'}\`,
|
|
94
|
-
\`Acceptance plan: \${process.env.LOOP_ACCEPTANCE_PLAN_FILE || 'not provided'}\`,
|
|
95
|
-
\`Live amendments: \${process.env.LOOP_LATEST_AMENDMENT_FILE || 'not provided'}\`,
|
|
96
|
-
\`Checkpoints dir: \${process.env.LOOP_CHECKPOINTS_DIR || 'not provided'}\`,
|
|
97
|
-
'', task.body, '',
|
|
98
|
-
${JSON.stringify(finish)}
|
|
99
|
-
].join('\\n');
|
|
100
|
-
const child = spawn(${JSON.stringify(hermesBin)}, ['-z', prompt], { cwd: process.cwd(), env: process.env, stdio: 'inherit' });
|
|
101
|
-
child.on('close', (code, signal) => { process.exitCode = code ?? (signal ? 128 : 1); });
|
|
102
|
-
`;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function wrapperSource({ queue, loopBin, language }) {
|
|
106
|
-
const amendmentPattern = language === 'zh' ? '(?:继续(?:当前|这个)?\\s*loop|给(?:当前|这个)?\\s*loop\\s*(?:补充|增加|加)|补充当前\\s*loop)' : '(?:continue\\s+(?:the\\s+)?(?:current\\s+)?loop|amend\\s+(?:the\\s+)?(?:current\\s+)?loop|add\\s+(?:this\\s+)?amendment\\s+to\\s+(?:the\\s+)?(?:current\\s+)?loop)';
|
|
107
|
-
const queueOnlyPattern = language === 'zh' ? '(?:只入队|只排队|暂不执行|不立即执行)' : '(?:queue\\s+(?:this|it)\\s+only|only\\s+queue\\s+(?:this|it)|enqueue\\s+(?:this|it)\\s+only|do\\s+not\\s+(?:run|execute)\\s+(?:this|it)\\s+(?:yet|now))';
|
|
108
|
-
return `#!/usr/bin/env node
|
|
109
|
-
import { spawn } from 'node:child_process';
|
|
110
|
-
const [command, ...rest] = process.argv.slice(2);
|
|
111
|
-
function run(args) { return new Promise((resolve) => { const child = spawn(process.execPath, [${JSON.stringify(loopBin)}, ...args], { cwd: process.cwd(), env: process.env, stdio: 'inherit' }); child.on('close', (code, signal) => resolve(code ?? (signal ? 128 : 1))); }); }
|
|
112
|
-
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
113
|
-
async function runWhenUnlocked(args, waitMs = 300000) { const deadline = Date.now() + waitMs; while (true) { const code = await run(args); if (code !== 2 || Date.now() >= deadline) return code; await wait(250); } }
|
|
114
|
-
if (command === 'route') {
|
|
115
|
-
const messageIndex = rest.indexOf('--message'); const message = messageIndex >= 0 ? String(rest[messageIndex + 1] || '') : '';
|
|
116
|
-
const amendment = new RegExp(${JSON.stringify(amendmentPattern)}, 'i').test(message);
|
|
117
|
-
const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', amendment ? '--amend-active' : '--supersede-active', ...rest]);
|
|
118
|
-
const queueOnly = new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
|
|
119
|
-
const runCode = routeCode || queueOnly || amendment ? routeCode : await runWhenUnlocked(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
120
|
-
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
121
|
-
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
122
|
-
process.exitCode = routeCode || runCode || humanCode || terminalCode;
|
|
123
|
-
} else if (command === 'run-once') {
|
|
124
|
-
const runCode = await run(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs', ...rest]);
|
|
125
|
-
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
126
|
-
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
127
|
-
process.exitCode = runCode || humanCode || terminalCode;
|
|
128
|
-
} else if (command === 'scheduler-tick') {
|
|
129
|
-
const tickCode = await run(['queue-scheduler-tick', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs', ...rest]);
|
|
130
|
-
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
131
|
-
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
132
|
-
process.exitCode = tickCode;
|
|
133
|
-
} else { console.error(${JSON.stringify(text(language, 'Usage: node scripts/loops/hermes-loop.mjs route|run-once|scheduler-tick', '用法:node scripts/loops/hermes-loop.mjs route|run-once|scheduler-tick'))}); process.exitCode = 1; }
|
|
134
|
-
`;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function notifierSource({ hermesBin, language }) {
|
|
138
|
-
return `#!/usr/bin/env node
|
|
139
|
-
import { spawn } from 'node:child_process';
|
|
140
|
-
const message = process.argv.slice(2).join(' ').trim();
|
|
141
|
-
const rawSource = process.env.LOOP_HUMAN_INPUT_SOURCE || process.env.LOOP_NOTIFICATION_SOURCE || '';
|
|
142
|
-
if (!message) { console.error(${JSON.stringify(text(language, 'loop notifier requires a message', 'loop 通知器需要消息参数'))}); process.exit(2); }
|
|
143
|
-
let source; try { source = JSON.parse(rawSource); } catch { console.error(${JSON.stringify(text(language, 'loop notifier received invalid source metadata', 'loop 通知器收到无效的来源元数据'))}); process.exit(2); }
|
|
144
|
-
if (!source || typeof source !== 'object' || !source.target) { console.error(${JSON.stringify(text(language, 'Hermes loop notifier requires source.target in platform[:chat[:thread]] form', 'Hermes loop 通知器要求 source.target 使用 platform[:chat[:thread]] 格式'))}); process.exit(2); }
|
|
145
|
-
const args = ['send', '--to', String(source.target), '--quiet', message];
|
|
146
|
-
if (process.env.LOOP_NOTIFICATION_DRY_RUN === '1') { console.log(JSON.stringify({ dryRun: true, command: ${JSON.stringify(hermesBin)}, args })); }
|
|
147
|
-
else { const child = spawn(${JSON.stringify(hermesBin)}, args, { cwd: process.cwd(), env: process.env, stdio: 'inherit' }); child.on('close', (code, signal) => { process.exitCode = code ?? (signal ? 128 : 1); }); }
|
|
148
|
-
`;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
82
|
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`; }
|
|
152
83
|
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`; }
|
|
153
84
|
function instructionsBlock({ queue, language }) {
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Generated Hermes workspace scripts. Shared by the installer, which writes
|
|
2
|
+
// them, and the doctor, which warns when an installed copy is out of date.
|
|
3
|
+
|
|
4
|
+
export const text = (language, en, zh) => language === 'zh' ? zh : en;
|
|
5
|
+
|
|
6
|
+
export function dispatcherSource({ hermesBin, language }) {
|
|
7
|
+
const intro = language === 'zh' ? ['你收到的是一个已经由 Loop Engineering 管理的任务。', '不要再次路由或入队。', '实施前阅读任务合同、开发计划、验收计划和实时补充要求。'] : ['You are receiving an already loop-managed task.', 'Do not route or enqueue this task again.', 'Read the task contract, development plan, acceptance plan, and live amendments before implementation.'];
|
|
8
|
+
// The runner kills a turn at its dispatch timeout; a one-shot Hermes turn
|
|
9
|
+
// that runs into it loses unsaved work and spends a recovery attempt.
|
|
10
|
+
const timeBudget = text(language, 'Complete as much of the task as this turn allows and checkpoint after each verified sub-step. This turn is stopped after about MINUTES minutes: by about BUDGET minutes in, stop starting new sub-steps, write a checkpoint with the remaining work and finish.', '这一轮尽量多完成任务,每验证完一个子步骤写一次检查点。这一轮约 MINUTES 分钟后会被终止:到约 BUDGET 分钟时不要再开始新的子步骤,写好包含剩余工作的检查点后结束。');
|
|
11
|
+
const finish = text(language, 'Before each checkpoint and final completion, reread the live amendment file. Write a checkpoint when possible and finish with status, evidence, verification, blockers, and next action.', '每次写检查点和最终完成前都重新读取实时补充要求文件。尽可能写检查点,并以状态、证据、验证、阻塞和下一步结束。');
|
|
12
|
+
return `#!/usr/bin/env node
|
|
13
|
+
import { readFile } from 'node:fs/promises';
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
const task = JSON.parse(await readFile(process.env.LOOP_TASK_FILE, 'utf8'));
|
|
16
|
+
const prompt = [
|
|
17
|
+
${intro.map((line) => JSON.stringify(line)).join(',\n ')},
|
|
18
|
+
\`Task id: \${task.id}\`,
|
|
19
|
+
\`Task contract: \${process.env.LOOP_TASK_CONTRACT_FILE || 'not provided'}\`,
|
|
20
|
+
\`Development plan: \${process.env.LOOP_DEV_PLAN_FILE || 'not provided'}\`,
|
|
21
|
+
\`Acceptance plan: \${process.env.LOOP_ACCEPTANCE_PLAN_FILE || 'not provided'}\`,
|
|
22
|
+
\`Live amendments: \${process.env.LOOP_LATEST_AMENDMENT_FILE || 'not provided'}\`,
|
|
23
|
+
\`Checkpoints dir: \${process.env.LOOP_CHECKPOINTS_DIR || 'not provided'}\`,
|
|
24
|
+
'', task.body, '',
|
|
25
|
+
...(Number(process.env.LOOP_TURN_TIMEOUT_MS) > 0 ? [${JSON.stringify(timeBudget)}.replace('MINUTES', String(Math.max(1, Math.floor(Number(process.env.LOOP_TURN_TIMEOUT_MS) / 60000)))).replace('BUDGET', String(Math.max(1, Math.floor(Number(process.env.LOOP_TURN_TIMEOUT_MS) * 0.8 / 60000))))] : []),
|
|
26
|
+
${JSON.stringify(finish)}
|
|
27
|
+
].join('\\n');
|
|
28
|
+
const child = spawn(${JSON.stringify(hermesBin)}, ['-z', prompt], { cwd: process.cwd(), env: process.env, stdio: 'inherit' });
|
|
29
|
+
child.on('close', (code, signal) => { process.exitCode = code ?? (signal ? 128 : 1); });
|
|
30
|
+
`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function wrapperSource({ queue, loopBin, language }) {
|
|
34
|
+
const amendmentPattern = language === 'zh' ? '(?:继续(?:当前|这个)?\\s*loop|给(?:当前|这个)?\\s*loop\\s*(?:补充|增加|加)|补充当前\\s*loop)' : '(?:continue\\s+(?:the\\s+)?(?:current\\s+)?loop|amend\\s+(?:the\\s+)?(?:current\\s+)?loop|add\\s+(?:this\\s+)?amendment\\s+to\\s+(?:the\\s+)?(?:current\\s+)?loop)';
|
|
35
|
+
const queueOnlyPattern = language === 'zh' ? '(?:只入队|只排队|暂不执行|不立即执行)' : '(?:queue\\s+(?:this|it)\\s+only|only\\s+queue\\s+(?:this|it)|enqueue\\s+(?:this|it)\\s+only|do\\s+not\\s+(?:run|execute)\\s+(?:this|it)\\s+(?:yet|now))';
|
|
36
|
+
return `#!/usr/bin/env node
|
|
37
|
+
import { spawn } from 'node:child_process';
|
|
38
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
39
|
+
function run(args) { return new Promise((resolve) => { const child = spawn(process.execPath, [${JSON.stringify(loopBin)}, ...args], { cwd: process.cwd(), env: process.env, stdio: 'inherit' }); child.on('close', (code, signal) => resolve(code ?? (signal ? 128 : 1))); }); }
|
|
40
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
41
|
+
async function runWhenUnlocked(args, waitMs = 300000) { const deadline = Date.now() + waitMs; while (true) { const code = await run(args); if (code !== 2 || Date.now() >= deadline) return code; await wait(250); } }
|
|
42
|
+
if (command === 'route') {
|
|
43
|
+
const messageIndex = rest.indexOf('--message'); const message = messageIndex >= 0 ? String(rest[messageIndex + 1] || '') : '';
|
|
44
|
+
const amendment = new RegExp(${JSON.stringify(amendmentPattern)}, 'i').test(message);
|
|
45
|
+
const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', amendment ? '--amend-active' : '--supersede-active', ...rest]);
|
|
46
|
+
const queueOnly = new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
|
|
47
|
+
const runCode = routeCode || queueOnly || amendment ? routeCode : await runWhenUnlocked(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
48
|
+
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
49
|
+
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
50
|
+
process.exitCode = routeCode || runCode || humanCode || terminalCode;
|
|
51
|
+
} else if (command === 'run-once') {
|
|
52
|
+
const runCode = await run(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs', ...rest]);
|
|
53
|
+
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
54
|
+
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
55
|
+
process.exitCode = runCode || humanCode || terminalCode;
|
|
56
|
+
} else if (command === 'scheduler-tick') {
|
|
57
|
+
const tickCode = await run(['queue-scheduler-tick', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/hermes-loop-notify.mjs', ...rest]);
|
|
58
|
+
const humanCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
59
|
+
const terminalCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/hermes-loop-notify.mjs']);
|
|
60
|
+
process.exitCode = tickCode;
|
|
61
|
+
} else { console.error(${JSON.stringify(text(language, 'Usage: node scripts/loops/hermes-loop.mjs route|run-once|scheduler-tick', '用法:node scripts/loops/hermes-loop.mjs route|run-once|scheduler-tick'))}); process.exitCode = 1; }
|
|
62
|
+
`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function notifierSource({ hermesBin, language }) {
|
|
66
|
+
return `#!/usr/bin/env node
|
|
67
|
+
import { spawn } from 'node:child_process';
|
|
68
|
+
const message = process.argv.slice(2).join(' ').trim();
|
|
69
|
+
const rawSource = process.env.LOOP_HUMAN_INPUT_SOURCE || process.env.LOOP_NOTIFICATION_SOURCE || '';
|
|
70
|
+
if (!message) { console.error(${JSON.stringify(text(language, 'loop notifier requires a message', 'loop 通知器需要消息参数'))}); process.exit(2); }
|
|
71
|
+
let source; try { source = JSON.parse(rawSource); } catch { console.error(${JSON.stringify(text(language, 'loop notifier received invalid source metadata', 'loop 通知器收到无效的来源元数据'))}); process.exit(2); }
|
|
72
|
+
if (!source || typeof source !== 'object' || !source.target) { console.error(${JSON.stringify(text(language, 'Hermes loop notifier requires source.target in platform[:chat[:thread]] form', 'Hermes loop 通知器要求 source.target 使用 platform[:chat[:thread]] 格式'))}); process.exit(2); }
|
|
73
|
+
const args = ['send', '--to', String(source.target), '--quiet', message];
|
|
74
|
+
if (process.env.LOOP_NOTIFICATION_DRY_RUN === '1') { console.log(JSON.stringify({ dryRun: true, command: ${JSON.stringify(hermesBin)}, args })); }
|
|
75
|
+
else { const child = spawn(${JSON.stringify(hermesBin)}, args, { cwd: process.cwd(), env: process.env, stdio: 'inherit' }); child.on('close', (code, signal) => { process.exitCode = code ?? (signal ? 128 : 1); }); }
|
|
76
|
+
`;
|
|
77
|
+
}
|
|
@@ -7,6 +7,16 @@ import { execFileSync } from 'node:child_process';
|
|
|
7
7
|
import { enqueueTask, runCommand, runQueueOnce } from '../lib/core.mjs';
|
|
8
8
|
import { runIsolatedVerification, validateIsolatedVerification } from '../lib/isolated-verification.mjs';
|
|
9
9
|
|
|
10
|
+
// These tests drive the real sandbox. Say what is missing instead of failing
|
|
11
|
+
// later on an unrelated file read.
|
|
12
|
+
const missingTools = process.platform !== 'linux' ? ['Linux'] : ['bwrap', 'strace', 'python3'].filter((tool) => {
|
|
13
|
+
try { execFileSync('sh', ['-c', `command -v ${tool}`], { stdio: 'ignore' }); return false; } catch { return true; }
|
|
14
|
+
});
|
|
15
|
+
if (missingTools.length) {
|
|
16
|
+
console.error(`isolated verification self-test needs ${missingTools.join(', ')} (Debian/Ubuntu: apt-get install bubblewrap strace python3). Set LOOP_SKIP_ISOLATION_TESTS=1 to skip it on machines that cannot run the sandbox.`);
|
|
17
|
+
process.exit(process.env.LOOP_SKIP_ISOLATION_TESTS === '1' ? 0 : 1);
|
|
18
|
+
}
|
|
19
|
+
|
|
10
20
|
const base = await mkdtemp(path.join(tmpdir(), 'loop-isolation-self-test-'));
|
|
11
21
|
const quote = (value) => "'" + String(value).replaceAll("'", "'\"'\"'") + "'";
|
|
12
22
|
const run = async (project, command, inputs, label, runtimeFiles = []) => {
|
|
@@ -28,7 +38,7 @@ await writeFile(path.join(pythonProject, 'input.txt'), 'hello\n');
|
|
|
28
38
|
await writeFile(path.join(pythonProject, 'hidden.txt'), 'private\n');
|
|
29
39
|
const python = await run(pythonProject, 'cat input.txt > /out/result.txt', ['input.txt'], 'python-pass');
|
|
30
40
|
assert.equal(python.result.exitCode, 0, JSON.stringify(python.terminal) + '\n' +
|
|
31
|
-
(await readFile(path.join(base, 'python-pass', 'stderr.log'), 'utf8')).slice(0, 500));
|
|
41
|
+
(await readFile(path.join(base, 'python-pass', 'stderr.log'), 'utf8').catch(() => '')).slice(0, 500));
|
|
32
42
|
assert.equal(python.terminal.status, 'passed');
|
|
33
43
|
assert.equal((await readFile(path.join(base, 'python-pass', 'output', 'result.txt'), 'utf8')).trim(), 'hello');
|
|
34
44
|
|
|
@@ -188,6 +198,11 @@ for (const [label, command, expected] of [
|
|
|
188
198
|
['double-slash', 'cat //work/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
|
|
189
199
|
['missing-alias', 'cat //work/../work/missing.txt 2>/dev/null || true', 'passed'],
|
|
190
200
|
['file-alias', 'cat ../work/input.txt/../hidden.txt 2>/dev/null || true', 'passed'],
|
|
201
|
+
['symlink-tmp', 'ln -s /work /tmp/w; cat /tmp/w/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
|
|
202
|
+
['symlink-out', 'ln -s /work /out/w; cat /out/w/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
|
|
203
|
+
['symlink-renamed', 'ln -s /work /tmp/a; mv /tmp/a /tmp/b; cat /tmp/b/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
|
|
204
|
+
['symlink-missing', 'ln -s /work /tmp/w; cat /tmp/w/missing.txt 2>/dev/null || true', 'passed'],
|
|
205
|
+
['task-alias', 'cat /proc/self/task/$$/cwd/hidden.txt 2>/dev/null || true', 'failed_or_unknown'],
|
|
191
206
|
]) {
|
|
192
207
|
await enqueueTask(queueProject, { queue: 'path-' + label, title: label, task: 'Verify path semantics' });
|
|
193
208
|
const outcome = await runQueueOnce(queueProject, { queue: 'path-' + label, dispatcher: 'true',
|
|
@@ -198,4 +213,18 @@ for (const [label, command, expected] of [
|
|
|
198
213
|
if (expected !== 'passed') assert.equal(outcome.status, 'verify_failed');
|
|
199
214
|
}
|
|
200
215
|
|
|
201
|
-
|
|
216
|
+
// The sandbox holds no capabilities even when the host runs as root: it can
|
|
217
|
+
// neither remount the read-only system binds nor read root-only host files.
|
|
218
|
+
const privileges = await run(pythonProject, "grep CapEff /proc/self/status > /out/caps.txt; " +
|
|
219
|
+
"mount -o remount,rw,bind /usr 2>/dev/null && touch /usr/.loop-isolation-probe 2>/dev/null; " +
|
|
220
|
+
"cat /etc/shadow > /out/shadow.txt 2>/dev/null; true", ['input.txt'], 'privileges');
|
|
221
|
+
assert.equal(privileges.terminal.status, 'passed', JSON.stringify(privileges.terminal));
|
|
222
|
+
assert.match(await readFile(path.join(base, 'privileges', 'output', 'caps.txt'), 'utf8'), /CapEff:\s+0+\s*$/);
|
|
223
|
+
assert.equal(await readFile('/usr/.loop-isolation-probe').then(() => true, () => false), false, 'the sandbox wrote the host /usr');
|
|
224
|
+
assert.equal((await readFile(path.join(base, 'privileges', 'output', 'shadow.txt'), 'utf8').catch(() => '')).length, 0, 'the sandbox read /etc/shadow');
|
|
225
|
+
|
|
226
|
+
// A failed isolation says why.
|
|
227
|
+
const reasoned = await run(pythonProject, 'cat hidden.txt >/dev/null 2>&1 || true', ['input.txt'], 'reason');
|
|
228
|
+
assert.match(reasoned.result.isolation.reason, /read audit failed: undeclared available project input/);
|
|
229
|
+
|
|
230
|
+
console.log('isolated verification: two projects passed; undeclared input, aliases, forged trace and privileges rejected');
|
|
@@ -131,3 +131,35 @@ with tempfile.TemporaryDirectory() as tmp:
|
|
|
131
131
|
trace.write_text(f'1 access("{name}", R_OK) = -1 ENOENT (missing)\n')
|
|
132
132
|
assert not module.trace_verdict(trace, {}, root, {})[0]
|
|
133
133
|
print('self cwd/root aliases and unknown fd/process alias regressions passed')
|
|
134
|
+
|
|
135
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
136
|
+
root = Path(tmp)
|
|
137
|
+
(root / 'hidden.txt').write_text('hidden')
|
|
138
|
+
(root / 'sub').mkdir()
|
|
139
|
+
trace = root / 'trace'
|
|
140
|
+
# Symlinks the sandbox creates in /tmp or /out are followed by the audit,
|
|
141
|
+
# including after a rename and with relative targets.
|
|
142
|
+
for setup, probe, allowed in [
|
|
143
|
+
('1 symlink("/work", "/tmp/w") = 0\n', '/tmp/w/hidden.txt', False),
|
|
144
|
+
('1 symlinkat("../work", AT_FDCWD</tmp>, "rel") = 0\n', '/tmp/rel/hidden.txt', False),
|
|
145
|
+
('1 symlink("/work", "/out/w") = 0\n1 rename("/out/w", "/tmp/moved") = 0\n', '/tmp/moved/hidden.txt', False),
|
|
146
|
+
('1 symlink("/work", "/tmp/w") = 0\n', '/tmp/w/missing.txt', True),
|
|
147
|
+
('1 symlink("/usr", "/tmp/u") = 0\n', '/tmp/u/hidden.txt', True),
|
|
148
|
+
]:
|
|
149
|
+
trace.write_text('1 chdir("/work") = 0\n' + setup + f'1 access("{probe}", R_OK) = -1 ENOENT (missing)\n')
|
|
150
|
+
ok, errors = module.trace_verdict(trace, {}, root, {})
|
|
151
|
+
assert ok == allowed, (setup, probe, errors)
|
|
152
|
+
# Another thread's view cannot be proven to be this process's cwd/root.
|
|
153
|
+
for name in ['/proc/self/task/7/cwd/hidden.txt', '/proc/self/task/7/root/work/hidden.txt']:
|
|
154
|
+
trace.write_text(f'1 chdir("/work") = 0\n1 access("{name}", R_OK) = -1 ENOENT (missing)\n')
|
|
155
|
+
assert not module.trace_verdict(trace, {}, root, {})[0], name
|
|
156
|
+
# Calls that never return when the PID namespace is torn down are not
|
|
157
|
+
# unfinished file syscalls; an unfinished open still fails.
|
|
158
|
+
teardown = ('1 chdir("/work") = 0\n2 wait4(-1, <unfinished ...>\n3 exit_group(0) = ?\n'
|
|
159
|
+
'2 <... wait4 resumed> <unfinished ...>) = ?\n2 +++ killed by SIGKILL +++\n'
|
|
160
|
+
'4 exit_group(0 <unfinished ...>\n4 +++ killed by SIGKILL +++\n')
|
|
161
|
+
trace.write_text(teardown)
|
|
162
|
+
assert module.trace_verdict(trace, {}, root, {}) == (True, []), module.trace_verdict(trace, {}, root, {})
|
|
163
|
+
trace.write_text('1 chdir("/work") = 0\n5 openat(AT_FDCWD</work>, "hidden.txt", O_RDONLY <unfinished ...>\n5 +++ killed by SIGKILL +++\n')
|
|
164
|
+
assert not module.trace_verdict(trace, {}, root, {})[0]
|
|
165
|
+
print('created symlinks, task aliases and namespace teardown regressions passed')
|