feat(strategist): prompt intelligence v1 — Groq composes context-aware auto-inject bodies

Closes the gap Cursor's audit named and Claude's response confirmed:
auto-inject had become 'generic next_best ladder' instead of
'context-aware prompt that drives the product forward.' Thirty commits
of plumbing (status field, queue in DB, daemon heartbeat, /tmp mirror)
didn't change what the model reads when it wakes up. This commit does.

Full reasoning + design in content/thoughts/strategist-and-prompt-quality.md.

Changes (in order of blast radius):

  1. /api/control/dispatch — strategist v1 (the meat)
     • DispatchAction expands from 'queue | nextbest' to add 'composed'
       and 'off'.
     • DispatchResult.prompt holds the Groq-composed body when
       action='composed'.
     • Groq prompt asks for one of three actions + an optional PROMPT:
       body. The composer drafts a fresh prompt from handoff.next,
       queue tail, recent commits, and outcome streak — concrete verbs,
       named files where possible, ≤2000 chars.
     • maxTokens 100 → 1500 so the composed body has room.
     • Reads auto_inject_mode from beacon_settings and gates:
       off → action='off' (suppress), queue_only → queue or off,
       next_best → skip Groq + return nextbest, strategist → full chain.
     • Strategist now runs even with empty queue — that's when it's
       most valuable (smart nudge from session.next + commits alone).
       Previously short-circuited to nextbest on empty queue.

  2. src/lib/orchestration/renderers.ts — SSOT next_best body
     • Adopts the bash hook's shape (the concrete one user has been
       pasting every loop turn). Old abstract scan ladder is gone.
     • Model-agnostic: avoids assumed tech stack (no hardcoded `git
       status` / `npx tsc`). Verifies via 'are there type/lint/compile
       errors' phrasing that translates across runtimes.

  3. src/hooks/use-project-card-actions.ts — consume composed bodies
     • handleAutoInject branches on action='composed' and injects the
       returned prompt body as a custom prompt instead of firing
       sendIntent('next_best').
     • Respects action='off' from mode_gate by returning early.
     • Pre-fetch fires whenever ready (not gated on queue.length > 0)
       so the strategist can compose even when queue is empty.

  4. beacon_settings.auto_inject_mode (drizzle/0011)
     • New text column, default 'strategist'. Values: strategist |
       queue_only | next_best | off.
     • Schema TS + queries plumbed; UI carryover patched in
       BeaconSettings.tsx (full UI for the toggle is a follow-up).

  5. /api/control/runtime-state — defensive against duplicate keys
     • Found two rows for same lowercase project_key ('cockpit' and
       'Cockpit', empty queue won iteration order). Sync now groups
       by lowercase and prefers the row with the longest queue. The
       duplicate row was deleted from Neon as a one-time fix; long-
       term a uniqueness-on-lowercase migration is queued.

Migrations applied to Neon prod: 0011 via psql + neonctl. Local PG
is no longer authoritative (.env.local now points cockpit-app at
Neon; verified daemon-token auth resolves to default user b94a359d
and runtime-state sync writes /tmp/agent-queue-cockpit with the real
queue content).

Tests: tsc clean, eslint clean (src/ + home/), npm run test:home
89/89. UI for autoInjectMode toggle is queued.

Co-developed with: prompt-quality audit pass from Cursor Composer
2.5 + Claude synthesis; provenance + design rationale in
content/thoughts/strategist-and-prompt-quality.md.
This commit is contained in:
g-but committed 2026-05-20 13:31:57 +02:00
1 parent 88f65afd85
commit 852c51bbab
9 files changed
+325 -40

No files matched your search

