This commit is contained in:
greeneclipse committed 2026-10-14 20:02:42 +02:00
1 parent 3b0d692839
commit 8b540d22bc
14 files changed
+526 -82

No files matched your search

@@ -0,0 +1,81 @@
package aiprompts
import (
"strings"
"testing"
)
func TestCanonicalDefaultsSameForEveryCategory(t *testing.T) {
canonical, err := OfflineDefaultPrompt("en")
if err != nil {
t.Fatal(err)
}
names := []string{"", "High chairs", "Televisions", "Cables", "Mixers", "Unlisted category", "Stolčki"}
for _, name := range names {
got := DefaultCategoryFormula("", name)
if got.Overlay != canonical {
t.Fatalf("%s differs from canonical English\n%s", name, got.Overlay)
}
if !strings.Contains(got.Overlay, "<p>{") || strings.Contains(got.Overlay, "first verified benefit") {
t.Fatalf("legacy HTML slipped through for %s", name)
}
if got.DescriptionTemplateJSON != DefaultCategoryFormula("", "unknown").DescriptionTemplateJSON {
t.Fatalf("%s has category-specific HTML validation shape", name)
}
if got.TitleTemplateJSON != DefaultCategoryFormula("", "unknown").TitleTemplateJSON {
t.Fatalf("%s has category-specific structured title", name)
}
old := PriorDefaultCategoryFormula("", name)
if old.Overlay == got.Overlay {
t.Fatalf("%s lost old default for migration", name)
}
previous := PreviousSEODefaultCategoryFormula("", name)
if previous.Overlay == got.Overlay {
t.Fatalf("%s lost SEO-v4 default for migration", name)
}
}
if sources := AllDefaultCategoryPrompts(); len(sources) != 1 || sources[0] != canonical {
t.Fatalf("expected one shared template, got %d", len(sources))
}
}
func TestLocalizedMetaOverridesGlobalEnglishTemplate(t *testing.T) {
en := DefaultCategoryFormula("", "Any")
hr, err := OfflineDefaultPrompt("hr")
if err != nil {
t.Fatal(err)
}
resolved := EffectiveDescriptionFormula(en.DescriptionTemplateJSON, hr)
if !strings.Contains(resolved.MetaDescription, "sažmi") {
t.Fatalf("Croatian meta instructions not honored: %s", resolved.MetaDescription)
}
if strings.Contains(resolved.MetaDescription, "Summarize what") {
t.Fatalf("English leaked into Croatian meta")
}
}
func TestCanonicalLocalesHaveExactlySameHTMLStructure(t *testing.T) {
want := []string{"p", "h2", "p", "h2", "ul"}
for _, lang := range OfflinePromptLanguages() {
source, err := OfflineDefaultPrompt(lang)
if err != nil {
t.Fatal(err)
}
section := DescriptionSectionInstructions(source)
f := DeriveDescriptionFormulaFromLegacyParts(LegacyEnhanceParts{DescriptionRules: section, WasLegacy: true})
if len(f.Sections) != len(want) {
t.Fatalf("%s has %d sections", lang, len(f.Sections))
}
for i, typ := range want {
if f.Sections[i].Type != typ {
t.Fatalf("%s section %d is %s not %s", lang, i, f.Sections[i].Type, typ)
}
}
if !f.Sections[1].Optional || !f.Sections[2].Optional || !f.Sections[3].Optional || !f.Sections[4].Optional {
t.Fatalf("%s optional feature/spec sections missing flags", lang)
}
if strings.Contains(section, "<h1>") || strings.Contains(section, "100 words") {
t.Fatalf("%s obsolete structure", lang)
}
}
}
@@ -136,19 +136,29 @@ var (
defaultFormulaByKey map[string]CategoryFormulaDefaults
legacyFormulaByKey map[string]CategoryFormulaDefaults
priorFormulaByKey map[string]CategoryFormulaDefaults
seoV4FormulaByKey map[string]CategoryFormulaDefaults
legacyFormulaGeneric CategoryFormulaDefaults
priorFormulaGeneric CategoryFormulaDefaults
seoV4FormulaGeneric CategoryFormulaDefaults
defaultFormulaGeneric CategoryFormulaDefaults
defaultFormulaCount int
)
func loadDefaultCategoryFormulas() {
defaultFormulaGeneric = buildCategoryFormulaDefaults("", GenericDefaultCategoryPrompt)
// Every platform category now shares EXACTLY the same structural formula.
// Localization changes language only, never the number or order of blocks.
canonical, err := OfflineDefaultPrompt("en")
if err != nil {
panic("invalid bundled English default: " + err.Error())
}
defaultFormulaGeneric = buildCanonicalCategoryFormulaDefaults("", canonical)
seoV4FormulaGeneric = withPreviouslyShippedMetaTitle(buildCategoryFormulaDefaults("", GenericDefaultCategoryPrompt))
legacyFormulaGeneric = buildCategoryFormulaDefaults("", LegacyGenericDefaultCategoryPrompt)
priorFormulaGeneric = buildCategoryFormulaDefaults("", PriorGenericDefaultCategoryPrompt)
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
legacyFormulaByKey = map[string]CategoryFormulaDefaults{}
priorFormulaByKey = map[string]CategoryFormulaDefaults{}
seoV4FormulaByKey = map[string]CategoryFormulaDefaults{}
var f defaultCategoryPromptsFile
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
@@ -166,6 +176,13 @@ func loadDefaultCategoryFormulas() {
// description and meta structure across the platform defaults.
parts := ParseLegacyCombinedEnhancePrompt(prompt)
base := ParseLegacyCombinedEnhancePrompt(GenericDefaultCategoryPrompt)
seoV4Parts := parts
seoV4Parts.DescriptionRules = base.DescriptionRules
seoV4Parts.MetaRules = base.MetaRules
if seoV4Parts.TitleRules == "" {
seoV4Parts.TitleRules = base.TitleRules
}
seoV4 := withPreviouslyShippedMetaTitle(buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), seoV4Parts))
priorBase := ParseLegacyCombinedEnhancePrompt(PriorGenericDefaultCategoryPrompt)
priorParts := parts
priorParts.DescriptionRules = priorBase.DescriptionRules
@@ -176,7 +193,7 @@ func loadDefaultCategoryFormulas() {
if parts.TitleRules == "" {
parts.TitleRules = base.TitleRules
}
res := buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), parts)
res := buildCanonicalCategoryFormulaDefaults(strings.TrimSpace(e.Name), canonical)
if res.Overlay == "" {
continue
}
@@ -186,11 +203,73 @@ func loadDefaultCategoryFormulas() {
defaultFormulaByKey[k] = res
legacyFormulaByKey[k] = legacy
priorFormulaByKey[k] = priorFormula
seoV4FormulaByKey[k] = seoV4
}
}
}
}
// buildCanonicalCategoryFormulaDefaults derives the JSON validation and title
// elements from the SAME localized prompt used by the API/UI. Never derive the
// default English shape from legacy taxonomy-specific prompts.
func buildCanonicalCategoryFormulaDefaults(name, prompt string) CategoryFormulaDefaults {
title := ExtractEnhanceSectionBody(prompt, SectionTitleStart, SectionTitleEnd)
description := ExtractEnhanceSectionBody(prompt, SectionDescriptionStart, SectionDescriptionEnd)
meta := ExtractEnhanceSectionBody(prompt, SectionMetaStart, SectionMetaEnd)
if title == "" || description == "" || meta == "" {
panic("incomplete canonical SEO prompt")
}
parts := LegacyEnhanceParts{TitleRules: title, DescriptionRules: description, MetaRules: meta, WasLegacy: true}
result := buildCategoryFormulaDefaultsFromParts(name, parts)
// Generic legacy parsing falls back to type-before-brand and omits color.
// The canonical title must use the exact brand → type → model → optional
// color order stated in all 25 human-readable instructions.
titleFormula := TitleFormula{Separator: " ", Elements: []TitleFormulaElement{
{ID: "0-variable-brand", Type: "variable", Label: "Brand", Value: "brand", Description: "Official brand spelling", Example: "GROHE"},
{ID: "1-variable-product_type", Type: "variable", Label: "Product type", Value: "product_type", Description: "Specific product type in the target language", Example: "basin mixer"},
{ID: "2-variable-product_model", Type: "variable", Label: "Model", Value: "product_model", Description: "Official model and part number", Example: "Essence 24058GN1"},
{ID: "3-variable-barva", Type: "variable", Label: "Color (optional)", Value: "barva", Description: "Only when a verified color is supplied"},
}}
if encoded, err := json.Marshal(titleFormula); err == nil {
result.TitleTemplateJSON = string(encoded)
}
result.Overlay = prompt
return result
}
// SEO-v4 historically overwrote explicit English meta-title instructions with
// a legacy title length rule. Match the stored bytes for exact migrations only;
// new canonical defaults retain their actual localized meta instructions.
func withPreviouslyShippedMetaTitle(def CategoryFormulaDefaults) CategoryFormulaDefaults {
if strings.TrimSpace(def.DescriptionTemplateJSON) == "" {
return def
}
var f DescriptionFormula
if json.Unmarshal([]byte(def.DescriptionTemplateJSON), &f) != nil {
return def
}
if strings.TrimSpace(f.MetaTitle) != "" {
f.MetaTitle = DefaultMetaTitleRuleEN
if data, err := json.Marshal(f); err == nil {
def.DescriptionTemplateJSON = string(data)
}
}
return def
}
// PreviousSEODefaultCategoryFormula matches the built-in SEO-v4 formula, which
// differed by category in English and by language for non-English locales.
// It is only used for safe migrations of exact old platform defaults.
func PreviousSEODefaultCategoryFormula(uniqueID, name string) CategoryFormulaDefaults {
defaultFormulaOnce.Do(loadDefaultCategoryFormulas)
for _, key := range []string{uniqueID, name} {
if def, ok := seoV4FormulaByKey[NormalizeCategoryKey(key)]; ok {
return def
}
}
return seoV4FormulaGeneric
}
func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefaults {
parts := ParseLegacyCombinedEnhancePrompt(legacyPrompt)
if !parts.WasLegacy {
@@ -207,7 +286,7 @@ func buildCategoryFormulaDefaultsFromParts(name string, parts LegacyEnhanceParts
desc := DeriveDescriptionFormulaFromLegacyParts(parts)
// The derivation seeds a Slovenian meta-title rule for legacy A1 dumps; these
// formulas are the English set, so the whole formula must read in English.
if strings.TrimSpace(desc.MetaTitle) != "" {
if strings.TrimSpace(desc.MetaTitle) == DefaultLegacyMetaTitleRule {
desc.MetaTitle = DefaultMetaTitleRuleEN
}
if len(desc.Sections) > 0 || desc.MetaTitle != "" || desc.MetaDescription != "" {
@@ -36,7 +36,7 @@ func TestDefaultCategoryFormula_matchesA1Shape(t *testing.T) {
}
}
// Mirrors the Slovenian Stolčki formula: znamka, tip izdelka, poln model.
want := []string{"brand", "product_type", "product_model"}
want := []string{"brand", "product_type", "product_model", "barva"}
if strings.Join(vars, ",") != strings.Join(want, ",") {
t.Fatalf("title slots = %v want %v", vars, want)
}
@@ -250,7 +250,12 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
if isBuiltInMetaRoleBoilerplate(metaBody) {
metaBody = ""
}
if strings.TrimSpace(out.MetaTitle) == "" && strings.TrimSpace(out.MetaDescription) == "" && strings.TrimSpace(metaBody) != "" {
// Explicit language-scoped Meta instructions belong to the current language.
// A shared JSON description_template may hold English default meta rules,
// but must not override the translated --- Meta --- section in the API.
if mt, md, ok := splitLocalizedMetaRules(metaBody); ok {
out.MetaTitle, out.MetaDescription = mt, md
} else if strings.TrimSpace(out.MetaTitle) == "" && strings.TrimSpace(out.MetaDescription) == "" && strings.TrimSpace(metaBody) != "" {
out.MetaDescription = strings.TrimSpace(metaBody)
out.MetaTitle = DefaultLegacyMetaTitleRule
} else {
@@ -264,6 +269,28 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
return out
}
// splitLocalizedMetaRules parses the two fixed schema keys while retaining the
// instructions verbatim in the category's selected content language. The braces
// are editor instruction delimiters, not text for SEO output.
func splitLocalizedMetaRules(body string) (title, description string, ok bool) {
body = strings.TrimSpace(body)
if strings.HasPrefix(body, "{") && strings.HasSuffix(body, "}") &&
!strings.HasPrefix(body, "{{") {
body = strings.TrimSpace(body[1 : len(body)-1])
}
lower := strings.ToLower(body)
if !strings.HasPrefix(lower, "meta_title:") {
return "", "", false
}
idx := strings.Index(lower, "meta_description:")
if idx < 0 {
return "", "", false
}
title = strings.TrimSpace(body[len("meta_title:"):idx])
description = strings.TrimSpace(body[idx+len("meta_description:"):])
return title, description, title != "" && description != ""
}
func isBuiltInMetaRoleBoilerplate(body string) bool {
lower := strings.ToLower(strings.TrimSpace(body))
return strings.HasPrefix(lower, "role: meta")