taskforce-loop-engineering 0.15.19 → 0.15.21

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,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.15.21 - 2026-09-30
6
+
7
+ - Add opt-in reconciliation of mutable project relay backlog statuses against unique accepted done-task evidence, while preserving fail-closed project, backlog, and task-binding checks.
8
+ - Defer internal relay tasks and accept their bound project-relay markers in the OpenClaw route installer.
9
+
10
+ ## 0.15.20 - 2026-09-29
11
+
12
+ - Add opt-in, source-preserving project backlog relay after accepted scoped tasks; fail closed on external or gated items, missing terminal authority, busy queues, and duplicates.
13
+ - Require a completed backlog-item binding and explicit in-progress terminal record for relay; reject missing or malformed authoritative backlogs instead of falling back to stale initial data.
14
+
5
15
  ## 0.15.19 - 2026-09-19
6
16
 
7
17
  - Recover OpenClaw dispatcher launches rejected during Gateway restart drain by rotating the runtime session and requeueing the task.
package/README.md CHANGED
@@ -425,6 +425,32 @@ loop-engineering project-status --root /path/to/workspace --project launch-site
425
425
  Project intake does not enqueue work or run a scheduler by itself. Use the
426
426
  generated backlog and existing queue commands when the plan is ready.
427
427
 
428
+ For an existing project that should relay from one accepted scoped task to the
429
+ next local item, opt in with `queues[].autostart: true` and an authoritative
430
+ backlog `items`/`tasks` entry with `status: "ready"`, `autoRun: true`,
431
+ `scope: "local_only"`, `externalActionsAllowed: false`,
432
+ `humanGateRequired: false`, a title, and a task body. The completed predecessor
433
+ must have an explicit `projectId`, `backlogItemId` (use `--backlog-item-id` when
434
+ enqueuing), full conversation source, and a `ready_to_apply` judgement. Its
435
+ bound backlog item must already have an accepted/completed status. The project
436
+ must have a readable acceptance ledger or terminal contract with explicit
437
+ `in_progress` or `ongoing` status, and its configured authoritative backlog
438
+ must be readable. The runner enqueues at most one
439
+ dependency-ready item after the accepted task; duplicate markers, a busy
440
+ queue, human gates, missing authority, or accepted project terminal state stop
441
+ the relay. The existing scheduler executes that queued item on its next tick.
442
+ The relay does not infer safe work from prose or promote project acceptance.
443
+
444
+ Projects with a mutable `backlogSource` may also set
445
+ `relayStatusReconciliation: true`. After an accepted task, Loop changes a
446
+ `ready` local-only relay item to `completed` only when exactly one matching
447
+ same-project task is in the done queue and its persisted final judgement is
448
+ `ready_to_apply` without a human gate. Missing, duplicate, failed, gated, or
449
+ external-action tasks leave the source unchanged. Reconciliation is idempotent
450
+ and also runs on subsequent non-plan-only scheduler ticks, so an interrupted
451
+ completion write can recover. It does not change the project acceptance ledger or requirement matrix. Do
452
+ not enable it on an immutable or generated authoritative backlog source.
453
+
428
454
  ## Observability
429
455
 
430
456
  Use `doctor` for a read-only health view of the loop workspace:
