dsh-desktop-kit 2.24.1 → 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.
Files changed (71) hide show
  1. package/CHANGELOG.md +71 -10
  2. package/README.md +193 -262
  3. package/client.js +1 -1
  4. package/docs/ARCHITECTURE.md +9 -6
  5. package/docs/PROPOSAL-2.25-quality-pipeline.md +435 -0
  6. package/docs/PROPOSAL-NEXUM-FINDINGS.md +259 -0
  7. package/docs/TEST-2.30.0.md +83 -0
  8. package/docs/images/capability-map-2.30.png +0 -0
  9. package/docs/images/hero-2.30.png +0 -0
  10. package/docs/images/quality-pipeline-2.30.png +0 -0
  11. package/docs/preview/capability-map-2.30.html +106 -0
  12. package/docs/preview/hero-2.30.html +133 -0
  13. package/docs/preview/quality-pipeline-2.30.html +142 -0
  14. package/docs/preview/readme-visuals.css +111 -0
  15. package/index.js +6 -0
  16. package/package.json +11 -4
  17. package/plugins/dsh-agent-extensions/lib/routing.js +4 -0
  18. package/plugins/dsh-agent-extensions/lib/scaffold.js +152 -27
  19. package/plugins/dsh-agent-extensions/lib/settings.js +19 -0
  20. package/plugins/dsh-agent-extensions/lib/swarm.js +6 -2
  21. package/plugins/dsh-browser-qa/index.js +202 -9
  22. package/plugins/dsh-browser-qa/lib/design-more.js +688 -0
  23. package/plugins/dsh-browser-qa/lib/extras.js +1313 -0
  24. package/plugins/dsh-browser-qa/lib/pages.js +4 -3
  25. package/plugins/dsh-browser-qa/lib/png.js +190 -0
  26. package/plugins/dsh-browser-qa/lib/ui-gate.js +171 -31
  27. package/plugins/dsh-i18n/README.md +36 -0
  28. package/plugins/dsh-i18n/cordis.patch.yml +3 -0
  29. package/plugins/dsh-i18n/index.js +294 -0
  30. package/plugins/dsh-i18n/lib/lang.js +179 -0
  31. package/plugins/dsh-i18n/package.json +29 -0
  32. package/plugins/dsh-quality-pipeline/README.md +53 -0
  33. package/plugins/dsh-quality-pipeline/cordis.patch.yml +3 -0
  34. package/plugins/dsh-quality-pipeline/index.js +647 -0
  35. package/plugins/dsh-quality-pipeline/lib/acceptance.js +132 -0
  36. package/plugins/dsh-quality-pipeline/lib/autostart.js +159 -0
  37. package/plugins/dsh-quality-pipeline/lib/design.js +123 -0
  38. package/plugins/dsh-quality-pipeline/lib/machine.js +312 -0
  39. package/plugins/dsh-quality-pipeline/lib/prework.js +215 -0
  40. package/plugins/dsh-quality-pipeline/lib/release.js +53 -0
  41. package/plugins/dsh-quality-pipeline/lib/schema.js +256 -0
  42. package/plugins/dsh-quality-pipeline/lib/store.js +114 -0
  43. package/plugins/dsh-quality-pipeline/lib/text.js +109 -0
  44. package/plugins/dsh-quality-pipeline/package.json +33 -0
  45. package/plugins/dsh-remote-ops/README.md +38 -0
  46. package/plugins/dsh-remote-ops/cordis.patch.yml +3 -0
  47. package/plugins/dsh-remote-ops/index.js +268 -0
  48. package/plugins/dsh-remote-ops/lib/hosts.js +118 -0
  49. package/plugins/dsh-remote-ops/lib/ssh.js +96 -0
  50. package/plugins/dsh-remote-ops/lib/state.js +66 -0
  51. package/plugins/dsh-remote-ops/package.json +31 -0
  52. package/plugins/dsh-skill-autopilot/index.js +204 -15
  53. package/skills/a11y-audit/SKILL.md +67 -0
  54. package/skills/cms-ops/SKILL.md +74 -0
  55. package/skills/design-system/SKILL.md +100 -0
  56. package/skills/legal-ru-web/SKILL.md +68 -0
  57. package/skills/manifest.json +38 -18
  58. package/skills/release-pipeline/SKILL.md +67 -0
  59. package/skills/ui-batch/SKILL.md +60 -0
  60. package/skills/web-build/SKILL.md +106 -0
  61. package/skills/web-build/recipes/form.md +16 -0
  62. package/skills/web-build/recipes/payment.md +16 -0
  63. package/skills/web-build/recipes/review.md +16 -0
  64. package/skills-baseline.json +192 -0
  65. package/skills/ui-design-system/references/accessibility-and-responsive.md +0 -50
  66. package/skills/ui-design-system/references/tokens-and-components.md +0 -67
  67. package/skills/ui-design-system/references/visual-qa.md +0 -44
  68. package/skills/visual-qa/references/commands.md +0 -32
  69. /package/skills/{ui-craft/SKILL.md → design-system/references/ui-craft.md} +0 -0
  70. /package/skills/{ui-design-system/SKILL.md → design-system/references/ui-design-system.md} +0 -0
  71. /package/skills/{visual-qa/SKILL.md → ui-batch/references/visual-qa.md} +0 -0
