Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
agents: upgrade resx-translation skill
fatDuckf2f09368526a
diff --git a/.agents/skills/resx-translation/SKILL.md b/.agents/skills/resx-translation/SKILL.mdindex 3c34848..31a7c80 100644--- a/.agents/skills/resx-translation/SKILL.md+++ b/.agents/skills/resx-translation/SKILL.md@@ -3,20 +3,19 @@ name: resx-translationdescription: Translate, extend, and create `.resx` localization files for .NET apps with project-aware wording and minimal file churn. Use this skill whenever the user wants to localize or update `Translations.resx`, `*.resx`, WPF/WinForms/.NET resource files, add a new language like `vi`, `ja`, or `fr-FR`, fill missing translations, or improve an existing locale while preserving XML structure, placeholders, naming conventions, and current formatting. Trigger even when the user does not mention `.resx` explicitly but is clearly asking to localize app text, UI labels, menus, dialogs, settings, validation messages, or existing app translations. Also trigger for requests like "translate this resx", "add a new language", "fill missing strings", "localize my app", "translate resource files", or "complete the existing locale".----# Resx Translation+# Resx Translation Skill## Golden Rule: Use helpers, NEVER `read` the full file-**Do NOT use `read`/`glob`/`grep`** to discover files, check encoding, or audit translations.+**Do NOT use `read`/`glob`/`grep`** to discover files, check encoding, or audit translations.Use the helper scripts — they return structured data in <10 lines, saving hundreds of tokens.-**Never `read` an entire `.resx` file.** Files can exceed 100k tokens.-Use `(filename:line)` annotations from `audit_translations.py` to `read` only the relevant lines:+**Never `read` an entire `.resx` file.** Files can exceed 100k tokens.+Use `(filename:line)` annotations from helpers to `read` only the relevant lines:```-# audit shows: - AppTitle = 'OptimizerDuck' (Translations.resx:42)-read Translations.vi.resx offset=42 limit=5-read Translations.resx offset=42 limit=5+# resx_audit shows: [-] AppTitle (default:L42 #3) = 'OptimizerDuck'+read Translations.vi-VN.resx offset=42 limit=5```Only `read` 1-5 lines around each flagged key — never the whole file.@@ -25,197 +24,235 @@ Only `read` 1-5 lines around each flagged key — never the whole file.## Helper Scripts Reference-All scripts are in `<skill>\helpers\`. Replace `<skill>` with the skill base path (run `codegraph_node resx-translation` or check `.agents/skills/resx-translation`).+All scripts are in `<skill>\helpers\`. Replace `<skill>` with the skill base path.----### `find_resx.py` — Discover `.resx` files, encoding, Designer.cs status+### `resx_core.py` — Core library (do not run directly)-**What it does**: Lists all `.resx` files in a directory — key count, encoding (UTF-8 with/without BOM), file size, and whether `.Designer.cs` is in sync. Use this **instead of** `glob` + `read`.--**Usage**:-```powershell-python <skill>\helpers\find_resx.py Resources\Languages-```--**Flags**:-| Flag | Description |-|------|-------------|-| `--json` | Output as JSON for programmatic use |-| (none) | Human-readable table |--**Output**:-```-════════════════════════-resx discovery-════════════════════════- directory: Resources\Languages- default : Translations.resx- pattern : Translations.*.resx- files : 3-- Translations.resx- keys : 45- size : 3200 bytes- encoding: UTF-8 with BOM- designer: Translations.Designer.cs (synced)-- Translations.vi.resx- keys : 30- size : 2400 bytes- encoding: UTF-8 with BOM- designer: (none)-```--**Next step**:-- If adding a new locale → `create_locale.py`.-- If auditing/translating → `audit_translations.py`.+Shared data structures and operations used by all other scripts:+- `ResxEntry` / `ResxFile` — parsed .resx with index, line numbers, encoding+- `parse_resx(path)` — parse a .resx file+- `auto_detect(directory)` — detect base file and locale pattern+- `diff_files(default, locale)` — compare two files, returns `KeyDiff` list+- `write_translations(path, dict, mode)` — batch add/update keys+- `add_keys(path, dict)` — add new keys before `</root>`+- `update_values(path, dict)` — update existing key values+- `parse_batch_input(raw)` — parse KEY=VALUE pairs from text+- `format_entries_table(entries)` — compact aligned table output+- `format_diffs_compact(diffs)` — compact diff output with status markers----### `audit_translations.py` — Find missing / empty / untranslated keys+### `resx_audit.py` — Audit translations (missing, empty, untranslated, warnings)-**What it does**: Compares all locale files against the union of all keys. Reports keys that are **missing** (absent from a locale), **empty** (present but blank), or **untranslated** (identical to the default file). Use this **instead of** manually diffing files.+**What it does**: Compares all locale files against the default. Reports issues with line numbers, indices, and warnings (mixed encodings, key count mismatch, duplicate keys, Designer.cs sync).**Usage**:```powershell-python <skill>\helpers\audit_translations.py Resources\Languages --auto-detect --show-missing --show-untranslated+python <skill>\helpers\resx_audit.py Resources\Languages+python <skill>\helpers\resx_audit.py Resources\Languages --lang vi-VN+python <skill>\helpers\resx_audit.py Resources\Languages --json```**Flags**:| Flag | Description ||------|-------------|-| `--show-missing` | Keys absent from a locale that exist in others |-| `--show-empty` | Keys with empty values |-| `--show-untranslated` | Keys whose value matches the default file |-| `--by-key` | Group results by key name instead of by locale |-| `--fail-on-any` | Exit code 1 if any issues found (CI gate) |-| `--auto-detect` | Auto-detect file pattern from directory |-| `--check-designer` | Also audit `.Designer.cs` for missing/stale properties |-| `--default-file` | Custom base filename (e.g. `Strings.resx`) |-| `--pattern` | Custom locale glob (e.g. `Strings.*.resx`) |--**Output** (with `--show-missing --show-untranslated`):+| `--lang CODE` | Filter by locale (e.g. `vi`, `ja-JP`) |+| `--no-missing` | Hide missing keys |+| `--no-empty` | Hide empty values |+| `--no-untranslated` | Hide untranslated |+| `--no-warnings` | Hide warnings |+| `--check-designer` | Audit `.Designer.cs` sync |+| `--by-key` | Group by key name |+| `--json` | JSON output (full metadata per issue) |+| `--fail-on-any` | Exit code 1 if any issues (CI gate) |++**Output**:```-════════════════════════-translation audit-════════════════════════+============================================================+resx manager — audit+============================================================+ default : Translations.resx (45 keys)+ locales : 13- [vi]+ [vi-VN] — Translations.vi-VN.resxmissing=15 | untranslated=5- missing keys (15):- - AppTitle = 'OptimizerDuck' (Translations.resx:42)- - ButtonCancel = 'Cancel' (Translations.resx:55)- ...+ missing (15):+ [-] AppTitle (default:L42 #3) = 'OptimizerDuck'+ [-] ButtonCancel (default:L55 #12) = 'Cancel'- untranslated values (5):- - LabelStatus (Translations.vi.resx:120)- - TextWelcome (Translations.vi.resx:135)- ...+ untranslated (5):+ [U] LabelStatus (Translations.vi-VN.resx:L120 #45)- [ja]- ok+ warnings (1):+ ! mixed encodings: UTF-8 with BOM, UTF-8 (no BOM)-════════════════════════+============================================================summary-════════════════════════- locales: 3- keys : 45- pattern: Translations.*.resx- missing: 15+============================================================+ keys : 45+ locales : 13+ missing : 15untranslated: 5+ warnings : 1```-**Clean output** (no issues):-```- all translations look good across all locales-```--**Next step**:-- Issues found → use `question` tool to ask user which locale → `read` that file + source → translate only flagged keys.-- Clean → nothing to do.-----### `create_locale.py` — Add a new language file+### `resx_list.py` — List all translations with index and line numbers-**What it does**: Duplicates the source `.resx` into a new locale file (e.g. `Translations.vi.resx`). Uses `shutil.copy2` to preserve exact encoding, BOM, metadata. **30x faster** than reading + rewriting XML.+**What it does**: Lists every translation entry with index, key, line number, and value. Supports locale filtering and key search.**Usage**:```powershell-python <skill>\helpers\create_locale.py Resources\Languages --locale vi+# List all files and entries+python <skill>\helpers\resx_list.py Resources\Languages++# Filter by locale+python <skill>\helpers\resx_list.py Resources\Languages --lang vi-VN++# Search keys+python <skill>\helpers\resx_list.py Resources\Languages --key Dashboard++# Keys only (no values)+python <skill>\helpers\resx_list.py Resources\Languages --keys-only++# JSON output+python <skill>\helpers\resx_list.py Resources\Languages --json```**Flags**:| Flag | Description ||------|-------------|-| `--locale` | **(Required)** Language code: `vi`, `ja`, `fr-FR`, `de`, etc. |-| `--source` | Source filename (default: auto-detected base `.resx`) |-| `--dry-run` | Preview without creating |+| `--lang CODE` | Filter by locale |+| `--key TEXT` | Filter keys by substring |+| `--keys-only` | Show only keys, no values |+| `--no-values` | Hide values entirely |+| `--json` | JSON output |**Output**:```-Created: Translations.vi.resx (45 keys copied from Translations.resx)+============================================================+resx manager — file listing+============================================================+ directory : Resources\Languages+ default : Translations.resx (45 keys, UTF-8 with BOM)+ locales : 13++--- Translations.resx (default) ---+ [#0 ] Sidebar.Dashboard = 'Dashboard' (Translations.resx:L125)+ [#1 ] Sidebar.Settings = 'Settings' (Translations.resx:L127)+ [#2 ] Button.Close = 'Close' (Translations.resx:L133)+ [#3 ] Dashboard.SystemInfo.Cpu.Cores = '{0} Cores' (Translations.resx:L136)```-If the file already exists:-```-already exists: Translations.vi.resx+---++### `resx_create.py` — Create a new locale file++**What it does**: Copies the source `.resx` to create a new locale file. Preserves encoding, BOM, XML structure.++**Usage**:+```powershell+python <skill>\helpers\resx_create.py Resources\Languages --locale vi-VN+python <skill>\helpers\resx_create.py Resources\Languages --locale ja-JP --dry-run```-**Next step**: Translate ALL values in the new file → run `sync_resx.py --fill-source` to catch any keys added to source after creation.+**Flags**:+| Flag | Description |+|------|-------------|+| `--locale` | **(Required)** Language code |+| `--source` | Source filename (default: auto-detected) |+| `--dry-run` | Preview without creating |+| `--json` | JSON output |----### `sync_resx.py` — Propagate new keys from source to locales+### `resx_sync.py` — Sync missing keys from source to locales-**What it does**: Copies newly added keys from the source `.resx` into all (or a specific) locale files. New `<data>` elements are inserted before `</root>`, preserving XML structure and indentation.+**What it does**: Copies keys that exist in source but are missing from locale files.**Usage**:```powershell-python <skill>\helpers\sync_resx.py Resources\Languages --fill-source+# Sync with English fallback values+python <skill>\helpers\resx_sync.py Resources\Languages --fill-source++# Sync with TODO markers+python <skill>\helpers\resx_sync.py Resources\Languages --fill-marker "TODO"++# Sync specific locale only+python <skill>\helpers\resx_sync.py Resources\Languages --locale vi-VN --fill-source```**Flags**:| Flag | Description ||------|-------------|-| `--fill-source` | Copy source value as-is (English fallback) |-| `--fill-marker "TODO"` | Fill with a marker string instead |-| (no fill flags) | Fill with empty string |-| `--locale vi-VN` | Target a specific locale only |+| `--fill-source` | Copy source value as-is |+| `--fill-marker "TEXT"` | Fill with marker string |+| `--locale CODE` | Target specific locale || `--dry-run` | Preview without writing |-| `--source` | Custom source filename |-| `--target` | Custom locale glob pattern |+| `--json` | JSON output |-**Output**:+---++### `resx_write.py` — Batch write translations to multiple locales++**What it does**: Write/update translation keys across multiple locale files. Supports `--key`/`--value`, `--file`, or `--stdin` input. Modes: `auto` (add+update), `update` (existing only), `add` (new only).++**Usage**:+```powershell+# Single key to all locales+python <skill>\helpers\resx_write.py Resources\Languages --key AppTitle --value "OptimizerDuck" --locale all++# Single key to specific locale+python <skill>\helpers\resx_write.py Resources\Languages --key Button.Close --value "Đóng" --locale vi-VN++# Write from file (KEY=VALUE or JSON)+python <skill>\helpers\resx_write.py Resources\Languages --file translations.txt --locale vi-VN++# Write from stdin+echo "Button.Close=Đóng" | python <skill>\helpers\resx_write.py Resources\Languages --stdin --locale vi-VN++# Dry run+python <skill>\helpers\resx_write.py Resources\Languages --key Button.Close --value "Đóng" --locale vi-VN --dry-run+```++**KEY=VALUE file format**:```-════════════════════════-resx sync-════════════════════════- Translations.vi.resx: added 3 key(s) (vi)- Translations.ja.resx: ok (already up to date)--════════════════════════-result-════════════════════════- total keys added: 3+# Comments and blank lines are ignored+Button.Close=Đóng+Button.Save=Lưu+Sidebar.Dashboard=Bảng điều khiển```-**Next step**:-- `--fill-source` → those keys have English text and need translation → run `audit_translations.py --show-untranslated` to find them.-- `--fill-marker "TODO"` → search for and translate markers.+**Flags**:+| Flag | Description |+|------|-------------|+| `--key TEXT` | Single key to write |+| `--value TEXT` | Value for `--key` |+| `--file PATH` | File with KEY=VALUE or JSON |+| `--stdin` | Read from stdin |+| `--locale CODE` | Target locale (`vi`, `ja`, `all`) |+| `--mode` | `auto` / `update` / `add` / `upsert` |+| `--dry-run` | Preview without writing |+| `--json` | JSON output |+| `--source` | Source .resx to create locale from if missing |----## Task Dispatch: Determine what the user needs+## Task Dispatch-| User says (Vietnamese) | Meaning | Action |-|---|---|---|-| *"dịch các translation còn thiếu"* / *"translate missing translations"* | Fill only missing/untranslated keys | Run `audit` → ask → translate **only flagged keys** |-| *"dịch ngôn ngữ mới"* / *"add new language"* | Brand new locale | `create_locale.py` → translate **all keys** |-| *"dịch các translation"* / *"translate translations"* | General translate request | Run `audit` → find untranslated → ask → translate |-| *"cập nhật translations"* / *"update translations"* | Sync + translate new keys | `sync_resx.py` → `audit` → translate untranslated |+| User says | Action |+|---|---|+| *"dịch các translation còn thiếu"* | `resx_audit` → ask → `resx_write` for flagged keys |+| *"dịch ngôn ngữ mới"* | `resx_create` → `resx_sync --fill-source` → `resx_write` |+| *"dịch các translation"* | `resx_audit --no-missing` → `resx_write` for untranslated |+| *"cập nhật translations"* | `resx_sync --fill-source` → `resx_audit` → `resx_write` |+| *"liệt kê translations"* | `resx_list` |+| *"tìm key X"* | `resx_list --key X` |+| *"kiểm tra Designer.cs"* | `resx_audit --check-designer` |---@@ -226,71 +263,77 @@ result**Before any translation work**, use the `question` tool to:1. **If multiple locales have issues**: Ask which locale(s) to work on-2. **Confirm the approach**: Describe what `audit` found and what you plan to do (how many keys, which file)+2. **Confirm the approach**: Describe what `resx_audit` found and what you plan to do3. **Domain context**: If the app has specialized terminology, ask about preferred translations-This prevents wasted work. Example:--> `audit` shows `vi` has 15 missing and 5 untranslated keys out of 45 total.-> `ja` is fully translated.-> Should I proceed with translating `vi` only?-----### A. "Dịch các translation còn thiếu" — Fill Missing Translations+### A. Fill Missing Translations-1. **Run `audit_translations.py --show-missing --show-untranslated`** to find issues-2. **Ask user** (via `question`): which locale, confirm scope-3. **`read` only specific lines** in the locale file + source file using line numbers from the audit output (e.g., `read Translations.vi.resx offset=42 limit=5`)-4. **Translate only flagged keys** — skip everything else-5. Report: which file, language, how many keys translated+1. **Run `resx_audit.py`** to find issues+2. **Ask user**: which locale, confirm scope+3. **Use `resx_write.py`** to write translations:+ ```powershell+ python <skill>\helpers\resx_write.py Resources\Languages --key Button.Close --value "Đóng" --locale vi-VN+ ```+ Or batch from file:+ ```powershell+ python <skill>\helpers\resx_write.py Resources\Languages --file translations.txt --locale vi-VN+ ```+4. **Verify**: run `resx_audit.py` again----### B. "Dịch ngôn ngữ mới" — Add New Language+### B. Add New Language-1. **Run `find_resx.py`** to see existing files and encoding-2. **Ask user**: confirm language code + any domain-specific preferences-3. **Run `create_locale.py --locale <code>`** to create the file-4. **Translate ALL values** in the new file-5. **Run `sync_resx.py --fill-source`** to catch any keys added after creation-6. Report: file created, language, key count+1. **Run `resx_list.py`** to see existing files+2. **Ask user**: confirm language code+3. **Run `resx_create.py --locale <code>`**+4. **Run `resx_sync.py --fill-source`** to fill with English fallback+5. **Run `resx_audit.py --lang <code>`** to find untranslated+6. **Use `resx_write.py`** to translate all untranslated keys----### C. "Dịch các translation" — Translate Existing Translations+### C. Batch Translate from File-1. **Run `audit_translations.py --show-untranslated`** to find untranslated keys-2. **Ask user** (via `question`): which locale(s), confirm scope-3. **`read` only specific lines** in the locale file + source file using line numbers from the audit output-4. **Translate only untranslated keys**-5. Report: file, language, keys translated+1. Create a KEY=VALUE file:+ ```+ Button.Close=Đóng+ Button.Save=Lưu+ Sidebar.Dashboard=Bảng điều khiển+ ```+2. **Run `resx_write.py --file translations.txt --locale vi-VN`**+3. **Verify**: `resx_audit.py --lang vi-VN`---## Translation Rules- Translate **only user-facing text**. Never change keys, node names, attributes, or XML structure.-- Preserve exactly: `{0}`, `{1}`, `%s` placeholders; HTML/XAML fragments; product names; error codes; escaped characters.-- Short strings (`Open`, `Save`, `Apply`, `Reset`, etc.) depend on screen context — inspect nearby code if unsure.-- Keep English terms when they function as product language (`Playlist`, `Profile`, `Driver`, `Theme`, `Preset`) unless the app consistently localizes them.+- Preserve exactly: `{0}`, `{1}`, `%s` placeholders; HTML/XAML fragments; product names; error codes.+- Short strings (`Open`, `Save`, `Apply`, `Reset`) depend on context — inspect nearby code if unsure.+- Keep English terms that function as product language (`Playlist`, `Profile`, `Driver`, `Theme`, `Preset`).- Preserve original encoding (UTF-8 with/without BOM).## Editing Behavior-- Edit the target file directly using `edit` tool.-- No explanations, comments, translation tables, or layout changes added to the file.-- Preserve ordering, indentation, XML declaration, surrounding nodes.-- Report back briefly: which file was updated/created, language, key count.+- Use `resx_write.py` for all writes — never manually edit `.resx` files.+- The script preserves XML structure, encoding, and indentation.+- Report back briefly: which file was updated, language, key count.## Quick Reference| Need | Command ||---|---|-| See all `.resx` files, encoding, Designer.cs | `find_resx.py <dir>` |-| Find missing / untranslated keys | `audit_translations.py <dir> --show-missing --show-untranslated` |-| Find empty values | `audit_translations.py <dir> --show-empty` |-| Create new locale | `create_locale.py <dir> --locale <code>` |-| Sync new keys to locales | `sync_resx.py <dir> --fill-source` |-| Preview sync | `sync_resx.py <dir> --fill-marker "TODO" --dry-run` |-| CI check | `audit_translations.py <dir> --fail-on-any` |+| Audit all locales | `resx_audit.py <dir>` |+| Audit specific locale | `resx_audit.py <dir> --lang vi-VN` |+| List all translations | `resx_list.py <dir>` |+| Search keys | `resx_list.py <dir> --key Dashboard` |+| Create new locale | `resx_create.py <dir> --locale vi-VN` |+| Sync missing keys | `resx_sync.py <dir> --fill-source` |+| Write single key | `resx_write.py <dir> --key K --value V --locale vi-VN` |+| Write from file | `resx_write.py <dir> --file tr.txt --locale vi-VN` |+| Write to all locales | `resx_write.py <dir> --key K --value V --locale all` |+| CI check | `resx_audit.py <dir> --fail-on-any` |+| Designer.cs check | `resx_audit.py <dir> --check-designer` |diff --git a/.agents/skills/resx-translation/helpers/audit_translations.py b/.agents/skills/resx-translation/helpers/audit_translations.pydeleted file mode 100644index 4be0ad8..0000000--- a/.agents/skills/resx-translation/helpers/audit_translations.py+++ /dev/null@@ -1,263 +0,0 @@-# audit_translations.py — Audit .resx locale files for missing, empty, or untranslated keys--from __future__ import annotations--try:- import argparse- import sys- from pathlib import Path-except ImportError as ex:- print(f"failed to import required module: {ex}")- raise SystemExit(1)--sys.path.insert(0, str(Path(__file__).resolve().parent))-from resx_helpers import (- auto_detect_pattern,- compute_issues,- ensure_utf8,- find_designer,- get_union_keys,- load_designer_keys,- load_resx,- load_resx_with_lines,- print_header,- resx_key_to_property,-)---def parse_args() -> argparse.Namespace:- p = argparse.ArgumentParser(description="Audit .resx translation files across all locales.")-- p.add_argument("path", type=Path, help="Path to the translations directory")-- p.add_argument("--default-file", default=None, help="Base .resx filename (default: auto-detected)")- p.add_argument("--pattern", default=None, help="Glob pattern for locale files (default: auto-detected)")- p.add_argument("--auto-detect", action="store_true", help="Auto-detect file pattern from directory")-- p.add_argument("--show-missing", action="store_true", help="Show keys present in other locales but missing")- p.add_argument("--show-empty", action="store_true", help="Show keys with empty values")- p.add_argument("--show-untranslated", action="store_true", help="Show keys matching the default file value")-- p.add_argument("--by-key", action="store_true", help="Group results by key name")- p.add_argument("--fail-on-any", action="store_true", help="Exit code 1 if any issues found")- p.add_argument("--check-designer", action="store_true", help="Check .Designer.cs for missing properties")-- return p.parse_args()---def designer_check(base: Path, default_name: str, all_keys: set[str]) -> None:- designer = find_designer(base, default_name)- if not designer:- print("\n [designer] no .Designer.cs found")- return-- props = load_designer_keys(designer)- resx_props = {resx_key_to_property(k) for k in all_keys}- missing = sorted(resx_props - props)- stale = sorted(props - resx_props)-- if not missing and not stale:- print(f"\n [designer] {designer.name}: ok ({len(props)} properties)")- return-- if stale:- print(f"\n [designer] {designer.name}: {len(stale)} stale propert(y/ies) (in .Designer.cs but not in .resx):")- for s in stale:- print(f" - {s}")-- if missing:- print(f"\n [designer] {designer.name}: {len(missing)} missing propert(y/ies) (in .resx but not in .Designer.cs):")- for m in missing:- print(f" - {m}")-- print(" (regenerate by rebuilding the project or running ResGen)")---def main():- try:- args = parse_args()- ensure_utf8()- base = args.path.resolve()-- if not base.exists() or not base.is_dir():- print(f"directory not found:\n{base}")- sys.exit(1)-- if args.auto_detect or not args.default_file:- default_name, pattern, detected = auto_detect_pattern(base)- default_name = args.default_file or default_name- pattern = args.pattern or pattern- else:- default_name = args.default_file- pattern = args.pattern or default_name.replace(".resx", ".*.resx")-- if not pattern:- print("no locale pattern could be determined")- sys.exit(1)-- default_path = base / default_name- default_data = load_resx(default_path) if default_path.exists() else {}- default_lang = None-- locale_data: dict[str, dict[str, str]] = {}- locale_line_data: dict[str, dict[str, int]] = {}- locale_filenames: dict[str, str] = {}- for fp in sorted(base.glob(pattern)):- lang = fp.stem.split(".", 1)[1] if "." in fp.stem else fp.stem- result = load_resx_with_lines(fp)- if result is not None:- values = {}- lines_map = {}- for k, (v, ln) in result.items():- values[k] = v- lines_map[k] = ln- locale_data[lang] = values- locale_line_data[lang] = lines_map- locale_filenames[lang] = fp.name- if fp.name == default_name:- default_lang = lang-- if default_data and default_lang is None:- default_lang = Path(default_name).stem- locale_data[default_lang] = default_data- locale_filenames[default_lang] = default_name- default_with_lines = load_resx_with_lines(default_path)- if default_with_lines is not None:- locale_line_data[default_lang] = {k: ln for k, (_, ln) in default_with_lines.items()}-- if not locale_data:- print(f"no files matching '{pattern}' in {base}")- sys.exit(1)-- all_keys = get_union_keys(locale_data)- if not all_keys:- print("all loaded files are empty")- sys.exit(1)-- issues = compute_issues(locale_data, default_data, default_lang)-- totals = {- kind: sum(len(issues[l][kind]) for l in locale_data)- for kind in ("missing", "empty", "untranslated")- }- any_issues = any(issues[l][k] for l in locale_data for k in ("missing", "empty", "untranslated"))- show_flags = args.show_missing or args.show_empty or args.show_untranslated- names = sorted(locale_data)-- print_header("translation audit")-- if not any_issues:- print("\n all translations look good across all locales")- print_header("summary")- print(f" locales: {len(names)}")- print(f" keys : {len(all_keys)}")- print(f" pattern: {pattern}")- if args.check_designer:- designer_check(base, default_name, all_keys)- return-- if args.by_key:- key_map: dict[str, list[str]] = {}- for lang in names:- iss = issues[lang]- if args.show_missing:- for k in iss["missing"]:- key_map.setdefault(k, []).append(f"{lang}:missing")- if args.show_empty:- for k in iss["empty"]:- key_map.setdefault(k, []).append(f"{lang}:empty")- if args.show_untranslated:- for k in iss["untranslated"]:- key_map.setdefault(k, []).append(f"{lang}:untranslated")-- if not show_flags:- for lang in names:- for kind in ("missing", "empty", "untranslated"):- for k in issues[lang][kind]:- key_map.setdefault(k, []).append(f"{lang}:{kind}")-- print(f"\n {len(key_map)} key(s) with issues across {len(names)} locale(s)")- for key in sorted(key_map):- default_file = locale_filenames.get(default_lang, default_name) if default_lang else default_name- line_num = locale_line_data.get(default_lang, {}).get(key, 0)- line_str = f" ({default_file}:{line_num})" if line_num else ""- print(f"\n {key}{line_str}")- for entry in sorted(key_map[key]):- print(f" - {entry}")- else:- for lang in names:- iss = issues[lang]- missing = iss["missing"]- empty = iss["empty"]- untranslated = iss["untranslated"]-- print(f"\n [{lang}]")- if not missing and not empty and not untranslated:- print(" ok")- continue-- parts = []- if missing:- parts.append(f"missing={len(missing)}")- if empty:- parts.append(f"empty={len(empty)}")- if untranslated:- parts.append(f"untranslated={len(untranslated)}")- print(" " + " | ".join(parts))-- if args.show_missing and missing:- print(f"\n missing keys ({len(missing)}):")- for key in missing:- sample = None- for olang in names:- if olang != lang and key in locale_data[olang]:- sample = locale_data[olang][key]- break- default_file = locale_filenames.get(default_lang, default_name) if default_lang else default_name- line_num = locale_line_data.get(default_lang, {}).get(key, 0)- line_str = f" ({default_file}:{line_num})" if line_num else ""- if sample is not None:- print(f" - {key} = {sample!r}{line_str}")- else:- print(f" - {key}{line_str}")-- if args.show_empty and empty:- print(f"\n empty values ({len(empty)}):")- for k in empty:- locale_file = locale_filenames.get(lang, f"{lang}.resx")- line_num = locale_line_data.get(lang, {}).get(k, 0)- line_str = f" ({locale_file}:{line_num})" if line_num else ""- print(f" - {k}{line_str}")-- if args.show_untranslated and untranslated:- print(f"\n untranslated values ({len(untranslated)}):")- for k in untranslated:- locale_file = locale_filenames.get(lang, f"{lang}.resx")- line_num = locale_line_data.get(lang, {}).get(k, 0)- line_str = f" ({locale_file}:{line_num})" if line_num else ""- print(f" - {k}{line_str}")-- print_header("summary")- print(f" locales: {len(names)}")- print(f" keys : {len(all_keys)}")- print(f" pattern: {pattern}")- for kind in ("missing", "empty", "untranslated"):- if totals[kind]:- print(f" {kind}: {totals[kind]}")-- if args.check_designer:- designer_check(base, default_name, all_keys)-- if args.fail_on_any and any(totals.values()):- sys.exit(1)-- except KeyboardInterrupt:- print("\ncancelled")- sys.exit(130)- except Exception as ex:- print(f"\nfatal: {ex}")- sys.exit(1)---if __name__ == "__main__":- main()diff --git a/.agents/skills/resx-translation/helpers/create_locale.py b/.agents/skills/resx-translation/helpers/create_locale.pydeleted file mode 100644index 7689756..0000000--- a/.agents/skills/resx-translation/helpers/create_locale.py+++ /dev/null@@ -1,72 +0,0 @@-# create_locale.py — Create a new locale .resx file from the source--from __future__ import annotations--import argparse-import sys-import shutil-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-from resx_helpers import auto_detect_pattern, ensure_utf8, load_resx---def main():- try:- parser = argparse.ArgumentParser(- description="Create a new locale .resx file from the source."- )- parser.add_argument("path", type=Path, help="Translations directory")- parser.add_argument("--locale", required=True,- help="Language code (e.g. vi, ja, fr-FR)")- parser.add_argument("--source", default=None,- help="Source .resx (default: auto-detected base file)")- parser.add_argument("--dry-run", action="store_true",- help="Preview without creating")- args = parser.parse_args()-- ensure_utf8()- base = args.path.resolve()-- if not base.exists() or not base.is_dir():- print(f"directory not found: {base}")- sys.exit(1)-- default_name, _, _ = auto_detect_pattern(base)- source_name = args.source or default_name- source_path = base / source_name-- if not source_path.exists():- print(f"source not found: {source_path}")- sys.exit(1)-- stem = Path(source_name).stem- ext = Path(source_name).suffix- new_name = f"{stem}.{args.locale}{ext}"- new_path = base / new_name-- if new_path.exists():- print(f"already exists: {new_name}")- sys.exit(1)-- source_data = load_resx(source_path)- if source_data is None:- sys.exit(1)-- if args.dry_run:- print(f"[dry-run] would create: {new_name} ({len(source_data)} keys from {source_name})")- return-- shutil.copy2(source_path, new_path)- print(f"Created: {new_name} ({len(source_data)} keys copied from {source_name})")-- except KeyboardInterrupt:- print("\ncancelled")- sys.exit(130)- except Exception as ex:- print(f"\nfatal: {ex}")- sys.exit(1)---if __name__ == "__main__":- main()diff --git a/.agents/skills/resx-translation/helpers/find_resx.py b/.agents/skills/resx-translation/helpers/find_resx.pydeleted file mode 100644index 7c9e168..0000000--- a/.agents/skills/resx-translation/helpers/find_resx.py+++ /dev/null@@ -1,131 +0,0 @@-# find_resx.py — Discover .resx files, naming patterns, and Designer.cs bindings--from __future__ import annotations--try:- import argparse- import json- import sys- from pathlib import Path-except ImportError as ex:- print(f"failed to import required module: {ex}")- raise SystemExit(1)--sys.path.insert(0, str(Path(__file__).resolve().parent))-from resx_helpers import (- auto_detect_pattern,- ensure_utf8,- find_designer,- load_designer_keys,- load_resx,- print_header,- resx_key_to_property,-)---def detect_encoding(path: Path) -> str:- raw = path.read_bytes()- if raw[:3] == b"\xef\xbb\xbf":- return "UTF-8 with BOM"- return "UTF-8 (no BOM)" if raw[:5] == b"<?xml" else "unknown"---def scan(base: Path) -> list[dict]:- if not base.is_dir():- print(f"not a directory: {base}")- sys.exit(1)-- all_resx = sorted(base.glob("*.resx"))- if not all_resx:- return []-- default_name, pattern, _ = auto_detect_pattern(base)-- result = []- for rp in all_resx:- data = load_resx(rp)- if data is None:- continue-- info = {- "file": rp.name,- "size": rp.stat().st_size,- "encoding": detect_encoding(rp),- "keys": len(data),- }-- designer = find_designer(base, rp.name)- if designer:- props = load_designer_keys(designer)- resx_props = {resx_key_to_property(k) for k in data}- info["designer"] = designer.name- info["designer_props"] = len(props)- info["synced"] = props == resx_props- out_of_sync = (resx_props - props) | (props - resx_props)- info["out_of_sync_count"] = len(out_of_sync)-- result.append(info)-- return result---def main():- try:- parser = argparse.ArgumentParser(- description="Discover .resx files, naming patterns, and Designer.cs bindings."- )- parser.add_argument("path", nargs="?", type=Path, default=Path("."),- help="Translations directory (default: current)")- parser.add_argument("--json", action="store_true", help="Output as JSON")- args = parser.parse_args()-- ensure_utf8()- base = args.path.resolve()-- if not base.exists():- print(f"directory not found: {base}")- sys.exit(1)-- default_name, pattern, _ = auto_detect_pattern(base)- files = scan(base)-- if not files:- print(f"no .resx files found in {base}")- sys.exit(0)-- if args.json:- json.dump({"default": default_name, "pattern": pattern, "files": files},- sys.stdout, indent=2)- print()- return-- print_header("resx discovery")- print(f" directory: {base}")- print(f" default : {default_name}")- print(f" pattern : {pattern}")- print(f" files : {len(files)}")-- for info in files:- designer = info.get("designer")- synced = info.get("synced")- if designer:- status = "synced" if synced else f"{info['out_of_sync_count']} out of sync"- else:- status = "no Designer.cs"-- print(f"\n {info['file']}")- print(f" keys : {info['keys']}")- print(f" size : {info['size']} bytes")- print(f" encoding: {info['encoding']}")- print(f" designer: {designer or '(none)'} ({status})")-- except KeyboardInterrupt:- print("\ncancelled")- sys.exit(130)- except Exception as ex:- print(f"\nfatal: {ex}")- sys.exit(1)---if __name__ == "__main__":- main()diff --git a/.agents/skills/resx-translation/helpers/resx_audit.py b/.agents/skills/resx-translation/helpers/resx_audit.pynew file mode 100644index 0000000..365329e--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_audit.py@@ -0,0 +1,276 @@+# resx_audit.py — Comprehensive ResX audit: missing, empty, untranslated, warnings++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from resx_core import (+ KeyDiff,+ ResxFile,+ auto_detect,+ diff_files,+ ensure_utf8,+ find_designer,+ format_diffs_compact,+ load_designer_keys,+ parse_resx,+ resx_key_to_property,+)+++def audit_directory(+ base: Path,+ *,+ show_missing: bool = True,+ show_empty: bool = True,+ show_untranslated: bool = True,+ show_warnings: bool = True,+ check_designer: bool = False,+ by_key: bool = False,+ lang_filter: str | None = None,+ json_out: bool = False,+ fail_on_any: bool = False,+) -> None:+ default_name, pattern, _ = auto_detect(base)+ if not default_name:+ print("no .resx files found")+ sys.exit(1)++ default_path = base / default_name+ default = parse_resx(default_path)+ if default is None:+ print(f"error parsing {default_name}")+ sys.exit(1)++ # Parse locale files+ locales: list[ResxFile] = []+ for fp in sorted(base.glob(pattern)):+ if fp.name == default_name:+ continue+ rf = parse_resx(fp)+ if rf is not None:+ locales.append(rf)++ if lang_filter:+ locales = [lf for lf in locales if lang_filter.lower() in lf.lang.lower()]++ if not locales:+ print("no locale files found")+ sys.exit(0)++ # Compute diffs+ all_diffs: dict[str, list[KeyDiff]] = {}+ for lf in locales:+ all_diffs[lf.lang] = diff_files(default, lf)++ # Collect issues+ total_missing = 0+ total_empty = 0+ total_untranslated = 0+ warnings: list[str] = []++ for lang, diffs in all_diffs.items():+ for d in diffs:+ if d.status == "missing":+ total_missing += 1+ elif d.status == "empty":+ total_empty += 1+ elif d.status == "untranslated":+ total_untranslated += 1++ # Warnings+ if show_warnings:+ # Check encoding consistency+ encodings = set()+ encodings.add(default.encoding)+ for lf in locales:+ encodings.add(lf.encoding)+ if len(encodings) > 1:+ warnings.append(f"mixed encodings: {', '.join(sorted(encodings))}")++ # Check key count mismatch+ counts = {lf.lang: lf.key_count for lf in locales}+ if len(set(counts.values())) > 1:+ min_c = min(counts.values())+ max_c = max(counts.values())+ warnings.append(f"key count mismatch: {min_c} to {max_c}")++ # Check for duplicate keys in any file+ for lf in [default] + locales:+ keys = [e.key for e in lf.entries]+ seen = set()+ for k in keys:+ if k in seen:+ warnings.append(f"duplicate key '{k}' in {lf.filename}")+ seen.add(k)++ # Designer.cs check+ if check_designer:+ designer = find_designer(base, default_name)+ if designer:+ d_props = load_designer_keys(designer)+ r_props = {resx_key_to_property(k) for k in default.keys}+ missing_props = r_props - d_props+ stale_props = d_props - r_props+ if missing_props:+ warnings.append(f"Designer.cs missing {len(missing_props)} properties")+ if stale_props:+ warnings.append(f"Designer.cs has {len(stale_props)} stale properties")++ any_issues = total_missing + total_empty + total_untranslated > 0 or warnings++ if json_out:+ data = {+ "default": default.filename,+ "locales": len(locales),+ "total_keys": default.key_count,+ "missing": total_missing,+ "empty": total_empty,+ "untranslated": total_untranslated,+ "warnings": warnings,+ "details": {},+ }+ for lang, diffs in all_diffs.items():+ issues = [d for d in diffs if d.status != "ok"]+ data["details"][lang] = [+ {+ "key": d.key,+ "status": d.status,+ "default_value": d.default_value,+ "locale_value": d.locale_value,+ "default_line": d.default_line,+ "locale_line": d.locale_line,+ "default_index": d.default_index,+ "locale_index": d.locale_index,+ }+ for d in issues+ ]+ json.dump(data, sys.stdout, indent=2, ensure_ascii=False)+ print()+ if fail_on_any and any_issues:+ sys.exit(1)+ return++ # Human-readable output+ print(f"\n{'=' * 60}")+ print("resx manager — audit")+ print(f"{'=' * 60}")+ print(f" default : {default.filename} ({default.key_count} keys)")+ print(f" locales : {len(locales)}")++ if not any_issues:+ print(f"\n all translations look good across all locales")+ _print_summary(default.key_count, len(locales), 0, 0, 0, warnings)+ return++ # Per-locale issues+ for lf in locales:+ lang = lf.lang+ diffs = all_diffs.get(lang, [])+ issues = [d for d in diffs if d.status != "ok"]+ missing = [d for d in diffs if d.status == "missing"]+ empty = [d for d in diffs if d.status == "empty"]+ untranslated = [d for d in diffs if d.status == "untranslated"]++ print(f"\n [{lang}] — {lf.filename}")+ if not issues:+ print(f" ok ({lf.key_count} keys)")+ continue++ parts = []+ if missing:+ parts.append(f"missing={len(missing)}")+ if empty:+ parts.append(f"empty={len(empty)}")+ if untranslated:+ parts.append(f"untranslated={len(untranslated)}")+ print(f" {' | '.join(parts)}")++ if show_missing and missing:+ print(f"\n missing ({len(missing)}):")+ for d in missing:+ val_preview = d.default_value[:50] + "..." if len(d.default_value) > 50 else d.default_value+ print(f" [-] {d.key} (default:L{d.default_line} #{d.default_index}) = '{val_preview}'")++ if show_empty and empty:+ print(f"\n empty ({len(empty)}):")+ for d in empty:+ print(f" [E] {d.key} ({lf.filename}:L{d.locale_line} #{d.locale_index})")++ if show_untranslated and untranslated:+ print(f"\n untranslated ({len(untranslated)}):")+ for d in untranslated:+ print(f" [U] {d.key} ({lf.filename}:L{d.locale_line} #{d.locale_index})")++ # Warnings+ if warnings:+ print(f"\n warnings ({len(warnings)}):")+ for w in warnings:+ print(f" ! {w}")++ _print_summary(default.key_count, len(locales), total_missing, total_empty, total_untranslated, warnings)++ if fail_on_any and any_issues:+ sys.exit(1)+++def _print_summary(keys: int, locales: int, missing: int, empty: int,+ untranslated: int, warnings: list[str]) -> None:+ print(f"\n{'=' * 60}")+ print("summary")+ print(f"{'=' * 60}")+ print(f" keys : {keys}")+ print(f" locales : {locales}")+ if missing:+ print(f" missing : {missing}")+ if empty:+ print(f" empty : {empty}")+ if untranslated:+ print(f" untranslated: {untranslated}")+ if warnings:+ print(f" warnings : {len(warnings)}")+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Comprehensive ResX audit: missing, empty, untranslated, warnings."+ )+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),+ help="Translations directory")+ parser.add_argument("--lang", default=None, help="Filter by locale code")+ parser.add_argument("--no-missing", action="store_true", help="Hide missing keys")+ parser.add_argument("--no-empty", action="store_true", help="Hide empty values")+ parser.add_argument("--no-untranslated", action="store_true", help="Hide untranslated")+ parser.add_argument("--no-warnings", action="store_true", help="Hide warnings")+ parser.add_argument("--check-designer", action="store_true", help="Audit Designer.cs")+ parser.add_argument("--by-key", action="store_true", help="Group by key name")+ parser.add_argument("--json", action="store_true", help="JSON output")+ parser.add_argument("--fail-on-any", action="store_true", help="Exit 1 if issues found")+ args = parser.parse_args()++ ensure_utf8()+ base = args.path.resolve()+ if not base.is_dir():+ print(f"directory not found: {base}")+ sys.exit(1)++ audit_directory(+ base,+ show_missing=not args.no_missing,+ show_empty=not args.no_empty,+ show_untranslated=not args.no_untranslated,+ show_warnings=not args.no_warnings,+ check_designer=args.check_designer,+ by_key=args.by_key,+ lang_filter=args.lang,+ json_out=args.json,+ fail_on_any=args.fail_on_any,+ )+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/resx-translation/helpers/resx_core.py b/.agents/skills/resx-translation/helpers/resx_core.pynew file mode 100644index 0000000..9ada7e3--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_core.py@@ -0,0 +1,455 @@+# resx_core.py — Core ResX manager library+# Provides low-level ResX parsing, writing, encoding, and batch operations.++from __future__ import annotations++import io+import json+import re+import sys+import xml.etree.ElementTree as ET+from dataclasses import dataclass, field+from pathlib import Path+from typing import Optional+from xml.sax.saxutils import escape as _xml_escape++# ---------------------------------------------------------------------------+# Encoding helpers+# ---------------------------------------------------------------------------++def ensure_utf8() -> None:+ """Force stdout to UTF-8 to avoid encoding errors on Windows."""+ try:+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")+ except Exception:+ pass+++def detect_encoding(path: Path) -> str:+ """Return 'UTF-8 with BOM', 'UTF-8 (no BOM)', or 'unknown'."""+ try:+ raw = path.read_bytes()+ except Exception:+ return "unknown"+ if raw[:3] == b"\xef\xbb\xbf":+ return "UTF-8 with BOM"+ if raw[:5] == b"<?xml" or raw[:6] == b"<?xml ":+ return "UTF-8 (no BOM)"+ return "unknown"+++def read_resx_text(path: Path) -> str | None:+ """Read a .resx file preserving BOM awareness."""+ try:+ return path.read_text(encoding="utf-8-sig")+ except Exception:+ return None+++# ---------------------------------------------------------------------------+# Data classes+# ---------------------------------------------------------------------------++@dataclass+class ResxEntry:+ """A single <data> entry inside a .resx file."""+ key: str+ value: str+ line: int # 1-based line number of <data name="..."> in the raw file+ index: int # 0-based ordinal among all <data> elements+ xml_space: str = "preserve"+++@dataclass+class ResxFile:+ """Parsed representation of a .resx file."""+ path: Path+ filename: str+ lang: str # extracted locale code, or 'default' for the base file+ encoding: str+ entries: list[ResxEntry] = field(default_factory=list)+ _key_map: dict[str, ResxEntry] = field(default_factory=dict, repr=False)++ def __post_init__(self) -> None:+ self._key_map = {e.key: e for e in self.entries}++ @property+ def key_count(self) -> int:+ return len(self.entries)++ @property+ def keys(self) -> list[str]:+ return [e.key for e in self.entries]++ def get(self, key: str) -> ResxEntry | None:+ return self._key_map.get(key)++ def has_key(self, key: str) -> bool:+ return key in self._key_map++ def to_dict(self) -> dict[str, str]:+ return {e.key: e.value for e in self.entries}+++# ---------------------------------------------------------------------------+# Parsing+# ---------------------------------------------------------------------------++_DATA_RE = re.compile(r'<data\s+name="([^"]*)"(?:\s+[^>]*)?>')+_SPACE_RE = re.compile(r'xml:space="([^"]*)"')+++def parse_resx(path: Path) -> ResxFile | None:+ """Parse a .resx file into a ResxFile. Returns None on error."""+ text = read_resx_text(path)+ if text is None:+ return None++ encoding = detect_encoding(path)+ lang = _extract_lang(path)++ # Build line number map: key -> line number+ line_map: dict[str, int] = {}+ for i, line in enumerate(text.splitlines(), 1):+ m = _DATA_RE.search(line)+ if m:+ line_map[m.group(1)] = i++ # Parse XML for values+ try:+ tree = ET.fromstring(text.encode("utf-8"))+ except ET.ParseError:+ return None++ entries: list[ResxEntry] = []+ for idx, data_el in enumerate(tree.findall("data")):+ name = data_el.get("name")+ if not name:+ continue+ val_el = data_el.find("value")+ value = (val_el.text or "").strip() if val_el is not None else ""+ xml_space = data_el.get("xml:space", "preserve")+ line = line_map.get(name, 0)+ entries.append(ResxEntry(key=name, value=value, line=line, index=idx, xml_space=xml_space))++ return ResxFile(+ path=path,+ filename=path.name,+ lang=lang,+ encoding=encoding,+ entries=entries,+ )+++def _extract_lang(path: Path) -> str:+ """Extract locale from filename. 'Translations.vi.resx' -> 'vi', 'Translations.resx' -> 'default'."""+ stem = path.stem+ parts = stem.split(".", 1)+ return parts[1] if len(parts) > 1 else "default"+++# ---------------------------------------------------------------------------+# Auto-detection+# ---------------------------------------------------------------------------++def auto_detect(directory: Path) -> tuple[str, str, list[Path]]:+ """Detect the base .resx and locale pattern in a directory.+ Returns (base_filename, locale_glob, locale_files).+ """+ all_resx = sorted(directory.glob("*.resx"))+ if not all_resx:+ return ("", "", [])++ no_lang = [f for f in all_resx if "." not in f.stem]+ has_lang = [f for f in all_resx if "." in f.stem]++ if no_lang:+ base = no_lang[0]+ elif has_lang:+ base = has_lang[0]+ else:+ base = all_resx[0]++ base_stem = base.stem+ pattern = f"{base_stem}.*.resx"+ return base.name, pattern, has_lang+++# ---------------------------------------------------------------------------+# Writing — add keys+# ---------------------------------------------------------------------------++def add_keys(path: Path, entries: dict[str, str]) -> int:+ """Add new <data> entries to a .resx file before </root>. Returns count added."""+ text = read_resx_text(path)+ if text is None:+ return -1++ existing = set(re.findall(r'<data\s+name="([^"]*)"', text))+ to_add = {k: v for k, v in entries.items() if k not in existing}+ if not to_add:+ return 0++ buf: list[str] = []+ for key, val in to_add.items():+ escaped = _xml_escape(val)+ buf.append(+ f' <data name="{key}" xml:space="preserve">\n'+ f' <value>{escaped}</value>\n'+ f' </data>'+ )++ insert = "\n".join(buf) + "\n</root>"+ new_text = text.replace("</root>", insert)++ try:+ path.write_text(new_text, encoding="utf-8-sig")+ except Exception:+ return -1++ return len(to_add)+++# ---------------------------------------------------------------------------+# Writing — update existing values+# ---------------------------------------------------------------------------++def update_values(path: Path, updates: dict[str, str]) -> int:+ """Update values of existing <data> entries. Returns count updated."""+ text = read_resx_text(path)+ if text is None:+ return -1++ count = 0+ for key, new_val in updates.items():+ # Match the <data> block for this key and replace <value>...</value>+ pattern = re.compile(+ r'(<data\s+name="' + re.escape(key) + r'"[^>]*>\s*'+ r'<value>)(.*?)(</value>)',+ re.DOTALL,+ )+ escaped = _xml_escape(new_val)+ new_text, n = pattern.subn(r'\g<1>' + escaped + r'\g<3>', text, count=1)+ if n > 0:+ text = new_text+ count += 1++ if count > 0:+ try:+ path.write_text(text, encoding="utf-8-sig")+ except Exception:+ return -1++ return count+++# ---------------------------------------------------------------------------+# Writing — create new locale+# ---------------------------------------------------------------------------++def create_locale(source_path: Path, target_path: Path) -> bool:+ """Copy a source .resx to create a new locale file."""+ import shutil+ if target_path.exists():+ return False+ try:+ shutil.copy2(source_path, target_path)+ return True+ except Exception:+ return False+++# ---------------------------------------------------------------------------+# Batch write from structured input+# ---------------------------------------------------------------------------++def parse_batch_input(raw: str) -> dict[str, str]:+ """Parse KEY=VALUE pairs from a multiline string.+ Supports:+ KEY=VALUE+ KEY="quoted value with spaces"+ # comments and blank lines are skipped+ """+ result: dict[str, str] = {}+ for line in raw.strip().splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ if "=" not in line:+ continue+ key, _, val = line.partition("=")+ key = key.strip()+ val = val.strip()+ # Strip surrounding quotes+ if len(val) >= 2 and val[0] == val[-1] and val[0] in ('"', "'"):+ val = val[1:-1]+ if key:+ result[key] = val+ return result+++def write_translations(+ path: Path,+ translations: dict[str, str],+ mode: str = "auto",+) -> dict[str, int]:+ """Write translations to a .resx file.+ mode:+ 'update' — only update existing keys+ 'add' — only add new keys+ 'upsert' — add new + update existing+ 'auto' — update existing, add new (same as upsert)+ Returns dict with counts: {'added': N, 'updated': N, 'skipped': N}.+ """+ text = read_resx_text(path)+ if text is None:+ return {"added": -1, "updated": 0, "skipped": 0}++ existing = set(re.findall(r'<data\s+name="([^"]*)"', text))+ to_update = {k: v for k, v in translations.items() if k in existing}+ to_add = {k: v for k, v in translations.items() if k not in existing}++ updated = 0+ added = 0++ if mode in ("update", "auto", "upsert") and to_update:+ updated = update_values(path, to_update)+ # Re-read after update+ text = read_resx_text(path) or text++ if mode in ("add", "auto", "upsert") and to_add:+ added = add_keys(path, to_add)++ skipped = len(translations) - updated - added+ return {"added": added, "updated": updated, "skipped": max(0, skipped)}+++# ---------------------------------------------------------------------------+# Diff / comparison+# ---------------------------------------------------------------------------++@dataclass+class KeyDiff:+ """Difference for a single key between two ResxFiles."""+ key: str+ status: str # 'missing', 'empty', 'untranslated', 'ok'+ default_value: str = ""+ locale_value: str = ""+ default_line: int = 0+ locale_line: int = 0+ default_index: int = 0+ locale_index: int = 0+++def diff_files(default: ResxFile, locale: ResxFile) -> list[KeyDiff]:+ """Compare a locale file against the default. Returns list of KeyDiff for all keys."""+ default_map = default.to_dict()+ locale_map = locale.to_dict()+ all_keys = list(dict.fromkeys(list(default_map.keys()) + list(locale_map.keys())))++ diffs: list[KeyDiff] = []+ for key in all_keys:+ dv = default_map.get(key, "")+ lv = locale_map.get(key, "")+ d_entry = default.get(key)+ l_entry = locale.get(key)++ if key not in locale_map:+ status = "missing"+ elif not lv:+ status = "empty"+ elif dv and lv == dv and locale.lang != "default":+ status = "untranslated"+ else:+ status = "ok"++ diffs.append(KeyDiff(+ key=key,+ status=status,+ default_value=dv,+ locale_value=lv,+ default_line=d_entry.line if d_entry else 0,+ locale_line=l_entry.line if l_entry else 0,+ default_index=d_entry.index if d_entry else 0,+ locale_index=l_entry.index if l_entry else 0,+ ))++ return diffs+++# ---------------------------------------------------------------------------+# Designer.cs helpers+# ---------------------------------------------------------------------------++_DESIGNER_PROP_RE = re.compile(r'internal\s+static\s+string\s+(\w+)')+++def find_designer(base_dir: Path, resx_name: str) -> Path | None:+ candidate = base_dir / resx_name.replace(".resx", ".Designer.cs")+ return candidate if candidate.exists() else None+++def load_designer_keys(designer_path: Path) -> set[str]:+ try:+ text = designer_path.read_text(encoding="utf-8")+ except Exception:+ return set()+ return {m.group(1) for m in _DESIGNER_PROP_RE.finditer(text)}+++def resx_key_to_property(key: str) -> str:+ return key.replace(".", "_")+++# ---------------------------------------------------------------------------+# Token-efficient output formatters+# ---------------------------------------------------------------------------++def format_entry_compact(entry: ResxEntry, show_value: bool = True, max_val: int = 60) -> str:+ """Format a single entry compactly: [#idx] Key = 'value' (line:N)"""+ val = entry.value+ if show_value and len(val) > max_val:+ val = val[:max_val] + "..."+ escaped = val.replace("\\", "\\\\").replace("'", "\\'")+ parts = [f"[#{entry.index}]", f"{entry.key} = '{escaped}'"]+ if entry.line:+ parts.append(f"(line:{entry.line})")+ return " ".join(parts)+++def format_entries_table(entries: list[ResxEntry], show_values: bool = True) -> str:+ """Format entries as a compact aligned table."""+ if not entries:+ return " (no entries)"++ lines: list[str] = []+ max_key_len = max(len(e.key) for e in entries)+ for e in entries:+ idx = f"#{e.index:<3d}"+ key = e.key.ljust(max_key_len)+ line_info = f"L{e.line}" if e.line else "?"+ if show_values:+ val = e.value+ if len(val) > 50:+ val = val[:47] + "..."+ lines.append(f" [{idx}] {key} = '{val}' ({e.filename}:{line_info})")+ else:+ lines.append(f" [{idx}] {key} ({e.filename}:{line_info})")+ return "\n".join(lines)+++def format_diffs_compact(diffs: list[KeyDiff], default_filename: str, locale_filename: str) -> str:+ """Format diffs in a compact, token-efficient way."""+ issues = [d for d in diffs if d.status != "ok"]+ if not issues:+ return " all translations look good"++ lines: list[str] = []+ for d in issues:+ if d.status == "missing":+ lines.append(f" [-] {d.key} (in {default_filename}:L{d.default_line} #{d.default_index})")+ elif d.status == "empty":+ lines.append(f" [E] {d.key} (in {locale_filename}:L{d.locale_line} #{d.locale_index})")+ elif d.status == "untranslated":+ lines.append(f" [U] {d.key} = '{d.default_value[:40]}' ({locale_filename}:L{d.locale_line})")+ return "\n".join(lines)diff --git a/.agents/skills/resx-translation/helpers/resx_create.py b/.agents/skills/resx-translation/helpers/resx_create.pynew file mode 100644index 0000000..bcc7ac6--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_create.py@@ -0,0 +1,99 @@+# resx_create.py — Create new locale .resx files from the source++from __future__ import annotations++import argparse+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from resx_core import (+ auto_detect,+ create_locale,+ ensure_utf8,+ parse_resx,+)+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Create new locale .resx files from the source."+ )+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),+ help="Translations directory")+ parser.add_argument("--locale", required=True,+ help="Language code (e.g. vi, ja, fr-FR)")+ parser.add_argument("--source", default=None,+ help="Source .resx (default: auto-detected base)")+ parser.add_argument("--dry-run", action="store_true",+ help="Preview without creating")+ parser.add_argument("--json", action="store_true", help="JSON output")+ args = parser.parse_args()++ ensure_utf8()+ base = args.path.resolve()+ if not base.is_dir():+ print(f"directory not found: {base}")+ sys.exit(1)++ default_name, _, _ = auto_detect(base)+ source_name = args.source or default_name+ source_path = base / source_name++ if not source_path.exists():+ print(f"source not found: {source_path}")+ sys.exit(1)++ source = parse_resx(source_path)+ if source is None:+ print(f"error parsing {source_name}")+ sys.exit(1)++ stem = Path(source_name).stem+ new_name = f"{stem}.{args.locale}.resx"+ new_path = base / new_name++ if new_path.exists():+ msg = f"already exists: {new_name}"+ if args.json:+ import json+ json.dump({"error": msg, "file": new_name}, sys.stdout)+ print()+ else:+ print(msg)+ sys.exit(1)++ if args.dry_run:+ if args.json:+ import json+ json.dump({+ "dry_run": True,+ "would_create": new_name,+ "source": source_name,+ "keys": source.key_count,+ }, sys.stdout, indent=2)+ print()+ else:+ print(f"[dry-run] would create: {new_name} ({source.key_count} keys from {source_name})")+ return++ ok = create_locale(source_path, new_path)+ if ok:+ if args.json:+ import json+ json.dump({+ "created": new_name,+ "source": source_name,+ "keys": source.key_count,+ "encoding": source.encoding,+ }, sys.stdout, indent=2)+ print()+ else:+ print(f"Created: {new_name} ({source.key_count} keys from {source_name}, {source.encoding})")+ else:+ print(f"error creating {new_name}")+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/resx-translation/helpers/resx_helpers.py b/.agents/skills/resx-translation/helpers/resx_helpers.pydeleted file mode 100644index c55f2b1..0000000--- a/.agents/skills/resx-translation/helpers/resx_helpers.py+++ /dev/null@@ -1,170 +0,0 @@-# resx_helpers.py — Shared utilities for resx translation tools--from __future__ import annotations--import io-import re-import sys-import xml.etree.ElementTree as ET-from pathlib import Path-from xml.sax.saxutils import escape as xml_escape--DESIGNER_PROP_RE = re.compile(r'internal\s+static\s+string\s+(\w+)')---def ensure_utf8() -> None:- try:- sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")- except Exception:- pass---def load_resx(path: Path) -> dict[str, str] | None:- try:- tree = ET.parse(path)- except (FileNotFoundError, ET.ParseError, PermissionError) as ex:- print(f" [error] {path.name}: {ex}", file=sys.stderr)- return None- except Exception as ex:- print(f" [error] unexpected: {path.name}: {ex}", file=sys.stderr)- return None-- result = {}- for data in tree.getroot().findall("data"):- name = data.get("name")- if name:- val = data.findtext("value")- result[name] = (val or "").strip()- return result---def load_resx_with_lines(path: Path) -> dict[str, tuple[str, int]] | None:- try:- tree = ET.parse(path)- except (FileNotFoundError, ET.ParseError, PermissionError) as ex:- print(f" [error] {path.name}: {ex}", file=sys.stderr)- return None- except Exception as ex:- print(f" [error] unexpected: {path.name}: {ex}", file=sys.stderr)- return None-- try:- lines = path.read_text(encoding="utf-8-sig").splitlines()- except Exception as ex:- print(f" [error] scanning {path.name}: {ex}", file=sys.stderr)- return None-- key_lines: dict[str, int] = {}- for i, line in enumerate(lines, 1):- m = re.search(r'<data\s+name="([^"]*)"', line)- if m:- key_lines[m.group(1)] = i-- result: dict[str, tuple[str, int]] = {}- for data in tree.getroot().findall("data"):- name = data.get("name")- if name:- val = data.findtext("value")- result[name] = ((val or "").strip(), key_lines.get(name, 0))-- return result---def extract_lang(filepath: Path) -> str:- stem = filepath.stem- parts = stem.split(".", 1)- return parts[1] if len(parts) > 1 else parts[0]---def auto_detect_pattern(directory: Path) -> tuple[str, str, list[Path]]:- all_resx = sorted(directory.glob("*.resx"))- if not all_resx:- return ("Translations.resx", "Translations.*.resx", [])-- no_lang = [f for f in all_resx if "." not in f.stem]- has_lang = [f for f in all_resx if "." in f.stem]- default = no_lang[0].name if no_lang else all_resx[0].name-- base_stem = Path(default).stem- pattern = f"{base_stem}.*.resx" if has_lang else default.replace(".resx", ".*.resx")- return default, pattern, has_lang---def find_designer(base_dir: Path, resx_name: str) -> Path | None:- candidate = base_dir / resx_name.replace(".resx", ".Designer.cs")- return candidate if candidate.exists() else None---def load_designer_keys(designer_path: Path) -> set[str]:- try:- text = designer_path.read_text(encoding="utf-8")- except Exception as ex:- print(f" [error] reading {designer_path.name}: {ex}", file=sys.stderr)- return set()- return {m.group(1) for m in DESIGNER_PROP_RE.finditer(text)}---def resx_key_to_property(key: str) -> str:- return key.replace(".", "_")---def get_union_keys(locale_data: dict[str, dict[str, str]]) -> set[str]:- keys: set[str] = set()- for data in locale_data.values():- keys.update(data.keys())- return keys---def compute_issues(- locale_data: dict[str, dict[str, str]],- default_data: dict[str, str],- default_lang: str | None,-) -> dict[str, dict[str, list[str]]]:- all_keys = get_union_keys(locale_data)- issues: dict[str, dict[str, list[str]]] = {}- for lang, data in locale_data.items():- issues[lang] = {- "missing": sorted(all_keys - data.keys()),- "empty": sorted(k for k, v in data.items() if not v),- "untranslated": sorted(- k for k, v in data.items()- if lang != default_lang and k in default_data and v == default_data[k]- ),- }- return issues---def print_header(title: str) -> None:- n = min(len(title), 72)- print(f"\n{'=' * n}")- print(title)- print("=" * n)---def add_keys_to_resx(resx_path: Path, new_entries: dict[str, str]) -> int:- try:- content = resx_path.read_text(encoding="utf-8-sig")- except Exception as ex:- print(f" [error] reading {resx_path.name}: {ex}", file=sys.stderr)- return -1-- existing = set(re.findall(r'<data\s+name="([^"]*)"', content))- to_add = {k: v for k, v in new_entries.items() if k not in existing}- if not to_add:- return 0-- buf = []- for key, val in to_add.items():- escaped = xml_escape(val)- buf.append(f' <data name="{key}" xml:space="preserve">\n <value>{escaped}</value>\n </data>')-- repl = "\n".join(buf) + "\n</root>"- new_content = content.replace("</root>", repl)-- try:- resx_path.write_text(new_content, encoding="utf-8-sig")- except Exception as ex:- print(f" [error] writing {resx_path.name}: {ex}", file=sys.stderr)- return -1-- return len(to_add)diff --git a/.agents/skills/resx-translation/helpers/resx_list.py b/.agents/skills/resx-translation/helpers/resx_list.pynew file mode 100644index 0000000..ace642a--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_list.py@@ -0,0 +1,140 @@+# resx_list.py — List ResX files and their translations with index, line numbers, values++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from resx_core import (+ ResxFile,+ auto_detect,+ detect_encoding,+ ensure_utf8,+ format_entries_table,+ format_entry_compact,+ parse_resx,+)+++def list_directory(base: Path, *, lang_filter: str | None = None,+ show_values: bool = True, json_out: bool = False,+ keys_only: bool = False, key_filter: str | None = None) -> None:+ default_name, pattern, locale_files = auto_detect(base)+ if not default_name:+ print(f"no .resx files found in {base}")+ sys.exit(1)++ default_path = base / default_name+ default = parse_resx(default_path)+ if default is None:+ print(f"error parsing {default_name}")+ sys.exit(1)++ # Parse all locale files+ locales: list[ResxFile] = []+ for fp in sorted(base.glob(pattern)):+ if fp.name == default_name:+ continue+ rf = parse_resx(fp)+ if rf is not None:+ locales.append(rf)++ if lang_filter:+ locales = [lf for lf in locales if lang_filter.lower() in lf.lang.lower()]++ if json_out:+ data = {+ "default": {+ "file": default.filename,+ "lang": default.lang,+ "encoding": default.encoding,+ "keys": default.key_count,+ "entries": [+ {"index": e.index, "key": e.key, "value": e.value, "line": e.line}+ for e in default.entries+ ],+ },+ "locales": [+ {+ "file": lf.filename,+ "lang": lf.lang,+ "encoding": lf.encoding,+ "keys": lf.key_count,+ "entries": [+ {"index": e.index, "key": e.key, "value": e.value, "line": e.line}+ for e in lf.entries+ ],+ }+ for lf in locales+ ],+ }+ json.dump(data, sys.stdout, indent=2, ensure_ascii=False)+ print()+ return++ # Human-readable output+ print(f"\n{'=' * 60}")+ print("resx manager — file listing")+ print(f"{'=' * 60}")+ print(f" directory : {base}")+ print(f" default : {default.filename} ({default.key_count} keys, {default.encoding})")+ print(f" locales : {len(locales)}")++ # Default file entries+ print(f"\n--- {default.filename} (default) ---")+ entries = default.entries+ if key_filter:+ entries = [e for e in entries if key_filter.lower() in e.key.lower()]+ if keys_only:+ for e in entries:+ print(format_entry_compact(e, show_value=False))+ else:+ print(format_entries_table(entries, show_values=show_values))++ # Locale files+ for lf in locales:+ print(f"\n--- {lf.filename} ({lf.lang}) — {lf.key_count} keys, {lf.encoding} ---")+ entries = lf.entries+ if key_filter:+ entries = [e for e in entries if key_filter.lower() in e.key.lower()]+ if keys_only:+ for e in entries:+ print(format_entry_compact(e, show_value=False))+ else:+ print(format_entries_table(entries, show_values=show_values))+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="List ResX files with translations, indices, and line numbers."+ )+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),+ help="Translations directory (default: current)")+ parser.add_argument("--lang", default=None, help="Filter by locale code (e.g. 'vi', 'ja')")+ parser.add_argument("--key", default=None, help="Filter keys by substring")+ parser.add_argument("--keys-only", action="store_true", help="Show only keys, no values")+ parser.add_argument("--no-values", action="store_true", help="Hide values entirely")+ parser.add_argument("--json", action="store_true", help="Output as JSON")+ args = parser.parse_args()++ ensure_utf8()+ base = args.path.resolve()+ if not base.is_dir():+ print(f"directory not found: {base}")+ sys.exit(1)++ list_directory(+ base,+ lang_filter=args.lang,+ show_values=not args.no_values,+ json_out=args.json,+ keys_only=args.keys_only,+ key_filter=args.key,+ )+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/resx-translation/helpers/resx_sync.py b/.agents/skills/resx-translation/helpers/resx_sync.pynew file mode 100644index 0000000..91dcf8f--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_sync.py@@ -0,0 +1,149 @@+# resx_sync.py — Synchronise missing keys from source to locale files++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from resx_core import (+ add_keys,+ auto_detect,+ ensure_utf8,+ parse_resx,+)+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Sync missing keys from source .resx to locale files."+ )+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),+ help="Translations directory")+ parser.add_argument("--source", default=None,+ help="Source .resx (default: auto-detected)")+ parser.add_argument("--locale", default=None,+ help="Only sync a specific locale")+ parser.add_argument("--fill-source", action="store_true",+ help="Copy source value as-is (default: empty)")+ parser.add_argument("--fill-marker", default=None,+ help="Fill with marker string (e.g. 'TODO')")+ parser.add_argument("--dry-run", action="store_true",+ help="Preview without writing")+ parser.add_argument("--json", action="store_true", help="JSON output")+ args = parser.parse_args()++ ensure_utf8()+ base = args.path.resolve()+ if not base.is_dir():+ print(f"directory not found: {base}")+ sys.exit(1)++ default_name, pattern, _ = auto_detect(base)+ source_name = args.source or default_name+ source_path = base / source_name++ if not source_path.exists():+ print(f"source not found: {source_path}")+ sys.exit(1)++ source = parse_resx(source_path)+ if source is None:+ print(f"error parsing {source_name}")+ sys.exit(1)++ source_keys = source.to_dict()++ # Find target locale files+ targets: list[Path] = []+ for fp in sorted(base.glob(pattern)):+ if fp.name == source_name:+ continue+ if args.locale and args.locale.lower() not in fp.stem.lower():+ continue+ targets.append(fp)++ if not targets:+ msg = f"no locale files matching pattern"+ if args.json:+ json.dump({"error": msg}, sys.stdout)+ print()+ else:+ print(msg)+ sys.exit(1)++ results: list[dict] = []+ total_added = 0++ for fp in targets:+ rf = parse_resx(fp)+ if rf is None:+ results.append({"file": fp.name, "error": "parse failed"})+ continue++ missing = {k: v for k, v in source_keys.items() if not rf.has_key(k)}+ if not missing:+ results.append({"file": fp.name, "lang": rf.lang, "added": 0})+ continue++ if args.fill_source:+ fill = {k: source_keys[k] for k in missing}+ elif args.fill_marker:+ fill = {k: args.fill_marker for k in missing}+ else:+ fill = {k: "" for k in missing}++ if args.dry_run:+ results.append({+ "file": fp.name,+ "lang": rf.lang,+ "would_add": len(missing),+ "keys": list(missing.keys()),+ })+ continue++ added = add_keys(fp, fill)+ total_added += added+ results.append({"file": fp.name, "lang": rf.lang, "added": added})++ if args.json:+ json.dump({+ "source": source_name,+ "dry_run": args.dry_run,+ "results": results,+ "total_added": total_added,+ }, sys.stdout, indent=2, ensure_ascii=False)+ print()+ return++ # Human-readable+ print(f"\n{'=' * 60}")+ print("resx manager — sync keys")+ print(f"{'=' * 60}")+ print(f" source : {source_name} ({source.key_count} keys)")++ for r in results:+ if "error" in r:+ print(f" {r['file']}: error — {r['error']}")+ continue+ added = r.get("added", 0)+ would = r.get("would_add", 0)+ if args.dry_run:+ print(f" {r['file']} ({r['lang']}): would add {would}")+ if "keys" in r:+ for k in r["keys"]:+ print(f" + {k}")+ else:+ print(f" {r['file']} ({r['lang']}): added {added}")++ if not args.dry_run:+ print(f"\n{'=' * 60}")+ print("result")+ print(f"{'=' * 60}")+ print(f" total added: {total_added}")+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/resx-translation/helpers/resx_write.py b/.agents/skills/resx-translation/helpers/resx_write.pynew file mode 100644index 0000000..d4420ee--- /dev/null+++ b/.agents/skills/resx-translation/helpers/resx_write.py@@ -0,0 +1,250 @@+# resx_write.py — Batch write/update translations to ResX files+# Supports: KEY=VALUE pairs, JSON, stdin, single or multiple locales.++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from resx_core import (+ auto_detect,+ ensure_utf8,+ parse_batch_input,+ parse_resx,+ write_translations,+)+++def resolve_targets(+ base: Path,+ default_name: str,+ locale: str | None,+ all_locales: bool,+) -> list[Path]:+ """Resolve which locale files to write to."""+ _, pattern, _ = auto_detect(base)+ targets: list[Path] = []++ for fp in sorted(base.glob(pattern)):+ if fp.name == default_name:+ continue+ if locale and locale.lower() not in fp.stem.lower():+ continue+ targets.append(fp)++ if not targets and locale:+ # If locale specified but no file exists, try creating it+ source_path = base / default_name+ stem = Path(default_name).stem+ new_path = base / f"{stem}.{locale}.resx"+ if new_path.exists():+ targets.append(new_path)++ return targets+++def read_input_source(source: str | None, stdin_flag: bool) -> dict[str, str] | None:+ """Read translations from a source. Returns parsed KEY=VALUE dict."""+ if stdin_flag or source == "-":+ raw = sys.stdin.read()+ return parse_batch_input(raw)++ if source and Path(source).is_file():+ text = Path(source).read_text(encoding="utf-8")+ # Try JSON first, then KEY=VALUE+ try:+ data = json.loads(text)+ if isinstance(data, dict):+ return {str(k): str(v) for k, v in data.items()}+ except (json.JSONDecodeError, ValueError):+ pass+ return parse_batch_input(text)++ # Treat as inline KEY=VALUE string+ if source:+ return parse_batch_input(source)++ return None+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Batch write/update translations to ResX files.",+ epilog="""+Examples:+ # Write a single key to all locales+ python resx_write.py lang --key AppTitle --value "OptimizerDuck" --locale vi++ # Write multiple keys from stdin (KEY=VALUE format)+ echo "AppTitle=OptimizerDuck\nButtonSave=Lưu" | python resx_write.py lang --stdin --locale vi++ # Write from a file+ python resx_write.py lang --file translations.txt --locale vi++ # Update existing keys only (skip new keys)+ python resx_write.py lang --file translations.txt --locale vi --mode update++ # Add new keys only+ python resx_write.py lang --file translations.txt --locale vi --mode add++ # Dry run — show what would change+ python resx_write.py lang --file translations.txt --locale vi --dry-run+ """,+ )+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),+ help="Translations directory")++ # Input methods (mutually exclusive group)+ input_group = parser.add_mutually_exclusive_group()+ input_group.add_argument("--key", help="Single key to write")+ input_group.add_argument("--file", type=Path, help="File with KEY=VALUE pairs or JSON")+ input_group.add_argument("--stdin", action="store_true", help="Read from stdin")++ parser.add_argument("--value", help="Value for --key mode")+ parser.add_argument("--locale", default=None,+ help="Target locale(s): 'vi', 'ja', 'all'")+ parser.add_argument("--mode", choices=["auto", "update", "add", "upsert"],+ default="auto",+ help="Write mode: auto (default), update, add, upsert")+ parser.add_argument("--dry-run", action="store_true",+ help="Show what would change without writing")+ parser.add_argument("--json", action="store_true", help="JSON output")+ parser.add_argument("--source", default=None,+ help="Source .resx to create locale from (if missing)")++ args = parser.parse_args()+ ensure_utf8()++ base = args.path.resolve()+ if not base.is_dir():+ print(f"directory not found: {base}")+ sys.exit(1)++ default_name, pattern, _ = auto_detect(base)+ if not default_name:+ print("no .resx files found")+ sys.exit(1)++ # Build translations dict+ translations: dict[str, str] = {}+ if args.key:+ if not args.value:+ print("--value is required with --key")+ sys.exit(1)+ translations[args.key] = args.value+ else:+ translations = read_input_source(+ str(args.file) if args.file else args.source,+ args.stdin,+ ) or {}++ if not translations:+ print("no translations to write")+ sys.exit(1)++ # Resolve target files+ targets = resolve_targets(base, default_name, args.locale, args.locale == "all")+ if not targets:+ print(f"no locale files found for '{args.locale or 'all'}'")+ sys.exit(1)++ # Create locale files if needed+ if args.source:+ from resx_core import create_locale+ source_path = base / args.source+ for fp in list(targets):+ if not fp.exists():+ ok = create_locale(source_path, fp)+ if ok:+ print(f" created: {fp.name}")++ # Write to each target+ results: list[dict] = []+ total_added = 0+ total_updated = 0++ for fp in targets:+ if not fp.exists():+ print(f" skip: {fp.name} (not found)")+ continue++ if args.dry_run:+ rf = parse_resx(fp)+ if rf is None:+ continue+ existing = set(rf.keys)+ to_update = {k: v for k, v in translations.items() if k in existing}+ to_add = {k: v for k, v in translations.items() if k not in existing}+ would_update = 0+ would_add = 0+ if args.mode in ("update", "auto", "upsert"):+ would_update = len(to_update)+ if args.mode in ("add", "auto", "upsert"):+ would_add = len(to_add)+ results.append({+ "file": fp.name,+ "lang": rf.lang,+ "would_update": would_update,+ "would_add": would_add,+ })+ continue++ result = write_translations(fp, translations, mode=args.mode)+ total_added += result["added"]+ total_updated += result["updated"]+ results.append({+ "file": fp.name,+ "added": result["added"],+ "updated": result["updated"],+ "skipped": result["skipped"],+ })++ if args.json:+ json.dump({+ "translations": translations,+ "mode": args.mode,+ "dry_run": args.dry_run,+ "results": results,+ "total_added": total_added,+ "total_updated": total_updated,+ }, sys.stdout, indent=2, ensure_ascii=False)+ print()+ return++ # Human-readable output+ print(f"\n{'=' * 60}")+ print("resx manager — write translations")+ print(f"{'=' * 60}")+ print(f" keys : {len(translations)}")+ print(f" mode : {args.mode}")+ print(f" dry_run : {args.dry_run}")++ for r in results:+ if args.dry_run:+ print(f"\n {r['file']} ({r['lang']})")+ if r["would_update"]:+ print(f" would update: {r['would_update']}")+ if r["would_add"]:+ print(f" would add : {r['would_add']}")+ else:+ print(f"\n {r['file']}")+ if r["added"]:+ print(f" + added : {r['added']}")+ if r["updated"]:+ print(f" ~ updated : {r['updated']}")+ if r["skipped"]:+ print(f" - skipped : {r['skipped']}")++ if not args.dry_run:+ print(f"\n{'=' * 60}")+ print("result")+ print(f"{'=' * 60}")+ print(f" total added : {total_added}")+ print(f" total updated: {total_updated}")+++if __name__ == "__main__":+ main()diff --git a/.agents/skills/resx-translation/helpers/sync_resx.py b/.agents/skills/resx-translation/helpers/sync_resx.pydeleted file mode 100644index bdb5862..0000000--- a/.agents/skills/resx-translation/helpers/sync_resx.py+++ /dev/null@@ -1,123 +0,0 @@-# sync_resx.py — Synchronise missing keys from a source .resx into locale files--from __future__ import annotations--try:- import argparse- import sys- from pathlib import Path-except ImportError as ex:- print(f"failed to import required module: {ex}")- raise SystemExit(1)--sys.path.insert(0, str(Path(__file__).resolve().parent))-from resx_helpers import (- add_keys_to_resx,- auto_detect_pattern,- ensure_utf8,- load_resx,- print_header,-)---def main():- try:- parser = argparse.ArgumentParser(- description="Sync missing keys from a source .resx into locale files."- )- parser.add_argument("path", type=Path, help="Translations directory")- parser.add_argument("--source", default=None,- help="Source .resx file (default: auto-detected base file)")- parser.add_argument("--target", default=None,- help="Target locale glob pattern (default: auto-detected)")- parser.add_argument("--fill-source", action="store_true",- help="Copy source value as-is (default: empty string)")- parser.add_argument("--fill-marker", default=None,- help="Fill with a marker string instead of empty (e.g. 'TODO')")- parser.add_argument("--dry-run", action="store_true",- help="Show what would be added without writing")- parser.add_argument("--locale", default=None,- help="Only sync a specific locale (e.g. 'vi-VN')")- args = parser.parse_args()-- ensure_utf8()- base = args.path.resolve()-- if not base.exists() or not base.is_dir():- print(f"directory not found: {base}")- sys.exit(1)-- default_name, pattern, _ = auto_detect_pattern(base)- source_name = args.source or default_name- locale_pattern = args.target or pattern-- source_path = base / source_name- if not source_path.exists():- print(f"source not found: {source_path}")- sys.exit(1)-- source_data = load_resx(source_path)- if source_data is None:- sys.exit(1)-- targets = sorted(base.glob(locale_pattern))- if args.locale:- targets = [t for t in targets if args.locale in t.stem]- if not targets:- print(f"no locale files matching '{args.locale}' in {base}")- sys.exit(1)-- print_header("resx sync")-- total_added = 0- for fp in targets:- if fp.name == source_name and not args.locale:- continue-- locale_data = load_resx(fp)- if locale_data is None:- continue-- missing = {k: v for k, v in source_data.items() if k not in locale_data}- if not missing:- print(f" {fp.name}: ok (no missing keys)")- continue-- lang = fp.stem.split(".", 1)[1] if "." in fp.stem else fp.stem-- if args.fill_source:- fill = {k: source_data[k] for k in missing}- elif args.fill_marker is not None:- fill = {k: args.fill_marker for k in missing}- else:- fill = {k: "" for k in missing}-- if args.dry_run:- print(f" {fp.name}: would add {len(missing)} key(s)")- for k in sorted(missing):- print(f" + {k} = {fill[k]!r}")- continue-- added = add_keys_to_resx(fp, fill)- if added > 0:- print(f" {fp.name}: added {added} key(s) ({lang})")- total_added += added- elif added == 0:- print(f" {fp.name}: ok (already up to date)")- else:- print(f" {fp.name}: error")-- if not args.dry_run:- print_header("result")- print(f" total keys added: {total_added}")-- except KeyboardInterrupt:- print("\ncancelled")- sys.exit(130)- except Exception as ex:- print(f"\nfatal: {ex}")- sys.exit(1)---if __name__ == "__main__":- main()