diff --git a/package.json b/package.json index 112698c60..45c0c0f70 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "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", + "generate:agent-prompts": "npx tsx scripts/generate-agent-prompts.ts", "db:dump": "bash scripts/db/dump.sh", "db:restore": "bash scripts/db/restore.sh", "db:oracle-bootstrap": "bash scripts/db/oracle-bootstrap.sh", diff --git a/scripts/generate-agent-prompts.ts b/scripts/generate-agent-prompts.ts new file mode 100644 index 000000000..ae906c364 --- /dev/null +++ b/scripts/generate-agent-prompts.ts @@ -0,0 +1,104 @@ +/** + * Generate ~/.config/agent-prompts.json from src/config/prompt-library.ts. + * + * The daemon (scripts/agent-hook-bridge.sh and friends) reads the JSON file + * directly from disk via `get_prompt`. The TS PROMPT_TEMPLATES file is the + * SSOT — this script is the build bridge that keeps the daemon working + * while we incrementally migrate prompts out of legacy JSON. + * + * Behavior: + * - Reads existing JSON (if present) — entries NOT covered by TS agentKey + * are preserved verbatim. This means legacy prompts that haven't been + * migrated to TS yet still work; the daemon doesn't lose them. + * - TS entries with agentKey set are transformed to AgentPrompt shape and + * either added or replace the matching JSON entry. + * - Writes the merged set back to ~/.config/agent-prompts.json with a + * stable key order so diffs are reviewable. + * + * Run: npm run generate:agent-prompts + * (or: npx tsx scripts/generate-agent-prompts.ts) + * + * The user should re-run this whenever they edit prompt-library.ts entries + * with agentKey set. Future: hook into next.config build step or a pre-push + * husky hook so it's automatic. + */ +import { readFileSync, writeFileSync, existsSync } from "fs"; +import { join } from "path"; +import { homedir } from "os"; +import { PROMPT_TEMPLATES } from "../src/config/prompt-library"; + +type AgentPrompt = { + key: string; + slot: number | null; + icon: string; + label: string; + style: string; + category: string; + dimensionId: string | null; + prompt: string; + sendNow?: boolean; +}; + +const JSON_PATH = process.env.AGENT_PROMPTS_FILE ?? join(homedir(), ".config", "agent-prompts.json"); + +function loadExisting(): AgentPrompt[] { + if (!existsSync(JSON_PATH)) return []; + try { + return JSON.parse(readFileSync(JSON_PATH, "utf-8")); + } catch (e) { + console.error(`[generate-agent-prompts] failed to parse ${JSON_PATH}:`, e); + return []; + } +} + +function transformTsEntry(t: typeof PROMPT_TEMPLATES[number]): AgentPrompt | null { + if (!t.agentKey) return null; + return { + key: t.agentKey, + slot: t.slot ?? null, + icon: t.icon ?? "•", + label: t.name, + style: t.style ?? "dimension", + category: t.category, + dimensionId: t.dimensionId ?? null, + prompt: t.template, + ...(t.sendNow !== undefined ? { sendNow: t.sendNow } : {}), + }; +} + +function main(): void { + const existing = loadExisting(); + const tsTransformed = PROMPT_TEMPLATES + .map(transformTsEntry) + .filter((p): p is AgentPrompt => p !== null); + + const byKey = new Map(); + for (const p of existing) byKey.set(p.key, p); + for (const p of tsTransformed) byKey.set(p.key, p); // TS wins on conflict + + // Sort by slot (defined first), then alphabetically by key. Makes the + // diff readable when a single prompt changes. + const merged = [...byKey.values()].sort((a, b) => { + const sa = a.slot ?? 999; + const sb = b.slot ?? 999; + if (sa !== sb) return sa - sb; + return a.key.localeCompare(b.key); + }); + + const before = existing.length; + const after = merged.length; + const overridden = tsTransformed.filter((t) => existing.some((e) => e.key === t.key)).length; + const added = tsTransformed.length - overridden; + const untouched = existing.filter((e) => !tsTransformed.some((t) => t.key === e.key)).length; + + writeFileSync(JSON_PATH, JSON.stringify(merged, null, 2) + "\n", "utf-8"); + + console.log(`[generate-agent-prompts] wrote ${after} entries to ${JSON_PATH}`); + console.log(` before: ${before} JSON entries`); + console.log(` TS entries with agentKey: ${tsTransformed.length}`); + console.log(` ↳ overrode existing JSON: ${overridden}`); + console.log(` ↳ newly added: ${added}`); + console.log(` legacy JSON entries preserved: ${untouched}`); +} + +main(); diff --git a/src/app/api/prompts/agent/route.ts b/src/app/api/prompts/agent/route.ts index cebcd386b..0e93e2dda 100644 --- a/src/app/api/prompts/agent/route.ts +++ b/src/app/api/prompts/agent/route.ts @@ -2,6 +2,7 @@ import { NextResponse } from "next/server"; import { readFileSync } from "fs"; import { PROMPTS_FILE } from "@/lib/agent-config"; import { getSessionUserId } from "@/lib/session"; +import { PROMPT_TEMPLATES } from "@/config/prompt-library"; // readFileSync has no Next.js dynamic signal — force dynamic so middleware runs. export const dynamic = "force-dynamic"; @@ -11,23 +12,61 @@ export type AgentPrompt = { slot: number | null; icon: string; label: string; - style: "primary" | "action" | "more" | "dimension" | "internal"; + style: "primary" | "action" | "more" | "dimension" | "internal" | "danger"; category: string; dimensionId: string | null; prompt: string; + /** True when the consumer should fire the prompt immediately on click; + * false (default) means click should fill the composer textarea so the + * user can preview/edit before sending. Per the unified UX shipped + * 2026-05-31; before that, every entry point made its own per-component + * decision and same prompt could send-or-fill depending on the surface. */ + sendNow?: boolean; }; +/** Merges the legacy JSON prompt file with the TS PROMPT_TEMPLATES library + * into the AgentPrompt shape consumed by DimensionSection. TS entries that + * set `agentKey` win on conflict — letting the TS file gradually replace + * the JSON without breaking the daemon, which still reads from JSON. + * Once all daemon consumers migrate to this API, the JSON file becomes + * pure build artifact (generated by scripts/generate-agent-prompts.ts). */ +function mergePromptSources(): AgentPrompt[] { + let jsonPrompts: AgentPrompt[] = []; + try { + const raw = readFileSync(PROMPTS_FILE(), "utf-8"); + jsonPrompts = JSON.parse(raw); + } catch { + // JSON file missing is fine — TS source is the SSOT + } + + // TS templates with agentKey set become AgentPrompt entries. + const tsPrompts: AgentPrompt[] = PROMPT_TEMPLATES + .filter((t) => t.agentKey) + .map((t) => ({ + key: t.agentKey!, + slot: t.slot ?? null, + icon: t.icon ?? "•", + label: t.name, + style: (t.style ?? "dimension") as AgentPrompt["style"], + category: t.category, + dimensionId: t.dimensionId ?? null, + prompt: t.template, + sendNow: t.sendNow ?? false, + })); + + // TS wins on key conflict — this is how the SSOT migration happens + // incrementally without breaking the daemon's JSON consumers. + const byKey = new Map(); + for (const p of jsonPrompts) byKey.set(p.key, p); + for (const p of tsPrompts) byKey.set(p.key, p); + return [...byKey.values()]; +} + export async function GET() { const userId = await getSessionUserId(); if (!userId) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } - try { - const raw = readFileSync(PROMPTS_FILE(), "utf-8"); - const prompts: AgentPrompt[] = JSON.parse(raw); - return NextResponse.json(prompts); - } catch { - return NextResponse.json([], { status: 200 }); - } + return NextResponse.json(mergePromptSources()); } diff --git a/src/config/prompt-library.ts b/src/config/prompt-library.ts index 50de486e9..b2321e02e 100644 --- a/src/config/prompt-library.ts +++ b/src/config/prompt-library.ts @@ -1,8 +1,26 @@ /** - * Prompt Library — SSOT for all prompt templates. - * Categories: fleet → security → engineering → frontend → backend → database → devops → design → business → marketing → research → personal - * scope: "global" = runs across all projects, "project" = runs against one project - * suggestedSchedule: cron expression if this makes sense as a recurring job + * Prompt Library — SSOT for all prompt template metadata. + * + * Single source of truth for: what prompts exist, their names/descriptions/ + * categories, and how they surface in the UI (style, slot, icon, sendNow). + * + * For prompts that ALSO need to be dispatchable by the autopilot daemon + * (the ones the agent-hook-bridge.sh script reads to know what to inject), + * set `agentKey` to the snake_case identifier the daemon expects. The + * template body lives both here AND in ~/.config/agent-prompts.json — that + * JSON file is now a build artifact, generated from this TS source via + * `npm run generate:agent-prompts`. Edit ONLY this file when adding/changing + * a prompt; never hand-edit the JSON. + * + * Categories: fleet → security → engineering → frontend → backend → database + * → devops → design → business → marketing → research → personal + * → control (autopilot/loop primitives) → content (copy/docs) + * scope: "global" = runs across all projects, "project" = runs against one + * style: "primary" | "action" | "more" | "dimension" | "internal" | "danger" + * — drives CTA prominence in the IntentPanel and DimensionSection + * sendNow: if true, clicking the prompt SENDS immediately (no preview). + * Default false — clicks fill the textarea so users can edit first. + * Per the unified prompt-UX rule shipped 2026-05-31. */ import { APP_NAME } from "./brand"; @@ -19,10 +37,14 @@ export type PromptCategory = | "business" | "marketing" | "research" - | "personal"; + | "personal" + | "control" + | "content"; type PromptScope = "global" | "project"; +export type PromptStyle = "primary" | "action" | "more" | "dimension" | "internal" | "danger"; + export type PromptTemplate = { id: string; name: string; @@ -33,6 +55,20 @@ export type PromptTemplate = { suggestedSchedule?: string; // cron expr, e.g. "0 9 * * 1" tags?: string[]; featured?: boolean; // show in Quick Access row + /** Snake_case key the daemon dispatches by. When set, this prompt is also + * exposed via /api/prompts/agent and the autopilot can fire it. */ + agentKey?: string; + /** Emoji shown in chips and DimensionSection rows. */ + icon?: string; + /** CTA prominence in IntentPanel + DimensionSection. */ + style?: PromptStyle; + /** Keyboard shortcut slot (1-14) for beacon popup. */ + slot?: number; + /** Grouping in DimensionSection — independent of category for back-compat + * with the legacy JSON taxonomy. */ + dimensionId?: string; + /** If true: click sends immediately. Default false: click fills textarea. */ + sendNow?: boolean; }; export const CATEGORY_META: Record = { @@ -48,6 +84,8 @@ export const CATEGORY_META: Record.blockers/pending/$(date -u +%Y%m%d-%H%M%S)-.md with this structure: + +# + +**Blocking:** +**Why the agent cannot do it:** + +## What the user needs to do + + +## How the agent will know it is resolved + + +After writing the file, do NOT pick a task this iteration. Update

.md with status: blocked and next: empty (the blocker file IS the next step). Tell the user one sentence: "Raised blocker: . See ~/.claude/sessions/<P>.blockers/pending/<filename>." + +Next loop iteration: next_best Setup detects the file, Rule 0 surfaces it, and on user confirmation the agent moves the file from pending/ to applied/.`, + agentKey: "blocker_create", + icon: "🚧", + style: "danger", + dimensionId: "control", + tags: ["control", "blocker"], + }, + { + id: "orient", + name: "Orient", + description: "Re-read project state from scratch — git log, roadmap, session handoff, recent failures — and report current reality.", + category: "control", + scope: "global", + template: `Re-establish ground truth before doing anything. Run: + git log --oneline -10 + git status + git stash list + cat ~/.claude/sessions/<P>.roadmap.md | head -50 + cat ~/.claude/sessions/<P>.md + ls ~/.claude/sessions/<P>.blockers/pending/ 2>/dev/null + +Then in 5 bullets tell me: +- What shipped in the last 24h +- What is uncommitted/stashed +- What the roadmap says the highest priority is +- Any pending blocker +- One concrete next step you'd take`, + agentKey: "orient", + icon: "🧭", + style: "more", + dimensionId: "control", + tags: ["control", "orientation"], + }, + { + id: "unblock", + name: "Unblock", + description: "Agent is stuck — diagnose what's preventing progress and propose two paths forward.", + category: "control", + scope: "global", + template: `You appear stuck. Diagnose: +1. What was the last thing you tried, and what was its concrete failure mode? (Quote the error or output.) +2. What assumption are you making that might be wrong? (Name it explicitly.) +3. What is the simplest test that would falsify that assumption? +4. Propose TWO different paths forward — not variants of the same approach. Describe what makes each one risky. + +Do not implement either path yet. Hand off to the user with these four answers so they can pick.`, + agentKey: "unblock", + icon: "🔓", + style: "more", + dimensionId: "control", + tags: ["control", "diagnosis"], + }, + { + id: "roadmap-check", + name: "Roadmap check", + description: "Audit ~/.claude/sessions/<P>.roadmap.md for stale entries, duplicates, completed items still marked open.", + category: "control", + scope: "global", + template: `Read ~/.claude/sessions/<P>.roadmap.md end-to-end. For every T0/T1/T2 entry, verify against git log + current code state: +- Is it actually still open? (If it was shipped, mark DONE with the commit hash.) +- Is it a duplicate of another entry? (Collapse.) +- Does it have a clear next-step verb, or is it vague aspirational text? (Reword or delete.) + +Report a punch list of stale/duplicate/vague entries you'd fix. Don't fix yet — surface for the user first.`, + agentKey: "roadmap_check", + icon: "🗺️", + style: "more", + dimensionId: "control", + tags: ["control", "roadmap"], + }, + { + id: "onboarding-audit", + name: "Onboarding audit", + description: "Walk the new-user signup-to-first-action flow as if you were a stranger and document every friction point.", + category: "control", + scope: "global", + template: `Walk through the new-user signup-to-first-action flow as if you were a stranger: +1. Landing page → /sign-up +2. Email/password OR OAuth +3. Email verification +4. /onboarding (username, first project, connect-machine instructions) +5. /today landing experience + +For each step, name (a) what is unclear, (b) what is missing, (c) what is broken, (d) what would make you bounce. Use browser tools (mcp__claude-in-chrome) to actually click through if possible. Don't fix anything — produce a punch list ordered by drop-off severity.`, + agentKey: "onboarding", + icon: "🚪", + style: "more", + dimensionId: "control", + tags: ["control", "onboarding"], + }, ]; export const ALL_CATEGORIES = Object.keys(CATEGORY_META) as PromptCategory[];