@@ -228,6 +228,7 @@ function parseArgs(argv) {
228
228
  else if (a === '--source-target') args.sourceTarget = argv[++i];
229
229
  else if (a === '--source-account') args.sourceAccount = argv[++i];
230
230
  else if (a === '--source-message-id') args.sourceMessageId = argv[++i];
231
+ else if (a === '--backlog-item-id') args.backlogItemId = argv[++i];
231
232
  else if (a === '--source-reply-to') args.sourceReplyTo = argv[++i];
232
233
  else if (a === '--progress-notify-command') args.progressNotifyCommand = argv[++i];
233
234
  else if (a === '--include-active') args.includeActive = true;
@@ -1637,7 +1638,7 @@ Advanced compatibility commands:
1637
1638
  loop-engineering project-intake --name project --brief "Project brief" [--type auto|web_app|code_project|research|content|ops|qa|knowledge_base|infra_audit|assistant_workflow] [--queue name] [--check "npm test"] [--root <workspace>] [--json]
1638
1639
  loop-engineering project-plan --project project [--root <workspace>] [--json] [--force]
1639
1640
  loop-engineering project-status --project project [--root <workspace>] [--json]
1640
- loop-engineering enqueue --queue name --title "Title" (--task "Body" | --file task.md) [--root <workspace>]
1641
+ loop-engineering enqueue --queue name --title "Title" (--task "Body" | --file task.md) [--backlog-item-id id] [--root <workspace>]
1641
1642
  loop-engineering route-message --message "User message" [--queue name] [--route --confirm-execute] [--supersede-active | --amend-active] [--source-channel name --source-target id --source-account id --source-message-id id --source-reply-to id] [--root <workspace>] [--json]
1642
1643
  loop-engineering run-queue --config configs/loops/queues/name.json [--progress-notify-command "command"] [--root <workspace>]
1643
1644
  loop-engineering run-queue --queue name --dispatcher "command" [--preflight-config configs/loops/name.json] [--root <workspace>]
package/lib/core.mjs CHANGED
@@ -1935,6 +1935,7 @@ export async function enqueueTask(root, options) {
1935
1935
  enqueuedAt: new Date().toISOString(),
1936
1936
  ...(options.riskAssessment ? { riskAssessment: options.riskAssessment } : {}),
1937
1937
  ...(options.projectId ? { projectId: normalizeProjectId(options.projectId) } : {}),
1938
+ ...(options.backlogItemId ? { backlogItemId: normalizeLoopId(options.backlogItemId) } : {}),
1938
1939
  ...(options.supersedesTaskId ? { supersedesTaskId: options.supersedesTaskId } : {}),
1939
1940
  ...(options.supersedeReason ? { supersedeReason: options.supersedeReason } : {}),
1940
1941
  ...(taskSourceFromOptions(options) ? { source: taskSourceFromOptions(options) } : {})
@@ -2589,6 +2590,124 @@ async function projectHasSafeActionableBacklog(root, spec, checkpoint = null) {
2589
2590
  });
2590
2591
  }
2591
2592
 
