Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

translate skill for .po files (#1121)

Anshul sharma7e4e986cf304
diff --git a/.ai/skills/README.md b/.ai/skills/README.md
index f8a9bbb57f..71fde0a1a6 100644
--- a/.ai/skills/README.md
+++ b/.ai/skills/README.md
@@ -64,6 +64,7 @@ in root-cause, BLOCKED in fix) always surface to the human.
| `error` | Capture screenshot + snapshot on browser failure | `.ai/scratch/e2e/…` (building block) |
| `create-agents-md` | Generate/refresh a grounded AGENTS.md | `AGENTS.md` |
| `carbon-docs` | Author reader-facing docs in the docs app | `docs/content/**` |
+| `translate` | Fill missing i18n .po translations via cheap Haiku subagents | `packages/locale/locales/*/*.po` |
| `test-driven-development` | Red→green→refactor discipline (vitest) | tests-first code |
| `writing-skills` | House guide for authoring skills | skills |
| `pr-explainer` | Self-contained HTML review aid for a PR | `.pr-review/*.html` |
diff --git a/.ai/skills/check-and-commit/SKILL.md b/.ai/skills/check-and-commit/SKILL.md
index 358ecae3ad..676cdbb388 100644
--- a/.ai/skills/check-and-commit/SKILL.md
+++ b/.ai/skills/check-and-commit/SKILL.md
@@ -1,6 +1,6 @@
---
name: check-and-commit
-description: Pre-commit verification gate — runs Carbon's validation gates in order (generate:types if schema changed, biome, scoped typecheck, scoped tests, build if needed), fixes straightforward failures, then commits the specific files with a conventional message. Use after /fix, after an /execute task, or after manual changes when the work should be committed. Commits only when every gate is green; pushes only if the branch already tracks a remote or the user asked.
+description: Pre-commit verification gate — runs Carbon's validation gates in order (generate:types if schema changed, biome, scoped typecheck, scoped tests, build if needed, and /translate to fill missing i18n .po strings when UI/locale files changed), fixes straightforward failures, then commits the specific files with a conventional message. Use after /fix, after an /execute task, or after manual changes when the work should be committed. Commits only when every gate is green; pushes only if the branch already tracks a remote or the user asked.
---
<!-- Workflow pattern inspired by Open Mercato (MIT License)
https://github.com/open-mercato/open-mercato
@@ -18,12 +18,20 @@ then committing."
```bash
git status --porcelain
-git diff --name-only
+git diff --name-only HEAD # staged + unstaged vs HEAD — the full change set
```
-From the changed paths, derive:
+Derive every flag below from `git diff --name-only HEAD` (all changes vs the last
+commit). Plain `git diff --name-only` omits already-staged files, which would let
+staged UI/`.po` files slip past `I18N_RELEVANT` and skip Gate 6. From the changed
+paths, derive:
- `SCHEMA_CHANGED` — any file under `packages/database/supabase/migrations/`
+- `I18N_RELEVANT` — the diff adds/edits UI source that can introduce new
+ translatable strings (`apps/erp/app/**`, `apps/mes/app/**`,
+ `packages/react/src/**`) **or** touches any `packages/locale/locales/**/*.po`.
+ When true, Gate 3 (i18n) fills missing translations so they ship in this same
+ commit instead of drifting behind the code.
- the set of **touched packages** — run this to map changed files to workspace
package names (these are the `--filter` values for the gates):
@@ -62,6 +70,25 @@ pnpm --filter <pkg> test
pnpm exec turbo run build --filter=<pkg>
```
+### Gate 6 — i18n translations (only if `I18N_RELEVANT`)
+
+Run **last**, after the code gates are green — so no Haiku translation effort is
+spent on a commit that would fail typecheck/tests. Fill missing `.po`
+translations by invoking the **translate skill** (`/translate`), not by hand:
+
+- Invoke `/translate`. It refreshes catalogs (`lingui:extract`), fans missing
+ `msgstr` out to Haiku subagents, merges deterministically, and verifies with
+ `linguito check` — see `.ai/skills/translate/SKILL.md` for the full loop.
+- If it reports `NOTHING_TO_TRANSLATE` / `linguito check` already clean → nothing
+ to add; mark the gate SKIP and continue.
+- Otherwise it fills `packages/locale/locales/**/*.po`. Treat the gate as PASS
+ only when `/translate` finishes with `Remaining ... : 0` and `linguito check`
+ exits 0. If it stops with a residual after its 3-round cap → **STOP, report
+ BLOCKED** (don't commit half-translated catalogs).
+- The filled `.po` files are now part of this change — add them explicitly in
+ Step 4 alongside the code (their package is `@carbon/locale`). `/translate`
+ removes its own `.ai/scratch/translate/` scratch; never stage that.
+
## Step 3: Fix policy
| Failure | Action |
@@ -113,6 +140,7 @@ git commit -m "<type>(<scope>): <description>"
| typecheck (<pkgs>) | PASS | |
| test (<pkgs>) | PASS | <pre-existing failures noted> |
| build | PASS / SKIP | |
+| i18n (/translate) | PASS / SKIP | <N filled across locales, or "no missing"> |
**Commit:** `<sha>` — `<message>` · **Pushed:** yes/no
**Excluded from staging:** <files left uncommitted and why, or "none">
diff --git a/.ai/skills/translate/SKILL.md b/.ai/skills/translate/SKILL.md
new file mode 100644
index 0000000000..e8a0b1a83c
--- /dev/null
+++ b/.ai/skills/translate/SKILL.md
@@ -0,0 +1,178 @@
+---
+name: translate
+description: Fill missing i18n translations in the Lingui .po catalogs cheaply — extract every empty msgstr, fan out chunked jobs to Haiku subagents (model override, not the main model), merge results back deterministically, and verify zero remain. Produces filled packages/locale/locales/*/*.po. Use when the user asks to translate/fill missing translations, run "pnpm translate" cheaply, or after adding new UI strings. Do not use to add or mark new strings (that is lingui:extract in code) or to change the locale list — use the i18n-lingui-system rule.
+---
+
+# translate — fill missing .po translations with a cheap model
+
+Replaces `pnpm translate` (which would run every string through the main model).
+Instead: a deterministic script finds every empty `msgstr`, chunks them into
+jobs, **Haiku subagents** translate the chunks (invoked with `model: "haiku"` so
+the expensive main model only orchestrates), and a deterministic merge script
+writes them back — no model in the write path. Input → output: empty `msgstr` in
+`packages/locale/locales/{locale}/{erp,mes}.po` → filled `msgstr`.
+
+**Announce at start:** "Using the translate skill — filling missing .po translations via Haiku subagents."
+
+Scope: all target locales at once (supportedLanguages minus source `en`; orphaned
+`nl` is excluded automatically). Never overwrites an existing translation — only
+empty `msgstr` are touched.
+
+## Step 1 — Extract missing translations into chunked jobs
+
+```bash
+pnpm run lingui:extract # refresh catalogs from source strings
+node .ai/skills/translate/scripts/extract-missing.mjs # scan → chunk jobs
+```
+
+Read the printed summary. It prints total missing, chunk count, and per-locale
+counts, then writes `.ai/scratch/translate/manifest.json` plus one input file per
+chunk under `.ai/scratch/translate/in/`.
+
+- If the output contains `NOTHING_TO_TRANSLATE` → **STOP**, report "no missing
+ translations", skip to nothing. Do not run later steps.
+
+## Step 2 — Start the live progress watcher, then fan out subagents
+
+First launch the background watcher **once** — it ticks every 10s independently of
+the main loop (so it keeps reporting even while a batch of subagents is in
+flight). Use the `Bash` tool with `run_in_background: true`:
+
+```bash
+node .ai/skills/translate/scripts/progress.mjs --watch
+```
+
+It reports `chunks done/total · strings done/total (%)` with a per-locale
+breakdown, updating as each subagent writes its `out/` file. (Tune cadence with
+`TRANSLATE_PROGRESS_INTERVAL=5` seconds if the user wants faster ticks.) It stops
+itself when Step 5 writes the `.done` marker.
+
+Then read `.ai/scratch/translate/manifest.json` — an array of
+`{ chunk, in, out, locale, catalog, langLabel, count }`.
+
+For **every** entry, dispatch an `Agent` with **`model: "haiku"`**. Dispatch in
+batches of **up to 10 Agent calls per message** (multiple tool_use blocks in one
+message) so they run concurrently. **After each batch returns, run a one-shot
+snapshot** so progress is visible inline even if the background watcher output
+isn't surfaced:
+
+```bash
+node .ai/skills/translate/scripts/progress.mjs
+```
+
+Then send the next batch. Use this exact prompt, substituting the entry's `in`
+and `out` absolute paths:
+
+````text
+You are a professional software-localization translator for a manufacturing ERP.
+
+Read the input file (JSON) at this absolute path:
+<manifest entry `in`>
+
+It is: { "locale", "langLabel", "catalog", "items": [ { "msgid", "note?" } ] }.
+Translate every item's `msgid` from English into the language named by `langLabel`.
+
+RULES — follow exactly:
+1. Preserve every placeholder EXACTLY: `{0}`, `{name}`, `{count}`, etc. Never
+ translate, rename, reorder-away, or drop a placeholder token.
+2. For ICU syntax like `{0, plural, one {…} other {…}}`, keep the structure,
+ keywords (`plural`, `select`, `one`, `other`, `=0`, `#`) and braces intact;
+ translate ONLY the human words inside each `{…}` branch.
+3. Preserve leading/trailing spaces, capitalization intent, and punctuation.
+4. Do NOT translate brand names, code identifiers, or placeholder variable names.
+5. Use `note` only as context for a placeholder; never include it in the output.
+
+OUTPUT — write ONLY a JSON object (create/overwrite) to this absolute path:
+<manifest entry `out`>
+
+It maps each input `msgid` (exact original English key, unchanged) to its
+translation, e.g. { "Add parts": "Ajouter des pièces", "{0} days": "{0} jours" }.
+Every input item must be a key. No commentary. Then reply only: DONE.
+````
+
+Do **NOT** trust the subagent's reply count — a subagent may misreport how many
+it wrote. The merge script in Step 3 is the source of truth for completeness.
+
+## Step 3 — Merge deterministically and verify
+
+```bash
+node .ai/skills/translate/scripts/merge-translations.mjs
+```
+
+Read its output:
+- `Merged: N filled, M unmatched` — `unmatched` means the model returned a key
+ that no longer matches an empty `msgid` (usually the model altered the key);
+ those are skipped safely.
+- `Remaining empty msgstr in targeted catalogs: R`.
+- `Missing/invalid chunk outputs` — chunks whose `out` file is absent or bad JSON.
+
+## Step 4 — Retry until dry (max 3 rounds total)
+
+| Situation | Action |
+|-----------|--------|
+| `Remaining` is `0` | Go to Step 5. |
+| `Remaining > 0` and rounds so far `< 3` | Re-run Step 1's `extract-missing.mjs` only (NOT `lingui:extract` again) — it regenerates jobs for just the still-empty entries — then redo the **subagent dispatch + snapshot + merge** (Step 2's fan-out and Step 3). Do **not** relaunch the watcher — the one from Step 2 keeps running and re-reads the new manifest. Each round shrinks. |
+| `Remaining > 0` after 3 rounds | **STOP.** Report the residual count and the locales still short; do not loop further. |
+
+If a whole locale keeps failing, lower the chunk size and retry that round:
+`TRANSLATE_CHUNK_SIZE=15 node .ai/skills/translate/scripts/extract-missing.mjs`.
+
+## Step 5 — Normalize and report
+
+```bash
+touch .ai/scratch/translate/.done # stops the background progress watcher
+pnpm run lingui:clean # strip POT date + origin churn (same as pnpm translate)
+```
+
+Do **not** run `lingui:compile` — `.mjs` are gitignored build artifacts, produced
+at build time.
+
+## Step 6 — Verify nothing is left
+
+```bash
+pnpm exec linguito check # exits 0 = clean; non-zero = still-missing entries
+```
+
+This is the same missing-translation check `pnpm translate` runs, **without** the
+LLM step — do NOT run `pnpm translate` itself here (it would re-invoke an LLM).
+
+| Result | Action |
+|--------|--------|
+| Exit 0 / "no missing" | Verified clean → Step 7. |
+| Non-zero, lists entries | Those `msgstr` are still empty. If under the 3-round cap, go back to Step 4 (re-run `extract-missing.mjs` → dispatch → merge). Otherwise report the residual and STOP. |
+
+Report: total filled, per-locale counts, any residual, and that the changed files
+are `packages/locale/locales/*/*.po`.
+
+## Step 7 — Clean up scratch (always, even on partial/failed runs)
+
+```bash
+rm -rf .ai/scratch/translate
+```
+
+Leaving `in/`, `out/`, and `manifest.json` behind risks a stale chunk merging on
+the next run. (`extract-missing.mjs` also wipes this dir at the start of every
+run, but clean up here too so the tree is tidy.)
+
+## Output
+
+Filled `msgstr` values in `packages/locale/locales/{locale}/{erp,mes}.po`. Commit
+only if the user asks, via `/check-and-commit` (the `.po` files are the artifact;
+`.mjs` stay gitignored). Scratch under `.ai/scratch/translate/` is disposable.
+
+## Done when
+- [ ] `node .ai/skills/translate/scripts/merge-translations.mjs` reports
+ `Remaining empty msgstr ... : 0` (or the residual is reported after 3 rounds).
+- [ ] `pnpm run lingui:clean` has run.
+- [ ] `pnpm exec linguito check` exits 0 (or the residual is reported after 3 rounds).
+- [ ] Only `msgstr` lines changed in the `.po` diff (no `msgid` touched):
+ `git diff --no-color packages/locale/locales | grep -E '^\+' | grep -vE '^\+msgstr|^\+\+\+'` is empty.
+- [ ] `.ai/scratch/translate` has been removed.
+
+## Failure → action
+| Symptom | Action |
+|---------|--------|
+| `extract-missing.mjs` errors reading config | Confirm `packages/locale/src/config.ts` still defines `supportedLanguages` + `languageNativeLabels`; the parser reads them by regex. |
+| Merge shows many `unmatched` | The model rewrote keys. Re-run the round with smaller `TRANSLATE_CHUNK_SIZE`; unmatched entries stay empty and are retried next round. |
+| A subagent dies / returns no file | That chunk's `out` is listed as missing; the next retry round re-dispatches only the still-empty entries. |
+| `lingui:extract` produces huge unrelated diff | Expected on this branch; `lingui:clean` strips the date/origin churn. Real content changes are legitimate. |
diff --git a/.ai/skills/translate/scripts/extract-missing.mjs b/.ai/skills/translate/scripts/extract-missing.mjs
new file mode 100644
index 0000000000..4500a4da3f
--- /dev/null
+++ b/.ai/skills/translate/scripts/extract-missing.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+// Step 1 of /translate. Scans every committed .po catalog for empty msgstr
+// entries and writes deterministic, chunked translation jobs for cheap-model
+// subagents to fill.
+//
+// Outputs (all under .ai/scratch/translate/, gitignored):
+// in/{n}.json one chunk of msgids to translate (subagent INPUT)
+// manifest.json list of {in,out,locale,catalog,langLabel,count}
+// (subagents write out/{n}.json — this script only creates in/ + manifest)
+//
+// Locale scope: supportedLanguages from packages/locale/src/config.ts, minus
+// the source locale "en". Orphaned locales on disk (e.g. nl) are excluded
+// because they're not in supportedLanguages.
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync } from "node:fs";
+import { parsePo, readLocaleConfig } from "./lib-po.mjs";
+
+const REPO = process.cwd();
+const CONFIG = `${REPO}/packages/locale/src/config.ts`;
+const LOCALES_DIR = `${REPO}/packages/locale/locales`;
+const OUT_DIR = `${REPO}/.ai/scratch/translate`;
+const CATALOGS = ["erp", "mes"];
+const CHUNK_SIZE = Number(process.env.TRANSLATE_CHUNK_SIZE || 40);
+
+const { codes, labels } = readLocaleConfig(CONFIG, readFileSync);
+const targets = codes.filter((c) => c !== "en");
+
+// Fresh scratch each run so stale chunks never merge.
+rmSync(OUT_DIR, { recursive: true, force: true });
+mkdirSync(`${OUT_DIR}/in`, { recursive: true });
+mkdirSync(`${OUT_DIR}/out`, { recursive: true });
+
+const manifest = [];
+let chunkNo = 0;
+let totalMissing = 0;
+
+for (const locale of targets) {
+ const langLabel = labels[locale] || locale;
+ for (const catalog of CATALOGS) {
+ const po = `${LOCALES_DIR}/${locale}/${catalog}.po`;
+ if (!existsSync(po)) continue;
+ const { entries } = parsePo(readFileSync(po, "utf8"));
+ const missing = entries.filter((e) => e.msgid !== "" && e.msgstr === "");
+ if (missing.length === 0) continue;
+ totalMissing += missing.length;
+ for (let i = 0; i < missing.length; i += CHUNK_SIZE) {
+ const slice = missing.slice(i, i + CHUNK_SIZE);
+ const inPath = `${OUT_DIR}/in/${chunkNo}.json`;
+ const outPath = `${OUT_DIR}/out/${chunkNo}.json`;
+ writeFileSync(
+ inPath,
+ JSON.stringify(
+ {
+ locale,
+ langLabel,
+ catalog,
+ items: slice.map((e) => ({
+ msgid: e.msgid,
+ // translator notes (#. lines) carry placeholder context
+ note: e.comments.filter((c) => c.startsWith("#.")).join(" ").trim() || undefined,
+ })),
+ },
+ null,
+ 2,
+ ),
+ );
+ manifest.push({ chunk: chunkNo, in: inPath, out: outPath, locale, catalog, langLabel, count: slice.length });
+ chunkNo++;
+ }
+ }
+}
+
+writeFileSync(`${OUT_DIR}/manifest.json`, JSON.stringify(manifest, null, 2));
+
+const byLocale = {};
+for (const m of manifest) byLocale[m.locale] = (byLocale[m.locale] || 0) + m.count;
+console.log(`Missing translations: ${totalMissing} across ${targets.length} locales`);
+console.log(`Chunks: ${manifest.length} (size ${CHUNK_SIZE}) → ${OUT_DIR}/manifest.json`);
+for (const [loc, n] of Object.entries(byLocale)) console.log(` ${loc}: ${n}`);
+if (totalMissing === 0) console.log("NOTHING_TO_TRANSLATE");
diff --git a/.ai/skills/translate/scripts/lib-po.mjs b/.ai/skills/translate/scripts/lib-po.mjs
new file mode 100644
index 0000000000..04f9b2a739
--- /dev/null
+++ b/.ai/skills/translate/scripts/lib-po.mjs
@@ -0,0 +1,70 @@
+// Shared .po parsing helpers for the /translate skill.
+// A .po entry is: optional comment lines (#...), a msgid (one or more quoted
+// lines), then a msgstr (one or more quoted lines). Values are the quoted
+// segments concatenated, with PO escape sequences decoded.
+
+const UNESCAPE = { '"': '"', "\\": "\\", n: "\n", t: "\t", r: "\r" };
+
+export function unescapePo(s) {
+ return s.replace(/\\(["\\ntr])/g, (_m, c) => UNESCAPE[c]);
+}
+
+export function escapePo(s) {
+ return s
+ .replace(/\\/g, "\\\\")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, "\\n")
+ .replace(/\t/g, "\\t")
+ .replace(/\r/g, "\\r");
+}
+
+function stripQuotes(q) {
+ const m = q.match(/^"([\s\S]*)"$/);
+ return m ? m[1] : "";
+}
+
+// Parse into { lines, entries }. Each entry: { comments[], msgid, msgstr,
+// msgstrLineIndex, msgstrLineCount }. Line indices point into `lines` so a
+// caller can rewrite a msgstr in place and re-join.
+export function parsePo(text) {
+ const lines = text.split("\n");
+ const entries = [];
+ let i = 0;
+ while (i < lines.length) {
+ const comments = [];
+ while (i < lines.length && lines[i].startsWith("#")) comments.push(lines[i++]);
+ if (i >= lines.length) break;
+ if (!lines[i].startsWith("msgid ")) {
+ i++;
+ continue;
+ }
+ const msgidQ = [lines[i].slice("msgid ".length)];
+ i++;
+ while (i < lines.length && lines[i].startsWith('"')) msgidQ.push(lines[i++]);
+ if (i >= lines.length || !lines[i].startsWith("msgstr ")) continue;
+ const msgstrLineIndex = i;
+ const msgstrQ = [lines[i].slice("msgstr ".length)];
+ i++;
+ while (i < lines.length && lines[i].startsWith('"')) msgstrQ.push(lines[i++]);
+ entries.push({
+ comments,
+ msgid: msgidQ.map((q) => unescapePo(stripQuotes(q))).join(""),
+ msgstr: msgstrQ.map((q) => unescapePo(stripQuotes(q))).join(""),
+ msgstrLineIndex,
+ msgstrLineCount: msgstrQ.length,
+ });
+ }
+ return { lines, entries };
+}
+
+// supportedLanguages + languageNativeLabels parsed straight from the source of
+// truth so the skill never drifts from the runtime locale list.
+export function readLocaleConfig(configPath, readFileSync) {
+ const src = readFileSync(configPath, "utf8");
+ const listMatch = src.match(/supportedLanguages\s*=\s*\[([\s\S]*?)\]/);
+ const codes = [...listMatch[1].matchAll(/"([a-z-]+)"/g)].map((m) => m[1]);
+ const labelBlock = src.match(/languageNativeLabels[^{]*\{([\s\S]*?)\}/)[1];
+ const labels = {};
+ for (const m of labelBlock.matchAll(/(\w+)\s*:\s*"([^"]+)"/g)) labels[m[1]] = m[2];
+ return { codes, labels };
+}
diff --git a/.ai/skills/translate/scripts/merge-translations.mjs b/.ai/skills/translate/scripts/merge-translations.mjs
new file mode 100644
index 0000000000..f5d95d8f90
--- /dev/null
+++ b/.ai/skills/translate/scripts/merge-translations.mjs
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+// Final step of /translate. Reads the chunk outputs produced by the cheap-model
+// subagents and writes each translation into the matching empty msgstr in the
+// .po files. Deterministic: no model in the write path, only exact msgid match,
+// and only empty msgstr are ever touched (existing translations are never
+// overwritten). Reports matched / unmatched / still-missing counts.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { escapePo, parsePo } from "./lib-po.mjs";
+
+const REPO = process.cwd();
+const OUT_DIR = `${REPO}/.ai/scratch/translate`;
+const LOCALES_DIR = `${REPO}/packages/locale/locales`;
+const MANIFEST = `${OUT_DIR}/manifest.json`;
+
+if (!existsSync(MANIFEST)) {
+ console.error(`No manifest at ${MANIFEST}. Run extract-missing.mjs first.`);
+ process.exit(1);
+}
+const manifest = JSON.parse(readFileSync(MANIFEST, "utf8"));
+
+// Merge all chunk outputs for a given (locale,catalog) against its .po once.
+const byPo = {};
+for (const m of manifest) {
+ const key = `${m.locale}/${m.catalog}`;
+ (byPo[key] ||= { locale: m.locale, catalog: m.catalog, outs: [] }).outs.push(m.out);
+}
+
+let matched = 0;
+let unmatched = 0;
+const missingChunks = [];
+
+for (const { locale, catalog, outs } of Object.values(byPo)) {
+ const translations = {};
+ for (const out of outs) {
+ if (!existsSync(out)) {
+ missingChunks.push(out);
+ continue;
+ }
+ try {
+ Object.assign(translations, JSON.parse(readFileSync(out, "utf8")));
+ } catch {
+ missingChunks.push(`${out} (invalid JSON)`);
+ }
+ }
+ if (Object.keys(translations).length === 0) continue;
+
+ const po = `${LOCALES_DIR}/${locale}/${catalog}.po`;
+ const { lines, entries } = parsePo(readFileSync(po, "utf8"));
+ const targeted = new Set();
+ for (const e of entries) {
+ if (e.msgid === "" || e.msgstr !== "") continue; // only fill empties
+ const t = translations[e.msgid];
+ if (t === undefined || t === "") continue;
+ if (e.msgstrLineCount !== 1) continue; // empty msgstr is always one line
+ lines[e.msgstrLineIndex] = `msgstr "${escapePo(t)}"`;
+ matched++;
+ targeted.add(e.msgid);
+ }
+ // Translations the model returned that matched no empty msgid.
+ for (const k of Object.keys(translations)) if (!targeted.has(k)) unmatched++;
+ writeFileSync(po, lines.join("\n"));
+}
+
+// Recount remaining empties across the targeted catalogs.
+let remaining = 0;
+for (const { locale, catalog } of Object.values(byPo)) {
+ const { entries } = parsePo(readFileSync(`${LOCALES_DIR}/${locale}/${catalog}.po`, "utf8"));
+ remaining += entries.filter((e) => e.msgid !== "" && e.msgstr === "").length;
+}
+
+console.log(`Merged: ${matched} filled, ${unmatched} unmatched (key mismatch)`);
+console.log(`Remaining empty msgstr in targeted catalogs: ${remaining}`);
+if (missingChunks.length) {
+ console.log(`Missing/invalid chunk outputs (${missingChunks.length}):`);
+ for (const c of missingChunks) console.log(` ${c}`);
+}
+if (remaining > 0) console.log("INCOMPLETE — re-run /translate to fill the rest");
diff --git a/.ai/skills/translate/scripts/progress.mjs b/.ai/skills/translate/scripts/progress.mjs
new file mode 100644
index 0000000000..2695ce08a8
--- /dev/null
+++ b/.ai/skills/translate/scripts/progress.mjs
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+// Live progress for /translate. Reads the manifest + the out/ chunk files that
+// Haiku subagents write as they finish, and reports how many chunks / strings
+// are done, overall and per locale.
+//
+// node progress.mjs one-shot snapshot (print after each batch)
+// node progress.mjs --watch tick every 10s until .done marker (background)
+//
+// Runs independently of the main agent loop, so --watch keeps ticking even while
+// the main loop is blocked awaiting a batch of subagents.
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+
+const REPO = process.cwd();
+const DIR = `${REPO}/.ai/scratch/translate`;
+const MANIFEST = `${DIR}/manifest.json`;
+const DONE_MARKER = `${DIR}/.done`;
+const watch = process.argv.includes("--watch");
+const INTERVAL_MS = Number(process.env.TRANSLATE_PROGRESS_INTERVAL || 10) * 1000;
+const MAX_MS = 45 * 60 * 1000; // safety stop
+
+function bar(frac, width = 24) {
+ const n = Math.max(0, Math.min(width, Math.round(frac * width)));
+ return `[${"#".repeat(n)}${"-".repeat(width - n)}]`;
+}
+
+function snapshot() {
+ if (!existsSync(MANIFEST)) return "[progress] waiting for manifest…";
+ let manifest;
+ try {
+ manifest = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ } catch {
+ return "[progress] manifest being rewritten…";
+ }
+ const outFiles = existsSync(`${DIR}/out`) ? new Set(readdirSync(`${DIR}/out`)) : new Set();
+ const exp = {};
+ const got = {};
+ let chunksDone = 0;
+ let strDone = 0;
+ let strExp = 0;
+ for (const m of manifest) {
+ exp[m.locale] = (exp[m.locale] || 0) + m.count;
+ got[m.locale] = got[m.locale] || 0;
+ strExp += m.count;
+ const fname = `${m.chunk}.json`;
+ if (outFiles.has(fname)) {
+ try {
+ const keys = Object.keys(JSON.parse(readFileSync(`${DIR}/out/${fname}`, "utf8"))).length;
+ chunksDone++;
+ strDone += keys;
+ got[m.locale] += keys;
+ } catch {
+ // half-written file this tick; counts next tick
+ }
+ }
+ }
+ const frac = strExp ? strDone / strExp : 1;
+ const perLocale = Object.keys(exp)
+ .map((l) => `${l} ${got[l]}/${exp[l]}`)
+ .join(" · ");
+ const ts = new Date().toISOString().slice(11, 19);
+ return (
+ `[progress ${ts}] ${bar(frac)} chunks ${chunksDone}/${manifest.length} · ` +
+ `strings ${strDone}/${strExp} (${Math.round(frac * 100)}%)\n ${perLocale}`
+ );
+}
+
+if (!watch) {
+ console.log(snapshot());
+} else {
+ const start = Date.now();
+ console.log(snapshot());
+ const timer = setInterval(() => {
+ if (existsSync(DONE_MARKER) || Date.now() - start > MAX_MS) {
+ console.log(snapshot());
+ console.log("[progress] done.");
+ clearInterval(timer);
+ return;
+ }
+ console.log(snapshot());
+ }, INTERVAL_MS);
+}