taskforce-loop-engineering 0.16.5 → 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 CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Add a manually dispatched `Release` workflow (`.github/workflows/release.yml`). It verifies the version, the commit on main and the changelog section, and runs the full test suite. It then creates the tag and GitHub release and publishes to npm (trusted publishing or `NPM_TOKEN`) and ClawHub (`CLAWHUB_TOKEN`) from the `release` environment. Every step skips work that is already done, so a failed run can be dispatched again.
6
+
7
+ ## 0.16.6 - 2026-11-28
8
+
9
+ Loop speed release: workers complete whole milestones per turn instead of tiny steps, continuations are scheduled right after the run, and workers are told the dispatch timeout. Publication does not upgrade installed CLIs or generated integrations. OpenClaw picks up the new worker instructions with the package upgrade (re-run `loop-engineering-openclaw-manage --action upgrade --confirm-upgrade` as usual). Hermes needs its generated files regenerated: run `loop-engineering-hermes-doctor`, which now warns about out-of-date files, then rerun the installer with `--confirm-install --force` and the same `--queue` and `--language`; this also rewrites the queue config, scheduler units and managed `AGENTS.md` block, so back up local changes first. Without that, Hermes still gets the scheduler change but not the new turn-size and time-budget prompt.
10
+
11
+ - Stop splitting Loop work into needlessly small turns. Worker instructions no longer say "work on one bounded objective this turn" or, without live context telemetry, "finish one small objective and checkpoint"; workers complete as much of the current milestone as the turn allows, checkpoint after verified sub-steps and hand off only when the remaining work will not fit. The deterministic dev plan and the code-project template no longer ask for "the smallest useful change", and the distributed skill says the same.
12
+ - Schedule continuations right after the run: an accepted project milestone that continues (`project_in_progress`) or a validated context handoff is now its own `continuation` scheduler group and runs again the minimum interval after the run ends. Previously it fell into the unknown group, got no speed-up, and long-run headroom delayed the next tick to 1.25× the previous run's duration after its start, idling for a quarter of every long turn. Real runtime interruptions keep their recovery headroom.
13
+ - Tell workers the dispatch timeout. The runner sets `LOOP_TURN_TIMEOUT_MS` and the OpenClaw worker instructions ask for a checkpoint and handoff by about 80% of it, so the larger turns hand off instead of being killed at the timeout, which loses unsaved work and spends one of the default two runtime recovery attempts.
14
+ - The Hermes one-shot dispatcher now asks the worker to complete as much of the task as the turn allows, checkpoint verified sub-steps and finish before about 80% of `LOOP_TURN_TIMEOUT_MS`. Custom dispatchers receive `LOOP_TURN_TIMEOUT_MS` too (documented in the README). Generated Hermes files change only after rerunning the installer with `--confirm-install --force`.
15
+ - `loop-engineering-hermes-doctor` warns when an installed Hermes dispatcher, wrapper or notifier differs from what the current package generates, telling apart a copy from an older version and one edited by hand, and names the installer command that regenerates it. The warnings do not change the doctor's status or exit code. The generated-script sources moved to `scripts/hermes-sources.mjs`, shared by the installer and the doctor.
16
+
5
17
  ## 0.16.5 - 2026-11-02
6
18
 
7
19
  Security and correctness release for 0.16.1–0.16.4. Publication does not upgrade installed CLIs or generated integrations; re-run `loop-engineering-openclaw-manage --action upgrade --confirm-upgrade` (Hermes: rerun the installer with `--confirm-install --force`).
package/README.md CHANGED
@@ -284,7 +284,11 @@ loop-engineering-hermes-smoke \
284
284
  ```
285
285
 
286
286
  The doctor checks the Hermes CLI, `hermes send`, generated files, queue wiring,
287
- and a delivery dry-run. The smoke creates a temporary queue, executes a bounded
287
+ and a delivery dry-run. After a package upgrade, it also warns when a generated
288
+ dispatcher, wrapper or notifier is out of date (or was edited by hand) and prints
289
+ the installer command that regenerates it; rerunning with `--force` also rewrites
290
+ the queue config, scheduler units and managed `AGENTS.md` block, so back up local
291
+ changes first. The smoke creates a temporary queue, executes a bounded
288
292
  Hermes worker task, verifies contract/plan/final-judgement artifacts, tests the
289
293
  notification return path without sending externally, and removes its artifacts.
290
294
 
@@ -729,8 +733,14 @@ LOOP_HUMAN_REVISION_REQUEST_FILE_REL
729
733
  LOOP_RUN_ID
730
734
  LOOP_ATTEMPT
731
735
  LOOP_MAX_ATTEMPTS
736
+ LOOP_TURN_TIMEOUT_MS
732
737
  ```