2593
+ export async function projectRelayReconcile(root, { queue, project } = {}) {
2594
+ project = normalizeProjectId(project);
2595
+ const spec = await readJson(projectConfigPathFor(root, project));
2596
+ if (spec.relayStatusReconciliation !== true || !spec.backlogSource
2597
+ || !spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true)) return { changed: 0 };
2598
+ const acceptance = await projectAcceptanceRecord(root, spec);
2599
+ const ledger = acceptance?.record;
2600
+ if (!ledger || typeof ledger !== 'object' || Array.isArray(ledger)
2601
+ || !['in_progress', 'ongoing'].includes(ledger.status)
2602
+ || ledger.terminalState?.accepted === true || ledger.terminalAccepted === true) return { changed: 0 };
2603
+ const backlogFile = path.resolve(root, safeRelativePath(spec.backlogSource, 'project backlog source'));
2604
+ let backlog;
2605
+ try { backlog = await readJson(backlogFile); } catch { return { changed: 0 }; }
2606
+ if (!backlog || typeof backlog !== 'object' || Array.isArray(backlog)) return { changed: 0 };
2607
+ const field = Array.isArray(backlog.items) ? 'items' : Array.isArray(backlog.tasks) ? 'tasks' : null;
2608
+ if (!field) return { changed: 0 };
2609
+ const completed = new Map();
2610
+ for (const file of await listJson(queueSubdirFor(root, queue, 'done'))) {
2611
+ const task = await readJson(path.join(queueSubdirFor(root, queue, 'done'), file));
2612
+ if (task.projectId !== project || task.status !== 'completed' || !task.id
2613
+ || !task.source?.channel || !task.source?.target || !task.source?.account || !task.source?.message_id) continue;
2614
+ const marker = String(task.body ?? '').match(/^\[project-relay:([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)\](?:\n|$)/);
2615
+ if (marker?.[1] !== project || task.backlogItemId !== marker[2]) continue;
2616
+ const ids = completed.get(marker[2]) ?? [];
2617
+ ids.push(task.id);
2618
+ completed.set(marker[2], ids);
2619
+ }
2620
+ const itemCounts = new Map();
2621
+ for (const item of backlog[field]) {
2622
+ if (item?.id) itemCounts.set(item.id, (itemCounts.get(item.id) ?? 0) + 1);
2623
+ }
2624
+ let changed = 0;
2625
+ const items = [];
2626
+ for (const item of backlog[field]) {
2627
+ if (!item || typeof item !== 'object' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(item.id ?? ''))
2628
+ || itemCounts.get(item.id) !== 1
2629
+ || (completed.get(item.id) ?? []).length !== 1
2630
+ || item.status !== 'ready' || item.autoRun !== true || item.scope !== 'local_only'
2631
+ || item.externalActionsAllowed !== false || item.humanGateRequired !== false) {
2632
+ items.push(item);
2633
+ continue;
2634
+ }
2635
+ const judgementFile = path.join(taskRuntimeDirFor(root, queue, completed.get(item.id)[0]), 'final_judgement.json');
2636
+ const judgement = await exists(judgementFile) ? await readJson(judgementFile) : null;
2637
+ if (judgement?.outcome !== 'ready_to_apply' || judgement.requires_human_gate !== false) {
2638
+ items.push(item);
2639
+ continue;
2640
+ }
2641
+ items.push({ ...item, status: 'completed' });
2642
+ changed += 1;
2643
+ }
2644
+ if (changed) {
2645
+ const temporary = `${backlogFile}.${process.pid}.tmp`;
2646
+ await writeJson(temporary, { ...backlog, [field]: items });
2647
+ await rename(temporary, backlogFile);
2648
+ }
2649
+ return { changed };
2650
+ }
2651
+
2652
+ export async function projectRelayNext(root, { queue, task, finalJudgement } = {}) {
2653
+ if (!task?.projectId || finalJudgement?.outcome !== 'ready_to_apply' || finalJudgement.requires_human_gate) return null;
2654
+ const project = normalizeProjectId(task.projectId);
2655
+ const spec = await readJson(projectConfigPathFor(root, project));
2656
+ if (!spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true)) return null;
2657
+ const acceptance = await projectAcceptanceRecord(root, spec);
2658
+ const ledger = acceptance?.record;
2659
+ if (!ledger || typeof ledger !== 'object' || Array.isArray(ledger)
2660
+ || !['in_progress', 'ongoing'].includes(ledger.status)
2661
+ || ledger.terminalState?.accepted === true || ledger.terminalAccepted === true) return null;
2662
+ if (!task.source?.channel || !task.source?.target || !task.source?.account || !task.source?.message_id) return null;
2663
+ // A completed queue task is not proof that any particular backlog item was
2664
+ // accepted. Require a durable binding before advancing to another item.
2665
+ const predecessorId = task.backlogItemId;
2666
+ if (typeof predecessorId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(predecessorId)) return null;
2667
+ const queueState = await queueStatus(root, queue);
2668
+ if (queueState.queued || queueState.active || queueState.waiting) return null;
2669
+ await projectRelayReconcile(root, { queue, project });
2670
+ const backlogSource = spec.backlogSource ?? spec.authoritativeBacklog;
2671
+ if (typeof backlogSource !== 'string' || !backlogSource.trim()) return null;
2672
+ let backlog;
2673
+ try {
2674
+ backlog = await readJson(path.resolve(root, safeRelativePath(backlogSource, 'project backlog source')));
2675
+ } catch { return null; }
2676
+ const items = Array.isArray(backlog?.items) ? backlog.items : Array.isArray(backlog?.tasks) ? backlog.tasks : null;
2677
+ if (!items?.length) return null;
2678
+ const byId = new Map(items.map((item) => [item.id, item]));
2679
+ const complete = new Set(['accepted', 'complete', 'completed', 'done', 'phase_complete']);
2680
+ if (!complete.has(byId.get(predecessorId)?.status)) return null;
2681
+ const queuedBodies = [];
2682
+ for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
2683
+ for (const file of await listJson(queueSubdirFor(root, queue, subdir))) {
2684
+ queuedBodies.push(String((await readJson(path.join(queueSubdirFor(root, queue, subdir), file))).body ?? ''));
2685
+ }
2686
+ }
2687
+ const item = items.find((candidate) => {
2688
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(String(candidate.id ?? ''))) return false;
2689
+ if (candidate.status !== 'ready' || candidate.autoRun !== true || candidate.scope !== 'local_only'
2690
+ || candidate.externalActionsAllowed !== false || candidate.humanGateRequired !== false
2691
+ || candidate.blocked === true || candidate.requires_human_input === true
2692
+ || typeof candidate.title !== 'string' || !candidate.title.trim()
2693
+ || typeof candidate.task !== 'string' || !candidate.task.trim()) return false;
2694
+ const dependencies = candidate.dependsOn ?? candidate.depends_on ?? [];
2695
+ if (!Array.isArray(dependencies) || !dependencies.every((id) => complete.has(byId.get(id)?.status))) return false;
2696
+ return !queuedBodies.some((body) => body.includes(`[project-relay:${project}/${candidate.id}]`));
2697
+ });
2698
+ if (!item) return null;
2699
+ const marker = `[project-relay:${project}/${item.id}]`;
2700
+ const result = await enqueueTask(root, {
2701
+ queue,
2702
+ title: item.title,
2703
+ task: `${marker}\n${item.task}\nLocal-only project continuation. This does not authorize external writes or satisfy project terminal acceptance.`,
2704
+ projectId: project,
2705
+ backlogItemId: item.id,
2706
+ ...taskSourceOptions(task.source)
2707
+ });
2708
+ return { project, itemId: item.id, taskId: result.task.id, file: result.file };
2709
+ }
2710
+
2592
2711
  async function tasksById(root, queue) {
2593
2712
  const tasks = new Map();
2594
2713
  for (const subdir of ['inbox', 'active', 'waiting', 'done', 'failed', 'canceled']) {
@@ -4627,6 +4746,18 @@ export async function queueSchedulerTick(root, options) {
4627
4746
  status = statusBefore.queued > 0 ? 'planned_due' : 'empty';
4628
4747
  }
4629
4748
 
4749
+ const relayReconciliation = [];
4750
+ if (!options.planOnly) {
4751
+ for (const spec of await projectSpecs(root)) {
4752
+ if (spec.relayStatusReconciliation !== true || !spec.queues?.some((entry) => entry.queue === queue && entry.autostart === true)) continue;
4753
+ try {
4754
+ relayReconciliation.push({ project: spec.project, ...await projectRelayReconcile(root, { queue, project: spec.project }) });
4755
+ } catch (error) {
4756
+ relayReconciliation.push({ project: spec.project, error: error instanceof Error ? error.message : String(error) });
4757
+ }
4758
+ }
4759
+ }
4760
+
4630
4761
  const statusAfter = await queueStatus(root, queue);
4631
4762
  const run = runResult?.run ?? null;
4632
4763
  const observed = {
@@ -4717,6 +4848,7 @@ export async function queueSchedulerTick(root, options) {
4717
4848
  progressReportPath: path.relative(root, queueProgressStatePath(root, queue)),
4718
4849
  statusBefore,
4719
4850
  statusAfter,
4851
+ relayReconciliation,
4720
4852
  run: runResult
4721
4853
  };
4722
4854
  }
@@ -5557,6 +5689,7 @@ export async function queueRevisionPlan(root, queue, taskId, options = {}) {
5557
5689
  body,
5558
5690
  source: task.source ?? null,
5559
5691
  projectId: task.projectId ?? task.project_id ?? null,
5692
+ backlogItemId: task.backlogItemId ?? null,
5560
5693
  revisionOf: task.id,
5561
5694
  revisionSourceRun: task.runPath,
5562
5695
  revisionRequestPath,
@@ -5592,6 +5725,7 @@ export async function queueRevisionNext(root, queue, taskId, options = {}) {
5592
5725
  title: plan.plannedTask.title,
5593
5726
  task: plan.plannedTask.body,
5594
5727
  projectId: plan.plannedTask.projectId ?? undefined,
5728
+ backlogItemId: plan.plannedTask.backlogItemId ?? undefined,
5595
5729
  ...taskSourceOptions(plan.plannedTask.source)
5596
5730
  });
5597
5731
  const nextTask = {
@@ -5646,6 +5780,7 @@ export async function queueRevisionApplyPlan(root, planPath, options = {}) {
5646
5780
  title: plan.plannedTask.title,
5647
5781
  task: plan.plannedTask.body,
5648
5782
  projectId: plan.plannedTask.projectId ?? undefined,
5783
+ backlogItemId: plan.plannedTask.backlogItemId ?? undefined,
5649
5784
  ...taskSourceOptions(plan.plannedTask.source)
5650
5785
  });
5651
5786
  const guard = plan.revisionPolicyGuard ?? plan.plannedTask.revisionPolicyGuard ?? null;
@@ -9797,6 +9932,15 @@ export async function runQueueOnce(root, options) {
9797
9932
  });
9798
9933
  }
