fix(orchestration): wire openclaw lifecycle events end-to-end

The codex/gemini branch in /api/orchestration/run emits task_started at
line ~296 before injectIntoTab. The openclaw branch did not. So every
successful openclaw run was invisible in orchestration_events — only
its orchestration_runs row existed. Commit 9a0ac77 closed the worker-
start-failure pair (failed-to-spawn now emits task_failed), but the
happy path and the in-worker error path were both still silent.

Three coordinated changes:

  1. Route emits task_started before scheduleOpenClawWorker — mirrors
     the codex/gemini emit shape so dispatches across all adapters look
     uniform in queries.

  2. scheduleOpenClawWorker signature gains userId, encodes it into
     the base64 payload. The worker needs user_id to write to
     orchestration_events (NOT NULL constraint).

  3. Worker emits task_completed (state:'done') or task_failed
     (state:'error' or thrown) after its terminal updateOrchestrationRun.
     Source field 'openclaw-worker' (vs 'api-orchestration' on the start
     event) so timeline queries can tell which process emitted what.

After this, orchestration_events carries a full started/completed-or-
failed pair for every openclaw dispatch — same shape as codex/gemini —
and the single dispatch-success-rate query introduced in 9a0ac77 covers
every adapter without per-adapter casing.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-21 06:55:58 +02:00
1 parent 9a0ac77ac3
commit a12d2d9841
2 files changed
+52 -4

No files matched your search

+30 -1
View File
@@ -4,6 +4,7 @@ import { runOpenClawIntent } from "@/lib/orchestration/runners/openclaw";
import type { OrchestrationTaskRequest } from "@/lib/orchestration";
import { parseOrchestrationSummary } from "@/lib/orchestration/summary";
import { updateOrchestrationRun } from "@/db/queries/orchestration-runs";
import { createOrchestrationEvent } from "@/db/queries/orchestration-events";
async function main() {
const encoded = process.argv[2];
@@ -11,14 +12,37 @@ async function main() {
const payload = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as {
runId: string;
userId: string;
request: OrchestrationTaskRequest;
};
const { runId, request } = payload;
const { runId, userId, request } = payload;
const logPath = path.join(process.cwd(), ".next", "logs", `openclaw-worker-${runId}.log`);
fs.mkdirSync(path.dirname(logPath), { recursive: true });
const log = (msg: string) => fs.appendFileSync(logPath, `[${new Date().toISOString()}] ${msg}\n`);
// Emit task_completed (success) or task_failed (error) to close the pair
// started by the route at line ~385. Without this, every openclaw run on
// the happy path showed task_started but never task_completed, leaving
// dispatch-success-rate queries unable to count completions for openclaw.
const emitLifecycleEvent = async (eventType: "task_completed" | "task_failed", detail: string) => {
try {
await createOrchestrationEvent({
userId,
projectId: request.projectId ?? null,
projectKey: request.projectKey,
eventType,
source: "openclaw-worker",
adapter: request.adapter,
intent: request.intent,
detail: detail.slice(0, 400),
happenedAt: new Date(),
});
} catch (e) {
log(`emitLifecycleEvent ${eventType} failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
log("worker start");
log(`project=${request.projectKey} intent=${request.intent}`);
@@ -44,6 +68,10 @@ async function main() {
finishedAt: new Date(),
});
log("after updateOrchestrationRun success/error");
await emitLifecycleEvent(
result.ok ? "task_completed" : "task_failed",
result.ok ? `${request.intent} done` : `${request.intent}: ${result.error ?? "openclaw returned not-ok"}`,
);
} catch (error) {
log(`catch error=${error instanceof Error ? error.stack ?? error.message : String(error)}`);
await updateOrchestrationRun(runId, {
@@ -57,6 +85,7 @@ async function main() {
finishedAt: new Date(),
});
log("after updateOrchestrationRun catch");
await emitLifecycleEvent("task_failed", error instanceof Error ? error.message : "OpenClaw run crashed");
throw error;
}
}
+22 -3
View File
@@ -42,9 +42,11 @@ const RunOrchestrationBody = z.object({
queue: z.array(z.string().max(4000)).max(200).optional(),
});
async function scheduleOpenClawWorker(runId: string, request: OrchestrationTaskRequest) {
async function scheduleOpenClawWorker(runId: string, userId: string, request: OrchestrationTaskRequest) {
const workerPath = path.join(process.cwd(), "scripts", "run-openclaw-orchestration.ts");
const payload = Buffer.from(JSON.stringify({ runId, request }), "utf8").toString("base64url");
// userId in the payload so the worker can emit task_completed/task_failed
// to orchestration_events (user_id is NOT NULL on that table).
const payload = Buffer.from(JSON.stringify({ runId, userId, request }), "utf8").toString("base64url");
const command = `cd ${JSON.stringify(process.cwd())} && set -a && source .env.local >/dev/null 2>&1 && npx tsx ${JSON.stringify(workerPath)} ${JSON.stringify(payload)}`;
const child = spawn("bash", ["-lc", command], {
cwd: process.cwd(),
@@ -380,8 +382,25 @@ export async function POST(req: NextRequest) {
},
});
// Emit task_started for openclaw too — until now this branch had no
// lifecycle event of any kind on success (the codex/gemini branch at
// line ~296 emits task_started but this branch skipped it), so every
// successful openclaw run was invisible in orchestration_events. The
// matching task_completed/task_failed is emitted by the worker script.
createOrchestrationEvent({
userId,
projectId: request.projectId ?? null,
projectKey: request.projectKey,
eventType: "task_started",
source: "api-orchestration",
adapter: request.adapter,
intent: request.intent,
detail: intent.name,
happenedAt: new Date(),
}).catch((e) => console.error("[orchestration/run] task_started write failed:", e));
try {
await scheduleOpenClawWorker(run.id, request);
await scheduleOpenClawWorker(run.id, userId, request);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await updateOrchestrationRun(run.id, {