Skip to content

Commit beef898

Browse files
committed
Synchronize English and Chinese RFC views through Zcode GLM
1 parent bd73272 commit beef898

13 files changed

Lines changed: 638 additions & 18 deletions

File tree

‎.github/workflows/rfc-portability.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,4 @@ jobs:
2525
with:
2626
node-version: '22'
2727
- run: python -m pip install -e '.[dev]'
28-
- run: python -m pytest test/test_rfc_application.py test/test_rfc_providers.py test/test_rfc_http.py test/test_rfc_integration.py test/test_rfc_security.py test/test_rfc_migration.py test/test_rfc_graph.py test/test_rfc_markdown.py test/test_rfc_components.py
28+
- run: python -m pytest test/test_rfc_application.py test/test_rfc_providers.py test/test_rfc_http.py test/test_rfc_integration.py test/test_rfc_security.py test/test_rfc_migration.py test/test_rfc_graph.py test/test_rfc_markdown.py test/test_rfc_components.py test/test_rfc_translations.py

‎doc/architecture/SPEC/rfc_service.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@
6868
来源性能陈述不得转为已验证事实。长章节按需渲染,正文版本缓存复用内容节点与图表。
6969
原文编辑在有权限的独立弹窗内完成,保留未提交输入并校验保存版本;不新增 API/表结构。
7070

71+
- **双语同步。** `language=en/zh` 为详情、列表、分页和更新结果增加受权限过滤的
72+
`translations` 展示映射;原始字段不变。`?lang=en/zh` 选择页面语言,浏览器仅持久化
73+
公开语言偏好,不保存 RFC 译文。新增 SQLite `translations` 表按 RFC/文本摘要/目标语言
74+
隔离队列、缓存和租约。后台通过已登录的 Zcode 调用 GLM,模型 I/O 不持有 DB 事务,
75+
不阻塞跟踪队列;执行前和返回后校验有效身份、来源访问和当前文本,陈旧结果丢弃。
76+
代码/标识/链接/数值保留,译文不得修改验收事实;失效响应退避重试并展示原文。
77+
公开 `/roadmap-languages.json` 只返回随包 UI 字面量,私有 RFC 译文不能进入公开目录。
78+
7179
- **正文渲染。** 内容组件、草稿与导入预览使用随包交付的 markdown-it 15.0.2 渲染
7280
Markdown;禁用源 HTML 与图片加载,链接只允许 HTTP(S) 或当前文档锚点。
7381
原文保留用于编辑、发布和导出。

‎doc/features/rfc-service.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,28 @@ users edit the complete source in a separate dialog, with revision conflict chec
6262
and unsaved input preserved across close/reopen and work updates. API and storage
6363
formats are unchanged.
6464

65+
The language switch provides English and Simplified Chinese views (`?lang=en`
66+
or `?lang=zh`), remembering only the public locale preference. Interface and RFC
67+
display strings are synchronized by GLM through the existing Zcode tool-less
68+
adapter; source Markdown, identifiers, code, links, numbers, owners and acceptance
69+
facts remain authoritative. Translated text stays in the service SQLite cache and
70+
browser session memory. Queue execution and cache reads recheck current RFC/source
71+
access; failed or stale translations never overwrite the source. Pending text
72+
remains readable in its source language with a synchronization indicator.
73+
74+
Enable on an execution host with a logged-in Zcode CLI using provider config:
75+
76+
```json
77+
{"translations":{"enabled":true,"backend":"zcode","model":"GLM-5.3-Flash","reasoning":"low","cli":"/path/to/zcode","timeout_seconds":180}}
78+
```
79+
80+
The standalone worker translates changed text in batches, outside database
81+
transactions and independently of tracking operations. It resumes expired leases
82+
after restart and retries invalid/failed responses with backoff. The public UI
83+
catalog contains only shipped interface literals; RFC translation maps require
84+
the same authorization as the RFC and are filtered to currently visible strings.
85+
The language parameter is additive; API responses retain original canonical text.
86+
6587
Draft previews, import previews, and individual content components display rendered
6688
Markdown, including headings, lists, tables, links, and code blocks. The browser uses the
6789
bundled markdown-it 15.0.2 parser (MIT, shipped with its license), with raw HTML

