612 lines
21 KiB
Go
612 lines
21 KiB
Go
// 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
|
|
//
|
|
// Requires migration 048 and DATABASE_URL only. No API key or LLM is used.
|
|
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()
|
|
}
|
|
|
|
// saveDefaultLanguage is safe to resume and cannot overwrite an existing
|
|
// translation, including an administrator's concurrent edit to the cache.
|
|
func saveDefaultLanguage(ctx context.Context, pool *pgxpool.Pool, hash, source, lang, value string) (bool, error) {
|
|
_, err := pool.Exec(ctx, `INSERT INTO default_category_prompt_translations(source_hash, source_prompt)
|
|
VALUES($1, $2) ON CONFLICT (source_hash) DO NOTHING`, hash, source)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
result, err := pool.Exec(ctx, `UPDATE default_category_prompt_translations
|
|
SET translations = jsonb_set(translations, ARRAY[$3::text], to_jsonb($4::text), true), updated_at = now()
|
|
WHERE source_hash = $1 AND source_prompt = $2 AND COALESCE(btrim(translations->>$3), '') = ''`,
|
|
hash, source, lang, value)
|
|
return result.RowsAffected() > 0, err
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// isMixedBuiltInEnglishPrompt recognizes a historical default whose three
|
|
// roles came from different RELEASED defaults. A full role scaffold is required;
|
|
// each role must be an EXACT prior built-in fragment. Never match arbitrary
|
|
// user-written instructions by keywords or number of paragraphs.
|
|
func isMixedBuiltInEnglishPrompt(value string, versions []aiprompts.CategoryFormulaDefaults) bool {
|
|
markers := [][2]string{
|
|
{aiprompts.SectionTitleStart, aiprompts.SectionTitleEnd},
|
|
{aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd},
|
|
{aiprompts.SectionMetaStart, aiprompts.SectionMetaEnd},
|
|
}
|
|
if !aiprompts.CategoryEnhanceHasRoleSections(value) {
|
|
return false
|
|
}
|
|
// No unrecognized preamble, trailing content, or hidden custom section.
|
|
if strings.TrimSpace(strings.ReplaceAll(value, "\r\n", "\n")) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
|
TitleRules: aiprompts.ExtractEnhanceSectionBody(value, markers[0][0], markers[0][1]),
|
|
DescriptionRules: aiprompts.ExtractEnhanceSectionBody(value, markers[1][0], markers[1][1]),
|
|
MetaRules: aiprompts.ExtractEnhanceSectionBody(value, markers[2][0], markers[2][1]),
|
|
WasLegacy: true,
|
|
}) {
|
|
return false
|
|
}
|
|
for _, pair := range markers {
|
|
text := aiprompts.ExtractEnhanceSectionBody(value, pair[0], pair[1])
|
|
if text == "" {
|
|
return false
|
|
}
|
|
known := false
|
|
for _, ver := range versions {
|
|
if text == aiprompts.ExtractEnhanceSectionBody(ver.Overlay, pair[0], pair[1]) {
|
|
known = true
|
|
break
|
|
}
|
|
}
|
|
if !known {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// isKnownBuiltInVariantSet permits migrations from *mixed* released platform
|
|
// versions (for example, English from the old five-H2 default and German from
|
|
// the SEO-v4 release). Every non-empty language must match a known, exact
|
|
// built-in value. One company-authored field disqualifies the entire category.
|
|
// Cache lookups are read-only; no fuzzy matches on real tenant instructions.
|
|
func isKnownBuiltInVariantSet(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache map[string]*defaultTranslation) bool {
|
|
allowedEN := map[string]bool{}
|
|
allowedLocalized := map[string]map[string]bool{}
|
|
for _, version := range versions {
|
|
if version.Overlay == "" {
|
|
continue
|
|
}
|
|
allowedEN[strings.TrimSpace(version.Overlay)] = true
|
|
if entry := cache[catalog.DefaultPromptHash(version.Overlay)]; entry != nil {
|
|
for lang, val := range entry.Values {
|
|
if !company.IsAllowedLanguage(lang) || strings.TrimSpace(val) == "" {
|
|
continue
|
|
}
|
|
if lang == "en" {
|
|
allowedEN[strings.TrimSpace(val)] = true
|
|
continue
|
|
}
|
|
if allowedLocalized[lang] == nil {
|
|
allowedLocalized[lang] = map[string]bool{}
|
|
}
|
|
allowedLocalized[lang][strings.TrimSpace(val)] = true
|
|
}
|
|
}
|
|
}
|
|
for lang, val := range prompts {
|
|
val = strings.TrimSpace(val)
|
|
if val == "" {
|
|
continue
|
|
}
|
|
if lang == "*" || lang == "en" {
|
|
if !allowedEN[val] && !isMixedBuiltInEnglishPrompt(val, versions) {
|
|
return false
|
|
}
|
|
} else if !company.IsAllowedLanguage(lang) || !allowedLocalized[lang][val] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Only exact former built-in JSON is eligible for an upgrade, even when the
|
|
// prompt and formula columns happen to be from different older deployments.
|
|
func isKnownBuiltInFormula(current string, versions []aiprompts.CategoryFormulaDefaults, title bool) bool {
|
|
if matchesDefaultFormula(current, "") {
|
|
return true
|
|
}
|
|
for _, version := range versions {
|
|
compare := version.DescriptionTemplateJSON
|
|
if title {
|
|
compare = version.TitleTemplateJSON
|
|
}
|
|
if matchesDefaultFormula(current, compare) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// upgradeOldDefault is scoped to a single category and guarded by an exact
|
|
// snapshot of its three current columns, so concurrent edits are not overwritten.
|
|
func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow, def aiprompts.CategoryFormulaDefaults, translations company.LangPromptMap) (bool, error) {
|
|
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
|
|
}
|
|
|
|
// replaceKnownBuiltInLocales upgrades only exact released DEFAULT locale values.
|
|
// A1 can contain its own custom Slovenian category prompt alongside an old
|
|
// platform-generated English translation. Preserve its custom languages, name
|
|
// and meta formulas while replacing the old built-in English/other languages.
|
|
func replaceKnownBuiltInLocales(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache map[string]*defaultTranslation) int {
|
|
if len(versions) == 0 {
|
|
return 0
|
|
}
|
|
canonical := versions[0]
|
|
current := cache[catalog.DefaultPromptHash(canonical.Overlay)]
|
|
if current == nil {
|
|
return 0
|
|
}
|
|
updates := 0
|
|
for lang, text := range prompts {
|
|
val := strings.TrimSpace(text)
|
|
if val == "" {
|
|
continue
|
|
}
|
|
replacement := strings.TrimSpace(current.Values[lang])
|
|
if lang == "*" || lang == "en" {
|
|
replacement = canonical.Overlay
|
|
}
|
|
if replacement == "" || replacement == val {
|
|
continue
|
|
}
|
|
for _, prior := range versions[1:] {
|
|
if prior.Overlay == "" {
|
|
continue
|
|
}
|
|
old := prior.Overlay
|
|
if lang != "*" && lang != "en" {
|
|
entry := cache[catalog.DefaultPromptHash(prior.Overlay)]
|
|
if entry == nil {
|
|
continue
|
|
}
|
|
old = strings.TrimSpace(entry.Values[lang])
|
|
}
|
|
if (val == strings.TrimSpace(old) && old != "") ||
|
|
((lang == "*" || lang == "en") && isMixedBuiltInEnglishPrompt(val, versions)) {
|
|
prompts[lang] = replacement
|
|
updates++
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return updates
|
|
}
|
|
|
|
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
|
|
// It neither translates nor changes A1 naming/meta instructions.
|
|
func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRow, cache map[string]*defaultTranslation, dryRun bool) (int, int, bool, error) {
|
|
next := make(company.LangPromptMap, len(row.Prompts))
|
|
removed := 0
|
|
for lang, value := range row.Prompts {
|
|
cleaned, n := aiprompts.NormalizeA1RepeatedBenefits(value)
|
|
next[lang] = cleaned
|
|
removed += n
|
|
}
|
|
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
|
|
versions := []aiprompts.CategoryFormulaDefaults{def,
|
|
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
|
|
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
|
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name)}
|
|
localesUpgraded := replaceKnownBuiltInLocales(next, versions, cache)
|
|
desc, n, err := aiprompts.NormalizeA1DescriptionTemplate(row.Desc)
|
|
if err != nil {
|
|
return 0, 0, false, err
|
|
}
|
|
removed += n
|
|
if removed == 0 && localesUpgraded == 0 || dryRun {
|
|
return removed, localesUpgraded, false, nil
|
|
}
|
|
encoded, err := company.EncodeLangPromptMap(next)
|
|
if err != nil {
|
|
return removed, localesUpgraded, false, err
|
|
}
|
|
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 {
|
|
return removed, localesUpgraded, false, err
|
|
}
|
|
return removed, localesUpgraded, result.RowsAffected() == 1, nil
|
|
}
|
|
|
|
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")
|
|
dryRun := flag.Bool("dry-run", false, "show needed localized defaults and eligible categories without database writes")
|
|
langs := flag.String("langs", "", "comma-separated subset; defaults to all supported content languages")
|
|
limit := flag.Int("limit", 0, "optional maximum number of built-in templates to seed (pilot only)")
|
|
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)
|
|
}
|
|
// 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 {
|
|
if strings.TrimSpace(entry.Values[lang]) != "" {
|
|
continue
|
|
}
|
|
missing++
|
|
if *dryRun {
|
|
// Simulate bundled values in memory so the preview classifies
|
|
// existing mixed-language defaults exactly as the real run.
|
|
preview := source
|
|
if lang != "en" {
|
|
var previewErr error
|
|
preview, previewErr = aiprompts.OfflineDefaultPrompt(lang)
|
|
if previewErr != nil {
|
|
failures++
|
|
log.Printf("FAIL preview language=%s: %v", lang, previewErr)
|
|
continue
|
|
}
|
|
}
|
|
entry.Values[lang] = preview
|
|
continue
|
|
}
|
|
translated := source
|
|
if lang != "en" {
|
|
translated, err = aiprompts.OfflineDefaultPrompt(lang)
|
|
if err != nil {
|
|
failures++
|
|
log.Printf("FAIL default=%d/%d lang=%s: %v", i+1, len(sources), lang, err)
|
|
continue
|
|
}
|
|
}
|
|
saved, err := saveDefaultLanguage(ctx, pool, hash, source, lang, translated)
|
|
if err != nil {
|
|
failures++
|
|
log.Printf("FAIL storing default=%d lang=%s: %v", i+1, lang, err)
|
|
continue
|
|
}
|
|
if saved {
|
|
inserted++
|
|
}
|
|
entry.Values[lang] = translated
|
|
}
|
|
if !*dryRun {
|
|
log.Printf("default templates %d/%d cached languages=%d", i+1, len(sources), len(entry.Values))
|
|
}
|
|
}
|
|
// 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)
|
|
}
|
|
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales := 0, 0, 0, 0, 0, 0, 0, 0
|
|
for _, row := range categories {
|
|
// A1 has its own Slovenian category instructions. Never apply the
|
|
// global platform-default backfill to this customer.
|
|
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
|
|
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
|
|
protected++
|
|
removed, localized, updated, cleanErr := normalizeA1Category(ctx, pool, row, cache, *dryRun)
|
|
if cleanErr != nil {
|
|
failures++
|
|
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
|
|
} else {
|
|
a1Removed += removed
|
|
a1Locales += localized
|
|
if updated {
|
|
a1Updated++
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
|
|
entry := cache[catalog.DefaultPromptHash(def.Overlay)]
|
|
if entry == nil {
|
|
continue
|
|
} // -limit pilot excludes some templates
|
|
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
|
|
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
|
|
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) &&
|
|
strings.TrimSpace(row.Title) != "" && strings.TrimSpace(row.Desc) != "" {
|
|
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
|
|
}
|
|
// Upgrade *only* built-in snapshots, including mixed versions left by
|
|
// prior migrations. Never touch any tenant-authored language or formula.
|
|
versions := []aiprompts.CategoryFormulaDefaults{
|
|
def,
|
|
aiprompts.PreviousSEODefaultCategoryFormula(row.UID, row.Name),
|
|
aiprompts.PriorDefaultCategoryFormula(row.UID, row.Name),
|
|
aiprompts.LegacyDefaultCategoryFormula(row.UID, row.Name),
|
|
}
|
|
if !isKnownBuiltInVariantSet(row.Prompts, versions, cache) ||
|
|
!isKnownBuiltInFormula(row.Title, versions, true) ||
|
|
!isKnownBuiltInFormula(row.Desc, versions, false) {
|
|
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++
|
|
}
|
|
|
|
}
|
|
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_default_locales_upgraded=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, failures, *dryRun)
|
|
if *dryRun && missing > 0 {
|
|
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
|
|
}
|
|
if failures > 0 {
|
|
os.Exit(1)
|
|
}
|
|
}
|