Beautiful Open-Source Form Builder
feat: improve AI-generated form quality (#1273)
Julien Nahumebb1abb46e5a
diff --git a/api/app/Mcp/Resources/FormFieldCatalogResource.php b/api/app/Mcp/Resources/FormFieldCatalogResource.phpindex aa3c787c3..f3a0cf465 100644--- a/api/app/Mcp/Resources/FormFieldCatalogResource.php+++ b/api/app/Mcp/Resources/FormFieldCatalogResource.php@@ -12,7 +12,7 @@ use Laravel\Mcp\Server\Attributes\Uri;use Laravel\Mcp\Server\Resource;#[Name('form_field_catalog')]-#[Description('Canonical OpnForm field, presentation, media, and layout reference, including focused-mode guidance, aliases, and plan behavior.')]+#[Description('Canonical OpnForm field, presentation, media, layout, and authoring-quality reference, including focused-mode guidance, aliases, and plan behavior.')]#[Uri('opnform://reference/form-fields/v1')]#[MimeType('application/json')]class FormFieldCatalogResource extends Resourcediff --git a/api/app/Mcp/Servers/OpnFormServer.php b/api/app/Mcp/Servers/OpnFormServer.phpindex a2c77055d..0f1afff00 100644--- a/api/app/Mcp/Servers/OpnFormServer.php+++ b/api/app/Mcp/Servers/OpnFormServer.php@@ -33,7 +33,7 @@ use Laravel\Mcp\Server\Attributes\Version;#[Name('OpnForm')]#[Version('1.0.0')]-#[Instructions('Default every request to create a new form to the guest draft workflow unless the user explicitly asks to save it in their connected OpnForm account or a workspace. A natural request such as "create a contact form" needs no login: read the schema and field catalog, validate the definition, call create_form_draft, then call preview_form_draft. For a message or other long answer, use type text with multi_lines true; textarea is not a valid field type. If validation fails, correct and revalidate the definition before creating a draft. Never ask the user to connect, call get_account_context, or call create_form_in_account when guest draft tools can satisfy the request. OAuth is required only for connected-account operations: saving directly to a workspace, managing existing account forms, publishing, trashing, and reading or exporting submissions. Enabling or selecting the plugin is not OAuth authentication. If an account-scoped tool challenges, ask the user to authenticate the OpnForm MCP server in the host; do not repeatedly retry from the guest workflow. In local Codex, start a new conversation after OAuth so the MCP client loads the stored credential. If guest draft tools are unexpectedly missing, do not substitute an authenticated tool unless the user requested account persistence; ask the user to start a new conversation with OpnForm selected before the first message. Use OpnForm MCP tools directly. Never invoke Codex or ChatGPT recursively, run `codex exec`, use shell or raw HTTP, inspect repositories or caches, or switch connectors. Read the schema and field catalog again before changing presentation, fields, layout, or media, then validate before saving. Focused presentation creates one step per block automatically: use full-width blocks, no page breaks or standalone media blocks, and attach optional media through the block image property. Use only durable public HTTPS asset URLs, never localhost or temporary tunnel URLs.')]+#[Instructions('Default every request to create a new form to the guest draft workflow unless the user explicitly asks to save it in their connected OpnForm account or a workspace. A natural request such as "create a contact form" needs no login: read the schema and field catalog, validate, create_form_draft, then preview_form_draft. Follow the catalog authoring guidelines: use human labels, helpful example placeholders, appropriate fields and layout, a contextual submit label, and a useful completion message. Correct relevant non-blocking quality_warnings while preserving intentional choices. For a message or other long answer, use type text with multi_lines true; textarea is not a valid field type. If validation fails, correct and revalidate the definition before creating a draft. Never ask the user to connect when guest draft tools can satisfy the request. OAuth is required only for connected-account operations. Enabling or selecting the plugin is not OAuth authentication. If an account-scoped tool challenges, ask the user to authenticate the OpnForm MCP server in the host; do not repeatedly retry from the guest workflow. In local Codex, start a new conversation after OAuth so the MCP client loads the stored credential. If guest draft tools are unexpectedly missing, do not substitute an authenticated tool unless the user requested account persistence; ask the user to start a new conversation with OpnForm selected before the first message. Use OpnForm MCP tools directly. Never invoke Codex or ChatGPT recursively, run `codex exec`, use shell or raw HTTP, inspect repositories or caches, or switch connectors. Read the schema and field catalog again before changing presentation, fields, layout, or media, then validate before saving. Focused presentation creates one step per block automatically: use full-width blocks, no page breaks or standalone media blocks, and attach optional media through the block image property. Use only durable public HTTPS asset URLs, never localhost or temporary tunnel URLs.')]class OpnFormServer extends Server{public int $maxPaginationLength = 100;diff --git a/api/app/Mcp/Tools/ValidateFormDefinitionTool.php b/api/app/Mcp/Tools/ValidateFormDefinitionTool.phpindex a20f792e6..4eafbe185 100644--- a/api/app/Mcp/Tools/ValidateFormDefinitionTool.php+++ b/api/app/Mcp/Tools/ValidateFormDefinitionTool.php@@ -3,6 +3,7 @@namespace App\Mcp\Tools;use App\Service\Forms\AgentFormDefinition;+use App\Service\Forms\AgentFormQualityAnalyzer;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -15,15 +16,18 @@ use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Name('validate_form_definition')]-#[Description('Normalize and validate an OpnForm agent form definition without storing it. Returns the canonical definition with defaults, stable block IDs, sanitized content, and normalized aliases.')]+#[Description('Normalize and validate an OpnForm agent form definition without storing it. Returns the canonical definition with defaults, stable block IDs, sanitized content, normalized aliases, and non-blocking authoring-quality warnings.')]#[IsReadOnly]#[IsDestructive(false)]#[IsIdempotent]#[IsOpenWorld(false)]class ValidateFormDefinitionTool extends GuestMcpTool{- public function handle(Request $request, AgentFormDefinition $formDefinition): ResponseFactory- {+ public function handle(+ Request $request,+ AgentFormDefinition $formDefinition,+ AgentFormQualityAnalyzer $qualityAnalyzer,+ ): ResponseFactory {$validated = $request->validate(['definition' => ['required', 'array'],]);@@ -34,6 +38,7 @@ class ValidateFormDefinitionTool extends GuestMcpTool'valid' => true,'schema_version' => AgentFormDefinition::SCHEMA_VERSION,'definition' => $definition,+ 'quality_warnings' => $qualityAnalyzer->analyze($definition),]);}@@ -41,7 +46,7 @@ class ValidateFormDefinitionTool extends GuestMcpTool{return ['definition' => $schema->object()- ->description('Form definition following opnform://schemas/agent-form-definition/v1. IDs and optional defaults may be omitted.')+ ->description('Form definition following opnform://schemas/agent-form-definition/v1 and the authoring guidelines in opnform://reference/form-fields/v1. IDs and optional defaults may be omitted.')->required(),];}@@ -52,6 +57,13 @@ class ValidateFormDefinitionTool extends GuestMcpTool'valid' => $schema->boolean()->required(),'schema_version' => $schema->integer()->required(),'definition' => $schema->object()->required(),+ 'quality_warnings' => $schema->array()+ ->items($schema->object([+ 'code' => $schema->string()->required(),+ 'message' => $schema->string()->required(),+ 'path' => $schema->string()->required(),+ ]))+ ->required(),];}}diff --git a/api/app/Service/AI/Prompts/Form/GenerateFormFieldsPrompt.php b/api/app/Service/AI/Prompts/Form/GenerateFormFieldsPrompt.phpindex 8d04c1b94..7f4b31d24 100644--- a/api/app/Service/AI/Prompts/Form/GenerateFormFieldsPrompt.php+++ b/api/app/Service/AI/Prompts/Form/GenerateFormFieldsPrompt.php@@ -3,6 +3,7 @@namespace App\Service\AI\Prompts\Form;use App\Service\AI\Prompts\Prompt;+use App\Service\Forms\AgentFormAuthoringGuide;class GenerateFormFieldsPrompt extends Prompt{@@ -46,16 +47,8 @@ class GenerateFormFieldsPrompt extends Prompt{widthGuidance}- Field generation guidelines:- - Choose the most appropriate field type based on the data being collected- - Consider the existing form context and avoid duplicating fields- - Use logical field names that clearly describe the data being collected- - Add helpful placeholder text and help text for complex fields- - Set appropriate validation (required fields where necessary - do not add * to the field name if required - it's done automatically)- - Use appropriate width settings for better layout- - For select/multi-select fields, provide relevant options based on the context- - For number fields, consider if rating, scale, or slider would be more appropriate- - For rich text fields, consider if multi-line, matrix, or barcode input would be useful+ Follow this shared quality baseline:+ {authoringGuidelines}Return an array of field objects that:- Match the field description requirements@@ -147,6 +140,7 @@ class GenerateFormFieldsPrompt extends Prompt? 'In focused mode, do not use width options. Each step contains a single full-width question.': 'Field width options:\n- width: "full" (default)\n- width: "1/2"\n- width: "1/3"\n- width: "2/3"\n- width: "1/4"\n- width: "3/4"\nFields can share rows when room allows.';$variables['{allowedFieldTypesList}'] = $this->formatAllowedTypes($rules['allowedFieldTypes']);+ $variables['{authoringGuidelines}'] = AgentFormAuthoringGuide::fieldsPrompt();return $variables;}diff --git a/api/app/Service/AI/Prompts/Form/GenerateFormPrompt.php b/api/app/Service/AI/Prompts/Form/GenerateFormPrompt.phpindex f5b5ed94f..03bc95088 100644--- a/api/app/Service/AI/Prompts/Form/GenerateFormPrompt.php+++ b/api/app/Service/AI/Prompts/Form/GenerateFormPrompt.php@@ -3,6 +3,7 @@namespace App\Service\AI\Prompts\Form;use App\Service\AI\Prompts\Prompt;+use App\Service\Forms\AgentFormAuthoringGuide;class GenerateFormPrompt extends Prompt{@@ -45,14 +46,8 @@ class GenerateFormPrompt extends PromptIf the form is too long, you can paginate it by adding one or multiple page breaks (nf-page-break).- Create a complete form with appropriate fields based on the description. Include:- - A clear `title` (internal for form admin)- - `nf-text` blocks to add a title or text to the form using some basic html (h1, p, b, i, u etc)- - Logical field grouping- - Required fields where necessary (do not add * to the field name if required - it's done automatically)- - Help text for complex fields- - Appropriate validation- - Customized submission text+ Create a complete form with a clear internal title and follow this shared quality baseline:+ {authoringGuidelines}EOD;/**@@ -81,7 +76,7 @@ class GenerateFormPrompt extends Prompt],'submitted_text' => ['type' => 'string',- 'description' => 'Text to display after form submission (default: "<p>Thank you for your submission!</p>")'+ 'description' => 'Specific text that confirms what happened after submission and, when known, what comes next.'],'uppercase_labels' => ['type' => 'boolean',@@ -89,7 +84,7 @@ class GenerateFormPrompt extends Prompt],'submit_button_text' => ['type' => 'string',- 'description' => 'Text for the submit button (default: "Submit")'+ 'description' => 'Contextual action label such as "Send message", "Request a quote", or "Join the waitlist".'],'re_fill_button_text' => ['type' => 'string',@@ -197,6 +192,7 @@ class GenerateFormPrompt extends Prompt$vars['{modeConstraints}'] = $modeConstraints;$vars['{widthGuidance}'] = $widthGuidance;$vars['{allowedFieldTypesList}'] = $this->formatAllowedTypes($rules['allowedFieldTypes']);+ $vars['{authoringGuidelines}'] = AgentFormAuthoringGuide::completeFormPrompt();return $vars;}diff --git a/api/app/Service/Forms/AgentFormAuthoringGuide.php b/api/app/Service/Forms/AgentFormAuthoringGuide.phpnew file mode 100644index 000000000..ee98daf9e--- /dev/null+++ b/api/app/Service/Forms/AgentFormAuthoringGuide.php@@ -0,0 +1,65 @@+<?php++namespace App\Service\Forms;++class AgentFormAuthoringGuide+{+ private const RULES = [+ 'context' => [+ 'Infer the form purpose, audience, language, and tone from the request. Make conservative assumptions and produce a useful first draft instead of blocking on non-essential questions.',+ 'Keep short forms short. Ask only for information that serves the stated purpose and do not duplicate questions.',+ ],+ 'copy' => [+ 'Unless the form is intentionally trivial, begin with a concise nf-text heading and one supporting sentence that explains the form purpose.',+ 'Use human-facing labels in sentence case. Use short noun labels for identity fields and direct, unbiased questions for surveys; never expose raw identifiers or snake_case.',+ 'Use placeholders only for a useful example or expected format. Never use a placeholder instead of a visible label or merely repeat the label.',+ 'Use help text only for constraints, unfamiliar information, formatting guidance, or why the information is requested.',+ ],+ 'fields' => [+ 'Choose the most specific supported field type. Use text with multi_lines true for messages, comments, descriptions, and other long answers.',+ 'Mark only essential fields as required. For choice fields, provide clear, non-overlapping options and use visible choices for small option sets when appropriate.',+ ],+ 'layout' => [+ 'In classic mode, pair at most two related short fields on a row, keep long answers full width, and split longer forms by meaningful sections rather than arbitrary field counts.',+ 'In focused mode, keep one concise question or explanation per step and follow the focused presentation constraints from the field catalog.',+ 'Use clean neutral style defaults when no brand direction is supplied. Do not invent brand colors, logos, or decorative media.',+ ],+ 'completion' => [+ 'Use a contextual submit label such as Send message, Request a quote, or Join the waitlist instead of a generic Submit label.',+ 'Write a specific completion message that confirms what happened and, when known, what comes next.',+ ],+ 'integrity' => [+ 'Keep language, capitalization, terminology, tone, and option style consistent throughout the form.',+ 'Do not invent legal consent, marketing opt-ins, sensitive questions, response times, eligibility claims, or business commitments.',+ ],+ ];++ public static function reference(): array+ {+ return [+ 'objective' => 'Create a polished respondent-facing form, not merely the smallest valid schema.',+ 'rules' => self::RULES,+ 'validation' => 'Treat quality warnings from validate_form_definition as non-blocking editorial guidance. Correct relevant warnings before creating or saving, while preserving intentional user choices.',+ ];+ }++ public static function completeFormPrompt(): string+ {+ return self::promptForGroups(array_keys(self::RULES));+ }++ public static function fieldsPrompt(): string+ {+ return self::promptForGroups(['context', 'copy', 'fields', 'layout', 'integrity']);+ }++ private static function promptForGroups(array $groups): string+ {+ $lines = collect($groups)+ ->flatMap(fn (string $group): array => self::RULES[$group])+ ->map(fn (string $rule): string => '- '.$rule)+ ->implode("\n");++ return "Form authoring quality baseline:\n{$lines}";+ }+}diff --git a/api/app/Service/Forms/AgentFormFieldCatalog.php b/api/app/Service/Forms/AgentFormFieldCatalog.phpindex c9ecb5ef3..741164133 100644--- a/api/app/Service/Forms/AgentFormFieldCatalog.php+++ b/api/app/Service/Forms/AgentFormFieldCatalog.php@@ -103,6 +103,7 @@ class AgentFormFieldCatalog],],],+ 'authoring_guidelines' => AgentFormAuthoringGuide::reference(),'block_media' => ['property' => 'image','attach_to' => 'Any input block or nf-text block, especially for focused steps. This differs from the classic-only nf-image standalone block and its image_block property.',diff --git a/api/app/Service/Forms/AgentFormQualityAnalyzer.php b/api/app/Service/Forms/AgentFormQualityAnalyzer.phpnew file mode 100644index 000000000..abf0981be--- /dev/null+++ b/api/app/Service/Forms/AgentFormQualityAnalyzer.php@@ -0,0 +1,182 @@+<?php++namespace App\Service\Forms;++use Illuminate\Support\Str;++class AgentFormQualityAnalyzer+{+ private const MAX_WARNINGS = 50;++ private const RAW_LABELS = [+ 'name',+ 'email',+ 'phone',+ 'subject',+ 'message',+ 'website',+ 'company',+ 'address',+ 'comment',+ 'feedback',+ ];++ private const GENERIC_SUBMIT_LABELS = [+ '',+ 'submit',+ 'send',+ 'soumettre',+ 'envoyer',+ ];++ public function analyze(array $definition): array+ {+ $warnings = [];+ $properties = collect($definition['properties'] ?? [])+ ->filter(fn ($property): bool => is_array($property) && ! ($property['hidden'] ?? false));+ $inputProperties = $properties+ ->filter(fn (array $property): bool => in_array($property['type'] ?? null, AgentFormFieldCatalog::INPUT_TYPES, true));++ if ($inputProperties->count() > 1 && ! $this->hasVisibleIntroduction($properties->all())) {+ $warnings[] = $this->warning(+ 'missing_visible_intro',+ 'Add a concise nf-text heading and supporting sentence unless this form is intentionally minimal.',+ 'properties',+ );+ }++ foreach ($inputProperties as $index => $property) {+ $path = "properties.{$index}";+ $label = Str::squish(strip_tags((string) ($property['name'] ?? '')));+ $normalizedLabel = Str::lower($label);++ if ($this->looksLikeRawLabel($label)) {+ $warnings[] = $this->warning(+ 'machine_like_label',+ "Replace the raw label [{$label}] with clear respondent-facing copy in sentence case.",+ $path.'.name',+ );+ }++ $placeholder = Str::squish((string) ($property['placeholder'] ?? ''));+ if ($placeholder === '' && $this->wouldBenefitFromPlaceholder($property)) {+ $warnings[] = $this->warning(+ 'missing_helpful_placeholder',+ 'Add a useful example or expected format as the placeholder, without replacing the visible label.',+ $path.'.placeholder',+ );+ } elseif ($placeholder !== '' && $this->placeholderRepeatsLabel($placeholder, $normalizedLabel)) {+ $warnings[] = $this->warning(+ 'placeholder_repeats_label',+ 'Replace the placeholder with a useful example or format, or remove it if it adds no information.',+ $path.'.placeholder',+ );+ }++ if (($property['type'] ?? null) === 'text'+ && ! ($property['multi_lines'] ?? false)+ && $this->looksLikeLongAnswer($normalizedLabel)) {+ $warnings[] = $this->warning(+ 'long_answer_should_be_multiline',+ 'Set multi_lines to true for this message, comment, description, or other long-answer field.',+ $path.'.multi_lines',+ );+ }++ if (count($warnings) >= self::MAX_WARNINGS) {+ break;+ }+ }++ $submitLabel = Str::lower(Str::squish((string) ($definition['submit_button_text'] ?? '')));+ if (in_array($submitLabel, self::GENERIC_SUBMIT_LABELS, true)) {+ $warnings[] = $this->warning(+ 'generic_submit_label',+ 'Use a contextual action label such as Send message, Request a quote, or Join the waitlist.',+ 'submit_button_text',+ );+ }++ if ($this->hasGenericCompletionMessage((string) ($definition['submitted_text'] ?? ''))) {+ $warnings[] = $this->warning(+ 'generic_completion_message',+ 'Write a specific completion message that confirms what happened and, when known, what comes next.',+ 'submitted_text',+ );+ }++ return array_slice($warnings, 0, self::MAX_WARNINGS);+ }++ private function hasVisibleIntroduction(array $properties): bool+ {+ foreach ($properties as $property) {+ if (($property['type'] ?? null) !== 'nf-text') {+ continue;+ }++ if (Str::squish(strip_tags((string) ($property['content'] ?? ''))) !== '') {+ return true;+ }+ }++ return false;+ }++ private function looksLikeRawLabel(string $label): bool+ {+ if (preg_match('/^[a-z0-9]+(?:[_-][a-z0-9]+)+$/', $label) === 1) {+ return true;+ }++ return $label === Str::lower($label) && in_array($label, self::RAW_LABELS, true);+ }++ private function wouldBenefitFromPlaceholder(array $property): bool+ {+ if (in_array($property['type'] ?? null, ['email', 'phone_number', 'url'], true)) {+ return true;+ }++ return ($property['type'] ?? null) === 'text' && ($property['multi_lines'] ?? false);+ }++ private function placeholderRepeatsLabel(string $placeholder, string $normalizedLabel): bool+ {+ $normalizedPlaceholder = Str::lower(trim($placeholder, " \t\n\r\0\x0B.:"));++ return $normalizedPlaceholder === $normalizedLabel+ || in_array($normalizedPlaceholder, ["enter {$normalizedLabel}", "your {$normalizedLabel}"], true);+ }++ private function looksLikeLongAnswer(string $label): bool+ {+ return Str::contains($label, [+ 'message',+ 'comment',+ 'feedback',+ 'description',+ 'details',+ 'notes',+ 'request',+ 'demande',+ 'commentaire',+ 'description',+ 'détails',+ ]);+ }++ private function hasGenericCompletionMessage(string $message): bool+ {+ $message = Str::lower(Str::squish(strip_tags($message)));++ return $message === ''+ || $message === 'thank you for your submission!'+ || Str::startsWith($message, 'amazing, we saved your answers.');+ }++ private function warning(string $code, string $message, string $path): array+ {+ return compact('code', 'message', 'path');+ }+}diff --git a/api/tests/Feature/Mcp/AgentPluginPackageTest.php b/api/tests/Feature/Mcp/AgentPluginPackageTest.phpindex e76251f55..eac7d05e0 100644--- a/api/tests/Feature/Mcp/AgentPluginPackageTest.php+++ b/api/tests/Feature/Mcp/AgentPluginPackageTest.php@@ -79,6 +79,7 @@ it('ships a valid native OpenAI plugin wrapper for the hosted MCP server', funct->and(array_diff(array_keys($native['interface']), $nativeInterfaceFields))->toBe([])->and($native['interface']['websiteURL'])->toBe($portable['author']['url'])->and($native['interface']['defaultPrompt'])->toHaveCount(3)+ ->and($native['interface']['defaultPrompt'][0])->toContain('polished contact form')->and($nativeMcp['mcpServers']['opnform'])->toBe(['type' => 'http','url' => $portableMcp['mcpServers']['opnform']['url'],@@ -158,6 +159,12 @@ it('ships a discoverable OpnForm skill with the complete safety workflow', funct'do not loop or claim the connection succeeded','`textarea` is not a valid OpnForm field type','never continue to draft creation after validation fails',+ "field reference's `authoring_guidelines`",+ '`quality_warnings` as non-blocking editorial guidance',+ 'Use human-facing labels in sentence case',+ 'Add placeholders only when they provide a useful example or expected format',+ 'pair at most two related short fields on a row',+ 'not a generic “Submit”',)->and($skill)->toContain('confirm_publish: true', 'confirm_trash: true')->and($skill)->not->toContain('`confirm: true`')diff --git a/api/tests/Feature/Mcp/McpFoundationTest.php b/api/tests/Feature/Mcp/McpFoundationTest.phpindex 935acb008..9f2e6cf57 100644--- a/api/tests/Feature/Mcp/McpFoundationTest.php+++ b/api/tests/Feature/Mcp/McpFoundationTest.php@@ -38,7 +38,9 @@ it('exposes the OpnForm MCP endpoint and initializes the protocol', function ()&& str_contains($discoveryInstructions, 'A natural request such as "create a contact form" needs no login')&& str_contains($discoveryInstructions, 'Never ask the user to connect')&& str_contains($discoveryInstructions, 'OAuth is required only for connected-account operations')- && str_contains($discoveryInstructions, 'Enabling or selecting the plugin is not OAuth authentication');+ && str_contains($discoveryInstructions, 'Enabling or selecting the plugin is not OAuth authentication')+ && str_contains($discoveryInstructions, 'Follow the catalog authoring guidelines')+ && str_contains($discoveryInstructions, 'quality_warnings');});});@@ -194,11 +196,41 @@ it('publishes the canonical form field catalog', function () {->assertSee('payment')->assertSee('presentation_modes')->assertSee('focused')+ ->assertSee('authoring_guidelines')+ ->assertSee('polished respondent-facing form')->assertSee('block_media')->assertSee('trycloudflare.com')->assertSee('save');});+it('returns non-blocking authoring quality warnings with a valid definition', function () {+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [+ 'definition' => [+ 'title' => 'Contact form',+ 'properties' => [+ ['name' => 'name', 'type' => 'text'],+ ['name' => 'email', 'type' => 'email'],+ ['name' => 'message', 'type' => 'text'],+ ],+ ],+ ])+ ->assertOk()+ ->assertStructuredContent(+ fn (AssertableJson $json) => $json+ ->where('valid', true)+ ->where('schema_version', 1)+ ->has('definition')+ ->has(+ 'quality_warnings',+ fn (AssertableJson $warnings) => $warnings+ ->each(+ fn (AssertableJson $warning) => $warning+ ->hasAll(['code', 'message', 'path'])+ )+ )+ );+});+it('requires public durable HTTPS URLs for agent-provided media', function () {$definition = app(AgentFormDefinition::class);diff --git a/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.php b/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.phpnew file mode 100644index 000000000..71dcd4544--- /dev/null+++ b/api/tests/Unit/Service/Forms/AgentFormAuthoringGuideTest.php@@ -0,0 +1,49 @@+<?php++use App\Service\AI\Prompts\Form\GenerateFormFieldsPrompt;+use App\Service\AI\Prompts\Form\GenerateFormPrompt;+use App\Service\Forms\AgentFormAuthoringGuide;++uses(Tests\TestCase::class);++it('provides one shared authoring baseline to MCP resources and native prompts', function () {+ $reference = AgentFormAuthoringGuide::reference();+ $completePrompt = AgentFormAuthoringGuide::completeFormPrompt();+ $fieldsPrompt = AgentFormAuthoringGuide::fieldsPrompt();++ expect($reference)+ ->toHaveKeys(['objective', 'rules', 'validation'])+ ->and($reference['rules'])->toHaveKeys(['context', 'copy', 'fields', 'layout', 'completion', 'integrity'])+ ->and($completePrompt)->toContain(+ 'human-facing labels in sentence case',+ 'Use placeholders only for a useful example or expected format',+ 'Use a contextual submit label',+ 'Do not invent legal consent',+ )+ ->and($fieldsPrompt)->toContain('pair at most two related short fields on a row')+ ->and($fieldsPrompt)->not->toContain('Use a contextual submit label');+});++it('injects the shared authoring baseline into native form prompts', function () {+ $formPrompt = new class ('Create a contact form') extends GenerateFormPrompt {+ public function compiled(): string+ {+ return $this->buildPrompt();+ }+ };++ $fieldsPrompt = new class ('Add contact details', 'Contact form') extends GenerateFormFieldsPrompt {+ public function compiled(): string+ {+ return $this->buildPrompt();+ }+ };++ expect($formPrompt->compiled())+ ->toContain('Form authoring quality baseline')+ ->toContain('Use a contextual submit label')+ ->not->toContain('{authoringGuidelines}')+ ->and($fieldsPrompt->compiled())+ ->toContain('Use human-facing labels in sentence case')+ ->not->toContain('{authoringGuidelines}');+});diff --git a/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.php b/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.phpnew file mode 100644index 000000000..c5900b8fd--- /dev/null+++ b/api/tests/Unit/Service/Forms/AgentFormQualityAnalyzerTest.php@@ -0,0 +1,54 @@+<?php++use App\Service\Forms\AgentFormDefinition;+use App\Service\Forms\AgentFormQualityAnalyzer;++uses(Tests\TestCase::class);++it('returns actionable non-blocking warnings for a minimal machine-like form', function () {+ $definition = app(AgentFormDefinition::class)->normalizeAndValidate([+ 'title' => 'Contact form',+ 'properties' => [+ ['name' => 'name', 'type' => 'text'],+ ['name' => 'email', 'type' => 'email'],+ ['name' => 'message', 'type' => 'text'],+ ],+ ]);++ $warnings = app(AgentFormQualityAnalyzer::class)->analyze($definition);+ $codes = collect($warnings)->pluck('code');++ expect($codes)->toContain(+ 'missing_visible_intro',+ 'machine_like_label',+ 'missing_helpful_placeholder',+ 'long_answer_should_be_multiline',+ 'generic_submit_label',+ 'generic_completion_message',+ )->and($warnings)->each->toHaveKeys(['code', 'message', 'path']);+});++it('does not warn for a polished contact form', function () {+ $definition = app(AgentFormDefinition::class)->normalizeAndValidate([+ 'title' => 'Contact requests',+ 'submit_button_text' => 'Send message',+ 'submitted_text' => '<p>Thanks — your message has been sent. We will get back to you soon.</p>',+ 'properties' => [+ [+ 'name' => 'Introduction',+ 'type' => 'nf-text',+ 'content' => '<h1>Contact us</h1><p>Tell us how we can help.</p>',+ ],+ ['name' => 'Full name', 'type' => 'text', 'placeholder' => 'Jane Smith', 'width' => '1/2'],+ ['name' => 'Email address', 'type' => 'email', 'placeholder' => '[email protected]', 'width' => '1/2'],+ [+ 'name' => 'How can we help?',+ 'type' => 'text',+ 'multi_lines' => true,+ 'placeholder' => 'Tell us a little about your request',+ ],+ ],+ ]);++ expect(app(AgentFormQualityAnalyzer::class)->analyze($definition))->toBe([]);+});diff --git a/plugins/opnform/.codex-plugin/plugin.json b/plugins/opnform/.codex-plugin/plugin.jsonindex c224aab60..439c56879 100644--- a/plugins/opnform/.codex-plugin/plugin.json+++ b/plugins/opnform/.codex-plugin/plugin.json@@ -21,8 +21,8 @@"mcpServers": "./.mcp.json","interface": {"displayName": "OpnForm",- "shortDescription": "Build and manage forms with your AI assistant",- "longDescription": "Create and preview private form drafts without an account. Connect OpnForm only when you need to save, publish, manage existing forms, or search and export submissions.",+ "shortDescription": "Build polished forms with your AI assistant",+ "longDescription": "Create polished, respondent-friendly form drafts and preview them without an account. Connect OpnForm only when you need to save, publish, manage existing forms, or search and export submissions.","developerName": "OpnForm","category": "Productivity","capabilities": [@@ -34,7 +34,7 @@"privacyPolicyURL": "https://opnform.com/privacy-policy","termsOfServiceURL": "https://opnform.com/terms-conditions","defaultPrompt": [- "Create a contact form for my business and show me a preview.",+ "Create a polished contact form for my business and show me a preview.","Find recent submissions containing a specific email address.","Update my form, then ask me before publishing it."],diff --git a/plugins/opnform/skills/opnform/SKILL.md b/plugins/opnform/skills/opnform/SKILL.mdindex 427b0cf7a..3af0eabf8 100644--- a/plugins/opnform/skills/opnform/SKILL.md+++ b/plugins/opnform/skills/opnform/SKILL.md@@ -22,8 +22,8 @@ Treat an unqualified request such as “create a contact form”, “build a surThis is the default workflow for new-form requests, including when the user does not mention “guest”, “draft”, “preview”, or “without login”. The presence of OAuth-protected account tools does not make authentication a prerequisite for these steps.-1. Read `opnform://schemas/agent-form-definition/v1` and `opnform://reference/form-fields/v1` before generating a definition. Re-read the field reference before changing presentation style, fields, layout, or media later in the conversation. Do not inspect the OpnForm source tree or guess product behavior when the MCP resources describe it.-2. Call `validate_form_definition`. Resolve every validation error before creating or saving a draft.+1. Read `opnform://schemas/agent-form-definition/v1` and `opnform://reference/form-fields/v1` before generating a definition. Follow the field reference's `authoring_guidelines`. Re-read the field reference before changing presentation style, fields, layout, or media later in the conversation. Do not inspect the OpnForm source tree or guess product behavior when the MCP resources describe it.+2. Perform the respondent-facing quality pass below, then call `validate_form_definition`. Resolve every validation error. Treat `quality_warnings` as non-blocking editorial guidance: correct relevant warnings before creating or saving while preserving intentional user choices.3. Call `create_form_draft` with the validated definition.4. Keep the returned `draft_token` private. It is a capability secret: never quote it to the user, write it to a file, log it, or send it to another service.5. Call `preview_form_draft` and present its interactive MCP preview when the host supports it.@@ -33,6 +33,19 @@ This is the default workflow for new-form requests, including when the user doesThe browser editor keeps the guest draft available through an HttpOnly session. The user can preview and edit before signing in. Authentication and workspace selection happen only when the user chooses to save the draft into an OpnForm account.+### Produce a polished first draft++- Infer the form's purpose, audience, language, and tone. Make conservative assumptions and show a useful first draft instead of blocking on non-essential questions.+- Keep short forms short. Unless the form is intentionally trivial, begin with a concise `nf-text` heading and one supporting sentence explaining its purpose.+- Use human-facing labels in sentence case. Use short noun labels for identity fields and direct, unbiased questions for surveys; never expose raw identifiers or snake_case.+- Add placeholders only when they provide a useful example or expected format. Never use them instead of visible labels or repeat “Enter your [label]”.+- Add help text only for constraints, unfamiliar information, formatting, or why information is requested.+- Use the most specific field type and mark only essential fields as required. Avoid duplicate or unnecessary questions.+- In classic mode, pair at most two related short fields on a row and keep long answers full width. Split long forms by meaningful sections, not arbitrary field counts.+- Use clean neutral style defaults unless the user supplies brand direction. Do not invent brand colors, logos, decorative media, legal consent, sensitive questions, response times, or business commitments.+- Use a contextual action such as “Send message”, “Request a quote”, or “Join the waitlist”, not a generic “Submit”. Add a specific completion message that confirms what happened and, when known, what comes next.+- Keep language, capitalization, tone, terminology, and option style consistent throughout the form.+### Common field mappings- Use `type: text` for both short text and long-answer fields. Set `multi_lines: true` for a message, comment, description, or other textarea-style answer; `textarea` is not a valid OpnForm field type.diff --git a/plugins/opnform/skills/opnform/agents/openai.yaml b/plugins/opnform/skills/opnform/agents/openai.yamlindex da6e474e8..b4f858731 100644--- a/plugins/opnform/skills/opnform/agents/openai.yaml+++ b/plugins/opnform/skills/opnform/agents/openai.yaml@@ -1,8 +1,8 @@interface:display_name: "OpnForm"- short_description: "Create and manage OpnForm forms through MCP"+ short_description: "Create polished OpnForm forms through MCP"brand_color: "#2563EB"- default_prompt: "Use $opnform to create, preview, or manage an OpnForm form directly through MCP."+ default_prompt: "Use $opnform to create a polished, respondent-friendly form and show me an interactive preview."dependencies:tools:- type: "mcp"