2026-10-14 18:18:54 +02:00
// Command seed-category-prompt-translations permanently caches translations of
// PLATFORM DEFAULT category prompts for every tenant and all new categories.
// Categories with any custom prompt are never modified. Safe to rerun.
//
// Usage:
//
// go run ./cmd/seed-category-prompt-translations -dry-run
// go run ./cmd/seed-category-prompt-translations
// go run ./cmd/seed-category-prompt-translations -langs sl,hr,de
//
2026-10-14 18:47:00 +02:00
// Requires migration 048 and DATABASE_URL only. No API key or LLM is used.
2026-10-14 18:18:54 +02:00
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
"github.com/descrybe/descrybe-v2/apps/api/internal/company"
"github.com/descrybe/descrybe-v2/apps/api/internal/config"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type categoryRow struct {
ID uuid . UUID
Company uuid . UUID
Name string
UID string
Prompts company . LangPromptMap
Raw [] byte
Title string
Desc string
CompanyName string
}
func langsToSeed ( raw string ) ([] string , error ) {
if strings . TrimSpace ( raw ) == "" {
return append ([] string ( nil ), company . ContentLanguages ... ), nil
}
unique := map [ string ] bool {}
out := make ([] string , 0 )
for _ , input := range strings . Split ( raw , "," ) {
lang , err := company . ParseLanguage ( input , false )
if err != nil {
return nil , err
}
if ! unique [ lang ] {
out = append ( out , lang )
unique [ lang ] = true
}
}
return out , nil
}
// fetchCategories includes NULL/empty prompts: those also receive defaults.
func fetchCategories ( ctx context . Context , pool * pgxpool . Pool , id uuid . UUID , all bool ) ([] categoryRow , error ) {
query := `SELECT c.id, c.company_id, c.name, c.unique_id,
COALESCE(c.prompt, '{}'::jsonb), COALESCE(c.title_template::text, ''), COALESCE(c.description_template::text, ''), COALESCE(co.name, '') FROM categories c JOIN companies co ON co.id = c.company_id`
args := [] any {}
if ! all {
query += ` WHERE c.company_id = $1`
args = append ( args , id )
}
query += ` ORDER BY c.company_id, c.unique_id`
rows , err := pool . Query ( ctx , query , args ... )
if err != nil {
return nil , err
}
defer rows . Close ()
out := make ([] categoryRow , 0 )
for rows . Next () {
var row categoryRow
if err := rows . Scan ( & row . ID , & row . Company , & row . Name , & row . UID , & row . Raw , & row . Title , & row . Desc , & row . CompanyName ); err != nil {
return nil , err
}
if err := json . Unmarshal ( row . Raw , & row . Prompts ); err != nil {
return nil , fmt . Errorf ( "category %s: decode prompt: %w" , row . UID , err )
}
if row . Prompts == nil {
row . Prompts = company . LangPromptMap {}
}
out = append ( out , row )
}
return out , rows . Err ()
}
type defaultTranslation struct {
Source string
Values company . LangPromptMap
}
func loadTranslationCache ( ctx context . Context , pool * pgxpool . Pool ) ( map [ string ] * defaultTranslation , error ) {
rows , err := pool . Query ( ctx , `SELECT source_hash, source_prompt, translations FROM default_category_prompt_translations` )
if err != nil {
return nil , fmt . Errorf ( "load shared defaults (run migration 048): %w" , err )
}
defer rows . Close ()
out := make ( map [ string ] * defaultTranslation )
for rows . Next () {
var hash , source string
var raw [] byte
if err := rows . Scan ( & hash , & source , & raw ); err != nil {
return nil , err
}
if catalog . DefaultPromptHash ( source ) != hash {
return nil , fmt . Errorf ( "corrupt shared default hash %s" , hash )
}
var values company . LangPromptMap
if err := json . Unmarshal ( raw , & values ); err != nil {
return nil , err
}
if values == nil {
values = company . LangPromptMap {}
}
out [ hash ] = & defaultTranslation { Source : source , Values : values }
}
return out , rows . Err ()
}
2026-10-14 20:28:38 +02:00
// saveDefaultLanguage owns ONLY the shared platform-default cache. Unlike tenant
// prompts, this is generated application data: outdated translations must be
// refreshed on a release. Earlier versions used DO NOTHING and permanently
// retained the English five-benefit scaffold in this cache.
2026-10-14 18:18:54 +02:00
func saveDefaultLanguage ( ctx context . Context , pool * pgxpool . Pool , hash , source , lang , value string ) ( bool , error ) {
2026-10-14 20:28:38 +02:00
result , err := pool . Exec ( ctx , `INSERT INTO default_category_prompt_translations
(source_hash, source_prompt, translations, updated_at)
VALUES ($1, $2, jsonb_build_object($3::text, $4::text), now())
ON CONFLICT (source_hash) DO UPDATE SET
translations = jsonb_set(default_category_prompt_translations.translations,
ARRAY[$3::text], to_jsonb($4::text), true), updated_at = now()
WHERE default_category_prompt_translations.source_prompt = EXCLUDED.source_prompt
AND default_category_prompt_translations.translations->>$3 IS DISTINCT FROM $4` ,
2026-10-14 18:18:54 +02:00
hash , source , lang , value )
return result . RowsAffected () > 0 , err
}
2026-10-14 20:28:38 +02:00
// Historical cache snapshots are read-only proof of previously shipped platform
// translations. They may be used for exact-match migration, NEVER as replacement
// text. This keeps custom company wording protected.
func knownCacheValues ( source string , current , historical map [ string ] * defaultTranslation , lang string ) [] string {
values := make ([] string , 0 , 2 )
hash := catalog . DefaultPromptHash ( source )
for _ , cache := range [] map [ string ] * defaultTranslation { current , historical } {
if entry := cache [ hash ]; entry != nil {
if value := strings . TrimSpace ( entry . Values [ lang ]); value != "" {
values = append ( values , value )
}
}
}
return values
}
2026-10-14 18:18:54 +02:00
// extendDefaultPrompt inserts only missing language variants. The SQL compares
// the full source snapshot: edits made during a long translation run are safe.
func extendDefaultPrompt ( ctx context . Context , pool * pgxpool . Pool , row categoryRow , expectedSource string , cached company . LangPromptMap , langs [] string ) ( bool , error ) {
if ! catalog . IsUntouchedDefaultPrompt ( row . Prompts , expectedSource , cached ) {
return false , nil
}
next := make ( company . LangPromptMap , len ( row . Prompts ) + len ( langs ) + 1 )
for k , v := range row . Prompts {
next [ k ] = v
}
if strings . TrimSpace ( next [ "*" ]) == "" {
next [ "*" ] = expectedSource
}
changed := len ( row . Prompts ) == 0 || next [ "*" ] != row . Prompts [ "*" ]
for _ , lang := range langs {
if strings . TrimSpace ( next [ lang ]) != "" {
continue
}
if text := strings . TrimSpace ( cached [ lang ]); text != "" {
next [ lang ] = text
changed = true
}
}
if ! changed {
return false , nil
}
encoded , err := company . EncodeLangPromptMap ( next )
if err != nil {
return false , err
}
result , err := pool . Exec ( ctx , `UPDATE categories SET prompt = $4::jsonb, updated_at = now()
WHERE id = $1 AND company_id = $2 AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb` ,
row . ID , row . Company , string ( row . Raw ), string ( encoded ))
return result . RowsAffected () > 0 , err
}
// matchesDefaultFormula compares semantically identical JSON values, allowing
// column whitespace/key order differences but never matching a custom formula.
func matchesDefaultFormula ( current , previous string ) bool {
current = strings . TrimSpace ( current )
if current == "" || current == "null" || current == "{}" {
return true
}
if previous == "" {
return false
}
var a , b any
if json . Unmarshal ([] byte ( current ), & a ) != nil || json . Unmarshal ([] byte ( previous ), & b ) != nil {
return false
}
left , _ := json . Marshal ( a )
right , _ := json . Marshal ( b )
return string ( left ) == string ( right )
}
2026-10-14 20:02:42 +02:00
// 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.
2026-10-14 20:28:38 +02:00
func isKnownBuiltInVariantSet ( prompts company . LangPromptMap , versions [] aiprompts . CategoryFormulaDefaults , cache , historical map [ string ] * defaultTranslation ) bool {
2026-10-14 20:02:42 +02:00
allowedEN := map [ string ] bool {}
allowedLocalized := map [ string ] map [ string ] bool {}
for _ , version := range versions {
if version . Overlay == "" {
continue
}
allowedEN [ strings . TrimSpace ( version . Overlay )] = true
2026-10-14 20:28:38 +02:00
for _ , previous := range [] map [ string ] * defaultTranslation { cache , historical } {
if entry := previous [ 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
2026-10-14 20:02:42 +02:00
}
}
}
}
for lang , val := range prompts {
2026-10-14 20:54:29 +02:00
// 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
}
2026-10-14 20:02:42 +02:00
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
}
2026-10-14 18:18:54 +02:00
// 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 ) {
next := company . LangPromptMap { "*" : def . Overlay }
for lang , value := range translations {
if company . IsAllowedLanguage ( lang ) && strings . TrimSpace ( value ) != "" {
next [ lang ] = value
}
}
next [ "en" ] = def . Overlay
encoded , err := company . EncodeLangPromptMap ( next )
if err != nil {
return false , err
}
// Preserve existing complete title formulas if equal to the legacy default,
// but repair missing ones. Replace standard description layout with the
// non-repeating platform structure after confirming it was not customized.
result , err := pool . Exec ( ctx , `UPDATE categories SET prompt = $4::jsonb,
title_template = $5::jsonb, description_template = $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 ),
def . TitleTemplateJSON , def . DescriptionTemplateJSON , row . Title , row . Desc )
return result . RowsAffected () > 0 , err
}
2026-10-14 20:54:29 +02:00
// 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
}
2026-10-14 20:02:42 +02:00
// 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.
2026-10-14 20:28:38 +02:00
func replaceKnownBuiltInLocales ( prompts company . LangPromptMap , versions [] aiprompts . CategoryFormulaDefaults , cache , historical map [ string ] * defaultTranslation ) int {
2026-10-14 20:02:42 +02:00
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
}
2026-10-14 20:28:38 +02:00
for _ , prior := range versions {
2026-10-14 20:02:42 +02:00
if prior . Overlay == "" {
continue
}
2026-10-14 20:28:38 +02:00
known := [] string {}
if lang == "*" || lang == "en" {
known = append ( known , prior . Overlay )
} else {
known = knownCacheValues ( prior . Overlay , cache , historical , lang )
}
matched := ( lang == "*" || lang == "en" ) && isMixedBuiltInEnglishPrompt ( val , versions )
for _ , old := range known {
if val == strings . TrimSpace ( old ) && old != "" {
matched = true
2026-10-14 20:02:42 +02:00
}
}
2026-10-14 20:54:29 +02:00
if ! matched && isExactOldDefaultLanguage ( val , lang , versions , cache , historical ) {
matched = true
}
2026-10-14 20:28:38 +02:00
if matched {
2026-10-14 20:02:42 +02:00
prompts [ lang ] = replacement
updates ++
break
}
}
}
return updates
}
2026-10-14 18:47:00 +02:00
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
// It neither translates nor changes A1 naming/meta instructions.
2026-10-14 20:28:38 +02:00
func normalizeA1Category ( ctx context . Context , pool * pgxpool . Pool , row categoryRow , cache , historical map [ string ] * defaultTranslation , dryRun bool ) ( int , int , bool , error ) {
2026-10-14 18:47:00 +02:00
next := make ( company . LangPromptMap , len ( row . Prompts ))
removed := 0
2026-10-14 20:28:38 +02:00
metaUpdated := 0
2026-10-14 18:47:00 +02:00
for lang , value := range row . Prompts {
cleaned , n := aiprompts . NormalizeA1RepeatedBenefits ( value )
removed += n
2026-10-14 20:28:38 +02:00
locale := lang
if locale == "*" || ! company . IsAllowedLanguage ( locale ) {
locale = "sl"
}
if metaClean , changed := aiprompts . NormalizeA1MetaRole ( cleaned , locale ); changed {
cleaned = metaClean
metaUpdated ++
}
next [ lang ] = cleaned
2026-10-14 18:47:00 +02:00
}
2026-10-14 20:02:42 +02:00
def := aiprompts . DefaultCategoryFormula ( row . UID , row . Name )
versions := [] aiprompts . CategoryFormulaDefaults { def ,
2026-10-14 20:28:38 +02:00
aiprompts . PreviousCanonicalV6CategoryFormula ( row . UID , row . Name ),
2026-10-14 20:02:42 +02:00
aiprompts . PreviousSEODefaultCategoryFormula ( row . UID , row . Name ),
aiprompts . PriorDefaultCategoryFormula ( row . UID , row . Name ),
aiprompts . LegacyDefaultCategoryFormula ( row . UID , row . Name )}
2026-10-14 20:28:38 +02:00
localesUpgraded := replaceKnownBuiltInLocales ( next , versions , cache , historical )
2026-10-14 18:47:00 +02:00
desc , n , err := aiprompts . NormalizeA1DescriptionTemplate ( row . Desc )
2026-10-14 18:18:54 +02:00
if err != nil {
2026-10-14 20:02:42 +02:00
return 0 , 0 , false , err
2026-10-14 18:18:54 +02:00
}
2026-10-14 18:47:00 +02:00
removed += n
2026-10-14 20:28:38 +02:00
metaLocale := "sl"
if normalized , repaired , normalizeErr := aiprompts . NormalizeA1MetaTemplate ( desc , metaLocale ); normalizeErr != nil {
return 0 , 0 , false , normalizeErr
} else if repaired {
desc = normalized
metaUpdated ++
}
if ( removed == 0 && localesUpgraded == 0 && metaUpdated == 0 ) || dryRun {
2026-10-14 20:02:42 +02:00
return removed , localesUpgraded , false , nil
2026-10-14 18:47:00 +02:00
}
encoded , err := company . EncodeLangPromptMap ( next )
if err != nil {
2026-10-14 20:02:42 +02:00
return removed , localesUpgraded , false , err
2026-10-14 18:47:00 +02:00
}
result , err := pool . Exec ( ctx , `UPDATE categories SET prompt = $4::jsonb,
description_template = NULLIF($5,'')::jsonb, updated_at = now()
WHERE id = $1 AND company_id = $2
AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
AND COALESCE(description_template::text,'') = $6` ,
row . ID , row . Company , string ( row . Raw ), string ( encoded ), desc , row . Desc )
if err != nil {
2026-10-14 20:02:42 +02:00
return removed , localesUpgraded , false , err
2026-10-14 18:47:00 +02:00
}
2026-10-14 20:02:42 +02:00
return removed , localesUpgraded , result . RowsAffected () == 1 , nil
2026-10-14 18:18:54 +02:00
}
func main () {
config . LoadDotEnv ()
postgres := flag . String ( "postgres" , os . Getenv ( "DATABASE_URL" ), "Postgres URL" )
companyID := flag . String ( "company" , "" , "optional company UUID for backfilling existing categories; shared defaults are global" )
all := flag . Bool ( "all-companies" , false , "legacy alias; all companies are now the default" )
2026-10-14 18:47:00 +02:00
dryRun := flag . Bool ( "dry-run" , false , "show needed localized defaults and eligible categories without database writes" )
2026-10-14 18:18:54 +02:00
langs := flag . String ( "langs" , "" , "comma-separated subset; defaults to all supported content languages" )
2026-10-14 18:47:00 +02:00
limit := flag . Int ( "limit" , 0 , "optional maximum number of built-in templates to seed (pilot only)" )
2026-10-14 18:18:54 +02:00
flag . Parse ()
if strings . TrimSpace ( * postgres ) == "" {
log . Fatal ( "DATABASE_URL/-postgres is required" )
}
if * limit < 0 {
log . Fatal ( "-limit must be >= 0" )
}
if * companyID != "" && * all {
log . Fatal ( "choose -company or -all-companies, not both" )
}
allCompanies := * companyID == ""
var id uuid . UUID
if ! allCompanies {
var err error
id , err = uuid . Parse ( * companyID )
if err != nil {
log . Fatal ( "invalid -company UUID: " , err )
}
}
targetLangs , err := langsToSeed ( * langs )
if err != nil {
log . Fatal ( err )
}
ctx := context . Background ()
pool , err := pgxpool . New ( ctx , * postgres )
if err != nil {
log . Fatal ( err )
}
defer pool . Close ()
cache , err := loadTranslationCache ( ctx , pool )
if err != nil {
log . Fatal ( err )
}
2026-10-14 20:28:38 +02:00
// Keep the old cache for exact-match detection when correcting stale records.
historical := make ( map [ string ] * defaultTranslation , len ( cache ))
for key , entry := range cache {
values := make ( company . LangPromptMap , len ( entry . Values ))
for lang , value := range entry . Values {
values [ lang ] = value
}
historical [ key ] = & defaultTranslation { Source : entry . Source , Values : values }
}
// An exact frozen v6 bundle supplies migration evidence even when a past
// deployment failed to populate its shared translation cache.
previous := aiprompts . PreviousCanonicalV6CategoryFormula ( "" , "" )
oldHash := catalog . DefaultPromptHash ( previous . Overlay )
if historical [ oldHash ] == nil {
oldValues := make ( company . LangPromptMap )
for _ , lang := range company . ContentLanguages {
if old , loadErr := aiprompts . PreviousOfflineDefaultPromptV6 ( lang ); loadErr == nil {
oldValues [ lang ] = old
}
}
historical [ oldHash ] = & defaultTranslation { Source : previous . Overlay , Values : oldValues }
}
2026-10-14 18:18:54 +02:00
// Always include the generic default and the complete bundled taxonomy.
// One translation cache is shared across EVERY company, including future ones.
sources := aiprompts . AllDefaultCategoryPrompts ()
if * limit > 0 && * limit < len ( sources ) {
sources = sources [: * limit ]
}
missing , inserted , failures := 0 , 0 , 0
for i , source := range sources {
hash := catalog . DefaultPromptHash ( source )
entry , exists := cache [ hash ]
if ! exists {
entry = & defaultTranslation { Source : source , Values : company . LangPromptMap {}}
cache [ hash ] = entry
}
if entry . Source != source {
log . Fatalf ( "shared default hash collision for %s" , hash )
}
for _ , lang := range targetLangs {
translated := source
if lang != "en" {
2026-10-14 18:47:00 +02:00
translated , err = aiprompts . OfflineDefaultPrompt ( lang )
2026-10-14 18:18:54 +02:00
if err != nil {
failures ++
2026-10-14 20:28:38 +02:00
log . Printf ( "FAIL bundled default=%d lang=%s: %v" , i + 1 , lang , err )
2026-10-14 18:18:54 +02:00
continue
}
}
2026-10-14 20:28:38 +02:00
if entry . Values [ lang ] == translated {
continue
}
missing ++
if * dryRun {
// A dry run must compare against the corrected bundle, not an
// old value from the database cache.
entry . Values [ lang ] = translated
continue
}
saved , saveErr := saveDefaultLanguage ( ctx , pool , hash , source , lang , translated )
if saveErr != nil {
2026-10-14 18:18:54 +02:00
failures ++
2026-10-14 20:28:38 +02:00
log . Printf ( "FAIL storing default=%d lang=%s: %v" , i + 1 , lang , saveErr )
2026-10-14 18:18:54 +02:00
continue
}
if saved {
inserted ++
}
entry . Values [ lang ] = translated
}
if ! * dryRun {
2026-10-14 18:47:00 +02:00
log . Printf ( "default templates %d/%d cached languages=%d" , i + 1 , len ( sources ), len ( entry . Values ))
2026-10-14 18:18:54 +02:00
}
}
// Refresh from the database before comparing company prompts: another seed
// or administrator may have changed a cached language during this run.
if ! * dryRun {
cache , err = loadTranslationCache ( ctx , pool )
if err != nil {
log . Fatal ( err )
}
}
categories , err := fetchCategories ( ctx , pool , id , allCompanies )
if err != nil {
log . Fatal ( err )
}
2026-10-14 20:54:29 +02:00
eligible , changed , custom , upgraded , protected , a1Removed , a1Updated , a1Locales , localeRepaired := 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
2026-10-14 18:18:54 +02:00
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 ++
2026-10-14 20:28:38 +02:00
removed , localized , updated , cleanErr := normalizeA1Category ( ctx , pool , row , cache , historical , * dryRun )
2026-10-14 18:47:00 +02:00
if cleanErr != nil {
failures ++
log . Printf ( "FAIL cleaning A1 category=%s: %v" , row . UID , cleanErr )
} else {
a1Removed += removed
2026-10-14 20:02:42 +02:00
a1Locales += localized
2026-10-14 18:47:00 +02:00
if updated {
a1Updated ++
}
}
2026-10-14 18:18:54 +02:00
continue
}
def := aiprompts . DefaultCategoryFormula ( row . UID , row . Name )
entry := cache [ catalog . DefaultPromptHash ( def . Overlay )]
if entry == nil {
continue
} // -limit pilot excludes some templates
2026-10-14 18:47:00 +02:00
if catalog . IsUntouchedDefaultPrompt ( row . Prompts , def . Overlay , entry . Values ) &&
matchesDefaultFormula ( row . Title , def . TitleTemplateJSON ) &&
2026-10-14 20:02:42 +02:00
matchesDefaultFormula ( row . Desc , def . DescriptionTemplateJSON ) &&
strings . TrimSpace ( row . Title ) != "" && strings . TrimSpace ( row . Desc ) != "" {
2026-10-14 18:18:54 +02:00
eligible ++
if * dryRun {
continue
}
updated , err := extendDefaultPrompt ( ctx , pool , row , def . Overlay , entry . Values , targetLangs )
if err != nil {
failures ++
log . Printf ( "FAIL extending company=%s category=%s: %v" , row . Company , row . UID , err )
} else if updated {
changed ++
}
continue
}
2026-10-14 20:02:42 +02:00
// Upgrade *only* built-in snapshots, including mixed versions left by
// prior migrations. Never touch any tenant-authored language or formula.
versions := [] aiprompts . CategoryFormulaDefaults {
def ,
2026-10-14 20:28:38 +02:00
aiprompts . PreviousCanonicalV6CategoryFormula ( row . UID , row . Name ),
2026-10-14 20:02:42 +02:00
aiprompts . PreviousSEODefaultCategoryFormula ( row . UID , row . Name ),
2026-10-14 19:23:16 +02:00
aiprompts . PriorDefaultCategoryFormula ( row . UID , row . Name ),
aiprompts . LegacyDefaultCategoryFormula ( row . UID , row . Name ),
2026-10-14 18:18:54 +02:00
}
2026-10-14 20:28:38 +02:00
if ! isKnownBuiltInVariantSet ( row . Prompts , versions , cache , historical ) ||
2026-10-14 20:02:42 +02:00
! isKnownBuiltInFormula ( row . Title , versions , true ) ||
! isKnownBuiltInFormula ( row . Desc , versions , false ) {
2026-10-14 20:54:29 +02:00
// 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
}
2026-10-14 18:18:54 +02:00
custom ++
continue
}
eligible ++
if * dryRun {
upgraded ++
continue
}
updated , err := upgradeOldDefault ( ctx , pool , row , def , entry . Values )
if err != nil {
failures ++
log . Printf ( "FAIL upgrading company=%s category=%s: %v" , row . Company , row . UID , err )
} else if updated {
changed ++
upgraded ++
}
2026-10-14 19:23:16 +02:00
2026-10-14 18:18:54 +02:00
}
2026-10-14 20:54:29 +02:00
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 )
2026-10-14 18:18:54 +02:00
if * dryRun && missing > 0 {
2026-10-14 18:47:00 +02:00
log . Printf ( "dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM" )
2026-10-14 18:18:54 +02:00
}
if failures > 0 {
os . Exit ( 1 )
}
}