mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 10:07:19 +01:00
fix(dispatch): gate autopilot on status:working + pending blockers
Live-incident regression. Earlier today the autopilot injected a 2000-char next_best template into the user's keystrokes mid-typing while they were composing a message to the agent, producing garbled text like "wtf ust happened? what is this injecSetup (run, read outputs):...". The session handoff said status:working — which is documented in three places as the suppression signal — but the daemon fired anyway because nothing in the dispatch pipeline actually read the status field. Root cause: agent-hook-bridge.sh:autopilot_dispatch_and_inject() extracted done/next/tests/todos/health from the session file but not status. The dispatch route's HandoffSchema didn't include status either. The user trusted a guarantee the code never made. Three coordinated fixes: 1. agent-hook-bridge.sh now reads `status:` from the session file AND counts files in ~/.claude/sessions/<P>.blockers/pending/. Either condition (status:working OR blockerCount>0) causes the daemon to skip the dispatch HTTP call entirely — saves a network round-trip and surfaces the gate in daemon logs. 2. The dispatch route's HandoffSchema gains a `status` field and the body gains `blockerCount`. Defence-in-depth: even if a custom integration or cloud-only caller bypasses the daemon's client-side gate, the route refuses to act on a working status or pending blockers. Two new DispatchResult.source values (status_gate, blocker_gate) make these refusals greppable in logs. 3. The gate logic moves out of the route handler into a pure helper at src/lib/orchestration/dispatch-gates.ts so the invariants can be unit-tested without spinning up a real Next request. 11 inline tests cover: status:working wins over every mode; blockers beat happy-path; legacy empty status preserves existing permissive behavior; etc. Wired into `npm run test:dispatch-gates`. Closes the highest-impact symptom of the strategist's broken trust model. The user can now leave autopilot on and trust that their status:working handoff actually stops it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
5 files changed
+283
-39
No files matched your search
@@ -23,6 +23,7 @@
|
||||
"test:onboarding-heal": "npx tsx scripts/test/onboarding-heal.ts",
|
||||
"test:db-url": "npx tsx scripts/test/db-url.ts",
|
||||
"test:orchestration-summary": "npx tsx scripts/test/orchestration-summary.ts",
|
||||
"test:dispatch-gates": "npx tsx scripts/test/dispatch-gates.ts",
|
||||
"db:dump": "bash scripts/db/dump.sh",
|
||||
"db:restore": "bash scripts/db/restore.sh",
|
||||
"db:oracle-bootstrap": "bash scripts/db/oracle-bootstrap.sh",
|
||||
|
||||
@@ -403,14 +403,34 @@ autopilot_dispatch_and_inject() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
local done_line next_line tests_line todos_line health_line
|
||||
done_line=""; next_line=""; tests_line=""; todos_line=""; health_line=""
|
||||
local done_line next_line tests_line todos_line health_line status_line
|
||||
done_line=""; next_line=""; tests_line=""; todos_line=""; health_line=""; status_line=""
|
||||
if [ -f "$session_file" ]; then
|
||||
done_line=$(grep -m1 '^done:' "$session_file" 2>/dev/null | sed 's/^done:[[:space:]]*//' || true)
|
||||
next_line=$(grep -m1 '^next:' "$session_file" 2>/dev/null | sed 's/^next:[[:space:]]*//' || true)
|
||||
tests_line=$(grep -m1 '^tests:' "$session_file" 2>/dev/null | sed 's/^tests:[[:space:]]*//' || true)
|
||||
todos_line=$(grep -m1 '^todos:' "$session_file" 2>/dev/null | sed 's/^todos:[[:space:]]*//' || true)
|
||||
health_line=$(grep -m1 '^health:' "$session_file" 2>/dev/null | sed 's/^health:[[:space:]]*//' || true)
|
||||
status_line=$(grep -m1 '^status:' "$session_file" 2>/dev/null | sed 's/^status:[[:space:]]*//' || true)
|
||||
fi
|
||||
|
||||
# SSOT for autopilot pause signals lives on the user's filesystem: the agent
|
||||
# writes status:working when mid-task, and drops blocker files in pending/
|
||||
# when it needs a human action. Both gate the dispatch endpoint below.
|
||||
if [ "$status_line" = "working" ]; then
|
||||
log "autopilot: session status=working — staying idle (agent owns the loop)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local blocker_dir blocker_count
|
||||
blocker_dir="${HOME}/.claude/sessions/${tab_name}.blockers/pending"
|
||||
blocker_count=0
|
||||
if [ -d "$blocker_dir" ]; then
|
||||
blocker_count=$(find "$blocker_dir" -maxdepth 1 -type f 2>/dev/null | wc -l | tr -d ' ')
|
||||
fi
|
||||
if [ "$blocker_count" -gt 0 ]; then
|
||||
log "autopilot: ${blocker_count} pending blocker(s) at ${blocker_dir} — staying idle"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local queue_json
|
||||
@@ -419,10 +439,11 @@ autopilot_dispatch_and_inject() {
|
||||
local payload
|
||||
payload=$(jq -nc \
|
||||
--arg done "$done_line" --arg next "$next_line" --arg health "$health_line" \
|
||||
--arg tests "$tests_line" --arg todos "$todos_line" \
|
||||
--arg tests "$tests_line" --arg todos "$todos_line" --arg status "$status_line" \
|
||||
--arg project "$tab_name" \
|
||||
--argjson blockers "$blocker_count" \
|
||||
--argjson queue "$queue_json" \
|
||||
'{handoff:{done:$done,next:$next,health:$health,tests:$tests,todos:$todos},queue:$queue,projectName:$project,projectKey:$project}')
|
||||
'{handoff:{done:$done,next:$next,health:$health,tests:$tests,todos:$todos,status:$status},blockerCount:$blockers,queue:$queue,projectName:$project,projectKey:$project}')
|
||||
|
||||
local result action prompt reason
|
||||
result=$(curl -sf --max-time 18 -X POST "${APP_BASE_URL}/api/control/dispatch" \
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Inline tests for the dispatch-gate decisions. These gates short-circuit
|
||||
* /api/control/dispatch BEFORE any Groq call and BEFORE any auto-injection.
|
||||
* They are the safety primitives the user trusts: "if I write status:working,
|
||||
* autopilot stays out of my way." Live-incident regression coverage for
|
||||
* 2026-05-31 where the autopilot fired into the user's keystrokes mid-typing
|
||||
* despite the session handoff saying status:working.
|
||||
*
|
||||
* Run: npm run test:dispatch-gates
|
||||
*/
|
||||
import { evaluateDispatchGates } from "@/lib/orchestration/dispatch-gates";
|
||||
|
||||
function assert(condition: boolean, message: string): void {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
function runTests(): void {
|
||||
let passed = 0;
|
||||
const check = (label: string, fn: () => void) => {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ✓ ${label}`);
|
||||
};
|
||||
|
||||
check("status:working short-circuits before any other gate", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "working",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result !== null, "expected gate to fire");
|
||||
assert(result!.action === "off", `expected action=off, got ${result!.action}`);
|
||||
assert(result!.source === "status_gate", `expected source=status_gate, got ${result!.source}`);
|
||||
});
|
||||
|
||||
check("status:working overrides queue_only mode (user-intent wins)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "working",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
queueLength: 3,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.source === "status_gate", "status_gate must win over mode_gate even with queue items");
|
||||
});
|
||||
|
||||
check("pending blocker short-circuits before mode gate", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 1,
|
||||
mode: "strategist",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.source === "blocker_gate", "blocker_gate must fire when count > 0");
|
||||
assert(result?.action === "off", "blocked dispatch must yield action=off");
|
||||
assert(result!.reason.includes("1 pending blocker"), "reason must surface the count");
|
||||
});
|
||||
|
||||
check("blocker count plural in reason when > 1", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 3,
|
||||
mode: "strategist",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result!.reason.includes("3 pending blocker"), "reason must surface the actual count");
|
||||
});
|
||||
|
||||
check("mode=off returns mode_gate when status and blockers are clean", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "off",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.source === "mode_gate", "mode_gate fires when user disabled autopilot");
|
||||
assert(result?.action === "off", "mode=off yields action=off");
|
||||
});
|
||||
|
||||
check("mode=queue_only with empty queue yields action=off (idle)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.action === "off", "queue_only + empty queue = idle");
|
||||
assert(result?.reason.includes("queue is empty"), "reason must explain empty queue");
|
||||
});
|
||||
|
||||
check("mode=queue_only with queue fires action=queue", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
queueLength: 2,
|
||||
streakSuffix: " [last 5: ✓✓✓]",
|
||||
});
|
||||
assert(result?.action === "queue", "queue_only + items = fire queue head");
|
||||
assert(result?.reason.includes("[last 5: ✓✓✓]"), "streak suffix must be appended");
|
||||
});
|
||||
|
||||
check("mode=next_best returns canned action with streak suffix", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "next_best",
|
||||
queueLength: 0,
|
||||
streakSuffix: " [last 5: ✗✓]",
|
||||
});
|
||||
assert(result?.action === "nextbest", "legacy mode = canned next_best");
|
||||
assert(result?.reason.includes("[last 5: ✗✓]"), "streak suffix appended");
|
||||
});
|
||||
|
||||
check("mode=strategist with clean state yields null (fall through to Groq)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result === null, "no gate fired → null → route proceeds to Groq composition");
|
||||
});
|
||||
|
||||
check("empty status string is treated permissively (preserves legacy behavior)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result === null, "missing status (legacy clients) does not block — preserves existing behavior");
|
||||
});
|
||||
|
||||
check("status:ready with blockers still blocks (safety beats happy-path)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 2,
|
||||
mode: "strategist",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.source === "blocker_gate", "blocker beats ready status");
|
||||
});
|
||||
|
||||
console.log(`\n${passed} passed`);
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -19,6 +19,7 @@ import { logDebug } from "@/db/queries/debug-logs";
|
||||
import { getRecentOutcomes, type RecentOutcome } from "@/db/queries/orchestration-runs";
|
||||
import { getBeaconSettings } from "@/db/queries/beacon-settings";
|
||||
import { DEFAULT_AUTO_INJECT_MODE } from "@/lib/constants/control";
|
||||
import { evaluateDispatchGates, type AutoInjectMode } from "@/lib/orchestration/dispatch-gates";
|
||||
|
||||
// Compact display: ✓ for success, ✗ for error/hang/timeout, ~ for partial, ✕ for user_abort.
|
||||
const OUTCOME_GLYPH: Record<RecentOutcome["outcome"], string> = {
|
||||
@@ -39,11 +40,20 @@ const HandoffSchema = z.object({
|
||||
health: z.string().default(""),
|
||||
tests: z.string().default(""),
|
||||
todos: z.string().default(""),
|
||||
/** Agent's self-reported lifecycle. "working" means the agent is mid-task and
|
||||
* the autopilot must NOT inject anything. "ready" means handoff is final and
|
||||
* the strategist may pick the next task. Empty string is legacy / unknown
|
||||
* (treated permissively as "ready" so existing behavior is preserved). */
|
||||
status: z.string().default(""),
|
||||
});
|
||||
|
||||
const DispatchBody = z.object({
|
||||
handoff: HandoffSchema,
|
||||
queue: z.array(z.string().trim().min(1)).max(20),
|
||||
/** Count of files in ~/.claude/sessions/<P>.blockers/pending/ as reported by
|
||||
* the local daemon. Any value > 0 short-circuits dispatch — a blocker file
|
||||
* is a human-action gate and autopilot has to wait until it clears. */
|
||||
blockerCount: z.number().int().nonnegative().default(0),
|
||||
projectName: z.string().optional(),
|
||||
projectKey: z.string().optional(),
|
||||
gitBranch: z.string().optional(),
|
||||
@@ -56,7 +66,7 @@ export type DispatchResult = {
|
||||
action: DispatchAction;
|
||||
reason: string;
|
||||
/** Which inference path produced the decision. */
|
||||
source: "groq" | "health_gate" | "empty_queue" | "fallback" | "mode_gate";
|
||||
source: "groq" | "health_gate" | "empty_queue" | "fallback" | "mode_gate" | "status_gate" | "blocker_gate";
|
||||
/** Strategist-composed prompt body when action="composed". The caller
|
||||
* injects this as a custom prompt instead of firing the canned
|
||||
* next_best template. Absent for queue / nextbest / off paths. */
|
||||
@@ -195,7 +205,7 @@ export async function POST(req: NextRequest) {
|
||||
const dataOrResp = await readJsonBody(req, DispatchBody);
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
|
||||
const { handoff, queue, projectName, projectKey, gitBranch, recentCommits } = dataOrResp;
|
||||
const { handoff, queue, blockerCount, projectName, projectKey, gitBranch, recentCommits } = dataOrResp;
|
||||
|
||||
// Recent outcomes for this project — feeds Groq and is surfaced in the reason.
|
||||
// Safe-defaults: if the lookup fails, dispatch still proceeds.
|
||||
@@ -206,42 +216,22 @@ export async function POST(req: NextRequest) {
|
||||
const streak = streakLine(recentOutcomes);
|
||||
const streakSuffix = streak ? ` [last 5: ${streak}]` : "";
|
||||
|
||||
// Per-user auto-inject mode (added 2026-05-20). Gates the strategist
|
||||
// behavior before any expensive work:
|
||||
// strategist → Groq composes context-aware prompt (opt-in)
|
||||
// queue_only → only fire when there's a queue item; else off (DEFAULT for new users since 2026-05-25)
|
||||
// next_best → legacy: skip Groq, fire canned template
|
||||
// off → auto-inject disabled entirely; user dispatches by hand
|
||||
// Per-user auto-inject mode + the two safety gates (status:working,
|
||||
// pending blockers) added 2026-05-31. Centralized in evaluateDispatchGates
|
||||
// so the invariants are unit-tested without spinning up a real route.
|
||||
const settings = await getBeaconSettings(userId).catch(() => null);
|
||||
const mode = settings?.auto_inject_mode ?? DEFAULT_AUTO_INJECT_MODE;
|
||||
const mode = (settings?.auto_inject_mode ?? DEFAULT_AUTO_INJECT_MODE) as AutoInjectMode;
|
||||
|
||||
if (mode === "off") {
|
||||
return NextResponse.json({
|
||||
action: "off",
|
||||
reason: "Auto-inject is disabled in your beacon settings.",
|
||||
source: "mode_gate",
|
||||
} satisfies DispatchResult);
|
||||
}
|
||||
const gated = evaluateDispatchGates({
|
||||
status: handoff.status,
|
||||
blockerCount,
|
||||
mode,
|
||||
queueLength: queue.length,
|
||||
streakSuffix,
|
||||
});
|
||||
if (gated) return NextResponse.json(gated satisfies DispatchResult);
|
||||
|
||||
if (mode === "queue_only") {
|
||||
return NextResponse.json({
|
||||
action: queue.length > 0 ? "queue" : "off",
|
||||
reason: queue.length > 0
|
||||
? `Queue-only mode — firing queue item 1.${streakSuffix}`
|
||||
: "Queue-only mode and queue is empty — nothing to do.",
|
||||
source: "mode_gate",
|
||||
} satisfies DispatchResult);
|
||||
}
|
||||
|
||||
if (mode === "next_best") {
|
||||
return NextResponse.json({
|
||||
action: "nextbest",
|
||||
reason: `Legacy next_best mode (no strategist).${streakSuffix}`,
|
||||
source: "mode_gate",
|
||||
} satisfies DispatchResult);
|
||||
}
|
||||
|
||||
// mode === "strategist" — fall through to existing logic.
|
||||
// mode === "strategist" — fall through to Groq composition.
|
||||
|
||||
// No queue items + strategist mode: still call Groq to compose from
|
||||
// handoff + commits + outcomes. The strategist's value is highest
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Pre-Groq gates for the /api/control/dispatch route. Centralized so the
|
||||
* route handler stays focused on the strategist composition path and so
|
||||
* the gate invariants can be unit-tested without a running server.
|
||||
*
|
||||
* Gate precedence (first matching wins; all return action="off"):
|
||||
* 1. handoff.status === "working" — agent declared mid-task; never interrupt
|
||||
* 2. blockerCount > 0 — human-action gate is open; wait for clear
|
||||
* 3. mode === "off" — user disabled autopilot in settings
|
||||
* Plus the non-off short-circuits:
|
||||
* 4. mode === "queue_only" — fire queue head or stay idle
|
||||
* 5. mode === "next_best" — fire the canned template
|
||||
* `null` means "no gate fired — proceed to strategist (Groq composition)".
|
||||
*/
|
||||
|
||||
import type { DispatchAction, DispatchResult } from "@/app/api/control/dispatch/route";
|
||||
|
||||
export type AutoInjectMode = "off" | "queue_only" | "next_best" | "strategist";
|
||||
|
||||
export type GateInput = {
|
||||
status: string;
|
||||
blockerCount: number;
|
||||
mode: AutoInjectMode;
|
||||
queueLength: number;
|
||||
streakSuffix: string;
|
||||
};
|
||||
|
||||
export function evaluateDispatchGates(input: GateInput): DispatchResult | null {
|
||||
const { status, blockerCount, mode, queueLength, streakSuffix } = input;
|
||||
|
||||
if (status === "working") {
|
||||
return {
|
||||
action: "off",
|
||||
reason: "Agent reported status:working — autopilot must not interrupt an in-progress turn.",
|
||||
source: "status_gate",
|
||||
};
|
||||
}
|
||||
|
||||
if (blockerCount > 0) {
|
||||
return {
|
||||
action: "off",
|
||||
reason: `${blockerCount} pending blocker file(s) — autopilot waits until the user clears the human-action gate.`,
|
||||
source: "blocker_gate",
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "off") {
|
||||
return {
|
||||
action: "off",
|
||||
reason: "Auto-inject is disabled in your beacon settings.",
|
||||
source: "mode_gate",
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "queue_only") {
|
||||
const fired: DispatchAction = queueLength > 0 ? "queue" : "off";
|
||||
return {
|
||||
action: fired,
|
||||
reason: queueLength > 0
|
||||
? `Queue-only mode — firing queue item 1.${streakSuffix}`
|
||||
: "Queue-only mode and queue is empty — nothing to do.",
|
||||
source: "mode_gate",
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "next_best") {
|
||||
return {
|
||||
action: "nextbest",
|
||||
reason: `Legacy next_best mode (no strategist).${streakSuffix}`,
|
||||
source: "mode_gate",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user