diff --git a/src/migrations/20261019_120000_add_ai_prompt_entity_context.ts b/src/migrations/20261019_120000_add_ai_prompt_entity_context.ts new file mode 100644 index 00000000..e954cdbc --- /dev/null +++ b/src/migrations/20261019_120000_add_ai_prompt_entity_context.ts @@ -0,0 +1,75 @@ +import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres"; + +/** + * AI Compose seeded prompts previously referenced the document generically + * ("... of {{ title }}."). They now name the entity type ("... of the technology + * {{ title }}."), and for a collection's own title field they drop the token in + * favour of "this " ("... name for this technology."). This rewrites the + * existing instruction rows to match `staticAiPrompt` in `payload.config.ts`, so + * no reseed is needed and the shared system/layout/disabled columns (and any + * admin edits to them) are preserved. + * + * Idempotent: the up statements only touch rows that still contain `{{ title }}` + * (the identity pass converts them first, so the general pass skips them), and + * down keys off the exact inserted noun phrase. Safe to re-run. + */ + +const titleFieldFor = (collection: { admin?: { useAsTitle?: string } }): string => + collection.admin?.useAsTitle ?? "title"; + +const labelToText = (value: unknown, fallback: string): string => + typeof value === "string" ? value : fallback; + +export async function up({ db, payload }: MigrateUpArgs): Promise { + for (const collection of payload.config.collections) { + const slug = collection.slug; + const noun = labelToText(collection.labels?.singular, slug).toLowerCase(); + const titleField = titleFieldFor(collection); + + // Identity rows (the collection's own title field): `{{ title }}` is empty + // on a new document or the value being replaced on an existing one, so drop + // the token in favour of "this ". + await db.execute(sql` + UPDATE "plugin_ai_instructions" + SET "prompt" = replace("prompt", ' for {{ title }}', ${" for this " + noun}) + WHERE "schema_path" = ${`${slug}.${titleField}`} + AND "prompt" LIKE '%{{ title }}%'; + `); + + // Every other row: name the entity immediately before the token. Runs after + // the identity pass, which has already removed `{{ title }}` from those rows. + await db.execute(sql` + UPDATE "plugin_ai_instructions" + SET "prompt" = replace( + replace("prompt", 'of {{ title }}', ${"of the " + noun + " {{ title }}"}), + 'for {{ title }}', ${"for the " + noun + " {{ title }}"} + ) + WHERE "schema_path" LIKE ${`${slug}.%`} + AND "prompt" LIKE '%{{ title }}%'; + `); + } +} + +export async function down({ db, payload }: MigrateDownArgs): Promise { + for (const collection of payload.config.collections) { + const slug = collection.slug; + const noun = labelToText(collection.labels?.singular, slug).toLowerCase(); + const titleField = titleFieldFor(collection); + + // Reverse the identity pass first so "this " becomes the token again, + // then the general pass, which is unambiguous because the noun is explicit. + await db.execute(sql` + UPDATE "plugin_ai_instructions" + SET "prompt" = replace("prompt", ${" for this " + noun}, ' for {{ title }}') + WHERE "schema_path" = ${`${slug}.${titleField}`}; + `); + + await db.execute(sql` + UPDATE "plugin_ai_instructions" + SET "prompt" = replace( + replace("prompt", ${"of the " + noun + " {{ title }}"}, 'of {{ title }}'), + ${"for the " + noun + " {{ title }}"}, 'for {{ title }}') + WHERE "schema_path" LIKE ${`${slug}.%`}; + `); + } +} diff --git a/src/migrations/index.ts b/src/migrations/index.ts index e00e7580..ea22d6fc 100644 --- a/src/migrations/index.ts +++ b/src/migrations/index.ts @@ -140,6 +140,7 @@ import * as migration_20261014_140500_add_minigame_phasing_out_status from './20 import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states'; import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields'; import * as migration_20261015_120000_add_bomperator_minigame_stats from './20261015_120000_add_bomperator_minigame_stats'; +import * as migration_20261019_120000_add_ai_prompt_entity_context from './20261019_120000_add_ai_prompt_entity_context'; export const migrations = [ { @@ -852,4 +853,9 @@ export const migrations = [ down: migration_20261015_120000_add_bomperator_minigame_stats.down, name: '20261015_120000_add_bomperator_minigame_stats' }, + { + up: migration_20261019_120000_add_ai_prompt_entity_context.up, + down: migration_20261019_120000_add_ai_prompt_entity_context.down, + name: '20261019_120000_add_ai_prompt_entity_context' + }, ]; diff --git a/src/payload.config.ts b/src/payload.config.ts index b4a00d13..1a798657 100644 --- a/src/payload.config.ts +++ b/src/payload.config.ts @@ -3,7 +3,7 @@ import { postgresAdapter } from "@payloadcms/db-postgres"; import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical"; import { nodemailerAdapter } from "@payloadcms/email-nodemailer"; import path from "path"; -import { buildConfig } from "payload"; +import { buildConfig, formatLabels } from "payload"; import { fileURLToPath } from "url"; import sharp from "sharp"; import nodemailer from "nodemailer"; @@ -150,40 +150,76 @@ const AI_TEXT_FIELD_ALLOWLIST = new Set([ // Textarea/richText fields that are system-managed or technical, never AI-able. const AI_FIELD_DENYLIST = new Set(["contentsnapshot", "html", "script"]); -const staticAiPrompt = (fieldName: string, fieldLabel: string, fieldType: string): string => { +// Entity noun for a collection, used to tell the model what kind of document it +// is writing for ("the technology Barracks"). Prefers an explicit collection +// label (e.g. Experience → "XP Level"); otherwise Payload's slug-derived label. +const collectionNoun = (slug: string): string => { + const collection = collections.find((candidate) => candidate.slug === slug); + const custom = collection?.labels?.singular; + const label = typeof custom === "string" ? custom : formatLabels(slug).singular; + return label.toLowerCase(); +}; + +// True when the field being generated *is* the collection's own title field, so +// `{{ title }}` would be empty (new document) or the value being replaced +// (existing document). Those prompts read "this " instead of the token. +const isIdentityField = (slug: string, path: string): boolean => { + const collection = collections.find((candidate) => candidate.slug === slug); + return path === `${slug}.${collection?.admin?.useAsTitle ?? "title"}`; +}; + +const staticAiPrompt = ( + fieldName: string, + fieldLabel: string, + fieldType: string, + collectionSlug: string, + path: string, +): string => { + const noun = collectionNoun(collectionSlug); + const identity = isIdentityField(collectionSlug, path); + switch (fieldName) { case "description": case "gamedescription": - return `Write an immersive, in-universe description for the "${fieldLabel}" of {{ title }}. 2-4 sentences of plain prose. No markdown, no lists, no headings.`; + return `Write an immersive, in-universe description for the "${fieldLabel}" of the ${noun} {{ title }}. 2-4 sentences of plain prose. No markdown, no lists, no headings.`; case "summary": - return `Write a concise summary for the "${fieldLabel}" of {{ title }}. 1-3 sentences of plain prose.`; + return `Write a concise summary for the "${fieldLabel}" of the ${noun} {{ title }}. 1-3 sentences of plain prose.`; case "bio": - return `Write a short in-universe biography for {{ title }}. A few sentences of plain prose covering background and personality.`; + return `Write a short in-universe biography for the ${noun} {{ title }}. A few sentences of plain prose covering background and personality.`; case "occupation": - return `Suggest a short occupation label for {{ title }}. Reply with 1-3 words only, no explanation.`; + return `Suggest a short occupation label for the ${noun} {{ title }}. Reply with 1-3 words only, no explanation.`; case "name": - return `Suggest a single fitting name for {{ title }}. Reply with the name only, no explanation.`; + return identity + ? `Suggest a single fitting name for this ${noun}. Reply with the name only, no explanation.` + : `Suggest a single fitting name for the ${noun} {{ title }}. Reply with the name only, no explanation.`; case "title": - return `Suggest a single fitting title for {{ title }}. Reply with the title only, no explanation.`; + return identity + ? `Suggest a single fitting title for this ${noun}. Reply with the title only, no explanation.` + : `Suggest a single fitting title for the ${noun} {{ title }}. Reply with the title only, no explanation.`; default: if (fieldType === "richText") { - return `Write long-form content for the "${fieldLabel}" section of {{ title }}. Structured prose with an introduction, clear sections, and a conclusion.`; + return `Write long-form content for the "${fieldLabel}" section of the ${noun} {{ title }}. Structured prose with an introduction, clear sections, and a conclusion.`; } - return `Write suitable content for the "${fieldLabel}" of {{ title }}. Plain prose, concise and relevant.`; + return `Write suitable content for the "${fieldLabel}" of the ${noun} {{ title }}. Plain prose, concise and relevant.`; } }; const aiFieldSeedPrompts: SeedPromptFunction = ({ path, fieldType, fieldLabel }) => { const fieldName = (path.split(".").pop() ?? "").toLowerCase(); + const collectionSlug = path.split(".")[0] ?? ""; if (AI_FIELD_DENYLIST.has(fieldName)) return false; if (fieldType === "textarea" || fieldType === "richText") { - return { data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType) } }; + return { + data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType, collectionSlug, path) }, + }; } if (fieldType === "text" && AI_TEXT_FIELD_ALLOWLIST.has(fieldName)) { - return { data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType) } }; + return { + data: { prompt: staticAiPrompt(fieldName, fieldLabel, fieldType, collectionSlug, path) }, + }; } return false; @@ -408,6 +444,64 @@ const scopedCollections = collections.map((collection) => ({ }, })); +// AI Compose prompt templates use `{{ title }}` for the document being edited. +// Payload's `useAsTitle` is per-collection (usually `name`, not `title`), and the +// plugin's Handlebars context only exposes raw document fields, so `{{ title }}` +// resolved to an empty string on every collection without a literal `title` field. +// Expose `title` as a computed prompt field backed by the collection's real +// `useAsTitle` field, with fallbacks for partial/unsaved documents. +const useAsTitleByCollection = new Map( + scopedCollections.map((collection) => [collection.slug, collection.admin?.useAsTitle ?? "title"]), +); + +const TITLE_FALLBACK_FIELDS = [ + "title", + "name", + "label", + "subject", + "summary", + "detail", + "username", + "email", + "id", +] as const; + +const titleValueToString = (value: unknown): string => { + if (value == null) return ""; + if (typeof value === "string" || typeof value === "number") return String(value); + if (Array.isArray(value)) { + return value.map(titleValueToString).filter(Boolean).join(", "); + } + if (typeof value === "object") { + const record = value as Record; + return titleValueToString(record.title ?? record.name ?? record.label ?? record.id); + } + return ""; +}; + +const readDocumentPath = (data: Record, path: string): unknown => + path + .split(".") + .reduce( + (value, key) => + value && typeof value === "object" ? (value as Record)[key] : undefined, + data, + ); + +const resolvePromptTitle = (data: Record, collection: string): string => { + const configured = titleValueToString( + readDocumentPath(data, useAsTitleByCollection.get(collection) ?? "title"), + ); + if (configured) return configured; + + for (const field of TITLE_FALLBACK_FIELDS) { + const value = titleValueToString(readDocumentPath(data, field)); + if (value) return value; + } + + return ""; +}; + // MCP: eligible per collection, not granted: `enabled: true` makes all CRUD // capabilities available, but each MCP API key still picks its own capability // checkboxes and each collection's access control still applies. @@ -595,6 +689,15 @@ export default buildConfig({ }), payloadAiPlugin({ seedPrompts: aiFieldSeedPrompts, + // Resolve `{{ title }}` from the collection's actual `useAsTitle` field + // (e.g. `name` on Technologies) instead of requiring a literal `title`. + promptFields: [ + { + name: "title", + getter: (data, ctx) => + resolvePromptTitle((data ?? {}) as Record, ctx.collection), + }, + ], collections: { [GameHardResources.slug]: true, [GameStructures.slug]: true,