Skip to content

Commit 5322da7

Browse files
committed
fix(docs-i18n): isolate translation rules and preserve placeholders
1 parent 638ffcd commit 5322da7

7 files changed

Lines changed: 97 additions & 8 deletions

File tree

‎docs/.i18n/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Fields:
6565
## Translation mechanics
6666

6767
- `scripts/docs-i18n` still owns translation generation.
68+
- Translation rules and glossary guidance are passed as Codex developer instructions; document text is user input, and repository `AGENTS.md` instructions are excluded from translation calls. Placeholder spelling and occurrence counts must match the input, even when the target language restructures comparisons or references.
6869
- Doc mode writes `x-i18n.source_hash` into each translated page.
6970
- The publish workflow precomputes a pending file list by comparing the current English source hash to the stored locale `x-i18n.source_hash`.
7071
- If the pending count is `0`, the expensive translation step is skipped entirely.
@@ -79,3 +80,9 @@ Fields:
7980
- Source repo secret: `OPENCLAW_DOCS_SYNC_TOKEN`
8081
- Publish repo secret: `OPENCLAW_DOCS_I18N_OPENAI_API_KEY`
8182
- If locale output looks stale, check the `Translate All` workflow in `openclaw/docs` first.
83+
84+
### Rejected translation diagnostics
85+
86+
For an operator-approved, bounded diagnostic, set `OPENCLAW_DOCS_I18N_LOG_REJECTED_BODY=1` (the publish repo's reusable locale workflow exposes `log_rejected_body`). This opt-in logs rejected raw chunks at the placeholder-validation boundary, including the chunk ID, normalized masked input, returned translation, and error. It also logs failed leaf-fallback errors and rejected bodies at final-document validation. Validation and retry behavior stay unchanged.
87+
88+
The chunk input/output are the Go translator boundary values, after its whitespace and input-wrapper handling, not raw provider transport bytes. Diagnostics can contain complete document text; limit the selected paths and attempts, retain the logs, and inspect them before sharing. Enabling the flag cannot recover responses from an earlier run.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"errors"
7+
"fmt"
8+
"log"
9+
"strings"
10+
"testing"
11+
)
12+
13+
func TestDocChunkRejectedBodyDiagnostics(t *testing.T) {
14+
const source = " Keep __OC_I18N_900000__ once.\n"
15+
const response = "Keep __OC_I18N_900000__ twice: __OC_I18N_900000__."
16+
const chunkID = "channels/example.md.chunk-001"
17+
const rejection = "placeholder duplicated: __OC_I18N_900000__ count=2"
18+
for _, enabled := range []string{"", "0", "1"} {
19+
t.Run("enabled="+enabled, func(t *testing.T) {
20+
t.Setenv("OPENCLAW_DOCS_I18N_LOG_REJECTED_BODY", enabled)
21+
var logs bytes.Buffer
22+
previousOutput := log.Writer()
23+
log.SetOutput(&logs)
24+
t.Cleanup(func() { log.SetOutput(previousOutput) })
25+
calls := 0
26+
translator := &CodexTranslator{
27+
runPrompt: func(context.Context, codexPromptRequest) (string, error) {
28+
calls++
29+
if calls == 1 {
30+
return response, nil
31+
}
32+
return "", errors.New("synthetic leaf failure")
33+
},
34+
}
35+
36+
translated, err := translateDocBlockGroup(context.Background(), translator, chunkID,
37+
[]string{source}, []string{"__OC_I18N_900000__"}, nil, "en", "ko")
38+
if translated != "" || err == nil || err.Error() != chunkID+": "+rejection {
39+
t.Fatalf("diagnostics changed the rejection: translated=%q err=%v", translated, err)
40+
}
41+
if calls != 2 {
42+
t.Fatalf("expected raw attempt and leaf fallback, got %d prompts", calls)
43+
}
44+
for _, want := range []string{
45+
fmt.Sprintf("rejected raw chunk %s input=%q output=%q err=%s", chunkID, strings.TrimPrefix(source, " "), response+"\n", rejection),
46+
"chunk leaf-fallback failed " + chunkID + " err=synthetic leaf failure",
47+
} {
48+
if strings.Contains(logs.String(), want) != (enabled == "1") {
49+
t.Errorf("diagnostic presence for %q does not match opt-in %q; logs:\n%s", want, enabled, &logs)
50+
}
51+
}
52+
})
53+
}
54+
}

