From af670e79f00c49635af936c60676e9e849a48dfc Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Wed, 14 Oct 2026 20:54:29 +0200 Subject: [PATCH] fixes --- README.md | 16 ++ .../seed-category-prompt-translations/main.go | 223 +++++++++++++++++- .../main_test.go | 119 ++++++++++ .../aiprompts/defaults/prompt-rules-v3.json | 127 ++++++++++ .../aiprompts/offline_translations.go | 20 ++ .../internal/aiprompts/seo_locales_test.go | 18 ++ .../src/lib/category-prompt-examples.test.ts | 14 ++ docs/seo-prompts-all-25-languages.md | 206 ++++++++-------- docs/seo-prompts-v8.md | 28 +++ 9 files changed, 667 insertions(+), 104 deletions(-) create mode 100644 apps/api/internal/aiprompts/defaults/prompt-rules-v3.json create mode 100644 docs/seo-prompts-v8.md diff --git a/README.md b/README.md index 7832812..61e322d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,19 @@ +# v8 fix — existing non-A1 language prompts + +This update addresses the remaining English/Croatian/Bulgarian mismatch in existing non-A1 categories. It includes the exact historical v3 locale snapshots, so the seed can identify the old five-section translations and upgrade them **without overriding custom company instructions**. It also updates any exact old structured description formula that would otherwise force the AI to output five H2 sections. + +**Run after deploying API + worker + frontend**: + +```bash +npm run migrate +npm run seed:category-prompts:i18n -- -dry-run +npm run seed:category-prompts:i18n +``` + +Check `legacy_upgraded` and `non_a1_legacy_locales_repaired` in the seed output, then reload the category editor. No OpenAI key is needed for the seed. See `docs/seo-prompts-v8.md` and `docs/seo-prompts-all-25-languages.md`. + +--- + > **Prompt hotfix v7 (October 2026):** Fixed the API/worker Go compile error, normalized all 25 languages to brace-delimited SEO title/HTML description/meta instructions, and corrected the offline seed's stale shared cache and v6 legacy migration. A1's obsolete meta rule is upgraded, and A1 SEO meta is no longer silently discarded. Run `npm run migrate` then `npm run seed:category-prompts:i18n`. See [docs/seo-prompts-v7.md](docs/seo-prompts-v7.md). # Descrybe v2 diff --git a/apps/api/cmd/seed-category-prompt-translations/main.go b/apps/api/cmd/seed-category-prompt-translations/main.go index 39ffa6d..caef809 100644 --- a/apps/api/cmd/seed-category-prompt-translations/main.go +++ b/apps/api/cmd/seed-category-prompt-translations/main.go @@ -285,6 +285,11 @@ func isKnownBuiltInVariantSet(prompts company.LangPromptMap, versions []aiprompt } } for lang, val := range prompts { + // The v3 localized plain-text template was not in the v6 migration + // allowlist, which left non-A1 companies using five 100-word sections. + if isExactOldDefaultLanguage(val, lang, versions, cache, historical) { + continue + } val = strings.TrimSpace(val) if val == "" { continue @@ -346,6 +351,196 @@ func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow, return result.RowsAffected() > 0, err } +// isExactOldDefaultLanguage recognizes prior SHIPPED locale values, including +// the v3 plain-text Croatian/Bulgarian instructions that the old migrations +// missed. It never matches arbitrary text by language, length or keywords. +func isExactOldDefaultLanguage(value, lang string, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation) bool { + value = strings.TrimSpace(value) + if value == "" { + return false + } + if old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang); err == nil && value == old { + return true + } + if old, err := aiprompts.PreviousOfflineDefaultPromptV6(lang); err == nil && value == old { + return true + } + if lang != "*" && lang != "en" { + for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} { + old, err := oldFn(lang) + if err == nil && value == aiprompts.ExtractEnhanceSectionBody(old, aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd) { + return true + } + } + } + for _, prior := range versions { + if prior.Overlay == "" { + continue + } + if (lang == "*" || lang == "en") && value == strings.TrimSpace(prior.Overlay) { + return true + } + for _, old := range knownCacheValues(prior.Overlay, cache, historical, lang) { + if value == strings.TrimSpace(old) { + return true + } + } + } + return false +} + +// patchKnownRoleSections upgrades a matching old default ROLE, even when the +// company customized an unrelated role (e.g. title). The custom role remains +// unchanged. Only exact bundled historical strings qualify for replacement. +func patchKnownRoleSections(value, lang, replacement string, versions []aiprompts.CategoryFormulaDefaults) (string, bool) { + if !aiprompts.CategoryEnhanceHasRoleSections(value) || !aiprompts.CategoryEnhanceHasRoleSections(replacement) { + return "", false + } + extract := func(prompt, start, end string) string { + return aiprompts.ExtractEnhanceSectionBody(prompt, start, end) + } + starts := [3]string{aiprompts.SectionTitleStart, aiprompts.SectionDescriptionStart, aiprompts.SectionMetaStart} + ends := [3]string{aiprompts.SectionTitleEnd, aiprompts.SectionDescriptionEnd, aiprompts.SectionMetaEnd} + oldParts := [3]string{} + for i := range starts { + oldParts[i] = extract(value, starts[i], ends[i]) + } + // Do not normalize a prompt containing preambles, extra text, or custom markup. + if strings.TrimSpace(value) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{ + TitleRules: oldParts[0], DescriptionRules: oldParts[1], MetaRules: oldParts[2], WasLegacy: true, + }) { + return "", false + } + parts := oldParts + changed := false + for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} { + old, err := oldFn(lang) + if err != nil { + continue + } + for i := range starts { + prev := extract(old, starts[i], ends[i]) + newText := extract(replacement, starts[i], ends[i]) + if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText { + parts[i] = newText + changed = true + } + } + } + // Older English categories used category-specific built-in naming with + // the five-H2 boilerplate. Match only shipped role text; never guess by + // counting H2s or searching for marketing words. + if lang == "en" { + for _, prior := range versions[1:] { + if prior.Overlay == "" { + continue + } + for i := range starts { + prev := extract(prior.Overlay, starts[i], ends[i]) + newText := extract(replacement, starts[i], ends[i]) + if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText { + parts[i] = newText + changed = true + } + } + } + } + if !changed { + return "", false + } + return aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{ + TitleRules: parts[0], DescriptionRules: parts[1], MetaRules: parts[2], WasLegacy: true, + }), true +} + +// repairOldLocaleDefaults upgrades specific released default values without +// relying on the other language entries or the title/description JSON columns. +// This is deliberately separate from the all-or-nothing category upgrade: an +// unrelated custom locale or formula must not prevent safe default repairs. +func repairOldLocaleDefaults(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation, targetLangs []string) (company.LangPromptMap, int) { + allowed := map[string]bool{} + for _, lang := range targetLangs { + allowed[lang] = true + } + next := make(company.LangPromptMap, len(prompts)) + updates := 0 + for lang, value := range prompts { + next[lang] = value + if lang != "*" && !allowed[lang] { + continue + } + locale := lang + if lang == "*" { + locale = "en" + if !allowed[locale] { + continue + } + } + replacement, err := aiprompts.OfflineDefaultPrompt(locale) + if err != nil { + continue + } + if lang == "*" || lang == "en" { + replacement = versions[0].Overlay + } + if strings.TrimSpace(replacement) == strings.TrimSpace(value) { + continue + } + if isExactOldDefaultLanguage(value, lang, versions, cache, historical) { + next[lang] = replacement + updates++ + } else if patched, ok := patchKnownRoleSections(value, locale, replacement, versions); ok { + next[lang] = patched + updates++ + } + } + return next, updates +} + +// repairOldFormulaField replaces an exact known platform JSON formula, leaving +// edited company formulas untouched. A language-agnostic old HTML constraint +// can otherwise override an already-migrated localized prompt in the API. +func repairOldFormulaField(value string, versions []aiprompts.CategoryFormulaDefaults, title bool) (string, bool) { + if len(versions) < 2 { + return value, false + } + current := versions[0].DescriptionTemplateJSON + if title { + current = versions[0].TitleTemplateJSON + } + if matchesDefaultFormula(value, current) { + return value, false + } + for _, old := range versions[1:] { + previous := old.DescriptionTemplateJSON + if title { + previous = old.TitleTemplateJSON + } + if previous != "" && matchesDefaultFormula(value, previous) { + return current, true + } + } + return value, false +} + +// persistRepairedDefaults applies a compare-and-swap update to all three +// columns, even when only a single field changed. Racing admin edits are safe. +func persistRepairedDefaults(ctx context.Context, pool *pgxpool.Pool, row categoryRow, next company.LangPromptMap, title, description string) (bool, error) { + encoded, err := company.EncodeLangPromptMap(next) + if err != nil { + return false, err + } + result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb, + title_template = NULLIF($5, '')::jsonb, + description_template = NULLIF($6, '')::jsonb, + updated_at = now() + WHERE id = $1 AND company_id = $2 AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb + AND COALESCE(title_template::text, '') = $7 + AND COALESCE(description_template::text, '') = $8`, + row.ID, row.Company, string(row.Raw), string(encoded), title, description, row.Title, row.Desc) + return result.RowsAffected() == 1, 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 @@ -388,6 +583,9 @@ func replaceKnownBuiltInLocales(prompts company.LangPromptMap, versions []aiprom matched = true } } + if !matched && isExactOldDefaultLanguage(val, lang, versions, cache, historical) { + matched = true + } if matched { prompts[lang] = replacement updates++ @@ -582,7 +780,7 @@ func main() { if err != nil { log.Fatal(err) } - eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales := 0, 0, 0, 0, 0, 0, 0, 0 + eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales, localeRepaired := 0, 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. @@ -636,6 +834,27 @@ func main() { if !isKnownBuiltInVariantSet(row.Prompts, versions, cache, historical) || !isKnownBuiltInFormula(row.Title, versions, true) || !isKnownBuiltInFormula(row.Desc, versions, false) { + // Repair only exact-match *shipped* defaults when a different + // language or a structured formula was intentionally customized. + next, repaired := repairOldLocaleDefaults(row.Prompts, versions, cache, historical, targetLangs) + title, repairedTitle := repairOldFormulaField(row.Title, versions, true) + desc, repairedDesc := repairOldFormulaField(row.Desc, versions, false) + if repaired != 0 || repairedTitle || repairedDesc { + eligible++ + if *dryRun { + localeRepaired += repaired + continue + } + updated, updateErr := persistRepairedDefaults(ctx, pool, row, next, title, desc) + if updateErr != nil { + failures++ + log.Printf("FAIL repairing default locales company=%s category=%s: %v", row.Company, row.UID, updateErr) + } else if updated { + changed++ + localeRepaired += repaired + } + continue + } custom++ continue } @@ -654,7 +873,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_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) + 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 non_a1_legacy_locales_repaired=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, localeRepaired, failures, *dryRun) if *dryRun && missing > 0 { log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM") } diff --git a/apps/api/cmd/seed-category-prompt-translations/main_test.go b/apps/api/cmd/seed-category-prompt-translations/main_test.go index abe50cf..fe43420 100644 --- a/apps/api/cmd/seed-category-prompt-translations/main_test.go +++ b/apps/api/cmd/seed-category-prompt-translations/main_test.go @@ -68,3 +68,122 @@ func TestV6SharedCacheMigrationUsesHistoricalExactStrings(t *testing.T) { t.Fatal("custom company locale overwritten") } } + +// Reproduces the non-A1 records from the production report: the v3 seed +// generated only a translated paragraph of five-H2 instructions in hr/bg, +// while the English company variant still used five literal HTML H2 blocks. +func TestV3NonA1DescriptionMigrationAcrossAll25Languages(t *testing.T) { + canonical := aiprompts.DefaultCategoryFormula("", "Bathroom mixers") + prior := aiprompts.PriorDefaultCategoryFormula("", "Bathroom mixers") + versions := []aiprompts.CategoryFormulaDefaults{canonical, prior} + oldPrompts := company.LangPromptMap{} + for _, lang := range company.ContentLanguages { + old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang) + if err != nil { + t.Fatal(err) + } + oldPrompts[lang] = old + } + oldPrompts["*"] = prior.Overlay + // A manually customized German description must remain untouched. + oldPrompts["de"] = "--- Title ---\nMein Shop Titel\n--- End Title ---\n\n--- Description ---\nEigenes Unternehmen\n--- End Description ---\n\n--- Meta ---\nMeine Meta\n--- End Meta ---" + got, count := repairOldLocaleDefaults(oldPrompts, versions, nil, nil, company.ContentLanguages) + if count != len(company.ContentLanguages) { // 24 translated + wildcard; custom de untouched + t.Fatalf("repaired %d entries; want %d", count, len(company.ContentLanguages)) + } + if got["de"] != oldPrompts["de"] { + t.Fatal("custom German company formula overwritten") + } + for _, lang := range company.ContentLanguages { + if lang == "de" { + continue + } + expected, err := aiprompts.OfflineDefaultPrompt(lang) + if err != nil { + t.Fatal(err) + } + if lang == "en" { + expected = canonical.Overlay + } + if got[lang] != expected { + t.Fatalf("%s retained obsolete default", lang) + } + body := aiprompts.DescriptionSectionInstructions(got[lang]) + if strings.Count(body, "

{") != 2 || strings.Count(body, "

{") != 2 || strings.Count(body, "

'), lang); + assert.doesNotMatch(description, /100 words|100 riječi|100 думи/, lang); + } + }); +}); diff --git a/docs/seo-prompts-all-25-languages.md b/docs/seo-prompts-all-25-languages.md index ebc83a2..f989853 100644 --- a/docs/seo-prompts-all-25-languages.md +++ b/docs/seo-prompts-all-25-languages.md @@ -1,16 +1,18 @@ -# Bundled category SEO formulas — all 25 content languages +# Canonical product SEO formulas — all 25 languages -These are offline application defaults. `{}` delimits instructions, `{{...}}` denotes a product-data variable, and HTML tags specify output structure. The description is not a rendered product description. +These are the actual bundled defaults loaded by `OfflineDefaultPrompt` and the frontend. Every language uses the identical HTML skeleton: `

`, optional `

`, optional `