chore(westernization): add rebase-verification tooling and docs

The October rebase silently shipped runtime-breaking merge artifacts that
neither the web build nor the test suites caught (blank models page,
ReferenceError on role open, broken provider management). Make every one
of those failure classes fail loudly and early:

- manager-web/scripts/integrity-check.js: AST pass (acorn + eslint-scope)
  for undefined identifiers (lost imports, dropped function params and
  const bindings), vue-template-compiler pass for mismatched tags, and a
  duplicate-options-key pass (double 'computed:' clobbering). Negative-
  tested against reproductions of all three shipped bugs.
- manager-web/scripts/check-i18n.js rewritten for the fork: base locale
  is en, locales discovered dynamically, plus a pass that fails when any
  $t('a.b') key referenced in src/ has no definition (upstream rebases
  kept adding views with keys never added downstream).
- scripts/westernization_rebase_check.sh: one-command gate chaining audit,
  integrity, i18n parity, snapshot/contract/unit tests and the production
  build; heavier Java/Python suites run only when toolchains exist.
- scripts/translate_han_llm.py: vendored from the one-off /tmp tool used
  for the translation sweep; repo-relative paths, endpoint/model via
  TRANSLATE_API/TRANSLATE_MODEL env, cache gitignored.
- CI: the Vue job now runs integrity-check, check:i18n, test:snapshot and
  test:contract before test:unit; new nightly Upstream Sync Check workflow
  dry-merges upstream/main into a throwaway branch and runs the same web
  gates so a breaking incoming merge alerts before a human sync.
- westernization.md: tooling table, five known merge-corruption failure
  classes with symptoms and repair strategy, translator usage, updated
  rebase order and good-outcome checklist.

acorn and eslint-scope are now explicit devDependencies.
This commit is contained in:
lapy 2026-10-13 11:35:11 +01:00
parent 50b9d6974d
commit cd83c805f5
10 changed files with 827 additions and 52 deletions

View file

@ -66,4 +66,8 @@ jobs:
working-directory: main/manager-web
run: |
npm ci --no-audit --no-fund
node scripts/integrity-check.js
npm run check:i18n
npm run test:snapshot
npm run test:contract
npm run test:unit

View file

@ -0,0 +1,51 @@
name: Upstream Sync Check
# Nightly dry-run: merge upstream/main into the downstream branch in a
# throwaway workspace and run the web verification gates against the merged
# result. This gives an early, loud signal ("the next sync will break") the
# night before a human performs the real sync, instead of after deploy.
# It never pushes anything.
on:
schedule:
- cron: '30 4 * * *' # 04:30 UTC daily
workflow_dispatch:
jobs:
dry-merge:
name: Merge upstream/main and run web gates
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Configure git identity
run: |
git config user.email "ci@localhost"
git config user.name "upstream-sync-check"
- name: Merge upstream/main (dry run)
run: |
git remote add upstream https://github.com/xinnan-tech/xiaozhi-esp32-server.git || true
git fetch upstream main
git checkout -B sync-dry-run
if ! git merge --no-commit --no-ff upstream/main; then
echo "::error::upstream/main no longer merges cleanly into this branch; resolve conflicts before syncing"
git diff --name-only --diff-filter=U || true
exit 1
fi
echo "MERGED_CLEAN=1" >> "$GITHUB_ENV"
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: main/manager-web/package-lock.json
- name: Web gates on merged tree
working-directory: main/manager-web
run: |
npm ci --no-audit --no-fund
node scripts/integrity-check.js
npm run --silent check:i18n
npm run --silent test:snapshot
npm run --silent test:contract
- name: Westernization audit on merged tree
run: bash scripts/westernization_audit.sh

1
.gitignore vendored
View file

@ -187,3 +187,4 @@ uploadfile
!main/manager-mobile/**/*.json
original-server
scripts/.translate_cache.json

View file

@ -34,7 +34,9 @@
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/test-utils": "^1.3.6",
"acorn": "^8.18.0",
"compression-webpack-plugin": "^11.1.0",
"eslint-scope": "^5.1.1",
"jsdom": "^24.1.0",
"sass": "^1.32.7",
"sass-loader": "^12.0.0",
@ -4164,7 +4166,6 @@
"resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.18.0.tgz",
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
},

View file

