dsh-desktop-kit 2.24.0 → 2.30.0
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.
- package/CHANGELOG.md +74 -6
- package/README.md +192 -291
- package/client.js +1 -1
- package/cordis.patch.yml +5 -151
- package/docs/ARCHITECTURE.md +10 -16
- package/docs/COMPATIBILITY.md +1 -1
- package/docs/DEVELOPMENT.md +0 -1
- package/docs/PROPOSAL-2.25-quality-pipeline.md +435 -0
- package/docs/PROPOSAL-NEXUM-FINDINGS.md +259 -0
- package/docs/TEST-2.24.1.md +66 -0
- package/docs/TEST-2.30.0.md +83 -0
- package/docs/images/capability-map-2.30.png +0 -0
- package/docs/images/hero-2.30.png +0 -0
- package/docs/images/quality-pipeline-2.30.png +0 -0
- package/docs/preview/capability-map-2.30.html +106 -0
- package/docs/preview/hero-2.30.html +133 -0
- package/docs/preview/quality-pipeline-2.30.html +142 -0
- package/docs/preview/readme-visuals.css +111 -0
- package/index.js +6 -0
- package/package.json +11 -4
- package/plugins/dsh-agent-extensions/lib/routing.js +4 -0
- package/plugins/dsh-agent-extensions/lib/scaffold.js +152 -27
- package/plugins/dsh-agent-extensions/lib/settings.js +19 -0
- package/plugins/dsh-agent-extensions/lib/swarm.js +6 -2
- package/plugins/dsh-browser-qa/index.js +202 -9
- package/plugins/dsh-browser-qa/lib/design-more.js +688 -0
- package/plugins/dsh-browser-qa/lib/extras.js +1313 -0
- package/plugins/dsh-browser-qa/lib/pages.js +4 -3
- package/plugins/dsh-browser-qa/lib/png.js +190 -0
- package/plugins/dsh-browser-qa/lib/ui-gate.js +171 -31
- package/plugins/dsh-i18n/README.md +36 -0
- package/plugins/dsh-i18n/cordis.patch.yml +3 -0
- package/plugins/dsh-i18n/index.js +294 -0
- package/plugins/dsh-i18n/lib/lang.js +179 -0
- package/plugins/dsh-i18n/package.json +29 -0
- package/plugins/dsh-quality-pipeline/README.md +53 -0
- package/plugins/dsh-quality-pipeline/cordis.patch.yml +3 -0
- package/plugins/dsh-quality-pipeline/index.js +647 -0
- package/plugins/dsh-quality-pipeline/lib/acceptance.js +132 -0
- package/plugins/dsh-quality-pipeline/lib/autostart.js +159 -0
- package/plugins/dsh-quality-pipeline/lib/design.js +123 -0
- package/plugins/dsh-quality-pipeline/lib/machine.js +312 -0
- package/plugins/dsh-quality-pipeline/lib/prework.js +215 -0
- package/plugins/dsh-quality-pipeline/lib/release.js +53 -0
- package/plugins/dsh-quality-pipeline/lib/schema.js +256 -0
- package/plugins/dsh-quality-pipeline/lib/store.js +114 -0
- package/plugins/dsh-quality-pipeline/lib/text.js +109 -0
- package/plugins/dsh-quality-pipeline/package.json +33 -0
- package/plugins/dsh-remote-ops/README.md +38 -0
- package/plugins/dsh-remote-ops/cordis.patch.yml +3 -0
- package/plugins/dsh-remote-ops/index.js +268 -0
- package/plugins/dsh-remote-ops/lib/hosts.js +118 -0
- package/plugins/dsh-remote-ops/lib/ssh.js +96 -0
- package/plugins/dsh-remote-ops/lib/state.js +66 -0
- package/plugins/dsh-remote-ops/package.json +31 -0
- package/plugins/dsh-skill-autopilot/index.js +204 -15
- package/skills/a11y-audit/SKILL.md +67 -0
- package/skills/cms-ops/SKILL.md +74 -0
- package/skills/design-system/SKILL.md +100 -0
- package/skills/legal-ru-web/SKILL.md +68 -0
- package/skills/manifest.json +38 -18
- package/skills/release-pipeline/SKILL.md +67 -0
- package/skills/ui-batch/SKILL.md +60 -0
- package/skills/web-build/SKILL.md +106 -0
- package/skills/web-build/recipes/form.md +16 -0
- package/skills/web-build/recipes/payment.md +16 -0
- package/skills/web-build/recipes/review.md +16 -0
- package/skills-baseline.json +192 -0
- package/docs/TEST-2.24.0.md +0 -123
- package/skills/ui-design-system/references/accessibility-and-responsive.md +0 -50
- package/skills/ui-design-system/references/tokens-and-components.md +0 -67
- package/skills/ui-design-system/references/visual-qa.md +0 -44
- package/skills/visual-qa/references/commands.md +0 -32
- /package/skills/{ui-craft/SKILL.md → design-system/references/ui-craft.md} +0 -0
- /package/skills/{ui-design-system/SKILL.md → design-system/references/ui-design-system.md} +0 -0
- /package/skills/{visual-qa/SKILL.md → ui-batch/references/visual-qa.md} +0 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-i18n — localization as a process, not as 53 chats.
|
|
3
|
+
*
|
|
4
|
+
* Audits a Laravel-style dictionary (`lang/<locale>/*.php|json`), finds keys
|
|
5
|
+
* used in code but missing in dictionaries, prepares translation batches and
|
|
6
|
+
* writes validated translations back (with a `.bak` copy).
|
|
7
|
+
*/
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
applyTranslations,
|
|
13
|
+
diffDictionary,
|
|
14
|
+
flattenDictionary,
|
|
15
|
+
formatDiffRows,
|
|
16
|
+
parsePhpLang,
|
|
17
|
+
placeholdersOf,
|
|
18
|
+
readDictionary,
|
|
19
|
+
samePlaceholders,
|
|
20
|
+
usedKeys,
|
|
21
|
+
} from "./lib/lang.js";
|
|
22
|
+
|
|
23
|
+
export const inject = ["tools"];
|
|
24
|
+
|
|
25
|
+
const TOOL_NAME = "i18n_sync";
|
|
26
|
+
const ACTIONS = ["coverage", "diff", "plan", "apply", "check"];
|
|
27
|
+
const BATCH_DEFAULT = 120;
|
|
28
|
+
|
|
29
|
+
function sessionCwd(exec) {
|
|
30
|
+
const cwd = exec?.agent?.session?.header?.cwd;
|
|
31
|
+
return typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function appendEvidence(cwd, record) {
|
|
35
|
+
try {
|
|
36
|
+
const dir = path.join(cwd, ".dsh", "quality");
|
|
37
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
38
|
+
fs.appendFileSync(
|
|
39
|
+
path.join(dir, "evidence.jsonl"),
|
|
40
|
+
`${JSON.stringify({ at: new Date().toISOString(), kind: record.kind, gate: record.gate ?? "", value: record.value, note: String(record.note ?? "").slice(0, 600) })}\n`,
|
|
41
|
+
"utf8",
|
|
42
|
+
);
|
|
43
|
+
} catch {
|
|
44
|
+
/* evidence is best effort */
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const fail = (text) => ({ ok: false, text });
|
|
49
|
+
|
|
50
|
+
function localeDir(cwd, locale) {
|
|
51
|
+
const value = String(locale ?? "").trim();
|
|
52
|
+
if (!value) return null;
|
|
53
|
+
return path.isAbsolute(value) ? value : path.join(cwd, "lang", value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function baseOf(args) {
|
|
57
|
+
return String(args?.base ?? "ru").trim();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function extrasOf(args) {
|
|
61
|
+
return String(args?.extra ?? args?.langs ?? "")
|
|
62
|
+
.split(",")
|
|
63
|
+
.map((item) => item.trim())
|
|
64
|
+
.filter(Boolean);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Keys present in code but absent from the base dictionary, and orphans. */
|
|
68
|
+
function coverage(cwd, args) {
|
|
69
|
+
const baseDir = localeDir(cwd, baseOf(args));
|
|
70
|
+
if (!baseDir || !fs.existsSync(baseDir)) return fail(`нет каталога словаря: ${baseDir ?? "(base не задан)"}`);
|
|
71
|
+
const base = readDictionary(baseDir);
|
|
72
|
+
const flat = flattenDictionary(base);
|
|
73
|
+
const used = usedKeys(cwd, { dirs: String(args?.dirs ?? "").split(",").map((item) => item.trim()).filter(Boolean).length > 0 ? String(args.dirs).split(",").map((item) => item.trim()) : undefined });
|
|
74
|
+
const missing = [...used.keys()].filter((key) => !flat.has(key));
|
|
75
|
+
const known = new Set([...used.keys()]);
|
|
76
|
+
const unused = [...flat.keys()].filter((key) => !known.has(key));
|
|
77
|
+
const lines = [
|
|
78
|
+
`i18n coverage · базовый ${baseOf(args)} · файлов ${base.size} · ключей ${flat.size}`,
|
|
79
|
+
`используется в коде ${used.size} · отсутствует в словаре ${missing.length} · не используется ${unused.length}`,
|
|
80
|
+
];
|
|
81
|
+
for (const key of missing.slice(0, 20)) lines.push(` missing-in-dict ${key} (${used.get(key)} вызовов)`);
|
|
82
|
+
for (const key of unused.slice(0, 10)) lines.push(` unused ${key}`);
|
|
83
|
+
lines.push(missing.length === 0 ? "Итог: PASS — все ключи из кода есть в словаре" : "Итог: FAIL — часть строк живёт мимо словаря");
|
|
84
|
+
return { ok: missing.length === 0, missing: missing.length, unused: unused.length, text: lines.join("\n") };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function diff(cwd, args) {
|
|
88
|
+
const baseDir = localeDir(cwd, baseOf(args));
|
|
89
|
+
if (!baseDir || !fs.existsSync(baseDir)) return fail(`нет каталога словаря: ${baseDir ?? "(base не задан)"}`);
|
|
90
|
+
const extras = extrasOf(args);
|
|
91
|
+
if (extras.length === 0) return fail("нужно extra=en,zh-CN,ar (или langs=…)");
|
|
92
|
+
const base = readDictionary(baseDir);
|
|
93
|
+
const lines = [];
|
|
94
|
+
let failures = 0;
|
|
95
|
+
for (const locale of extras) {
|
|
96
|
+
const dir = localeDir(cwd, locale);
|
|
97
|
+
if (!dir || !fs.existsSync(dir)) {
|
|
98
|
+
lines.push(`${locale}: каталог не найден (${dir})`);
|
|
99
|
+
failures += 1;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const rows = diffDictionary(base, readDictionary(dir));
|
|
103
|
+
failures += rows.placeholders.length;
|
|
104
|
+
lines.push(formatDiffRows(locale, rows));
|
|
105
|
+
}
|
|
106
|
+
lines.push(failures === 0 ? "Итог: PASS — расхождений по плейсхолдерам нет" : "Итог: FAIL — есть плейсхолдеры, которые поедут в перевод");
|
|
107
|
+
return { ok: failures === 0, text: lines.join("\n") };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function plan(cwd, args) {
|
|
111
|
+
const baseDir = localeDir(cwd, baseOf(args));
|
|
112
|
+
const lang = String(args?.lang ?? "").trim();
|
|
113
|
+
if (!baseDir || !fs.existsSync(baseDir)) return fail(`нет каталога словаря: ${baseDir ?? "(base не задан)"}`);
|
|
114
|
+
if (!lang) return fail("нужен lang=en (язык, который переводим)");
|
|
115
|
+
const dir = localeDir(cwd, lang);
|
|
116
|
+
if (!dir) return fail("не удалось разобрать lang");
|
|
117
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
118
|
+
const base = readDictionary(baseDir);
|
|
119
|
+
const rows = diffDictionary(base, readDictionary(dir));
|
|
120
|
+
const pending = rows.missing.filter((item) => item.reason !== "empty");
|
|
121
|
+
const batchSize = Math.max(10, Math.min(300, Number(args?.batchSize) || BATCH_DEFAULT));
|
|
122
|
+
const batches = [];
|
|
123
|
+
for (let index = 0; index < pending.length; index += batchSize) batches.push(pending.slice(index, index + batchSize));
|
|
124
|
+
const wanted = Number(args?.batch);
|
|
125
|
+
if (!Number.isFinite(wanted)) {
|
|
126
|
+
const lines = [
|
|
127
|
+
`i18n plan · ${baseOf(args)} → ${lang}: к переводу ${pending.length} ключей, порций ${batches.length} по ${batchSize}`,
|
|
128
|
+
...batches.map((batch, index) => ` batch ${index + 1}: ${batch.length} ключей, с ${batch[0].key}`),
|
|
129
|
+
"Следующий шаг: action=plan lang=" + lang + " batch=1 — получите JSON для перевода.",
|
|
130
|
+
];
|
|
131
|
+
return { ok: true, batches: batches.length, pending: pending.length, text: lines.join("\n") };
|
|
132
|
+
}
|
|
133
|
+
const batch = batches[Math.max(0, Math.min(batches.length - 1, Math.floor(wanted) - 1))] ?? [];
|
|
134
|
+
if (batch.length === 0) return { ok: true, text: `i18n plan: порция ${wanted} пуста — переводить нечего.` };
|
|
135
|
+
const payload = Object.fromEntries(batch.map((item) => [item.key, item.value]));
|
|
136
|
+
const file = path.join(cwd, ".dsh", `i18n-${lang}-batch-${Math.floor(wanted)}.json`);
|
|
137
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
138
|
+
fs.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
|
139
|
+
return {
|
|
140
|
+
ok: true,
|
|
141
|
+
file,
|
|
142
|
+
keys: batch.length,
|
|
143
|
+
payload,
|
|
144
|
+
text: `i18n plan: порция ${wanted} · ${batch.length} ключей → ${file}\n` + batch.slice(0, 5).map((item) => ` ${item.key} = ${item.value.slice(0, 60)}`).join("\n"),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function check(cwd, args) {
|
|
149
|
+
const baseDir = localeDir(cwd, baseOf(args));
|
|
150
|
+
const lang = String(args?.lang ?? "").trim();
|
|
151
|
+
if (!baseDir || !fs.existsSync(baseDir)) return fail(`нет каталога словаря: ${baseDir ?? "(base не задан)"}`);
|
|
152
|
+
if (!lang) return fail("нужен lang=ar (какой язык проверяем)");
|
|
153
|
+
const dir = localeDir(cwd, lang);
|
|
154
|
+
if (!dir || !fs.existsSync(dir)) return fail(`нет каталога ${dir}`);
|
|
155
|
+
const base = readDictionary(baseDir);
|
|
156
|
+
const rows = diffDictionary(base, readDictionary(dir));
|
|
157
|
+
const lines = [formatDiffRows(lang, rows)];
|
|
158
|
+
if (lang.startsWith("ar")) {
|
|
159
|
+
const arabic = /[\u0600-\u06FF]/u;
|
|
160
|
+
const latinOnly = [];
|
|
161
|
+
for (const [file, pairs] of readDictionary(dir).entries()) {
|
|
162
|
+
for (const [key, value] of Object.entries(pairs)) {
|
|
163
|
+
if (value.trim().length > 3 && !arabic.test(value) && !/^[\d\s:./%-]+$/u.test(value)) latinOnly.push(`${file}.${key}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
lines.push(`RTL-проверка: ${latinOnly.length} значений без арабских символов${latinOnly.length > 0 ? ` (например ${latinOnly.slice(0, 5).join(", ")})` : ""}`);
|
|
167
|
+
}
|
|
168
|
+
const ok = rows.placeholders.length === 0 && rows.missing.length === 0;
|
|
169
|
+
lines.push(ok ? "Итог: PASS — плейсхолдеры и ключи на месте" : "Итог: FAIL — есть пропуски или расхождения плейсхолдеров");
|
|
170
|
+
return { ok, text: lines.join("\n") };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function applyAction(cwd, args) {
|
|
174
|
+
const baseDir = localeDir(cwd, baseOf(args));
|
|
175
|
+
const lang = String(args?.lang ?? "").trim();
|
|
176
|
+
if (!baseDir || !fs.existsSync(baseDir)) return fail(`нет каталога словаря: ${baseDir ?? "(base не задан)"}`);
|
|
177
|
+
if (!lang) return fail("нужен lang=zh-CN");
|
|
178
|
+
const dir = localeDir(cwd, lang);
|
|
179
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
180
|
+
let payload = null;
|
|
181
|
+
if (typeof args?.file === "string" && args.file.trim().length > 0) {
|
|
182
|
+
const file = path.isAbsolute(args.file) ? args.file : path.join(cwd, args.file);
|
|
183
|
+
try {
|
|
184
|
+
payload = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
185
|
+
} catch (error) {
|
|
186
|
+
return fail(`не читается ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
187
|
+
}
|
|
188
|
+
} else if (args?.translations && typeof args.translations === "object") {
|
|
189
|
+
payload = args.translations;
|
|
190
|
+
}
|
|
191
|
+
if (!payload || typeof payload !== "object") return fail("нужен file=<json> или translations=<object> вида {\"admin.title\": \"…\"}");
|
|
192
|
+
|
|
193
|
+
const base = flattenDictionary(readDictionary(baseDir));
|
|
194
|
+
const grouped = new Map();
|
|
195
|
+
const rejected = [];
|
|
196
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
197
|
+
const baseValue = base.get(key);
|
|
198
|
+
if (baseValue === undefined) {
|
|
199
|
+
rejected.push(`${key}: нет такого ключа в ${baseOf(args)}`);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
203
|
+
rejected.push(`${key}: пустой перевод`);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (!samePlaceholders(baseValue, value)) {
|
|
207
|
+
rejected.push(`${key}: плейсхолдеры ${placeholdersOf(baseValue).join(",") || "—"} ↔ ${placeholdersOf(value).join(",") || "—"}`);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const at = key.indexOf(".");
|
|
211
|
+
const file = key.slice(0, at);
|
|
212
|
+
const inner = key.slice(at + 1);
|
|
213
|
+
if (!grouped.has(file)) grouped.set(file, {});
|
|
214
|
+
grouped.get(file)[inner] = value;
|
|
215
|
+
}
|
|
216
|
+
const written = [];
|
|
217
|
+
for (const [file, translations] of grouped.entries()) {
|
|
218
|
+
const result = applyTranslations(dir, file, translations, { baseDir });
|
|
219
|
+
if (result.ok) written.push(`${file}: +${result.added} (${result.total} всего${result.backup ? `, бэкап ${path.basename(result.backup)}` : ", создан"})`);
|
|
220
|
+
else rejected.push(`${file}: ${result.error}`);
|
|
221
|
+
}
|
|
222
|
+
appendEvidence(cwd, { kind: "i18n:apply", value: `${lang}: ${written.length} файлов`, note: `отклонено ${rejected.length}` });
|
|
223
|
+
const ok = written.length > 0 && rejected.length === 0;
|
|
224
|
+
return {
|
|
225
|
+
ok,
|
|
226
|
+
text: [
|
|
227
|
+
`i18n apply · ${baseOf(args)} → ${lang}`,
|
|
228
|
+
...written.map((line) => ` записано ${line}`),
|
|
229
|
+
...rejected.slice(0, 10).map((line) => ` отклонено ${line}`),
|
|
230
|
+
ok ? "Итог: PASS — переводы записаны, бэкап рядом" : rejected.length > 0 ? "Итог: FAIL — часть ключей отклонена (плейсхолдеры/пустые)" : "Итог: нечего записывать",
|
|
231
|
+
].join("\n"),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function makeToolDefinition() {
|
|
236
|
+
return {
|
|
237
|
+
name: TOOL_NAME,
|
|
238
|
+
description:
|
|
239
|
+
"Localization pipeline for a Laravel-style dictionary (lang/<locale>/*.php|json). coverage: keys used in code (__(), @lang, trans) but missing in the base locale, plus unused keys. diff: per-file missing/extra/untranslated and placeholder mismatches for several locales. plan: split pending keys into batches and emit a JSON payload for translation. apply: write validated translations back (placeholder check, .bak backup) from a JSON file or an object. check: verify one locale including an RTL heuristic for Arabic.",
|
|
240
|
+
parameters: {
|
|
241
|
+
type: "object",
|
|
242
|
+
additionalProperties: false,
|
|
243
|
+
properties: {
|
|
244
|
+
action: { type: "string", enum: ACTIONS, description: "coverage | diff | plan | apply | check" },
|
|
245
|
+
base: { type: "string", description: "base locale or path (default lang/ru)" },
|
|
246
|
+
extra: { type: "string", description: "diff: comma-separated locales, e.g. en,zh-CN,ar" },
|
|
247
|
+
lang: { type: "string", description: "plan/apply/check: target locale" },
|
|
248
|
+
batch: { type: "integer", description: "plan: batch number (omit for the batch list)" },
|
|
249
|
+
batchSize: { type: "integer", description: "plan: keys per batch (default 120)" },
|
|
250
|
+
file: { type: "string", description: "apply: JSON file with {full.key: translation}" },
|
|
251
|
+
translations: { type: "object", description: "apply: inline {full.key: translation}" },
|
|
252
|
+
dirs: { type: "string", description: "coverage: comma-separated source folders" },
|
|
253
|
+
},
|
|
254
|
+
required: ["action"],
|
|
255
|
+
},
|
|
256
|
+
timeoutMs: 120_000,
|
|
257
|
+
output: {
|
|
258
|
+
schema: { type: "object", additionalProperties: true },
|
|
259
|
+
render(_args, value) {
|
|
260
|
+
const text = value && typeof value === "object" && typeof value.text === "string" ? value.text : JSON.stringify(value);
|
|
261
|
+
return [{ type: "text", text }];
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
async execute(args, exec) {
|
|
265
|
+
const cwd = sessionCwd(exec);
|
|
266
|
+
const action = String(args?.action ?? "").trim().toLowerCase();
|
|
267
|
+
try {
|
|
268
|
+
if (!ACTIONS.includes(action)) return fail(`i18n_sync: неизвестное действие «${action}». Доступно: ${ACTIONS.join(", ")}`);
|
|
269
|
+
if (action === "coverage") return coverage(cwd, args);
|
|
270
|
+
if (action === "diff") return diff(cwd, args);
|
|
271
|
+
if (action === "plan") return plan(cwd, args);
|
|
272
|
+
if (action === "apply") return applyAction(cwd, args);
|
|
273
|
+
if (action === "check") return check(cwd, args);
|
|
274
|
+
return fail(`i18n_sync: действие ${action} не реализовано`);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
return fail(`i18n_sync: ${error instanceof Error ? error.message : String(error)}`);
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function apply(ctx) {
|
|
283
|
+
try {
|
|
284
|
+
const tool = makeToolDefinition();
|
|
285
|
+
const register = () => ctx.tools.register(tool);
|
|
286
|
+
if (typeof ctx.effect === "function") ctx.effect(register, "i18n: tool");
|
|
287
|
+
else register();
|
|
288
|
+
} catch (error) {
|
|
289
|
+
ctx.logger?.warn?.(`[i18n] tool registration failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
290
|
+
}
|
|
291
|
+
ctx.logger?.info?.("[i18n] ready");
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export { makeToolDefinition, parsePhpLang };
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Language dictionary helpers: Laravel PHP arrays and flat JSON.
|
|
3
|
+
*
|
|
4
|
+
* A dictionary is `Map<file, Record<key, value>>`, where the full translation
|
|
5
|
+
* key is `${file}.${key}` — exactly how Laravel resolves `__('admin.title')`.
|
|
6
|
+
*/
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
const PHP_PAIR = /(['"])((?:\\.|(?!\1).)*)\1\s*=>\s*(['"])((?:\\.|(?!\3).)*)\3/gu;
|
|
11
|
+
const PLACEHOLDER = /:\w+|\{\w+\}|%\d*\$?[sd@]|%[sd@]/gu;
|
|
12
|
+
|
|
13
|
+
function unescapePhp(value) {
|
|
14
|
+
return value.replace(/\\(['"\\])/gu, "$1").replace(/\\n/gu, "\n");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function phpQuote(value) {
|
|
18
|
+
return `'${String(value).replace(/\\/gu, "\\\\").replace(/'/gu, "\\'")}'`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function parsePhpLang(text) {
|
|
22
|
+
const pairs = {};
|
|
23
|
+
for (const match of String(text ?? "").matchAll(PHP_PAIR)) {
|
|
24
|
+
const key = unescapePhp(match[2]);
|
|
25
|
+
const value = unescapePhp(match[4]);
|
|
26
|
+
if (key) pairs[key] = value;
|
|
27
|
+
}
|
|
28
|
+
return { pairs, nested: /=>\s*\[/u.test(text) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function serializePhpLang(pairs) {
|
|
32
|
+
const entries = Object.entries(pairs).map(([key, value]) => ` ${phpQuote(key)} => ${phpQuote(value)},`);
|
|
33
|
+
return `<?php\n\nreturn [\n${entries.join("\n")}\n];\n`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function parseJsonLang(text) {
|
|
37
|
+
const parsed = JSON.parse(String(text ?? "{}"));
|
|
38
|
+
const flat = {};
|
|
39
|
+
const walk = (value, prefix) => {
|
|
40
|
+
for (const [key, item] of Object.entries(value ?? {})) {
|
|
41
|
+
const full = prefix ? `${prefix}.${key}` : key;
|
|
42
|
+
if (item && typeof item === "object" && !Array.isArray(item)) walk(item, full);
|
|
43
|
+
else flat[full] = String(item ?? "");
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
walk(parsed, "");
|
|
47
|
+
return { pairs: flat, nested: true };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function serializeJsonLang(pairs) {
|
|
51
|
+
return `${JSON.stringify(pairs, null, 2)}\n`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Read a locale directory into `Map<file, pairs>`. */
|
|
55
|
+
export function readDictionary(dir) {
|
|
56
|
+
const dictionary = new Map();
|
|
57
|
+
if (!fs.existsSync(dir)) return dictionary;
|
|
58
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
59
|
+
if (!entry.isFile()) continue;
|
|
60
|
+
const file = path.join(dir, entry.name);
|
|
61
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
62
|
+
if (![".php", ".json"].includes(ext)) continue;
|
|
63
|
+
const text = fs.readFileSync(file, "utf8");
|
|
64
|
+
try {
|
|
65
|
+
const parsed = ext === ".json" ? parseJsonLang(text) : parsePhpLang(text);
|
|
66
|
+
dictionary.set(entry.name.replace(/\.(?:php|json)$/u, ""), parsed.pairs);
|
|
67
|
+
} catch {
|
|
68
|
+
/* a broken file must not stop the whole audit */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return dictionary;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function flattenDictionary(dictionary) {
|
|
75
|
+
const flat = new Map();
|
|
76
|
+
for (const [file, pairs] of dictionary.entries()) {
|
|
77
|
+
for (const [key, value] of Object.entries(pairs)) flat.set(`${file}.${key}`, value);
|
|
78
|
+
}
|
|
79
|
+
return flat;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function placeholdersOf(value) {
|
|
83
|
+
return [...new Set(String(value ?? "").match(PLACEHOLDER) ?? [])].sort();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function samePlaceholders(left, right) {
|
|
87
|
+
const a = placeholdersOf(left);
|
|
88
|
+
const b = placeholdersOf(right);
|
|
89
|
+
return a.length === b.length && a.every((item, index) => item === b[index]);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Per-file diff between the base locale and one target locale. */
|
|
93
|
+
export function diffDictionary(base, target) {
|
|
94
|
+
const rows = { missing: [], extra: [], changed: [], placeholders: [] };
|
|
95
|
+
for (const [file, pairs] of base.entries()) {
|
|
96
|
+
const other = target.get(file) ?? {};
|
|
97
|
+
for (const [key, value] of Object.entries(pairs)) {
|
|
98
|
+
const full = `${file}.${key}`;
|
|
99
|
+
if (!(key in other)) {
|
|
100
|
+
rows.missing.push({ key: full, value });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const translated = other[key];
|
|
104
|
+
if (!samePlaceholders(value, translated)) rows.placeholders.push({ key: full, base: value, target: translated });
|
|
105
|
+
else if (translated !== value || translated.trim().length === 0) {
|
|
106
|
+
if (translated.trim().length === 0) rows.missing.push({ key: full, value, reason: "empty" });
|
|
107
|
+
else if (translated === value) rows.changed.push({ key: full, base: value, target: translated, reason: "untranslated" });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
for (const key of Object.keys(other)) if (!(key in pairs)) rows.extra.push({ key: `${file}.${key}` });
|
|
111
|
+
}
|
|
112
|
+
for (const [file, pairs] of target.entries()) {
|
|
113
|
+
if (base.has(file)) continue;
|
|
114
|
+
for (const key of Object.keys(pairs)) rows.extra.push({ key: `${file}.${key}` });
|
|
115
|
+
}
|
|
116
|
+
return rows;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function formatDiffRows(name, rows) {
|
|
120
|
+
const lines = [
|
|
121
|
+
`${name}: missing ${rows.missing.length} · extra ${rows.extra.length} · untranslated ${rows.changed.length} · placeholder-mismatch ${rows.placeholders.length}`,
|
|
122
|
+
];
|
|
123
|
+
for (const item of rows.missing.slice(0, 8)) lines.push(` missing ${item.key}`);
|
|
124
|
+
for (const item of rows.changed.slice(0, 8)) lines.push(` untranslated ${item.key}`);
|
|
125
|
+
for (const item of rows.placeholders.slice(0, 8)) lines.push(` placeholder ${item.key}: ${placeholdersOf(item.base).join(",")} ↔ ${placeholdersOf(item.target).join(",")}`);
|
|
126
|
+
return lines.join("\n");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Write one batch of translations back into a locale file (PHP or JSON). */
|
|
130
|
+
export function applyTranslations(dir, file, translations, options = {}) {
|
|
131
|
+
const phpFile = path.join(dir, `${file}.php`);
|
|
132
|
+
const jsonFile = path.join(dir, `${file}.json`);
|
|
133
|
+
const existing = fs.existsSync(phpFile) ? phpFile : fs.existsSync(jsonFile) ? jsonFile : null;
|
|
134
|
+
/* A new locale starts from the base file's format, not from a guess. */
|
|
135
|
+
const baseFile = options.baseDir ? path.join(options.baseDir, `${file}.php`) : "";
|
|
136
|
+
const baseJson = options.baseDir ? path.join(options.baseDir, `${file}.json`) : "";
|
|
137
|
+
const isPhp = existing ? existing.endsWith(".php") : fs.existsSync(baseFile) || !fs.existsSync(baseJson);
|
|
138
|
+
const target = existing ?? path.join(dir, isPhp ? `${file}.php` : `${file}.json`);
|
|
139
|
+
const currentText = existing && fs.existsSync(existing) ? fs.readFileSync(existing, "utf8") : "";
|
|
140
|
+
const parsed = isPhp ? parsePhpLang(currentText) : parseJsonLang(currentText || "{}");
|
|
141
|
+
const next = { ...parsed.pairs, ...translations };
|
|
142
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
143
|
+
if (existing) fs.writeFileSync(`${target}.bak`, currentText, "utf8");
|
|
144
|
+
fs.writeFileSync(target, isPhp ? serializePhpLang(next) : serializeJsonLang(next), "utf8");
|
|
145
|
+
return {
|
|
146
|
+
ok: true,
|
|
147
|
+
file: target,
|
|
148
|
+
total: Object.keys(next).length,
|
|
149
|
+
added: Object.keys(translations).length,
|
|
150
|
+
backup: existing ? `${target}.bak` : "",
|
|
151
|
+
created: !existing,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Translation calls used in source files, as full keys. */
|
|
156
|
+
export function usedKeys(root, options = {}) {
|
|
157
|
+
const dirs = options.dirs ?? ["resources/views", "resources/js", "app", "src", "templates"];
|
|
158
|
+
const exts = new Set([".php", ".blade.php", ".js", ".ts", ".vue", ".twig", ".html"]);
|
|
159
|
+
const call = /(?:__|@lang|trans|Lang::get)\(\s*['"]([\w.-]+)['"]/gu;
|
|
160
|
+
const found = new Map();
|
|
161
|
+
const walk = (dir) => {
|
|
162
|
+
if (!fs.existsSync(dir)) return;
|
|
163
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
164
|
+
if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "vendor") continue;
|
|
165
|
+
const full = path.join(dir, entry.name);
|
|
166
|
+
if (entry.isDirectory()) walk(full);
|
|
167
|
+
else if ([...exts].some((ext) => full.endsWith(ext))) {
|
|
168
|
+
const text = fs.readFileSync(full, "utf8");
|
|
169
|
+
for (const match of text.matchAll(call)) {
|
|
170
|
+
const key = match[1];
|
|
171
|
+
if (!key.includes(".")) continue;
|
|
172
|
+
found.set(key, (found.get(key) ?? 0) + 1);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
for (const dir of dirs) walk(path.join(root, dir));
|
|
178
|
+
return found;
|
|
179
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-i18n",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Localization pipeline for DSH agents: dictionary audit, usage coverage, translation batches, placeholder validation and safe write-back with backups.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./index.js",
|
|
11
|
+
"./lib/lang": "./lib/lang.js",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"index.js",
|
|
16
|
+
"lib/**",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.0.0"
|
|
22
|
+
},
|
|
23
|
+
"dsh": {
|
|
24
|
+
"manifestVersion": 1,
|
|
25
|
+
"bundle": {
|
|
26
|
+
"patch": "./cordis.patch.yml"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# dsh-quality-pipeline
|
|
2
|
+
|
|
3
|
+
Миссия качества: фазы, гейты, единицы работы и приёмка с доказательствами.
|
|
4
|
+
Состояние — `.dsh/quality/mission.json`, доказательства — `.dsh/quality/evidence.jsonl`.
|
|
5
|
+
|
|
6
|
+
## Зачем
|
|
7
|
+
|
|
8
|
+
Текст «будь премиальным» не исполняется. Исполняется состояние: нельзя перейти в
|
|
9
|
+
следующую фазу, пока гейты предыдущей не зелёные, и нельзя закрыть гейт без
|
|
10
|
+
доказательства (команда, метрика или путь к отчёту).
|
|
11
|
+
|
|
12
|
+
## Инструмент `quality_gate`
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
quality_gate action=start task="Редизайн сайта клиники" profile=turnkey stack="wordpress, php" \
|
|
16
|
+
units=["Главная","Услуги","Врачи"] \
|
|
17
|
+
acceptance=[{"title":"audit matrix full","command":"node qa.mjs audit --matrix full","threshold":"overflow 0"}]
|
|
18
|
+
quality_gate action=status
|
|
19
|
+
quality_gate action=plan name="Отзывы"
|
|
20
|
+
quality_gate action=gate id=G4 unit=u1 evidence="browser_qa audit matrix=full: overflow 0, console 0, markup 0, 4/4"
|
|
21
|
+
quality_gate action=gate id=G6 unit=u1 evidence="a11y: critical 0, contrast 0, tap<24 0"
|
|
22
|
+
quality_gate action=accept run=true
|
|
23
|
+
quality_gate action=phase
|
|
24
|
+
quality_gate action=evidence kind=perf value="LCP 740" note="node qa.mjs perf --url …"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Фазы и гейты
|
|
28
|
+
|
|
29
|
+
| Фаза | Гейты |
|
|
30
|
+
|---|---|
|
|
31
|
+
| research | G0 миссия и приёмка · G1 референсы и нормы |
|
|
32
|
+
| plan | G2 прямой план, обратный план, пре-мортем |
|
|
33
|
+
| system | G3 токены, шкала, слои, состояния |
|
|
34
|
+
| build | G4 аудит единицы (overflow/console/markup/матрица) |
|
|
35
|
+
| verify | G5 интеракции · G6 доступность · G7 перф · G8 SEO · G9 админка · G10 право |
|
|
36
|
+
| fix | без гейта: возврат в build по findings |
|
|
37
|
+
| handoff | G11 приёмка (acceptance PASS) · G12 отчёт и runbook |
|
|
38
|
+
|
|
39
|
+
Профили: `fast` — G0, G4, G11; `standard` — G0, G1, G2, G4, G5, G6, G11; `turnkey` — все.
|
|
40
|
+
|
|
41
|
+
## Правила
|
|
42
|
+
|
|
43
|
+
- Гейт проходит только с evidence ≥ 12 символов; «готово» доказательством не считается.
|
|
44
|
+
- `handoff` требует `acceptance` PASS: в миссии должна быть хотя бы одна проверка с командой.
|
|
45
|
+
- `unit ... status=done` закрывается только когда его unit-scoped гейты (G4, G5, G6) зелёные.
|
|
46
|
+
- Команды приёмки разбираются без shell (`execFile`), `; | & > $` запрещены — инъекция невозможна.
|
|
47
|
+
- Каждый результат `browser_qa` автоматически попадает в evidence.
|
|
48
|
+
|
|
49
|
+
## Команда
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
/quality status | next | accept
|
|
53
|
+
```
|