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

@@ -194,6 +194,110 @@ func matchesDefaultFormula(current, previous string) bool {
return string(left) == string(right)
}
// isMixedBuiltInEnglishPrompt recognizes a historical default whose three
// roles came from different RELEASED defaults. A full role scaffold is required;
// each role must be an EXACT prior built-in fragment. Never match arbitrary
// user-written instructions by keywords or number of paragraphs.
func isMixedBuiltInEnglishPrompt(value string, versions []aiprompts.CategoryFormulaDefaults) bool {
markers := [][2]string{
{aiprompts.SectionTitleStart, aiprompts.SectionTitleEnd},
{aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd},
{aiprompts.SectionMetaStart, aiprompts.SectionMetaEnd},
}
if !aiprompts.CategoryEnhanceHasRoleSections(value) {
return false
}
// No unrecognized preamble, trailing content, or hidden custom section.
if strings.TrimSpace(strings.ReplaceAll(value, "\r\n", "\n")) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
TitleRules: aiprompts.ExtractEnhanceSectionBody(value, markers[0][0], markers[0][1]),
DescriptionRules: aiprompts.ExtractEnhanceSectionBody(value, markers[1][0], markers[1][1]),
MetaRules: aiprompts.ExtractEnhanceSectionBody(value, markers[2][0], markers[2][1]),
WasLegacy: true,
}) {
return false
}
for _, pair := range markers {
text := aiprompts.ExtractEnhanceSectionBody(value, pair[0], pair[1])
if text == "" {
return false
}
known := false
for _, ver := range versions {
if text == aiprompts.ExtractEnhanceSectionBody(ver.Overlay, pair[0], pair[1]) {
known = true
break
}
}
if !known {
return false
}
}
return true
}
// isKnownBuiltInVariantSet permits migrations from *mixed* released platform
// versions (for example, English from the old five-H2 default and German from
// the SEO-v4 release). Every non-empty language must match a known, exact
// built-in value. One company-authored field disqualifies the entire category.
// Cache lookups are read-only; no fuzzy matches on real tenant instructions.
func isKnownBuiltInVariantSet(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache map[string]*defaultTranslation) bool {
allowedEN := map[string]bool{}
allowedLocalized := map[string]map[string]bool{}
for _, version := range versions {
if version.Overlay == "" {
continue
}
allowedEN[strings.TrimSpace(version.Overlay)] = true
if entry := cache[catalog.DefaultPromptHash(version.Overlay)]; entry != nil {
for lang, val := range entry.Values {
if !company.IsAllowedLanguage(lang) || strings.TrimSpace(val) == "" {
continue
}
if lang == "en" {
allowedEN[strings.TrimSpace(val)] = true
continue
}
if allowedLocalized[lang] == nil {
allowedLocalized[lang] = map[string]bool{}
}
allowedLocalized[lang][strings.TrimSpace(val)] = true
}
}
}
for lang, val := range prompts {
val = strings.TrimSpace(val)
if val == "" {
continue
}
if lang == "*" || lang == "en" {
if !allowedEN[val] && !isMixedBuiltInEnglishPrompt(val, versions) {
return false
}
} else if !company.IsAllowedLanguage(lang) || !allowedLocalized[lang][val] {
return false
}
}
return true
}
// Only exact former built-in JSON is eligible for an upgrade, even when the
// prompt and formula columns happen to be from different older deployments.
func isKnownBuiltInFormula(current string, versions []aiprompts.CategoryFormulaDefaults, title bool) bool {
if matchesDefaultFormula(current, "") {
return true
}
for _, version := range versions {
compare := version.DescriptionTemplateJSON
if title {
compare = version.TitleTemplateJSON
}
if matchesDefaultFormula(current, compare) {
return true
}
}
return false
}
// upgradeOldDefault is scoped to a single category and guarded by an exact
// snapshot of its three current columns, so concurrent edits are not overwritten.
func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow, def aiprompts.CategoryFormulaDefaults, translations company.LangPromptMap) (bool, error) {
@@ -222,9 +326,58 @@ func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow,
return result.RowsAffected() > 0, err
}
// replaceKnownBuiltInLocales upgrades only exact released DEFAULT locale values.
// A1 can contain its own custom Slovenian category prompt alongside an old
// platform-generated English translation. Preserve its custom languages, name
// and meta formulas while replacing the old built-in English/other languages.
func replaceKnownBuiltInLocales(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache map[string]*defaultTranslation) int {
if len(versions) == 0 {
return 0
}
canonical := versions[0]
current := cache[catalog.DefaultPromptHash(canonical.Overlay)]
if current == nil {
return 0
}
updates := 0
for lang, text := range prompts {
val := strings.TrimSpace(text)
if val == "" {
continue
}
replacement := strings.TrimSpace(current.Values[lang])
if lang == "*" || lang == "en" {
replacement = canonical.Overlay
}
if replacement == "" || replacement == val {
continue
}
for _, prior := range versions[1:] {
if prior.Overlay == "" {
continue
}
old := prior.Overlay
if lang != "*" && lang != "en" {
entry := cache[catalog.DefaultPromptHash(prior.Overlay)]
if entry == nil {
continue
}
old = strings.TrimSpace(entry.Values[lang])
}
if (val == strings.TrimSpace(old) && old != "") ||
((lang == "*" || lang == "en") && isMixedBuiltInEnglishPrompt(val, versions)) {
prompts[lang] = replacement
updates++
break
}
}
}
return updates
}
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
// It neither translates nor changes A1 naming/meta instructions.
func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRow, dryRun bool) (int, bool, error) {
func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRow, cache map[string]*defaultTranslation, dryRun bool) (int, int, bool, error) {
next := make(company.LangPromptMap, len(row.Prompts))
removed := 0
for lang, value := range row.Prompts {
@@ -232,17 +385,23 @@ func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRo
next[lang] = cleaned
removed += n
}
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
versions := []aiprompts.CategoryFormulaDefaults{def,
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name)}
localesUpgraded := replaceKnownBuiltInLocales(next, versions, cache)
desc, n, err := aiprompts.NormalizeA1DescriptionTemplate(row.Desc)
if err != nil {
return 0, false, err
return 0, 0, false, err
}
removed += n
if removed == 0 || dryRun {
return removed, false, nil
if removed == 0 && localesUpgraded == 0 || dryRun {
return removed, localesUpgraded, false, nil
}
encoded, err := company.EncodeLangPromptMap(next)
if err != nil {
return removed, false, err
return removed, localesUpgraded, false, err
}
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
description_template = NULLIF($5,'')::jsonb, updated_at = now()
@@ -251,9 +410,9 @@ func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRo
AND COALESCE(description_template::text,'') = $6`,
row.ID, row.Company, string(row.Raw), string(encoded), desc, row.Desc)
if err != nil {
return removed, false, err
return removed, localesUpgraded, false, err
}
return removed, result.RowsAffected() == 1, nil
return removed, localesUpgraded, result.RowsAffected() == 1, nil
}
func main() {
@@ -320,6 +479,19 @@ func main() {
}
missing++
if *dryRun {
// Simulate bundled values in memory so the preview classifies
// existing mixed-language defaults exactly as the real run.
preview := source
if lang != "en" {
var previewErr error
preview, previewErr = aiprompts.OfflineDefaultPrompt(lang)
if previewErr != nil {
failures++
log.Printf("FAIL preview language=%s: %v", lang, previewErr)
continue
}
}
entry.Values[lang] = preview
continue
}
translated := source
@@ -358,19 +530,20 @@ func main() {
if err != nil {
log.Fatal(err)
}
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated := 0, 0, 0, 0, 0, 0, 0
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales := 0, 0, 0, 0, 0, 0, 0, 0
for _, row := range categories {
// A1 has its own Slovenian category instructions. Never apply the
// global platform-default backfill to this customer.
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
protected++
removed, updated, cleanErr := normalizeA1Category(ctx, pool, row, *dryRun)
removed, localized, updated, cleanErr := normalizeA1Category(ctx, pool, row, cache, *dryRun)
if cleanErr != nil {
failures++
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
} else {
a1Removed += removed
a1Locales += localized
if updated {
a1Updated++
}
@@ -384,7 +557,8 @@ func main() {
} // -limit pilot excludes some templates
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) {
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) &&
strings.TrimSpace(row.Title) != "" && strings.TrimSpace(row.Desc) != "" {
eligible++
if *dryRun {
continue
@@ -398,30 +572,17 @@ func main() {
}
continue
}
// Upgrade ONLY exact platform-generated copies, including the prior
// offline release. Custom company instructions are never replaced.
foundPrevious := false
for _, previous := range []aiprompts.CategoryFormulaDefaults{
// Upgrade *only* built-in snapshots, including mixed versions left by
// prior migrations. Never touch any tenant-authored language or formula.
versions := []aiprompts.CategoryFormulaDefaults{
def,
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name),
} {
if previous.Overlay == "" || previous.Overlay == def.Overlay {
continue
}
oldEntry := cache[catalog.DefaultPromptHash(previous.Overlay)]
oldTranslations := company.LangPromptMap{}
if oldEntry != nil {
oldTranslations = oldEntry.Values
}
if !catalog.IsUntouchedDefaultPrompt(row.Prompts, previous.Overlay, oldTranslations) ||
!matchesDefaultFormula(row.Title, previous.TitleTemplateJSON) ||
!matchesDefaultFormula(row.Desc, previous.DescriptionTemplateJSON) {
continue
}
foundPrevious = true
break
}
if !foundPrevious {
if !isKnownBuiltInVariantSet(row.Prompts, versions, cache) ||
!isKnownBuiltInFormula(row.Title, versions, true) ||
!isKnownBuiltInFormula(row.Desc, versions, false) {
custom++
continue
}
@@ -440,7 +601,7 @@ func main() {
}
}
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Updated, failures, *dryRun)
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_default_locales_upgraded=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, failures, *dryRun)
if *dryRun && missing > 0 {
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
}
@@ -9,47 +9,31 @@ import (
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
)
func TestSeedLanguagesAllSupported(t *testing.T) {
codes, err := langsToSeed("")
if err != nil || len(codes) != len(company.ContentLanguages) {
t.Fatalf("languages %v error %v", codes, err)
func TestDefaultMigrationRecognizesMixedLegacyEnglishWithoutTouchingCustom(t *testing.T) {
current := aiprompts.DefaultCategoryFormula("", "High chairs")
old := aiprompts.PriorDefaultCategoryFormula("", "High chairs")
seo := aiprompts.PreviousSEODefaultCategoryFormula("", "High chairs")
variants := []aiprompts.CategoryFormulaDefaults{current, seo, old, aiprompts.LegacyDefaultCategoryFormula("", "High chairs")}
mixed := strings.Replace(current.Overlay,
aiprompts.DescriptionSectionInstructions(current.Overlay),
aiprompts.DescriptionSectionInstructions(old.Overlay), 1)
if !isMixedBuiltInEnglishPrompt(mixed, variants) {
t.Fatal("old English five-section mixed default was not recognized")
}
if _, err := langsToSeed("invalid"); err == nil {
t.Fatal("invalid language accepted")
}
}
func TestOnlyPlatformDefaultsAreEligible(t *testing.T) {
source := aiprompts.GenericCategoryFormula().Overlay
translations := company.LangPromptMap{"de": "German default"}
eligible := categoryRow{Prompts: company.LangPromptMap{"*": source}}
if !catalog.IsUntouchedDefaultPrompt(eligible.Prompts, source, translations) {
t.Fatal("default should be eligible")
}
custom := categoryRow{Prompts: company.LangPromptMap{"*": source, "de": "tenant customized the prompt"}}
if catalog.IsUntouchedDefaultPrompt(custom.Prompts, source, translations) {
t.Fatal("custom prompt must be protected")
}
}
func TestOfflineDefaultCoverage(t *testing.T) {
for _, lang := range company.ContentLanguages {
if lang == "en" {
continue
} // English uses exact source text.
text, err := aiprompts.OfflineDefaultPrompt(lang)
if err != nil || strings.TrimSpace(text) == "" {
t.Fatalf("missing bundled language %s: %v", lang, err)
}
}
}
func TestStructuredCustomFormulasRemainProtected(t *testing.T) {
defaultTitle := `{"mode":"formula","productType":"lowercase"}`
if !matchesDefaultFormula(defaultTitle, defaultTitle) {
t.Fatal("matching default formula not recognized")
}
if matchesDefaultFormula(`{"mode":"formula","productType":"uppercase"}`, defaultTitle) {
t.Fatal("company-authored title formula must be protected")
cache := map[string]*defaultTranslation{
catalog.DefaultPromptHash(current.Overlay): {Source: current.Overlay, Values: company.LangPromptMap{"en": current.Overlay}},
catalog.DefaultPromptHash(old.Overlay): {Source: old.Overlay, Values: company.LangPromptMap{"en": old.Overlay}},
}
if !isKnownBuiltInVariantSet(company.LangPromptMap{"en": mixed}, variants, cache) {
t.Fatal("mixed, unedited platform default was flagged custom")
}
bad := strings.Replace(mixed, "--- Meta ---", "--- Meta ---\nUse my shop's custom brand voice", 1)
if isKnownBuiltInVariantSet(company.LangPromptMap{"en": bad}, variants, cache) {
t.Fatal("custom tenant meta text must remain protected")
}
a1 := company.LangPromptMap{"sl": "A1 custom Slovenian naming, meta, and description", "en": mixed}
changed := replaceKnownBuiltInLocales(a1, variants, cache)
if changed != 1 || a1["sl"] != "A1 custom Slovenian naming, meta, and description" || a1["en"] != current.Overlay {
t.Fatalf("A1 locale migration touched custom data: changed=%d, en=%q, sl=%q", changed, a1["en"], a1["sl"])
}
}
@@ -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")
@@ -38,8 +38,8 @@ func TestIsUntouchedDefaultPrompt(t *testing.T) {
func TestDefaultPromptSourcesCoverGenericAndTaxonomy(t *testing.T) {
all := aiprompts.AllDefaultCategoryPrompts()
if len(all) < 100 {
t.Fatalf("expected embedded taxonomy + generic, got %d", len(all))
if len(all) != 1 {
t.Fatalf("expected one shared canonical source for all categories, got %d", len(all))
}
generic := aiprompts.GenericCategoryFormula().Overlay
found := false
@@ -150,3 +150,19 @@ func TestRunSteps_defaultFormulaDrivesGeneration(t *testing.T) {
}
_ = company.DefaultLanguage
}
// Without a stored category prompt, fallback content must still use the target
// product's language, not default to old English HTML instructions.
func TestWithDefaultCategoryFormula_localizedFallback(t *testing.T) {
for _, lang := range []string{"en", "hr", "sl", "de", "ja"} {
input := ProductInput{CategoryUniqueID: "grohe", CategoryDisplayName: "Bathroom faucets", Language: lang}
got := withDefaultCategoryFormula(input)
expected, err := aiprompts.OfflineDefaultPrompt(lang)
if err != nil {
t.Fatal(err)
}
if got.CategoryEnhancePrompt != expected {
t.Fatalf("%s fallback uses wrong language", lang)
}
}
}
@@ -95,7 +95,14 @@ func withDefaultCategoryFormula(in ProductInput) ProductInput {
if def.Overlay == "" {
return in
}
// The language selected for product processing must also select the
// formula language, even when this is an uncached legacy category.
in.CategoryEnhancePrompt = def.Overlay
if lang := company.NormalizeLanguage(in.Language); company.IsAllowedLanguage(lang) {
if localized, err := aiprompts.OfflineDefaultPrompt(lang); err == nil {
in.CategoryEnhancePrompt = localized
}
}
if in.TitleTemplate == nil && def.TitleTemplateJSON != "" {
in.TitleTemplate = decodeOptionalJSONObject([]byte(def.TitleTemplateJSON))
}