@ -5,6 +5,7 @@
"scripts": {
"serve": "vue-cli-service serve",
"check:i18n": "node scripts/check-i18n.js",
"check:integrity": "node scripts/integrity-check.js",
"test:snapshot": "node --test src/components/agentSnapshotDisplayUtils.test.mjs src/apis/module/agentSnapshotApi.test.mjs",
"build": "vue-cli-service build",
"test:contract": "node --test tests/*Contract.test.mjs",
@ -39,7 +40,9 @@
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/test-utils": "^1.3.6",
"acorn": "^8.18.0",
"compression-webpack-plugin": "^11.1.0",
"eslint-scope": "^5.1.1",
"jsdom": "^24.1.0",
"sass": "^1.32.7",
"sass-loader": "^12.0.0",

View file

@ -1,50 +1,80 @@
/*
* i18n consistency checker (westernized fork).
*
* Differences from upstream's version:
* - The fork removed zh_CN/zh_TW locales; the base locale is `en`.
* - Locale set is discovered from src/i18n/*.js instead of hardcoded.
* - Also verifies that every static translation key referenced anywhere in
* src/ ($t('a.b'), i18n.t('a.b'), this.$t('a.b'), t('a.b')) exists in the
* base locale. Upstream rebases repeatedly added views calling $t() for
* keys that were never added downstream, which renders raw keys/blank
* labels at runtime with no build error.
*/
const fs = require('fs');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
const locales = [
{ name: 'zh_CN', file: 'src/i18n/zh_CN.js' },
{ name: 'zh_TW', file: 'src/i18n/zh_TW.js' },
{ name: 'en', file: 'src/i18n/en.js' },
{ name: 'de', file: 'src/i18n/de.js' },
{ name: 'vi', file: 'src/i18n/vi.js' },
{ name: 'pt_BR', file: 'src/i18n/pt_BR.js' },
];
const i18nDir = path.join(rootDir, 'src/i18n');
const BASE = 'en';
function discoverLocales() {
return fs
.readdirSync(i18nDir)
.filter((f) => f.endsWith('.js') && f !== 'index.js')
.map((f) => ({ name: f.replace(/\.js$/, ''), file: `src/i18n/${f}` }))
.sort((a, b) => (a.name === BASE ? -1 : b.name === BASE ? 1 : a.name.localeCompare(b.name)));
}
function evalLocale(file) {
const src = fs.readFileSync(path.join(rootDir, file), 'utf8');
const objText = src.replace(/^\s*import[^;]+;\s*$/gm, '').replace(/export\s+default\s*/, '');
// Locale files are plain object literals; evaluate without importing (ESM).
// eslint-disable-next-line no-new-func
return new Function(`"use strict"; return (${objText});`)();
}
function readLocale(locale) {
const filePath = path.join(rootDir, locale.file);
const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
const keys = [];
const flat = evalLocale(locale.file);
const keys = Object.keys(flat);
// duplicate detection on raw text (object literal would silently dedupe)
const lines = fs.readFileSync(path.join(rootDir, locale.file), 'utf8').split(/\r?\n/);
const seen = new Map();
const duplicates = [];
lines.forEach((line, index) => {
const match = line.match(/^\s*['"]([^'"]+)['"]\s*:/);
if (!match) {
return;
}
const key = match[1];
keys.push(key);
if (!seen.has(key)) {
seen.set(key, []);
}
seen.get(key).push(index + 1);
if (!match) return;
if (!seen.has(match[1])) seen.set(match[1], []);
seen.get(match[1]).push(index + 1);
});
seen.forEach((lineNumbers, key) => {
if (lineNumbers.length > 1) {
duplicates.push({ key, lineNumbers });
}
if (lineNumbers.length > 1) duplicates.push({ key, lineNumbers });
});
return { ...locale, keys, keySet: new Set(keys), duplicates, flat };
}
return {
...locale,
filePath,
keys,
keySet: new Set(keys),
duplicates,
};
function walk(dir, out = []) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) {
if (e.name !== 'node_modules') walk(p, out);
} else if (/\.(vue|js)$/.test(e.name) && !p.startsWith(i18nDir)) {
out.push(p);
}
}
return out;
}
function collectReferencedKeys() {
const keys = new Map(); // key -> first file seen
const re = /(?:\$t|\bt)\(\s*['"]([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)['"]\s*[,)]/g;
for (const f of walk(path.join(rootDir, 'src'))) {
const src = fs.readFileSync(f, 'utf8');
let m;
while ((m = re.exec(src))) {
if (!keys.has(m[1])) keys.set(m[1], path.relative(rootDir, f));
}
}
return keys;
}
function diffKeys(left, right) {
@ -52,19 +82,21 @@ function diffKeys(left, right) {
}
function formatKeyList(keys) {
return keys.length ? keys.map((key) => ` - ${key}`).join('\n') : '';
return keys.length ? keys.map((k) => ` - ${k}`).join('\n') : '';
}
function main() {
const results = locales.map(readLocale);
const base = results.find((locale) => locale.name === 'zh_CN');
const results = discoverLocales().map(readLocale);
const base = results.find((l) => l.name === BASE);
if (!base) {
console.error(`base locale "${BASE}" not found under src/i18n`);
process.exit(1);
}
const errors = [];
results.forEach((locale) => {
locale.duplicates.forEach(({ key, lineNumbers }) => {
errors.push(
`${locale.file} has duplicate key "${key}" on lines ${lineNumbers.join(', ')}`
);
errors.push(`${locale.file} has duplicate key "${key}" on lines ${lineNumbers.join(', ')}`);
});
});
@ -73,24 +105,33 @@ function main() {
.forEach((locale) => {
const missing = diffKeys(base.keySet, locale.keySet);
const extra = diffKeys(locale.keySet, base.keySet);
if (missing.length) {
errors.push(`${locale.file} is missing keys from ${base.file}:\n${formatKeyList(missing)}`);
}
if (extra.length) {
errors.push(`${locale.file} has keys that do not exist in ${base.file}:\n${formatKeyList(extra)}`);
}
});
const referenced = collectReferencedKeys();
const unresolved = [...referenced].filter(([k]) => !base.keySet.has(k));
if (unresolved.length) {
errors.push(
`referenced translation keys missing from ${base.file}:\n` +
unresolved.map(([k, f]) => ` - ${k} (used in ${f})`).join('\n')
);
}
if (errors.length) {
console.error(`i18n check failed with ${errors.length} issue(s):`);
console.error(errors.join('\n\n'));
process.exit(1);
}
const keyCount = base.keySet.size;
console.log(`i18n check passed: ${results.length} locale files, ${keyCount} keys each.`);
console.log(
`i18n check passed: ${results.length} locales x ${base.keySet.size} keys, ` +
`${referenced.size} referenced keys all resolve.`
);
}
main();

View file

@ -0,0 +1,194 @@
#!/usr/bin/env node
/*
* Post-rebase web integrity checker.
*
* The upstream rebase has repeatedly produced *silent* runtime breakage that
* `vue-cli-service build` does NOT fail on and that unit tests (which do not
* mount full views) do not catch. Three classes of corruption have bitten us:
*
* 1. Lost/duplicated imports -> shorthand component/object references to an
* identifier that was never imported/declared (e.g. `components:
* { CustomDialog }` with no import). Throwing module factory makes
* webpack cache a half-initialized module and vue-router silently renders
* a blank page (no console error).
*
* 2. Dropped function-signature parameters / const bindings (e.g. a method
* body that references `request`, `onTerminalFailure`, `retryCount`,
* `retryWindowStartedAt`, `failCallback` after the merge deleted them
* from the signature). Throws ReferenceError at call time.
*
* 3. Interleaved / half-converted Vue templates -> mismatched tags
* (`<el-button>` ... `</CustomButton>`, `<CustomDialog>` ... `</el-dialog>`)
* and duplicated option keys (`computed:` twice) that silently clobber
* each other.
*
* This script fails hard (exit 1) if any of those reappear, so a future
* rebase cannot merge them in silently. Run via `npm run check:integrity`
* (wired into CI and into scripts/westernization_rebase_check.sh).
*/
const fs = require('fs');
const path = require('path');
const acorn = require('acorn');
const { analyze } = require('eslint-scope');
const { parseComponent, compile } = require('vue-template-compiler');
const ROOT = path.resolve(__dirname, '..');
const SRC = path.join(ROOT, 'src');
// Browser/ES/Node globals that legitimately resolve outside module scope.
const GLOBALS = new Set([
'window', 'document', 'navigator', 'location', 'localStorage', 'sessionStorage', 'console',
'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'requestAnimationFrame',
'cancelAnimationFrame', 'Promise', 'JSON', 'Math', 'Date', 'Array', 'Object', 'String',
'Number', 'Boolean', 'Symbol', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Proxy', 'Reflect',
'Error', 'TypeError', 'RangeError', 'SyntaxError', 'EvalError', 'ReferenceError',
'URIError', 'RegExp', 'encodeURIComponent', 'decodeURIComponent', 'encodeURI', 'decodeURI',
'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'fetch', 'URL', 'URLSearchParams', 'Blob',
'File', 'FileReader', 'FormData', 'AbortController', 'AbortSignal', 'atob', 'btoa',
'Image', 'Audio', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'MutationObserver',
'IntersectionObserver', 'ResizeObserver', 'performance', 'crypto', 'process', 'Function',
'alert', 'confirm', 'prompt', 'getComputedStyle', 'matchMedia', 'CSS', 'DOMParser',
'XMLSerializer', 'TextEncoder', 'TextDecoder', 'Uint8Array', 'Int8Array', 'Uint16Array',
'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array',
'Uint8ClampedArray', 'DataView', 'ArrayBuffer', 'Notification', 'caches', 'indexedDB',
'self', 'globalThis', 'structuredClone', 'queueMicrotask', 'Intl', 'eval', 'arguments',
'AudioContext', 'webkitAudioContext', 'Element', 'Node', 'HTMLElement', 'SVGElement',
'Event', 'CustomEvent', 'KeyboardEvent', 'MouseEvent', 'DOMException', 'devicePixelRatio',
'screen', 'history', 'Worker', 'IDBKeyRange', 'SpeechSynthesisUtterance', 'Range', 'Text',
'undefined', 'NaN', 'Infinity', 'global', 'module', 'require', 'exports', 'Buffer',
'__dirname', '__filename', 'Response', 'Request', 'Headers', 'importScripts',
// ServiceWorker scope (src/service-worker.js, injected by workbox)
'workbox', 'skipWaiting', 'clients', 'registration', 'serviceWorker',
]);
// Vue SFC macros available inside <script setup>.
const SETUP_MACROS = new Set(['defineProps', 'defineEmits', 'defineExpose', 'defineSlots', 'withDefaults', 'withDefaults', 'defineModel', 'useSlots', 'useAttrs', 'defineOptions', 'defineComponent']);
function walk(dir, out = []) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (e.name === 'node_modules' || e.name === 'tests') continue;
const p = path.join(dir, e.name);
if (e.isDirectory()) walk(p, out);
else if (/\.(js|vue)$/.test(e.name)) out.push(p);
}
return out;
}
function scriptsOf(file, raw) {
if (!file.endsWith('.vue')) return [{ code: raw, offset: 1, setup: false }];
const parts = [];
const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
let m;
while ((m = re.exec(raw))) {
const attrs = m[1] || '';
const start = m.index + m[0].indexOf(m[2]);
parts.push({
code: m[2],
offset: raw.slice(0, start).split('\n').length,
setup: /\bsetup\b/.test(attrs),
});
}
return parts;
}
const errors = [];
function addError(kind, file, line, msg) {
errors.push(`${kind} ${path.relative(ROOT, file)}${line ? ':' + line : ''} ${msg}`);
}
// ---- Pass 1: undefined free identifiers (classes 1 & 2) ------------------
for (const f of walk(SRC)) {
const raw = fs.readFileSync(f, 'utf8');
for (const s of scriptsOf(f, raw)) {
let ast;
try {
ast = acorn.parse(s.code, {
ecmaVersion: 'latest', sourceType: 'module', locations: true, ranges: true,
allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true,
});
} catch (e) {
addError('PARSE', f, s.offset, e.message);
continue;
}
const sm = analyze(ast, { ecmaVersion: 13, sourceType: 'module' });
const globalScope = sm.scopes.find((sc) => sc.type === 'global');
for (const ref of globalScope.through) {
const name = ref.identifier.name;
if (GLOBALS.has(name)) continue;
if (s.setup && SETUP_MACROS.has(name)) continue;
// `Function` and other globals already filtered; report the rest.
const loc = ref.identifier.loc;
addError('UNDEF', f, loc ? s.offset + loc.start.line - 1 : s.offset, name);
}
}
}
// ---- Pass 2: Vue template compile errors (class 3) -----------------------
for (const f of walk(SRC)) {
if (!f.endsWith('.vue')) continue;
const sfc = parseComponent(fs.readFileSync(f, 'utf8'));
if (!sfc.template || !sfc.template.content.trim()) continue;
const res = compile(sfc.template.content, { preserveWhitespace: false });
if (res.errors && res.errors.length) {
for (const e of res.errors.slice(0, 6)) addError('TEMPLATE', f, null, String(e).slice(0, 140));
}
}
// ---- Pass 3: duplicated top-level Vue options keys (class 3) -------------
const OPTION_KEYS = new Set([
'name', 'components', 'directives', 'mixins', 'props', 'data', 'computed',
'methods', 'watch', 'created', 'mounted', 'beforeMount', 'updated',
'beforeUpdate', 'destroyed', 'beforeDestroy', 'activated', 'deactivated',
'render', 'template', 'inheritAttrs', 'model', 'provide', 'inject', 'filters',
]);
function dupOptionKeys(scriptCode) {
// Find `export default { ... }` object and read depth-1 keys.
const i = scriptCode.indexOf('export default');
if (i < 0) return [];
const start = scriptCode.indexOf('{', i);
if (start < 0) return [];
const keys = [];
let depth = 0, k = start, str = null;
while (k < scriptCode.length) {
const ch = scriptCode[k];
if (str) {
if (ch === '\\') { k += 2; continue; }
if (ch === str) str = null;
k++; continue;
}
if (ch === '"' || ch === "'" || ch === '`') { str = ch; k++; continue; }
if (ch === '{') { depth++; k++; continue; }
if (ch === '}') { depth--; if (depth === 0) break; k++; continue; }
if (depth === 1) {
const mm = /^([A-Za-z_$][\w$]*)\s*:/.exec(scriptCode.slice(k, k + 60));
if (mm) {
const ls = scriptCode.lastIndexOf('\n', k);
if (scriptCode.slice(ls + 1, k).trim() === '') {
keys.push(mm[1]);
k += mm[0].length - 1;
}
}
}
k++;
}
const seen = new Map();
for (const key of keys) seen.set(key, (seen.get(key) || 0) + 1);
return [...seen].filter(([key, n]) => n > 1 && OPTION_KEYS.has(key)).map(([key]) => key);
}
for (const f of walk(SRC)) {
if (!f.endsWith('.vue')) continue;
const raw = fs.readFileSync(f, 'utf8');
const sfc = parseComponent(raw);
const opts = sfc.script ? sfc.script.content : '';
for (const dup of dupOptionKeys(opts)) {
addError('DUP-OPT', f, null, `duplicate options key "${dup}" (later block clobbers the first)`);
}
}
// ---- Report --------------------------------------------------------------
if (errors.length) {
console.error(`web integrity check FAILED with ${errors.length} issue(s):`);
for (const e of errors) console.error(' ' + e);
process.exit(1);
}
console.log('web integrity check passed: no undefined identifiers, template errors, or duplicate option keys.');

View file

@ -0,0 +1,325 @@
#!/usr/bin/env python3
"""Translate Han-script spans in repo source to English using the local Qwen
OpenAI-compatible server (http://10.0.1.9:2000/v1, model qwen3.8).
Batched: each request carries a JSON array of spans; model must reply with a
same-length JSON array. Placeholder-safe, cached, resumable.
"""
import concurrent.futures as cf
import json
import os
import re
import sys
import threading
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
API = os.environ.get("TRANSLATE_API", "http://10.0.1.9:2000/v1/chat/completions")
MODEL = os.environ.get("TRANSLATE_MODEL", "qwen3.8:instruct")
EXCEPTION_PREFIXES = (
# User decision 2026-10-11: keep the two documented audit exception zones.
"main/manager-api/src/main/resources/db/changelog/",
"main/manager-web/public/generator/",
# Cubism model data (not audit-visible, functional as-is).
"main/digital-human/resources/",
"main/xiaozhi-server/models/",
"main/xiaozhi-server/assets/",
)
SKIP_DIR_PARTS = {
".git", "node_modules", "dist", "target", "build", "unpackage",
".webpack_cache", "logs", "__pycache__", ".venv", "venv", ".venv-xiaozhi",
"tmp", ".pytest_cache", ".pnpm-store", "env",
}
SKIP_EXT = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bin", ".onnx", ".so",
".ttf", ".woff", ".woff2", ".mp3", ".wav", ".opus", ".pdf", ".ico",
".jit", ".cmo3", ".can3", ".pyc", ".key", ".crt",
}
HAN = "\u4e00-\u9fff\u3400-\u4dbf"
CJK_RUN = re.compile(
rf"(?:[{HAN}][\u3000-\u303f\uff01-\uff5e\u201c\u201d\u2018\u2019\u2026\u00b7\u3001\u2014{HAN}]|[ \w.\-/:%#\u00b7][{HAN}]|[{HAN}])+"
)
_cache: dict[str, str] = {}
_lock = threading.Lock()
CACHE_FILE = Path(__file__).resolve().parent / ".translate_cache.json"
PROMPT = """You are a professional code-localization engine for an open-source voice-assistant project (English-first fork of a Chinese upstream).
You receive a JSON array of Chinese strings extracted from code comments, docstrings, log/exception messages, UI text and documentation.
Translate EVERY string to natural, concise English.
Hard rules:
- Reply with ONLY a JSON array of translated strings, same length, same order. No numbering, no explanations, no markdown fences, no trailing text.
- Keep byte-for-byte: printf specifiers (%s %d %5.2f), brace placeholders ({} {name} {{x}}), literal escape sequences (\\n \\t), XML/HTML/JSON tags (<memory> etc.), URLs, file paths, code identifiers, numbers, and any token matching XPH<number>.
- Keep the same punctuation style and trailing punctuation as the source.
- Do not merge, split, add, or drop items.
- Personal names may be rendered in pinyin.
Input:
"""
def _post(messages, max_tokens=8000):
body = {
"model": MODEL,
"messages": messages,
"temperature": 0,
"max_tokens": max_tokens,
"chat_template_kwargs": {"enable_thinking": False},
}
req = urllib.request.Request(
API, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=240) as r:
data = json.loads(r.read().decode())
return data["choices"][0]["message"]["content"] or ""
def _extract_array(text: str):
text = text.strip()
start = text.find("[")
while start != -1:
for end in range(len(text), start, -1):
chunk = text[start:end]
if not chunk.endswith("]"):
continue
try:
arr = json.loads(chunk)
except Exception:
continue
if isinstance(arr, list):
return arr
break
text = text[start + 1:]
start = text.find("[")
return None
PLACEHOLDER_RE = re.compile(r"%[-+ #0]*\d*\.?\d*[sdfiox]|\{\{?\w*\}?\}|XPH\d+|<[^<>\n]{1,30}>|\\[nt]")
def _placeholders_ok(src: str, out: str) -> bool:
missing = []
for tok in set(PLACEHOLDER_RE.findall(src)):
if tok not in out:
# tolerate tag-case and spacing differences
missing.append(tok)
if not missing:
return True
# \n counts should not shrink
if out.count("\\n") < src.count("\\n"):
return False
return False
def translate_batch(spans: list[str]) -> list[str | None]:
"""Translate a batch; returns list aligned with input (None on failure)."""
masked = []
masks = []
for s in spans:
toks = list(dict.fromkeys(PLACEHOLDER_RE.findall(s)))
m = s
for i, tok in enumerate(toks):
m = m.replace(tok, f"XPH{i}X", 1)
masks.append(toks)
masked.append(m)
results: list[str | None] = [None] * len(spans)
pending = list(range(len(spans)))
for attempt in range(3):
if not pending:
break
chunk = [masked[i] for i in pending]
try:
reply = _post([{"role": "user", "content": PROMPT + json.dumps(chunk, ensure_ascii=False)}])
except Exception as e:
print(f" request failed ({e}), retry {attempt+1}", flush=True)
time.sleep(2 + attempt * 3)
continue
arr = _extract_array(reply)
if arr is None or len(arr) != len(pending):
# length mismatch: retry once with halves, else singles next loop
if arr is None:
continue
# partial salvage where possible is risky on order; retry same batch
continue
still = []
for idx, item in zip(pending, arr):
out = str(item)
toks = masks[idx]
for i, tok in enumerate(toks):
out = out.replace(f"XPH{i}X", tok)
if re.search(f"[{HAN}]", out) or not out.strip():
still.append(idx)
elif not _placeholders_ok(masked[idx].replace("XPH", ""), out) and False:
still.append(idx)
elif not _placeholders_ok(masked[idx], out):
still.append(idx)
else:
results[idx] = out.strip()
pending = still
# singles fallback for stragglers
for i in list(pending):
try:
reply = _post([{"role": "user", "content": PROMPT + json.dumps([masked[i]], ensure_ascii=False)}], max_tokens=1000)
arr = _extract_array(reply)
if arr and len(arr) == 1:
out = str(arr[0])
for k, tok in enumerate(masks[i]):
out = out.replace(f"XPH{k}X", tok)
if not re.search(f"[{HAN}]", out) and _placeholders_ok(masked[i], out):
results[i] = out.strip()
pending.remove(i)
except Exception:
pass
if pending:
with _lock:
for i in pending:
_cache.setdefault(spans[i], spans[i]) # keep original
return results
def save_cache():
with _lock:
CACHE_FILE.write_text(json.dumps(_cache, ensure_ascii=False))
def load_cache():
if CACHE_FILE.exists():
try:
_cache.update(json.loads(CACHE_FILE.read_text()))
except Exception:
pass
def candidate_files(paths=None):
import subprocess
if paths:
return [ROOT / p for p in paths]
out = subprocess.check_output(["git", "-C", str(ROOT), "ls-files", "-co", "--exclude-standard"], text=True)
files = []
for line in out.splitlines():
p = Path(line)
parts = set(p.parts)
if parts & SKIP_DIR_PARTS:
continue
if p.suffix.lower() in SKIP_EXT:
continue
if any(line.startswith(pre) for pre in EXCEPTION_PREFIXES):
continue
f = ROOT / p
if not f.is_file():
continue
try:
raw = f.read_bytes()
except OSError:
continue
if b"\x00" in raw:
continue
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
continue
if re.search(f"[{HAN}]", text):
files.append(f)
return files
def collect_spans(files):
spans: set[str] = set()
for f in files:
try:
text = f.read_bytes().decode("utf-8")
except Exception:
continue
for m in CJK_RUN.finditer(text):
core = m.group(0).strip()
if core and re.search(f"[{HAN}]", core) and core not in _cache:
spans.add(core)
return sorted(spans)
def translate_all(spans, batch=24, workers=4):
batches = [spans[i:i + batch] for i in range(0, len(spans), batch)]
done = 0
with cf.ThreadPoolExecutor(max_workers=workers) as ex:
for res in ex.map(translate_batch, batches):
with _lock:
for s, t in zip(batches[0][:0] + [], res):
pass
done += 1
if done % 10 == 0:
print(f" batches {done}/{len(batches)}", flush=True)
save_cache()
def translate_all2(spans, batch=24, workers=4):
"""Proper batch runner keeping span alignment."""
batches = [spans[i:i + batch] for i in range(0, len(spans), batch)]
done = 0
def work(b):
outs = translate_batch(b)
with _lock:
for s, t in zip(b, outs):
if t:
_cache[s] = t
return b
with cf.ThreadPoolExecutor(max_workers=workers) as ex:
for _ in ex.map(work, batches):
done += 1
if done % 10 == 0:
print(f" batches {done}/{len(batches)}", flush=True)
save_cache()
def apply_files(files):
changed = 0
for f in files:
try:
text = f.read_bytes().decode("utf-8")
except Exception:
continue
def repl(m):
raw = m.group(0)
core = raw.strip()
if not re.search(f"[{HAN}]", core):
return raw
lead = raw[: len(raw) - len(raw.lstrip())]
trail = raw[len(raw.rstrip()):]
tr = _cache.get(core)
if tr is None or re.search(f"[{HAN}]", tr):
return raw
return lead + tr + trail
new = CJK_RUN.sub(repl, text)
if new != text:
f.write_bytes(new.encode("utf-8"))
changed += 1
return changed
def main():
load_cache()
paths = sys.argv[1:]
files = candidate_files(paths or None)
spans = collect_spans(files)
print(f"{len(files)} files, {len(spans)} spans to translate", flush=True)
translate_all2(spans)
save_cache()
changed = apply_files(files)
print(f"rewrote {changed} files", flush=True)
left = candidate_files()
print(f"leftover files with Han: {len(left)}")
for f in left[:40]:
print(" ", f.relative_to(ROOT))
# leftover spans report
left_spans = collect_spans(left)
print(f"leftover untranslated spans: {len(left_spans)}")
for s in left_spans[:15]:
print(" !", s[:80])
if __name__ == "__main__":
main()

View file

@ -0,0 +1,73 @@
#!/usr/bin/env bash
#
# Post-rebase verification gate for the westernized downstream branch.
#
# Run this after every upstream sync/rebase, BEFORE promoting the integration
# branch. It chains the checks that historically caught real regressions that
# `npm run build` and the unit suites do NOT catch on their own:
#
# * westernization audit (Han-script / path scan, exception zones)
# * manager-web integrity (undefined identifiers, template tag mismatches,
# duplicated Vue option keys -> the silent-blank-page class of bugs)
# * manager-web i18n parity + referenced-key coverage
# * manager-web snapshot/contract + unit tests
# * manager-web production build
#
# Subsystem suites that need heavier toolchains (Java, Python) are listed at
# the end but only run when their toolchain is present, so this script is safe
# to run in a web-only environment.
set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
fail=0
run() {
local name="$1"; shift
echo
echo "==> $name"
if "$@"; then
echo "--- PASS: $name"
else
echo "--- FAIL: $name"
fail=1
fi
}
# 1. Westernization audit (Han-script, paths, generator bundle).
run "westernization audit" bash scripts/westernization_audit.sh
# 2..5 manager-web checks (need node_modules; install if missing).
if [ -d main/manager-web/node_modules ] || npm --prefix main/manager-web ci --no-audit --no-fund >/dev/null 2>&1; then
run "manager-web integrity" node main/manager-web/scripts/integrity-check.js
run "manager-web i18n parity" npm --prefix main/manager-web run --silent check:i18n
run "manager-web snapshot tests" npm --prefix main/manager-web run --silent test:snapshot
run "manager-web contract tests" npm --prefix main/manager-web run --silent test:contract
run "manager-web unit tests" npm --prefix main/manager-web run --silent test:unit
run "manager-web build" npm --prefix main/manager-web run --silent build
else
echo "!! manager-web: node/npm unavailable or install failed - SKIPPING web checks"
fail=1
fi
# 6. Optional heavier suites when toolchains exist.
if command -v mvn >/dev/null 2>&1; then
run "manager-api compile" mvn -q -f main/manager-api/pom.xml -DskipTests compile
else
echo "==> mvn not present - skipping manager-api compile"
fi
if command -v python3 >/dev/null 2>&1 && python3 -c 'import pytest' >/dev/null 2>&1; then
( cd main/xiaozhi-server && PYTHONPATH=. pytest tests/test_smoke.py -q ) \
&& echo "--- PASS: python smoke" || { echo "--- FAIL: python smoke"; fail=1; }
else
echo "==> pytest not present - skipping python smoke"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "ALL REBASE CHECKS PASSED"
else
echo "REBASE CHECKS FAILED - fix the above before promoting the branch"
fi
exit "$fail"

View file

@ -171,6 +171,71 @@ If Han-script appears in the generated code bundle, fix the generator source
first before attempting bundle surgery. The audit treats the code bundle as
live source; only `generator/static` data is exempt.
## Verification Tooling (run these, don't trust the build)
`npm run build` treats broken Vue templates as *warnings* and the unit suites
do not mount full views, so a rebase can merge real breakage while everything
stays green. The 2026-10 rebase shipped three such silent regressions (blank
models page, `ReferenceError: request is not defined` when opening a role,
provider management rendered as garbage). All are now machine-checked:
| Check | Command | Catches |
| --- | --- | --- |
| Integrity | `node main/manager-web/scripts/integrity-check.js` | undefined identifiers (lost imports, dropped function params/`const request` bindings), mismatched template tags, duplicated Vue option keys (`computed:` twice clobbers the first) |
| i18n | `cd main/manager-web && npm run check:i18n` | duplicate keys, cross-locale drift vs `en`, `$t('...')` keys with no definition in any locale |
| Snapshot contract | `npm run test:snapshot` | agent snapshot API shape (`restoreAgentSnapshot` etc. were silently deleted once, while `AgentSnapshotDialog.vue` still called them) |
| Han audit | `./scripts/westernization_audit.sh` | Chinese text/paths outside exception zones |
| Everything | `./scripts/westernization_rebase_check.sh` | one gate chaining all of the above plus build and smoke suites |
CI runs the same set: `Westernization audit` job plus the `Vue (manager-web)`
job (`integrity-check -> check:i18n -> test:snapshot -> test:contract ->
test:unit`). A nightly `Upstream Sync Check` workflow dry-merges
`upstream/main` and runs the web gates on the merged result, so an incoming
breaking merge alerts the night before a human syncs.
### Known merge-corruption failure classes (2026-10 postmortem)
These are the shapes the auto-merge produced; the integrity checker flags all
of them, but knowing the shapes speeds up conflict resolution:
1. **Lost import** - `components: { CustomDialog }` shorthand with no matching
`import`. The chunk throws at eval time; webpack 5 caches the failed module,
so vue-router silently registers `default === undefined` and the page
renders `<!---->` with no console error.
2. **Dropped signature params / const bindings** - method bodies referencing
`request`, `onTerminalFailure`, `retryCount`, `retryWindowStartedAt`,
`failCallback` after the merge kept the old one-line signature. Compare
against `upstream/main` when a method looks half-converted.
3. **Whole methods deleted** while callers survive in another merged file
(`getRAGModels`, snapshot API). The integrity checker cannot see this (no
undefined identifier), so `Api.*` cross-reference plus the snapshot contract
tests exist; re-run the cross-reference from the postmortem after big
merges (snippet in commit `583c5304` message area, or grep `Api\.\w+\.\w+`
and diff against module exports).
4. **Interleaved implementations** - both an old `el-table` block and a new
`CustomTable` block merged into one view (ProviderManagement). When tags
mismatch like this, prefer taking upstream's newer version wholesale and
re-applying the few translation strings, instead of surgical repair.
5. **Half-converted components** - root tag converted (`el-dialog` ->
`CustomDialog`) but closing tag/footer wiring left behind
(FirmwareDialog, AddWisdomBodyDialog, CustomDialog's duplicated `computed`).
### Translation tool
The Han->English batch translator used for sweeps is vendored:
```bash
# needs the local OpenAI-compatible endpoint (override via env)
TRANSLATE_API=http://10.0.1.9:2000/v1/chat/completions \
TRANSLATE_MODEL=qwen3.8:instruct \
python3 scripts/translate_han_llm.py [path ...] # no args = whole repo
```
It is placeholder-safe (printf/brace/tag/URL masking), batched, cached
(`scripts/.translate_cache.json`, gitignored) and resumable. Never translate
inside the generator bundle - fix generator source (see Generator Rule) and
rebuild.
## Audit Workflow
Use the audit script after meaningful rebase batches:
@ -262,9 +327,18 @@ Harness files:
```bash
cd main/manager-web
npm run check:integrity # AST/template/option-key checks (see tooling table)
npm run check:i18n
npm test
npm run build
```
Or from the repo root, everything at once:
```bash
./scripts/westernization_rebase_check.sh
```
### Manager Mobile
```bash
@ -299,6 +373,7 @@ A rebase is in good shape when all of these are true:
- server runtime prompts and tool text are westernized
- docs and filenames are clean outside intentional exception zones
- `./scripts/westernization_audit.sh` passes
- `./scripts/westernization_rebase_check.sh` passes (integrity, i18n, web tests, build)
- `mvn -q -Dtest=LiquibaseWesternizationIntegrationTest test` passes
## Bad Smells
@ -312,20 +387,27 @@ Stop and correct course if any of these happen:
would do
- old migrations are rewritten instead of adding cleanup migrations
- the branch drifts into a single giant mixed overlay again
- the web build is green but a page renders blank - the build only *warns* on
broken templates; run `scripts/integrity-check.js`, it makes those errors
fatal
- a merged view/API file "looks fine" but half its function signatures changed
style - diff the file against `upstream/main`, not just against HEAD~1
## Practical Order On Future Rebases
When upstream moves a lot, use this order:
1. rebase or merge upstream into an integration branch
2. restore provider/runtime deletions and relocalization
3. restore admin API provider filtering and downstream cleanup migrations
4. restore web/mobile surface cleanup
5. restore docs/branding cleanup
6. rebuild generator from source if needed
7. run the audit script
8. run subsystem validation
9. only then promote the integration branch
2. scan the merge result for the five corruption shapes listed under "Known
merge-corruption failure classes" (`integrity-check.js` finds 1, 2, 4, 5)
3. restore provider/runtime deletions and relocalization
4. restore admin API provider filtering and downstream cleanup migrations
5. restore web/mobile surface cleanup
6. restore docs/branding cleanup
7. rebuild generator from source if needed
8. run `./scripts/westernization_rebase_check.sh` (audit + web gates)
9. run subsystem validation (mvn, pytest)
10. only then promote the integration branch
## Final Reminder