dsh-desktop-kit 2.31.0 → 2.33.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.
@@ -0,0 +1,122 @@
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
+
11
+ 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;
12
+ 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;
13
+ 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;
14
+ const CREDENTIAL = /\b(?:\.ssh[\\/]|id_(?:rsa|ed25519|ecdsa)|\.aws[\\/]|\.npmrc|\.git-credentials|credentials\.json|\.env(?:\.|$)|secret|token|api[_-]?key)\b/iu;
15
+ const MUTATING_TOOLS = new Set(["write", "edit", "apply_patch", "patch", "delete", "move", "mkdir", "touch"]);
16
+ const SHELL_TOOLS = new Set(["bash", "pwsh", "powershell", "shell", "sh", "zsh", "cmd", "terminal"]);
17
+
18
+ export function commandOf(args) {
19
+ if (typeof args === "string") return args;
20
+ if (!args || typeof args !== "object") return "";
21
+ for (const key of ["command", "cmd", "script"]) {
22
+ if (typeof args[key] === "string" && args[key].trim().length > 0) return args[key];
23
+ }
24
+ return "";
25
+ }
26
+
27
+ /** SHA-256 prefix so the runtime can show a stable fingerprint without the command. */
28
+ export function fingerprint(value) {
29
+ return crypto.createHash("sha256").update(String(value ?? "")).digest("hex").slice(0, 12);
30
+ }
31
+
32
+ /**
33
+ * Label a tool call by consequence. The label is advisory for policy and
34
+ * diagnostics; the authoritative allow/deny is still the DSH permission preset
35
+ * plus `guardrails.json`.
36
+ *
37
+ * @param {{name?: string, arguments?: unknown}} exec
38
+ * @param {string} [cwd]
39
+ * @returns {{level:'read'|'write'|'external'|'destructive'|'credential', irreversible:boolean, external:boolean, costly:boolean, needsApproval:boolean, reason:string, fingerprint:string}}
40
+ */
41
+ export function classifyConsequence(exec, cwd = "") {
42
+ const tool = String(exec?.name ?? "");
43
+ const args = exec?.arguments;
44
+ const command = commandOf(args);
45
+ const text = [tool, command, typeof args === "object" ? JSON.stringify(args) : String(args ?? "")].join("\n");
46
+ let level = "read";
47
+ let reason = "read-only";
48
+
49
+ if (DESTRUCTIVE.test(text)) {
50
+ level = "destructive";
51
+ reason = "destructive or irreversible command";
52
+ } else if (EXTERNAL.test(text)) {
53
+ level = "external";
54
+ reason = "external side effect";
55
+ } else if (CREDENTIAL.test(text)) {
56
+ level = "credential";
57
+ reason = "credential or secret path";
58
+ } else if (MUTATING_TOOLS.has(tool) || (SHELL_TOOLS.has(tool) && command.trim().length > 0 && COSTLY.test(command))) {
59
+ level = "write";
60
+ reason = "workspace mutation";
61
+ }
62
+
63
+ return {
64
+ level,
65
+ irreversible: level === "destructive",
66
+ external: level === "external" || level === "destructive",
67
+ costly: COSTLY.test(text),
68
+ needsApproval: level === "destructive" || level === "external" || level === "credential",
69
+ reason,
70
+ fingerprint: fingerprint([tool, command].join("\n")),
71
+ };
72
+ }
73
+
74
+ const MAX_DECISIONS = 80;
75
+
76
+ /**
77
+ * Bounded in-memory runtime. No disk writes, no command text, no secrets.
78
+ */
79
+ export function createRuntimeState({ limit = MAX_DECISIONS } = {}) {
80
+ const decisions = [];
81
+ let asks = 0;
82
+ let denies = 0;
83
+ return {
84
+ record(exec, decision, { mode, rule } = {}) {
85
+ if (!decision || (decision.kind !== "ask" && decision.kind !== "deny")) return;
86
+ const consequence = classifyConsequence(exec, exec?.agent?.session?.header?.cwd ?? "");
87
+ const item = {
88
+ at: new Date().toISOString(),
89
+ tool: String(exec?.name ?? ""),
90
+ kind: decision.kind,
91
+ level: consequence.level,
92
+ irreversible: consequence.irreversible,
93
+ external: consequence.external,
94
+ needsApproval: consequence.needsApproval,
95
+ fingerprint: consequence.fingerprint,
96
+ mode: typeof mode === "string" ? mode : (mode?.name ?? ""),
97
+ rule: String(rule ?? ""),
98
+ reason: String(decision.reason ?? "").slice(0, 240),
99
+ };
100
+ decisions.push(item);
101
+ if (decisions.length > limit) decisions.splice(0, decisions.length - limit);
102
+ if (decision.kind === "ask") asks += 1;
103
+ else denies += 1;
104
+ return item;
105
+ },
106
+ snapshot() {
107
+ return {
108
+ ok: true,
109
+ count: decisions.length,
110
+ asks,
111
+ denies,
112
+ last: decisions[decisions.length - 1] ?? null,
113
+ decisions: decisions.slice(-20),
114
+ };
115
+ },
116
+ reset() {
117
+ decisions.length = 0;
118
+ asks = 0;
119
+ denies = 0;
120
+ },
121
+ };
122
+ }
@@ -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(" ");