Prompt Library Architecture & Recommendation Engine
Prompt data model, 8 deliverable families (A-H), 10 target platforms, 60-second isolate cache with generation invalidation, ring-queue recommendations, and slot replacement state machine.
The Prompt Library (/prompts and /<locale>/prompts/<slug>) is rendered at the edge via TanStack Start SSR inside the Cloudflare Worker (server/src/promptLibrary.ts). Both the SSR renderer and public JSON endpoints (/api/prompts) share the exact same PromptReader implementation.
1. Prompt Data Model (prompts Table & PromptInput)
Each prompt preset is stored in PostgreSQL (prompts table) and validated by parsePromptInput() (server/src/promptLibrary.ts):
| Field | Type & Constraints | Purpose |
|---|---|---|
slug | string (<= 120 chars, /^[a-z0-9]+(?:-[a-z0-9]+)*$/) | Immutable URL identifier once published (SLUG_LOCKED). |
output | "image" | "video" (default "image") | Determines whether "Generate Same Style" routes to the image or video workbench and which model registry validates model. |
model | string | Validated against imageModels.getModel() when output === "image", or videoModels.getModel() when output === "video". |
use | PROMPT_USES ("poster", "commerce", "portrait", "character", "illustration") | Primary use-case filter tag. |
family | PROMPT_FAMILIES | null | Deliverable family (A–H, see Section 2). Also provides fallback cover /assets/family-<id>.webp. |
style | PROMPT_STYLES | null ("cyberpunk", "ink", "product", "cute", "anime", "cinematic", "portrait", "flat", "watercolor") | Workbench style preset. |
ratio | PROMPT_RATIOS | null ("1:1", "4:5", "2:3", "3:2", "3:4", "9:16", "16:9", "3:1") | For output === "video", restricted to PROMPT_VIDEO_RATIOS ("16:9", "9:16", "1:1"). |
imageCount | int (1..8) or null | Must be null for video presets. |
duration | int (1..30) or null | Mandatory for output === "video" (and <= model.maxDuration); must be null for image presets. Video preset credits scale by ceil((model.credits5s * duration) / 5). |
needsReference | boolean | Whether the user must upload a reference photo before generating. |
platforms | PROMPT_PLATFORMS[] | null (max 8) | Target publishing platforms (see Section 2). |
season | PROMPT_SEASONS | null ("spring", "summer", "autumn", "winter", "holiday", "evergreen") | Fourth filter dimension on /prompts. Invalid/missing values coerce to null. |
slots | Array<{ key: string }> (max 6, /^[a-z][a-z0-9_]*$/) | Variable placeholders (e.g., `{product}`, `{headline}`) exposed as interactive inputs on the detail page. |
promptEn | string | null (<= 4000 chars) | Canonical English prompt text sent to the AI model (promptIsEnglish = record.promptEn != null). |
translations | Record<Locale, Translation> | Localized title (<= 120 chars, mandatory in at least en and zh-CN to publish), subtitle (<= 200), uploadHint (<= 200), caveat (<= 300), and disclosure (<= 300). |
imageUrl | string | null (isOwnImageUrl) | Only accepts self-hosted /uploads/YYYY/MM/prompt_<12hex>.(webp|png|jpg) or static /assets/(demo|family|preset)-<slug>.webp. External URLs are rejected. |
2. The 8 Deliverable Families (A–H) & 10 Platforms
8 Deliverable Families (PROMPT_FAMILIES)
Every overseas preset belongs to one of 8 deliverable families (server/src/promptLibrary.ts and frontend/site/content/prompt-families.ts):
| Family Code | family Slug | Deliverable Scope | Fallback Cover Asset |
|---|---|---|---|
| Family A | listing | E-commerce product listing shots (studio backgrounds, lifestyle scenes, detail callouts) | /assets/family-listing.webp |
| Family B | social | Social media feed & story posts (Instagram 4:5, Pinterest 2:3, TikTok 9:16) | /assets/family-social.webp |
| Family C | cover | Video thumbnails, podcast covers, newsletter headers (3:1), and blog hero banners | /assets/family-cover.webp |
| Family D | person | Professional headshots, creator portraits, and lookbooks (enforces reference upload & disclosure redlines) | /assets/family-person.webp |
| Family E | brand | Brand collateral, flyers (3:4 with A5 trim caveat), packaging mockups, and menu cards | /assets/family-brand.webp |
| Family F | edit | Reference-locked image editing (e.g., F-02 product-photo-pure-white auto-framed to 85% fill, F-04 virtual staging) | /assets/family-edit.webp |
| Family G | motion | E-commerce product motion clips and social video loops (output = "video", requires duration) | /assets/family-motion.webp |
| Family H | print | Print-on-demand (POD) graphics, digital downloads, stickers, and seamless patterns | /assets/family-print.webp |
10 Supported Platforms (PROMPT_PLATFORMS)
Stored as lowercase slugs (brand names are never translated):
amazon, etsy, shopify, instagram, tiktok, pinterest, youtube, linkedin, facebook, printful.
URL Filter Validation (hasUnknownPromptFilter)
On /prompts, known filter keys (use, family, platform, season) are strictly validated against their enum sets (ALLOWED_PROMPT_FILTERS). Any request with a known filter key but an unknown or empty value (e.g., ?family=nonexistent) returns HTTP 404 (not a 307 redirect) to prevent search engines from indexing infinite junk parameter URLs, while unknown tracking query parameters (such as utm_*) pass through.
3. 60-Second Isolate Cache & Generation Counter (createCachedPromptReader)
Prior to 2026-11-16, rendering a single uncached /prompts/<slug> page required two cross-region Neon PostgreSQL queries (findPublishedPromptBySlug + listPublishedPrompts for related presets), adding ~1.3s of DB latency (~0.6s per round-trip).
createCachedPromptReader(repo, { ttlMs: 60_000 }) eliminates both redundant queries:
- Single Full-Set Snapshot:
- Caches the complete
listPublishedPrompts()array in Worker isolate memory for60seconds (ttlMs = 60,000, aligned with the HTML edge cache window). - Both
list(locale)anddetail(locale, slug)derive their output from this single cached array (detailfinds the targetslugin memory and computespickRelated()from the same array—zero second DB query).
- Caches the complete
- In-Flight Promise Deduplication:
- Concurrent requests across 14 locales hitting a cold isolate share a single
inflightPromise so the database is queried only once. - Failed DB queries clear
inflightin.finally()and are never cached.
- Concurrent requests across 14 locales hitting a cold isolate share a single
- Generation Counter Invalidation (
generationvs.inflightGeneration):- Whenever an operator creates, edits, reorders, batch-updates, or changes the status of a prompt in
/admin, the admin route callsonPromptsChanged()->promptReader.invalidate(). invalidate()incrementsgeneration += 1, clearscached = null, and resetsinflight = null.- If an older DB query was already in flight when
invalidate()fired (startedAt !== generation), its.then()handler refuses to write the stale snapshot intocached, guaranteeing that admin edits are visible immediately on the next preview request.
- Whenever an operator creates, edits, reorders, batch-updates, or changes the status of a prompt in
4. Ring-Queue Related Prompt Recommendation (pickRelated)
Earlier versions selected related presets using [...sameUse, ...rest].slice(0, 3), which caused extreme link-equity skew: across 41 live pages (123 recommendation links), 6 head pages captured 82 inbound links while 23 pages received 0 inbound links (orphaned from internal recommendations).
pickRelated(rows, slug, limit = 3) (server/src/promptLibrary.ts) solves this with a deterministic Ring-Queue Algorithm:
- Canonical Topological Sort:
- Sorts all published prompts by:
rankOf(PROMPT_FAMILIES, row.family)(listing->social-> ... ->print->null)rankOf(PROMPT_USES, row.use)(poster->commerce-> ... ->illustration)- Lexicographical
row.slug(a.slug < b.slug)
- Sorts all published prompts by:
- Ring-Queue Traversal:
- Finds the current prompt's index
atin the sorted ringorder. - Selects the next
limit = 3items immediately followingatmoduloorder.length:const row = order[(at + step) % order.length]!;
- Finds the current prompt's index
- Mathematical & SEO Properties:
- Provably Uniform In-Degree: In a library of
Npublished prompts, every prompt recommends3neighbors and is recommended by the3predecessors behind it—guaranteeing exact in-degree =3and out-degree =3for every single prompt page with zero orphan pages. - High Topical Relevance: Because items are sorted by
(family, use, slug), adjacent items in the ring share the same deliverable family or use case (81 / 123live edges share family or use case).
- Provably Uniform In-Degree: In a library of
5. Variable Slot Replacement vs. Translation State Machine
On the prompt detail page, presets with slots (such as `{product}`, `{brand_color}`) allow users to type custom values in their native language while keeping the final prompt delivered to the image/video model in accurate English:
- Canonical English Base (
promptEn):- The prompt template is authored in English with curly-brace placeholders (e.g.,
`Studio product photo of {product} on a marble podium...`).
- The prompt template is authored in English with curly-brace placeholders (e.g.,
- Two-Way Edge Translation Coordination:
- Reading the Prompt ("Translate" Toggle): When a user on a non-English locale clicks "Translate", the frontend (
frontend/site/prompt-translate.ts) callsPOST /api/translatewithto = currentLocale.protectSlots()replaces`{product}`with[[1]]before calling Workers AI andrestoreSlots()restores`{product}`afterward, caching the translated template in a sessionMapkeyed by`${to}\n${text}`. - Filling Slot Inputs: When a user enters a non-ASCII value (e.g.,
"磨砂玻璃香水瓶 30ml") into a slot input (<= 200chars,TRANSLATE_MAX_VALUE) and triggers generation or copy, the slot value is translated to English (to = "en") via/api/translateand substituted into the canonical EnglishpromptEntemplate so the upstream model receives a pure, high-precision English prompt. - Graceful Degradation on
HTTP 503: If/api/translatereturns503 UNAVAILABLE(e.g., local dev without Workers AI binding),translateTextthrowsPromptTranslateError("UNAVAILABLE")and the UI hides the translation button rather than showing a broken control.
- Reading the Prompt ("Translate" Toggle): When a user on a non-English locale clicks "Translate", the frontend (
Spending Safeguards, Worker Crons & Ops Alerts
Tiered daily video spending caps for paid vs. unpaid users, runtime app_settings switches, Worker Cron schedules, and 6-hour cooldown Resend alerts.
Compliance Redlines & Platform AI Disclosures
The 6 code-enforced compliance redlines in server/src/compliance/redlines.ts, derived Amazon main-image warnings, and copyable platform disclosure templates.