dsh-desktop-kit 2.30.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.en.md +118 -0
  3. package/README.md +71 -11
  4. package/client.js +1 -1
  5. package/docs/COMPATIBILITY.md +2 -1
  6. package/docs/LAPTOP-INSTALL.md +9 -5
  7. package/docs/MEASURED.md +25 -0
  8. package/docs/TEST-2.31.0.md +61 -0
  9. package/docs/TEST-2.32.0.md +32 -0
  10. package/docs/TEST-2.33.0.md +33 -0
  11. package/docs/UPGRADING.md +3 -1
  12. package/docs/images/hero-2.31.png +0 -0
  13. package/docs/measured.json +30 -0
  14. package/docs/preview/hero-2.31.html +133 -0
  15. package/doctor.ps1 +161 -142
  16. package/index.js +76 -5
  17. package/install.ps1 +178 -99
  18. package/lib/kit-diagnostics.js +780 -0
  19. package/package.json +8 -4
  20. package/plugins/dsh-agent-extensions/lib/agents.js +20 -1
  21. package/plugins/dsh-agent-extensions/lib/checkpoints.js +109 -5
  22. package/plugins/dsh-agent-extensions/lib/commands.js +40 -3
  23. package/plugins/dsh-agent-extensions/lib/instructions.js +96 -1
  24. package/plugins/dsh-agent-extensions/lib/locks.js +114 -0
  25. package/plugins/dsh-agent-extensions/lib/policy.js +5 -0
  26. package/plugins/dsh-agent-extensions/lib/project.js +7 -1
  27. package/plugins/dsh-agent-extensions/lib/scaffold.js +14 -14
  28. package/plugins/dsh-browser-qa/lib/ui-gate.js +5 -1
  29. package/plugins/dsh-guardrails/index.js +31 -4
  30. package/plugins/dsh-guardrails/lib/hooks.js +22 -5
  31. package/plugins/dsh-guardrails/lib/runtime.js +122 -0
  32. package/plugins/dsh-integrations/lib/job-sandbox.ps1 +1 -1
  33. package/plugins/dsh-profile-transfer/bootstrap/install-on-clean-machine.ps1 +1 -1
  34. package/plugins/dsh-project-memory/index.js +28 -3
  35. package/plugins/dsh-quality-pipeline/index.js +14 -3
  36. package/plugins/dsh-quality-pipeline/lib/text.js +1 -1
  37. package/skills/manifest.json +2 -2
  38. package/skills-baseline.json +9 -5
  39. package/uninstall.ps1 +1 -1
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-desktop-kit",
3
- "version": "2.30.0",
4
- "description": "DeepSeek Harness desktop kit 2.30.0 — 21 plugins and 35 skills: quality mission with phases, gates G0..G13, a pre-work layer (product brief, measured references, IA/content inventory, plan with dependencies, risks and blockers), an art-direction brief with variants, a release pipeline and remote_ops (typed ssh/scp with host state diff), units of work and an evidence trail; browser QA with 18 actions (interaction scenarios, accessibility WCAG 2.2 AA, performance budgets, element locate, pixel-diff baselines, palette contrast matrix, cross-page consistency, interactive-state and content checks, design report, reference take), plus an i18n dictionary pipeline; 14 project agents including ui-critic, a11y, cms-ops and a worktree builder; phase-aware skill routing with a token budget; MCP with OAuth 2.1, sampling and elicitation; read-only/writer swarm with a shared board; token lab, Skills Studio, project memory, guardrails, repo map, checkpoints, plan mode, GitHub review, hooks/commands, Russian UI and profile transfer.",
3
+ "version": "2.33.0",
4
+ "description": "DeepSeek Harness desktop kit 2.31.0 — 21 plugins and 35 skills: quality mission with phases, gates G0..G13, a pre-work layer (product brief, measured references, IA/content inventory, plan with dependencies, risks and blockers), an art-direction brief with variants, a release pipeline and remote_ops (typed ssh/scp with host state diff), units of work and an evidence trail; browser QA with 18 actions (interaction scenarios, accessibility WCAG 2.2 AA, performance budgets, element locate, pixel-diff baselines, palette contrast matrix, cross-page consistency, interactive-state and content checks, design report, reference take), plus an i18n dictionary pipeline; 14 project agents including ui-critic, a11y, cms-ops and a worktree builder; phase-aware skill routing with a token budget; MCP with OAuth 2.1, sampling and elicitation; read-only/writer swarm with a shared board; token lab, Skills Studio, project memory, guardrails, repo map, checkpoints, plan mode, GitHub review, hooks/commands, Russian UI and profile transfer. Includes local marketplace, localhost IDE bridge and an honest sandbox audit.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
7
7
  "dsh",
@@ -64,6 +64,7 @@
64
64
  "client.js",
65
65
  "cordis.patch.yml",