‎scripts/docs-i18n/doc_chunked_raw.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,10 @@ func translateDocBlockGroup(ctx context.Context, translator docsTranslator, chun
156156
if err == nil {
157157
err = validatePlaceholders(translated, placeholdersInText(normalizedSource, protectedPlaceholders))
158158
}
159+
if err != nil && os.Getenv("OPENCLAW_DOCS_I18N_LOG_REJECTED_BODY") == "1" {
160+
// Capture the rejected translator boundary before normalization or leaf fallback loses it.
161+
log.Printf("docs-i18n: rejected raw chunk %s input=%q output=%q err=%v", chunkID, normalizedSource, translated, err)
162+
}
159163
if err == nil {
160164
translated = sanitizeDocChunkProtocolWrappers(source, translated)
161165
translated = preserveDocChunkBoundaryWhitespace(normalizedSource, translated)
@@ -175,6 +179,8 @@ func translateDocBlockGroup(ctx context.Context, translator docsTranslator, chun
175179
if len(blocks) <= 1 {
176180
if fallback, fallbackErr := translateDocLeafBlock(ctx, translator, chunkID, source, protectedPlaceholders, listPlaceholders, srcLang, tgtLang); fallbackErr == nil {
177181
return fallback, nil
182+
} else if os.Getenv("OPENCLAW_DOCS_I18N_LOG_REJECTED_BODY") == "1" {
183+
log.Printf("docs-i18n: chunk leaf-fallback failed %s err=%v", chunkID, fallbackErr)
178184
}
179185
if plan, ok := planSingletonDocChunkRetry(source, docsI18nDocChunkMaxBytes(), docsI18nDocChunkPromptBudget()); ok {
180186
logDocChunkPlanSplit(chunkID, plan, source)

‎scripts/docs-i18n/prompt.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ Rules:
172172
- Preserve Markdown list nodes exactly: ordered versus unordered kind, nesting, item count, and ordered-list starting number. Do not let translated prose accidentally become a list item; for example, if a wrapped date would begin a line with “1.”, rephrase it or keep it on the preceding line when the source is not a list.
173173
- Preserve HTML/MDX tag names, attribute names, nesting, and structural attribute values exactly. Never change resource or behavior attributes such as “href”, “src”, “id”, “icon”, “path”, “type”, or “default”.
174174
- Translate user-visible prose inside string-valued component attributes such as “title”, “label”, “description”, and “placeholder”, unless a higher-precedence literal UI-label rule protects that value. Do not translate code-like attribute values.
175-
- Do not translate or modify code spans, executable code or config blocks, config keys, CLI flags, environment variables, commands, or placeholders such as __OC_I18N_####__.
175+
- Do not translate or modify code spans, executable code or config blocks, config keys, CLI flags, environment variables, or commands. Preserve every placeholder byte-for-byte and with exactly the same occurrence count as in the input (for example, __OC_I18N_####__). Never repeat a placeholder when expanding a comparison or clarifying a reference. Express precedence chains as an inline priority order from highest to lowest, naming each item once; use pronouns for later references.
176176
- Fenced text, transcript, output, and documentation examples are an exception to the preceding block rule: preserve angle-bracket placeholders, square-bracket config/protocol markers, and double-bracket directive tokens exactly, but translate ordinary human prose, including prose surrounding protected directive tokens.
177177
- Do not alter URLs, anchors, path fragments, or identifier spelling.
178178
- Preserve link-label association: translate each Markdown link label in place. Never move link markup to a different word or entity, and never replace a protected product-name label with a neighboring product name.

‎scripts/docs-i18n/prompt_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ func TestTranslationPromptUsesSharedContractAndLocaleOverlayForEverySupportedLoc
4747
"Preserve HTML/MDX tag names, attribute names, nesting, and structural attribute values exactly",
4848
"Fenced text, transcript, output, and documentation examples are an exception to the preceding block rule",
4949
"Preserve link-label association: translate each Markdown link label in place",
50+
"Preserve every placeholder byte-for-byte and with exactly the same occurrence count as in the input",
51+
"Never repeat a placeholder when expanding a comparison or clarifying a reference",
52+
"Express precedence chains as an inline priority order from highest to lowest, naming each item once",
5053
"Translate user-visible prose inside string-valued component attributes such as “title”, “label”, “description”, and “placeholder”",
5154
"When they name the documented product, provider, protocol, integration, runtime, or plugin, also preserve ambiguous names exactly: Render, Matrix, Raft, Chutes, fal (title: Fal), Fireworks, Inferrs, Meta, Runway, Synthetic, Upstash Box, Lobster, Mantis, Tokenjuice",
5255
"Translate the same words normally when the source clearly uses them as ordinary prose instead of a name",

‎scripts/docs-i18n/translator.go‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,9 @@ func runCodexExecPrompt(ctx context.Context, req codexPromptRequest) (string, er
232232
"--model", req.Model,
233233
"-c", fmt.Sprintf("model_reasoning_effort=%q", normalizeThinking(req.Thinking)),
234234
"-c", `service_tier="fast"`,
235+
// Translation rules are developer instructions, not repo-guided user prose.
236+
"-c", fmt.Sprintf("developer_instructions=%q", req.SystemPrompt),
237+
"-c", "project_doc_max_bytes=0",
235238
"--sandbox", "read-only",
236239
"--ignore-rules",
237240
"--skip-git-repo-check",
@@ -240,7 +243,7 @@ func runCodexExecPrompt(ctx context.Context, req codexPromptRequest) (string, er
240243
}
241244
command := exec.CommandContext(ctx, docsCodexExecutable(), args...)
242245
configureCodexPromptCommand(command)
243-
command.Stdin = strings.NewReader(buildCodexTranslationPrompt(req.SystemPrompt, req.Message))
246+
command.Stdin = strings.NewReader(buildCodexTranslationPrompt(req.Message))
244247
command.Env = append(os.Environ(), "CODEX_HOME="+codexHome)
245248
var stdout bytes.Buffer
246249
var stderr bytes.Buffer
@@ -306,9 +309,8 @@ func docsCodexExecutable() string {
306309
return "codex"
307310
}
308311

309-
func buildCodexTranslationPrompt(systemPrompt, message string) string {
310-
return strings.TrimSpace(systemPrompt) + "\n\n" +
311-
"Translate the exact input below. Return only the translated text, with no tool calls, reasoning, or commentary. Do not wrap the response in an additional code fence; preserve every code fence already present in the input exactly.\n\n" +
312+
func buildCodexTranslationPrompt(message string) string {
313+
return "Translate the exact input below. Return only the translated text, with no tool calls, reasoning, or commentary. Do not wrap the response in an additional code fence; preserve every code fence already present in the input exactly.\n\n" +
312314
"<openclaw_docs_i18n_input>\n" +
313315
message +
314316
"\n</openclaw_docs_i18n_input>\n"

‎scripts/docs-i18n/translator_test.go‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,10 +180,9 @@ func TestCodexTranslatorUsesExactGlossaryMatchWithoutPrompt(t *testing.T) {
180180
}
181181

182182
func TestBuildCodexTranslationPromptIncludesGuardrailsAndInput(t *testing.T) {
183-
prompt := buildCodexTranslationPrompt("System prompt.", "Hello\nworld")
183+
prompt := buildCodexTranslationPrompt("Hello\nworld")
184184

185185
for _, want := range []string{
186-
"System prompt.",
187186
"Return only the translated text",
188187
"Do not wrap the response in an additional code fence",
189188
"preserve every code fence already present in the input exactly",
@@ -216,6 +215,8 @@ set -eu
216215
out=""
217216
saw_effort=0
218217
saw_service=0
218+
saw_contract=0
219+
saw_project_docs_disabled=0
219220
while [ "$#" -gt 0 ]; do
220221
case "$1" in
221222
--output-last-message)
@@ -231,12 +232,24 @@ while [ "$#" -gt 0 ]; do
231232
service_tier=\"fast\")
232233
saw_service=1
233234
;;
235+
developer_instructions=\"Translate.\")
236+
saw_contract=1
237+
;;
238+
project_doc_max_bytes=0)
239+
saw_project_docs_disabled=1
240+
;;
234241
esac
235242
;;
236243
esac
237244
shift || true
238245
done
239-
cat >/dev/null
246+
input="$(cat)"
247+
case "$input" in
248+
*"Translate."*)
249+
echo "translation contract must not be repeated in user input" >&2
250+
exit 1
251+
;;
252+
esac
240253
if [ "$saw_effort" != "1" ]; then
241254
echo "missing high reasoning effort config" >&2
242255
exit 1
@@ -245,6 +258,10 @@ if [ "$saw_service" != "1" ]; then
245258
echo "missing fast service tier config" >&2
246259
exit 1
247260
fi
261+
if [ "$saw_contract" != "1" ] || [ "$saw_project_docs_disabled" != "1" ]; then
262+
echo "missing isolated developer translation contract" >&2
263+
exit 1
264+
fi
248265
if [ -z "${CODEX_HOME:-}" ]; then
249266
echo "missing CODEX_HOME" >&2
250267
exit 1

0 commit comments

Comments
 (0)