Skip to content

Commit 1d41881

Browse files
committed
fix(docs-i18n): centralize translation safeguards
1 parent 489690f commit 1d41881

10 files changed

Lines changed: 241 additions & 28 deletions

File tree

‎scripts/docs-i18n/doc_chunked_raw.go‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ import (
99
"slices"
1010
"strconv"
1111
"strings"
12+
13+
"github.com/yuin/goldmark"
14+
"github.com/yuin/goldmark/ast"
15+
"github.com/yuin/goldmark/extension"
16+
textpkg "github.com/yuin/goldmark/text"
1217
)
1318

1419
const defaultDocChunkMaxBytes = 12000
@@ -31,6 +36,8 @@ type docChunkStructure struct {
3136
headingLevels []int
3237
listShapes []markdownListShape
3338
inlineCodeSpans []string
39+
linkDestinations []string
40+
numericValues []string
3441
fencedPlaceholders []string
3542
fencedProtocolTokens []string
3643
fencedDirectiveTokens []string
@@ -97,6 +104,12 @@ func validateDocBodyFencedLiterals(source, translated string) error {
97104
if !slices.Equal(sourceStructure.fencedDirectiveTokens, translatedStructure.fencedDirectiveTokens) {
98105
return fmt.Errorf("fenced directive mismatch: source=%d translated=%d", len(sourceStructure.fencedDirectiveTokens), len(translatedStructure.fencedDirectiveTokens))
99106
}
107+
if !sameStringMultiset(sourceStructure.linkDestinations, translatedStructure.linkDestinations) {
108+
return fmt.Errorf("link destination mismatch: source=%d translated=%d", len(sourceStructure.linkDestinations), len(translatedStructure.linkDestinations))
109+
}
110+
if !sameStringMultiset(sourceStructure.numericValues, translatedStructure.numericValues) {
111+
return fmt.Errorf("numeric value mismatch: source=%d translated=%d", len(sourceStructure.numericValues), len(translatedStructure.numericValues))
112+
}
100113
return nil
101114
}
102115

@@ -280,6 +293,12 @@ func validateDocChunkTranslation(source, translated string) error {
280293
if !slices.Equal(sourceStructure.fencedDirectiveTokens, translatedStructure.fencedDirectiveTokens) {
281294
return fmt.Errorf("fenced directive mismatch: source=%d translated=%d", len(sourceStructure.fencedDirectiveTokens), len(translatedStructure.fencedDirectiveTokens))
282295
}
296+
if !sameStringMultiset(sourceStructure.linkDestinations, translatedStructure.linkDestinations) {
297+
return fmt.Errorf("link destination mismatch: source=%d translated=%d", len(sourceStructure.linkDestinations), len(translatedStructure.linkDestinations))
298+
}
299+
if !sameStringMultiset(sourceStructure.numericValues, translatedStructure.numericValues) {
300+
return fmt.Errorf("numeric value mismatch: source=%d translated=%d", len(sourceStructure.numericValues), len(translatedStructure.numericValues))
301+
}
283302
if !slices.Equal(sortedKeys(sourceStructure.tagCounts), sortedKeys(translatedStructure.tagCounts)) {
284303
return fmt.Errorf("component tag set mismatch")
285304
}
@@ -440,12 +459,43 @@ func summarizeDocChunkStructure(text string) docChunkStructure {
440459
headingLevels: extractMarkdownHeadingLevels(text),
441460
listShapes: extractMarkdownListShapes(text),
442461
inlineCodeSpans: extractMarkdownInlineCodeValues(text),
462+
linkDestinations: extractMarkdownLinkDestinations(text),
463+
numericValues: extractNumericValues(text),
443464
fencedPlaceholders: fencedPlaceholders,
444465
fencedProtocolTokens: fencedProtocolTokens,
445466
fencedDirectiveTokens: fencedDirectiveTokens,
446467
}
447468
}
448469

470+
func extractMarkdownLinkDestinations(text string) []string {
471+
// Validate inline Markdown destinations only. Reference-style links and GFM bare-autolink
472+
// boundaries remain governed by the shared structural and exact-URL prompt rules.
473+
source := []byte(normalizeDocComponentsForMarkdownParse(text))
474+
doc := parseDocsMarkdown(source)
475+
destinations := make([]string, 0)
476+
_ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
477+
if !entering {
478+
return ast.WalkContinue, nil
479+
}
480+
switch link := node.(type) {
481+
case *ast.Link:
482+
if link.Reference == nil {
483+
destinations = append(destinations, "link:"+string(link.Destination))
484+
}
485+
case *ast.Image:
486+
if link.Reference == nil {
487+
destinations = append(destinations, "image:"+string(link.Destination))
488+
}
489+
}
490+
return ast.WalkContinue, nil
491+
})
492+
return destinations
493+
}
494+
495+
func parseDocsMarkdown(source []byte) ast.Node {
496+
return goldmark.New(goldmark.WithExtensions(extension.GFM, extension.Footnote)).Parser().Parse(textpkg.NewReader(source))
497+
}
498+
449499
func countsWithoutFence(counts map[string]int) map[string]int {
450500
filtered := map[string]int{}
451501
for key, value := range counts {

‎scripts/docs-i18n/doc_mode_test.go‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2325,8 +2325,8 @@ func TestProcessFileDocUsesFieldLevelFrontmatterTranslation(t *testing.T) {
23252325
if !strings.Contains(text, "在 Fly.io 上部署 OpenClaw") {
23262326
t.Fatalf("expected translated read_when entry in output:\n%s", text)
23272327
}
2328-
if !strings.Contains(text, "prompt_version: 24") {
2329-
t.Fatalf("expected prompt version 24 in output metadata:\n%s", text)
2328+
if !strings.Contains(text, "prompt_version: 25") {
2329+
t.Fatalf("expected prompt version 25 in output metadata:\n%s", text)
23302330
}
23312331
}
23322332

@@ -2375,3 +2375,85 @@ func TestProcessFileDocRejectsSuspiciousFrontmatterScalarExpansion(t *testing.T)
23752375
t.Fatalf("expected read_when translation to survive fallback:\n%s", text)
23762376
}
23772377
}
2378+
2379+
func TestValidateDocChunkTranslationRejectsChangedCompositeLiteral(t *testing.T) {
2380+
t.Parallel()
2381+
2382+
tests := [][2]string{
2383+
{"Supports 1:1 conversations.\n", "आमने-सामने की बातचीत को सपोर्ट करता है।\n"},
2384+
{"Use mask 0xFF.\n", "Use mask 0xAA.\n"},
2385+
{"Use 1e-3.\n", "Use 1e -3.\n"},
2386+
}
2387+
for _, pair := range tests {
2388+
err := validateDocChunkTranslation(pair[0], pair[1])
2389+
if err == nil || !strings.Contains(err.Error(), "numeric value mismatch") {
2390+
t.Fatalf("expected composite-literal mismatch, got %v", err)
2391+
}
2392+
}
2393+
}
2394+
2395+
func TestValidateDocBodyRejectsChangedCompositeLiteral(t *testing.T) {
2396+
t.Parallel()
2397+
2398+
err := validateDocBodyFencedLiterals("Supports 1:1 conversations.\n", "आमने-सामने की बातचीत को सपोर्ट करता है।\n")
2399+
if err == nil || !strings.Contains(err.Error(), "numeric value mismatch") {
2400+
t.Fatalf("expected final-document numeric mismatch, got %v", err)
2401+
}
2402+
}
2403+
2404+
func TestExtractNumericValuesKeepsLowAmbiguityComposites(t *testing.T) {
2405+
t.Parallel()
2406+
2407+
got := strings.Join(extractNumericValues("0xFF 0b101 0o755 1.5:1 1e-3 v1.2.3"), ",")
2408+
if want := "0xFF,0b101,0o755,1.5:1,1e-3"; got != want {
2409+
t.Fatalf("unexpected composite literals: got=%q want=%q", got, want)
2410+
}
2411+
if err := validateDocChunkTranslation("Supports 1:1 conversations.\n", "Unterstützt 1:1-Unterhaltungen.\n"); err != nil {
2412+
t.Fatalf("expected locale compound after exact ratio to pass: %v", err)
2413+
}
2414+
}
2415+
2416+
func TestValidateDocChunkTranslationRejectsDroppedDuplicateLink(t *testing.T) {
2417+
t.Parallel()
2418+
2419+
source := "Deploy on [Render](https://render.com), then open [account](https://render.com).\n"
2420+
translated := "Auf [Render](https://render.com) bereitstellen, dann das Konto öffnen.\n"
2421+
err := validateDocChunkTranslation(source, translated)
2422+
if err == nil || !strings.Contains(err.Error(), "link destination mismatch") {
2423+
t.Fatalf("expected duplicate-link mismatch, got %v", err)
2424+
}
2425+
}
2426+
2427+
func TestValidateDocBodyRejectsDroppedLinkMarkup(t *testing.T) {
2428+
t.Parallel()
2429+
2430+
err := validateDocBodyFencedLiterals("Read [guide](/setup).\n", "Lesen Sie guide](/setup).\n")
2431+
if err == nil || !strings.Contains(err.Error(), "link destination mismatch") {
2432+
t.Fatalf("expected final-document link mismatch, got %v", err)
2433+
}
2434+
}
2435+
2436+
func TestExtractMarkdownLinkDestinationsUsesParsedNodes(t *testing.T) {
2437+
t.Parallel()
2438+
2439+
source := "[docs](https://host/a_(b)) [guide](/setup \"Setup guide\") [angle](<https://host/a b>)"
2440+
got := strings.Join(extractMarkdownLinkDestinations(source), ",")
2441+
want := "link:https://host/a_(b),link:/setup,link:https://host/a b"
2442+
if got != want {
2443+
t.Fatalf("unexpected parsed destinations: got=%q want=%q", got, want)
2444+
}
2445+
if got := extractMarkdownLinkDestinations("`[inline](https://example.com)`"); len(got) != 0 {
2446+
t.Fatalf("expected code-context link to be ignored, got %q", got)
2447+
}
2448+
}
2449+
2450+
func TestValidateDocChunkTranslationChecksLinkInsideMDX(t *testing.T) {
2451+
t.Parallel()
2452+
2453+
source := "<Card>\nRead [guide](/setup).\n</Card>\n"
2454+
translated := "<Card>\nLesen Sie guide](/setup).\n</Card>\n"
2455+
err := validateDocChunkTranslation(source, translated)
2456+
if err == nil || !strings.Contains(err.Error(), "link destination mismatch") {
2457+
t.Fatalf("expected MDX-contained link mismatch, got %v", err)
2458+
}
2459+
}

‎scripts/docs-i18n/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ func main() {
4747
docsRoot = flag.String("docs", "docs", "docs root")
4848
tmPath = flag.String("tm", "", "translation memory path")
4949
mode = flag.String("mode", "segment", "translation mode (segment|doc)")
50-
thinking = flag.String("thinking", "xhigh", "thinking level (low|medium|high|xhigh)")
50+
thinking = flag.String("thinking", "xhigh", "thinking level (low|medium|high|xhigh|max)")
5151
overwrite = flag.Bool("overwrite", false, "overwrite existing translations")
5252
allowPartial = flag.Bool("allow-partial", false, "write successful doc-mode outputs even when another file fails")
5353
maxFiles = flag.Int("max", 0, "max files to process (0 = all)")

‎scripts/docs-i18n/masking.go‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ var (
1313
linkURLRe = regexp.MustCompile(`\[[^\]]*\]\(([^)]+)\)`)
1414
placeholderRe = regexp.MustCompile(`__OC_I18N_\d+__`)
1515
listMarkerRe = regexp.MustCompile(`^([ \t]*(?:>[ \t]*)*)([-+*]|[0-9]+[.)])([ \t]+)`)
16+
// Hard validation stays limited to low-ambiguity composite literals. Plain numbers remain
17+
// model-visible so target-language plurals and ordinals can change grammar without false failures.
18+
numericValueRe = regexp.MustCompile(`(?:0[xX][0-9A-Za-z_]+|0[bB][0-9A-Za-z_]+|0[oO][0-9A-Za-z_]+|[0-9]+(?:\.[0-9]+)?(?::[0-9]+(?:\.[0-9]+)?)+|(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)[eE][+-]?[0-9]+)`)
1619
)
1720

1821
func maskMarkdown(text string, nextPlaceholder func() string, placeholders *[]string, mapping map[string]string) string {
@@ -113,6 +116,57 @@ func maskMarkdownDocSyntax(text string, nextPlaceholder func() string, placehold
113116
return maskByteRanges(masked, listRanges, nextPlaceholder, placeholders, mapping)
114117
}
115118

119+
func extractNumericValues(text string) []string {
120+
protocolRanges := make([][2]int, 0)
121+
for _, span := range placeholderRe.FindAllStringIndex(text, -1) {
122+
protocolRanges = append(protocolRanges, [2]int{span[0], span[1]})
123+
}
124+
values := make([]string, 0)
125+
for _, span := range numericValueRe.FindAllStringIndex(text, -1) {
126+
candidate := [2]int{span[0], span[1]}
127+
if hasCompositeNumericLeadingContinuation(text, candidate[0]) || hasCompositeNumericContinuation(text, candidate[1]) || rangeOverlapsAny(candidate, protocolRanges) {
128+
continue
129+
}
130+
values = append(values, text[span[0]:span[1]])
131+
}
132+
return values
133+
}
134+
135+
func hasCompositeNumericLeadingContinuation(text string, position int) bool {
136+
if position == 0 {
137+
return false
138+
}
139+
value := text[position-1]
140+
if value == '_' {
141+
for position > 0 && text[position-1] == '_' {
142+
position--
143+
}
144+
return position > 0 && isCompositeNumericWordByte(text[position-1])
145+
}
146+
return value == '.' || value == '-' || isCompositeNumericWordByte(value)
147+
}
148+
149+
func hasCompositeNumericContinuation(text string, position int) bool {
150+
if position >= len(text) {
151+
return false
152+
}
153+
value := text[position]
154+
if value == '_' {
155+
for position < len(text) && text[position] == '_' {
156+
position++
157+
}
158+
return position < len(text) && isCompositeNumericWordByte(text[position])
159+
}
160+
if isCompositeNumericWordByte(value) {
161+
return true
162+
}
163+
return value == '.' && position+1 < len(text) && isCompositeNumericWordByte(text[position+1])
164+
}
165+
166+
func isCompositeNumericWordByte(value byte) bool {
167+
return value >= '0' && value <= '9' || value >= 'A' && value <= 'Z' || value >= 'a' && value <= 'z'
168+
}
169+
116170
func markdownLiteralFenceByteRanges(text string) [][2]int {
117171
return markdownLiteralFenceByteRangesWithMode(text, true)
118172
}

0 commit comments

Comments
 (0)