mirror of
https://github.com/koala73/worldmonitor.git
synced 2026-04-25 17:14:57 +02:00
* feat(notifications): AI-enriched digest delivery (Phase 1) Add personalized LLM-generated executive summaries to digest notifications. When AI_DIGEST_ENABLED=1 (default), the digest cron fetches user preferences (watchlist, panels, frameworks), generates a tailored intelligence brief via Groq/OpenRouter, and prepends it to the story list in both text and HTML formats. New infrastructure: - convex/userPreferences: internalQuery for service-to-service access - convex/http: /relay/user-preferences endpoint (RELAY_SHARED_SECRET auth) - scripts/lib/llm-chain.cjs: shared Ollama->Groq->OpenRouter provider chain - scripts/lib/user-context.cjs: user preference extraction + LLM prompt formatting AI summary is cached (1h TTL) per stories+userContext hash. Falls back to raw digest on LLM failure (no regression). Subject line changes to "Intelligence Brief" when AI summary is present. * feat(notifications): per-user AI digest opt-out toggle AI executive summary in digests is now optional per user via alertRules.aiDigestEnabled (default true). Users can toggle it off in Settings > Notifications > Digest > "AI executive summary". Schema: added aiDigestEnabled to alertRules table Backend: Convex mutations, HTTP relay, edge function all forward the field Frontend: toggle in digest settings section with descriptive copy Digest cron: skips LLM call when rule.aiDigestEnabled === false * fix(notifications): address PR review — cache key, HTML replacement, UA 1. Add variant to AI summary cache key to prevent cross-variant poisoning 2. Use replacer function in html.replace() to avoid $-pattern corruption from LLM output containing dollar amounts ($500M, $1T) 3. Use service UA (worldmonitor-llm/1.0) instead of Chrome UA for LLM calls * fix(notifications): skip AI summary without prefs + fix HTML regex 1. Return null from generateAISummary() when fetchUserPreferences() returns null, so users without saved preferences get raw digest instead of a generic LLM summary 2. Fix HTML replace regex to match actual padding value (40px 32px 0) so the executive summary block is inserted in email HTML * fix(notifications): channel check before LLM, omission-safe aiDigest, richer cache key 1. Move channel fetch + deliverability check BEFORE AI summary generation so users with no verified channels don't burn LLM calls every cron run 2. Only patch aiDigestEnabled when explicitly provided (not undefined), preventing stale frontend tabs from silently clearing an opt-out 3. Include severity, phase, and sources in story hash for cache key so the summary invalidates when those fields change
84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import { ConvexError, v } from "convex/values";
|
|
import { internalQuery, mutation, query } from "./_generated/server";
|
|
import { CURRENT_PREFS_SCHEMA_VERSION, MAX_PREFS_BLOB_SIZE } from "./constants";
|
|
|
|
export const getPreferencesByUserId = internalQuery({
|
|
args: { userId: v.string(), variant: v.string() },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("userPreferences")
|
|
.withIndex("by_user_variant", (q) =>
|
|
q.eq("userId", args.userId).eq("variant", args.variant),
|
|
)
|
|
.unique();
|
|
},
|
|
});
|
|
|
|
export const getPreferences = query({
|
|
args: { variant: v.string() },
|
|
handler: async (ctx, args) => {
|
|
const identity = await ctx.auth.getUserIdentity();
|
|
if (!identity) return null;
|
|
const userId = identity.subject;
|
|
return await ctx.db
|
|
.query("userPreferences")
|
|
.withIndex("by_user_variant", (q) =>
|
|
q.eq("userId", userId).eq("variant", args.variant),
|
|
)
|
|
.unique();
|
|
},
|
|
});
|
|
|
|
export const setPreferences = mutation({
|
|
args: {
|
|
variant: v.string(),
|
|
data: v.any(),
|
|
expectedSyncVersion: v.number(),
|
|
schemaVersion: v.optional(v.number()),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const identity = await ctx.auth.getUserIdentity();
|
|
if (!identity) throw new ConvexError("UNAUTHENTICATED");
|
|
const userId = identity.subject;
|
|
|
|
const blobSize = JSON.stringify(args.data).length;
|
|
if (blobSize > MAX_PREFS_BLOB_SIZE) {
|
|
throw new ConvexError(`BLOB_TOO_LARGE: ${blobSize} > ${MAX_PREFS_BLOB_SIZE}`);
|
|
}
|
|
|
|
const existing = await ctx.db
|
|
.query("userPreferences")
|
|
.withIndex("by_user_variant", (q) =>
|
|
q.eq("userId", userId).eq("variant", args.variant),
|
|
)
|
|
.unique();
|
|
|
|
if (existing && existing.syncVersion !== args.expectedSyncVersion) {
|
|
throw new ConvexError("CONFLICT");
|
|
}
|
|
|
|
const nextSyncVersion = (existing?.syncVersion ?? 0) + 1;
|
|
const schemaVersion = args.schemaVersion ?? CURRENT_PREFS_SCHEMA_VERSION;
|
|
|
|
if (existing) {
|
|
await ctx.db.patch(existing._id, {
|
|
data: args.data,
|
|
schemaVersion,
|
|
updatedAt: Date.now(),
|
|
syncVersion: nextSyncVersion,
|
|
});
|
|
} else {
|
|
await ctx.db.insert("userPreferences", {
|
|
userId,
|
|
variant: args.variant,
|
|
data: args.data,
|
|
schemaVersion,
|
|
updatedAt: Date.now(),
|
|
syncVersion: nextSyncVersion,
|
|
});
|
|
}
|
|
|
|
return { syncVersion: nextSyncVersion };
|
|
},
|
|
});
|