9799
9934
 
9935
+ if (finalStatus === 'completed') {
9936
+ try {
9937
+ run.projectRelay = await projectRelayNext(root, { queue, task, finalJudgement: finalJudgement?.judgement });
9938
+ } catch (error) {
9939
+ run.projectRelay = { error: error instanceof Error ? error.message : String(error) };
9940
+ }
9941
+ await writeJson(runPath, run);
9942
+ }
9943
+
9800
9944
  const progressNotifications = await Promise.all(liveProgressNotifications);
9801
9945
  return {
9802
9946
  processed: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-loop-engineering",
3
- "version": "0.15.19",
3
+ "version": "0.15.21",
4
4
  "private": false,
5
5
  "description": "OpenClaw-native loop engineering CLI, templates, and skill for verifiable agent work loops.",
6
6
  "type": "module",
@@ -28,9 +28,9 @@
28
28
  "check:config-drift": "node scripts/distribution-skill-self-test.mjs && node --check scripts/config-drift-self-test.mjs && node scripts/config-drift-self-test.mjs",
29
29
  "check:openclaw-install": "node --check scripts/openclaw-install.mjs && node --check scripts/openclaw-doctor.mjs && node --check scripts/openclaw-smoke.mjs && node --check scripts/openclaw-manage.mjs && node scripts/openclaw-install-self-test.mjs",
30
30
  "check:hermes-install": "node --check scripts/hermes-install.mjs && node --check scripts/hermes-doctor.mjs && node --check scripts/hermes-smoke.mjs && node scripts/hermes-install-self-test.mjs",
31
- "check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs",
31
+ "check:project-gates": "node --check lib/core.mjs && node scripts/project-gate-reconciliation-self-test.mjs && node scripts/project-relay-self-test.mjs",
32
32
  "check:human-gates": "node --check lib/human-gate-command.mjs && node --check lib/human-gate-channel-adapter.mjs && node scripts/human-gate-command-self-test.mjs && node scripts/human-gate-final-judgement.mjs",
33
- "check": "npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
33
+ "check": "npm run check:project-gates && npm run check:config-drift && npm run check:openclaw-install && npm run check:hermes-install && node --check bin/loop-engineering.mjs && node --check lib/core.mjs && node --check lib/action-reservations.mjs && node --check lib/todo-control-plane.mjs && node --check lib/quota-runtime-decision.mjs && node --check lib/operator-dashboard.mjs && node scripts/action-reservation-self-test.mjs && node scripts/todo-control-plane-self-test.mjs && node scripts/quota-runtime-decision-self-test.mjs && node scripts/operator-dashboard-self-test.mjs && node scripts/final-judgement-self-test.mjs && node scripts/route-notify-self-test.mjs && node scripts/scheduler-heartbeat-self-test.mjs && node scripts/human-gate-lifecycle-v2-self-test.mjs && node bin/loop-engineering.mjs verify --config templates/workspace-health.json --root . && node bin/loop-engineering.mjs queue-status --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs project-intake --root /tmp/loop-engineering-check --name smoke-project --brief \"Build a small website project\" --type auto --check \"npm test\" --json >/dev/null && node bin/loop-engineering.mjs project-plan --root /tmp/loop-engineering-check --project smoke-project --force --json >/dev/null && node bin/loop-engineering.mjs project-status --root /tmp/loop-engineering-check --project smoke-project --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke --root /tmp/loop-engineering-check --plan-only --force-due --json >/dev/null && node bin/loop-engineering.mjs queue-scheduler-tick --queue smoke-progress --root /tmp/loop-engineering-check --plan-only --force-due --progress-report --progress-report-when-not-due --json >/dev/null && node bin/loop-engineering.mjs workflow-metrics --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs workflow-tune-plan --queue smoke --root . --json >/dev/null && node bin/loop-engineering.mjs code-queue-init --queue smoke-code --root /tmp/loop-engineering-check --force >/dev/null && node bin/loop-engineering.mjs code-worktree-list --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-status --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-task-dashboard --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup-plan --queue smoke-code --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs code-worktree-cleanup --queue smoke-code --root /tmp/loop-engineering-check --confirm-cleanup --json >/dev/null && node bin/loop-engineering.mjs code-patch-verify --patch README.md --root . --json >/dev/null && node bin/loop-engineering.mjs code-patch-apply-plan --patch README.md --json >/dev/null && node bin/loop-engineering.mjs queue-revision-ci-self-test --queue smoke-ci --root /tmp/loop-engineering-check --json >/dev/null && node bin/loop-engineering.mjs summarize --root . --json >/dev/null && node bin/loop-engineering.mjs dashboard-health --root . --max-age-seconds 999999999 --json >/dev/null && node bin/loop-engineering.mjs doctor --root . --json >/dev/null",
34
34
  "pack:dry": "npm pack --dry-run"
35
35
  },