‎src/infermatrix_copilot/rfc_service/application.py‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def content_digest(title, body):
3535

3636

3737
class RFCService:
38-
def __init__(self, state_dir, providers=None, roots=None, clock=time.time):
38+
def __init__(self, state_dir, providers=None, roots=None, clock=time.time, translator=None):
3939
self.store = Store(state_dir)
4040
self.providers = dict(providers or {})
4141
self.roots = [Path(p).expanduser().resolve() for p in (roots or [])]
@@ -46,6 +46,8 @@ def __init__(self, state_dir, providers=None, roots=None, clock=time.time):
4646
with self.store.transaction() as con:
4747
con.execute("INSERT OR IGNORE INTO metadata VALUES ('writer_id',?)", (identifier("workspace"),))
4848
self.writer_id = self.store.one("SELECT value FROM metadata WHERE key='writer_id'")["value"]
49+
from .translations import Translations
50+
self.translations = Translations(self, translator)
4951

5052
def capabilities(self):
5153
settings = self.settings()
@@ -208,7 +210,7 @@ def _compact_view(view, mode):
208210
fields = {"id", "repo_id", "title", "revision", "content_digest", "source", "state",
209211
"enrolled", "restricted", "updated", "role", "can_write", "can_publish",
210212
"implementation", "acceptance", "complete", "sync_status", "freshness",
211-
"next_actions", "last_discovery", "legacy_namespace", "namespace"}
213+
"next_actions", "last_discovery", "legacy_namespace", "namespace", "translations"}
212214
if mode == "detail":
213215
fields |= {"body", "features", "criteria", "scope", "auto_add", "max_auto_additions",
214216
"grants", "historical_claims", "historical_priorities", "ambiguities"}
@@ -250,6 +252,8 @@ def dispatch(self, principal, action, payload=None):
250252
principal = self._current(con, principal)
251253
result = self._dispatch(con, principal, action, payload)
252254
if isinstance(result, dict) and "repo_id" in result and "features" in result:
255+
if payload.get("language"):
256+
result["translations"] = self.translations.snapshot(con, principal, result, payload["language"])
253257
result = self._compact_view(result, payload.get("view"))
254258
return result
255259

@@ -386,6 +390,8 @@ def _dispatch(self, con, p, action, data):
386390
view = self._view(con, p, dict(row))
387391
if data.get("query") and data["query"].casefold() not in (view["title"] + view["body"]).casefold():
388392
continue
393+
if data.get("language"):
394+
view["translations"] = self.translations.snapshot(con, p, {"id": view["id"], "title": view["title"]}, data["language"])
389395
result.append(self._compact_view(view, data.get("view")))
390396
return {"rfcs": result}
391397
if action == "rfcs.draft":
@@ -435,8 +441,11 @@ def _dispatch(self, con, p, action, data):
435441
if data.get("query"):
436442
query = str(data["query"]).casefold()
437443
items = [item for item in items if query in encode(item).casefold()]
438-
return {"rfc_id": row["id"], "offset": offset, "limit": limit,
439-
"total": len(items), "suggestions": items[offset:offset + limit]}
444+
result = {"rfc_id": row["id"], "offset": offset, "limit": limit,
445+
"total": len(items), "suggestions": items[offset:offset + limit]}
446+
if data.get("language"):
447+
result["translations"] = self.translations.snapshot(con, p, {"id": row["id"], "suggestions": result["suggestions"]}, data["language"])
448+
return result
440449
if action == "rfcs.export":
441450
return {"rfc_id": row["id"], "markdown": row["body"], "content": row["body"], "tracking": view}
442451
return view
@@ -1099,4 +1108,10 @@ def build_service(state_dir, config_path=None):
10991108
if opts.get("api_url"):
11001109
kwargs["api_url"] = opts["api_url"]
11011110
providers[name] = cls(**kwargs)
1102-
return RFCService(state_dir, providers=providers, roots=roots)
1111+
translation_config = config.get("translations", {})
1112+
translator = None
1113+
if translation_config.get("enabled"):
1114+
from .translations import ZcodeTranslator
1115+
if translation_config.get("backend", "zcode") != "zcode": raise ValueError("RFC translations require the configured Zcode backend")
1116+
translator = ZcodeTranslator(translation_config)
1117+
return RFCService(state_dir, providers=providers, roots=roots, translator=translator)