@@ -0,0 +1,647 @@
1
+ /**
2
+ * dsh-quality-pipeline — the mission state machine of the kit.
3
+ *
4
+ * One tool (`quality_gate`) owns the durable state of a piece of work:
5
+ * phases, gates, units and acceptance. Every gate needs evidence; every phase
6
+ * transition is checked. The plugin also injects a two-line `<quality-state>`
7
+ * block into the system prompt, so the model always knows where it is without
8
+ * re-reading the plan.
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+
13
+ import { applyAcceptanceRows, formatAcceptance, runAcceptance } from "./lib/acceptance.js";
14
+ import { autoStartMission } from "./lib/autostart.js";
15
+ import { releaseAction } from "./lib/release.js";
16
+ import { formatBrief, normalizeBrief, normalizeVariants } from "./lib/design.js";
17
+ import { appendDecision, iaMarkdown, normalizeInventory, normalizePlan, normalizeProduct, planMissing, productMissing, scanBlockers } from "./lib/prework.js";
18
+ import {
19
+ GATES,
20
+ PHASES,
21
+ advancePhase,
22
+ blockingWork,
23
+ canEnterPhase,
24
+ describeGate,
25
+ failGate,
26
+ passGate,
27
+ planUnit,
28
+ progress,
29
+ setUnitStatus,
30
+ } from "./lib/machine.js";
31
+ import { QUALITY_PROFILES, WORK_TYPES, createMission, touch, validateMission } from "./lib/schema.js";
32
+ import { appendEvidence, deleteMission, readEvidence, readMission, writeMission } from "./lib/store.js";
33
+ import { formatGateList, formatPromptLine, formatStatus } from "./lib/text.js";
34
+
35
+ export const inject = ["tools"];
36
+
37
+ const TOOL_NAME = "quality_gate";
38
+ const MAX_RENDER_CHARS = 12_000;
39
+
40
+ const ACTIONS = ["start", "status", "list", "phase", "plan", "unit", "gate", "accept", "release", "brief", "product", "ia", "decision", "blockers", "evidence", "reset"];
41
+
42
+ function sessionCwd(exec) {
43
+ const cwd = exec?.agent?.session?.header?.cwd;
44
+ return typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd();
45
+ }
46
+
47
+ function failure(text) {
48
+ return { ok: false, text };
49
+ }
50
+
51
+ function parseList(value) {
52
+ if (Array.isArray(value)) return value.map((item) => String(item)).filter(Boolean);
53
+ if (typeof value === "string" && value.trim().length > 0) return value.split(",").map((item) => item.trim()).filter(Boolean);
54
+ return [];
55
+ }
56
+
57
+ function normalizeUnits(raw) {
58
+ if (Array.isArray(raw)) {
59
+ return raw
60
+ .map((unit) => (typeof unit === "string" ? { name: unit } : unit))
61
+ .filter((unit) => unit && typeof unit.name === "string" && unit.name.trim().length > 0);
62
+ }
63
+ return parseList(raw).map((name) => ({ name }));
64
+ }
65
+
66
+ function normalizeAcceptance(raw) {
67
+ if (!Array.isArray(raw)) return [];
68
+ return raw
69
+ .map((item, index) => {
70
+ if (typeof item === "string") return { id: `a${index + 1}`, title: item, command: "" };
71
+ if (!item || typeof item !== "object") return null;
72
+ return {
73
+ id: typeof item.id === "string" ? item.id : `a${index + 1}`,
74
+ title: String(item.title ?? item.name ?? `Проверка ${index + 1}`),
75
+ command: String(item.command ?? ""),
76
+ threshold: String(item.threshold ?? ""),
77
+ };
78
+ })
79
+ .filter(Boolean);
80
+ }
81
+
82
+ function startMission(cwd, args) {
83
+ const existing = readMission(cwd);
84
+ if (existing && args?.force !== true) {
85
+ return {
86
+ ok: false,
87
+ text: `Миссия уже есть: phase=${existing.phase}, профиль ${existing.profile}. Перезаписать — action=start force=true (старая уйдёт в evidence).`,
88
+ };
89
+ }
90
+ const mission = createMission({
91
+ task: args?.task,
92
+ type: args?.type,
93
+ profile: args?.profile,
94
+ stack: parseList(args?.stack),
95
+ units: normalizeUnits(args?.units),
96
+ acceptance: normalizeAcceptance(args?.acceptance),
97
+ release: normalizeAcceptance(args?.release),
98
+ design: { brief: args?.brief, variants: args?.variants },
99
+ invariants: parseList(args?.invariants),
100
+ });
101
+ writeMission(cwd, mission);
102
+ appendEvidence(cwd, { kind: "mission", note: `created profile=${mission.profile} type=${mission.type}`, value: mission.task.slice(0, 200) });
103
+ return {
104
+ ok: true,
105
+ mission,
106
+ text: [
107
+ `Миссия создана: ${mission.task.slice(0, 160)}`,
108
+ `Профиль ${mission.profile} · тип ${mission.type} · фаза ${mission.phase} (${mission.phases?.length ?? PHASES.length} фаз)`,
109
+ `Единиц: ${mission.units.length} · проверок: ${mission.acceptance.length}`,
110
+ "",
111
+ "Дальше по порядку:",
112
+ " 1) quality_gate action=plan name=\"Главная\" — добавьте единицы работы",
113
+ " 2) quality_gate action=accept — пропишите проверки с командами (без них handoff не откроется)",
114
+ " 3) quality_gate action=gate id=G0 evidence=\"…\" — закройте гейты первой фазы",
115
+ " 4) quality_gate action=phase — переход только при зелёных гейтах",
116
+ "Состояние: .dsh/quality/mission.json · доказательства: .dsh/quality/evidence.jsonl",
117
+ ].join("\n"),
118
+ };
119
+ }
120
+
121
+ function phaseAction(cwd, args) {
122
+ const mission = readMission(cwd);
123
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
124
+ const target = typeof args?.to === "string" && args.to.trim().length > 0 ? args.to.trim().toLowerCase() : undefined;
125
+ const check = canEnterPhase(mission, target ?? PHASES[PHASES.indexOf(mission.phase) + 1] ?? mission.phase);
126
+ if (target && !check.ok) return { ok: false, mission, text: `Переход в ${target} закрыт: ${check.reason}` };
127
+ const moved = advancePhase(mission, target);
128
+ if (!moved.ok) return { ok: false, mission, text: `Переход закрыт: ${moved.reason}` };
129
+ writeMission(cwd, moved.mission);
130
+ appendEvidence(cwd, { kind: "phase", note: `${mission.phase}`, value: moved.mission.phase });
131
+ return {
132
+ ok: true,
133
+ mission: moved.mission,
134
+ text: `Фаза: ${moved.mission.phase} (${moved.mission.phase}).\nГейты фазы: ${GATES.filter((gate) => gate.phase === moved.mission.phase).map((gate) => gate.id).join(", ") || "нет"}\n\n${formatStatus(moved.mission)}`,
135
+ };
136
+ }
137
+
138
+ function gateAction(cwd, args) {
139
+ const mission = readMission(cwd);
140
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
141
+ const id = String(args?.id ?? "").trim().toUpperCase();
142
+ const gate = describeGate(mission, id);
143
+ if (!gate) return failure(`Гейт не найден: ${id || "(пусто)"}. Доступно: ${GATES.map((item) => item.id).join(", ")}`);
144
+ const pass = args?.pass !== false;
145
+ const result = pass
146
+ ? passGate(mission, id, { evidence: args?.evidence, unit: args?.unit, note: args?.note })
147
+ : failGate(mission, id, { evidence: args?.evidence, unit: args?.unit });
148
+ if (!result.ok) return { ok: false, mission, text: result.reason };
149
+ writeMission(cwd, mission);
150
+ appendEvidence(cwd, {
151
+ kind: "gate",
152
+ gate: id,
153
+ unit: typeof args?.unit === "string" ? args.unit : "",
154
+ value: pass ? "passed" : "failed",
155
+ note: String(args?.evidence ?? "").slice(0, 400),
156
+ });
157
+ return {
158
+ ok: true,
159
+ mission,
160
+ text: `Гейт ${id} ${pass ? "PASS" : "FAIL"}: ${gate.title}${args?.unit ? ` · единица ${args.unit}` : ""}.\n\n${formatStatus(mission)}`,
161
+ };
162
+ }
163
+
164
+ async function acceptAction(cwd, args) {
165
+ const mission = readMission(cwd);
166
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
167
+ if (args?.run !== true) {
168
+ if (mission.acceptance.length === 0) {
169
+ return {
170
+ ok: false,
171
+ mission,
172
+ text: "Проверок нет. Добавьте их при старте: acceptance=[{title:'audit matrix full',command:'node qa.mjs audit --matrix full',threshold:'overflow 0'}]. Затем action=accept run=true.",
173
+ };
174
+ }
175
+ return {
176
+ ok: true,
177
+ mission,
178
+ text: [
179
+ `Приёмка: ${mission.acceptance.length} проверок (dry-run, ничего не запускалось)`,
180
+ ...mission.acceptance.map((item) => `- ${item.id} ${item.title}${item.command ? ` :: ${item.command}` : " (нет команды)"} [${item.status}]`),
181
+ "Запуск: action=accept run=true",
182
+ ].join("\n"),
183
+ };
184
+ }
185
+ const rows = await runAcceptance({ cwd, mission, only: parseList(args?.only) });
186
+ applyAcceptanceRows(mission, rows);
187
+ writeMission(cwd, mission);
188
+ for (const row of rows) {
189
+ appendEvidence(cwd, { kind: "acceptance", gate: "G11", value: row.status, note: `${row.id} ${row.title}`.slice(0, 300) });
190
+ }
191
+ const passed = rows.filter((row) => row.status === "pass").length;
192
+ const allPass = rows.length > 0 && passed === rows.length;
193
+ if (allPass) {
194
+ passGate(mission, "G11", { evidence: `acceptance ${passed}/${rows.length} PASS (${rows.map((row) => row.id).join(",")})` });
195
+ writeMission(cwd, mission);
196
+ }
197
+ return {
198
+ ok: allPass,
199
+ mission,
200
+ acceptance: rows,
201
+ text: `${formatAcceptance(rows)}${allPass ? "\nГейт G11 закрыт автоматически." : "\nG11 остаётся открытым."}`,
202
+ };
203
+ }
204
+
205
+ function briefAction(cwd, args) {
206
+ const mission = readMission(cwd);
207
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
208
+ mission.design = mission.design ?? { brief: null, variants: [] };
209
+ const wantsWrite = args?.brief !== undefined || Array.isArray(args?.variants) || typeof args?.choose === "string";
210
+ if (!wantsWrite) return { ok: true, mission, text: formatBrief(mission) };
211
+ if (args?.brief !== undefined) mission.design.brief = normalizeBrief(args.brief);
212
+ if (Array.isArray(args?.variants)) mission.design.variants = normalizeVariants(args.variants);
213
+ if (typeof args?.choose === "string" && args.choose.trim().length > 0) {
214
+ const id = args.choose.trim();
215
+ const variants = mission.design.variants ?? [];
216
+ if (variants.length === 0) return { ok: false, mission, text: "Сначала добавьте варианты: action=brief variants=[{title,summary},…]" };
217
+ const target = variants.find((variant) => variant.id === id || variant.title === id);
218
+ if (!target) return { ok: false, mission, text: `Вариант не найден: ${id} (есть ${variants.map((variant) => variant.id).join(", ")})` };
219
+ for (const variant of variants) variant.chosen = variant === target;
220
+ }
221
+ touch(mission);
222
+ writeMission(cwd, mission);
223
+ appendEvidence(cwd, {
224
+ kind: "design:brief",
225
+ gate: "G3",
226
+ value: args?.choose ? `chosen ${args.choose}` : "updated",
227
+ note: mission.design.brief ? `palette ${mission.design.brief.palette.length}, refs ${mission.design.brief.references.length}` : "no brief",
228
+ });
229
+ return { ok: true, mission, text: `${formatBrief(mission)}\n\n${formatStatus(mission)}` };
230
+ }
231
+
232
+ function preworkAction(cwd, args) {
233
+ const mission = readMission(cwd);
234
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
235
+ const action = String(args?.action ?? "");
236
+ if (action === "product") {
237
+ if (!args?.product) {
238
+ const product = mission.design?.product;
239
+ const missing = productMissing(product);
240
+ return {
241
+ ok: true,
242
+ mission,
243
+ text: product
244
+ ? `Продуктовый бриф: пользователей ${product.audience.length} · страниц ${product.pages.length} · метрик ${product.success.length} · ограничений ${product.constraints.length}${missing.length ? `\nНе хватает: ${missing.join("; ")}` : ""}`
245
+ : `Продуктовый бриф не заполнен. Заполните: quality_gate action=product product={audience:[{who,job}], pages:[…], success:[{metric,target}], constraints:[…], nonGoals:[…]}`,
246
+ };
247
+ }
248
+ mission.design = mission.design ?? {};
249
+ mission.design.product = normalizeProduct(args.product);
250
+ touch(mission);
251
+ writeMission(cwd, mission);
252
+ appendEvidence(cwd, { kind: "prework:product", gate: "G0", value: "written", note: `${mission.design.product.pages.length} страниц` });
253
+ const missing = productMissing(mission.design.product);
254
+ return {
255
+ ok: missing.length === 0,
256
+ mission,
257
+ text: `Продуктовый бриф записан.${missing.length ? `\nНе хватает: ${missing.join("; ")}` : "\nG0-продукт: PASS"}\n\n${formatStatus(mission)}`,
258
+ };
259
+ }
260
+ if (action === "plan") {
261
+ if (!args?.plan) {
262
+ const plan = mission.plan ?? { steps: [], risks: [], blockers: [] };
263
+ const missing = planMissing(plan, mission.units ?? []);
264
+ const openBlockers = (plan.blockers ?? []).filter((blocker) => blocker.open);
265
+ return {
266
+ ok: missing.length === 0,
267
+ mission,
268
+ text: [
269
+ `План: шагов ${plan.steps.length} · рисков ${plan.risks.length} · блокеров открытых ${openBlockers.length}`,
270
+ ...plan.steps.slice(0, 10).map((step) => ` ${step.id} ${step.title}${step.dependsOn.length ? ` ← ${step.dependsOn.join(",")}` : ""} [${step.size}]`),
271
+ ...openBlockers.slice(0, 8).map((blocker) => ` blocker ${blocker.severity} ${blocker.title}${blocker.owner ? ` (${blocker.owner})` : ""}`),
272
+ ...missing.map((item) => ` не хватает: ${item}`),
273
+ ].join("\n"),
274
+ };
275
+ }
276
+ mission.plan = normalizePlan({ ...(mission.plan ?? {}), ...args.plan });
277
+ touch(mission);
278
+ writeMission(cwd, mission);
279
+ appendEvidence(cwd, { kind: "prework:plan", gate: "G2", value: `${mission.plan.steps.length} шагов`, note: `${mission.plan.risks.length} рисков` });
280
+ const missing = planMissing(mission.plan, mission.units ?? []);
281
+ return {
282
+ ok: missing.length === 0,
283
+ mission,
284
+ text: `План записан: шагов ${mission.plan.steps.length}, рисков ${mission.plan.risks.length}, блокеров ${mission.plan.blockers.length}.${missing.length ? `\nНе хватает: ${missing.join("; ")}` : "\nG2: PASS"}\n\n${formatStatus(mission)}`,
285
+ };
286
+ }
287
+ if (action === "ia") {
288
+ const pages = normalizeInventory({ pages: args?.pages });
289
+ if (pages.length === 0) {
290
+ return failure("Нужен pages=[{url, template, sections:[…], content:'ready|todo|move|photo'}]");
291
+ }
292
+ let created = 0;
293
+ for (const page of pages) {
294
+ const planned = planUnit(mission, {
295
+ name: page.url,
296
+ kind: "page",
297
+ dod: [`контент: ${page.content}`, `шаблон: ${page.template || "—"}`],
298
+ });
299
+ if (planned.ok && !planned.duplicate) created += 1;
300
+ }
301
+ touch(mission);
302
+ writeMission(cwd, mission);
303
+ const file = path.join(cwd, "docs", "ia.md");
304
+ fs.mkdirSync(path.dirname(file), { recursive: true });
305
+ fs.writeFileSync(file, iaMarkdown(pages), "utf8");
306
+ appendEvidence(cwd, { kind: "prework:ia", gate: "G0", value: `${pages.length} страниц`, note: `новых единиц ${created}` });
307
+ return {
308
+ ok: true,
309
+ mission,
310
+ text: `Карта сайта: ${pages.length} страниц, новых единиц ${created}. Файл: ${file}\n${pages.filter((page) => page.content !== "ready").length} страниц без готового контента.\n\n${formatStatus(mission)}`,
311
+ };
312
+ }
313
+ if (action === "blockers") {
314
+ const plan = mission.plan ?? { steps: [], risks: [], blockers: [] };
315
+ if (typeof args?.close === "string" && args.close.trim().length > 0) {
316
+ const id = args.close.trim();
317
+ const blocker = (plan.blockers ?? []).find((item) => item.id === id);
318
+ if (!blocker) return failure(`Блокер не найден: ${id} (есть ${(plan.blockers ?? []).map((item) => item.id).join(", ")})`);
319
+ blocker.open = false;
320
+ mission.plan = plan;
321
+ touch(mission);
322
+ writeMission(cwd, mission);
323
+ return { ok: true, mission, text: `Блокер закрыт: ${id} ${blocker.title}` };
324
+ }
325
+ const scanned = args?.scan === false ? [] : scanBlockers(cwd);
326
+ const merged = [...(plan.blockers ?? []).filter((item) => !scanned.some((blocker) => blocker.title === item.title))];
327
+ let index2 = merged.length;
328
+ for (const blocker of scanned) {
329
+ index2 += 1;
330
+ merged.push({ ...blocker, id: `b${index2}` });
331
+ }
332
+ mission.plan = { ...plan, blockers: merged };
333
+ touch(mission);
334
+ writeMission(cwd, mission);
335
+ const open = merged.filter((item) => item.open);
336
+ return {
337
+ ok: open.filter((item) => item.severity === "P0").length === 0,
338
+ mission,
339
+ text: [
340
+ `Блокеров: ${merged.length}, открытых ${open.length}`,
341
+ ...open.map((item) => ` ${item.id} ${item.severity} ${item.title}${item.hint ? ` → ${item.hint}` : ""}`),
342
+ "Закрыть: action=blockers close=b1",
343
+ ].join("\n"),
344
+ };
345
+ }
346
+ if (action === "decision") {
347
+ const result = appendDecision(cwd, args?.decision);
348
+ if (!result.ok) return failure(result.error);
349
+ mission.decisions = [...(mission.decisions ?? []), { at: new Date().toISOString(), text: String(args.decision).slice(0, 400) }].slice(-100);
350
+ touch(mission);
351
+ writeMission(cwd, mission);
352
+ return { ok: true, mission, text: result.text };
353
+ }
354
+ return failure(`product/plan/ia/decision: неизвестное действие ${action}`);
355
+ }
356
+
357
+ function unitAction(cwd, args) {
358
+ const mission = readMission(cwd);
359
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
360
+ const status = String(args?.status ?? "").trim().toLowerCase();
361
+ if (!status) return failure("Нужен status: todo | doing | done | blocked");
362
+ const result = setUnitStatus(mission, args?.name ?? args?.unit ?? args?.id, status, { evidence: args?.evidence });
363
+ if (!result.ok) return { ok: false, mission, text: result.reason };
364
+ writeMission(cwd, mission);
365
+ appendEvidence(cwd, { kind: "unit", unit: result.unit.id, value: status, note: String(args?.evidence ?? "").slice(0, 300) });
366
+ return { ok: true, mission, text: `Единица ${result.unit.id} «${result.unit.name}» → ${status}.\n\n${formatStatus(mission)}` };
367
+ }
368
+
369
+ function planAction(cwd, args) {
370
+ const mission = readMission(cwd);
371
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
372
+ const units = Array.isArray(args?.units) && args.units.length > 0 ? normalizeUnits(args.units) : [{ name: args?.name, kind: args?.kind }];
373
+ const added = [];
374
+ for (const unit of units) {
375
+ const result = planUnit(mission, unit);
376
+ if (!result.ok) return { ok: false, mission, text: result.reason };
377
+ if (!result.duplicate) added.push(result.unit);
378
+ }
379
+ writeMission(cwd, mission);
380
+ return {
381
+ ok: true,
382
+ mission,
383
+ text: added.length > 0
384
+ ? `Добавлено единиц: ${added.length} (${added.map((unit) => `${unit.id} ${unit.name}`).join(", ")}).\n\n${formatStatus(mission)}`
385
+ : "Такие единицы уже есть.",
386
+ };
387
+ }
388
+
389
+ function evidenceAction(cwd, args) {
390
+ const mission = readMission(cwd);
391
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
392
+ const entry = appendEvidence(cwd, {
393
+ kind: String(args?.kind ?? "note").slice(0, 40),
394
+ gate: String(args?.id ?? args?.gate ?? "").toUpperCase().slice(0, 4),
395
+ unit: String(args?.unit ?? "").slice(0, 8),
396
+ value: String(args?.value ?? "").slice(0, 300),
397
+ note: String(args?.note ?? args?.evidence ?? "").slice(0, 600),
398
+ });
399
+ return { ok: true, mission, evidence: entry, text: `Evidence записан: ${entry.kind}${entry.gate ? ` · ${entry.gate}` : ""}${entry.value ? ` · ${entry.value}` : ""}` };
400
+ }
401
+
402
+ function makeToolDefinition() {
403
+ return {
404
+ name: TOOL_NAME,
405
+ description:
406
+ "Mission state machine for quality-critical work: phases (research→plan→system→build→verify→fix→handoff), gates G0..G12, units of work and acceptance checks, persisted in .dsh/quality/. start: create the mission (task, type, profile fast|standard|turnkey, stack, units, acceptance). status: phase, gates, units, blockers. list: gate registry with metrics. plan: add units of work. unit: set unit status todo|doing|done|blocked. gate: pass or fail one gate — a pass needs evidence of at least 12 characters (command, metric or report path). phase: move to the next phase; blocked until the required gates of earlier phases are green, and handoff additionally needs acceptance PASS. accept: run acceptance commands (shell is NOT used) and auto-close G11 when every check passes. evidence: append a record to .dsh/quality/evidence.jsonl. reset: delete the mission (confirm=true).",
407
+ parameters: {
408
+ type: "object",
409
+ additionalProperties: false,
410
+ properties: {
411
+ action: { type: "string", enum: ACTIONS, description: "start | status | list | phase | plan | unit | gate | accept | evidence | reset" },
412
+ task: { type: "string", description: "start: what we build, one or two sentences." },
413
+ type: { type: "string", enum: WORK_TYPES, description: "start: work type (default web-site)." },
414
+ profile: { type: "string", enum: QUALITY_PROFILES, description: "start: gate profile — fast (3 gates), standard (7), turnkey (all 13)." },
415
+ stack: { type: "string", description: "start: comma-separated stack, e.g. 'wordpress, php'." },
416
+ units: {
417
+ type: "array",
418
+ maxItems: 40,
419
+ description: "start/plan: units of work — strings or {name, kind, dod[]}.",
420
+ items: { type: "object", additionalProperties: true, properties: { name: { type: "string" }, kind: { type: "string" }, dod: { type: "array", items: { type: "string" } } } },
421
+ },
422
+ product: {
423
+ type: "object",
424
+ additionalProperties: true,
425
+ description: "product: product brief — {audience:[{who,job}], pages:[], success:[{metric,target}], nonGoals:[], constraints:[]}. G0 needs it.",
426
+ },
427
+ plan: {
428
+ type: "object",
429
+ additionalProperties: true,
430
+ description: "plan: {steps:[{title,unit,dependsOn,size}], risks:[{title,likelihood,impact,mitigation}], blockers:[{title,severity,owner,open}]}. G2 needs it.",
431
+ },
432
+ pages: {
433
+ type: "array",
434
+ maxItems: 60,
435
+ description: "ia: [{url, template, sections:[], content: ready|todo|move|photo}] — writes docs/ia.md and plans units.",
436
+ items: { type: "object", additionalProperties: true, properties: { url: { type: "string" }, template: { type: "string" }, content: { type: "string" }, sections: { type: "array", items: { type: "string" } } } },
437
+ },
438
+ decision: { type: "string", description: "decision: dated ADR entry, appended to .dsh/design/decisions.md." },
439
+ close: { type: "string", description: "blockers: id of the blocker to close (b1, b2, …)." },
440
+ scan: { type: "boolean", description: "blockers: scan the project for mechanical blockers (default true)." },
441
+ brief: {
442
+ type: "object",
443
+ additionalProperties: true,
444
+ description: "brief: art direction — {palette:[{name,value}], typefaces:[], scale, rhythm, radii, motion, tone, references:[{url,date,take}]}.",
445
+ },
446
+ variants: {
447
+ type: "array",
448
+ maxItems: 5,
449
+ description: "brief: 2–3 directions {title, summary, chosen} — required by the two-variant trigger.",
450
+ items: { type: "object", additionalProperties: true, properties: { title: { type: "string" }, summary: { type: "string" }, chosen: { type: "boolean" } } },
451
+ },
452
+ choose: { type: "string", description: "brief: id or title of the chosen variant." },
453
+ release: {
454
+ type: "array",
455
+ maxItems: 30,
456
+ description: "start: release steps {title, command}; run them with action=release run=true, which closes G13.",
457
+ items: { type: "object", additionalProperties: true, required: ["title"], properties: { id: { type: "string" }, title: { type: "string" }, command: { type: "string" }, threshold: { type: "string" } } },
458
+ },
459
+ acceptance: {
460
+ type: "array",
461
+ maxItems: 40,
462
+ description: "start: acceptance checks {title, command, threshold}.",
463
+ items: { type: "object", additionalProperties: true, required: ["title"], properties: { id: { type: "string" }, title: { type: "string" }, command: { type: "string" }, threshold: { type: "string" } } },
464
+ },
465
+ invariants: { type: "string", description: "start: comma-separated project invariants." },
466
+ to: { type: "string", enum: PHASES, description: "phase: explicit target phase (default: next)." },
467
+ name: { type: "string", description: "unit/plan: unit name or id." },
468
+ status: { type: "string", enum: ["todo", "doing", "done", "blocked"], description: "unit: new status." },
469
+ id: { type: "string", description: "gate: G0..G12. evidence: optional gate id." },
470
+ unit: { type: "string", description: "gate: unit id for unit-scoped gates (G4, G5, G6)." },
471
+ pass: { type: "boolean", description: "gate: true (default) marks passed, false marks failed." },
472
+ evidence: { type: "string", description: "gate/unit: proof — command, metric or report path (≥12 chars for a gate)." },
473
+ note: { type: "string", description: "gate/evidence: free-form note." },
474
+ value: { type: "string", description: "evidence: metric value." },
475
+ kind: { type: "string", description: "evidence: record kind (audit, interact, a11y, perf, note…)." },
476
+ run: { type: "boolean", description: "accept: true actually runs the commands (default dry-run)." },
477
+ only: { type: "string", description: "accept: comma-separated check ids to run." },
478
+ force: { type: "boolean", description: "start: overwrite an existing mission." },
479
+ confirm: { type: "boolean", description: "reset: required to delete the mission." },
480
+ },
481
+ required: ["action"],
482
+ },
483
+ timeoutMs: 180_000,
484
+ output: {
485
+ schema: { type: "object", additionalProperties: true },
486
+ render(_args, value) {
487
+ const text = value && typeof value === "object" && typeof value.text === "string" ? value.text : JSON.stringify(value);
488
+ return [{ type: "text", text: text.length <= MAX_RENDER_CHARS ? text : `${text.slice(0, MAX_RENDER_CHARS)}\n…` }];
489
+ },
490
+ },
491
+ async execute(args, exec) {
492
+ const cwd = sessionCwd(exec);
493
+ const action = String(args?.action ?? "").trim().toLowerCase();
494
+ try {
495
+ if (!ACTIONS.includes(action)) return failure(`quality_gate: неизвестное действие «${action}». Доступно: ${ACTIONS.join(", ")}`);
496
+ if (action === "start") return startMission(cwd, args);
497
+ if (action === "status") return { ok: true, mission: readMission(cwd), text: formatStatus(readMission(cwd)) };
498
+ if (action === "list") {
499
+ const mission = readMission(cwd);
500
+ if (!mission) return failure("Миссии нет: quality_gate action=start task=\"…\"");
501
+ return { ok: true, mission, text: formatGateList(mission) };
502
+ }
503
+ if (action === "phase") return phaseAction(cwd, args);
504
+ if (action === "gate") return gateAction(cwd, args);
505
+ if (action === "accept") return await acceptAction(cwd, args);
506
+ if (action === "release") {
507
+ return await releaseAction({
508
+ cwd,
509
+ args,
510
+ deps: { readMission, writeMission, appendEvidence, passGate, failGate, runAcceptance, applyAcceptanceRows, formatAcceptance, parseList },
511
+ });
512
+ }
513
+ if (action === "brief") return briefAction(cwd, args);
514
+ if (["product", "ia", "decision", "blockers"].includes(action)) return preworkAction(cwd, args);
515
+ if (action === "plan") {
516
+ if (args?.name !== undefined || Array.isArray(args?.units)) return planAction(cwd, args);
517
+ return preworkAction(cwd, { ...args, action: "plan" });
518
+ }
519
+ if (action === "unit") return unitAction(cwd, args);
520
+ if (action === "evidence") return evidenceAction(cwd, args);
521
+ if (action === "reset") {
522
+ if (args?.confirm !== true) return failure("reset требует confirm=true: миссия и её гейты будут удалены");
523
+ const removed = deleteMission(cwd);
524
+ return { ok: true, text: removed ? "Миссия удалена (evidence.jsonl сохранён)." : "Миссии не было." };
525
+ }
526
+ return failure(`quality_gate: действие ${action} не реализовано`);
527
+ } catch (error) {
528
+ return failure(`quality_gate: ${error instanceof Error ? error.message : String(error)}`);
529
+ }
530
+ },
531
+ };
532
+ }
533
+
534
+ function missionOf(assemblyContext) {
535
+ try {
536
+ const cwd = assemblyContext?.agent?.session?.header?.cwd;
537
+ if (!cwd) return null;
538
+ const raw = readMission(cwd);
539
+ if (!raw) return null;
540
+ const checked = validateMission(raw);
541
+ return checked.ok ? checked.mission : null;
542
+ } catch {
543
+ return null;
544
+ }
545
+ }
546
+
547
+ export function apply(ctx) {
548
+ try {
549
+ const tool = makeToolDefinition();
550
+ const register = () => ctx.tools.register(tool);
551
+ if (typeof ctx.effect === "function") ctx.effect(register, "quality-pipeline: tool");
552
+ else register();
553
+ } catch (error) {
554
+ ctx.logger?.warn?.(`[quality-pipeline] tool registration failed: ${error instanceof Error ? error.message : String(error)}`);
555
+ }
556
+
557
+ /* Zero-config: a web project gets its mission on the first session, so the
558
+ * phase router and the strict UI gate work without a single setup step. */
559
+ for (const event of ["agent/created", "session/created"]) {
560
+ try {
561
+ ctx.effect(
562
+ () =>
563
+ ctx.on(event, (payload) => {
564
+ const cwd = payload?.agent?.session?.header?.cwd ?? payload?.session?.header?.cwd;
565
+ if (typeof cwd === "string" && cwd.length > 0) autoStartMission(cwd, ctx.logger);
566
+ }),
567
+ `quality-pipeline: auto-start (${event})`,
568
+ );
569
+ } catch (error) {
570
+ ctx.logger?.debug?.(`[quality-pipeline] ${event} hook unavailable: ${String(error)}`);
571
+ }
572
+ }
573
+
574
+ try {
575
+ ctx.systemPrompt.context({
576
+ name: "dsh-quality-pipeline: mission state",
577
+ order: 131,
578
+ interpolate: false,
579
+ required: false,
580
+ text: (assemblyContext) => formatPromptLine(missionOf(assemblyContext)),
581
+ });
582
+ } catch (error) {
583
+ ctx.logger?.warn?.(`[quality-pipeline] prompt context skipped: ${error instanceof Error ? error.message : String(error)}`);
584
+ }
585
+
586
+ /* Every browser_qa result becomes an evidence record: the trail is automatic. */
587
+ try {
588
+ ctx.effect(
589
+ () =>
590
+ ctx.on("tools/result", (exec, result) => {
591
+ if (exec?.name !== "browser_qa") return;
592
+ try {
593
+ const cwd = exec?.agent?.session?.header?.cwd;
594
+ if (!cwd) return;
595
+ const action = exec?.arguments?.action ?? exec?.args?.action ?? "";
596
+ const summary = typeof result?.text === "string" ? result.text.split("\n").find((line) => line.startsWith("Итог:")) ?? "" : "";
597
+ appendEvidence(cwd, { kind: `browser_qa:${action}`, value: String(result?.ok === false ? "error" : "ok"), note: summary.slice(0, 300) || String(exec?.arguments?.url ?? "").slice(0, 200) });
598
+ } catch {
599
+ /* evidence must never break a tool result */
600
+ }
601
+ }),
602
+ "quality-pipeline: evidence trail",
603
+ );
604
+ } catch (error) {
605
+ ctx.logger?.warn?.(`[quality-pipeline] evidence hook skipped: ${error instanceof Error ? error.message : String(error)}`);
606
+ }
607
+
608
+ try {
609
+ ctx.inject(["commands"], (child) => {
610
+ const dispose = child.commands.register({
611
+ name: "quality",
612
+ description: "Миссия качества: статус, фазы, приёмка",
613
+ input: { hint: "status | accept | next" },
614
+ recordInput: false,
615
+ handler: async ({ rawInput, agent }) => {
616
+ const cwd = agent?.session?.header?.cwd ?? process.cwd();
617
+ const mission = readMission(cwd);
618
+ const command = String(rawInput ?? "").trim().toLowerCase();
619
+ try {
620
+ if (!mission) return { kind: "error", text: "Миссии нет. Начните с tool quality_gate action=start task=\"…\"" };
621
+ if (command === "accept") {
622
+ const rows = await runAcceptance({ cwd, mission });
623
+ applyAcceptanceRows(mission, rows);
624
+ writeMission(cwd, mission);
625
+ return { kind: rows.every((row) => row.status === "pass") ? "success" : "error", text: formatAcceptance(rows) };
626
+ }
627
+ if (command === "next") {
628
+ const blocking = blockingWork(mission);
629
+ return { kind: "success", text: blocking.length > 0 ? blocking.join("\n") : "Блокеров нет: mission готова к handoff." };
630
+ }
631
+ return { kind: "success", text: formatStatus(mission) };
632
+ } catch (error) {
633
+ return { kind: "error", text: `/quality: ${error instanceof Error ? error.message : String(error)}` };
634
+ }
635
+ },
636
+ });
637
+ ctx.effect(() => dispose, "quality-pipeline: /quality command");
638
+ });
639
+ } catch (error) {
640
+ ctx.logger?.debug?.(`[quality-pipeline] commands unavailable: ${String(error)}`);
641
+ }
642
+
643
+ ctx.logger?.info?.(`[quality-pipeline] ready: ${GATES.length} gates, ${PHASES.length} phases`);
644
+ }
645
+
646
+ /** Exported for tests. */
647
+ export { makeToolDefinition, runAcceptance, readMission, writeMission, readEvidence };