1
0
Fork 0

fix(ai): resolve compose title and name the entity in seeded prompts

This commit is contained in:
Jason Fraley 2026-10-19 11:32:59 -04:00
parent 869d2944b3
commit 88982bfcdf
3 changed files with 196 additions and 12 deletions

View file

@ -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 <noun>" ("... 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<void> {
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 <noun>".
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<void> {
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 <noun>" 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}.%`};
`);
}
}

View file

@ -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'
},
];

View file

@ -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 <noun>" 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<string, unknown>;
return titleValueToString(record.title ?? record.name ?? record.label ?? record.id);
}
return "";
};
const readDocumentPath = (data: Record<string, unknown>, path: string): unknown =>
path
.split(".")
.reduce<unknown>(
(value, key) =>
value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined,
data,
);
const resolvePromptTitle = (data: Record<string, unknown>, 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<string, unknown>, ctx.collection),
},
],
collections: {
[GameHardResources.slug]: true,
[GameStructures.slug]: true,