feat(telemetry): debug_logs schema + /api/inject failure capture

Per pattern_vercel_log_fallback (memory): journalctl on Vercel is unreliable
for post-incident forensics. The debug_logs table already existed in Neon
(raw-SQL writes from src/auth.ts) but had no Drizzle model and no typed
helper, so other call sites couldn't ergonomically write to it.

Add the missing layer:

- src/db/schema/debug-logs.ts: Drizzle model that matches the live shape
  exactly — column meta (not context), no user_id (the existing auth
  writes don't use it; adding it would require a destructive schema change).
- src/db/queries/debug-logs.ts: logDebug() fire-and-forget helper that
  swallows insert failures (telemetry can never break the operation it
  observes) and a getRecentDebugLogs reader for a future admin view.
- src/app/api/inject/route.ts: logDebug calls on both failure paths
  (unknown-tab → warn, executeInject !ok → error). Meta includes userId,
  tab, mode, adapter, promptKey, promptLabel, customPromptLen, and
  runtimeAvailable so the next incident has full context without needing
  Vercel logs.

Schema push was blocked by drizzle-kit interactive-only column-conflict
prompts on unrelated existing tables — used CREATE TABLE IF NOT EXISTS via
postgres-js to verify the table shape on Neon, then aligned the Drizzle
model to the existing columns. No destructive migration needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-21 01:08:40 +02:00
1 parent 9c2525ca8b
commit 99fca8201d
4 files changed
+80

No files matched your search

+26
View File
@@ -9,6 +9,7 @@ import { executeInject } from "@/lib/executor";
import { createOrchestrationEvent } from "@/db/queries/orchestration-events";
import { insertPromptHistory } from "@/db/queries/prompt-history";
import { upsertProjectState } from "@/db/queries/project-states";
import { logDebug } from "@/db/queries/debug-logs";
const InjectBody = z.object({
tab: z.string().min(1).max(80),
@@ -35,6 +36,12 @@ export async function POST(req: NextRequest) {
dbProjects.find((p) => p.name.toLowerCase() === tab.toLowerCase()) ??
dbTeamProjects.find((p) => p.name.toLowerCase() === tab.toLowerCase());
if (!dbMatch) {
logDebug({
source: "api/inject",
level: "warn",
message: `Unknown tab: ${tab}`,
meta: { userId, tab, hasPromptKey: !!promptKey, hasCustomPrompt: !!customPrompt },
});
return NextResponse.json({ error: `Unknown tab: ${tab}` }, { status: 404 });
}
@@ -161,6 +168,25 @@ export async function POST(req: NextRequest) {
);
if (!result.ok) {
// Per pattern_vercel_log_fallback: journalctl on Vercel is unreliable.
// Capture failures in debug_logs so post-incident forensics can answer
// "what actually broke" without depending on log retention.
logDebug({
source: "api/inject",
level: "error",
message: `Injection failed: ${result.error}`,
meta: {
userId,
tab: effectiveTab,
canonical,
mode: result.mode,
adapter: eventAdapter,
promptKey: promptKey ?? null,
promptLabel,
customPromptLen: customPrompt?.length ?? 0,
runtimeAvailable: isRuntimeAvailable(),
},
});
return NextResponse.json({ error: `Injection failed: ${result.error}` }, { status: 500 });
}
+20
View File
@@ -0,0 +1,20 @@
import { db } from "@/db";
import { debugLogs, type NewDebugLog } from "@/db/schema/debug-logs";
import { desc } from "drizzle-orm";
/**
* Fire-and-forget logger. Never throws — a telemetry failure must not break
* the user-facing operation it was observing. Returns the insert promise so
* tests can await it, but callers should NOT await this in request handlers.
*/
export function logDebug(entry: Omit<NewDebugLog, "id" | "createdAt">): Promise<unknown> {
return db.insert(debugLogs).values(entry).catch((err) => {
// Telemetry failed — log to stderr as the absolute last resort.
console.error("[debug-logs] insert failed:", err, "for entry:", { source: entry.source, level: entry.level, message: entry.message });
});
}
/** Most-recent N debug log entries, newest first. UI helper for a future admin view. */
export async function getRecentDebugLogs(limit = 50) {
return db.select().from(debugLogs).orderBy(desc(debugLogs.createdAt)).limit(limit);
}
+33
View File
@@ -0,0 +1,33 @@
import { pgTable, uuid, text, timestamp, jsonb, index } from "drizzle-orm/pg-core";
/**
* Server-side telemetry for failures that don't fit dedicated tables.
* failed_commands captures pending_commands errors; debug_logs is the
* catch-all for everything else (/api/inject 5xx, auth resolution failures,
* upstream tool errors, anything where journalctl on Vercel isn't reliable
* enough for post-incident forensics).
*
* Table predates this schema file — created by raw SQL ahead of the Drizzle
* model. This file documents the existing shape so callers can use the typed
* insert helper in @/db/queries/debug-logs instead of raw SQL. Column names
* MUST match the live table: meta (not context), no user_id.
*
* Source: short stable string identifying the call site ("api/inject",
* "api/control/dispatch", "auth").
* Level: "error" | "warn" | "info" — UI filters by this.
* Meta: free-form JSONB — request body shape, error stack, runtime info.
*/
export const debugLogs = pgTable("debug_logs", {
id: uuid("id").primaryKey().defaultRandom(),
source: text("source").notNull(),
level: text("level").notNull(),
message: text("message").notNull(),
meta: jsonb("meta"),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
}, (table) => [
index("idx_debug_logs_created_at").on(table.createdAt),
index("idx_debug_logs_source").on(table.source),
]);
export type DebugLog = typeof debugLogs.$inferSelect;
export type NewDebugLog = typeof debugLogs.$inferInsert;
+1
View File
@@ -26,3 +26,4 @@ export * from "./captures";
export * from "./habit-goals";
export * from "./beacon-settings";
export * from "./user-preferences";
export * from "./debug-logs";