@@ -0,0 +1,132 @@
---
title: Prompt Intelligence — Why Plumbing Was Not Enough
summary: A migration from "infrastructure-only auto-inject" to a strategist that composes context-aware prompts. Closes the gap between the queue, the agent, and the user's actual intent.
excerpt: We spent thirty commits making the queue durable, the status field model-agnostic, and the daemon honest. None of that made the injected prompt smarter. This is the work that does.
publishedAt: 2026-05-20
tags: agents,prompts,orchestration,strategist,architecture
featured: false
author: g
readingTimeMin: 12
---
## The Gap That Took Two Audits To See
Over the last two weeks Cockpit's orchestration layer got steadily more correct: per-project `status` gating so auto-inject only fires when the agent self-reports `ready`, queue moved from `/tmp` to `project_states.prompt_queue`, daemon heartbeat to keep the cloud's view fresh, queue context plumbed into the dispatched prompt body, click-to-expand on truncated working banners, the lot. All real. All shipped. None of it changed what the model actually reads when it wakes up.
The injected prompt is still one of two ladders.
**`renderTaskForAdapter` in `src/lib/orchestration/renderers.ts`:**
```
Work on the project at <path>.
Before choosing work, scan in order:
1. interrupted or uncommitted work to resume
2. failing tests or broken flows
3. SSOT / DRY / quality violations
4. mission or product misalignment
Pick the highest-impact item and execute it fully.
```
**`~/.config/agent-prompts.json` consumed by `scripts/agent-hook-bridge.sh`:**
```
Run `git status && git log --oneline -10`. Then run `npx tsc --noEmit`…
Work in this order: type errors → uncommitted work → session next: → highest-impact gap.
One thing. Done and committed.
```
Two templates, same intent ID, slightly different text. Cursor's audit caught it; this doc is the migration plan.
The user's own custom prompts in `prompt_history` look nothing like either ladder. They name the bug verbatim ("Failed to load chunk … and butaeff@gmail.com / password doesn't work"), they include constraints ("auth first, not release yet"), they often correct the orchestration system itself ("why was `continue` injected — is this SSOT?"). The auto-inject text is a generic triage scan that fires on a timer and produces work that drifts away from whatever the user last cared about.
The system has two halves and only one of them is intelligent.
## The Two Halves
| Half | What it does | Who wrote it |
|---|---|---|
| Plumbing | Get bytes from queue → DB → daemon → zellij → agent | Code (now solid) |
| Prompt | Decide what bytes to send | Static template (still dumb) |
The May 18 vision — *"go to bed, wake up to good work"* — needs the second half to be at least as smart as the first.
## What "Smart" Looks Like
Not a new model. Not a new service. The Groq call in `/api/control/dispatch` already has access to the right context: latest session handoff, queue head + tail, recent commits, outcome streak. Today it returns `ACTION: QUEUE | NEXTBEST + REASON` — a two-way classifier in 100 tokens. The strategist v1 promotes that same call to compose the *full prompt body* the agent receives, with a third action:
```
ACTION: QUEUE_ITEM | COMPOSED | NEXTBEST
PROMPT: <full text to inject, ≤4000 chars>
REASON: one sentence
```
- `QUEUE_ITEM` — fire `queue[0]` verbatim (unchanged behavior; fast path when the user has been explicit).
- `COMPOSED` — Groq writes a fresh prompt body using the handoff's `next:`, the queue tail, the last commit message, and the outcome streak. This is what closes the gap.
- `NEXTBEST` — explicit fallback to the SSOT next_best template (rarely; only when the strategist genuinely can't find a more specific direction).
The hard gates stay where they are: `status === 'ready'` agent-side, health-critical → recovery intent, manual click bypasses everything. The strategist only chooses *what to compose*, not *whether to fire*.
## What's Being Shipped
In order, smallest blast radius first.
### 1. One database for cloud and local stack
Local cockpit-app on `localhost:3000` has been pointed at a local Postgres for dev convenience. The hosted app on Vercel has always used Neon. The user's queue items, project rows, and `prompt_history` all live in Neon — the local Postgres is a near-empty dev artifact (2 users, 3 cockpit-ish project rows, zero non-empty queues at the time of this writing).
The split caused real bugs: yesterday's `/api/control` GET sync (commit `58e4366`) and `/api/control/runtime-state` POST sync (commit `eadb392`) both mirror DB → `/tmp/agent-queue-<tab>` when called from a local cockpit-app — but they query whichever DB the local cockpit-app is configured for, which has been local Postgres, which has been empty. The home/ queue badge from `3c78208` correspondingly read `/tmp` and reported zero queued even when Neon had pending items.
The fix is one line in `.env.local`: point `DATABASE_URL` (and `NEON_DATABASE_URL_DIRECT` for migrations) at Neon. Existing local data is preserved untouched (just no longer authoritative). Restart `cockpit-app`. Done.
### 2. SSOT one `next_best` template
The two templates that have diverged converge on the bash-hook version's shape, which Cursor noted is the better one: concrete commands ordered by priority, not abstract scanning categories. The repo-side source moves to that style in `src/lib/orchestration/renderers.ts:renderIntentBody`. The user-managed `~/.config/agent-prompts.json` is left to the user — it's their stored template, not in the repo — but is documented as a layer that should match.
### 3. Strategist v1 — `/api/control/dispatch` writes the prompt
`buildPrompt()` already constructs the system prompt that asks Groq to pick between queue and nextbest. Two changes:
- The Groq prompt asks for the new three-action protocol with an optional `PROMPT:` body.
- The response parser handles the third action and returns `prompt` alongside `reason`.
`DispatchResult` gains an optional `prompt: string | null` field. The caller — `handleAutoInject` in `src/hooks/use-project-card-actions.ts` and the beacon's parallel path — picks up the composed body and injects it as a custom prompt (going through `onInject` with `customPrompt`) rather than firing the canned `next_best` intent.
`maxTokens` on the Groq call jumps from 100 to ~1500 to give room for a composed body. Temperature stays low (0.2) so the strategist sticks to the facts in context rather than improvising fiction.
Failure mode is the existing one: if Groq times out, errors, or returns malformed output, fall back to queue head → next_best. The strategist is additive, not load-bearing.
### 4. `autoInjectMode` flag
A new per-user (or per-project) setting in `beacon_settings`:
```
auto_inject_mode: 'strategist' | 'queue_only' | 'next_best' | 'off'
```
- `strategist` (default) — full chain: queue → strategist → next_best fallback.
- `queue_only` — only fire queue items; never auto-compose, never next_best.
- `next_best` — legacy behavior (raw template, no strategist call). For users who want the current ladder.
- `off` — disable auto-inject entirely; user dispatches by hand.
`handleAutoInject` respects the mode. Default for existing users is `strategist`, which is a behavior change — the migration note is that this is the intended product direction and the user can opt back into `next_best` if they prefer the old ladder.
### 5. Sentinel-ordering fix — read once, cleanup at end
In `scripts/agent-hook-bridge.sh:handle_stop`, the runId sentinel is read once at the top into a local, both `finish_orchestration_run` and `emit_worker_finished` consume the local, and the sentinel is deleted exactly once at the end. This is the "read-once" shape Cursor described — smaller diff than the swap I'd tried before, no logic change inside either function.
## What's Deliberately Out of Scope
- A separate strategist service or worker pool. The existing Groq call is enough for v1.
- A persistent prompt-evaluation feedback loop ("did this composed prompt produce a useful outcome?"). That's v2.
- Multi-project queue intelligence (compose across projects). Single-project for now.
- Replacing the bash hook's prompt file. User-owned config, left alone.
## Success Signal
After this lands, if you write `status: ready` in `Cockpit.md` and walk away, the next thing your terminal receives is either (a) the top queue item you actually queued, or (b) a Groq-composed prompt that names what you said you'd do next, references the last commit's failure if there was one, and asks for the specific work — not "scan in order: 1, 2, 3, 4."
If you wake up and see "Pick the highest-impact item and execute it fully" again, the strategist has failed and we revert to the gate.
## Provenance
This document is the synthesis of two audits — Cursor Composer 2.5's first pass on this codebase, and Claude's response refining it. The actual implementation commits will reference this file.
@@ -0,0 +1,17 @@
-- Add auto_inject_mode to beacon_settings so users can opt out of the
-- strategist-composed auto-inject (default new behavior) and pick a
-- mode that fits their workflow:
--
-- strategist — DEFAULT: queue head → COMPOSED body → next_best fallback
-- queue_only — only fire queue items; never auto-compose or next_best
-- next_best — legacy: skip strategist call, fire canned template
-- off — disable auto-inject entirely (user must dispatch by hand)
--
-- Default value is 'strategist' for both new and existing users — the
-- new behavior is the intended product direction; users who prefer the
-- old ladder can flip this to 'next_best' explicitly.
--
-- Idempotent — re-runs without error.
ALTER TABLE "beacon_settings"
ADD COLUMN IF NOT EXISTS "auto_inject_mode" text NOT NULL DEFAULT 'strategist';
+111 -31
View File
@@ -1,10 +1,14 @@
/**
* POST /api/control/dispatch
*
* Strategist layer: decides whether to drain the queue or run next_best
* given the current session handoff, pending queue items, git context, and
* recent commit history. Returns quickly (< 300ms on Groq free tier).
* Falls back to QUEUE when Groq is unavailable.
* Strategist layer (v2, 2026-05-20): decides whether to drain the queue,
* fire the canned next_best template, OR compose a context-aware prompt
* body from session handoff + queue tail + recent commits + outcome
* streak. The composed path is the answer to "the agent's auto-injected
* prompts are dumb" — see content/thoughts/strategist-and-prompt-quality.md.
*
* Returns quickly (< 1.5s on Groq free tier; composed bodies add latency
* proportional to maxTokens). Falls back to QUEUE when Groq is unavailable.
*/
import { NextRequest, NextResponse } from "next/server";
@@ -12,6 +16,7 @@ import { readJsonBody, z } from "@/lib/api/route-helpers";
import { callGroqText } from "@/lib/groq";
import { getApiUserId } from "@/lib/session";
import { getRecentOutcomes, type RecentOutcome } from "@/db/queries/orchestration-runs";
import { getBeaconSettings } from "@/db/queries/beacon-settings";
// Compact display: ✓ for success, ✗ for error/hang/timeout, ~ for partial, ✕ for user_abort.
const OUTCOME_GLYPH: Record<RecentOutcome["outcome"], string> = {
@@ -43,13 +48,17 @@ const DispatchBody = z.object({
recentCommits: z.array(z.string()).max(5).optional(),
});
export type DispatchAction = "queue" | "nextbest";
export type DispatchAction = "queue" | "nextbest" | "composed" | "off";
export type DispatchResult = {
action: DispatchAction;
reason: string;
/** Which inference path produced the decision. */
source: "groq" | "health_gate" | "empty_queue" | "fallback";
source: "groq" | "health_gate" | "empty_queue" | "fallback" | "mode_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. */
prompt?: string;
};
// ── Prompt construction ────────────────────────────────────────────────────
@@ -96,48 +105,83 @@ The agent just finished a work session. Handoff summary:
The queue has ${queue.length} pending task${queue.length === 1 ? "" : "s"}:
${queueList}${queueOverflow}
Decide: should the agent next run queue item 1, or follow its own suggested next step?
Decide one of three actions:
Rules:
- Prefer QUEUE when: the first queue item is contextually related to what was just done or the recent commits, OR health is good and there is no strong continuity signal.
- Prefer NEXTBEST when: the agent's "next" field describes an obvious direct follow-up to "done", OR health is "needs attention" and the queue item is unrelated to recent commit history.
- NEXTBEST is already required (caller enforces it) when health is "critical" or tests contain "fail" — do not factor those in; focus on the subtler cases.
1. ACTION: QUEUE — fire queue item 1 verbatim. Prefer when the first queue item is contextually related to what was just done, OR when health is good and there is no strong continuity signal.
Respond in exactly this format (two lines, nothing else):
ACTION: QUEUE
REASON: one sentence explaining why the queue item should fire next
2. ACTION: NEXTBEST — fire the canned next_best template (generic "verify health, fix typecheck, execute session next, find adjacent broken thing"). Only choose this when both queue and handoff.next are weak signals AND there's no specific direction emerging from commits/outcomes.
or
3. ACTION: COMPOSED — you write a fresh prompt body that names exactly what the agent should do right now, drawing on the handoff's "next", the queue tail, the last commit, and the outcome streak. Prefer this when handoff.next is specific (e.g. "fix login flow", "ship migration 0011") or when a queue item plus commit history together point at one clear move. The body should sound like a teammate's next-step note — concrete verbs, named files or features where possible, ≤2000 characters.
ACTION: NEXTBEST
REASON: one sentence explaining why the agent's continuation is better right now`;
Respond in this format (no extra text):
ACTION: <QUEUE | NEXTBEST | COMPOSED>
REASON: one sentence on why this action is right now
PROMPT: <only when ACTION is COMPOSED — the full prompt body the agent will receive. Omit this line otherwise.>`;
}
// ── Groq call ─────────────────────────────────────────────────────────────
async function callGroq(prompt: string): Promise<{ action: DispatchAction; reason: string }> {
const text = await callGroqText(prompt, { maxTokens: 100, temperature: 0.2, timeoutMs: 10_000 });
async function callGroq(prompt: string): Promise<{ action: DispatchAction; reason: string; prompt?: string }> {
// maxTokens bumped from 100 → 1500 so the strategist has room for the
// COMPOSED body (≤2000 chars ≈ ~500 tokens, plus 50 for ACTION + REASON
// and a safety margin). Temperature stays low so the composer sticks to
// the named context rather than improvising.
const text = await callGroqText(prompt, { maxTokens: 1500, temperature: 0.2, timeoutMs: 15_000 });
return parseGroqResponse(text);
}
function parseGroqResponse(text: string): { action: DispatchAction; reason: string } {
const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
function parseGroqResponse(text: string): { action: DispatchAction; reason: string; prompt?: string } {
const lines = text.split("\n");
let action: DispatchAction = "queue";
let reason = "Continuing with queue order.";
let promptBody: string | undefined;
// Collecting the PROMPT: body across multiple lines (it can be a paragraph).
let inPrompt = false;
const promptLines: string[] = [];
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line && !inPrompt) continue;
for (const line of lines) {
const upper = line.toUpperCase();
if (upper.startsWith("ACTION:")) {
const val = upper.replace("ACTION:", "").trim();
action = val === "NEXTBEST" ? "nextbest" : "queue";
if (val === "NEXTBEST") action = "nextbest";
else if (val === "COMPOSED") action = "composed";
else action = "queue";
inPrompt = false;
continue;
}
if (line.toLowerCase().startsWith("reason:")) {
reason = line.slice("reason:".length).trim();
inPrompt = false;
continue;
}
if (line.toLowerCase().startsWith("prompt:")) {
promptLines.push(line.slice("prompt:".length).trim());
inPrompt = true;
continue;
}
if (inPrompt) {
// Continuation of multi-line PROMPT body.
promptLines.push(rawLine);
}
}
return { action, reason };
if (promptLines.length > 0) {
promptBody = promptLines.join("\n").trim();
}
// Sanity: if Groq said COMPOSED but didn't actually emit a body, downgrade
// to NEXTBEST so the caller doesn't dispatch an empty custom prompt.
if (action === "composed" && (!promptBody || promptBody.length < 10)) {
action = "nextbest";
promptBody = undefined;
}
return { action, reason, prompt: promptBody };
}
// ── Route handler ──────────────────────────────────────────────────────────
@@ -160,15 +204,49 @@ export async function POST(req: NextRequest) {
const streak = streakLine(recentOutcomes);
const streakSuffix = streak ? ` [last 5: ${streak}]` : "";
// No queue items — trivially run next_best.
if (queue.length === 0) {
// Per-user auto-inject mode (added 2026-05-20). Gates the strategist
// behavior before any expensive work:
// strategist → current default; queue → composed → next_best fallback
// queue_only → only fire when there's a queue item; else off
// next_best → legacy: skip Groq, fire canned template
// off → auto-inject disabled entirely; user dispatches by hand
const settings = await getBeaconSettings(userId).catch(() => null);
const mode = settings?.auto_inject_mode ?? "strategist";
if (mode === "off") {
return NextResponse.json({
action: "nextbest",
reason: `Queue is empty — running AI-driven next step.${streakSuffix}`,
source: "empty_queue",
action: "off",
reason: "Auto-inject is disabled in your beacon settings.",
source: "mode_gate",
} 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.
// No queue items + strategist mode: still call Groq to compose from
// handoff + commits + outcomes. The strategist's value is highest
// exactly when the queue is empty and the user wants a smart nudge.
// (Previously this short-circuited to nextbest, which was the bug
// Cursor's audit named.)
// Hard health gate (duplicate of client-side check — defence in depth).
const health = handoff.health.toLowerCase();
const tests = handoff.tests.toLowerCase();
@@ -180,15 +258,17 @@ export async function POST(req: NextRequest) {
} satisfies DispatchResult);
}
// Groq classification.
// Groq composition. Even with an empty queue, the strategist composes
// from session next, recent commits, and outcome streak.
const prompt = buildPrompt(handoff, queue, projectName, gitBranch, recentCommits, recentOutcomes);
try {
const { action, reason } = await callGroq(prompt);
const { action, reason, prompt: composedPrompt } = await callGroq(prompt);
return NextResponse.json({
action,
reason: `${reason}${streakSuffix}`,
source: "groq",
...(composedPrompt ? { prompt: composedPrompt } : {}),
} satisfies DispatchResult);
} catch (e) {
// Groq unavailable, key invalid, or timeout — surface the actual cause so
+14 -1
View File
@@ -96,10 +96,23 @@ export async function POST(req: NextRequest) {
if (isRuntimeAvailable()) {
try {
const states = await getProjectStatesByUserId(userId);
// Defensive against duplicate rows that share the same lowercase
// project_key (e.g. 'cockpit' vs 'Cockpit' — caught on 2026-05-20
// because the iteration order let an empty-queue dup overwrite the
// real queue's mirror file). Group by lowercase key and pick the
// row with the longest prompt_queue; ties keep first-seen.
const byKey = new Map<string, typeof states[number]>();
for (const s of states) {
if (!s.projectKey) continue;
const k = s.projectKey.toLowerCase();
const cur = byKey.get(k);
const sLen = s.promptQueue?.length ?? 0;
const curLen = cur?.promptQueue?.length ?? 0;
if (!cur || sLen > curLen) byKey.set(k, s);
}
for (const [k, s] of byKey) {
try {
const p = stateFile.queue(s.projectKey.toLowerCase());
const p = stateFile.queue(k);
fs.writeFileSync(p + ".tmp", JSON.stringify(s.promptQueue ?? []));
fs.renameSync(p + ".tmp", p);
} catch { /* per-file failure is non-fatal */ }
+4 -1
View File
@@ -57,7 +57,10 @@ export function BeaconSettings() {
transcription_provider: provider,
});
if (!res.ok) await throwApiError(res, "Failed to save");
setData({ popup_mode: popupMode, countdown_seconds: countdown, min_idle_seconds: minIdle, whisper_model: model, transcription_provider: provider });
// Preserve auto_inject_mode through saves until this component grows a
// UI for it; without the carryover the new field reverts to default
// on every patch.
setData({ popup_mode: popupMode, countdown_seconds: countdown, min_idle_seconds: minIdle, whisper_model: model, transcription_provider: provider, auto_inject_mode: data?.auto_inject_mode ?? "strategist" });
setSaved(true);
} catch (e) {
setError(e instanceof Error ? e.message : "Something went wrong");
+11
View File
@@ -7,12 +7,15 @@ import {
DEFAULT_POPUP_MODE,
} from "@/lib/constants/control";
export type AutoInjectMode = "strategist" | "queue_only" | "next_best" | "off";
export type BeaconSettingsData = {
popup_mode: string;
countdown_seconds: number;
min_idle_seconds: number;
whisper_model: string;
transcription_provider: string;
auto_inject_mode: AutoInjectMode;
};
const DEFAULTS: BeaconSettingsData = {
@@ -21,8 +24,13 @@ const DEFAULTS: BeaconSettingsData = {
min_idle_seconds: DEFAULT_BEACON_MIN_IDLE_S,
whisper_model: "base",
transcription_provider: "auto",
auto_inject_mode: "strategist",
};
function coerceAutoInjectMode(v: string | null | undefined): AutoInjectMode {
return v === "queue_only" || v === "next_best" || v === "off" ? v : "strategist";
}
/** PyQt mode was retired (see scripts/beacon.py). Legacy DB rows with 'both' or
* 'pyqt' are coerced to 'web' on read so the UI never offers a dead option. */
function coercePopupMode(stored: string): string {
@@ -44,6 +52,7 @@ export async function getBeaconSettings(userId: string): Promise<BeaconSettingsD
min_idle_seconds: rows[0].minIdleSeconds,
whisper_model: rows[0].whisperModel,
transcription_provider: rows[0].transcriptionProvider,
auto_inject_mode: coerceAutoInjectMode(rows[0].autoInjectMode),
};
}
@@ -63,6 +72,7 @@ export async function upsertBeaconSettings(
minIdleSeconds: merged.min_idle_seconds,
whisperModel: merged.whisper_model,
transcriptionProvider: merged.transcription_provider,
autoInjectMode: merged.auto_inject_mode,
})
.onConflictDoUpdate({
target: beaconSettings.userId,
@@ -72,6 +82,7 @@ export async function upsertBeaconSettings(
minIdleSeconds: merged.min_idle_seconds,
whisperModel: merged.whisper_model,
transcriptionProvider: merged.transcription_provider,
autoInjectMode: merged.auto_inject_mode,
updatedAt: new Date(),
},
});
+3
View File
@@ -9,6 +9,9 @@ export const beaconSettings = pgTable("beacon_settings", {
minIdleSeconds: integer("min_idle_seconds").notNull().default(0),
whisperModel: text("whisper_model").notNull().default("base"),
transcriptionProvider: text("transcription_provider").notNull().default("auto"),
// strategist | queue_only | next_best | off — drives handleAutoInject's
// behavior. Defaults to strategist (Groq composes context-aware prompts).
autoInjectMode: text("auto_inject_mode").notNull().default("strategist"),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
}, (t) => [
index("idx_beacon_settings_user_id").on(t.userId),
+20 -1
View File
@@ -41,8 +41,12 @@ export function useProjectCardActions({
const [preloadedDispatch, setPreloadedDispatch] = useState<DispatchResult | null>(null);
// Pre-fetch dispatch decision as soon as the ready banner appears.
// Note 2026-05-20: previously gated on queue.length > 0, which short-
// circuited the strategist for the most-valuable case (empty queue,
// smart-nudge needed). Now fires whenever ready — server decides what
// to do based on auto_inject_mode + queue + handoff.
useEffect(() => {
if (!isReadyNow || queue.length === 0) {
if (!isReadyNow) {
setPreloadedDispatch(null);
return;
}
@@ -162,6 +166,8 @@ export function useProjectCardActions({
}
const decision = preloadedDispatch;
const action = decision?.action ?? (queue.length > 0 ? "queue" : "nextbest");
// mode_gate may have returned "off" — suppress auto-inject entirely.
if (action === "off") return;
if (action === "queue") {
const queued = shiftQueue();
if (queued) {
@@ -172,6 +178,19 @@ export function useProjectCardActions({
return;
}
}
// Strategist v1: when /api/control/dispatch composed a context-aware
// body, inject that directly as a custom prompt instead of falling
// back to the canned next_best template. Closes the "auto-inject is
// generic and unrelated to what I last asked for" gap. The composed
// body is constructed from session handoff, queue tail, recent
// commits, and outcome streak by Groq — see /api/control/dispatch.
if (action === "composed" && decision?.prompt && decision.prompt.length > 10) {
setSending("custom");
setDismissed(true);
try { await onInject(project.tab, undefined, decision.prompt); }
finally { setSending(null); }
return;
}
await sendIntent("next_best");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [preloadedDispatch, shiftQueue, queue.length, project.tab, onInject, setDismissed, project.session?.status, project.session?.health, project.session?.tests]);
+13 -6
View File
@@ -26,14 +26,21 @@ function renderSharedExecutionRules(): string {
function renderIntentBody(request: OrchestrationTaskRequest): string {
switch (request.intent) {
case "next_best":
// SSOT'd 2026-05-20 against ~/.config/agent-prompts.json (bash hook's
// slot 1). The bash hook's version was sharper — concrete gates first,
// then session-handoff awareness, then "find the adjacent broken
// thing." The previous TS text was an abstract scan ladder that
// produced drift. Model-agnostic shape: no assumed tech stack.
return [
`Work on the project at ${request.projectPath}.`,
"Before choosing work, scan in order:",
"1. interrupted or uncommitted work to resume",
"2. failing tests or broken flows",
"3. SSOT / DRY / quality violations",
"4. mission or product misalignment",
"Pick the highest-impact item and execute it fully.",
"",
"Verify health first:",
"1. Are there type/lint/compile errors? Fix them before anything else.",
"2. Is there uncommitted or merge-conflicted work? Resolve and commit.",
"3. Does the session handoff's `next:` field name a specific task? Execute it exactly.",
"4. If `next:` is vague or missing, find the single most impactful gap: scan recent commits for what was just built and look for the adjacent broken thing — a silent error, a flow that doesn't close, a feature half-wired.",
"",
"One thing. Done and committed.",
].join("\n");
case "test_and_fix":
return [