36
36
  "exports": {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
2
+ import { chmod, mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { tmpdir } from 'node:os';
5
5
  import path from 'node:path';
@@ -205,4 +205,28 @@ const zhInstructions = await readFile(path.join(root, 'AGENTS.md'), 'utf8');
205
205
  const zhDispatcher = await readFile(path.join(root, 'scripts/loops/openclaw-loop-dispatch.mjs'), 'utf8');
206
206
  const zhNotifier = await readFile(path.join(root, 'scripts/loops/openclaw-loop-notify.mjs'), 'utf8');
207
207
  if (zhQueue.language !== 'zh' || !zhInstructions.includes('Loop Engineering 会话路由') || !zhDispatcher.includes('已经由 Loop Engineering 管理') || !zhNotifier.includes('通知器需要消息参数')) throw new Error('Chinese installation did not localize generated configuration and runtime files');
208
+ const installedWrapper = path.join(root, 'scripts/loops/openclaw-loop.mjs');
209
+ async function routeWithRelayFlag(message) {
210
+ return new Promise((resolve) => {
211
+ const child = spawn(process.execPath, [installedWrapper, 'route', '--relay-enqueue', '--message', message,
212
+ '--source-channel', 'feishu', '--source-target', 'owner', '--source-account', 'main',
213
+ '--source-message-id', 'relay-source-1'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
214
+ let stderr = '';
215
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
216
+ child.on('close', (code) => resolve({ code, stderr }));
217
+ });
218
+ }
219
+ const rejectedRelay = await routeWithRelayFlag('走 loop:普通任务');
220
+ if (rejectedRelay.code !== 2 || !rejectedRelay.stderr.includes('internal project relay marker')) throw new Error('internal enqueue flag accepted an unmarked task');
221
+ const projectRelay = await routeWithRelayFlag('走 loop: [project-relay:relay-project/local-1] 本地任务');
222
+ if (projectRelay.code !== 0) throw new Error(`project relay marker was rejected: ${projectRelay.stderr}`);
223
+ const internalRelay = await routeWithRelayFlag('走 loop: [project-scout:abc123] 本地只读扫描');
224
+ if (internalRelay.code !== 0) throw new Error(`internal relay enqueue failed: ${internalRelay.stderr}`);
225
+ const inboxDir = path.join(root, 'runtime/loops/test-tasks/inbox');
226
+ const queuedFiles = (await readdir(inboxDir)).filter((name) => name.endsWith('.json'));
227
+ if (queuedFiles.length !== 2) throw new Error('internal relays did not defer exactly two tasks to the scheduler');
228
+ const queuedTasks = await Promise.all(queuedFiles.map(async (file) => JSON.parse(await readFile(path.join(inboxDir, file), 'utf8'))));
229
+ if (!queuedTasks.some((task) => task.body.includes('[project-relay:relay-project/local-1]'))
230
+ || !queuedTasks.some((task) => task.body.includes('[project-scout:abc123]'))
231
+ || queuedTasks.some((task) => task.body.includes('只入队'))) throw new Error('internal relay corrupted task intent');
208
232
  console.log('openclaw installer self-test passed');
@@ -194,6 +194,11 @@ async function runWhenUnlocked(args, waitMs = 300000) {
194
194
  if (command === 'route') {
195
195
  const messageIndex = rest.indexOf('--message');
196
196
  const message = messageIndex >= 0 ? String(rest[messageIndex + 1] || '') : '';
197
+ const relayEnqueue = rest.includes('--relay-enqueue');
198
+ if (relayEnqueue && !/\\[project-(?:relay:[a-zA-Z0-9._-]+\\/[a-zA-Z0-9._-]+|scout:[a-z0-9_-]+)\\]/.test(message)) {
199
+ console.error('--relay-enqueue requires an internal project relay marker');
200
+ process.exit(2);
201
+ }
197
202
  const optionValue = (name) => {
198
203
  const index = rest.indexOf(name);
199
204
  return index >= 0 ? String(rest[index + 1] || '').trim() : '';
@@ -207,8 +212,9 @@ if (command === 'route') {
207
212
  }
208
213
  const amendment = new RegExp(${JSON.stringify(amendmentPattern)}, 'i').test(message);
209
214
  const routeMode = amendment ? '--amend-active' : '--supersede-active';
210
- const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', routeMode, ...rest]);
211
- const queueOnly = new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
215
+ const routedArgs = rest.filter((arg) => arg !== '--relay-enqueue');
216
+ const routeCode = await run(['route-message', '--queue', ${JSON.stringify(queue)}, '--route', '--confirm-execute', routeMode, ...routedArgs]);
217
+ const queueOnly = relayEnqueue || new RegExp(${JSON.stringify(queueOnlyPattern)}, 'i').test(message);
212
218
  const runCode = routeCode || queueOnly || amendment ? routeCode : await runWhenUnlocked(['run-queue', '--config', ${JSON.stringify(`configs/loops/queues/${queue}.json`)}, '--progress-notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
213
219
  const humanNotifyCode = await run(['queue-human-input-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
214
220
  const terminalNotifyCode = await run(['queue-terminal-notify', '--queue', ${JSON.stringify(queue)}, '--notify-command', 'node scripts/loops/openclaw-loop-notify.mjs']);
@@ -0,0 +1,108 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdtemp, mkdir, readFile, rm, writeFile, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { ensureQueueDirs, projectRelayNext, projectRelayReconcile, queueSchedulerTick, queueStatus } from '../lib/core.mjs';
6
+
7
+ const root = await mkdtemp(path.join(os.tmpdir(), 'loop-project-relay-'));
8
+ const queue = 'relay-test';
9
+ const project = 'relay-project';
10
+ const configFile = path.join(root, 'configs/loops/projects', `${project}.json`);
11
+ const backlogFile = path.join(root, 'project/backlog.json');
12
+ const ledgerFile = path.join(root, 'project/ledger.json');
13
+ const writeJson = async (file, value) => {
14
+ await mkdir(path.dirname(file), { recursive: true });
15
+ await writeFile(file, `${JSON.stringify(value)}\n`);
16
+ };
17
+ const spec = { schemaVersion: 1, project, type: 'code_project', queues: [{ queue, kind: 'standard', autostart: true }],
18
+ backlogSource: 'project/backlog.json', acceptanceLedger: 'project/ledger.json' };
19
+ const item = { id: 'local-1', status: 'ready', title: 'Local proof', task: 'Verify the local entry', autoRun: true,
20
+ scope: 'local_only', externalActionsAllowed: false, humanGateRequired: false, dependsOn: [] };
21
+ const predecessor = { id: 'local-0', status: 'accepted' };
22
+ const task = { id: 'accepted-task', projectId: project, backlogItemId: predecessor.id,
23
+ source: { channel: 'feishu', target: 'owner', account: 'main', message_id: 'message-1' } };
24
+ const finalJudgement = { outcome: 'ready_to_apply', requires_human_gate: false };
25
+ await ensureQueueDirs(root, queue);
26
+ await writeJson(configFile, spec);
27
+ await writeJson(backlogFile, { items: [predecessor, item] });
28
+ await writeJson(ledgerFile, { status: 'in_progress' });
29
+
30
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement: { outcome: 'blocked' } }), null);
31
+ assert.equal(await projectRelayNext(root, { queue, task: { ...task, source: null }, finalJudgement }), null);
32
+ await writeJson(configFile, { ...spec, queues: [{ queue, kind: 'standard', autostart: false }] });
33
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null);
34
+ await writeJson(configFile, spec);
35
+ for (const unsafe of [{ ...item, humanGateRequired: true }, { ...item, externalActionsAllowed: true },
36
+ { ...item, scope: 'production' }, { ...item, autoRun: false }, { ...item, blocked: true },
37
+ { ...item, dependsOn: ['unaccepted'] }]) {
38
+ await writeJson(backlogFile, { items: [predecessor, unsafe] });
39
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null);
40
+ }
41
+ await writeJson(backlogFile, { items: [predecessor, item] });
42
+ await writeJson(configFile, { ...spec, acceptanceLedger: 'project/missing-ledger.json' });
43
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'missing terminal authority fails closed');
44
+ await writeJson(configFile, spec);
45
+ assert.equal(await projectRelayNext(root, { queue, task: { ...task, backlogItemId: undefined }, finalJudgement }), null,
46
+ 'unbound predecessor cannot authorize a relay');
47
+ await writeJson(backlogFile, { items: [{ ...predecessor, status: 'ready' }, item] });
48
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null,
49
+ 'a completed task with a stale ready backlog item cannot relay itself');
50
+ await writeJson(backlogFile, { items: [predecessor, item] });
51
+ await writeJson(ledgerFile, null);
52
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'null ledger fails closed');
53
+ await writeJson(ledgerFile, { status: 'unknown' });
54
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'unknown ledger state fails closed');
55
+ await writeJson(ledgerFile, { status: 'in_progress' });
56
+ await unlink(backlogFile);
57
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'missing authoritative backlog fails closed');
58
+ await writeJson(backlogFile, { items: [predecessor, item] });
59
+ const result = await projectRelayNext(root, { queue, task, finalJudgement });
60
+ assert.equal(result.itemId, 'local-1');
61
+ const queued = JSON.parse(await readFile(path.join(root, result.file), 'utf8'));
62
+ assert.equal(queued.projectId, project);
63
+ assert.equal(queued.backlogItemId, item.id);
64
+ assert.equal(queued.source.message_id, 'message-1');
65
+ assert.match(queued.body, /\[project-relay:relay-project\/local-1\]/);
66
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'busy queue must not enqueue twice');
67
+ assert.equal((await queueStatus(root, queue)).queued, 1);
68
+ await writeJson(ledgerFile, { status: 'accepted' });
69
+ assert.equal(await projectRelayNext(root, { queue, task, finalJudgement }), null, 'accepted project cannot relay');
70
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'reconciliation is opt-in');
71
+ await writeJson(configFile, { ...spec, relayStatusReconciliation: true });
72
+ await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, status: 'completed' });
73
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'a queue row alone is not acceptance');
74
+ await writeJson(path.join(root, 'runtime/loops', queue, 'tasks', queued.id, 'final_judgement.json'), { outcome: 'ready_to_apply', requires_human_gate: false });
75
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'accepted project cannot mutate backlog');
76
+ await writeJson(ledgerFile, { status: 'in_progress' });
77
+ await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, backlogItemId: 'wrong', status: 'completed' });
78
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'marker without matching backlog binding is not evidence');
79
+ await writeJson(path.join(root, 'runtime/loops', queue, 'done', `${queued.id}.json`), { ...queued, status: 'completed' });
80
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 1);
81
+ assert.equal((await readFile(backlogFile, 'utf8')).includes('"status": "completed"'), true);
82
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'reconciliation is idempotent');
83
+ await writeJson(backlogFile, { items: [{ ...item, externalActionsAllowed: true }] });
84
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'unsafe backlog rows are not promoted');
85
+ await writeJson(backlogFile, { items: [item] });
86
+ await writeJson(path.join(root, 'runtime/loops', queue, 'done', 'duplicate.json'), { ...queued, id: 'duplicate', status: 'completed' });
87
+ await writeJson(path.join(root, 'runtime/loops', queue, 'tasks', 'duplicate', 'final_judgement.json'), { outcome: 'ready_to_apply' });
88
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'duplicate task evidence cannot promote a row');
89
+ await writeJson(backlogFile, { items: [item] });
90
+ await writeJson(path.join(root, 'runtime/loops', queue, 'scheduler/state.json'), { nextRunAt: '2999-01-01T00:00:00.000Z' });
91
+ const planned = await queueSchedulerTick(root, { queue, planOnly: true });
92
+ assert.equal(planned.relayReconciliation.length, 0, 'plan-only scheduler cannot mutate the backlog');
93
+ assert.equal(JSON.parse(await readFile(backlogFile, 'utf8')).items[0].status, 'ready');
94
+ await writeJson(path.join(root, 'runtime/loops', queue, 'done', 'duplicate.json'), { ...queued, id: 'duplicate', projectId: 'another-project', status: 'completed' });
95
+ await writeJson(backlogFile, { items: [item, { ...item }] });
96
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'duplicate backlog ids cannot be reconciled');
97
+ await writeJson(backlogFile, { items: [item] });
98
+ await writeJson(ledgerFile, { status: 'unknown' });
99
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'invalid project acceptance cannot change backlog');
100
+ await writeJson(ledgerFile, { status: 'in_progress' });
101
+ await unlink(backlogFile);
102
+ assert.equal((await projectRelayReconcile(root, { queue, project })).changed, 0, 'missing authoritative backlog fails closed');
103
+ await writeJson(backlogFile, { items: [item] });
104
+ await rm(path.join(root, result.file));
105
+ const tick = await queueSchedulerTick(root, { queue });
106
+ assert.deepEqual(tick.relayReconciliation, [{ project, changed: 1 }], 'idle scheduler repairs interrupted status writes');
107
+ assert.equal((await readFile(backlogFile, 'utf8')).includes('"status": "completed"'), true);
108
+ console.log('project relay self-test passed');