tokensafe 4.12.1 → 4.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,671 @@
1
+ """
2
+ Deterministic string-catalog audits: lint, coverage, show, apply.
3
+
4
+ The point of this module is to turn "read 18 files per locale and judge every
5
+ sentence" into "list the 40 keys that are actually wrong". Every check is
6
+ deterministic — no model, no network, no guessing — so the same input always
7
+ produces the same punch list and the cost of a review pass stops scaling with
8
+ the size of the catalog.
9
+
10
+ Writing back is byte-preserving: the parser records each string's character
11
+ span, and a patch is spliced into the original text from the end backwards.
12
+ Prettier wrapping, comments, key order and trailing commas survive untouched.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import difflib
18
+ import json
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass, field
23
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
24
+
25
+ from src.format_parsers.i18n_strings import (
26
+ CatalogEntry,
27
+ StringCatalogReducer,
28
+ locale_namespace_from_path,
29
+ placeholders,
30
+ try_parse,
31
+ )
32
+
33
+ CATALOG_EXTS = (".ts", ".js", ".mjs", ".cjs", ".cts", ".json")
34
+ CONFIG_NAMES = ("messages", "locales", "locale", "i18n", "lang", "langs", "translations")
35
+
36
+ # Brand terms that stay in Latin script in every locale.
37
+ GLOSSARY_TERMS = ("TokenSafe", "OUMV", "Sextant", "MCP", "OCC")
38
+
39
+ # English function words. Kept weak on purpose: a single hit never fires.
40
+ ENGLISH_STOPWORDS = frozenset({
41
+ "the", "and", "of", "to", "you", "your", "with", "for", "this", "that",
42
+ "from", "will", "not", "are", "was", "were", "have", "has", "can", "but",
43
+ "all", "more", "than", "when", "what", "how", "about", "into", "does",
44
+ "done", "run", "use", "it", "is", "be", "by", "on", "in", "at", "as",
45
+ })
46
+ STRONG_ENGLISH = frozenset({
47
+ "the", "and", "of", "to", "your", "you", "with", "this", "that", "from",
48
+ })
49
+
50
+ # Literal-translation smells, per locale. Advisory only.
51
+ CALQUE_PATTERNS: Dict[str, Tuple[str, ...]] = {
52
+ # Deliberately narrow: "данные" is data, "является" is the translationese tell.
53
+ "ru": (r"\bявляется\b", r"\bосуществля\w+", r"\bпроизводится\b", r"\bв целях\b"),
54
+ "uk": (r"\bздійсню\w+", r"\bв цілях\b"),
55
+ "de": (r"\bwerden\b.*\b(?:von|durch)\b", r"\bist es\b", r"\bes ist\b"),
56
+ "fr": (r"\bil est (?:important|nécessaire) de\b", r"\bse réalise\b"),
57
+ "es": (r"\bse realiza\b", r"\bes necesario\b", r"\bse está\b"),
58
+ "tr": (r"\bgerçekleştiril\w+", r"\bsöz konusu\b"),
59
+ "pl": (r"\bjest (?:to|wykonywane)\b", r"\bw celu\b"),
60
+ "pt": (r"\bé realizado\b", r"\bé necessário\b"),
61
+ "kk": (r"\bболып табылады\b", r"\bжүзеге асырыл\w+"),
62
+ "ja": (r"することができます", r"を行う"),
63
+ "ko": (r"수 있습니다", r"를 수행"),
64
+ }
65
+
66
+ # Length corridors against English; CJK legitimately runs shorter.
67
+ LENGTH_BOUNDS: Dict[str, Tuple[float, float]] = {
68
+ "ja": (0.25, 1.6), "ko": (0.25, 1.6), "kk": (0.5, 2.0),
69
+ }
70
+ DEFAULT_LENGTH_BOUNDS = (0.5, 2.0)
71
+
72
+ SEVERITY_ORDER = {"high": 0, "low": 1}
73
+ MAX_VALUE_PREVIEW = 240
74
+
75
+
76
+ @dataclass
77
+ class LocaleCatalog:
78
+ """All string leaves of one locale, plus the source text per file."""
79
+
80
+ messages_dir: str
81
+ locale: str
82
+ texts: Dict[str, str] = field(default_factory=dict) # relpath -> text
83
+ entries: Dict[str, CatalogEntry] = field(default_factory=dict) # path -> entry
84
+ owners: Dict[str, str] = field(default_factory=dict) # path -> relpath
85
+
86
+ @property
87
+ def relpaths(self) -> List[str]:
88
+ return sorted(self.texts)
89
+
90
+
91
+ def resolve_messages_dir(root: str) -> Optional[str]:
92
+ """Finds the message-catalog directory under a project root."""
93
+ root = os.path.abspath(root)
94
+ if os.path.basename(root) in CONFIG_NAMES and _looks_like_catalog_dir(root):
95
+ return root
96
+ candidates = [
97
+ os.path.join(root, "src", "i18n", "messages"),
98
+ os.path.join(root, "src", "i18n", "locales"),
99
+ os.path.join(root, "src", "messages"),
100
+ os.path.join(root, "src", "locales"),
101
+ os.path.join(root, "messages"),
102
+ os.path.join(root, "locales"),
103
+ os.path.join(root, "i18n", "messages"),
104
+ os.path.join(root, "app", "locales"),
105
+ os.path.join(root, "public", "locales"),
106
+ ]
107
+ for cand in candidates:
108
+ if _looks_like_catalog_dir(cand):
109
+ return cand
110
+ # Bounded walk: depth 3, at most 200 directories.
111
+ seen = 0
112
+ for dirpath, dirnames, _files in os.walk(root):
113
+ depth = dirpath[len(root):].count(os.sep)
114
+ if depth >= 3:
115
+ dirnames[:] = []
116
+ continue
117
+ for name in list(dirnames):
118
+ seen += 1
119
+ if seen > 200:
120
+ return None
121
+ if name in CONFIG_NAMES:
122
+ cand = os.path.join(dirpath, name)
123
+ if _looks_like_catalog_dir(cand):
124
+ return cand
125
+ return None
126
+
127
+
128
+ def _looks_like_catalog_dir(path: str) -> bool:
129
+ if not os.path.isdir(path):
130
+ return False
131
+ try:
132
+ with os.scandir(path) as entries:
133
+ subdirs = [d for d in entries if d.is_dir()]
134
+ except OSError:
135
+ return False
136
+ for sub in subdirs:
137
+ try:
138
+ with os.scandir(sub.path) as files:
139
+ for f in files:
140
+ if f.is_file() and f.name.lower().endswith(CATALOG_EXTS):
141
+ return True
142
+ except OSError:
143
+ continue
144
+ return False
145
+
146
+
147
+ def list_locales(messages_dir: str) -> List[str]:
148
+ try:
149
+ return sorted(
150
+ d.name for d in os.scandir(messages_dir)
151
+ if d.is_dir() and not d.name.startswith(".")
152
+ )
153
+ except OSError:
154
+ return []
155
+
156
+
157
+ _LOCALE_CACHE: "OrderedDict[Tuple[str, str, float], LocaleCatalog]" = OrderedDict()
158
+ _LOCALE_CACHE_MAX = 24
159
+
160
+
161
+ def load_locale(messages_dir: str, locale: str) -> LocaleCatalog:
162
+ """Parses every catalog file of a locale. Cached by directory mtime."""
163
+ messages_dir = os.path.abspath(messages_dir)
164
+ locale_dir = os.path.join(messages_dir, locale)
165
+ try:
166
+ mtime = os.path.getmtime(locale_dir)
167
+ except OSError:
168
+ mtime = 0.0
169
+ key = (messages_dir, locale, mtime)
170
+ cached = _LOCALE_CACHE.get(key)
171
+ if cached is not None:
172
+ _LOCALE_CACHE.move_to_end(key)
173
+ return cached
174
+
175
+ catalog = LocaleCatalog(messages_dir=messages_dir, locale=locale)
176
+ try:
177
+ names = sorted(os.scandir(locale_dir), key=lambda d: d.name)
178
+ except OSError:
179
+ names = []
180
+ for dirent in names:
181
+ if not dirent.is_file() or not dirent.name.lower().endswith(CATALOG_EXTS):
182
+ continue
183
+ try:
184
+ with open(dirent.path, "r", encoding="utf-8", errors="replace") as handle:
185
+ text = handle.read()
186
+ except OSError:
187
+ continue
188
+ relpath = os.path.relpath(dirent.path, messages_dir)
189
+ catalog.texts[relpath] = text
190
+ entries, error = try_parse(text)
191
+ if error:
192
+ continue
193
+ for entry in entries:
194
+ catalog.entries[entry.path] = entry
195
+ catalog.owners[entry.path] = relpath
196
+
197
+ _LOCALE_CACHE[key] = catalog
198
+ if len(_LOCALE_CACHE) > _LOCALE_CACHE_MAX:
199
+ _LOCALE_CACHE.popitem(last=False)
200
+ return catalog
201
+
202
+
203
+ def clear_cache() -> None:
204
+ _LOCALE_CACHE.clear()
205
+
206
+
207
+ # ---------------------------------------------------------------------------
208
+ # Heuristics
209
+ # ---------------------------------------------------------------------------
210
+
211
+ def _placeholder_only(value: str) -> bool:
212
+ stripped = re.sub(r"\{[^}]+\}", "", value)
213
+ return not stripped.strip(" \t.,:;!?()[]{}\"'`-–—·→✓%")
214
+
215
+
216
+ def _is_glossary_only(base: str) -> bool:
217
+ rest = base
218
+ for term in GLOSSARY_TERMS:
219
+ rest = rest.replace(term, " ")
220
+ return not re.search(r"[A-Za-z]{3,}", rest)
221
+
222
+
223
+ def _identical_code(base: str, target: str) -> bool:
224
+ if base.strip() != target.strip():
225
+ return False
226
+ if len(base.strip()) < 12:
227
+ return False
228
+ if _is_glossary_only(base) or _placeholder_only(base):
229
+ return False
230
+ if "@" in base:
231
+ return False
232
+ if not re.search(r"[A-Za-z]{3,}", base):
233
+ return False
234
+ return True
235
+
236
+
237
+ def _identical_severity(base: str) -> str:
238
+ """Brand names stay identical on purpose; untranslated prose does not.
239
+
240
+ A hit is `high` only when the base reads like a sentence — at least four
241
+ words and at least one English function word. "TokenSafe Community
242
+ Edition" or "Cursor Pro / Claude Pro / Windsurf" fall to `low`.
243
+ """
244
+ words = re.findall(r"[A-Za-z']+", base.lower())
245
+ if len(words) >= 4 and (set(words) & STRONG_ENGLISH):
246
+ return "high"
247
+ return "low"
248
+
249
+
250
+ def _glossary_severity(term: str) -> str:
251
+ return "high" if term in ("TokenSafe", "OUMV", "Sextant") else "low"
252
+
253
+
254
+ def _english_leak(target: str) -> bool:
255
+ words = re.findall(r"[A-Za-z']+", target.lower())
256
+ if len(target) < 30 or len(words) < 4:
257
+ return False
258
+ hits = {w for w in words if w in ENGLISH_STOPWORDS}
259
+ strong = hits & STRONG_ENGLISH
260
+ return len(hits) >= 3 and bool(strong)
261
+
262
+
263
+ def _glossary_lost(base: str, target: str) -> Optional[str]:
264
+ for term in GLOSSARY_TERMS:
265
+ if term in base and term not in target:
266
+ return term
267
+ return None
268
+
269
+
270
+ def _length_outlier(locale: str, base: str, target: str) -> bool:
271
+ if len(base) < 25 or len(target) < 3:
272
+ return False
273
+ lo, hi = LENGTH_BOUNDS.get(locale, DEFAULT_LENGTH_BOUNDS)
274
+ ratio = len(target) / max(1, len(base))
275
+ return ratio < lo or ratio > hi
276
+
277
+
278
+ def _calque(locale: str, target: str) -> Optional[str]:
279
+ for pattern in CALQUE_PATTERNS.get(locale, ()):
280
+ m = re.search(pattern, target, re.IGNORECASE)
281
+ if m:
282
+ return m.group(0)
283
+ return None
284
+
285
+
286
+ def lint(
287
+ messages_dir: str,
288
+ locale: str,
289
+ base_locale: str = "en",
290
+ severity: str = "all",
291
+ limit: int = 0,
292
+ ) -> Dict[str, Any]:
293
+ """Compares one locale against the base and returns the suspect list."""
294
+ target = load_locale(messages_dir, locale)
295
+ base = load_locale(messages_dir, base_locale)
296
+ if locale == base_locale:
297
+ return {
298
+ "locale": locale, "base": base_locale, "messages_dir": messages_dir,
299
+ "stats": {"target_keys": len(target.entries), "suspects": 0, "by_reason": {}},
300
+ "suspects": [], "note": "target equals base locale",
301
+ }
302
+
303
+ suspects: List[Dict[str, Any]] = []
304
+ by_reason: Dict[str, int] = {}
305
+ duplicate_seen: Dict[str, str] = {}
306
+
307
+ for path in sorted(base.entries):
308
+ base_value = base.entries[path].value
309
+ entry = target.entries.get(path)
310
+ if entry is None:
311
+ reasons = []
312
+ if locale == base_locale:
313
+ continue
314
+ by_reason["missing"] = by_reason.get("missing", 0) + 1
315
+ suspects.append({
316
+ "path": path, "reasons": ["missing"], "severity": "high",
317
+ "base": base_value, "target": None,
318
+ })
319
+ continue
320
+
321
+ value = entry.value
322
+ reasons: List[str] = []
323
+ if _identical_code(base_value, value):
324
+ reasons.append("identical")
325
+ if placeholders(base_value) != placeholders(value):
326
+ reasons.append("placeholder_mismatch")
327
+ if _english_leak(value):
328
+ reasons.append("contains_english")
329
+ term = _glossary_lost(base_value, value)
330
+ if term:
331
+ reasons.append(f"glossary:{term}")
332
+ if _length_outlier(locale, base_value, value):
333
+ reasons.append("length_ratio")
334
+ calque = _calque(locale, value)
335
+ if calque:
336
+ reasons.append(f"calque:{calque}")
337
+ if len(value) >= 20 and " " in value:
338
+ first = duplicate_seen.get(value)
339
+ if first and first != path:
340
+ reasons.append(f"duplicate:{first}")
341
+ else:
342
+ duplicate_seen[value] = path
343
+
344
+ if not reasons:
345
+ continue
346
+ high = "placeholder_mismatch" in reasons or "contains_english" in reasons
347
+ if "identical" in reasons and _identical_severity(base_value) == "high":
348
+ high = True
349
+ for reason in reasons:
350
+ if reason.startswith("glossary:") and _glossary_severity(reason.split(":", 1)[1]) == "high":
351
+ high = True
352
+ for reason in reasons:
353
+ key = reason.split(":", 1)[0]
354
+ by_reason[key] = by_reason.get(key, 0) + 1
355
+ suspects.append({
356
+ "path": path, "reasons": reasons, "severity": "high" if high else "low",
357
+ "base": base_value, "target": value,
358
+ })
359
+
360
+ for path in sorted(set(target.entries) - set(base.entries)):
361
+ by_reason["orphan"] = by_reason.get("orphan", 0) + 1
362
+ suspects.append({
363
+ "path": path, "reasons": ["orphan"], "severity": "high",
364
+ "base": None, "target": target.entries[path].value,
365
+ })
366
+
367
+ total_all = len(suspects)
368
+ if severity == "high":
369
+ suspects = [s for s in suspects if s["severity"] == "high"]
370
+ suspects.sort(key=lambda s: (SEVERITY_ORDER.get(s["severity"], 9), s["path"]))
371
+ if limit and limit > 0:
372
+ suspects = suspects[:limit]
373
+
374
+ return {
375
+ "locale": locale,
376
+ "base": base_locale,
377
+ "messages_dir": messages_dir,
378
+ "stats": {
379
+ "base_keys": len(base.entries),
380
+ "target_keys": len(target.entries),
381
+ "missing": by_reason.get("missing", 0),
382
+ "orphan": by_reason.get("orphan", 0),
383
+ "total_suspects": total_all,
384
+ "suspects": len(suspects),
385
+ "by_reason": dict(sorted(by_reason.items(), key=lambda kv: -kv[1])),
386
+ },
387
+ "suspects": suspects,
388
+ }
389
+
390
+
391
+ def coverage(messages_dir: str, base_locale: str = "en") -> Dict[str, Any]:
392
+ """Per-locale key coverage without the per-key suspect list."""
393
+ base = load_locale(messages_dir, base_locale)
394
+ locales: List[Dict[str, Any]] = []
395
+ for locale in list_locales(messages_dir):
396
+ catalog = load_locale(messages_dir, locale)
397
+ if locale == base_locale:
398
+ locales.append({
399
+ "locale": locale,
400
+ "files": len(catalog.texts),
401
+ "keys": len(catalog.entries),
402
+ "missing": 0,
403
+ "orphan": 0,
404
+ "identical_to_base": 0,
405
+ "placeholder_mismatch": 0,
406
+ "untranslated_pct": 0.0,
407
+ })
408
+ continue
409
+ identical = sum(
410
+ 1 for path, entry in catalog.entries.items()
411
+ if path in base.entries and _identical_code(base.entries[path].value, entry.value)
412
+ )
413
+ placeholder_bad = sum(
414
+ 1 for path, entry in catalog.entries.items()
415
+ if path in base.entries
416
+ and placeholders(base.entries[path].value) != placeholders(entry.value)
417
+ )
418
+ locales.append({
419
+ "locale": locale,
420
+ "files": len(catalog.texts),
421
+ "keys": len(catalog.entries),
422
+ "missing": len(set(base.entries) - set(catalog.entries)),
423
+ "orphan": len(set(catalog.entries) - set(base.entries)),
424
+ "identical_to_base": identical,
425
+ "placeholder_mismatch": placeholder_bad,
426
+ "untranslated_pct": round(100.0 * identical / max(1, len(catalog.entries)), 2),
427
+ })
428
+ return {
429
+ "messages_dir": messages_dir,
430
+ "base": base_locale,
431
+ "base_keys": len(base.entries),
432
+ "locales": locales,
433
+ }
434
+
435
+
436
+ def show(messages_dir: str, locale: str, paths: Sequence[str]) -> Dict[str, Any]:
437
+ """Exact values for the requested paths (prefix match expands)."""
438
+ catalog = load_locale(messages_dir, locale)
439
+ out: Dict[str, Any] = {}
440
+ for wanted in paths:
441
+ if wanted in catalog.entries:
442
+ out[wanted] = catalog.entries[wanted].value
443
+ continue
444
+ prefix = wanted.rstrip(".")
445
+ matches = {
446
+ path: entry.value for path, entry in catalog.entries.items()
447
+ if path == prefix or path.startswith(prefix + ".") or path.startswith(prefix + "[")
448
+ }
449
+ if matches:
450
+ out[wanted] = matches
451
+ else:
452
+ out[wanted] = None
453
+ return {"locale": locale, "values": out}
454
+
455
+
456
+ # ---------------------------------------------------------------------------
457
+ # Write-back
458
+ # ---------------------------------------------------------------------------
459
+
460
+ def _quote_and_escape(value: str, preferred: str = "'") -> Tuple[str, str]:
461
+ """Returns (literal_with_quotes, quote_char) preserving the original style."""
462
+ quote = preferred if preferred in ("'", '"') else "'"
463
+ if quote == "'" and "'" in value and '"' not in value:
464
+ quote = '"'
465
+ escaped = value.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
466
+ if quote == "'":
467
+ escaped = escaped.replace("'", "\\'")
468
+ else:
469
+ escaped = escaped.replace('"', '\\"')
470
+ return f"{quote}{escaped}{quote}", quote
471
+
472
+
473
+ def _splice(text: str, replacements: List[Tuple[int, int, str]]) -> str:
474
+ """Applies (start, end, literal) replacements from the end backwards."""
475
+ out = text
476
+ for start, end, literal in sorted(replacements, key=lambda r: r[0], reverse=True):
477
+ out = out[:start] + literal + out[end:]
478
+ return out
479
+
480
+
481
+ def apply(
482
+ messages_dir: str,
483
+ locale: str,
484
+ patch: Dict[str, str],
485
+ base_locale: str = "en",
486
+ dry_run: bool = False,
487
+ ) -> Dict[str, Any]:
488
+ """Writes `{path: new_value}` into the locale, byte-preserving elsewhere."""
489
+ catalog = load_locale(messages_dir, locale)
490
+ base = load_locale(messages_dir, base_locale) if locale != base_locale else catalog
491
+ refused: Dict[str, str] = {}
492
+ per_file: Dict[str, List[Tuple[int, int, str]]] = {}
493
+ changed: List[Dict[str, Any]] = []
494
+
495
+ for path, new_value in patch.items():
496
+ if not isinstance(new_value, str):
497
+ refused[path] = "value is not a string"
498
+ continue
499
+ entry = catalog.entries.get(path)
500
+ if entry is None:
501
+ refused[path] = "path not found in locale"
502
+ continue
503
+ base_entry = base.entries.get(path)
504
+ if base_entry is not None and placeholders(base_entry.value) != placeholders(new_value):
505
+ refused[path] = (
506
+ f"placeholder mismatch: base={placeholders(base_entry.value)} "
507
+ f"new={placeholders(new_value)}"
508
+ )
509
+ continue
510
+ relpath = catalog.owners.get(path)
511
+ if not relpath:
512
+ refused[path] = "file not resolved"
513
+ continue
514
+ literal, _quote = _quote_and_escape(new_value, entry.quote)
515
+ per_file.setdefault(relpath, []).append((entry.value_start, entry.value_end, literal))
516
+ changed.append({
517
+ "path": path, "file": relpath,
518
+ "before": entry.value, "after": new_value,
519
+ })
520
+
521
+ diffs: List[str] = []
522
+ written: List[str] = []
523
+ for relpath, replacements in sorted(per_file.items()):
524
+ text = catalog.texts[relpath]
525
+ new_text = _splice(text, replacements)
526
+ entries_after, error = try_parse(new_text)
527
+ if error:
528
+ for path, _old in ((c["path"], c["before"]) for c in changed if c["file"] == relpath):
529
+ refused[path] = f"refused: post-write parse failed ({error})"
530
+ changed = [c for c in changed if c["file"] != relpath]
531
+ continue
532
+ after_map = {e.path: e.value for e in entries_after}
533
+ broken = [
534
+ c["path"] for c in changed
535
+ if c["file"] == relpath and after_map.get(c["path"]) != c["after"]
536
+ ]
537
+ if broken:
538
+ for path in broken:
539
+ refused[path] = "refused: value did not round-trip"
540
+ changed = [c for c in changed if not (c["file"] == relpath and c["path"] in broken)]
541
+ continue
542
+ diff = list(difflib.unified_diff(
543
+ text.splitlines(), new_text.splitlines(),
544
+ fromfile=relpath, tofile=relpath, lineterm="", n=1,
545
+ ))
546
+ diffs.extend(diff)
547
+ if not dry_run:
548
+ abspath = os.path.join(catalog.messages_dir, relpath)
549
+ tmp = abspath + ".tokensafe.tmp"
550
+ with open(tmp, "w", encoding="utf-8") as handle:
551
+ handle.write(new_text)
552
+ os.replace(tmp, abspath)
553
+ written.append(relpath)
554
+
555
+ if not dry_run and written:
556
+ clear_cache()
557
+
558
+ return {
559
+ "locale": locale,
560
+ "dry_run": dry_run,
561
+ "changed": changed,
562
+ "refused": refused,
563
+ "written_files": written,
564
+ "diff": "\n".join(diffs),
565
+ }
566
+
567
+
568
+ # ---------------------------------------------------------------------------
569
+ # Rendering
570
+ # ---------------------------------------------------------------------------
571
+
572
+ def _clip(value: Optional[str]) -> str:
573
+ if value is None:
574
+ return "—"
575
+ flat = value.replace("\n", "\\n")
576
+ return flat if len(flat) <= MAX_VALUE_PREVIEW else flat[:MAX_VALUE_PREVIEW] + "…"
577
+
578
+
579
+ def render_lint(result: Dict[str, Any], show_values: bool = True) -> str:
580
+ stats = result.get("stats") or {}
581
+ total = stats.get("total_suspects", stats.get("suspects", 0))
582
+ shown = stats.get("suspects", 0)
583
+ count_label = f"{shown} of {total} suspects" if shown != total else f"{shown} suspects"
584
+ lines = [
585
+ f"# [TokenSafe Catalog Lint: {result.get('locale')} vs {result.get('base')} | "
586
+ f"{stats.get('target_keys', 0)} keys | {count_label}]"
587
+ ]
588
+ reasons = stats.get("by_reason") or {}
589
+ if reasons:
590
+ lines.append("# " + " · ".join(f"{k}={v}" for k, v in reasons.items()))
591
+ if not result.get("suspects"):
592
+ lines.append("# nothing to fix")
593
+ return "\n".join(lines)
594
+ for item in result["suspects"]:
595
+ lines.append(f"{item['severity'][0].upper()} {item['path']} [{' '.join(item['reasons'])}]")
596
+ if show_values:
597
+ if item.get("base") is not None:
598
+ lines.append(f" en: {_clip(item['base'])}")
599
+ lines.append(f" {result.get('locale')}: {_clip(item.get('target'))}")
600
+ return "\n".join(lines)
601
+
602
+
603
+ def render_coverage(result: Dict[str, Any]) -> str:
604
+ lines = [
605
+ f"# [TokenSafe Catalog Coverage: {result.get('messages_dir')} | "
606
+ f"base={result.get('base')} | {result.get('base_keys')} keys]",
607
+ "locale files keys missing orphan identical placeholder_bad pct",
608
+ ]
609
+ for row in result.get("locales") or []:
610
+ lines.append(
611
+ f"{row['locale']:<6} {row['files']:>5} {row['keys']:>5} {row['missing']:>7} "
612
+ f"{row['orphan']:>6} {row['identical_to_base']:>9} {row['placeholder_mismatch']:>13} "
613
+ f"{row['untranslated_pct']:>5}"
614
+ )
615
+ return "\n".join(lines)
616
+
617
+
618
+ def render_apply(result: Dict[str, Any]) -> str:
619
+ changed = result.get("changed") or []
620
+ head = (
621
+ f"# [TokenSafe Catalog Apply: {result.get('locale')} | "
622
+ f"{'dry-run' if result.get('dry_run') else 'written'} | {len(changed)} keys]"
623
+ )
624
+ parts = [head]
625
+ for item in changed:
626
+ parts.append(f"{item['path']}: {_clip(item['before'])} -> {_clip(item['after'])}")
627
+ for path, reason in (result.get("refused") or {}).items():
628
+ parts.append(f"REFUSED {path}: {reason}")
629
+ if result.get("diff"):
630
+ parts.append("")
631
+ parts.append(result["diff"])
632
+ return "\n".join(parts)
633
+
634
+
635
+ def run_command(messages_dir: str, command: str, flags: Dict[str, str]) -> Tuple[str, Dict[str, Any]]:
636
+ """CLI/MCP shared entry: `lint|coverage|show|apply` + flags -> (text, payload)."""
637
+ locale = flags.get("locale") or flags.get("l") or ""
638
+ base = flags.get("base") or "en"
639
+ if command == "lint":
640
+ if not locale:
641
+ raise ValueError("lint requires --locale")
642
+ payload = lint(messages_dir, locale, base,
643
+ severity=flags.get("severity", "all"),
644
+ limit=int(flags.get("limit", "0") or 0))
645
+ return render_lint(payload), payload
646
+ if command == "coverage":
647
+ payload = coverage(messages_dir, base)
648
+ return render_coverage(payload), payload
649
+ if command == "show":
650
+ if not locale:
651
+ raise ValueError("show requires --locale")
652
+ paths = [p for p in re.split(r"[,\s]+", flags.get("keys", "")) if p]
653
+ if not paths:
654
+ raise ValueError("show requires --keys <path[,path]>")
655
+ payload = show(messages_dir, locale, paths)
656
+ return json.dumps(payload, indent=2, ensure_ascii=False), payload
657
+ if command == "apply":
658
+ if not locale:
659
+ raise ValueError("apply requires --locale")
660
+ patch_raw = flags.get("patch") or ""
661
+ if patch_raw.startswith("@"):
662
+ with open(patch_raw[1:], "r", encoding="utf-8") as handle:
663
+ patch = json.load(handle)
664
+ else:
665
+ patch = json.loads(patch_raw or "{}")
666
+ if not isinstance(patch, dict) or not patch:
667
+ raise ValueError("apply requires a JSON object of {path: value} via --patch")
668
+ payload = apply(messages_dir, locale, patch, base,
669
+ dry_run=str(flags.get("dry_run", "")).lower() in ("1", "true", "yes"))
670
+ return render_apply(payload), payload
671
+ raise ValueError(f"unknown dict command: {command}")
package/src/installer.py CHANGED
@@ -64,6 +64,7 @@ UNIFIED_TOKENSAFE_RULE = (
64
64
  "ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
65
65
  "static OUMV works offline on read/edit tasks too, and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
66
66
  "In mixed monorepos (e.g. React + Node.js), use `oumv` on supported profiles and `repo_map`/`smart_read_file`/`scoped_search` on unsupported stacks (e.g. `backend/node`).\n"
67
+ "13. **String Catalogs (`dict`)**: NEVER read a whole i18n catalog (`messages/<locale>/*.ts`, `locales/*.json`) to review or edit translations. A catalog is 100% payload, so reading 18 files per locale is the most expensive way to work, and fanning out one subagent per locale that each re-reads the English oracle multiplies it. Start with `tokensafe:run_helper(action='dict', command='lint --locale <l> --base en --json')` (CLI: `tokensafe dict lint --locale <l>`), which returns only suspect keys: untranslated, missing, orphan, placeholder drift, English leakage, brand loss. Patch with `dict apply --locale <l> --patch patch.json`, after `--dry-run`: it writes byte-preserving edits. `smart_read_file` on a catalog returns a digest on purpose; `dict show --keys a.b` returns exact values.\n"
67
68
  )
68
69
 
69
70
  # Short pointer written into PROJECT-level rule files when the full protocol is
@@ -77,7 +78,8 @@ POINTER_RULE = (
77
78
  "`tokensafe:scoped_search` (single or `queries` batch, never raw grep/find), `tokensafe:smart_read_file` (symbol, `targets` bundle, or `.d.ts` `package_name`), "
78
79
  "`tokensafe:apply_edits` for multi-file edits, `tokensafe:oumv` (MANDATORY first on OUMV-supported React/Vue/Go/FastAPI stacks — live or static offline; check `status` in mixed monorepos), "
79
80
  "`tokensafe:session_context(action='budget'|'compact'|'prune'|'mistakes')` for context & anti-stuck hygiene, and "
80
- "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress')`; "
81
+ "`tokensafe:run_helper(action='sanitize'|'guard'|'diff'|'deps'|'web'|'expand'|'image'|'compress'|'dict')` "
82
+ "(string catalogs: `dict lint --locale <l>`, then `dict apply`, never read whole catalogs); "
81
83
  "never hardcode secret fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
82
84
  )
83
85