66
66
  "README.md",
67
+ "README.en.md",
67
68
  "CHANGELOG.md",
68
69
  "LICENSE",
69
70
  "doctor.ps1",
@@ -71,6 +72,7 @@
71
72
  "uninstall.ps1",
72
73
  "lib/**",
73
74
  "docs/**",
75
+ "!docs/analysis/**",
74
76
  "skills-baseline.json",
75
77
  "plugins/*/package.json",
76
78
  "plugins/*/*.js",
@@ -90,11 +92,13 @@
90
92
  "build:client": "node tools/build-client.mjs",
91
93
  "build:skills": "node tools/build-skill-manifest.mjs",
92
94
  "check:client": "node tools/check-client.mjs client.js",
93
- "test": "node tools/integrations-tests.mjs && node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/quality-pipeline-tests.mjs && node tools/remote-ops-tests.mjs && node tools/i18n-tests.mjs && node tools/autopilot-route-tests.mjs && node tools/browser-qa-tests.mjs && node tools/browser-qa-extras-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/research-ledger-tests.mjs && node tools/research-eval.mjs && node tools/citation-eval.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/mcp-catalog-tests.mjs && node tools/mcp-bootstrap-tests.mjs && node tools/instructions-tests.mjs && node tools/mcp-elicitation-tests.mjs && node tools/mcp-sampling-tests.mjs && node tools/mcp-oauth-tests.mjs && node tools/worktrees-tests.mjs && node tools/transcripts-tests.mjs && node tools/team-messages-tests.mjs && node tools/rc3-compat-tests.mjs && node tools/swarm-tests.mjs && node tools/team-presets-tests.mjs && node tools/team-board-tests.mjs && node tools/team-agents-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs",
95
+ "test": "node tools/integrations-tests.mjs && node tools/smoke-tests.mjs && node tools/memory-tests.mjs && node tools/skills-sync-tests.mjs && node tools/kit-upgrade-tests.mjs && node plugins/dsh-profile-transfer/test/transfer.test.mjs && node --test plugins/dsh-memory-bridge/test/bridge.test.mjs plugins/dsh-memory-bridge/test/github.test.mjs plugins/dsh-memory-bridge/test/merge.test.mjs plugins/dsh-memory-bridge/test/user-specific.test.mjs && node tools/repo-map-tests.mjs && node tools/checkpoints-tests.mjs && node tools/plan-mode-tests.mjs && node tools/quality-pipeline-tests.mjs && node tools/remote-ops-tests.mjs && node tools/i18n-tests.mjs && node tools/autopilot-route-tests.mjs && node tools/browser-qa-tests.mjs && node tools/browser-qa-extras-tests.mjs && node tools/ui-gate-tests.mjs && node tools/agent-extensions-tests.mjs && node tools/research-ledger-tests.mjs && node tools/research-eval.mjs && node tools/citation-eval.mjs && node tools/mcp-manager-tests.mjs && node tools/github-review-tests.mjs && node tools/mcp-catalog-tests.mjs && node tools/mcp-bootstrap-tests.mjs && node tools/instructions-tests.mjs && node tools/mcp-elicitation-tests.mjs && node tools/mcp-sampling-tests.mjs && node tools/mcp-oauth-tests.mjs && node tools/worktrees-tests.mjs && node tools/transcripts-tests.mjs && node tools/team-messages-tests.mjs && node tools/rc3-compat-tests.mjs && node tools/swarm-tests.mjs && node tools/team-presets-tests.mjs && node tools/team-board-tests.mjs && node tools/team-agents-tests.mjs && node tools/background-agents-tests.mjs && node tools/permissions-ui-tests.mjs && node plugins/dsh-guardrails/tools/guardrails-tests.mjs && node tools/kit-diagnostics-tests.mjs && node tools/onboarding-tests.mjs && node tools/check-release-consistency.mjs",
94
96
  "skills:cost": "node tools/skill-cost.mjs",
95
97
  "skills:check": "node tools/skill-cost.mjs --check",
96
98
  "release": "node tools/release.mjs",
97
- "verify:release": "node tools/verify-release.mjs"
99
+ "verify:release": "node tools/verify-release.mjs",
100
+ "measure": "node tools/measure.mjs",
101
+ "check:release": "node tools/check-release-consistency.mjs"
98
102
  },
