1
0
Fork 0
polaris-task-force/tests/int/ai-compose-system.int.spec.ts
Z8MB1E f5166c80b6 fix(ai-compose): keep named action instructions in the system prompt
The plugin carries a named action's whole instruction in the system
prompt (Expand, Simplify, Rephrase, Proofread, Summarize, Tone,
Translate), while Compose on richText wraps the field's own system prompt
in buildRichTextSystem, which adds rules demanding lexical JSON and a
blog layout. buildComposeSystem discarded the incoming system prompt and
kept only the block-placeholder paragraph, so every named action reached
the model without its instruction and richText Compose lost the field's
own prompt too.

Keep the caller's prompt and strip only the contradiction: cut at the
plugin's RULES marker, re-append the extracted block-placeholder
paragraph, drop the JSON and layout lines as a backstop in case that
marker is reworded, then append AI_OUTPUT_RULES. The fieldType argument
is no longer needed.

The tests embed the plugin's real Expand, Simplify and Rephrase systems
and assert each instruction arrives intact with the rules appended.
2026-10-19 13:34:37 -04:00

211 lines
9 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
AI_OUTPUT_RULES,
buildComposeSystem,
extractBlockPlaceholderInstruction,
plainTextToLexicalJson,
resolveProseShape,
wrapProse,
} from "@/lib/ai/composeSystem";
// The exact system `@ai-stack/payloadcms@3.2.30` builds for a richText field
// (dist/endpoints/index.js -> buildRichTextSystem). Captured verbatim so that a
// plugin upgrade which changes the wording fails this spec loudly instead of
// silently letting the JSON/layout instructions back into the model's prompt.
const PLUGIN_RICH_TEXT_SYSTEM = `INSTRUCTIONS:
You are a highly skilled and professional blog writer,
renowned for crafting engaging and well-organized articles.
RULES:
- Generate original and unique content based on the given topic.
- Ensure the output follows the provided rich text JSON schema exactly.
- Produce valid JSON with no undefined or null values.
- The text may contain one or more standalone placeholder tokens of the exact form
"[[[BLOCK_<number>]]]" (e.g. "[[[BLOCK_0]]]").
These represent embedded content you cannot see. Reproduce every such token EXACTLY as given,
completely unchanged (do not translate, reword, remove, or merge it with other text), as its
own paragraph, in the same relative position within the surrounding text.
---
LAYOUT INSTRUCTIONS:
[paragraph] - Write a concise introduction (2-3 sentences) that outlines the main topic.
[horizontalrule] - Insert a horizontal rule to separate the introduction from the main content.
[list] - Create a list with 3-5 items. Each list item should contain:
a. [heading] - A brief, descriptive heading (up to 5 words)
b. [paragraph] - A short explanation or elaboration (1-2 sentences)
---
ADDITIONAL GUIDELINES:
- Ensure coherence and logical flow between all sections.
`;
// Verbatim from the plugin's `defaultPrompts` (dist/ai/prompts.js). These named
// actions carry their whole instruction in the system prompt, so anything that
// drops it (as this module once did) turns them into a generic prose request.
const EXPAND_SYSTEM = `You are a creative writer and subject matter expert. Expand the given text by adding depth, detail, and relevant information while maintaining the original tone and style.
-------------
INSTRUCTIONS:
- Understand the main ideas and tone of the text.
- Add more details, examples, explanations, or context.
- Maintain the original tone, style, and intent.
- Ensure the expanded version flows naturally and coherently.
- Do not contradict or alter the original meaning.
-------------`;
const SIMPLIFY_SYSTEM = `You are a skilled communicator specializing in clear and concise writing. Simplify the given text to make it easier to understand while retaining its core message.
-------------
INSTRUCTIONS:
- Simplify the language, using more common words and shorter sentences.
- Remove unnecessary details or jargon while keeping essential information.
- Maintain the original meaning and key points.
-------------`;
const REPHRASE_SYSTEM = `You are a skilled language expert. Rephrase the given text while maintaining its original meaning, tone, and emotional content.
-------------
INSTRUCTIONS:
- Rephrase the text according to the guidelines of the ORIGINAL SYSTEM PROMPT, if provided.
- Retain the original meaning, tone, and emotional content.
-------------
Previous prompt:
Summarise the field in two sentences.`;
describe("buildComposeSystem", () => {
it("keeps the field's own system prompt and drops the plugin's JSON/layout rules", () => {
const system = buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_SYSTEM });
expect(system).toContain("professional blog writer");
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toMatch(/\[paragraph\]|\[horizontalrule\]|\[list\]|\[heading\]|\[quote\]/);
expect(system).not.toContain("ADDITIONAL GUIDELINES");
});
it("keeps the block-placeholder paragraph so embedded blocks survive", () => {
const system = buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_SYSTEM });
expect(system).toContain("- The text may contain one or more standalone placeholder tokens");
expect(system).toContain("[[[BLOCK_<number>]]]");
expect(system).toContain("the same relative position within the surrounding text.");
});
it("passes every named action's instruction through unchanged", () => {
const cases = [
[EXPAND_SYSTEM, "Expand the given text by adding depth, detail"],
[SIMPLIFY_SYSTEM, "Simplify the given text to make it easier to understand"],
[REPHRASE_SYSTEM, "Rephrase the given text while maintaining its original meaning"],
] as const;
for (const [actionSystem, instruction] of cases) {
const system = buildComposeSystem({ pluginSystem: actionSystem });
expect(system).toContain(instruction);
expect(system).toContain("INSTRUCTIONS:");
// The output contract is still enforced on top of the action.
expect(system).toContain("Respond with plain prose only.");
expect(system.endsWith(AI_OUTPUT_RULES)).toBe(true);
}
// The Rephrase action also appends the field's previous prompt.
expect(buildComposeSystem({ pluginSystem: REPHRASE_SYSTEM })).toContain(
"Summarise the field in two sentences.",
);
});
it("adds the em-dash rule exactly once for every action and field shape", () => {
const systems = [
buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_SYSTEM }),
buildComposeSystem({ pluginSystem: EXPAND_SYSTEM }),
buildComposeSystem({ pluginSystem: SIMPLIFY_SYSTEM }),
buildComposeSystem({}),
buildComposeSystem({ pluginSystem: undefined }),
];
for (const system of systems) {
expect(system.match(/Never use em-dashes/g)).toHaveLength(1);
expect(system).toContain("Respond with plain prose only.");
}
});
it("sends only the shared rules when the plugin provides no system prompt", () => {
expect(buildComposeSystem({})).toBe(AI_OUTPUT_RULES);
expect(buildComposeSystem()).toBe(AI_OUTPUT_RULES);
expect(buildComposeSystem({ pluginSystem: "" })).toBe(AI_OUTPUT_RULES);
});
it("still drops JSON and layout demands if the plugin's marker wording changes", () => {
const reworded = PLUGIN_RICH_TEXT_SYSTEM.replace("\n\nRULES:", "\n\nGUIDELINES:");
const system = buildComposeSystem({ pluginSystem: reworded });
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toContain("[paragraph] - Write a concise introduction");
expect(system).toContain("professional blog writer");
});
it("sends the real em-dash character to the model", () => {
expect(AI_OUTPUT_RULES).toContain("em-dashes (\u2014)");
});
});
describe("extractBlockPlaceholderInstruction", () => {
it("returns the placeholder paragraph without the surrounding rules", () => {
const block = extractBlockPlaceholderInstruction(PLUGIN_RICH_TEXT_SYSTEM);
expect(block.startsWith("- The text may contain")).toBe(true);
expect(block.endsWith("surrounding text.")).toBe(true);
expect(block).not.toMatch(/JSON/);
});
it("returns an empty string when there is nothing to keep", () => {
expect(extractBlockPlaceholderInstruction(undefined)).toBe("");
expect(extractBlockPlaceholderInstruction("just some prose")).toBe("");
expect(extractBlockPlaceholderInstruction(EXPAND_SYSTEM)).toBe("");
});
});
describe("resolveProseShape / wrapProse", () => {
const lexicalSchema = { definitions: { root: {} }, type: "object" };
const textSchema = {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
};
it("wraps prose into lexical JSON for a richText schema", () => {
const shape = resolveProseShape(lexicalSchema);
expect(shape).toEqual({ kind: "lexical" });
const json = wrapProse(shape!, "First paragraph.\n\nSecond paragraph.");
expect(json).toEqual(plainTextToLexicalJson("First paragraph.\n\nSecond paragraph."));
const root = (json as { root: { children: Array<{ children: Array<{ text: string }> }> } }).root;
expect(root.children).toHaveLength(2);
expect(root.children[0].children[0].text).toBe("First paragraph.");
});
it("wraps prose into the field's own key for a single string property", () => {
const shape = resolveProseShape(textSchema);
expect(shape).toEqual({ kind: "field", key: "name" });
expect(wrapProse(shape!, "Barracks")).toEqual({ name: "Barracks" });
});
it("declines shapes it cannot wrap", () => {
expect(
resolveProseShape({ type: "object", properties: { tags: { type: "array" } } }),
).toBeNull();
expect(
resolveProseShape({
type: "object",
properties: { a: { type: "string" }, b: { type: "string" } },
}),
).toBeNull();
expect(resolveProseShape(undefined)).toBeNull();
});
});