dsh-desktop-kit 2.23.26 → 2.24.1

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.
@@ -42,9 +42,15 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
42
42
  if (!subagents || typeof subagents.startActivation !== "function") {
43
43
  throw new Error("subagents service is unavailable");
44
44
  }
45
- const providers = typeof subagents.list === "function" ? subagents.list() : [];
45
+ const listed = typeof subagents.list === "function" ? subagents.list() : [];
46
+ /* DSH 0.2.2-rc.3 removed provider enumeration from ctx.subagents; probe known
47
+ * provider names instead of failing every run. */
48
+ const probed = listed.length > 0 || typeof subagents.getProvider !== "function"
49
+ ? []
50
+ : ["spawn", "fork", "subagent-spawn-in-process"].filter((name) => subagents.getProvider(name));
51
+ const providers = listed.length > 0 ? listed : probed;
46
52
  const provider = providers.includes("spawn") ? "spawn" : providers[0];
47
- if (!provider) throw new Error("no subagent provider is registered");
53
+ if (!provider) throw new Error("no subagent provider is registered (spawn/fork not found; DSH 0.2.2-rc.3 hides providers from ctx.subagents.list())");
48
54
  const project = projectFor(exec?.agent?.session?.header?.cwd);
49
55
  const cwd = options.cwd ?? exec?.agent?.session?.header?.cwd;
50
56
  const isBackground = options.background === true;
@@ -72,20 +78,28 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
72
78
  "Task:",
73
79
  String(task ?? ""),
74
80
  ].filter((line) => line !== "").join("\n");
75
- const start = (selectedRoute) => subagents.startActivation({
76
- provider,
77
- label: `agent:${definition.name}`,
78
- childId: reservedId,
79
- request: {
81
+ /* DSH 0.2.2-rc.3 flattened the old nested `request` argument into the
82
+ * activation spec (and removed `subagents.list()`); support both shapes. */
83
+ const activationApi = typeof subagents.list === "function" ? "request" : "flat";
84
+ const start = (selectedRoute) => {
85
+ const request = {
80
86
  prompt: [{ type: "text", text: prompt }],
81
87
  parent: exec.agent,
82
88
  signal: controller.signal,
83
89
  cwd,
84
90
  ...(selectedRoute.model || selectedRoute.reasoningEffort ? { agentOptions: agentOptionsFor(selectedRoute) } : {}),
85
- },
86
- signal: controller.signal,
87
- delivery: "caller",
88
- });
91
+ };
92
+ const base = {
93
+ provider,
94
+ label: `agent:${definition.name}`,
95
+ childId: reservedId,
96
+ signal: controller.signal,
97
+ delivery: "caller",
98
+ };
99
+ return activationApi === "request"
100
+ ? subagents.startActivation({ ...base, request })
101
+ : subagents.startActivation({ ...base, ...request });
102
+ };
89
103
  try {
90
104
  activation = await start(route);
91
105
  } catch (error) {
@@ -122,8 +136,19 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
122
136
  };
123
137
  upsertRun(project.root, record);
124
138
  remember(record, activation, project.root, signal, abort);