99
103
  "engines": {
100
104
  "node": ">=20"
@@ -12,6 +12,7 @@ import { loadRuns, runPreview, updateRun, upsertRun } from "./runs.js";
12
12
  import { saveTranscript } from "./transcripts.js";
13
13
  import { findingsPrompt, parseFindings, validateFindings } from "./findings.js";
14
14
  import { agentOptionsFor, chooseAgentRoute } from "./routing.js";
15
+ import { acquireLock, releaseLock } from "./locks.js";
15
16
 
16
17
  const MODEL_ERROR = /(?:model|provider).*(?:not found|unknown|unsupported|unavailable|not available|invalid|no such|does not exist)/iu;
17
18
  const background = new Map();
@@ -64,8 +65,20 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
64
65
  const route = chooseAgentRoute(definition, task, options.route);
65
66
  let routeUsed = route;
66
67
  setChildPolicy(reservedId, definition);
68
+ let heldLock = null;
67
69
  let activation;
68
70
  try {
71
+ if (definition.permission !== "read-only" && options.lock !== false) {
72
+ heldLock = acquireLock({
73
+ cwd: options.worktree?.path ?? project.root,
74
+ owner: reservedId,
75
+ scope: "writer",
76
+ });
77
+ if (!heldLock.ok) {
78
+ const holder = heldLock.holder ?? {};
79
+ throw new Error(`project busy: writer lock held by ${holder.owner ?? "another agent"} since ${holder.createdAt ?? "?"}`);
80
+ }
81
+ }
69
82
  const prompt = [
70
83
  `<project-agent name="${definition.name}">`,
71
84
  definition.body,
@@ -162,6 +175,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
162
175
  }
163
176
  try { await activation.dispose?.(); } catch { /* best effort */ }
164
177
  clearChildPolicy(activeId);
178
+ releaseLock({ cwd: options.worktree?.path ?? project.root, owner: reservedId });
165
179
  background.delete(record.id);
166
180
  signal?.removeEventListener?.("abort", abort);
167
181
  }).catch((error) => {
@@ -175,6 +189,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
175
189
  });
176
190
  }
177
191
  clearChildPolicy(activeId);
192
+ releaseLock({ cwd: options.worktree?.path ?? project.root, owner: reservedId });
178
193
  background.delete(record.id);
179
194
  signal?.removeEventListener?.("abort", abort);
180
195
  });
@@ -212,6 +227,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
212
227
  };
213
228
  } catch (error) {
214
229
  clearChildPolicy(activeId);
230
+ releaseLock({ cwd: options.worktree?.path ?? project.root, owner: reservedId });
215
231
  if (isBackground) {
216
232
  const message = error instanceof Error ? error.message : String(error);
217
233
  const record = {
@@ -235,7 +251,10 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
235
251
  }
236
252
  throw error;
237
253
  } finally {
238
- if (!isBackground) signal?.removeEventListener?.("abort", abort);
254
+ if (!isBackground) {
255
+ releaseLock({ cwd: options.worktree?.path ?? project.root, owner: reservedId });
256
+ signal?.removeEventListener?.("abort", abort);
257
+ }
239
258
  }
240
259
  }
241
260
 
@@ -35,13 +35,108 @@ function homeDirectory(home) {
35
35
  return home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
36
36
  }
37
37
 
