dsh-desktop-kit 2.31.0 → 2.34.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.
@@ -30,7 +30,7 @@ const AGENT_TEMPLATES = {
30
30
  "---",
31
31
  "name: reviewer",
32
32
  "description: Ревью диффа, тестов и рисков. Возвращает только findings.",
33
- "tools: read, grep, glob, browser_qa, team_board, team_message",
33
+ "tools: read, grep, glob, browser_qa, read_image, web_fetch, skill, team_board, team_message",
34
34
  "permission: read-only",
35
35
  "---",
36
36
  "",
@@ -41,7 +41,7 @@ const AGENT_TEMPLATES = {
41
41
  "---",
42
42
  "name: researcher",
43
43
  "description: Исследует документацию и практики по внешним источникам, не меняет код.",
44
- "tools: read, grep, glob, web_search, web_fetch, browser_qa, team_board, team_message",
44
+ "tools: read, grep, glob, web_search, web_fetch, browser_qa, read_image, skill, team_board, team_message",
45
45
  "permission: read-only",
46
46
  "---",
47
47
  "",
@@ -52,7 +52,7 @@ const AGENT_TEMPLATES = {
52
52
  "---",
53
53
  "name: tester",
54
54
  "description: Запускает тесты и проверки в рабочей папке, разбирает падения.",
55
- "tools: read, grep, glob, bash, pwsh, browser_qa, team_board, team_message",
55
+ "tools: read, grep, glob, bash, pwsh, browser_qa, read_image, skill, team_board, team_message",
56
56
  "permission: workspace-write",
57
57
  "---",
58
58
  "",
@@ -63,7 +63,7 @@ const AGENT_TEMPLATES = {
63
63
  "---",
64
64
  "name: coordinator",
65
65
  "description: Координирует рой: читает board, назначает задачи, пишет участникам.",
66
- "tools: read, grep, repo_map, browser_qa, team_board, team_message",
66
+ "tools: read, grep, glob, repo_map, browser_qa, read_image, web_fetch, skill, list_agents, team_board, team_message",
67
67
  "permission: read-only",
68
68
  "---",
69
69
  "",
@@ -74,7 +74,7 @@ const AGENT_TEMPLATES = {
74
74
  "---",
75
75
  "name: verifier",
76
76
  "description: Проверяет claims, ссылки, даты и тесты; возвращает structured findings.",
77
- "tools: read, grep, glob, repo_map, web_fetch, browser_qa, research_ledger, team_board, team_message",
77
+ "tools: read, grep, glob, repo_map, web_fetch, browser_qa, read_image, research_ledger, skill, team_board, team_message",
78
78
  "model: deepseek-v4-pro",
79
79
  "permission: read-only",
80
80
  "output: findings",
@@ -87,7 +87,7 @@ const AGENT_TEMPLATES = {
87
87
  "---",
88
88
  "name: synthesizer",
89
89
  "description: Сводит findings команды в единый PASS/FAIL без дублей.",
90
- "tools: read, repo_map, research_ledger, team_board, team_message",
90
+ "tools: read, repo_map, research_ledger, web_fetch, skill, team_board, team_message",
91
91
  "model: deepseek-v4-pro",
92
92
  "permission: read-only",
93
93
  "output: findings",
@@ -100,7 +100,7 @@ const AGENT_TEMPLATES = {
100
100
  "---",
101
101
  "name: security",
102
102
  "description: Ищет уязвимости, секреты, права и опасные дефолты; не меняет код.",
103
- "tools: read, grep, glob, repo_map, guardrails, team_board, team_message",
103
+ "tools: read, grep, glob, repo_map, guardrails, web_fetch, skill, team_board, team_message",
104
104
  "model: deepseek-v4-pro",
105
105
  "permission: read-only",
106
106
  "output: findings",
@@ -113,7 +113,7 @@ const AGENT_TEMPLATES = {
113
113
  "---",
114
114
  "name: performance",
115
115
  "description: Ищет узкие места, лишние запросы и регрессии производительности.",
116
- "tools: read, grep, glob, repo_map, browser_qa, team_board, team_message",
116
+ "tools: read, grep, glob, repo_map, browser_qa, read_image, skill, team_board, team_message",
117
117
  "model: deepseek-v4-pro",
118
118
  "permission: read-only",
119
119
  "output: findings",
@@ -126,7 +126,7 @@ const AGENT_TEMPLATES = {
126
126
  "---",
127
127
  "name: ui-critic",
128
128
  "description: Визуальный критик: скриншоты, сетка, ритм отступов, типографика, состояния.",
129
- "tools: read, grep, glob, browser_qa, team_board, team_message",
129
+ "tools: read, grep, glob, browser_qa, read_image, skill, team_board, team_message",
130
130
  "permission: read-only",
131
131
  "output: findings",
132
132
  "---",
@@ -138,7 +138,7 @@ const AGENT_TEMPLATES = {
138
138
  "---",
139
139
  "name: a11y",
140
140
  "description: Доступность по WCAG 2.2 AA: имена, подписи, контраст, фокус, тап-таргеты.",
141
- "tools: read, grep, glob, browser_qa, team_board, team_message",
141
+ "tools: read, grep, glob, browser_qa, read_image, skill, team_board, team_message",
142
142
  "permission: read-only",
143
143
  "output: findings",
144
144
  "---",
@@ -150,7 +150,7 @@ const AGENT_TEMPLATES = {
150
150
  "---",
151
151
  "name: cms-ops",
152
152
  "description: CMS-эксплуатация: версии, плагины, checksums, почта, cron, права, обновляемость.",
153
- "tools: read, grep, glob, pwsh, browser_qa, team_board, team_message",
153
+ "tools: read, grep, glob, pwsh, browser_qa, read_image, web_fetch, skill, team_board, team_message",
154
154
  "permission: read-only",
155
155
  "output: findings",
156
156
  "---",
@@ -162,7 +162,7 @@ const AGENT_TEMPLATES = {
162
162
  "---",
163
163
  "name: builder",
164
164
  "description: Писатель: собирает одну единицу работы в своём worktree и сдаёт её на проверку.",
165
- "tools: read, grep, glob, write, edit, pwsh, browser_qa, quality_gate, team_board, team_message",
165
+ "tools: read, grep, glob, write, edit, pwsh, browser_qa, read_image, skill, quality_gate, team_board, team_message",
166
166
  "permission: workspace-write",
167
167
  "---",
168
168
  "",
@@ -173,7 +173,7 @@ const AGENT_TEMPLATES = {
173
173
  "---",
174
174
  "name: release-ops",
175
175
  "description: Выпускает релизы: сборка, подпись, канал обновлений, бэкап, выкатка, откат.",
176
- "tools: read, grep, glob, pwsh, remote_ops, quality_gate, team_board, team_message",
176
+ "tools: read, grep, glob, pwsh, remote_ops, quality_gate, read_image, skill, team_board, team_message",
177
177
  "permission: workspace-write",
178
178
  "---",
179
179
  "",
@@ -184,7 +184,7 @@ const AGENT_TEMPLATES = {
184
184
  "---",
185
185
  "name: demo-watch",
186
186
  "description: Следит за демо-стендом: доступность, состояние обновлений, следы демо на проде.",
187
- "tools: read, grep, glob, remote_ops, browser_qa, team_board, team_message",
187
+ "tools: read, grep, glob, remote_ops, browser_qa, read_image, skill, team_board, team_message",
188
188
  "permission: read-only",
189
189
  "output: findings",
190
190
  "---",
@@ -27,6 +27,29 @@ const SHELL_WRITE = /(?:^|[\s"'=])(?:>|>>|Set-Content|Add-Content|Out-File|Copy-
27
27
  const MAX_REMINDERS = 4;
28
28
  const MAX_PATHS = 12;
29
29
 
30
+ /**
31
+ * Optional critical-scenario coverage: `.dsh/quality/ui.json` with
32
+ * `{ "scenarios": ["menu", "checkout"] }`. When present, a single passing
33
+ * interact is no longer enough; distinct interact runs must cover the list.
34
+ */
35
+ export function readUiCoverage(cwd) {
36
+ if (!cwd) return [];
37
+ for (const name of ["ui.json", "ui-coverage.json"]) {
38
+ try {
39
+ const raw = JSON.parse(fs.readFileSync(path.join(cwd, ".dsh", "quality", name), "utf8"));
40
+ const scenarios = Array.isArray(raw?.scenarios) ? raw.scenarios : [];
41
+ return scenarios
42
+ .map((item) => (typeof item === "string" ? item : item?.name))
43
+ .filter((item) => typeof item === "string" && item.trim().length > 0)
44
+ .map((item) => item.trim())
45
+ .slice(0, 20);
46
+ } catch {
47
+ /* optional */
48
+ }
49
+ }
50
+ return [];
51
+ }
52
+
30
53
  function shellUiPath(command) {
31
54
  const match = String(command).match(/(?:[A-Za-z]:[\\/]|\.{0,2}[\\/])?[^\s"'<>|;]+\.(?:html?|xhtml|css|scss|sass|less|jsx|tsx|vue|svelte|astro|mdx)/iu);
32
55
  return match?.[0] ?? "";
@@ -217,6 +240,8 @@ export function createUiGate(ctx) {
217
240
  a11y: null,
218
241
  interactAt: 0,
219
242
  interact: null,
243
+ interactRuns: new Set(),
244
+ coverage: [],
220
245
  paths: new Set(),
221
246
  reminders: 0,
222
247
  };
@@ -238,6 +263,8 @@ export function createUiGate(ctx) {
238
263
  state.clean = false;
239
264
  state.a11y = null;
240
265
  state.interact = null;
266
+ state.interactRuns.clear();
267
+ state.coverage = readUiCoverage(cwdOf(ctx, actor));
241
268
  state.lastEditAt = Date.now();
242
269
  state.reminders = 0;
243
270
  state.paths.add(file);
@@ -272,6 +299,11 @@ export function createUiGate(ctx) {
272
299
  if (!parsed) return;
273
300
  state.interactAt = Date.now();
274
301
  state.interact = parsed;
302
+ if (parsed.pass === true) {
303
+ const steps = exec?.arguments?.steps ?? exec?.args?.steps ?? exec?.input?.steps ?? [];
304
+ const digest = crypto.createHash("sha1").update(JSON.stringify(steps)).digest("hex").slice(0, 12);
305
+ state.interactRuns.add(digest);
306
+ }
275
307
  }
276
308
 
277
309
  /** What still blocks the turn, in the order the model should fix it. */
@@ -282,7 +314,9 @@ export function createUiGate(ctx) {
282
314
  if (!strict) return missing;
283
315
  if (!state.a11yAt || state.a11yAt < state.lastEditAt) missing.push("a11y-missing");
284
316
  else if (Number(state.a11y?.serious ?? 0) > 0) missing.push("a11y-issues");
285
- if (state.interactAt >= state.lastEditAt && state.interact && state.interact.pass !== true) missing.push("interact-fail");
317
+ if (!state.interactAt || state.interactAt < state.lastEditAt) missing.push("interact-missing");
318
+ else if (state.interact && state.interact.pass !== true) missing.push("interact-fail");
319
+ else if ((state.coverage?.length ?? 0) > 0 && (state.interactRuns?.size ?? 0) < state.coverage.length) missing.push("interact-coverage");
286
320
  return missing;
287
321
  }
288
322
 
@@ -307,9 +341,15 @@ export function createUiGate(ctx) {
307
341
  if (missing.includes("a11y-issues")) {
308
342
  lines.push(`browser_qa a11y нашёл serious ${state.a11y?.serious ?? "?"}: почини и прогони a11y заново — порог 0.`);
309
343
  }
344
+ if (missing.includes("interact-missing")) {
345
+ lines.push("Гейт качества требует поведение, а не только геометрию: запусти browser_qa action=interact хотя бы по одному ключевому сценарию (меню, форма, модалка) и приложи PASS.");
346
+ }
310
347
  if (missing.includes("interact-fail")) {
311
348
  lines.push("Сценарий browser_qa action=interact упал: элемент перекрыт, невидим или не прошло ожидание. Почини и прогони сценарий заново.");
312
349
  }
350
+ if (missing.includes("interact-coverage")) {
351
+ lines.push(`Нужно покрытие критических сценариев (${(state.coverage ?? []).join(", ")}): сейчас пройдено ${state.interactRuns?.size ?? 0}/${state.coverage?.length ?? 0}. Прогони отдельный interact для каждого сценария из .dsh/quality/ui.json.`);
352
+ }
313
353
  lines.push("</ui-gate>");
314
354
  return lines.join("\n");
315
355
  }
@@ -18,6 +18,7 @@
18
18
  * `<DSH_HOME>/guardrails.json`.
19
19
  */
20
20
  import fs from "node:fs";
21
+ import os from "node:os";
21
22
  import path from "node:path";
22
23
 
23
24
  import { createGuard, createHookState, registerHooks } from "./lib/hooks.js";
@@ -32,13 +33,14 @@ import {
32
33
  policyPath,
33
34
  } from "./lib/policy.js";
34
35
  import { scanProject } from "./lib/scan.js";
36
+ import { createRuntimeState } from "./lib/runtime.js";
35
37
 
36
38
  /** Tool and hook plugin depends on the tool registry only. */
37
39
  export const inject = ["tools"];
38
40
 
39
41
  const PLUGIN_NAME = "dsh-guardrails";
40
42
  const PLUGIN_VERSION = "1.0.0";
41
- const ACTIONS = ["status", "check", "policy"];
43
+ const ACTIONS = ["status", "check", "policy", "runtime"];
42
44
  const DEFAULT_ACTION = "status";
43
45
  const TEXT_LIMIT = 24_000;
44
46
 
@@ -306,6 +308,30 @@ function renderScanReport(value) {
306
308
  return lines.join("\n");
307
309
  }
308
310
 
311
+ /* ------------------------------------------------------------------ */
312
+ /* runtime */
313
+ /* ------------------------------------------------------------------ */
314
+
315
+ function runtimeValue(runtime, mode) {
316
+ const snapshot = runtime.snapshot();
317
+ const lines = [
318
+ "Guardrails runtime (in-memory, no command text):",
319
+ `permission: ${mode ? `${mode.name} (sandbox=${mode.sandbox}, approval=${mode.approval ?? "default"})` : "unknown (no DSH permission preset)"}`,
320
+ `decisions: ${snapshot.count} · ask ${snapshot.asks} · deny ${snapshot.denies}`,
321
+ ];
322
+ if (!snapshot.last) {
323
+ lines.push("Последних ask/deny нет: за этот процесс не было решений.");
324
+ } else {
325
+ for (const item of snapshot.decisions) {
326
+ lines.push(
327
+ `- ${item.at} ${item.kind.toUpperCase()} ${item.tool} · level=${item.level}${item.irreversible ? " · irreversible" : ""}${item.external ? " · external" : ""} · mode=${item.mode || "?"} · rule=${item.rule || "?"} · fp=${item.fingerprint}`,
328
+ );
329
+ }
330
+ }
331
+ lines.push("DSH владеет approval-карточкой; runtime только фиксирует ask/deny для диагностики.");
332
+ return { ok: true, enabled: true, ...snapshot, text: lines.join("\n") };
333
+ }
334
+
309
335
  /* ------------------------------------------------------------------ */
310
336
  /* Plugin entry */
311
337
  /* ------------------------------------------------------------------ */
@@ -314,7 +340,9 @@ export function apply(ctx) {
314
340
  const env = process.env;
315
341
  const logger = ctx?.logger;
316
342
  const hookState = createHookState();
317
- const guard = createGuard({ env, logger, modeFor: (agent) => resolveMode(ctx, agent) });
343
+ const runtimeFile = path.join(env.DSH_HOME || path.join(os.homedir(), ".dsh"), "agent-extensions", "runtime.json");
344
+ const runtime = createRuntimeState({ persistPath: runtimeFile });
345
+ const guard = createGuard({ env, logger, runtime, modeFor: (agent) => resolveMode(ctx, agent) });
318
346
  try {
319
347
  registerHooks(ctx, guard, hookState);
320
348
  } catch (error) {
@@ -325,7 +353,7 @@ export function apply(ctx) {
325
353
  const tool = {
326
354
  name: "guardrails",
327
355
  description:
328
- "Read-only guardrails control and security scan. `status` shows effective command rules, protected paths, hook registration and the DSH_GUARDRAILS kill switch. `check` scans a project or worktree with strict limits (no network) for secrets, .env files, protected paths, oversized files, dangerous commands in shell scripts and `git diff --check`; token values are redacted. `policy` prints the effective JSON policy. Scanning never executes files and never writes.",
356
+ "Read-only guardrails control and security scan. `status` shows effective command rules, protected paths, hook registration and the DSH_GUARDRAILS kill switch. `check` scans a project or worktree with strict limits (no network) for secrets, .env files, protected paths, oversized files, dangerous commands in shell scripts and `git diff --check`; token values are redacted. `policy` prints the effective JSON policy. `runtime` shows the current permission preset and recent ask/deny decisions (consequence level, fingerprint; command text is never stored). Scanning never executes files and never writes.",
329
357
  parameters: {
330
358
  type: "object",
331
359
  additionalProperties: false,
@@ -333,7 +361,7 @@ export function apply(ctx) {
333
361
  action: {
334
362
  type: "string",
335
363
  enum: ACTIONS,
336
- description: "status (rules, protected paths, hooks) | check (bounded read-only scan) | policy (effective JSON policy).",
364
+ description: "status (rules, protected paths, hooks) | check (bounded read-only scan) | policy (effective JSON policy) | runtime (permission preset + recent ask/deny).",
337
365
  },
338
366
  root: {
339
367
  type: "string",
@@ -368,6 +396,7 @@ export function apply(ctx) {
368
396
  const loaded = loadPolicy({ env });
369
397
  if (action === "policy") return policyValue(loaded);
370
398
  if (action === "status") return statusValue(loaded, hookState);
399
+ if (action === "runtime") return runtimeValue(runtime, resolveMode(ctx, exec?.agent));
371
400
  if (action === "check") return await checkValue(loaded, args, exec, logger);
372
401
  return {
373
402
  ok: false,
@@ -131,7 +131,15 @@ export function createGuard(options = {}) {
131
131
  const env = options.env ?? process.env;
132
132
  const policyFile = options.policyFile;
133
133
  const logger = options.logger;
134
+ const runtime = options.runtime;
134
135
  const load = () => loadPolicy({ env, ...(policyFile === undefined ? {} : { filePath: policyFile }) });
136
+ function record(exec, decision, mode, rule) {
137
+ try {
138
+ runtime?.record?.(exec, decision, { mode, rule });
139
+ } catch {
140
+ /* runtime diagnostics must never break a decision */
141
+ }
142
+ }
135
143
  async function allowPreTool(next) {
136
144
  return typeof next === "function" ? next() : { kind: "allow" };
137
145
  }
@@ -155,15 +163,19 @@ export function createGuard(options = {}) {
155
163
  const ruleId = verdict.primary?.id ?? "policy";
156
164
  logger?.debug?.(`[guardrails] pre-execute ${verdict.action} tool=${toolName} rule=${ruleId}`);
157
165
  if (verdict.action === "deny") {
158
- return denyDecision(
166
+ const decision = denyDecision(
159
167
  `guardrails: command denied by rule "${ruleId}" (${verdict.primary?.description ?? "policy"}). ${policyHint()}`,
160
168
  ruleId,
161
169
  );
170
+ record(exec, decision, "rule", ruleId);
171
+ return decision;
162
172
  }
163
- return askDecision(
173
+ const decision = askDecision(
164
174
  `guardrails: command requires confirmation by rule "${ruleId}" (${verdict.primary?.description ?? "policy"})`,
165
175
  ruleId,
166
176
  );
177
+ record(exec, decision, "rule", ruleId);
178
+ return decision;
167
179
  }
168
180
  }
169
181
  }
@@ -172,18 +184,23 @@ export function createGuard(options = {}) {
172
184
  const hit = matchProtectedPath(requestedPath, { policy: loaded.policy, env });
173
185
  if (hit === undefined) continue;
174
186
  logger?.debug?.(`[guardrails] pre-execute deny tool=${toolName} rule=${hit.id}`);
175
- return denyDecision(
187
+ const decision = denyDecision(
176
188
  `guardrails: modifying a protected path is not allowed: ${requestedPath} (rule: ${hit.id}). ${policyHint()}`,
177
189
  hit.id,
178
190
  );
191
+ record(exec, decision, "protected-path", hit.id);
192
+ return decision;
179
193
  }
180
194
  }
181
195
  const mode = typeof options.modeFor === "function" ? options.modeFor(exec?.agent) : undefined;
182
196
  const modeHit = modeDecision(mode, exec, exec?.agent?.session?.header?.cwd ?? process.cwd());
183
197
  if (modeHit) {
184
198
  logger?.debug?.(`[guardrails] pre-execute mode=${mode?.name ?? "?"} action=${modeHit.kind} tool=${toolName}`);
185
- if (modeHit.kind === "ask") return askDecision(modeHit.reason, "permission-mode");
186
- return denyDecision(modeHit.reason, "permission-mode");
199
+ const decision = modeHit.kind === "ask"
200
+ ? askDecision(modeHit.reason, "permission-mode")
201
+ : denyDecision(modeHit.reason, "permission-mode");
202
+ record(exec, decision, mode, "permission-mode");
203
+ return decision;
187
204
  }
188
205
  return allowPreTool(next);
189
206
  } catch (error) {
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Consequence classification and the in-memory approval runtime.
3
+ *
4
+ * DSH owns the approval card. This module does not create a second one: it
5
+ * labels a decision (read/write/external/destructive/credential), records the
6
+ * ask/deny that DSH actually received, and exposes a bounded snapshot for
7
+ * `/guardrails action=runtime`. Command text is never stored; only a hash.
8
+ */
9
+ import crypto from "node:crypto";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+
13
+ const DESTRUCTIVE = /\b(?:rm\s+-rf|rmdir\s+\/s|rd\s+\/s|del\s+\/[sfq]|git\s+(?:reset\s+--hard|clean\s+-[a-z]*f|push\s+(?:--force|-f)|checkout\s+--\s+\.)|drop\s+(?:table|database|schema)|truncate\s+table|delete\s+from|format\s+[a-z]:|shutdown|Stop-Computer|Remove-Item\b[^\n]*-Recurse|migrate:fresh|migrate:refresh|db:wipe|pg_dropcluster)\b/iu;
14
+ const EXTERNAL = /\b(?:git\s+push|npm\s+publish|pnpm\s+publish|gh\s+release|gh\s+pr\s+(?:create|merge)|ssh\b|scp\b|remote_ops|curl\b[^\n]*(?:-X\s*(?:POST|PUT|DELETE)|--data)|Invoke-WebRequest\b[^\n]*-Method\s*(?:Post|Put|Delete)|wget\b[^\n]*--post)/iu;
15
+ const COSTLY = /\b(?:npm\s+(?:install|i|add)|pnpm\s+(?:add|install)|yarn\s+add|pip\s+install|composer\s+(?:install|update|require)|winget\s+install|choco\s+install|docker\s+pull|git\s+clone)\b/iu;
16
+ const CREDENTIAL = /\b(?:\.ssh[\\/]|id_(?:rsa|ed25519|ecdsa)|\.aws[\\/]|\.npmrc|\.git-credentials|credentials\.json|\.env(?:\.|$)|secret|token|api[_-]?key)\b/iu;
17
+ const MUTATING_TOOLS = new Set(["write", "edit", "apply_patch", "patch", "delete", "move", "mkdir", "touch"]);
18
+ const SHELL_TOOLS = new Set(["bash", "pwsh", "powershell", "shell", "sh", "zsh", "cmd", "terminal"]);
19
+
20
+ export function commandOf(args) {
21
+ if (typeof args === "string") return args;
22
+ if (!args || typeof args !== "object") return "";
23
+ for (const key of ["command", "cmd", "script"]) {
24
+ if (typeof args[key] === "string" && args[key].trim().length > 0) return args[key];
25
+ }
26
+ return "";
27
+ }
28
+
29
+ /** SHA-256 prefix so the runtime can show a stable fingerprint without the command. */
30
+ export function fingerprint(value) {
31
+ return crypto.createHash("sha256").update(String(value ?? "")).digest("hex").slice(0, 12);
32
+ }
33
+
34
+ /**
35
+ * Label a tool call by consequence. The label is advisory for policy and
36
+ * diagnostics; the authoritative allow/deny is still the DSH permission preset
37
+ * plus `guardrails.json`.
38
+ *
39
+ * @param {{name?: string, arguments?: unknown}} exec
40
+ * @param {string} [cwd]
41
+ * @returns {{level:'read'|'write'|'external'|'destructive'|'credential', irreversible:boolean, external:boolean, costly:boolean, needsApproval:boolean, reason:string, fingerprint:string}}
42
+ */
43
+ export function classifyConsequence(exec, cwd = "") {
44
+ const tool = String(exec?.name ?? "");
45
+ const args = exec?.arguments;
46
+ const command = commandOf(args);
47
+ const text = [tool, command, typeof args === "object" ? JSON.stringify(args) : String(args ?? "")].join("\n");
48
+ let level = "read";
49
+ let reason = "read-only";
50
+
51
+ if (DESTRUCTIVE.test(text)) {
52
+ level = "destructive";
53
+ reason = "destructive or irreversible command";
54
+ } else if (EXTERNAL.test(text)) {
55
+ level = "external";
56
+ reason = "external side effect";
57
+ } else if (CREDENTIAL.test(text)) {
58
+ level = "credential";
59
+ reason = "credential or secret path";
60
+ } else if (MUTATING_TOOLS.has(tool) || (SHELL_TOOLS.has(tool) && command.trim().length > 0 && COSTLY.test(command))) {
61
+ level = "write";
62
+ reason = "workspace mutation";
63
+ }
64
+
65
+ return {
66
+ level,
67
+ irreversible: level === "destructive",
68
+ external: level === "external" || level === "destructive",
69
+ costly: COSTLY.test(text),
70
+ needsApproval: level === "destructive" || level === "external" || level === "credential",
71
+ reason,
72
+ fingerprint: fingerprint([tool, command].join("\n")),
73
+ };
74
+ }
75
+
76
+ const MAX_DECISIONS = 80;
77
+
78
+ /**
79
+ * Bounded runtime. No command text, no secrets. When `persistPath` is set the
80
+ * snapshot survives a DSH restart, which makes `/guardrails runtime` useful for
81
+ * "what did I approve an hour ago" instead of only the current process.
82
+ */
83
+ export function createRuntimeState({ limit = MAX_DECISIONS, persistPath = "" } = {}) {
84
+ const decisions = [];
85
+ let asks = 0;
86
+ let denies = 0;
87
+ let loaded = false;
88
+ if (persistPath) {
89
+ try {
90
+ const raw = JSON.parse(fs.readFileSync(persistPath, "utf8"));
91
+ if (Array.isArray(raw?.decisions)) decisions.push(...raw.decisions.slice(-limit));
92
+ asks = Number(raw?.asks) || 0;
93
+ denies = Number(raw?.denies) || 0;
94
+ loaded = true;
95
+ } catch {
96
+ /* no previous runtime */
97
+ }
98
+ }
99
+ function persist() {
100
+ if (!persistPath) return;
101
+ try {
102
+ fs.mkdirSync(path.dirname(persistPath), { recursive: true, mode: 0o700 });
103
+ const temporary = `${persistPath}.${process.pid}.tmp`;
104
+ fs.writeFileSync(temporary, `${JSON.stringify({ updatedAt: new Date().toISOString(), asks, denies, decisions }, null, 2)}\n`, { mode: 0o600 });
105
+ fs.renameSync(temporary, persistPath);
106
+ } catch {
107
+ /* diagnostics are best effort */
108
+ }
109
+ }
110
+ return {
111
+ record(exec, decision, { mode, rule } = {}) {
112
+ if (!decision || (decision.kind !== "ask" && decision.kind !== "deny")) return;
113
+ const consequence = classifyConsequence(exec, exec?.agent?.session?.header?.cwd ?? "");
114
+ const item = {
115
+ at: new Date().toISOString(),
116
+ tool: String(exec?.name ?? ""),
117
+ kind: decision.kind,
118
+ level: consequence.level,
119
+ irreversible: consequence.irreversible,
120
+ external: consequence.external,
121
+ needsApproval: consequence.needsApproval,
122
+ fingerprint: consequence.fingerprint,
123
+ mode: typeof mode === "string" ? mode : (mode?.name ?? ""),
124
+ rule: String(rule ?? ""),
125
+ reason: String(decision.reason ?? "").slice(0, 240),
126
+ };
127
+ decisions.push(item);
128
+ if (decisions.length > limit) decisions.splice(0, decisions.length - limit);
129
+ if (decision.kind === "ask") asks += 1;
130
+ else denies += 1;
131
+ persist();
132
+ return item;
133
+ },
134
+ snapshot() {
135
+ return {
136
+ ok: true,
137
+ persisted: Boolean(persistPath),
138
+ loaded,
139
+ count: decisions.length,
140
+ asks,
141
+ denies,
142
+ last: decisions[decisions.length - 1] ?? null,
143
+ decisions: decisions.slice(-20),
144
+ };
145
+ },
146
+ reset() {
147
+ decisions.length = 0;
148
+ asks = 0;
149
+ denies = 0;
150
+ persist();
151
+ },
152
+ };
153
+ }
@@ -1109,6 +1109,31 @@ async function runTool(deps, args, exec) {
1109
1109
  markMemoryUpdated(state, sessionId);
1110
1110
  return jsonResult([`Автоскан «${project.name}» обновлён: ${facts.stats?.files ?? 0} файлов, ${facts.warnings?.length ?? 0} предупреждений.`, ...summary].join("\n"), { project, scan: facts });
1111
1111
  }
1112
+ if (action === "health") {
1113
+ const project = projectFromArgs(deps, args, session);
1114
+ const root = project.roots[0] ?? process.cwd();
1115
+ const facts = loadScan(project) ?? scanProject(root);
1116
+ const findings = [];
1117
+ if (!exists(root)) findings.push({ level: "error", code: "root-missing", message: `корень не найден: ${root}` });
1118
+ if (!exists(path.join(root, ".dsh"))) findings.push({ level: "warning", code: "no-dsh", message: "нет .dsh: агенты, hooks, verify и project memory не настроены" });
1119
+ if (!exists(path.join(root, ".dsh", "PROJECT.md"))) findings.push({ level: "warning", code: "no-project-md", message: "нет .dsh/PROJECT.md: создайте /init" });
1120
+ if (!exists(path.join(root, "AGENTS.md")) && !exists(path.join(root, "CLAUDE.md"))) findings.push({ level: "info", code: "no-instructions", message: "нет AGENTS.md/CLAUDE.md: правила проекта не загружаются" });
1121
+ const git = gitInfo(root);
1122
+ if (!git) findings.push({ level: "warning", code: "no-git", message: "нет git: используйте файловые checkpoint и делайте резервные копии" });
1123
+ for (const warning of (facts.warnings ?? []).slice(0, 10)) findings.push({ level: "warning", code: "scan-warning", message: String(warning) });
1124
+ const age = project.lastScanAt ? Date.now() - Date.parse(project.lastScanAt) : null;
1125
+ if (age !== null && Number.isFinite(age) && age > 30 * 24 * 60 * 60 * 1000) findings.push({ level: "info", code: "stale-scan", message: `автоскан старше 30 дней: ${project.lastScanAt}` });
1126
+ const lines = [
1127
+ `Project health: «${project.name}» (${project.slug})`,
1128
+ `Root: ${root}`,
1129
+ `Git: ${git ? `${git.branch ?? "detached"} @ ${String(git.head ?? "").slice(0, 12)}` : "none"}`,
1130
+ `Scan: ${facts.scannedAt ?? "never"} · ${facts.stats?.files ?? 0} files`,
1131
+ `Findings: ${findings.length}`,
1132
+ ...findings.map((item) => `- ${item.level.toUpperCase()} ${item.code}: ${item.message}`),
1133
+ findings.length === 0 ? "Проблем не найдено." : "Исправьте warnings/errors; info — не блокер.",
1134
+ ];
1135
+ return jsonResult(lines.join("\n"), { project, root, git, findings, scan: { at: facts.scannedAt, warnings: facts.warnings ?? [], files: facts.stats?.files ?? 0 } });
1136
+ }
1112
1137
  if (action === "status") {
1113
1138
  const project = projectFromArgs(deps, args, session);
1114
1139
  const fresh = freshness(project);
@@ -1191,8 +1216,8 @@ const TOOL_PARAMETERS = {
1191
1216
  properties: {
1192
1217
  action: {
1193
1218
  type: "string",
1194
- enum: ["status", "brief", "list", "read", "search", "scan", "append_journal", "update_section", "register"],
1195
- description: "status|brief|list|read|search|scan|append_journal|update_section|register",
1219
+ enum: ["status", "brief", "list", "read", "search", "scan", "health", "append_journal", "update_section", "register"],
1220
+ description: "status|brief|list|read|search|scan|health|append_journal|update_section|register",
1196
1221
  },
1197
1222
  project: { type: "string", description: "Project slug or name; defaults to the current Session's project." },
1198
1223
  file: { type: "string", enum: SECTION_NAMES, description: "Dossier section for read/update_section." },
@@ -1221,7 +1246,7 @@ function makeToolDefinition(deps) {
1221
1246
  return {
1222
1247
  name: "project_memory",
1223
1248
  description:
1224
- "Local long-term project memory. The plugin auto-detects the project from cwd, scans manifests/docs locally and injects a compact digest. Use brief for a one-screen card, status for freshness, read/search for details, scan to refresh the local recon, update_section/append_journal to record durable facts, register only when auto-detection is wrong. Never store secrets or PII; link to files instead of copying code.",
1249
+ "Local long-term project memory. The plugin auto-detects the project from cwd, scans manifests/docs locally and injects a compact digest. Use brief for a one-screen card, status for freshness, health for project health (git, .dsh, instructions, scan warnings), read/search for details, scan to refresh the local recon, update_section/append_journal to record durable facts, register only when auto-detection is wrong. Never store secrets or PII; link to files instead of copying code.",
1225
1250
  parameters: TOOL_PARAMETERS,
1226
1251
  timeoutMs: 20000,
1227
1252
  output: {
@@ -610,14 +610,25 @@ export function apply(ctx) {
610
610
  const dispose = child.commands.register({
611
611
  name: "quality",
612
612
  description: "Миссия качества: статус, фазы, приёмка",
613
- input: { hint: "status | accept | next" },
613
+ input: { hint: "start | status | accept | next" },
614
614
  recordInput: false,
615
615
  handler: async ({ rawInput, agent }) => {
616
616
  const cwd = agent?.session?.header?.cwd ?? process.cwd();
617
- const mission = readMission(cwd);
617
+ let mission = readMission(cwd);
618
618
  const command = String(rawInput ?? "").trim().toLowerCase();
619
+ const raw = String(rawInput ?? "").trim();
619
620
  try {
620
- if (!mission) return { kind: "error", text: "Миссии нет. Начните с tool quality_gate action=start task=\"…\"" };
621
+ if (!mission) {
622
+ if (command === "start" || command.startsWith("start ")) {
623
+ const task = raw.replace(/^start\s*/iu, "").trim() || `Качество проекта ${path.basename(cwd)}`;
624
+ mission = createMission({ task, type: "web-site", profile: "standard" });
625
+ mission.autoStarted = false;
626
+ writeMission(cwd, mission);
627
+ return { kind: "success", text: formatStatus(mission) };
628
+ }
629
+ return { kind: "error", text: "Миссии нет. Начните с /quality start [задача] — или tool quality_gate action=start task=\"…\"." };
630
+ }
631
+ if (command === "start") return { kind: "success", text: `Миссия уже существует (${mission.profile}). ${formatStatus(mission)}` };
621
632
  if (command === "accept") {
622
633
  const rows = await runAcceptance({ cwd, mission });
623
634
  applyAcceptanceRows(mission, rows);
@@ -95,7 +95,7 @@ function describeGateIds(mission) {
95
95
  /** One line for the system prompt: cheap, stable, no tables. */
96
96
  export function formatPromptLine(mission) {
97
97
  if (!mission) {
98
- return "<quality-state>Миссии нет. Для веб-проекта она создаётся автоматически на первом ходе; вручную — tool quality_gate action=start task=\"…\" (профиль fast|standard|turnkey).</quality-state>";
98
+ return "<quality-state>Миссии нет. Для веб-проекта она создаётся автоматически на первом ходе; вручную — /quality start (или tool quality_gate action=start task=\"…\", профиль fast|standard|turnkey).</quality-state>";
99
99
  }
100
100
  const current = progress(mission);
101
101
  const open = current.missing.slice(0, 6).join(" ");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "kitVersion": "2.31.0",
4
- "generatedAt": "2026-12-01T19:01:37.037Z",
3
+ "kitVersion": "2.34.0",
4
+ "generatedAt": "2026-12-02T11:57:02.832Z",
5
5
  "skills": {
6
6
  "a11y-audit": {
7
7
  "hash": "707659a5cc1207b478bcf45012b06ba46ba88e795ef7e482799f415072fc47b2",
@@ -109,9 +109,9 @@
109
109
  "bytes": 4257
110
110
  },
111
111
  "seo": {
112
- "hash": "4e2a6a3c960fa51edbdac0467d41ea023be37a50afb67b03c0474f33adfb6fc6",
112
+ "hash": "ed48ebc4c1278f857ff430f9a5ec55f638c2f9ba07cc406185cfb94be18ee80d",
113
113
  "files": 29,
114
- "bytes": 386399
114
+ "bytes": 386169
115
115
  },
116
116
  "service-desk-conventions": {
117
117
  "hash": "22ae6c29b7debb0154d183bc732795b67557aeaa0ac906d7b038134aea8ba39a",
@@ -174,9 +174,9 @@
174
174
  "bytes": 14150
175
175
  },
176
176
  "wow-design": {
177
- "hash": "bba0d65db46c89d971eed43e7cd934f59752c062795a4e0d3d345d7313640e48",
177
+ "hash": "81139f32fc759f438a36eb4c0212ed3ea17df9d8075e909580e12bc47a0848dd",
178
178
  "files": 52,
179
- "bytes": 918621
179
+ "bytes": 913669
180
180
  }
181
181
  }
182
182
  }