733
738
 
739
+ `LOOP_TURN_TIMEOUT_MS` is the dispatch timeout after which the runner kills the
740
+ turn. Custom dispatchers should pass it to the worker so it checkpoints and
741
+ finishes (or hands off) before then; a killed turn loses unsaved work and
742
+ spends a runtime recovery attempt.
743
+
734
744
  Before dispatch, `run-queue` writes planning artifacts under
735
745
  `runtime/loops/<queue>/tasks/<task_id>/`: `task_contract.json`,
736
746
  `acceptance_plan.json`, `dev_plan.json`, `checkpoints/`, `reviews/`, and
@@ -60,12 +60,22 @@ export function validHandoff(value, { taskId, runId, generation, attempt }) {
60
60
  if (!['completed', 'remaining', 'evidence', 'pendingActions', 'blockers'].every(k => Array.isArray(value[k]) && value[k].every(x => typeof x === 'string'))) return false;
61
61
  return value.remaining.length > 0 && value.evidence.length > 0;
62
62
  }
63
+ // Larger turns must not run into the dispatch timeout: a killed turn loses
64
+ // its unsaved work and counts against runtime recovery attempts, while a
65
+ // handoff does not.
66
+ function turnTimeoutInstruction(value) {
67
+ const ms = Number(value);
68
+ if (!Number.isFinite(ms) || ms <= 0) return [];
69
+ const minutes = (x) => Math.max(1, Math.floor(x / 60000));
70
+ return ['TIME BUDGET: This turn is stopped after about ' + minutes(ms) + ' minutes. By about ' + minutes(ms * 0.8) + ' minutes in, stop starting new sub-steps, save a checkpoint and hand off any remaining work instead of running into the limit.'];
71
+ }
63
72
  export function contextWorkerInstructions(env = process.env) {
64
73
  const policy = JSON.parse(env.LOOP_CONTEXT_POLICY || JSON.stringify(DEFAULT_CONTEXT_POLICY));
65
74
  return [
66
- 'CONTEXT BUDGET: Work on one bounded objective this turn. Read only necessary file ranges. Keep each tool response around 8 KiB or less; put full logs in task artifacts and return paths plus short excerpts. This is a cooperative tool-output budget, not runtime enforcement.',
75
+ 'CONTEXT BUDGET: Complete as much of the current milestone as this turn allows; do not stop after one small step, because every extra turn repeats planning, acceptance and scheduling. Save a checkpoint at natural boundaries (after each verified sub-step) so progress survives a handoff. Read only necessary file ranges. Keep each tool response around 8 KiB or less; put full logs in task artifacts and return paths plus short excerpts. This is a cooperative tool-output budget, not runtime enforcement.',
67
76
  'Read the resume manifest at ' + (env.LOOP_RESUME_FILE || '(unavailable)') + ' and only the latest relevant checkpoint; never reload entire session transcripts or all historical checkpoints.',
68
- 'At approximately ' + Math.round(policy.softRatio * 100) + '% of the model context window, save a checkpoint and prepare handoff. At ' + Math.round(policy.hardRatio * 100) + '% stop new work and hand off. If live usage is unavailable, finish one small objective and checkpoint; do not invent token measurements.',
77
+ 'At approximately ' + Math.round(policy.softRatio * 100) + '% of the model context window, save a checkpoint and prepare handoff. At ' + Math.round(policy.hardRatio * 100) + '% stop new work and hand off. If live usage is unavailable, keep working through the milestone, checkpoint after each verified sub-step, and hand off only when the remaining work clearly will not fit this turn; do not invent token measurements.',
78
+ ...turnTimeoutInstruction(env.LOOP_TURN_TIMEOUT_MS),
69
79
  'Before repeating an external/paid/destructive operation, verify its previous outcome using durable receipts/reservations; an uncertain outcome is a blocker, never permission to replay. Preserve existing human gates and amendment versions.',
70
80
  'If unfinished work needs a fresh session, first write a normal progress checkpoint (not ready_for_acceptance) with task_id and loop_run_id matching this run, then write JSON to ' + (env.LOOP_CONTEXT_HANDOFF_FILE || '(unavailable)') + ' and finish the turn. Never claim completion merely because you handed off.',
71
81
  'Handoff schema (max 16 KiB): ' + JSON.stringify({ version: 1, taskId: env.LOOP_TASK_ID, runId: env.LOOP_RUN_ID, generation: Number(env.LOOP_SESSION_GENERATION || 0), attempt: Number(env.LOOP_ATTEMPT || 1), reason: 'context_budget', checkpoint: 'path to the current progress checkpoint', summary: 'brief current state', completed: ['completed work'], remaining: ['remaining work'], evidence: ['checkpoint and verification paths'], nextAction: 'one concrete next step', authority: 'authorized scope and gates', pendingActions: ['uncertain external action receipts to reconcile, if any'], blockers: [] }),
package/lib/core.mjs CHANGED
@@ -1508,7 +1508,7 @@ const PROJECT_TEMPLATES = {
1508
1508
  ],
1509
1509
  backlog: [
1510
1510
  ['Inspect project baseline', 'Identify the current structure, existing checks, and likely implementation boundaries.'],
1511
- ['Implement first scoped change', 'Complete the smallest useful code change from the brief.'],
1511
+ ['Implement first scoped change', 'Complete the first coherent code change from the brief end to end, including its tests.'],
1512
1512
  ['Verify behavior', 'Run the project checks and record evidence.'],
1513
1513
  ['Prepare review bundle', 'Produce reviewable patch and closeout artifacts.']
1514
1514
  ]
@@ -3938,7 +3938,7 @@ function buildDevPlan(contract, acceptancePlan, firstCheckpointId = 'cp1', miles
3938
3938
  requires_human_gate: contract.requires_human_gate,
3939
3939
  approach: gated
3940
3940
  ? 'Read the task contract and acceptance plan, produce bounded local artifacts and checkpoint evidence, and stop before any live instrumentation, process control, external action, or repeated human-blocked retry.'
3941
- : 'Read the task contract and acceptance plan, make the smallest useful change, and record checkpoint evidence before claiming completion.',
3941
+ : 'Read the task contract and acceptance plan, complete the requested change in as few turns as practical (checkpointing verified sub-steps along the way), and record checkpoint evidence before claiming completion.',
3942
3942
  acceptance_alignment: {
3943
3943
  functional_checks: acceptancePlan.functional_checks.map((_, index) => `functional:${index + 1}`),
3944
3944
  regression_checks: acceptancePlan.regression_checks.map((_, index) => `regression:${index + 1}`),
@@ -5075,7 +5075,7 @@ function queueSchedulerOutcomeGroup(status) {
5075
5075
  function updateSchedulerCounters(previous, group) {
5076
5076
  const counters = previous?.counters ?? {};
5077
5077
  return {
5078
- consecutiveSuccesses: group === 'success' ? (counters.consecutiveSuccesses ?? 0) + 1 : 0,
5078
+ consecutiveSuccesses: group === 'success' || group === 'continuation' ? (counters.consecutiveSuccesses ?? 0) + 1 : 0,
5079
5079
  consecutiveFailures: group === 'failure' ? (counters.consecutiveFailures ?? 0) + 1 : 0,
5080
5080
  consecutiveIdle: group === 'idle' ? (counters.consecutiveIdle ?? 0) + 1 : 0,
5081
5081
  consecutiveHumanGates: group === 'human_gate' ? (counters.consecutiveHumanGates ?? 0) + 1 : 0,
@@ -5093,10 +5093,24 @@ function computeQueueSchedulerInterval(previous, policy, observed) {
5093
5093
  const previousInterval = Number.isFinite(previous?.currentIntervalMs)
5094
5094
  ? previous.currentIntervalMs
5095
5095
  : policy.initialIntervalMs;
5096
- const group = queueSchedulerOutcomeGroup(observed.status);
5096
+ const group = observed.continuation ? 'continuation' : queueSchedulerOutcomeGroup(observed.status);
5097
5097
  let next = previousInterval;
5098
5098
  const reasons = [];
5099
5099
 
5100
+ // A task that just made accepted progress (a project milestone, or a
5101
+ // validated context handoff) is waiting to continue. Run it again as soon
5102
+ // as the minimum interval after this run ends: the long-run headroom below
5103
+ // would otherwise idle for a quarter of every long turn, and the queue lock
5104
+ // already prevents overlap.
5105
+ if (group === 'continuation') {
5106
+ return {
5107
+ intervalMs: clamp(policy.minIntervalMs, policy.minIntervalMs, policy.maxIntervalMs),
5108
+ group,
5109
+ reasons: ['continuation_after_progress'],
5110
+ fromRunEnd: true
5111
+ };
5112
+ }
5113
+
5100
5114
  if (group === 'success' && observed.statusAfter.queued > 0) {
5101
5115
  next = previousInterval * policy.speedupFactor;
5102
5116
  reasons.push('queued_work_after_success_speedup');
@@ -5345,12 +5359,18 @@ export async function queueSchedulerTick(root, options) {
5345
5359
  durationMs: runDurationMs(run),
5346
5360
  statusBefore,
5347
5361
  statusAfter,
5362
+ continuation: status === 'project_in_progress'
5363
+ || (status === 'runtime_interrupted' && run?.dispatchFailureClassification?.category === 'context_handoff'),
5348
5364
  runPath: runResult?.runPath ?? null,
5349
5365
  taskId: runResult?.run?.taskId ?? null
5350
5366
  };
5351
5367
  const decision = computeQueueSchedulerInterval(previous, policy, observed);
5352
5368
  const counters = updateSchedulerCounters(previous, decision.group);
5353
- const nextRunAt = new Date(nowMs + decision.intervalMs).toISOString();
5369
+ // Continuations count from the end of this run, not from the tick start.
5370
+ const scheduledFromMs = decision.fromRunEnd
5371
+ ? (options.nowMs !== undefined ? nowMs + (observed.durationMs ?? 0) : Date.now())
5372
+ : nowMs;
5373
+ const nextRunAt = new Date(scheduledFromMs + decision.intervalMs).toISOString();
5354
5374
  const progressNotification = decideQueueProgressNotification(previousProgress, progressPolicy, observed, decision, nowMs);
5355
5375
  const progressReport = {
5356
5376
  version: 1,
@@ -10397,6 +10417,7 @@ export async function runQueueOnce(root, options) {
10397
10417
  ...taskPlanningEnv(root, taskContract, acceptancePlan, devPlan),
10398
10418
  LOOP_SESSION_GENERATION: String(task.runtimeSessionGeneration ?? 0),
10399
10419
  LOOP_CONTEXT_POLICY: JSON.stringify(budgetPolicy),
10420
+ LOOP_TURN_TIMEOUT_MS: String(timeoutMs),
10400
10421
  LOOP_RESUME_FILE: resumeFile,
10401
10422
  LOOP_CONTEXT_HANDOFF_FILE: contextPrefix + '.handoff.json',
10402
10423
  LOOP_CONTEXT_USAGE_FILE: contextPrefix + '.usage.json',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-loop-engineering",
3
- "version": "0.16.5",
3
+ "version": "0.16.6",
4
4
  "private": false,
5
5
  "description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
6
6
  "type": "module",
@@ -3,7 +3,8 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { mkdir } from 'node:fs/promises';
6
- import { buildFinalJudgement, enqueueTask, inferTaskScope, notifyTerminalTasks, queueRequeue, runQueueOnce, writeJson } from '../lib/core.mjs';
6
+ import { buildFinalJudgement, enqueueTask, inferTaskScope, notifyTerminalTasks, queueRequeue, queueSchedulerTick, runQueueOnce, writeJson } from '../lib/core.mjs';
7
+ import { contextWorkerInstructions } from '../lib/context-budget.mjs';
7
8
 
8
9
  // A worker that follows the dev plan's checkpoint template exactly. `script`
9
10
  // receives the tick number and returns { status, exit } decisions.
@@ -169,6 +170,40 @@ await writeFile(e.LOOP_CONTEXT_HANDOFF_FILE, JSON.stringify(handoff));
169
170
  assert.equal(result.processed, true);
170
171
  }
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
+
172
207
  console.log('continuation regression self-test passed');
173
208
  } finally {
174
209
  for (const root of roots) await rm(root, { recursive: true, force: true });
@@ -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 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) };
27
- console.log(args.json ? JSON.stringify(report, null, 2) : `Hermes Loop doctor: ${report.status}\nchecks: ${checks.length - failed.length}/${checks.length}\nfailed: ${report.failed.join(', ') || 'none'}`); if (failed.length) process.exitCode = 1;
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
+ }
@@ -128,7 +128,7 @@ The confirmed Hermes install creates the same Dashboard service and couples it t
128
128
  The generated worker uses `hermes -z` (`--oneshot`); the notifier uses `hermes send` without
129
129
  an LLM call. Preserve source metadata and pass `--source-target` in Hermes
130
130
  `platform:chat_id[:thread_id]` format. The managed systemd scheduler owns wakeups
131
- so durable queue continuity does not depend on resuming a Hermes Cron session.
131
+ so durable queue continuity does not depend on resuming a Hermes Cron session. After a package upgrade, rerun the Hermes doctor: it warns when a generated dispatcher, wrapper or notifier is out of date or was edited, and names the installer command that regenerates it (`--force` also rewrites the queue config, scheduler units and managed `AGENTS.md` block). Workers receive the dispatch timeout as `LOOP_TURN_TIMEOUT_MS` and should checkpoint and finish or hand off by about 80% of it.
132
132
 
133
133
  ## Cross-interface Human Gates
134
134
 
@@ -166,7 +166,7 @@ Pass the original request faithfully. Preserve source channel, target, account,
166
166
 
167
167
  ## Context Budget and Durable Handoff
168
168
 
169
- For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Keep one bounded objective per turn, read bounded file ranges, and save checkpoints instead of replaying transcripts. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
169
+ For OpenClaw workers, follow `references/context-budget.md` before long-running work or recovery. Finish as much of the current milestone per turn as fits, read bounded file ranges, and save checkpoints after verified sub-steps instead of replaying transcripts; splitting work into many tiny turns is slow, because each turn repeats planning, acceptance and scheduling. Resolve paths against the resume manifest's workspace root; preserve authority, amendments, and action receipts across session rotation. A handoff is incomplete work, not acceptance. Verify the installed dispatcher and queue policy before claiming these protections are active.
170
170
 
171
171
  ## Task vs Project Classification
172
172
 
@@ -250,7 +250,7 @@ Timeouts must terminate the spawned process group. After instrumentation timeout
250
250
  2. Classify task vs project and define the correct contract before execution.
251
251
  3. Use `route-message` or the installed conversation wrapper to preserve source metadata and apply immediate/queue-only/amend/supersede semantics.
252
252
  4. Run preflight before mutable work.
253
- 5. Execute one bounded tick or the project’s next actionable backlog item.
253
+ 5. Execute one tick for the task or the project’s next actionable backlog item, completing that item within the tick where possible.
254
254
  6. Emit ordered progress: planning, preflight, worker start, checkpoints, verification, acceptance, final judgement.
255
255
  7. Inspect run artifacts; never infer success only from dispatcher exit code.
256
256
  8. If acceptance fails, write a revision request with changed diagnosis/tactic/evidence/verification.
@@ -354,7 +354,7 @@ Summaries must cite the latest run/task/project evidence, verification performed
354
354
 
355
355
  ## Scheduler Policy
356
356
 
357
- Use scheduler ticks only after manual verification. Adaptive schedules may speed up with successful queued work and back off on empty queues, failures, long runs, or human gates.
357
+ Use scheduler ticks only after manual verification. Adaptive schedules may speed up with successful queued work and back off on empty queues, failures, long runs, or human gates. A project milestone that was accepted and continues, or a validated context handoff, is scheduled again the minimum interval after its run ends, without long-run headroom.
358
358
 
359
359
  `queue-scheduler-tick` is adaptive cadence logic, not a resident daemon. A cron, systemd timer, or equivalent external scheduler must wake it regularly. For project queues that promise automatic continuation, set `scheduler.required=true` and a bounded `scheduler.heartbeatMaxAge`; `doctor` must fail with `scheduler_missing` whenever queued work exists without a fresh scheduler heartbeat.
360
360
 
@@ -1,9 +1,9 @@
1
1
  # Context budget and recovery
2
2
 
3
3
  1. Inspect the installed OpenClaw dispatcher and queue `retry` configuration. New installations use `sessionMaxTicks: 3` and `contextBudget: { softRatio: 0.60, hardRatio: 0.75 }`. Existing explicit tick limits are retained until a reviewed integration upgrade. A package/skill update alone does not update generated workspace files. Hermes does not yet expose the OpenClaw telemetry adapter; do not claim equivalent telemetry protection there.
4
- 2. Keep one bounded objective per worker turn. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
4
+ 2. Complete as much of the current milestone as one worker turn allows, checkpointing after each verified sub-step; do not stop after a single small step, because every extra turn repeats planning, acceptance review and scheduling. Request file ranges and filtered results, aim for tool responses below 8 KiB, and save full logs to artifacts. Large task bodies are referenced through `LOOP_TASK_FILE` rather than inlined. These are worker instructions, not a universal cap on tool output or an in-turn token interrupt.
5
5
  3. Read `LOOP_RESUME_FILE`, the task contract/plans, latest amendment and latest relevant checkpoint. Resolve relative references against its `workspaceRoot`. Read a previous handoff only for outstanding context; newer checkpoints and amendments take precedence. Do not reload complete transcripts or all historical checkpoints.
6
- 4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, use a small work unit rather than inventing a percentage. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
6
+ 4. At roughly 60% context use, prepare a checkpoint; at 75%, stop adding work and hand off. If live usage is not available, keep working through the milestone with frequent checkpoints and hand off only when the remaining work clearly will not fit the turn; never invent a percentage. The runner passes the dispatch timeout as `LOOP_TURN_TIMEOUT_MS`; by about 80% of it, stop starting new sub-steps, checkpoint and hand off, because a killed turn loses unsaved work and consumes a runtime recovery attempt while a validated handoff does not. The OpenClaw adapter measures the final prompt after the worker exits from `agentMeta.lastCallUsage.input + cacheRead` against `agentMeta.contextTokens`; aggregate `usage` is not context occupancy. Cache-write tokens are not added again. Missing, malformed or oversized CLI JSON falls back to tick-based rotation. This sample is not a live high-water mark: runtime compaction may already have reduced it.
7
7
  5. For unfinished work requiring a new session, write a normal progress checkpoint with `task_id`, `loop_run_id`, and `blockers`, then the bounded JSON handoff at `LOOP_CONTEXT_HANDOFF_FILE` using the schema provided in the worker prompt. Include task/run/generation/attempt binding, the checkpoint path, summary, completed and remaining work, evidence, next action, authority, pending external actions and blockers. Keep it under 16 KiB and omit secrets. The runner validates binding and a real checkpoint inside this task's checkpoint directory; missing/malformed/stale evidence stops recovery rather than accepting the task.
8
8
  6. Verify pending external, paid or destructive actions against durable receipts/reservations before replay. Uncertain outcomes and authority blockers stop automatic continuation, including when the worker exits nonzero. An existing handoff is checked before any retry; malformed or stale handoffs fail closed. A clean handoff never overrides a permission failure. Effective blocked checkpoint reviews are checked before each ordinary dispatch retry and also veto runtime recovery when interruption happens before handoff creation. Ordinary and verification failures with effective blockers remain `needs_human_input`, not development revisions; resolved historical blockers do not. Record checkpoint `created_at` (UTC) and, when known, a task-monotonic numeric `sequence`; checkpoint IDs and regenerated review timestamps are not ordering evidence. Conflicting or missing chronology preserves unresolved reviews rather than guessing from names. A newer unblocked snapshot with unambiguous chronology can resolve historical blockers. Multi-milestone plans use the same rule within each milestone and count each planned milestone only once. Terminal acceptance may ignore a chronologically later `needs_human_acceptance` project snapshot only if that review independently passes acceptance and carries no materializable deferred gates. The project label alone cannot hide a blocked/revise review; missing blocker details are not proof of broader-project-only governance. Test accepted terminal + later unknown external outcome under ordinary failure (one and multiple attempts), overflow, incomplete turn and exhausted recovery, including the generated dispatcher. The veto must prevent queue re-entry, not merely change the judgement report. A handoff cannot authorize an action. The runner preserves the task id and increments the session generation on a validated handoff or recognized context overflow; it never retries a known runtime interruption in the same session. Exception recoveries use `runtimeRecoveryMaxAttempts`, default 2; exhaustion stops as `runtime_blocked`. Successful validated handoffs with nonempty, previously unseen checkpoint verification rotate without consuming or resetting this counter. Repeated or empty verification stops even if checkpoint/run IDs change. Verification fingerprints are cooperative evidence, not independent semantic proof. Accepted project progress resets the exception recovery counter.
9
9
  7. Inspect task/run artifacts after each tick. Accepted unfinished project milestones rotate at the soft/hard threshold or tick limit, whichever occurs first; completed tasks are never requeued just because usage is high. Handoffs remain `runtime_interrupted`, not completed. Full worker stdout/stderr stay in per-run/per-attempt logs; bounded tails plus deduplicated diagnostic signatures reach the runner. Signatures are matched across the complete stream before clipping (including split UTF-8 chunks), using the queue's configured patterns; human-action classification retains priority over runtime recovery. CLI JSON parsing is capped at 2 MiB. No protection here guarantees that one tool-heavy turn cannot overflow: worker discipline and the underlying runtime's compaction remain necessary.