139
+ /* DSH disposes the child session at settlement, so hold the live session
140
+ * now: otherwise the transcript save finds nothing and silently skips. */
141
+ let childSession = null;
142
+ try {
143
+ childSession = ctx.get?.("agents")?.get?.(String(activeId))?.session
144
+ ?? ctx.get?.("sessions")?.get?.(String(activeId))
145
+ ?? null;
146
+ } catch { childSession = null; }
147
+ const saveRunTranscript = () => {
148
+ try { saveTranscript(project.root, record.id, childSession ?? ctx.get("sessions")?.get(activeId)); } catch { /* best effort */ }
149
+ };
125
150
  activation.result.then(async (result) => {
126
- try { saveTranscript(project.root, record.id, ctx.get("sessions")?.get(activeId)); } catch { /* best effort */ }
151
+ saveRunTranscript();
127
152
  const currentRecord = loadRuns(project.root).find((item) => item.id === record.id);
128
153
  if (currentRecord?.status !== "canceled") {
129
154
  const text = textFromOutput(result?.output);
@@ -140,7 +165,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
140
165
  background.delete(record.id);
141
166
  signal?.removeEventListener?.("abort", abort);
142
167
  }).catch((error) => {
143
- try { saveTranscript(project.root, record.id, ctx.get("sessions")?.get(activeId)); } catch { /* best effort */ }
168
+ saveRunTranscript();
144
169
  const currentRecord = loadRuns(project.root).find((item) => item.id === record.id);
145
170
  if (currentRecord?.status !== "canceled") {
146
171
  finishRun(project.root, record.id, {
@@ -57,6 +57,9 @@ function withLock(root, operation) {
57
57
  const lock = path.join(dir, "board.lock");
58
58
  const started = Date.now();
59
59
  const sleeper = new Int32Array(new SharedArrayBuffer(4));
60
+ /* Windows reports a contended lock as EPERM/EACCES/EBUSY, not only EEXIST
61
+ (antivirus, concurrent workers, a handle still open). Retry them all. */
62
+ const RETRY_CODES = new Set(["EEXIST", "EPERM", "EACCES", "EBUSY"]);
60
63
  while (true) {
61
64
  try {
62
65
  const fd = fs.openSync(lock, "wx");
@@ -68,13 +71,16 @@ function withLock(root, operation) {
68
71
  try { fs.unlinkSync(lock); } catch { /* best effort */ }
69
72
  }
70
73
  } catch (error) {
71
- if (error?.code !== "EEXIST") throw error;
72
- try {
73
- const age = Date.now() - fs.statSync(lock).mtimeMs;
74
- if (age > 30_000) fs.unlinkSync(lock);
75
- } catch { /* lock vanished */ }
74
+ if (!RETRY_CODES.has(error?.code)) throw error;
75
+ if (error?.code === "EEXIST") {
76
+ try {
77
+ const age = Date.now() - fs.statSync(lock).mtimeMs;
78
+ if (age > 30_000) fs.unlinkSync(lock);
79
+ } catch { /* lock vanished */ }
80
+ }
76
81
  if (Date.now() - started > 5_000) throw new Error("board is busy; lock timeout");
77
- Atomics.wait(sleeper, 0, 0, 25);
82
+ /* Jitter keeps concurrent workers from retrying in lockstep. */
83
+ Atomics.wait(sleeper, 0, 0, 20 + Math.floor(Math.random() * 30));
78
84
  }
79
85
  }
80
86
  }
@@ -18,7 +18,9 @@ const EXTERNAL = [
18
18
  /(?:latest|current|price|pricing|version|release|docs?|documentation|rfc|standard|benchmark|cve)/iu,
19
19
  /(?:последн|актуальн|цен|тариф|верси|релиз|документац|стандарт|бенчмарк|уязвим)/iu,
20
20
  ];
21
- const MULTI = [/\b(?:and|plus|also)\b/iu, /(?:^|\s)(?:и|плюс|также)(?:\s|$)/iu];
21
+ /* A bare Russian "и" is far too common to signal several areas: "проверь X и Y"
22
+ * is one question. Only explicit "plus/also" (or the English equivalents) count. */
23
+ const MULTI = [/\b(?:and|plus|also)\b/iu, /(?:^|\s)(?:плюс|также)(?:\s|$)/iu];
22
24
 
23
25
  export function loadSwarmOptions(projectRoot) {
24
26
  try {
@@ -50,7 +50,7 @@ function makeToolDefinition() {
50
50
  return {
51
51
  name: TOOL_NAME,
52
52
  description:
53
- "Headless-Chrome quality checks without Playwright. status: detect Chrome and its version. shot: open an http(s) URL or local HTML file, set the viewport, save a PNG and return its path/size. audit: load the page at responsive widths (default 390/768/1440) and report horizontal overflow (documentElement.scrollWidth vs clientWidth), the overflowing elements, console errors, markup/accessibility issues (missing alt, unlabeled fields, nameless links/buttons, duplicate ids, heading order, lang/title/viewport, positive tabindex), and optionally one PNG per width (pass outDir). Uses the Chrome DevTools protocol over a temporary profile; no external network calls beyond the page itself.",
53
+ "Headless-Chrome quality checks without Playwright. status: detect Chrome and its version. shot: open an http(s) URL or local HTML file, set the viewport, save a PNG and return its path/size. audit: load the page at responsive viewports (matrix 'full' = phone 390x844 and 844x390, tablet 768x1024 and 1024x768, desktop 1440x900; default 390/768/1440) and report horizontal overflow (documentElement.scrollWidth vs clientWidth), the overflowing elements, per-viewport device labels, console errors, markup/accessibility issues (missing alt, unlabeled fields, nameless links/buttons, duplicate ids, heading order, lang/title/viewport, positive tabindex), and optionally one PNG per viewport (pass outDir). Uses the Chrome DevTools protocol over a temporary profile; no external network calls beyond the page itself.",
54
54
  parameters: {
55
55
  type: "object",
56
56
  additionalProperties: false,
@@ -71,6 +71,27 @@ function makeToolDefinition() {
71
71
  items: { type: "integer" },
72
72
  description: "Audit widths in CSS px (default [390, 768, 1440], at most 6 values).",
73
73
  },
74
+ matrix: {
75
+ type: "string",
76
+ enum: ["default", "full"],
77
+ description:
78
+ "audit: 'full' covers the responsive matrix — phone 390x844 and 844x390, tablet 768x1024 and 1024x768, desktop 1440x900. Use it for any UI change.",
79
+ },
80
+ viewports: {
81
+ type: "array",
82
+ maxItems: 6,
83
+ description: "audit: explicit {width, height} pairs; overrides widths and matrix (at most 6).",
84
+ items: {
85
+ type: "object",
86
+ additionalProperties: false,
87
+ required: ["width", "height"],
88
+ properties: {
89
+ width: { type: "integer" },
90
+ height: { type: "integer" },
91
+ label: { type: "string" },
92
+ },
93
+ },
94
+ },
74
95
  outDir: {
75
96
  type: "string",
76
97
  description:
@@ -126,6 +147,8 @@ function makeToolDefinition() {
126
147
  return await auditPages({
127
148
  target: args.url,
128
149
  widths,
150
+ matrix: args?.matrix,
151
+ viewports: args?.viewports,
129
152
  height: viewport.height,
130
153
  fullPage: args?.fullPage === true,
131
154
  outDir: hasOutDir ? args.outDir : null,
@@ -17,6 +17,7 @@ import {
17
17
  MARKUP_EXPRESSION,
18
18
  OVERFLOW_EXPRESSION,
19
19
  PAGE_INFO_EXPRESSION,
20
+ RESPONSIVE_MATRIX,
20
21
  SETTLE_EXPRESSION,
21
22
  abortError,
22
23
  consoleEventFromCdp,
@@ -28,6 +29,7 @@ import {
28
29
  normalizeTarget,
29
30
  normalizeViewport,
30
31
  parseTimeout,
32
+ parseViewports,
31
33
  parseWidths,
32
34
  pngSize,
33
35
  resolveOutDir,
@@ -36,6 +38,7 @@ import {
36
38
  shapeMarkupReport,
37
39
  shapeOverflowReport,
38
40
  summarizeAudit,
41
+ deviceLabel,
39
42
  } from "./qa.js";
40
43
 
41
44
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -416,20 +419,36 @@ export async function captureShot(options = {}) {
416
419
  */
417
420
  export async function auditPages(options = {}) {
418
421
  const { cwd, target } = normalizeOptions(options);
419
- const widths = parseWidths(options.widths);
420
- const { height } = normalizeViewport(options);
422
+ const { height: singleHeight } = normalizeViewport(options);
423
+ const explicit = parseViewports(options.viewports);
424
+ const viewports =
425
+ explicit.length > 0
426
+ ? explicit
427
+ : String(options.matrix ?? "").trim().toLowerCase() === "full"
428
+ ? RESPONSIVE_MATRIX.map((viewport) => ({
429
+ width: viewport.width,
430
+ height: viewport.height,
431
+ label: deviceLabel(viewport.width, viewport.height),
432
+ }))
433
+ : parseWidths(options.widths).map((width) => ({
434
+ width,
435
+ height: singleHeight,
436
+ label: deviceLabel(width, singleHeight),
437
+ }));
438
+ const widths = viewports.map((viewport) => viewport.width);
421
439
  const timeoutMs = parseTimeout(options.timeoutMs);
422
440
  const screenshots = options.screenshots === true || (typeof options.outDir === "string" && options.outDir.trim().length > 0);
423
441
  const outDir = screenshots ? resolveOutDir(options.outDir, cwd) : null;
424
442
  if (outDir !== null) await fsp.mkdir(outDir, { recursive: true });
425
- const budgetMs = Math.min(AUDIT_BUDGET_MS, timeoutMs * widths.length + 25_000);
443
+ const budgetMs = Math.min(AUDIT_BUDGET_MS, timeoutMs * viewports.length + 25_000);
426
444
  return withSession(options, async ({ session, page }) => {
427
445
  const deadline = Date.now() + budgetMs;
428
446
  const reports = [];
429
- for (const width of widths) {
447
+ for (const viewport of viewports) {
448
+ const { width, height, label } = viewport;
430
449
  if (options.signal?.aborted) throw abortError();
431
450
  if (Date.now() >= deadline) {
432
- reports.push({ width, height, skipped: true, reason: "time budget exhausted" });
451
+ reports.push({ width, height, deviceLabel: label, skipped: true, reason: "time budget exhausted" });
433
452
  continue;
434
453
  }
435
454
  page.console.reset();
@@ -463,6 +482,7 @@ export async function auditPages(options = {}) {
463
482
  reports.push({
464
483
  width,
465
484
  height,
485
+ deviceLabel: label,
466
486
  viewport: overflow.viewport,
467
487
  horizontalOverflow: overflow.horizontalOverflow,
468
488
  overflowingElements: overflow.overflowingElements,
@@ -478,7 +498,7 @@ export async function auditPages(options = {}) {
478
498
  });
479
499
  } catch (error) {
480
500
  if (isAbortError(error) || options.signal?.aborted) throw abortError();
481
- reports.push({ width, height, error: errorMessage(error) });
501
+ reports.push({ width, height, deviceLabel: label, error: errorMessage(error) });
482
502
  }
483
503
  }
484
504
  const result = {
@@ -493,7 +513,8 @@ export async function auditPages(options = {}) {
493
513
  chrome: session.chromeInfo(),
494
514
  outDir,
495
515
  widths,
496
- height,
516
+ viewports,
517
+ height: viewports[0]?.height ?? singleHeight,
497
518
  reports,
498
519
  summary: summarizeAudit(reports),
499
520
  };
@@ -14,6 +14,48 @@ import { fileURLToPath, pathToFileURL } from "node:url";
14
14
  export const DEFAULT_WIDTHS = Object.freeze([390, 768, 1440]);
15
15
  export const DEFAULT_VIEWPORT = Object.freeze({ width: 1440, height: 900 });
16
16
 
17
+ /**
18
+ * The responsive matrix an audit must cover for UI work: phones and tablets in
19
+ * both orientations, plus desktop. `matrix: "full"` expands to these pairs.
20
+ */
21
+ export const RESPONSIVE_MATRIX = Object.freeze([
22
+ { width: 390, height: 844 },
23
+ { width: 844, height: 390 },
24
+ { width: 768, height: 1024 },
25
+ { width: 1024, height: 768 },
26
+ { width: 1440, height: 900 },
27
+ ]);
28
+
29
+ /** Orientation classes the UI gate insists on before a turn may close. */
30
+ export const REQUIRED_ORIENTATIONS = Object.freeze([
31
+ "phone-portrait",
32
+ "phone-landscape",
33
+ "tablet-portrait",
34
+ "tablet-landscape",
35
+ ]);
36
+
37
+ /** WCAG 1.4.10 reflow floor: 320 CSS px is what a 1280 px viewport becomes at 400% zoom. */
38
+ export const REFLOW_FLOOR_WIDTH = 320;
39
+
40
+ export function deviceClassOf(width, height) {
41
+ // A landscape phone is wide but short, so the short side decides "phone";
42
+ // above that the CSS width separates tablets from desktop.
43
+ const short = Math.min(width, height);
44
+ if (short <= 500) return "phone";
45
+ if (width <= 1200) return "tablet";
46
+ return "desktop";
47
+ }
48
+
49
+ export function orientationOf(width, height) {
50
+ return width > height ? "landscape" : "portrait";
51
+ }
52
+
53
+ /** `phone-portrait`, `tablet-landscape`, `desktop` — the label the gate reads. */
54
+ export function deviceLabel(width, height) {
55
+ const device = deviceClassOf(width, height);
56
+ return device === "desktop" ? "desktop" : `${device}-${orientationOf(width, height)}`;
57
+ }
58
+
17
59
  export const LIMITS = Object.freeze({
18
60
  minWidth: 200,
19
61
  maxWidth: 3840,
@@ -68,6 +110,28 @@ export function parseWidths(widths, fallback = DEFAULT_WIDTHS) {
68
110
  return result.length > 0 ? result : [...fallback];
69
111
  }
70
112
 
113
+ /**
114
+ * Explicit audit viewports: `{width, height}` pairs clamped to the viewport
115
+ * range, de-duplicated, at most six. Invalid entries are dropped; an empty
116
+ * result means "use the widths/matrix path".
117
+ */
118
+ export function parseViewports(viewports) {
119
+ const source = Array.isArray(viewports) ? viewports : [];
120
+ const seen = new Set();
121
+ const result = [];
122
+ for (const raw of source) {
123
+ if (result.length >= LIMITS.maxWidths) break;
124
+ const width = clampInt(raw?.width, LIMITS.minWidth, LIMITS.maxWidth, null);
125
+ const height = clampInt(raw?.height, LIMITS.minHeight, LIMITS.maxHeight, null);
126
+ if (width === null || height === null) continue;
127
+ const key = `${width}x${height}`;
128
+ if (seen.has(key)) continue;
129
+ seen.add(key);
130
+ result.push({ width, height, label: deviceLabel(width, height) });
131
+ }
132
+ return result;
133
+ }
134
+
71
135
  export function parseTimeout(value, fallback = LIMITS.defaultTimeoutMs) {
72
136
  return clampInt(value, LIMITS.minTimeoutMs, LIMITS.maxTimeoutMs, fallback);
73
137
  }
@@ -695,7 +759,18 @@ export function summarizeAudit(reports = []) {
695
759
  const list = Array.isArray(reports) ? reports : [];
696
760
  const measured = list.filter((report) => report && report.error === undefined && report.skipped !== true);
697
761
  const failed = list.filter((report) => report && typeof report.error === "string");
762
+ const orientations = [
763
+ ...new Set(
764
+ measured
765
+ .map((report) => report.deviceLabel)
766
+ .filter((label) => typeof label === "string" && label.length > 0),
767
+ ),
768
+ ];
769
+ const missingOrientations = REQUIRED_ORIENTATIONS.filter((label) => !orientations.includes(label));
698
770
  return {
771
+ orientations,
772
+ missingOrientations,
773
+ matrixComplete: missingOrientations.length === 0,
699
774
  widthsRequested: list.length,
700
775
  widthsChecked: measured.length,
701
776
  widthsWithOverflow: measured.filter((report) => report.horizontalOverflow?.hasOverflow === true).length,
@@ -771,7 +846,7 @@ export function formatAuditText(report = {}) {
771
846
  ];
772
847
  if (item.loadTimedOut === true) bits.push("load timeout");
773
848
  if (typeof item.screenshot?.path === "string") bits.push(`PNG: ${item.screenshot.path}`);
774
- lines.push(`- ${item.width}px: ${bits.join(", ")}`);
849
+ lines.push(`- ${item.width}px: ${bits.join(", ")}${typeof item.deviceLabel === "string" ? ` [${item.deviceLabel}]` : ""}`);
775
850
  if (Array.isArray(markup.issues) && markup.issues.length > 0) {
776
851
  const top = markup.issues.slice(0, 3).map((issue) => `${issue.rule}${issue.selector ? ` (${issue.selector})` : ""}`);
777
852
  lines.push(` markup: ${top.join("; ")}${markup.total > top.length ? `; ещё ${markup.total - top.length}` : ""}`);
@@ -779,9 +854,15 @@ export function formatAuditText(report = {}) {
779
854
  if (typeof item.markupError === "string") lines.push(` markup: ошибка проверки — ${item.markupError}`);
780
855
  }
781
856
  const summary = report.summary ?? {};
857
+ const checkedOrientations = Array.isArray(summary.orientations) ? summary.orientations : [];
858
+ lines.push(
859
+ `Покрытие: ${REQUIRED_ORIENTATIONS.map((label) => `${label} ${checkedOrientations.includes(label) ? "✓" : "✗"}`).join(" · ")}` +
860
+ ` (matrix ${REQUIRED_ORIENTATIONS.filter((label) => checkedOrientations.includes(label)).length}/${REQUIRED_ORIENTATIONS.length})`,
861
+ );
782
862
  lines.push(
783
863
  `Итог: overflow на ${summary.widthsWithOverflow ?? 0} из ${summary.widthsChecked ?? 0} ширин · ` +
784
864
  `console errors: ${summary.consoleErrors ?? 0} · markup: ${summary.markupIssues ?? 0}` +
865
+ (summary.matrixComplete === true ? " · matrix: полная" : " · matrix: НЕ ПОЛНАЯ") +
785
866
  (report.outDir ? ` · PNG: ${report.outDir}` : ""),
786
867
  );
787
868
  if (report.warnings && report.warnings.length > 0) lines.push(`Предупреждения: ${report.warnings.join("; ")}`);
@@ -8,6 +8,7 @@
8
8
  * accidental infinite turn.
9
9
  */
10
10
  import crypto from "node:crypto";
11
+ import { REQUIRED_ORIENTATIONS } from "./qa.js";
11
12
 
12
13
  const UI_FILE = /\.(?:html?|xhtml|css|scss|sass|less|jsx|tsx|vue|svelte|astro|mdx)$/iu;
13
14
  const SKIP_PATH = /(?:^|[\\/])(?:node_modules|\.git|\.dsh|dist|build|coverage|qa)(?:[\\/]|$)/iu;
@@ -63,6 +64,12 @@ function auditFromText(result) {
63
64
  if (result?.isError === true) return null;
64
65
  const text = resultText(result);
65
66
  if (!text.includes("browser_qa audit:")) return null;
67
+ const coverage = text.match(/Покрытие: ([^\n]+)/u);
68
+ const orientations = coverage
69
+ ? [...coverage[1].matchAll(/(phone-portrait|phone-landscape|tablet-portrait|tablet-landscape)\s*(✓|✗)/gu)]
70
+ .filter((match) => match[2] === "✓")
71
+ .map((match) => match[1])
72
+ : [];
66
73
  const summary = text.match(/Итог: overflow на (\d+) из (\d+)[^\n]*console errors: (\d+)[^\n]*markup: (\d+)/iu);
67
74
  if (summary) {
68
75
  return {
@@ -72,6 +79,8 @@ function auditFromText(result) {
72
79
  widthsChecked: Number(summary[2]),
73
80
  consoleErrors: Number(summary[3]),
74
81
  markupIssues: Number(summary[4]),
82
+ orientations,
83
+ matrixComplete: REQUIRED_ORIENTATIONS.every((label) => orientations.includes(label)),
75
84
  },
76
85
  };
77
86
  }
@@ -84,14 +93,24 @@ function auditFromText(result) {
84
93
  widthsChecked: rows.length,
85
94
  consoleErrors: rows.reduce((sum, row) => sum + Number(row[3]), 0),
86
95
  markupIssues: rows.reduce((sum, row) => sum + Number(row[4]), 0),
96
+ orientations,
97
+ matrixComplete: REQUIRED_ORIENTATIONS.every((label) => orientations.includes(label)),
87
98
  },
88
99
  };
89
100
  }
90
101
 
102
+ /**
103
+ * A clean audit means zero overflow, console and markup issues *and* coverage
104
+ * of every required orientation. Phones and tablets in both orientations are
105
+ * the contract; a 3-width desktop-centred pass is not clean.
106
+ */
91
107
  function cleanAudit(summary) {
92
108
  const checked = Number(summary?.widthsChecked ?? 1);
109
+ const orientations = Array.isArray(summary?.orientations) ? summary.orientations : [];
110
+ const matrixComplete = REQUIRED_ORIENTATIONS.every((label) => orientations.includes(label));
93
111
  return (
94
112
  checked > 0 &&
113
+ matrixComplete &&
95
114
  Number(summary?.widthsWithOverflow ?? 0) === 0 &&
96
115
  Number(summary?.consoleErrors ?? 0) === 0 &&
97
116
  Number(summary?.markupIssues ?? 0) === 0
@@ -100,7 +119,9 @@ function cleanAudit(summary) {
100
119
 
101
120
  function summaryText(summary) {
102
121
  if (!summary) return "audit ещё не запускался";
103
- return `audit: overflow ${summary.widthsWithOverflow ?? "?"} · console ${summary.consoleErrors ?? "?"} · markup ${summary.markupIssues ?? "?"}`;
122
+ const orientations = Array.isArray(summary?.orientations) ? summary.orientations : [];
123
+ const coverage = REQUIRED_ORIENTATIONS.filter((label) => orientations.includes(label)).length;
124
+ return `audit: overflow ${summary.widthsWithOverflow ?? "?"} · console ${summary.consoleErrors ?? "?"} · markup ${summary.markupIssues ?? "?"} · matrix ${coverage}/${REQUIRED_ORIENTATIONS.length}`;
104
125
  }
105
126
 
106
127
  export function createUiGate(ctx) {
@@ -169,8 +190,9 @@ export function createUiGate(ctx) {
169
190
  "<ui-gate>",
170
191
  `Изменены UI-файлы: ${files}.`,
171
192
  `Последний ${summaryText(state.summary)}.`,
172
- "Ход не закрыт: запусти browser_qa action=audit для этой страницы/файла на 390/768/1440 (лучше с outDir), исправь overflow, console errors и markup (alt, label, duplicate id, heading order).",
173
- "После исправлений снова запусти audit. Не заявляй «готово», пока audit не станет чистым.",
193
+ "Ход не закрыт: запусти browser_qa action=audit matrix=full (телефон 390×844 и 844×390, планшет 768×1024 и 1024×768, десктоп 1440×900; лучше с outDir).",
194
+ "Overflow проверяй отдельно на каждой ширине и ориентации: назови элементы-виновники, почини, прогони audit заново.",
195
+ "Исправь также console errors и markup (alt, label, duplicate id, heading order). Не заявляй «готово», пока audit не чистый и покрытие не 4/4.",
174
196
  "</ui-gate>",
175
197
  ].join("\n");
176
198
  try {
@@ -1387,19 +1387,25 @@ ${summary}
1387
1387
  let activation;
1388
1388
  try {
1389
1389
  const prompt = buildCuratorPrompt(project, session, entry, reason);
1390
- activation = subagents.startActivation({
1390
+ const curatorRequest = {
1391
+ parent: agent,
1392
+ prompt: [{ type: "text", text: prompt }],
1393
+ cwd: project.roots[0],
1394
+ agentPreset: "standard",
1395
+ maxDepth: 1,
1396
+ };
1397
+ const curatorBase = {
1391
1398
  provider: "spawn",
1392
1399
  label: "project-memory curator",
1393
1400
  delivery: "caller",
1394
1401
  signal: controller.signal,
1395
- request: {
1396
- parent: agent,
1397
- prompt: [{ type: "text", text: prompt }],
1398
- cwd: project.roots[0],
1399
- agentPreset: "standard",
1400
- maxDepth: 1,
1401
- },
1402
- });
1402
+ };
1403
+ /* DSH 0.2.2-rc.3 flattened the nested `request` into the activation spec. */
1404
+ activation = subagents.startActivation(
1405
+ typeof subagents.list === "function"
1406
+ ? { ...curatorBase, request: curatorRequest }
1407
+ : { ...curatorBase, ...curatorRequest },
1408
+ );
1403
1409
  logAccess(`curator-start session=${sessionId} child=${String(activation.childId)} project=${project.slug}`);
1404
1410
  const result = await activation.result;
1405
1411
  const output = typeof result?.output === "string" ? result.output.replace(/\s+/gu, " ").trim() : "";
@@ -36,15 +36,25 @@ function readKitSettings() {
36
36
  }
37
37
 
38
38
  function qualityContractText() {
39
- const full = [
39
+ const researchFirst = readKitSettings().researchFirst !== false;
40
+ const clauses = [
41
+ researchFirst
42
+ ? "0) Референс сначала: перед задачей собери 2+ реально существующих примера и практики (аналогичные сайты и платформы, галереи, официальные доки) — с датой и ссылкой; для рекомендаций дай 2–3 варианта и объясни выбор."
43
+ : "0) Внешние факты — только web_search/web_fetch: 2+ независимых источника со ссылкой и датой.",
44
+ "1) UI всегда премиального уровня: сетка 4/8, дизайн-токены, типографическая шкала, все состояния (default, hover, focus-visible, active, disabled, loading, empty, error, success), подсказки рядом с полями.",
45
+ "2) Адаптив всегда: десктоп, планшет (портрет и ландшафт), телефон (портрет и ландшафт). «Только 1440» — брак.",
46
+ "3) OVERFLOW проверяй отдельно на КАЖДОЙ ширине и ориентации: browser_qa action=audit matrix=full, назови элементы-виновники, почини, прогони заново. Отдельный прогон обязателен, даже если «выглядит нормально».",
47
+ "4) Типографика и подсказки по делу: helper text, единицы, примеры; пустые и ошибочные состояния — полноценные экраны, а не заглушки.",
48
+ "5) Качество премиальное: контраст 4.5:1, видимый focus, тап-таргеты ≥44px, движение 150–250 мс с prefers-reduced-motion, у кнопок и ссылок понятные имена.",
49
+ "6) Тестируй всё: программные тесты + браузер; правь и тестируй снова, пока не чисто. «Готово» без прогонов не существует.",
50
+ "7) Инструменты по делу: один нужный навык (UI — wow-design/ui-craft, проверка — visual-qa, референсы — web-research), код — repo_map/checkpoint; если проверить нельзя — скажи честно.",
51
+ ];
52
+ return [
40
53
  "<quality-contract>",
41
- "Работай как топовый агент: 1) ПЕРЕД любой задачей — короткий web_search/web_fetch по лучшим мировым практикам и референсам; даже локальную задачу проверь на более качественный современный подход; 2) дай 2+ независимых источника, дату и ссылки; 3) для рекомендаций предложи 2–3 конкретных референса/варианта и объясни выбор; 4) внешние claims — research_ledger, проверка ссылок и дат перед выводами; 5) UI: до правок — wow-design/ui-craft, после — browser_qa audit 390/768/1440, исправь overflow, console errors и markup (alt, labels, duplicate id, heading order), приложи скриншоты; 6) код — repo_map/checkpoint/план/тесты; 7) не заявляй «готово» без проверки; если проверить нельзя — скажи честно.",
54
+ "Правила действуют в каждом проекте и каждом пресете.",
55
+ ...clauses,
42
56
  "</quality-contract>",
43
57
  ].join("\n");
44
- if (readKitSettings().researchFirst === false) {
45
- return full.replace("1) ПЕРЕД любой задачей — короткий web_search/web_fetch по лучшим мировым практикам и референсам; даже локальную задачу проверь на более качественный современный подход; 2) дай 2+ независимых источника, дату и ссылки; 3) для рекомендаций предложи 2–3 конкретных референса/варианта и объясни выбор; 4) внешние claims — research_ledger, проверка ссылок и дат перед выводами;", "1) внешние факты — web_search/web_fetch, 2+ источника со ссылками и датами; 2) для рекомендаций — 2–3 варианта с обоснованием;");
46
- }
47
- return full;
48
58
  }
49
59
  let skillMetaCache = { at: 0, map: new Map() };
50
60
 
@@ -69,7 +79,7 @@ const RULES = [
69
79
  id: "quality",
70
80
  label: "Качество UI",
71
81
  any: ["отступ", "адаптив", "горизонт", "overflow", "скриншот", "мобил", "планшет", "поехал", "съехал", "вёрстк", "верстк"],
72
- skills: ["ui-craft", "visual-qa"],
82
+ skills: ["web-quality", "ui-craft", "visual-qa"],
73
83
  },
74
84
  {
75
85
  id: "markup",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "kitVersion": "2.23.17",
4
- "generatedAt": "2026-11-12T18:27:10.256Z",
3
+ "kitVersion": "2.24.1",
4
+ "generatedAt": "2026-11-23T05:44:44.821Z",
5
5
  "skills": {
6
6
  "code-review-checklist": {
7
7
  "hash": "e665bf72cfbfb77948a3cd6df6ebced38777f9aff543d7b9c80b2ced8cccc662",
@@ -84,9 +84,9 @@
84
84
  "bytes": 4257
85
85
  },
86
86
  "seo": {
87
- "hash": "4e2a6a3c960fa51edbdac0467d41ea023be37a50afb67b03c0474f33adfb6fc6",
87
+ "hash": "ed48ebc4c1278f857ff430f9a5ec55f638c2f9ba07cc406185cfb94be18ee80d",
88
88
  "files": 29,
89
- "bytes": 386399
89
+ "bytes": 386169
90
90
  },
91
91
  "service-desk-conventions": {
92
92
  "hash": "22ae6c29b7debb0154d183bc732795b67557aeaa0ac906d7b038134aea8ba39a",
@@ -143,15 +143,20 @@
143
143
  "files": 2,
144
144
  "bytes": 4118
145
145
  },
146
+ "web-quality": {
147
+ "hash": "9cffe064faac7ec5763d4644c52e28e7993adca633e0ad92bbd4a88c67ceee23",
148
+ "files": 1,
149
+ "bytes": 5692
150
+ },
146
151
  "web-research": {
147
152
  "hash": "9bf4d8ba6d2a0fc39c241cdd9f5fe54835af28872473aa617941589c526387c8",
148
153
  "files": 3,
149
154
  "bytes": 14150
150
155
  },
151
156
  "wow-design": {
152
- "hash": "bba0d65db46c89d971eed43e7cd934f59752c062795a4e0d3d345d7313640e48",
157
+ "hash": "81139f32fc759f438a36eb4c0212ed3ea17df9d8075e909580e12bc47a0848dd",
153
158
  "files": 52,
154
- "bytes": 918621
159
+ "bytes": 913669
155
160
  }
156
161
  }
157
162
  }