Files
loki/scripts/test/dispatch-gates.ts
T
Mao NakamotoandClaude Opus 4.7 2391c6f735 feat(autopilot): collapse 5 modes to off|on; delete strategist + beacon popup
Session 3 of killing-the-bash-daemon plan (/home/g/.claude/plans/
structured-baking-kazoo.md). Collapses the five-tier auto_inject_mode
ladder (off|queue_only|beacon|next_best|strategist) to binary off|on
and removes the dead complexity that protected the upper tiers.

What the modes meant (now retired):
  off         — manual, every dispatch is a click
  queue_only  — drain the queue, then stop
  beacon      — popup with countdown auto-pick (default for new users)
  next_best   — auto-fire canned template silently
  strategist  — Groq composes a fresh prompt from context

What "on" means now: when status:ready arrives, fire the queue head if
non-empty, else the canned next_best template. Safety rails (status:
working/blocked, blockers, no-op fuse, health/tests gate) all still
apply — being "on" doesn't override the agent's "not done" signal.
Most users only ever toggled between off and "fire when ready"; the
intermediate tiers added cognitive load without proportionate value.

DB migration applied to both local and Hetzner prod in this commit:
  UPDATE beacon_settings SET auto_inject_mode = CASE WHEN
    auto_inject_mode='off' THEN 'off' ELSE 'on' END
  UPDATE entities SET auto_inject_mode_override = (same CASE)
  ALTER TABLE ... ADD CONSTRAINT CHECK IN ('off','on')
  ALTER TABLE beacon_settings ALTER COLUMN auto_inject_mode
    SET DEFAULT 'on'
0 beacon_settings rows existed (both envs), 21 entities updated on
prod, 1324 on local. Constraints added cleanly.

Code deltas:
  - src/config/beacon.ts — AUTO_INJECT_MODE_VALUES is ["off","on"].
    LEGACY_AUTO_INJECT_MODE_VALUES + normalizeAutoInjectMode helper
    kept for tolerant reads of any unmigrated row.
  - src/lib/constants/control.ts — DEFAULT_AUTO_INJECT_MODE = "on".
  - src/db/schema/beacon-settings.ts — default "on".
  - src/lib/orchestration/dispatch-gates.ts — simplified to off/on
    decision; no fall-through to a composer. Safety rails preserved.
  - src/app/api/control/dispatch/route.ts — 361 → 160 LoC. Deleted
    buildPrompt, callGroq, parseGroqResponse, OrangeCat fetch, the
    strategist branch, and the gitBranch/recentCommits/mission
    decision inputs. DispatchResult.source union dropped "groq" +
    "fallback"; DispatchAction dropped "composed".
  - scripts/test/dispatch-gates.ts — rewrote for binary modes;
    11/11 pass.

Popup deletion (the L3 "beacon" mode's UI surface):
  - src/app/beacon/{layout,[id]/{page,BeaconClient},live/{page,
    BeaconLiveClient}}.tsx — the popup React tree
  - src/app/api/beacon/{[id],cancel,sse,window/{hide,show}}/route.ts
    — popup-specific API routes
KEPT: /api/beacon/queue (Fleet Runner uses it), /api/beacon/recent,
/api/beacon/transcribe, top-level /api/beacon/route.ts (other
consumers besides the popup import cancelActiveBeaconSessions).

UI updates (mode collapse fans through):
  - AutomationPolicyControl.tsx — 2 dots not 5
  - ControlFleetStatus.tsx — 2 hint strings
  - ProjectCard.tsx — automation labels for off/on only
  - use-project-card-actions.ts — strategist "composed" path removed

Verification: tsc clean, test:home 97/97, test:dispatch-gates 11/11,
test:control-presenter 19/19, lint clean (8 pre-existing warnings).

scripts/agent-hook-bridge.sh shows as dirty in the working tree from
earlier system-level edits today; intentionally left out of this
commit. It (and the rest of the bash scripts) gets deleted in
Session 4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-11 07:37:51 +02:00

173 lines
6.1 KiB
TypeScript

/**
* Inline tests for the dispatch-gate decisions. These gates short-circuit
* /api/control/dispatch 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.
*
* The 5-tier autopilot ladder collapsed to off|on on 2026-06-11; tests
* exercise the simpler logic. The strategist composer path is gone.
*
* 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}`);
};
// ── Safety gates (must fire regardless of mode) ────────────────────────
check("status:working short-circuits before any other gate", () => {
const result = evaluateDispatchGates({
status: "working",
blockerCount: 0,
mode: "on",
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 on mode + queue (user-intent wins)", () => {
const result = evaluateDispatchGates({
status: "working",
blockerCount: 0,
mode: "on",
queueLength: 3,
streakSuffix: "",
});
assert(result?.source === "status_gate", "status_gate must win over mode_gate even with queue items");
});
check("status:blocked short-circuits before any other gate", () => {
const result = evaluateDispatchGates({
status: "blocked",
blockerCount: 0,
mode: "on",
queueLength: 5,
streakSuffix: "",
});
assert(result?.action === "off", "blocked status must yield action=off");
assert(result?.source === "status_gate", `expected source=status_gate, got ${result?.source}`);
assert(result!.reason.includes("status:blocked"), "reason must name blocked status");
});
check("pending blocker short-circuits before mode gate", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 1,
mode: "on",
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("no-op fuse short-circuits before mode gate", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 0,
mode: "on",
queueLength: 0,
streakSuffix: "",
noOpCount: 3,
});
assert(result?.action === "off", "no-op fuse must yield action=off");
assert(result?.source === "status_gate", `expected source=status_gate, got ${result?.source}`);
assert(result!.reason.includes("3 consecutive no-op"), "reason must name the no-op count");
});
check("blocker count plural in reason when > 1", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 3,
mode: "on",
queueLength: 0,
streakSuffix: "",
});
assert(result!.reason.includes("3 pending blocker"), "reason must surface the actual count");
});
// ── Mode gates (binary off / on) ───────────────────────────────────────
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=on with queue items fires action=queue", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 0,
mode: "on",
queueLength: 2,
streakSuffix: " [last 5: ✓✓✓]",
});
assert(result?.action === "queue", "on + items = fire queue head");
assert(result?.source === "mode_gate", `expected source=mode_gate, got ${result?.source}`);
assert(result?.reason.includes("[last 5: ✓✓✓]"), "streak suffix must be appended");
});
check("mode=on with empty queue fires action=nextbest", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 0,
mode: "on",
queueLength: 0,
streakSuffix: " [last 5: ✗✓]",
});
assert(result?.action === "nextbest", "on + empty queue = canned next_best");
assert(result?.source === "empty_queue", `expected source=empty_queue, got ${result?.source}`);
assert(result?.reason.includes("queue empty"), "reason must explain empty queue");
assert(result?.reason.includes("[last 5: ✗✓]"), "streak suffix appended");
});
check("empty status string is treated permissively (preserves legacy behavior)", () => {
const result = evaluateDispatchGates({
status: "",
blockerCount: 0,
mode: "on",
queueLength: 0,
streakSuffix: "",
});
// Empty status falls through to mode handling — autopilot fires.
assert(result?.action === "nextbest", "missing status (legacy clients) does not block — autopilot fires");
});
check("status:ready with blockers still blocks (safety beats happy-path)", () => {
const result = evaluateDispatchGates({
status: "ready",
blockerCount: 2,
mode: "on",
queueLength: 5,
streakSuffix: "",
});
assert(result?.source === "blocker_gate", "blocker beats ready status");
});
console.log(`\n${passed} passed`);
}
runTests();