‎src/infermatrix_copilot/rfc_service/cli.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,22 @@ def worker():
137137
print("RFC reconciliation failed; inspect the operation and audit history", file=sys.stderr)
138138
stop.wait(args.interval)
139139
thread = None
140+
translation_thread = None
140141
if not args.no_worker:
141142
thread = threading.Thread(target=worker, daemon=True)
142143
thread.start()
144+
if service.translations.enabled:
145+
def translate_worker():
146+
while not stop.is_set():
147+
try:
148+
service.translations.reconcile()
149+
result = service.translations.process()
150+
except Exception:
151+
result = {"processed": 0}
152+
print("RFC translation unavailable; source views remain accessible", file=sys.stderr)
153+
stop.wait(1 if result["processed"] else 5)
154+
translation_thread = threading.Thread(target=translate_worker, daemon=True)
155+
translation_thread.start()
143156
print(f"RFC service: {server.public_url}", flush=True)
144157
try:
145158
server.serve_forever()
@@ -148,6 +161,8 @@ def worker():
148161
server.server_close()
149162
if thread:
150163
thread.join(timeout=2)
164+
if translation_thread:
165+
translation_thread.join(timeout=2)
151166
return 0
152167
client = RFCClient(state_dir=state, service_url=service_url,
153168
token=os.environ.get(args.token_env, ""), config_path=args.config)

‎src/infermatrix_copilot/rfc_service/http.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"/roadmap-graph.mjs": ("roadmap-graph.mjs", "text/javascript; charset=utf-8"),
3232
"/roadmap-markdown-display.mjs": ("roadmap-markdown-display.mjs", "text/javascript; charset=utf-8"),
3333
"/roadmap-components.mjs": ("roadmap-components.mjs", "text/javascript; charset=utf-8"),
34+
"/roadmap-locale.mjs": ("roadmap-locale.mjs", "text/javascript; charset=utf-8"),
3435
"/roadmap-mermaid.js": ("roadmap-mermaid.js", "text/javascript; charset=utf-8"),
3536
"/style.css": ("style.css", "text/css; charset=utf-8"),
3637
}
@@ -227,6 +228,9 @@ def _session_cookie(self, secret: str, *, revoke: bool = False) -> str:
227228

228229
def _get(self) -> None:
229230
path, query = self._path()
231+
if path == "/roadmap-languages.json":
232+
self._json(self.server.service.translations.public_ui(query.get("language", "en")))
233+
return
230234
if path in _STATIC:
231235
name, mime = _STATIC[path]
232236
body, compressed, etag = _asset(name)

‎src/infermatrix_copilot/rfc_service/store.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY, actor TEXT NOT NULL REFERENCES users(id), credential_id TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL, repo_id TEXT NOT NULL, rfc_id TEXT NOT NULL DEFAULT '', payload TEXT NOT NULL, idempotency_key TEXT NOT NULL, request_digest TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', result TEXT NOT NULL DEFAULT '{}', error TEXT NOT NULL DEFAULT '', created REAL NOT NULL, updated REAL NOT NULL, worker TEXT NOT NULL DEFAULT '', lease_until REAL NOT NULL DEFAULT 0, UNIQUE(actor,idempotency_key));
2121
CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY, actor TEXT NOT NULL, action TEXT NOT NULL, repo_id TEXT NOT NULL DEFAULT '', rfc_id TEXT NOT NULL DEFAULT '', detail TEXT NOT NULL DEFAULT '{}', created REAL NOT NULL);
2222
CREATE INDEX IF NOT EXISTS operations_pending ON operations(status,lease_until,created);
23+
CREATE TABLE IF NOT EXISTS translations(scope TEXT NOT NULL, segment TEXT NOT NULL, language TEXT NOT NULL, source TEXT NOT NULL, translated TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'pending', credential_id TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', attempts INTEGER NOT NULL DEFAULT 0, retry_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0, worker TEXT NOT NULL DEFAULT '', updated REAL NOT NULL, PRIMARY KEY(scope,segment,language));
24+
CREATE INDEX IF NOT EXISTS translations_pending ON translations(status,retry_at,lease_until,updated);
2325
"""
2426

2527

0 commit comments

Comments
 (0)