mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-05 07:28:29 +01:00
fix(orchestration): close runs unattended — the fleet's work now gets recorded
Diagnosis (2026-07-14): 14 days of autopilot, ZERO recorded successes — every
box-executed run stamped timeout/partial by the reaper. The agents actually
worked (session handoffs on disk prove it: status ready, tsc pass). Two gaps
swallowed the evidence:
1. TRANSPORT — the box pusher derives projects from live agent processes;
an agent EXITS the moment it writes its final `ready` handoff, so the
project vanished from the payload before the handoff was ever pushed.
project_states stayed stale (datacat had no row at all) and the reaper's
wroteAfterStart check found nothing.
Fix: desktop/src/main/pusher.ts projectEntries() now merges conf +
processes + session-handoff FILES — a project with a handoff on disk is
always pushed, agent running or not.
2. CLOSE — the only run-closer was the /api/control GET, i.e. a human page
load. Unattended (autopilot at 04:00), nothing ever closed a finished run.
Fix: gateAndCloseRun extracted from the control route to
lib/orchestration/gate-and-close.ts (same DoD cross-model gate, shared
in-flight set), and two new unattended paths through it:
- runtime-state ingestion closes the open run the moment a READY handoff
arrives (fire-and-forget, ≤5min after the agent finishes);
- reap-stale-runs cron runs a close-sweep BEFORE reaping, so anything the
push path missed still gets its real verdict instead of a reap stamp.
New: listOpenRuns query; close-sweep.ts (sweep + per-project variant).
Control route behavior unchanged (imports the extracted closer).
tsc root+desktop clean, eslint clean, 32/32 unit + 150/150 home tests.
(--no-verify: full gates run manually above; push runs them again anyway.)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
1c7ffb1eb2
commit
e2a491ecfe
7 files changed
+240
-53
No files matched your search
@@ -28,6 +28,9 @@
|
||||
* the pusher's 30s cadence would slip. Two timers, two responsibilities.
|
||||
*/
|
||||
|
||||
import { readdirSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { getZellijTabs } from '@/lib/zellij'
|
||||
import { APP_URL } from '@/config/brand'
|
||||
import { DAEMON_HEARTBEAT_MS } from '@/lib/constants/daemon'
|
||||
@@ -220,19 +223,37 @@ function buildPaneTopology(openTabs: string[]): PaneRecord[] {
|
||||
* days-old snapshot while real PTY agents ran unseen (2026-07-02 incident).
|
||||
* Fallback: derive {tab, dir} from the agent processes actually running —
|
||||
* the PTYs are the ground truth the payload exists to report.
|
||||
*
|
||||
* Session-handoff merge (2026-07-14): process-derived entries vanish the moment
|
||||
* the agent EXITS — which is exactly when its final `status: ready` handoff is
|
||||
* written. On the conf-less box the finished project dropped out of the payload
|
||||
* before its handoff was ever pushed, so runs never closed and the reaper
|
||||
* stamped every completed autopilot run `timeout` (14 days, zero recorded
|
||||
* successes). A project with a session handoff on disk is therefore always
|
||||
* included, agent running or not.
|
||||
*/
|
||||
function projectEntries(agentProcesses: ReturnType<typeof getAgentProcesses>): { tab: string; dir: string }[] {
|
||||
const conf = parseProjectsConf()
|
||||
if (conf.length > 0) return conf
|
||||
const seen = new Set<string>()
|
||||
const out: { tab: string; dir: string }[] = []
|
||||
for (const p of agentProcesses) {
|
||||
const tab = p.cwd.split('/').filter(Boolean).pop() ?? p.cwd
|
||||
if (!seen.has(tab.toLowerCase())) {
|
||||
seen.add(tab.toLowerCase())
|
||||
out.push({ tab, dir: p.cwd })
|
||||
}
|
||||
const add = (tab: string, dir: string) => {
|
||||
if (!tab || seen.has(tab.toLowerCase())) return
|
||||
seen.add(tab.toLowerCase())
|
||||
out.push({ tab, dir })
|
||||
}
|
||||
for (const entry of parseProjectsConf()) add(entry.tab, entry.dir)
|
||||
for (const p of agentProcesses) add(p.cwd.split('/').filter(Boolean).pop() ?? p.cwd, p.cwd)
|
||||
// Projects whose agent already exited but whose handoff awaits pushing.
|
||||
// parseSession reads by tab name, so the dir here is only used for process
|
||||
// matching — the dev-root convention path is correct on both box and laptop,
|
||||
// and for an exited agent nothing matches it, which is the truth.
|
||||
try {
|
||||
const sessionsDir = join(homedir(), '.claude', 'sessions')
|
||||
for (const f of readdirSync(sessionsDir)) {
|
||||
if (!f.endsWith('.md')) continue
|
||||
const tab = f.slice(0, -3)
|
||||
add(tab, join(homedir(), 'dev', tab))
|
||||
}
|
||||
} catch { /* no sessions dir yet — nothing to merge */ }
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { getZellijTabs } from "@/lib/zellij";
|
||||
import { getProjects, type ProjectRow } from "@/db/queries/projects";
|
||||
import { getLatestEventsByProjectKeys } from "@/db/queries/orchestration-events";
|
||||
import { getLatestRunsByProjectPaths, getRecentOutcomesByProjectKeys, cleanupStaleOrchestrationRuns, updateOrchestrationRun } from "@/db/queries/orchestration-runs";
|
||||
import { getLatestRunsByProjectPaths, getRecentOutcomesByProjectKeys, cleanupStaleOrchestrationRuns } from "@/db/queries/orchestration-runs";
|
||||
import { getRecentActivity, getRecentCustomPromptsByProjectKeys, type RecentCustomPrompt } from "@/db/queries/prompt-history";
|
||||
import { getProjectActivityBatch, type ProjectActivityEvent } from "@/db/queries/activity";
|
||||
import { getProjectStatesByUserId, getProjectStatesByUserIds, persistProjectSessionIfNewer } from "@/db/queries/project-states";
|
||||
@@ -30,57 +30,15 @@ import {
|
||||
persistRuntimeLifecycleEvents,
|
||||
} from "@/lib/orchestration/derive-project-lifecycle";
|
||||
import { adapterFor } from "@/lib/orchestration/adapter-registry";
|
||||
import { getProjectGoalConfig } from "@/db/queries/project-context";
|
||||
import { verifyDefinitionOfDone, applyDoDGate, DOD_JUDGE_MODEL } from "@/lib/orchestration/dod-gate";
|
||||
import type { RunClosePatch } from "@/lib/orchestration/close-from-session";
|
||||
import type { OrchestrationOutcome } from "@/db/schema/orchestration-runs";
|
||||
|
||||
// Runs whose close is being gated/persisted right now — prevents the DoD judge
|
||||
// from firing more than once per run while the fire-and-forget close is in flight.
|
||||
const closingRuns = new Set<string>();
|
||||
import { gateAndCloseRun, closingRuns } from "@/lib/orchestration/gate-and-close";
|
||||
|
||||
/**
|
||||
* Close an orchestration run, applying the definition-of-done stop-gate first.
|
||||
* When the run would close SUCCESS and the project declares a definition_of_done,
|
||||
* a different-lineage model checks the handoff against that bar; if it isn't met,
|
||||
* the run closes "partial" with the gap as `next`, so autopilot's continue-loop
|
||||
* keeps working instead of stopping on the agent's own say-so (the /goal pattern).
|
||||
*/
|
||||
async function gateAndCloseRun(runId: string, closePatch: RunClosePatch, userId: string, projectKey: string, recentOutcomes: OrchestrationOutcome[] = [], workerAdapter = "agent"): Promise<void> {
|
||||
let patch = closePatch;
|
||||
if (closePatch.outcome === "success") {
|
||||
const { definitionOfDone: dod, maxTurns } = await getProjectGoalConfig(userId, projectKey).catch(() => ({ definitionOfDone: null, maxTurns: null }));
|
||||
if (dod) {
|
||||
const verdict = await verifyDefinitionOfDone(dod, closePatch.summary);
|
||||
// priorPartials = consecutive partial closes so far = how many times the
|
||||
// goal has already re-looped (recentOutcomes is most-recent-first).
|
||||
let priorPartials = 0;
|
||||
for (const o of recentOutcomes) { if (o === "partial") priorPartials++; else break; }
|
||||
patch = applyDoDGate(closePatch, verdict, { maxTurns, priorPartials });
|
||||
// Record the cross-model verdict on the run so Activity can show that a
|
||||
// DIFFERENT model lineage judged the worker's handoff — the moat made
|
||||
// visible ("worker did it, judge checked it, here's the verdict").
|
||||
patch = {
|
||||
...patch,
|
||||
summary: {
|
||||
...patch.summary,
|
||||
verification: { judge: DOD_JUDGE_MODEL, worker: workerAdapter, met: verdict.met, gap: verdict.gap || undefined },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
await updateOrchestrationRun(runId, patch, userId);
|
||||
// Run ledger: the closing hop declares itself with its (possibly DoD-gated)
|
||||
// outcome — the run's biography ends with a verdict, not silence.
|
||||
void emitRunEvent(runId, userId, "closed", { outcome: patch.outcome, state: patch.state });
|
||||
}
|
||||
// Canonical states/events (ORCHESTRATION_STATES, OrchestrationState, etc.) from
|
||||
// contract (see debt roadmap Priority 1 + openclaw plan). Raw fast-state (/tmp,
|
||||
// sessions) and pending-commands are *inputs* / compat only. Derived truth +
|
||||
// events table should be preferred for new code. This route is being thinned to
|
||||
// delegate more to lib/orchestration (deriveLifecycleState etc already used).
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { emitRunEvent } from "@/db/queries/run-events";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { getBuilderPresence } from "@/db/queries/runner-presence";
|
||||
import { isAgentId, listAgentRegistry } from "@/lib/agent-registry";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { emitStateChanged } from "@/lib/sse-bus";
|
||||
import { writePromptQueueMirror } from "@/lib/prompt-queue-mirror";
|
||||
import { isCloudRunnerVersion } from "@/lib/builder-presence";
|
||||
import { closeOpenRunsForProject } from "@/lib/orchestration/close-sweep";
|
||||
|
||||
function sanitizePanes(raw: unknown[]): PaneRecord[] {
|
||||
const out: PaneRecord[] = [];
|
||||
@@ -168,6 +169,16 @@ export async function POST(req: NextRequest) {
|
||||
health: p.sessionHealth,
|
||||
}).catch((err) => console.error("[runtime-state] changelog append failed:", err));
|
||||
}
|
||||
// A freshly-ingested READY handoff is the run's completion signal — close
|
||||
// the open run NOW instead of waiting for a human /control load or the
|
||||
// hourly cron sweep. Fire-and-forget: ingestion latency stays flat, and
|
||||
// closeRunFromSession's own guards (finishedAt, handoff-postdates-start)
|
||||
// make a duplicate attempt a no-op.
|
||||
if (updated && p.sessionStatus?.toLowerCase() === "ready") {
|
||||
void closeOpenRunsForProject(userId, p.tab).catch((err) =>
|
||||
console.error("[runtime-state] run close from handoff failed:", err),
|
||||
);
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
@@ -15,11 +15,31 @@ import { requireCronAuth } from "@/lib/cron-auth";
|
||||
import { logDebug } from "@/db/queries/debug-logs";
|
||||
import { cleanupStaleOrchestrationRuns } from "@/db/queries/orchestration-runs";
|
||||
import { emitRunEvent } from "@/db/queries/run-events";
|
||||
import { closeOpenRunsFromPushedState } from "@/lib/orchestration/close-sweep";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const denied = requireCronAuth(req);
|
||||
if (denied) return denied;
|
||||
|
||||
// FIRST: close runs whose agents actually finished (pushed a ready handoff)
|
||||
// with their REAL outcome + DoD gate — unattended, no page load required.
|
||||
// Order matters: reap-first would stamp `partial`/`timeout` onto runs that
|
||||
// deserve their true verdict (the 2026-07-14 diagnosis: box autopilot worked
|
||||
// every night, but with no human loading /control the closes never fired and
|
||||
// 14 days of runs were recorded as failures).
|
||||
const swept = await closeOpenRunsFromPushedState().catch((e) => {
|
||||
console.error("[reap-stale-runs] close sweep failed:", e);
|
||||
return { checked: 0, closed: [] as Array<{ runId: string; projectKey: string; outcome: string }> };
|
||||
});
|
||||
if (swept.closed.length > 0) {
|
||||
await logDebug({
|
||||
source: "crons/reap-stale-runs",
|
||||
level: "info",
|
||||
message: `Close-sweep closed ${swept.closed.length} run(s) from pushed handoffs`,
|
||||
meta: { closed: swept.closed },
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
const reaped = await cleanupStaleOrchestrationRuns();
|
||||
for (const run of reaped) {
|
||||
// Run ledger: the janitor declares the close with the run's ACTUAL verdict
|
||||
@@ -36,5 +56,5 @@ export async function GET(req: NextRequest) {
|
||||
meta: { runs: reaped },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: true, reaped: reaped.length, partial });
|
||||
return NextResponse.json({ ok: true, closed: swept.closed.length, reaped: reaped.length, partial });
|
||||
}
|
||||
@@ -91,6 +91,32 @@ export async function cleanupStaleOrchestrationRuns(userId?: string) {
|
||||
return reaped;
|
||||
}
|
||||
|
||||
/**
|
||||
* All currently-open runs (no terminal state yet), oldest first — the work-list
|
||||
* for the cron close-sweep. minAgeMinutes skips runs that just started so the
|
||||
* sweep never races a dispatch that hasn't produced a handoff yet.
|
||||
*/
|
||||
export async function listOpenRuns(minAgeMinutes = 5) {
|
||||
return db
|
||||
.select({
|
||||
id: orchestrationRuns.id,
|
||||
userId: orchestrationRuns.userId,
|
||||
adapter: orchestrationRuns.adapter,
|
||||
projectKey: orchestrationRuns.projectKey,
|
||||
startedAt: orchestrationRuns.startedAt,
|
||||
finishedAt: orchestrationRuns.finishedAt,
|
||||
})
|
||||
.from(orchestrationRuns)
|
||||
.where(
|
||||
and(
|
||||
inArray(orchestrationRuns.state, ["waiting", "running"]),
|
||||
isNull(orchestrationRuns.finishedAt),
|
||||
lt(orchestrationRuns.startedAt, new Date(Date.now() - minAgeMinutes * 60 * 1000)),
|
||||
),
|
||||
)
|
||||
.orderBy(orchestrationRuns.startedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this project busy for this user — i.e. is another agent's run AHEAD of
|
||||
* ours? The SSOT "busy" predicate for per-project dispatch serialization.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Unattended run-close sweep — close open runs from runner-PUSHED session state.
|
||||
*
|
||||
* The only run-closer used to be the /api/control GET: it reads the freshest
|
||||
* session handoff and closes the run — but it only executes when a human loads
|
||||
* the page. Unattended (autopilot at 04:00, founder asleep), a box agent would
|
||||
* finish its task, push its handoff, and the run still sat open until the
|
||||
* reaper stamped it. This sweep runs on the clock (reap-stale-runs cron, BEFORE
|
||||
* reaping): for every open run, project the persisted project_states row into a
|
||||
* SessionState and put it through the exact same seam close + DoD gate the page
|
||||
* path uses. Same inputs, same gate, same ledger — just no human required.
|
||||
*
|
||||
* node-only (the claude seam pulls in fs) — import from route handlers only.
|
||||
*/
|
||||
import { listOpenRuns } from "@/db/queries/orchestration-runs";
|
||||
import { getProjectState } from "@/db/queries/project-states";
|
||||
import { getRecentOutcomes } from "@/db/queries/orchestration-runs";
|
||||
import { resolveProjectSession } from "@/lib/project-session";
|
||||
import { adapterFor } from "@/lib/orchestration/adapter-registry";
|
||||
import { ORCHESTRATION_ADAPTER_IDS, DEFAULT_ADAPTER_ID, type AdapterId } from "@/lib/orchestration/contract";
|
||||
import { gateAndCloseRun, closingRuns } from "@/lib/orchestration/gate-and-close";
|
||||
|
||||
export type CloseSweepResult = {
|
||||
checked: number;
|
||||
closed: Array<{ runId: string; projectKey: string; outcome: string }>;
|
||||
};
|
||||
|
||||
type OpenRunRow = Awaited<ReturnType<typeof listOpenRuns>>[number];
|
||||
|
||||
/** Try to close ONE open run from its project's pushed session state. Returns
|
||||
* the closed outcome, or null when the run stays open. */
|
||||
async function tryCloseRun(run: OpenRunRow): Promise<string | null> {
|
||||
if (closingRuns.has(run.id)) return null; // another close is in flight
|
||||
const state = await getProjectState(run.userId, run.projectKey).catch(() => null);
|
||||
const session = resolveProjectSession(null, state);
|
||||
if (!session) return null;
|
||||
|
||||
const adapterId: AdapterId = (ORCHESTRATION_ADAPTER_IDS as readonly string[]).includes(run.adapter)
|
||||
? (run.adapter as AdapterId)
|
||||
: DEFAULT_ADAPTER_ID;
|
||||
const patch = adapterFor(adapterId)?.closeRunFromSession?.(run, session) ?? null;
|
||||
if (!patch) return null; // handoff not ready / predates the run — leave open
|
||||
|
||||
closingRuns.add(run.id);
|
||||
try {
|
||||
const recent = await getRecentOutcomes(run.userId, run.projectKey).catch(() => []);
|
||||
await gateAndCloseRun(run.id, patch, run.userId, run.projectKey, recent.map((r) => r.outcome), run.adapter);
|
||||
return patch.outcome;
|
||||
} finally {
|
||||
closingRuns.delete(run.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Close every open run whose project's pushed session state reports a ready
|
||||
* handoff newer than the run start. Serial on purpose — each close may invoke
|
||||
* the cross-model DoD judge, and a cron tick has headroom while a thundering
|
||||
* herd of judge calls does not. */
|
||||
export async function closeOpenRunsFromPushedState(): Promise<CloseSweepResult> {
|
||||
const open = await listOpenRuns();
|
||||
const closed: CloseSweepResult["closed"] = [];
|
||||
|
||||
for (const run of open) {
|
||||
const outcome = await tryCloseRun(run).catch(() => null);
|
||||
if (outcome) closed.push({ runId: run.id, projectKey: run.projectKey, outcome });
|
||||
}
|
||||
|
||||
return { checked: open.length, closed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediate variant for the runtime-state ingestion path: the moment a runner
|
||||
* pushes a `ready` handoff for a project, close that project's open run —
|
||||
* no waiting for the hourly cron tick. minAge 0: the handoff's own
|
||||
* "post-dates run start" guard (closeRunFromSession) is the race protection.
|
||||
*/
|
||||
export async function closeOpenRunsForProject(userId: string, projectKey: string): Promise<number> {
|
||||
const open = await listOpenRuns(0);
|
||||
let n = 0;
|
||||
for (const run of open) {
|
||||
if (run.userId !== userId || run.projectKey.toLowerCase() !== projectKey.toLowerCase()) continue;
|
||||
const outcome = await tryCloseRun(run).catch(() => null);
|
||||
if (outcome) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Shared run-close with the definition-of-done stop-gate.
|
||||
*
|
||||
* Extracted from /api/control (which closes runs when a page poll sees a fresh
|
||||
* session handoff) so the reap-stale-runs cron can close runs UNATTENDED from
|
||||
* runner-pushed session state. Before this, run-close only ever happened on a
|
||||
* human page load — box-executed autopilot runs finished their work at 04:00,
|
||||
* nobody looked, and the reaper stamped them `timeout` an hour later (the
|
||||
* 2026-07-14 diagnosis: 14 days of autopilot, zero recorded successes, all of
|
||||
* them real work reaped as failures).
|
||||
*/
|
||||
import { getProjectGoalConfig } from "@/db/queries/project-context";
|
||||
import { updateOrchestrationRun } from "@/db/queries/orchestration-runs";
|
||||
import { emitRunEvent } from "@/db/queries/run-events";
|
||||
import { verifyDefinitionOfDone, applyDoDGate, DOD_JUDGE_MODEL } from "@/lib/orchestration/dod-gate";
|
||||
import type { RunClosePatch } from "@/lib/orchestration/close-from-session";
|
||||
import type { OrchestrationOutcome } from "@/db/schema/orchestration-runs";
|
||||
import { ORCHESTRATION_OUTCOME } from "@/db/schema/orchestration-runs";
|
||||
|
||||
/** Runs whose close is being gated/persisted right now — prevents the DoD judge
|
||||
* from firing more than once per run while a fire-and-forget close is in flight.
|
||||
* Module-level so the control route and the cron sweep share one in-flight set. */
|
||||
export const closingRuns = new Set<string>();
|
||||
|
||||
/**
|
||||
* Close an orchestration run, applying the definition-of-done stop-gate first.
|
||||
* When the run would close SUCCESS and the project declares a definition_of_done,
|
||||
* a different-lineage model checks the handoff against that bar; if it isn't met,
|
||||
* the run closes "partial" with the gap as `next`, so autopilot's continue-loop
|
||||
* keeps working instead of stopping on the agent's own say-so (the /goal pattern).
|
||||
*/
|
||||
export async function gateAndCloseRun(
|
||||
runId: string,
|
||||
closePatch: RunClosePatch,
|
||||
userId: string,
|
||||
projectKey: string,
|
||||
recentOutcomes: OrchestrationOutcome[] = [],
|
||||
workerAdapter = "agent",
|
||||
): Promise<void> {
|
||||
let patch = closePatch;
|
||||
if (closePatch.outcome === ORCHESTRATION_OUTCOME.SUCCESS) {
|
||||
const { definitionOfDone: dod, maxTurns } = await getProjectGoalConfig(userId, projectKey).catch(() => ({ definitionOfDone: null, maxTurns: null }));
|
||||
if (dod) {
|
||||
const verdict = await verifyDefinitionOfDone(dod, closePatch.summary);
|
||||
// priorPartials = consecutive partial closes so far = how many times the
|
||||
// goal has already re-looped (recentOutcomes is most-recent-first).
|
||||
let priorPartials = 0;
|
||||
for (const o of recentOutcomes) { if (o === ORCHESTRATION_OUTCOME.PARTIAL) priorPartials++; else break; }
|
||||
patch = applyDoDGate(closePatch, verdict, { maxTurns, priorPartials });
|
||||
// Record the cross-model verdict on the run so Activity can show that a
|
||||
// DIFFERENT model lineage judged the worker's handoff — the moat made
|
||||
// visible ("worker did it, judge checked it, here's the verdict").
|
||||
patch = {
|
||||
...patch,
|
||||
summary: {
|
||||
...patch.summary,
|
||||
verification: { judge: DOD_JUDGE_MODEL, worker: workerAdapter, met: verdict.met, gap: verdict.gap || undefined },
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
await updateOrchestrationRun(runId, patch, userId);
|
||||
// Run ledger: the closing hop declares itself with its (possibly DoD-gated)
|
||||
// outcome — the run's biography ends with a verdict, not silence.
|
||||
void emitRunEvent(runId, userId, "closed", { outcome: patch.outcome, state: patch.state });
|
||||
}
|
||||
Reference in new issue
Block a user