fixes
This commit is contained in:
1 parent
3b0d692839
commit
8b540d22bc
14 files changed
+526
-82
No files matched your search
@@ -1,3 +1,5 @@
|
|||||||
|
> **Latest update (October 2026):** All 25 platform default category prompt languages now use the same canonical title/HTML description/SEO meta formula. Run `npm run seed:category-prompts:i18n` after `npm run migrate` to upgrade old untouched defaults, including old English five-H2 templates. No translation LLM or API key is required. See [docs/canonical-product-prompts-v6.md](docs/canonical-product-prompts-v6.md).
|
||||||
|
|
||||||
# Descrybe v2
|
# Descrybe v2
|
||||||
|
|
||||||
Go API + SvelteKit frontend + PostgreSQL rewrite of Descrybe (no Clerk).
|
Go API + SvelteKit frontend + PostgreSQL rewrite of Descrybe (no Clerk).
|
||||||
|
|||||||
@@ -194,6 +194,110 @@ func matchesDefaultFormula(current, previous string) bool {
|
|||||||
return string(left) == string(right)
|
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
|
// upgradeOldDefault is scoped to a single category and guarded by an exact
|
||||||
// snapshot of its three current columns, so concurrent edits are not overwritten.
|
// 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) {
|
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
|
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.
|
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
|
||||||
// It neither translates nor changes A1 naming/meta 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))
|
next := make(company.LangPromptMap, len(row.Prompts))
|
||||||
removed := 0
|
removed := 0
|
||||||
for lang, value := range row.Prompts {
|
for lang, value := range row.Prompts {
|
||||||
@@ -232,17 +385,23 @@ func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRo
|
|||||||
next[lang] = cleaned
|
next[lang] = cleaned
|
||||||
removed += n
|
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)
|
desc, n, err := aiprompts.NormalizeA1DescriptionTemplate(row.Desc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, false, err
|
return 0, 0, false, err
|
||||||
}
|
}
|
||||||
removed += n
|
removed += n
|
||||||
if removed == 0 || dryRun {
|
if removed == 0 && localesUpgraded == 0 || dryRun {
|
||||||
return removed, false, nil
|
return removed, localesUpgraded, false, nil
|
||||||
}
|
}
|
||||||
encoded, err := company.EncodeLangPromptMap(next)
|
encoded, err := company.EncodeLangPromptMap(next)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return removed, false, err
|
return removed, localesUpgraded, false, err
|
||||||
}
|
}
|
||||||
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||||
description_template = NULLIF($5,'')::jsonb, updated_at = now()
|
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`,
|
AND COALESCE(description_template::text,'') = $6`,
|
||||||
row.ID, row.Company, string(row.Raw), string(encoded), desc, row.Desc)
|
row.ID, row.Company, string(row.Raw), string(encoded), desc, row.Desc)
|
||||||
if err != nil {
|
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() {
|
func main() {
|
||||||
@@ -320,6 +479,19 @@ func main() {
|
|||||||
}
|
}
|
||||||
missing++
|
missing++
|
||||||
if *dryRun {
|
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
|
continue
|
||||||
}
|
}
|
||||||
translated := source
|
translated := source
|
||||||
@@ -358,19 +530,20 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
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 {
|
for _, row := range categories {
|
||||||
// A1 has its own Slovenian category instructions. Never apply the
|
// A1 has its own Slovenian category instructions. Never apply the
|
||||||
// global platform-default backfill to this customer.
|
// global platform-default backfill to this customer.
|
||||||
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
|
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
|
||||||
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
|
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
|
||||||
protected++
|
protected++
|
||||||
removed, updated, cleanErr := normalizeA1Category(ctx, pool, row, *dryRun)
|
removed, localized, updated, cleanErr := normalizeA1Category(ctx, pool, row, cache, *dryRun)
|
||||||
if cleanErr != nil {
|
if cleanErr != nil {
|
||||||
failures++
|
failures++
|
||||||
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
|
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
|
||||||
} else {
|
} else {
|
||||||
a1Removed += removed
|
a1Removed += removed
|
||||||
|
a1Locales += localized
|
||||||
if updated {
|
if updated {
|
||||||
a1Updated++
|
a1Updated++
|
||||||
}
|
}
|
||||||
@@ -384,7 +557,8 @@ func main() {
|
|||||||
} // -limit pilot excludes some templates
|
} // -limit pilot excludes some templates
|
||||||
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
|
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
|
||||||
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
|
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
|
||||||
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) {
|
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) &&
|
||||||
|
strings.TrimSpace(row.Title) != "" && strings.TrimSpace(row.Desc) != "" {
|
||||||
eligible++
|
eligible++
|
||||||
if *dryRun {
|
if *dryRun {
|
||||||
continue
|
continue
|
||||||
@@ -398,30 +572,17 @@ func main() {
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Upgrade ONLY exact platform-generated copies, including the prior
|
// Upgrade *only* built-in snapshots, including mixed versions left by
|
||||||
// offline release. Custom company instructions are never replaced.
|
// prior migrations. Never touch any tenant-authored language or formula.
|
||||||
foundPrevious := false
|
versions := []aiprompts.CategoryFormulaDefaults{
|
||||||
for _, previous := range []aiprompts.CategoryFormulaDefaults{
|
def,
|
||||||
|
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
|
||||||
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
||||||
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name),
|
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name),
|
||||||
} {
|
|
||||||
if previous.Overlay == "" || previous.Overlay == def.Overlay {
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
oldEntry := cache[catalog.DefaultPromptHash(previous.Overlay)]
|
if !isKnownBuiltInVariantSet(row.Prompts, versions, cache) ||
|
||||||
oldTranslations := company.LangPromptMap{}
|
!isKnownBuiltInFormula(row.Title, versions, true) ||
|
||||||
if oldEntry != nil {
|
!isKnownBuiltInFormula(row.Desc, versions, false) {
|
||||||
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 {
|
|
||||||
custom++
|
custom++
|
||||||
continue
|
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 {
|
if *dryRun && missing > 0 {
|
||||||
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
|
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"
|
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSeedLanguagesAllSupported(t *testing.T) {
|
func TestDefaultMigrationRecognizesMixedLegacyEnglishWithoutTouchingCustom(t *testing.T) {
|
||||||
codes, err := langsToSeed("")
|
current := aiprompts.DefaultCategoryFormula("", "High chairs")
|
||||||
if err != nil || len(codes) != len(company.ContentLanguages) {
|
old := aiprompts.PriorDefaultCategoryFormula("", "High chairs")
|
||||||
t.Fatalf("languages %v error %v", codes, err)
|
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 {
|
cache := map[string]*defaultTranslation{
|
||||||
t.Fatal("invalid language accepted")
|
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) {
|
||||||
func TestOnlyPlatformDefaultsAreEligible(t *testing.T) {
|
t.Fatal("mixed, unedited platform default was flagged custom")
|
||||||
source := aiprompts.GenericCategoryFormula().Overlay
|
}
|
||||||
translations := company.LangPromptMap{"de": "German default"}
|
bad := strings.Replace(mixed, "--- Meta ---", "--- Meta ---\nUse my shop's custom brand voice", 1)
|
||||||
eligible := categoryRow{Prompts: company.LangPromptMap{"*": source}}
|
if isKnownBuiltInVariantSet(company.LangPromptMap{"en": bad}, variants, cache) {
|
||||||
if !catalog.IsUntouchedDefaultPrompt(eligible.Prompts, source, translations) {
|
t.Fatal("custom tenant meta text must remain protected")
|
||||||
t.Fatal("default should be eligible")
|
}
|
||||||
}
|
a1 := company.LangPromptMap{"sl": "A1 custom Slovenian naming, meta, and description", "en": mixed}
|
||||||
custom := categoryRow{Prompts: company.LangPromptMap{"*": source, "de": "tenant customized the prompt"}}
|
changed := replaceKnownBuiltInLocales(a1, variants, cache)
|
||||||
if catalog.IsUntouchedDefaultPrompt(custom.Prompts, source, translations) {
|
if changed != 1 || a1["sl"] != "A1 custom Slovenian naming, meta, and description" || a1["en"] != current.Overlay {
|
||||||
t.Fatal("custom prompt must be protected")
|
t.Fatalf("A1 locale migration touched custom data: changed=%d, en=%q, sl=%q", changed, a1["en"], a1["sl"])
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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
|
defaultFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
legacyFormulaByKey map[string]CategoryFormulaDefaults
|
legacyFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
priorFormulaByKey map[string]CategoryFormulaDefaults
|
priorFormulaByKey map[string]CategoryFormulaDefaults
|
||||||
|
seoV4FormulaByKey map[string]CategoryFormulaDefaults
|
||||||
legacyFormulaGeneric CategoryFormulaDefaults
|
legacyFormulaGeneric CategoryFormulaDefaults
|
||||||
priorFormulaGeneric CategoryFormulaDefaults
|
priorFormulaGeneric CategoryFormulaDefaults
|
||||||
|
seoV4FormulaGeneric CategoryFormulaDefaults
|
||||||
defaultFormulaGeneric CategoryFormulaDefaults
|
defaultFormulaGeneric CategoryFormulaDefaults
|
||||||
defaultFormulaCount int
|
defaultFormulaCount int
|
||||||
)
|
)
|
||||||
|
|
||||||
func loadDefaultCategoryFormulas() {
|
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)
|
legacyFormulaGeneric = buildCategoryFormulaDefaults("", LegacyGenericDefaultCategoryPrompt)
|
||||||
priorFormulaGeneric = buildCategoryFormulaDefaults("", PriorGenericDefaultCategoryPrompt)
|
priorFormulaGeneric = buildCategoryFormulaDefaults("", PriorGenericDefaultCategoryPrompt)
|
||||||
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
|
defaultFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
legacyFormulaByKey = map[string]CategoryFormulaDefaults{}
|
legacyFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
priorFormulaByKey = map[string]CategoryFormulaDefaults{}
|
priorFormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
seoV4FormulaByKey = map[string]CategoryFormulaDefaults{}
|
||||||
|
|
||||||
var f defaultCategoryPromptsFile
|
var f defaultCategoryPromptsFile
|
||||||
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
|
if err := json.Unmarshal(defaultCategoryPromptsJSON, &f); err != nil {
|
||||||
@@ -166,6 +176,13 @@ func loadDefaultCategoryFormulas() {
|
|||||||
// description and meta structure across the platform defaults.
|
// description and meta structure across the platform defaults.
|
||||||
parts := ParseLegacyCombinedEnhancePrompt(prompt)
|
parts := ParseLegacyCombinedEnhancePrompt(prompt)
|
||||||
base := ParseLegacyCombinedEnhancePrompt(GenericDefaultCategoryPrompt)
|
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)
|
priorBase := ParseLegacyCombinedEnhancePrompt(PriorGenericDefaultCategoryPrompt)
|
||||||
priorParts := parts
|
priorParts := parts
|
||||||
priorParts.DescriptionRules = priorBase.DescriptionRules
|
priorParts.DescriptionRules = priorBase.DescriptionRules
|
||||||
@@ -176,7 +193,7 @@ func loadDefaultCategoryFormulas() {
|
|||||||
if parts.TitleRules == "" {
|
if parts.TitleRules == "" {
|
||||||
parts.TitleRules = base.TitleRules
|
parts.TitleRules = base.TitleRules
|
||||||
}
|
}
|
||||||
res := buildCategoryFormulaDefaultsFromParts(strings.TrimSpace(e.Name), parts)
|
res := buildCanonicalCategoryFormulaDefaults(strings.TrimSpace(e.Name), canonical)
|
||||||
if res.Overlay == "" {
|
if res.Overlay == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -186,11 +203,73 @@ func loadDefaultCategoryFormulas() {
|
|||||||
defaultFormulaByKey[k] = res
|
defaultFormulaByKey[k] = res
|
||||||
legacyFormulaByKey[k] = legacy
|
legacyFormulaByKey[k] = legacy
|
||||||
priorFormulaByKey[k] = priorFormula
|
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 {
|
func buildCategoryFormulaDefaults(name, legacyPrompt string) CategoryFormulaDefaults {
|
||||||
parts := ParseLegacyCombinedEnhancePrompt(legacyPrompt)
|
parts := ParseLegacyCombinedEnhancePrompt(legacyPrompt)
|
||||||
if !parts.WasLegacy {
|
if !parts.WasLegacy {
|
||||||
@@ -207,7 +286,7 @@ func buildCategoryFormulaDefaultsFromParts(name string, parts LegacyEnhanceParts
|
|||||||
desc := DeriveDescriptionFormulaFromLegacyParts(parts)
|
desc := DeriveDescriptionFormulaFromLegacyParts(parts)
|
||||||
// The derivation seeds a Slovenian meta-title rule for legacy A1 dumps; these
|
// 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.
|
// 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
|
desc.MetaTitle = DefaultMetaTitleRuleEN
|
||||||
}
|
}
|
||||||
if len(desc.Sections) > 0 || desc.MetaTitle != "" || desc.MetaDescription != "" {
|
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.
|
// 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, ",") {
|
if strings.Join(vars, ",") != strings.Join(want, ",") {
|
||||||
t.Fatalf("title slots = %v want %v", vars, want)
|
t.Fatalf("title slots = %v want %v", vars, want)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -250,7 +250,12 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
|
|||||||
if isBuiltInMetaRoleBoilerplate(metaBody) {
|
if isBuiltInMetaRoleBoilerplate(metaBody) {
|
||||||
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.MetaDescription = strings.TrimSpace(metaBody)
|
||||||
out.MetaTitle = DefaultLegacyMetaTitleRule
|
out.MetaTitle = DefaultLegacyMetaTitleRule
|
||||||
} else {
|
} else {
|
||||||
@@ -264,6 +269,28 @@ func EffectiveDescriptionFormula(stored any, categoryPrompt string) DescriptionF
|
|||||||
return out
|
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 {
|
func isBuiltInMetaRoleBoilerplate(body string) bool {
|
||||||
lower := strings.ToLower(strings.TrimSpace(body))
|
lower := strings.ToLower(strings.TrimSpace(body))
|
||||||
return strings.HasPrefix(lower, "role: meta")
|
return strings.HasPrefix(lower, "role: meta")
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ func TestIsUntouchedDefaultPrompt(t *testing.T) {
|
|||||||
|
|
||||||
func TestDefaultPromptSourcesCoverGenericAndTaxonomy(t *testing.T) {
|
func TestDefaultPromptSourcesCoverGenericAndTaxonomy(t *testing.T) {
|
||||||
all := aiprompts.AllDefaultCategoryPrompts()
|
all := aiprompts.AllDefaultCategoryPrompts()
|
||||||
if len(all) < 100 {
|
if len(all) != 1 {
|
||||||
t.Fatalf("expected embedded taxonomy + generic, got %d", len(all))
|
t.Fatalf("expected one shared canonical source for all categories, got %d", len(all))
|
||||||
}
|
}
|
||||||
generic := aiprompts.GenericCategoryFormula().Overlay
|
generic := aiprompts.GenericCategoryFormula().Overlay
|
||||||
found := false
|
found := false
|
||||||
|
|||||||
@@ -150,3 +150,19 @@ func TestRunSteps_defaultFormulaDrivesGeneration(t *testing.T) {
|
|||||||
}
|
}
|
||||||
_ = company.DefaultLanguage
|
_ = 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 == "" {
|
if def.Overlay == "" {
|
||||||
return in
|
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
|
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 != "" {
|
if in.TitleTemplate == nil && def.TitleTemplateJSON != "" {
|
||||||
in.TitleTemplate = decodeOptionalJSONObject([]byte(def.TitleTemplateJSON))
|
in.TitleTemplate = decodeOptionalJSONObject([]byte(def.TitleTemplateJSON))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Read-only localized examples, generated from the same 25-language JSON
|
* GENERATED from apps/api/internal/aiprompts/defaults/prompt-rules-25.json.
|
||||||
* bundled in the API. Category overrides are never written automatically.
|
* Run: node scripts/seed/build-category-ui-examples.mjs
|
||||||
|
* Read-only preview data; never writes category prompts automatically.
|
||||||
*/
|
*/
|
||||||
import { DEFAULT_CONTENT_LANGUAGE, parseContentLanguage } from '../content-languages.ts';
|
import { DEFAULT_CONTENT_LANGUAGE, parseContentLanguage } from '../content-languages.ts';
|
||||||
import type { EnhancePromptSectionId } from './prompt-sections';
|
import type { EnhancePromptSectionId } from './prompt-sections';
|
||||||
|
|||||||
@@ -35,3 +35,15 @@ describe('localized category prompt SEO formulas', () => {
|
|||||||
assert.notEqual(hr, en);
|
assert.notEqual(hr, en);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('canonical default template across languages', () => {
|
||||||
|
it('never mixes the previous English five-benefit formula with localized SEO defaults', () => {
|
||||||
|
for (const { value: language } of CONTENT_LANGUAGES) {
|
||||||
|
const rule = CATEGORY_FORMULA_RULES[language];
|
||||||
|
assert.equal((rule.description.match(/<h2>/g) ?? []).length, 2, language);
|
||||||
|
assert.equal((rule.description.match(/<p>/g) ?? []).length, 2, language);
|
||||||
|
assert.equal((rule.description.match(/<ul>/g) ?? []).length, 1, language);
|
||||||
|
assert.doesNotMatch(rule.description, /first verified benefit|fifth verified benefit|Write five different H2/i);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Descrybe — consistent product SEO formulas (v6)
|
||||||
|
|
||||||
|
## What changed
|
||||||
|
|
||||||
|
- Exactly one **canonical platform default formula** is used for all category types. It is translated into the same HTML and SEO structure in all 25 supported languages. Previously, English per-category defaults came from an older source, so English could retain a five-benefit/100-word template while other languages used the new SEO layout.
|
||||||
|
- The default title order is **verified brand → localized product type → official model/ID → optional verified color**, with no artificial punctuation or invented properties.
|
||||||
|
- Descriptions follow **`<p>` → optional `<h2>`+`<p>` → optional `<h2>`+`<ul><li>…</li></ul>`**. The storefront supplies the H1. Paragraph lengths are flexible; source facts matter more than word quotas. Omit unsupported feature and specification sections instead of making up content.
|
||||||
|
- Meta title and meta description are **separate plain-text fields**, with localized instructions. Meta descriptions should be factual and readable, typically 120–155 characters when information allows, with an upper bound of 155.
|
||||||
|
- Product generation falls back to the correct localized formula when a categorized product has no stored category prompt, including on older category records.
|
||||||
|
- The API resolves HTML structure and localized meta instructions from the active category language, instead of defaulting to English meta rules.
|
||||||
|
- Frontend examples are generated from the API's bundled JSON translation rules by `node scripts/seed/build-category-ui-examples.mjs`, so the examples can't silently diverge from the backend.
|
||||||
|
- The global offline seed now rewrites **only exact known platform-default snapshots**, including mixed older versions. Old translations are versioned by prompt hash. A1-authored prompts stay custom; an exact old default in a separate A1 language can be upgraded without overwriting its original Slovenian instructions.
|
||||||
|
- New category creation, including CSV category imports, reads the one cached shared template for all languages.
|
||||||
|
|
||||||
|
## Deployment (all companies)
|
||||||
|
|
||||||
|
Use the supplied source for **API + worker + frontend**, then from its root:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run migrate
|
||||||
|
npm run seed:category-prompts:i18n -- -dry-run
|
||||||
|
npm run seed:category-prompts:i18n
|
||||||
|
```
|
||||||
|
|
||||||
|
Neither the offline seed nor the locale rules require `OPENAI_API_KEY`. The database seed requires `DATABASE_URL` and migration 048.
|
||||||
|
|
||||||
|
The dry run is read-only and simulates the 25 bundled translations in memory, reporting eligible categories without writing to the database. The full run updates only built-in defaults and stores their 25 translations for all current and future companies. Company-authored templates are not overwritten; exact stock old English formulas can be upgraded even when other language slots were already updated.
|
||||||
|
|
||||||
|
The A1-only cleanup remains available as a separate command for **recognized Slovenian legacy descriptions**:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run cleanup:a1:prompts
|
||||||
|
npm run cleanup:a1:prompts -- -apply
|
||||||
|
```
|
||||||
|
|
||||||
|
**Reprocess products** to regenerate previously generated titles/descriptions/meta based on these formulas. The seed changes category configuration, not already published/generated product content.
|
||||||
|
|
||||||
|
### Custom prompts
|
||||||
|
|
||||||
|
The seed does not replace an existing custom prompt just because it contains H2 headings or mentions technical specifications. If a supposedly default category remains unchanged, inspect its `categories.prompt`, `title_template`, and `description_template`: at least one field may differ from every known shipped default. This is intentional, to protect user changes.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
- 25/25 languages: same description block order, role markers, and explicit title/description/meta rules.
|
||||||
|
- Isolated Go 1.23 category-default and HTML/parser tests pass.
|
||||||
|
- Frontend localization/role tests pass (11 checks).
|
||||||
|
- Go backend database integration tests require the project's Go 1.25 toolchain and a reachable PostgreSQL database. The seed was **not run against the live database**; inspect the dry-run report before applying.
|
||||||
|
- Company-level rules that suppress SEO-meta output (e.g. A1 export policy) have **not** been changed.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
|
||||||
|
const root = resolve(import.meta.dirname, '../..');
|
||||||
|
const source = resolve(root, 'apps/api/internal/aiprompts/defaults/prompt-rules-25.json');
|
||||||
|
const target = resolve(root, 'apps/web/src/lib/categories/prompt-examples.ts');
|
||||||
|
const rules = JSON.parse(readFileSync(source, 'utf8'));
|
||||||
|
const output = `/**
|
||||||
|
* GENERATED from apps/api/internal/aiprompts/defaults/prompt-rules-25.json.
|
||||||
|
* Run: node scripts/seed/build-category-ui-examples.mjs
|
||||||
|
* Read-only preview data; never writes category prompts automatically.
|
||||||
|
*/
|
||||||
|
import { DEFAULT_CONTENT_LANGUAGE, parseContentLanguage } from '../content-languages.ts';
|
||||||
|
import type { EnhancePromptSectionId } from './prompt-sections';
|
||||||
|
|
||||||
|
export const CATEGORY_FORMULA_RULES: Record<string, Record<EnhancePromptSectionId, string>> = ${JSON.stringify(rules, null, 2)};
|
||||||
|
|
||||||
|
export const CATEGORY_PROMPT_EXAMPLES = CATEGORY_FORMULA_RULES;
|
||||||
|
|
||||||
|
export function localizedCategoryPromptExample(language: string, section: EnhancePromptSectionId): string {
|
||||||
|
const code = parseContentLanguage(language, DEFAULT_CONTENT_LANGUAGE);
|
||||||
|
return (CATEGORY_FORMULA_RULES[code] ?? CATEGORY_FORMULA_RULES.en)[section];
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
writeFileSync(target, output);
|
||||||
|
console.log(`Generated ${Object.keys(rules).length} synchronized language examples.`);
|
||||||
Reference in new issue
Block a user