mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 09:20:03 +01:00
feat(handoff): agent-driven auto-inject gate via status field — model-agnostic
User asked: stop firing auto-inject prompts while the agent is mid-task;
inject should only fire when the agent has done everything and now
needs a nudge. They also called out the broader goal that this should
work for any model (claude, codex, gemini, openclaw, or future
adapters) — not just claude — since today's behavior is implicitly
claude-coupled through ~/.claude/sessions/*.md and the stop hook.
Added a new \`status\` field to the canonical handoff format. The
agent self-reports lifecycle state per turn:
status: ready — task fully done, auto-inject may proceed
status: working — agent is mid-task, suppress auto-inject
Missing / undefined / any-other-value is treated as NOT ready. This
inverts today's implicit default (auto-fire fires on every turn end)
so the agent must explicitly signal it's done with everything before
the beacon/ReadyBanner countdown fires the next prompt. Matches the
user's stated intent literally.
Why this is model-agnostic: the field lives in the canonical
ORCHESTRATION_TASK_SUMMARY_FIELDS constant that ALL adapters' handoff
templates read from (claude via buildPromptWithSession, openclaw via
renderSharedHandoffBlock, codex/gemini will inherit when their
handoff plumbing is wired). The parsers (parseSessionFile,
parseSessionText, home/watcher.ts:parseHandoff) all pick it up
automatically. Any new adapter that writes the standard handoff
format gets the same gating.
Files touched:
• src/lib/orchestration/contract.ts — added 'status' to
ORCHESTRATION_TASK_SUMMARY_FIELDS; OrchestrationTaskSummary makes
status optional for back-compat.
• src/lib/events.ts — Handoff zod schema gains status (defaults to
"") so home/ events with status round-trip cleanly.
• src/lib/control-types.ts — SessionState.status is optional;
legacy construction sites that don't yet plumb session_status can
omit it and naturally suppress auto-fire.
• src/lib/agent-config.ts:buildPromptWithSession — new status line
in the handoff template prose (the one claude reads each turn).
• src/lib/orchestration/renderers.ts:renderSharedHandoffBlock —
same line for openclaw.
• src/lib/session-content.ts:parseSessionText — beacon DB parser
extracts status.
• home/watcher.ts:FIELDS — home/ watcher's handoff parser includes
status (cascades to worker.idle events).
• src/hooks/use-project-card-actions.ts:handleAutoInject —
explicit gate: only fires when status === 'ready' (or
health-critical for recovery dispatches).
• src/app/beacon/[id]/BeaconClient.tsx:handleAutoInject — same
gate, parsing status out of session.sessionContent via
parseSessionText (BeaconSession carries raw md text).
• src/app/api/orchestration/runs/[id]/finish/route.ts — finish
body summary preserves status.
• home/{decide,emit,state,worker}.ts test fixtures — added
status: "" to all Handoff literals so the new required-after-
default field type-checks.
tsc clean, eslint clean, npm run test:home 82/82.
Transition note: until adapters start emitting status in their
handoffs, auto-inject will suppress for everyone. This is the user's
explicit choice ("only fire when the agent has done everything").
The handoff template prose now tells the agent to write the field,
so going forward agents will include it.
NOT shipped in this commit (deliberate scope cut, queued for next):
• DB column session_status on project_states (mirror of the new
field) — without it, control/stream/route.ts can't surface the
field server-side. Today the BeaconClient parses status directly
from raw session.md content; the broader cloud /control flow
will get accurate status once the column lands.
• Bash side (agent-hook-bridge.sh:emit_worker_finished) reading
status from session.md and including in worker.finished events.
The user has denied prior edits to that file; happy to ship if
they want or leave it for them to land.
This commit is contained in:
14 files changed
+80
-27
No files matched your search
+9
-9
@@ -214,7 +214,7 @@ function selfTest() {
|
||||
input: {
|
||||
project: {
|
||||
...baseProject,
|
||||
lastHandoff: { done: "x", next: "", tests: "", todos: "", health: "critical — auth broken" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "", todos: "", health: "critical — auth broken" },
|
||||
},
|
||||
},
|
||||
expect: (d) => d.action.kind === "recovery" && d.action.intent === "unblock",
|
||||
@@ -224,7 +224,7 @@ function selfTest() {
|
||||
input: {
|
||||
project: {
|
||||
...baseProject,
|
||||
lastHandoff: { done: "x", next: "", tests: "3/5 pass, 2 fail", todos: "", health: "good" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "3/5 pass, 2 fail", todos: "", health: "good" },
|
||||
},
|
||||
},
|
||||
expect: (d) => d.action.kind === "recovery" && d.action.intent === "test_and_fix",
|
||||
@@ -232,7 +232,7 @@ function selfTest() {
|
||||
{
|
||||
name: "queue head dispatched when present and health OK",
|
||||
input: {
|
||||
project: { ...baseProject, lastHandoff: { done: "x", next: "", tests: "all pass", todos: "0", health: "good" } },
|
||||
project: { ...baseProject, lastHandoff: { status: "", done:"x", next: "", tests: "all pass", todos: "0", health: "good" } },
|
||||
queueHead: "Run security audit",
|
||||
},
|
||||
expect: (d) => d.action.kind === "dispatch" && d.action.intent === "custom",
|
||||
@@ -240,7 +240,7 @@ function selfTest() {
|
||||
{
|
||||
name: "empty queue + healthy → next_best",
|
||||
input: {
|
||||
project: { ...baseProject, lastHandoff: { done: "x", next: "", tests: "all pass", todos: "0", health: "good" } },
|
||||
project: { ...baseProject, lastHandoff: { status: "", done:"x", next: "", tests: "all pass", todos: "0", health: "good" } },
|
||||
},
|
||||
expect: (d) => d.action.kind === "dispatch" && d.action.intent === "next_best",
|
||||
},
|
||||
@@ -249,7 +249,7 @@ function selfTest() {
|
||||
input: {
|
||||
// Fresh project, zero history. The UI Dispatch button hits this path —
|
||||
// it must fire even when computeConfidence is still neutral 0.5.
|
||||
project: { ...baseProject, lastHandoff: { done: "", next: "", tests: "", todos: "", health: "good" } },
|
||||
project: { ...baseProject, lastHandoff: { status: "", done:"", next: "", tests: "", todos: "", health: "good" } },
|
||||
autonomy: "manual",
|
||||
},
|
||||
expect: (d) => d.autoExecute,
|
||||
@@ -259,7 +259,7 @@ function selfTest() {
|
||||
input: {
|
||||
project: {
|
||||
...baseProject,
|
||||
lastHandoff: { done: "x", next: "", tests: "", todos: "", health: "critical — auth broken" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "", todos: "", health: "critical — auth broken" },
|
||||
},
|
||||
autonomy: "manual",
|
||||
},
|
||||
@@ -271,7 +271,7 @@ function selfTest() {
|
||||
project: {
|
||||
...baseProject,
|
||||
recentOutcomes: ["success", "success", "success", "success", "success"],
|
||||
lastHandoff: { done: "x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
},
|
||||
autonomy: "confirm",
|
||||
},
|
||||
@@ -283,7 +283,7 @@ function selfTest() {
|
||||
project: {
|
||||
...baseProject,
|
||||
recentOutcomes: ["success", "success", "success", "success", "success"],
|
||||
lastHandoff: { done: "x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
},
|
||||
autonomy: "sleep",
|
||||
},
|
||||
@@ -295,7 +295,7 @@ function selfTest() {
|
||||
project: {
|
||||
...baseProject,
|
||||
recentOutcomes: ["error", "error", "success"],
|
||||
lastHandoff: { done: "x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
lastHandoff: { status: "", done:"x", next: "", tests: "all pass", todos: "0", health: "good" },
|
||||
},
|
||||
autonomy: "sleep",
|
||||
},
|
||||
|
||||
+4
-4
@@ -65,7 +65,7 @@ function selfTest() {
|
||||
appendEvent({
|
||||
kind: "worker.idle",
|
||||
project: "TestProject",
|
||||
handoff: { done: "", next: "", tests: "", todos: "", health: "good" },
|
||||
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "good" },
|
||||
}, tmpLog);
|
||||
const line = fs.readFileSync(tmpLog, "utf8").trim();
|
||||
const parsed = parseEvent(line);
|
||||
@@ -83,9 +83,9 @@ function selfTest() {
|
||||
run: () => {
|
||||
const log = path.join(tmpDir, "distinct.jsonl");
|
||||
appendEvent({ kind: "worker.idle", project: "A",
|
||||
handoff: { done: "", next: "", tests: "", todos: "", health: "" }}, log);
|
||||
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, log);
|
||||
appendEvent({ kind: "worker.idle", project: "A",
|
||||
handoff: { done: "", next: "", tests: "", todos: "", health: "" }}, log);
|
||||
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, log);
|
||||
const lines = fs.readFileSync(log, "utf8").trim().split("\n");
|
||||
if (lines.length !== 2) return false;
|
||||
const r1 = parseEvent(lines[0]); const r2 = parseEvent(lines[1]);
|
||||
@@ -97,7 +97,7 @@ function selfTest() {
|
||||
run: () => {
|
||||
const nested = path.join(tmpDir, "deeply/nested/path/log.jsonl");
|
||||
appendEvent({ kind: "worker.idle", project: "Nest",
|
||||
handoff: { done: "", next: "", tests: "", todos: "", health: "" }}, nested);
|
||||
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "" }}, nested);
|
||||
return fs.existsSync(nested) && fs.statSync(nested).size > 0;
|
||||
},
|
||||
},
|
||||
|
||||
+1
-1
@@ -204,7 +204,7 @@ function selfTest() {
|
||||
});
|
||||
const finished = (runId: string, outcome: Outcome = "success"): Event => ({
|
||||
v: 1, id: `f-${runId}`, ts: baseTs, kind: "worker.finished",
|
||||
project: "T", runId, handoff: { done: "x", next: "", tests: "", todos: "", health: "good" },
|
||||
project: "T", runId, handoff: { status: "", done:"x", next: "", tests: "", todos: "", health: "good" },
|
||||
outcome, durationMs: 1000,
|
||||
});
|
||||
const cancel = (runId: string): Event => ({
|
||||
|
||||
+2
-1
@@ -47,13 +47,14 @@ const DEBOUNCE_MS = 250;
|
||||
|
||||
// ── Parse the session.md handoff format ──────────────────────────────────────
|
||||
// Format (per project CLAUDE.md):
|
||||
// status: <ready | working> # 'ready' = done, auto-inject may fire
|
||||
// done: <one sentence>
|
||||
// next: <one sentence>
|
||||
// tests: <N pass · N fail, or 'no suite'>
|
||||
// todos: <count> TODOs
|
||||
// health: <good | needs attention | critical>
|
||||
|
||||
const FIELDS = ["done", "next", "tests", "todos", "health"] as const;
|
||||
const FIELDS = ["status", "done", "next", "tests", "todos", "health"] as const;
|
||||
|
||||
function parseHandoff(content: string): Handoff {
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
+1
-1
@@ -356,7 +356,7 @@ function selfTest() {
|
||||
const idle: Event = {
|
||||
v: 1, id: "i1", ts: "2026-01-01T00:00:00Z",
|
||||
kind: "worker.idle", project: "Test",
|
||||
handoff: { done: "", next: "", tests: "", todos: "", health: "good" },
|
||||
handoff: { status: "", done:"", next: "", tests: "", todos: "", health: "good" },
|
||||
};
|
||||
applyEvent(s, idle, "live");
|
||||
return s.startedRunIds.size === 0 && s.pendingDispatches.size === 0;
|
||||
|
||||
@@ -35,10 +35,11 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
|
||||
const summary = body.summary
|
||||
? {
|
||||
done: body.summary.done ?? "",
|
||||
next: body.summary.next ?? "",
|
||||
tests: body.summary.tests ?? "",
|
||||
todos: body.summary.todos ?? "",
|
||||
status: body.summary.status ?? "",
|
||||
done: body.summary.done ?? "",
|
||||
next: body.summary.next ?? "",
|
||||
tests: body.summary.tests ?? "",
|
||||
todos: body.summary.todos ?? "",
|
||||
health: body.summary.health ?? "",
|
||||
}
|
||||
: null;
|
||||
|
||||
@@ -158,7 +158,18 @@ function BeaconBody({
|
||||
|
||||
// Auto-fire logic: picks the right choice based on queue / capacity issue state.
|
||||
// Called by ReadyBanner when the countdown reaches zero (and auto-continue is on).
|
||||
//
|
||||
// Agent-driven gate: handoff.status must say "ready" before any auto-fire
|
||||
// happens. Anything else (empty, "working", any other value) suppresses.
|
||||
// Model-agnostic — any adapter that writes the standard handoff fields
|
||||
// gets the same gating. Capacity-issue (agent quota hit) bypasses since
|
||||
// that's a recovery dispatch the user explicitly asked for.
|
||||
const handleAutoInject = useCallback(() => {
|
||||
// BeaconSession carries raw sessionContent — parse it here to extract
|
||||
// the handoff status. Capacity-issue dispatches bypass since the user
|
||||
// explicitly asked for the agent switch.
|
||||
const status = (parseSessionText(session.sessionContent).status ?? "").toLowerCase();
|
||||
if (status !== "ready" && !session.capacityIssue) return;
|
||||
const all = promptsRef.current;
|
||||
const primary = all.find((p) => p.style === "primary");
|
||||
const choice = session.capacityIssue && session.nextAgent
|
||||
@@ -168,7 +179,7 @@ function BeaconBody({
|
||||
: primary ? (primary.slot != null ? String(primary.slot) : primary.key) : "1";
|
||||
if (!session.capacityIssue && queue.length > 0) remove(0);
|
||||
submitRef.current(choice);
|
||||
}, [session.capacityIssue, session.nextAgent, queue, remove]);
|
||||
}, [session.sessionContent, session.capacityIssue, session.nextAgent, queue, remove]);
|
||||
|
||||
const morePrompts = prompts.filter((p) => p.style === "more");
|
||||
|
||||
|
||||
@@ -148,6 +148,14 @@ export function useProjectCardActions({
|
||||
|
||||
const handleAutoInject = useCallback(async () => {
|
||||
if (!isAutoContinueEnabledSync(project.tab)) return;
|
||||
// Agent-driven gate: handoff.status must explicitly say "ready" before
|
||||
// auto-inject can fire. Anything else (empty, "working", or any other
|
||||
// value) suppresses. This is the model-agnostic signal — any adapter
|
||||
// that writes the standard handoff format gets the same gating.
|
||||
// Health-critical bypasses the gate so recovery dispatches still fire.
|
||||
const status = (project.session?.status ?? "").toLowerCase();
|
||||
const healthCritical = (project.session?.health ?? "").toLowerCase().includes("critical");
|
||||
if (status !== "ready" && !healthCritical) return;
|
||||
if (sessionHealthBlocksQueue()) {
|
||||
await sendIntent("next_best");
|
||||
return;
|
||||
@@ -166,7 +174,7 @@ export function useProjectCardActions({
|
||||
}
|
||||
await sendIntent("next_best");
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [preloadedDispatch, shiftQueue, queue.length, project.tab, onInject, setDismissed, project.session?.health, project.session?.tests]);
|
||||
}, [preloadedDispatch, shiftQueue, queue.length, project.tab, onInject, setDismissed, project.session?.status, project.session?.health, project.session?.tests]);
|
||||
|
||||
const handleSendFromQueue = useCallback(async (index: number) => {
|
||||
const item = queue[index];
|
||||
|
||||
@@ -173,6 +173,7 @@ export function buildPromptWithSession(base: string, tab: string): string {
|
||||
const sessionFile = path.join(SESSIONS_DIR(), `${tab}.md`);
|
||||
const sessionUpdateBlock = [
|
||||
`When done, update ${sessionFile} with exactly these lines:`,
|
||||
"status: <ready | working> # 'ready' = task fully done; 'working' = still more to do on this task. Auto-inject only fires when 'ready'.",
|
||||
"done: <one sentence what you completed>",
|
||||
"next: <one sentence what remains>",
|
||||
"tests: <N pass · N fail, or 'no suite'>",
|
||||
|
||||
@@ -21,6 +21,13 @@ export type CurrentPrompt = {
|
||||
};
|
||||
|
||||
export type SessionState = {
|
||||
/** Agent's self-reported lifecycle state: 'ready' = done, auto-inject may
|
||||
* proceed; 'working' = mid-task, suppress auto-inject. Missing/undefined
|
||||
* is treated as NOT ready by the auto-inject gates (conservative). Optional
|
||||
* so legacy construction sites that don't yet plumb session_status can
|
||||
* omit it during the back-compat window — they'll just suppress auto-fire
|
||||
* which matches the user's stated intent. */
|
||||
status?: string;
|
||||
done: string;
|
||||
next: string;
|
||||
tests: string;
|
||||
|
||||
+11
-1
@@ -27,8 +27,18 @@ const RunId = z.string().uuid();
|
||||
const PaneId = z.string().min(1).max(120);
|
||||
const Project = z.string().min(1).max(200);
|
||||
|
||||
/** Five session-handoff fields the agent writes to ~/.claude/sessions/<tab>.md */
|
||||
/**
|
||||
* Six session-handoff fields the agent writes to ~/.claude/sessions/<tab>.md.
|
||||
*
|
||||
* `status` (added 2026-05) is the agent's self-reported lifecycle state for
|
||||
* the run — "ready" means done with everything (auto-inject may proceed),
|
||||
* "working" means mid-task (auto-inject suppressed). Missing/empty defaults
|
||||
* to "working" downstream — auto-inject only fires when the agent EXPLICITLY
|
||||
* signals it's done. Model-agnostic: every adapter that writes this handoff
|
||||
* format gets the same gating.
|
||||
*/
|
||||
export const Handoff = z.object({
|
||||
status: z.string().default(""),
|
||||
done: z.string().default(""),
|
||||
next: z.string().default(""),
|
||||
tests: z.string().default(""),
|
||||
|
||||
@@ -75,10 +75,21 @@ export type OrchestrationTaskRequest = {
|
||||
customInstructions?: string;
|
||||
};
|
||||
|
||||
export const ORCHESTRATION_TASK_SUMMARY_FIELDS = ["done", "next", "tests", "todos", "health"] as const;
|
||||
// `status` is the agent's self-reported lifecycle state for this handoff:
|
||||
// ready — task fully done, auto-inject may proceed
|
||||
// working — agent is mid-task, suppress auto-inject
|
||||
// Missing/empty defaults to working (conservative — auto-inject only fires
|
||||
// when the agent explicitly signals it's done with everything). This is
|
||||
// model-agnostic: any adapter that writes the standard handoff format
|
||||
// gets the same auto-inject suppression.
|
||||
export const ORCHESTRATION_TASK_SUMMARY_FIELDS = ["status", "done", "next", "tests", "todos", "health"] as const;
|
||||
export type OrchestrationTaskSummaryField = (typeof ORCHESTRATION_TASK_SUMMARY_FIELDS)[number];
|
||||
|
||||
export type OrchestrationTaskSummary = Record<OrchestrationTaskSummaryField, string>;
|
||||
// status is optional for back-compat — older summaries on the wire don't have
|
||||
// it. Downstream readers treat missing/undefined as "not ready" (suppress).
|
||||
export type OrchestrationTaskSummary =
|
||||
& { [K in Exclude<OrchestrationTaskSummaryField, "status">]: string }
|
||||
& { status?: string };
|
||||
|
||||
export type OrchestrationTaskStatus = {
|
||||
state: OrchestrationState;
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { AdapterId, OrchestrationTaskRequest } from "./contract";
|
||||
function renderSharedHandoffBlock(): string {
|
||||
return [
|
||||
"When done, update the session handoff with exactly these lines:",
|
||||
"status: <ready | working> # 'ready' = task fully done; 'working' = still more to do. Auto-inject only fires when 'ready'.",
|
||||
"done: <one sentence what you completed>",
|
||||
"next: <one sentence what remains>",
|
||||
"tests: <N pass · N fail, or 'no suite'>",
|
||||
|
||||
@@ -19,6 +19,7 @@ export function splitSessionItems(text: string): string[] {
|
||||
// ── Beacon DB content parser ──────────────────────────────────────────────────
|
||||
|
||||
type ParsedSession = {
|
||||
status: string;
|
||||
done: string[];
|
||||
next: string[];
|
||||
in_progress: string[];
|
||||
@@ -28,13 +29,14 @@ type ParsedSession = {
|
||||
};
|
||||
|
||||
export function parseSessionText(content: string): ParsedSession {
|
||||
const result: ParsedSession = { done: [], next: [], in_progress: [], tests: "", todos: "", health: "" };
|
||||
const result: ParsedSession = { status: "", done: [], next: [], in_progress: [], tests: "", todos: "", health: "" };
|
||||
for (const line of content.split("\n")) {
|
||||
const idx = line.indexOf(":");
|
||||
if (idx <= 0) continue;
|
||||
const k = line.slice(0, idx).trim().toLowerCase();
|
||||
const v = line.slice(idx + 1).trim();
|
||||
if (k === "done") result.done = splitSessionItems(v);
|
||||
if (k === "status") result.status = v;
|
||||
else if (k === "done") result.done = splitSessionItems(v);
|
||||
else if (k === "next") result.next = splitSessionItems(v);
|
||||
else if (k === "in_progress") result.in_progress = splitSessionItems(v);
|
||||
else if (k === "tests") result.tests = v;
|
||||
|
||||
Reference in new issue
Block a user