38
+ function digestOf(root) {
39
+ return crypto.createHash("sha256").update(String(root).toLowerCase()).digest("hex").slice(0, 16);
40
+ }
41
+
38
42
  function checkpointDir(root, home) {
39
- const digest = crypto.createHash("sha256").update(root.toLowerCase()).digest("hex").slice(0, 16);
40
- return path.join(homeDirectory(home), "agent-extensions", "checkpoints", digest);
43
+ return path.join(homeDirectory(home), "agent-extensions", "checkpoints", digestOf(root));
44
+ }
45
+
46
+ function fileCheckpointDir(root, home) {
47
+ return path.join(homeDirectory(home), "agent-extensions", "file-checkpoints", digestOf(root));
48
+ }
49
+
50
+ const FILE_SKIP = /(?:^|[\\/])(?:node_modules|\.git|\.dsh|dist|build|coverage|\.cache|vendor|\.next|target|\.ssh|\.aws|\.azure|\.gnupg)(?:[\\/]|$)|(?:^|[\\/])\.env(?:\.|$)|(?:^|[\\/])(?:\.npmrc|\.git-credentials|credentials)(?:[\\/]|$)|\.(?:pem|key|pfx|p12|kdbx)$/iu;
51
+ const FILE_LIMIT = 5000;
52
+ const BYTE_LIMIT = 200 * 1024 * 1024;
53
+
54
+ function resolveRoot(cwd) {
55
+ try {
56
+ return { root: repoRoot(cwd), kind: "git" };
57
+ } catch {
58
+ return { root: path.resolve(cwd || process.cwd()), kind: "files" };
59
+ }
60
+ }
61
+
62
+ function walkFiles(root, relative = "", state = { files: [], bytes: 0 }) {
63
+ const directory = path.join(root, relative);
64
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
65
+ const rel = relative ? path.join(relative, entry.name) : entry.name;
66
+ if (FILE_SKIP.test(rel)) continue;
67
+ const full = path.join(root, rel);
68
+ if (entry.isSymbolicLink()) continue;
69
+ if (entry.isDirectory()) {
70
+ walkFiles(root, rel, state);
71
+ continue;
72
+ }
73
+ if (!entry.isFile()) continue;
74
+ const size = fs.statSync(full).size;
75
+ state.files.push(rel);
76
+ state.bytes += size;
77
+ if (state.files.length > FILE_LIMIT) throw new Error(`checkpoint: больше ${FILE_LIMIT} файлов; укажите меньшую папку`);
78
+ if (state.bytes > BYTE_LIMIT) throw new Error(`checkpoint: больше ${Math.round(BYTE_LIMIT / 1024 / 1024)} МБ; укажите меньшую папку`);
79
+ }
80
+ return state;
81
+ }
82
+
83
+ function copyFiles(root, destination, files) {
84
+ for (const rel of files) {
85
+ const target = path.join(destination, rel);
86
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
87
+ fs.copyFileSync(path.join(root, rel), target);
88
+ }
89
+ }
90
+
91
+ function createFileCheckpoint({ cwd, label, home }) {
92
+ const root = path.resolve(cwd || process.cwd());
93
+ const id = `cp-${new Date().toISOString().replace(/[-:T.Z]/gu, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;
94
+ const state = walkFiles(root);
95
+ const directory = path.join(fileCheckpointDir(root, home), id);
96
+ fs.mkdirSync(path.join(directory, "files"), { recursive: true, mode: 0o700 });
97
+ copyFiles(root, path.join(directory, "files"), state.files);
98
+ const meta = {
99
+ id,
100
+ kind: "files",
101
+ label: String(label ?? ""),
102
+ createdAt: new Date().toISOString(),
103
+ root,
104
+ files: state.files.length,
105
+ bytes: state.bytes,
106
+ snapshot: path.join(directory, "files"),
107
+ };
108
+ fs.writeFileSync(path.join(directory, "meta.json"), `${JSON.stringify(meta, null, 2)}\n`, { mode: 0o600 });
109
+ return meta;
110
+ }
111
+
112
+ function listFileCheckpoints(root, home) {
113
+ const directory = fileCheckpointDir(root, home);
114
+ if (!fs.existsSync(directory)) return [];
115
+ return fs.readdirSync(directory)
116
+ .filter((name) => /^cp-[^\\/]+$/u.test(name))
117
+ .map((name) => {
118
+ try {
119
+ return JSON.parse(fs.readFileSync(path.join(directory, name, "meta.json"), "utf8"));
120
+ } catch {
121
+ return null;
122
+ }
123
+ })
124
+ .filter(Boolean);
125
+ }
126
+
127
+ function restoreFileCheckpoint(checkpoint) {
128
+ const snapshot = checkpoint.snapshot;
129
+ if (!snapshot || !fs.existsSync(snapshot)) throw new Error(`checkpoint snapshot not found: ${checkpoint.id}`);
130
+ const files = walkFiles(snapshot).files;
131
+ copyFiles(snapshot, checkpoint.root, files);
132
+ return checkpoint;
41
133
  }
42
134
 
135
+
43
136
  export function createCheckpoint({ cwd, label = "", home } = {}) {
44
- const root = repoRoot(cwd);
137
+ const resolved = resolveRoot(cwd);
138
+ if (resolved.kind === "files") return createFileCheckpoint({ cwd, label, home });
139
+ const root = resolved.root;
45
140
  const id = `cp-${new Date().toISOString().replace(/[-:T.Z]/gu, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;
46
141
  const indexPath = path.join(os.tmpdir(), `dsh-agent-extensions-index-${process.pid}-${Date.now()}`);
47
142
  const env = { GIT_INDEX_FILE: indexPath };
@@ -59,6 +154,7 @@ export function createCheckpoint({ cwd, label = "", home } = {}) {
59
154
  git(root, ["update-ref", `refs/dsh-agent-extensions/${id}`, commit], env);
60
155
  const meta = {
61
156
  id,
157
+ kind: "git",
62
158
  label: String(label ?? ""),
63
159
  createdAt: new Date().toISOString(),
64
160
  repo: root,
@@ -76,7 +172,9 @@ export function createCheckpoint({ cwd, label = "", home } = {}) {
76
172
  }
77
173
 
78
174
  export function listCheckpoints({ cwd, home } = {}) {
79
- const root = repoRoot(cwd);
175
+ const resolved = resolveRoot(cwd);
176
+ const root = resolved.root;
177
+ if (resolved.kind === "files") return listFileCheckpoints(root, home).sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt)));
80
178
  const directory = checkpointDir(root, home);
81
179
  if (!fs.existsSync(directory)) return [];
82
180
  return fs
@@ -94,7 +192,13 @@ export function listCheckpoints({ cwd, home } = {}) {
94
192
  }
95
193
 
96
194
  export function restoreCheckpoint({ cwd, id, home } = {}) {
97
- const root = repoRoot(cwd);
195
+ const resolved = resolveRoot(cwd);
196
+ if (resolved.kind === "files") {
197
+ const checkpoint = listFileCheckpoints(resolved.root, home).find((item) => item.id === id);
198
+ if (!checkpoint) throw new Error(`checkpoint not found: ${id}`);
199
+ return restoreFileCheckpoint(checkpoint);
200
+ }
201
+ const root = resolved.root;
98
202
  const checkpoints = listCheckpoints({ cwd: root, home });
99
203
  const checkpoint = checkpoints.find((item) => item.id === id);
100
204
  if (!checkpoint) throw new Error(`checkpoint not found: ${id}`);
@@ -7,6 +7,8 @@ import path from "node:path";
7
7
  import { spawnSync } from "node:child_process";
8
8
  import { createCheckpoint, listCheckpoints, restoreCheckpoint } from "./checkpoints.js";
9
9
  import { loadAgents, loadCommands, loadHooks, loadVerify, projectFor } from "./project.js";
10
+ import { validateProjectInstructions } from "./instructions.js";
11
+ import { listLocks } from "./locks.js";
10
12
 
11
13
  function sessionProject(ctx) {
12
14
  try {
@@ -100,6 +102,14 @@ function statusText(ctx) {
100
102
  if (project.dsh) {
101
103
  try { checkpoints = listCheckpoints({ cwd: project.root }); } catch { checkpoints = []; }
102
104
  }
105
+ let instructions = { bytes: 0, files: [], findings: [] };
106
+ try { instructions = validateProjectInstructions(project.root); } catch { /* best effort */ }
107
+ let locks = [];
108
+ try { locks = listLocks(); } catch { locks = []; }
109
+ let quality = null;
110
+ try {
111
+ quality = JSON.parse(fs.readFileSync(path.join(project.root, ".dsh", "quality", "mission.json"), "utf8"));
112
+ } catch { quality = null; }
103
113
  return [
104
114
  `Project: ${project.root}`,
105
115
  `.dsh: ${project.dsh ?? "нет"}`,
@@ -107,6 +117,10 @@ function statusText(ctx) {
107
117
  `Commands: ${commands.map((command) => `/${command.name}`).join(", ") || "нет"}`,
108
118
  `Hooks: ${hooks.trusted ? "trusted" : "не доверены"} · событий: ${Object.keys(hooks.hooks ?? {}).length}`,
109
119
  `Checkpoints: ${checkpoints.length}`,
120
+ `Instructions: ${instructions.files.length} файлов · ${instructions.bytes} байт · предупреждений ${instructions.findings.length}`,
121
+ ...instructions.findings.slice(0, 5).map((item) => ` ! ${item.code}: ${item.message}`),
122
+ `Locks: ${locks.length}${locks.length ? ` · ${locks.map((lock) => `${lock.root} (${lock.owner})`).join("; ")}` : ""}`,
123
+ `Quality: ${quality ? `${quality.profile} · ${quality.phase} · гейтов ${Object.values(quality.gates ?? {}).filter((gate) => gate.status === "passed").length}/${Object.keys(quality.gates ?? {}).length}` : "миссии нет (/quality start)"}`,
110
124
  ].join("\n");
111
125
  }
112
126
 
@@ -134,12 +148,32 @@ export function registerCommands(ctx) {
134
148
 
135
149
  register({
136
150
  name: "doctor",
137
- description: "Проверить hooks, agents, commands и checkpoints",
151
+ description: "Проверить hooks, agents, commands, инструкции, locks, quality и checkpoints",
138
152
  input: { hint: "" },
139
153
  recordInput: false,
140
154
  handler: () => ({ kind: "success", text: statusText(ctx) }),
141
155
  });
142
156
 
157
+ register({
158
+ name: "instructions",
159
+ description: "Проверить AGENTS.md/CLAUDE.md: битые @import, устаревшие навыки, дубли, размер",
160
+ input: { hint: "check" },
161
+ recordInput: false,
162
+ handler: () => {
163
+ const project = sessionProject(ctx);
164
+ try {
165
+ const report = validateProjectInstructions(project.root);
166
+ const lines = [
167
+ `Instructions: ${report.files.length} файлов · ${report.bytes} байт`,
168
+ report.findings.length ? report.findings.map((item) => `- ${item.level.toUpperCase()} ${item.code}${item.file ? ` (${item.file}${item.line ? `:${item.line}` : ""})` : ""}: ${item.message}`).join("\n") : "Проблем не найдено.",
169
+ ];
170
+ return { kind: report.ok ? "success" : "error", text: lines.join("\n") };
171
+ } catch (error) {
172
+ return { kind: "error", text: `instructions: ${error instanceof Error ? error.message : String(error)}` };
173
+ }
174
+ },
175
+ });
176
+
143
177
  register({
144
178
  name: "hooks",
145
179
  description: "Статус hooks, trust или отключение",
@@ -218,14 +252,17 @@ export function registerCommands(ctx) {
218
252
  * workspace happened to be first at plugin start. */
219
253
  register({
220
254
  name: "project",
221
- description: "Список или запуск проектных команд из .dsh/commands",
222
- input: { hint: "list | <name> [args]" },
255
+ description: "Список или запуск проектных команд; health — сводка проекта",
256
+ input: { hint: "list | health | <name> [args]" },
223
257
  recordInput: false,
224
258
  handler: ({ rawInput }) => {
225
259
  const project = sessionProject(ctx);
226
260
  const dshDir = project.dsh ?? path.join(project.root, ".dsh");
227
261
  const commands = loadCommands(project.root, dshDir);
228
262
  const input = String(rawInput ?? "").trim();
263
+ if (input === "health" || input === "status" || input === "os") {
264
+ return { kind: "success", text: statusText(ctx) };
265
+ }
229
266
  if (input.length === 0 || input === "list") {
230
267
  return {
231
268
  kind: "success",
@@ -10,6 +10,7 @@
10
10
  * are depth-limited and total-size limited.
11
11
  */
12
12
  import fs from "node:fs";
13
+ import os from "node:os";
13
14
  import path from "node:path";
14
15
  import { projectFor } from "./project.js";
15
16
 
@@ -100,5 +101,99 @@ export function renderProjectInstructions(cwd) {
100
101
  const result = loadProjectInstructions(cwd);
101
102
  if (result.sections.length === 0) return "";
102
103
  const body = result.sections.map((section) => `<instructions source="${section.scope}:${path.relative(result.root, section.file).split(path.sep).join("/")}">\n${section.text}\n</instructions>`).join("\n");
103
- return `<project-instructions>\n${body}\n</project-instructions>`;
104
+ const validation = validateProjectInstructions(cwd);
105
+ const warning = validation.findings.length > 0
106
+ ? `\n<instructions-warning>\n${validation.findings.slice(0, 6).map((item) => `- ${item.level.toUpperCase()} ${item.code}: ${item.message}`).join("\n")}\n</instructions-warning>`
107
+ : "";
108
+ return `<project-instructions>\n${body}${warning}\n</project-instructions>`;
109
+ }
110
+
111
+ const SKILL_PATH = /(?:~[\\/]\.dsh[\\/]skills[\\/]|[\\/]\.dsh[\\/]skills[\\/]|\bskills[\\/])([a-z0-9][a-z0-9-]*)/giu;
112
+ const BACKTICK = /`([a-z0-9][a-z0-9-]*)`/giu;
113
+
114
+ function dshSkillsDir() {
115
+ return path.join(process.env.DSH_HOME || path.join(os.homedir(), ".dsh"), "skills");
116
+ }
117
+
118
+ function skillExists(name) {
119
+ try {
120
+ return fs.existsSync(path.join(dshSkillsDir(), name, "SKILL.md"));
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+
126
+ /** Extract explicit skill references, not every hyphenated word. */
127
+ export function extractSkillReferences(text) {
128
+ const names = new Set();
129
+ for (const match of String(text ?? "").matchAll(SKILL_PATH)) names.add(match[1].toLowerCase());
130
+ const lines = String(text ?? "").split(/\r?\n/u);
131
+ for (const line of lines) {
132
+ if (!/(?:\bskill\b|\bнавык)/iu.test(line)) continue;
133
+ for (const match of line.matchAll(BACKTICK)) names.add(match[1].toLowerCase());
134
+ }
135
+ return [...names];
136
+ }
137
+
138
+ /**
139
+ * Validate project instructions before they reach the model.
140
+ *
141
+ * Findings are advisory: a stale skill reference does not stop the turn, but it
142
+ * is surfaced in the prompt and in `/instructions check`, so drift is visible.
143
+ */
144
+ export function validateProjectInstructions(cwd) {
145
+ const result = loadProjectInstructions(cwd);
146
+ const findings = [];
147
+ const seenFiles = new Set();
148
+ let bytes = 0;
149
+ for (const section of result.sections) {
150
+ bytes += Buffer.byteLength(section.text, "utf8");
151
+ const relative = path.relative(result.root, section.file).split(path.sep).join("/");
152
+ seenFiles.add(relative);
153
+ for (const name of extractSkillReferences(section.text)) {
154
+ if (!skillExists(name)) {
155
+ findings.push({
156
+ level: "warning",
157
+ code: "stale-skill",
158
+ file: relative,
159
+ message: `навык «${name}» указан, но ${path.join(dshSkillsDir(), name, "SKILL.md")} не найден`,
160
+ });
161
+ }
162
+ }
163
+ const raw = fs.readFileSync(section.file, "utf8");
164
+ raw.split(/\r?\n/u).forEach((line, index) => {
165
+ const match = /^\s*@([^\s#]+)\s*$/u.exec(line);
166
+ if (!match) return;
167
+ const target = path.resolve(path.dirname(section.file), match[1]);
168
+ const insideRoot = (() => {
169
+ const rel = path.relative(result.root, target);
170
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
171
+ })();
172
+ if (!insideRoot) {
173
+ findings.push({ level: "warning", code: "import-outside", file: relative, line: index + 1, message: `@import вне проекта: ${match[1]}` });
174
+ } else if (!fs.existsSync(target)) {
175
+ findings.push({ level: "warning", code: "import-missing", file: relative, line: index + 1, message: `@import не найден: ${match[1]}` });
176
+ }
177
+ });
178
+ }
179
+ const rootAgents = path.join(result.root, "AGENTS.md");
180
+ const rootClaude = path.join(result.root, "CLAUDE.md");
181
+ if (fs.existsSync(rootAgents) && fs.existsSync(rootClaude)) {
182
+ findings.push({
183
+ level: "warning",
184
+ code: "duplicate-root",
185
+ file: "AGENTS.md",
186
+ message: "в корне одновременно AGENTS.md и CLAUDE.md: проверьте, нет ли противоречий",
187
+ });
188
+ }
189
+ if (bytes > MAX_BYTES) {
190
+ findings.push({ level: "warning", code: "too-large", file: ".", message: `инструкции ${bytes} байт > ${MAX_BYTES}` });
191
+ }
192
+ return {
193
+ ok: findings.every((item) => item.level !== "error"),
194
+ root: result.root,
195
+ files: [...seenFiles],
196
+ bytes,
197
+ findings,
198
+ };
104
199
  }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Advisory writer locks for project agents.
3
+ *
4
+ * DSH does not serialise two writers in the same project. This lock is a
5
+ * local, best-effort guard: it lives under DSH_HOME, contains no secrets, and
6
+ * expires so a crashed agent cannot block the project forever. It is advisory
7
+ * (other tools can still edit); the value is that two `project_agent` writers
8
+ * no longer start on the same root by accident.
9
+ */
10
+ import crypto from "node:crypto";
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ const DEFAULT_TTL_MS = 15 * 60 * 1000;
16
+
17
+ function homeDirectory(home) {
18
+ return home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
19
+ }
20
+
21
+ function lockDirectory(home) {
22
+ return path.join(homeDirectory(home), "agent-extensions", "locks");
23
+ }
24
+
25
+ function lockFile(root, home) {
26
+ const digest = crypto.createHash("sha256").update(path.resolve(root).toLowerCase()).digest("hex").slice(0, 20);
27
+ return path.join(lockDirectory(home), `${digest}.json`);
28
+ }
29
+
30
+ function readLock(file) {
31
+ try {
32
+ return JSON.parse(fs.readFileSync(file, "utf8"));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function isStale(lock, now = Date.now()) {
39
+ const heartbeat = Date.parse(lock?.heartbeatAt ?? lock?.createdAt ?? "");
40
+ const ttl = Number(lock?.ttlMs) > 0 ? Number(lock.ttlMs) : DEFAULT_TTL_MS;
41
+ return !Number.isFinite(heartbeat) || now - heartbeat > ttl;
42
+ }
43
+
44
+ function safeWrite(file, value) {
45
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
46
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
47
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
48
+ fs.renameSync(temporary, file);
49
+ }
50
+
51
+ export function acquireLock({ cwd, owner, scope = "writer", ttlMs = DEFAULT_TTL_MS, home } = {}) {
52
+ if (!cwd) throw new Error("lock: cwd is required");
53
+ if (!owner) throw new Error("lock: owner is required");
54
+ const root = path.resolve(cwd);
55
+ const file = lockFile(root, home);
56
+ const now = new Date().toISOString();
57
+ const existing = readLock(file);
58
+ if (existing && !isStale(existing)) {
59
+ if (String(existing.owner) === String(owner)) {
60
+ const refreshed = { ...existing, heartbeatAt: now };
61
+ safeWrite(file, refreshed);
62
+ return { ok: true, lock: refreshed, refreshed: true };
63
+ }
64
+ return { ok: false, holder: existing, file };
65
+ }
66
+ const lock = {
67
+ id: crypto.randomUUID(),
68
+ root,
69
+ owner: String(owner),
70
+ scope: String(scope),
71
+ pid: process.pid,
72
+ createdAt: now,
73
+ heartbeatAt: now,
74
+ ttlMs: Number(ttlMs) > 0 ? Number(ttlMs) : DEFAULT_TTL_MS,
75
+ };
76
+ safeWrite(file, lock);
77
+ return { ok: true, lock, refreshed: false };
78
+ }
79
+
80
+ export function releaseLock({ cwd, owner, home } = {}) {
81
+ if (!cwd || !owner) return { ok: false, reason: "cwd and owner are required" };
82
+ const file = lockFile(cwd, home);
83
+ const existing = readLock(file);
84
+ if (!existing) return { ok: true, released: false };
85
+ if (String(existing.owner) !== String(owner)) return { ok: false, reason: "lock belongs to another owner", holder: existing };
86
+ fs.rmSync(file, { force: true });
87
+ return { ok: true, released: true };
88
+ }
89
+
90
+ export function refreshLock({ cwd, owner, home } = {}) {
91
+ const file = lockFile(cwd, home);
92
+ const existing = readLock(file);
93
+ if (!existing || String(existing.owner) !== String(owner)) return { ok: false, reason: "lock not held by owner" };
94
+ const refreshed = { ...existing, heartbeatAt: new Date().toISOString() };
95
+ safeWrite(file, refreshed);
96
+ return { ok: true, lock: refreshed };
97
+ }
98
+
99
+ export function listLocks({ home, includeStale = false } = {}) {
100
+ const directory = lockDirectory(home);
101
+ if (!fs.existsSync(directory)) return [];
102
+ return fs.readdirSync(directory)
103
+ .filter((name) => name.endsWith(".json"))
104
+ .map((name) => readLock(path.join(directory, name)))
105
+ .filter(Boolean)
106
+ .filter((lock) => includeStale || !isStale(lock))
107
+ .sort((left, right) => String(right.heartbeatAt).localeCompare(String(left.heartbeatAt)));
108
+ }
109
+
110
+ export function lockCount({ home } = {}) {
111
+ return listLocks({ home }).length;
112
+ }
113
+
114
+ export const LOCK_TTL_MS = DEFAULT_TTL_MS;
@@ -22,6 +22,8 @@ export function setChildPolicy(childId, definition) {
22
22
  policies.set(String(childId), {
23
23
  name: definition?.name ?? "project-agent",
24
24
  allowed: parseAllowedTools(definition?.tools),
25
+ disallowed: parseAllowedTools(definition?.disallowedTools ?? definition?.disallowed_tools),
26
+ maxTurns: Number(definition?.maxTurns ?? definition?.max_turns ?? 0) || 0,
25
27
  permission: definition?.permission === "read-only" || definition?.permission === "workspace-write"
26
28
  ? definition.permission
27
29
  : "full",
@@ -51,6 +53,9 @@ export function checkChildTool(exec) {
51
53
  if (policy.allowed.size > 0 && !policy.allowed.has(tool)) {
52
54
  return { kind: "deny", reason: `subagent ${policy.name}: tool ${tool} не входит в allowlist` };
53
55
  }
56
+ if (policy.disallowed.size > 0 && policy.disallowed.has(tool)) {
57
+ return { kind: "deny", reason: `subagent ${policy.name}: tool ${tool} запрещён disallowed_tools` };
58
+ }
54
59
  return null;
55
60
  }
56
61
 
@@ -9,7 +9,7 @@ import fs from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
 
12
- export const BUILTIN_COMMANDS = new Set(["init", "doctor", "verify", "hooks", "checkpoint", "rewind", "project"]);
12
+ export const BUILTIN_COMMANDS = new Set(["init", "doctor", "verify", "hooks", "checkpoint", "rewind", "project", "instructions"]);
13
13
 
14
14
  function dshHome() {
15
15
  return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
@@ -88,6 +88,12 @@ export function loadAgents(projectDir, dshDir) {
88
88
  model: typeof parsed.meta.model === "string" ? parsed.meta.model : "",
89
89
  effort: typeof parsed.meta.effort === "string" ? parsed.meta.effort : "",
90
90
  tools: typeof parsed.meta.tools === "string" ? parsed.meta.tools : "",
91
+ disallowedTools: typeof parsed.meta.disallowed_tools === "string" ? parsed.meta.disallowed_tools : "",
92
+ maxTurns: Number.isInteger(Number(parsed.meta.max_turns)) && Number(parsed.meta.max_turns) > 0 ? Number(parsed.meta.max_turns) : 0,
93
+ skills: typeof parsed.meta.skills === "string" ? parsed.meta.skills : "",
94
+ isolation: typeof parsed.meta.isolation === "string" ? parsed.meta.isolation : "",
95
+ memory: typeof parsed.meta.memory === "string" ? parsed.meta.memory : "",
96
+ background: parsed.meta.background === true,
91
97
  permission: typeof parsed.meta.permission === "string" ? parsed.meta.permission : "full",
92
98
  output: typeof parsed.meta.output === "string" ? parsed.meta.output : "",
93
99
  body: parsed.body,