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.
@@ -11,6 +11,7 @@ import fs from "node:fs";
11
11
  import os from "node:os";
12
12
  import path from "node:path";
13
13
  import { spawnSync } from "node:child_process";
14
+ import { scanTextForSecrets } from "../../dsh-guardrails/lib/secrets.js";
14
15
 
15
16
  function git(cwd, args, env, allowFail = false) {
16
17
  const result = spawnSync("git", args, {
@@ -35,13 +36,153 @@ function homeDirectory(home) {
35
36
  return home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
36
37
  }
37
38
 
39
+ function digestOf(root) {
40
+ return crypto.createHash("sha256").update(String(root).toLowerCase()).digest("hex").slice(0, 16);
41
+ }
42
+
38
43
  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);
44
+ return path.join(homeDirectory(home), "agent-extensions", "checkpoints", digestOf(root));
45
+ }
46
+
47
+ function fileCheckpointDir(root, home) {
48
+ return path.join(homeDirectory(home), "agent-extensions", "file-checkpoints", digestOf(root));
41
49
  }
42
50
 
51
+ 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;
52
+ const FILE_LIMIT = 5000;
53
+ const BYTE_LIMIT = 200 * 1024 * 1024;
54
+ const SECRET_SCAN_BYTES = 512 * 1024;
55
+ const RETENTION = 20;
56
+
57
+ function resolveRoot(cwd) {
58
+ try {
59
+ return { root: repoRoot(cwd), kind: "git" };
60
+ } catch {
61
+ return { root: path.resolve(cwd || process.cwd()), kind: "files" };
62
+ }
63
+ }
64
+
65
+ function walkFiles(root, relative = "", state = { files: [], bytes: 0 }) {
66
+ const directory = path.join(root, relative);
67
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
68
+ const rel = relative ? path.join(relative, entry.name) : entry.name;
69
+ if (FILE_SKIP.test(rel)) continue;
70
+ const full = path.join(root, rel);
71
+ if (entry.isSymbolicLink()) continue;
72
+ if (entry.isDirectory()) {
73
+ walkFiles(root, rel, state);
74
+ continue;
75
+ }
76
+ if (!entry.isFile()) continue;
77
+ const size = fs.statSync(full).size;
78
+ state.files.push(rel);
79
+ state.bytes += size;
80
+ if (state.files.length > FILE_LIMIT) throw new Error(`checkpoint: больше ${FILE_LIMIT} файлов; укажите меньшую папку`);
81
+ if (state.bytes > BYTE_LIMIT) throw new Error(`checkpoint: больше ${Math.round(BYTE_LIMIT / 1024 / 1024)} МБ; укажите меньшую папку`);
82
+ }
83
+ return state;
84
+ }
85
+
86
+ function copyFiles(root, destination, files, { scanSecrets = false } = {}) {
87
+ const skipped = [];
88
+ for (const rel of files) {
89
+ const source = path.join(root, rel);
90
+ if (scanSecrets) {
91
+ try {
92
+ if (fs.statSync(source).size <= SECRET_SCAN_BYTES) {
93
+ const text = fs.readFileSync(source, "utf8");
94
+ if (scanTextForSecrets(text, { maxFindings: 1 }).length > 0) {
95
+ skipped.push(rel);
96
+ continue;
97
+ }
98
+ }
99
+ } catch {
100
+ skipped.push(rel);
101
+ continue;
102
+ }
103
+ }
104
+ const target = path.join(destination, rel);
105
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
106
+ fs.copyFileSync(source, target);
107
+ }
108
+ return { skipped };
109
+ }
110
+
111
+ function createFileCheckpoint({ cwd, label, home }) {
112
+ const root = path.resolve(cwd || process.cwd());
113
+ const id = `cp-${new Date().toISOString().replace(/[-:T.Z]/gu, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;
114
+ const state = walkFiles(root);
115
+ const parent = fileCheckpointDir(root, home);
116
+ const finalDirectory = path.join(parent, id);
117
+ const temporary = path.join(parent, `${id}.tmp-${process.pid}-${crypto.randomBytes(3).toString("hex")}`);
118
+ let copied;
119
+ try {
120
+ fs.mkdirSync(path.join(temporary, "files"), { recursive: true, mode: 0o700 });
121
+ copied = copyFiles(root, path.join(temporary, "files"), state.files, { scanSecrets: true });
122
+ const meta = {
123
+ id,
124
+ kind: "files",
125
+ label: String(label ?? ""),
126
+ createdAt: new Date().toISOString(),
127
+ root,
128
+ files: state.files.length - copied.skipped.length,
129
+ skippedSecrets: copied.skipped.length,
130
+ bytes: state.bytes,
131
+ snapshot: path.join(finalDirectory, "files"),
132
+ };
133
+ fs.writeFileSync(path.join(temporary, "meta.json"), `${JSON.stringify(meta, null, 2)}\n`, { mode: 0o600 });
134
+ fs.renameSync(temporary, finalDirectory);
135
+ pruneFileCheckpoints(root, home);
136
+ return meta;
137
+ } catch (error) {
138
+ try { fs.rmSync(temporary, { recursive: true, force: true }); } catch { /* best effort */ }
139
+ throw error;
140
+ }
141
+ }
142
+
143
+ function pruneFileCheckpoints(root, home) {
144
+ const directory = fileCheckpointDir(root, home);
145
+ if (!fs.existsSync(directory)) return;
146
+ const entries = fs.readdirSync(directory)
147
+ .filter((name) => /^cp-[^\\/]+$/u.test(name))
148
+ .map((name) => {
149
+ try { return { name, at: fs.statSync(path.join(directory, name)).mtimeMs }; } catch { return null; }
150
+ })
151
+ .filter(Boolean)
152
+ .sort((left, right) => right.at - left.at);
153
+ for (const entry of entries.slice(RETENTION)) {
154
+ try { fs.rmSync(path.join(directory, entry.name), { recursive: true, force: true }); } catch { /* best effort */ }
155
+ }
156
+ }
157
+
158
+ function listFileCheckpoints(root, home) {
159
+ const directory = fileCheckpointDir(root, home);
160
+ if (!fs.existsSync(directory)) return [];
161
+ return fs.readdirSync(directory)
162
+ .filter((name) => /^cp-[^\\/]+$/u.test(name))
163
+ .map((name) => {
164
+ try {
165
+ return JSON.parse(fs.readFileSync(path.join(directory, name, "meta.json"), "utf8"));
166
+ } catch {
167
+ return null;
168
+ }
169
+ })
170
+ .filter(Boolean);
171
+ }
172
+
173
+ function restoreFileCheckpoint(checkpoint) {
174
+ const snapshot = checkpoint.snapshot;
175
+ if (!snapshot || !fs.existsSync(snapshot)) throw new Error(`checkpoint snapshot not found: ${checkpoint.id}`);
176
+ const files = walkFiles(snapshot).files;
177
+ copyFiles(snapshot, checkpoint.root, files);
178
+ return checkpoint;
179
+ }
180
+
181
+
43
182
  export function createCheckpoint({ cwd, label = "", home } = {}) {
44
- const root = repoRoot(cwd);
183
+ const resolved = resolveRoot(cwd);
184
+ if (resolved.kind === "files") return createFileCheckpoint({ cwd, label, home });
185
+ const root = resolved.root;
45
186
  const id = `cp-${new Date().toISOString().replace(/[-:T.Z]/gu, "").slice(0, 14)}-${crypto.randomBytes(3).toString("hex")}`;
46
187
  const indexPath = path.join(os.tmpdir(), `dsh-agent-extensions-index-${process.pid}-${Date.now()}`);
47
188
  const env = { GIT_INDEX_FILE: indexPath };
@@ -59,6 +200,7 @@ export function createCheckpoint({ cwd, label = "", home } = {}) {
59
200
  git(root, ["update-ref", `refs/dsh-agent-extensions/${id}`, commit], env);
60
201
  const meta = {
61
202
  id,
203
+ kind: "git",
62
204
  label: String(label ?? ""),
63
205
  createdAt: new Date().toISOString(),
64
206
  repo: root,
@@ -76,7 +218,9 @@ export function createCheckpoint({ cwd, label = "", home } = {}) {
76
218
  }
77
219
 
78
220
  export function listCheckpoints({ cwd, home } = {}) {
79
- const root = repoRoot(cwd);
221
+ const resolved = resolveRoot(cwd);
222
+ const root = resolved.root;
223
+ if (resolved.kind === "files") return listFileCheckpoints(root, home).sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt)));
80
224
  const directory = checkpointDir(root, home);
81
225
  if (!fs.existsSync(directory)) return [];
82
226
  return fs
@@ -94,7 +238,13 @@ export function listCheckpoints({ cwd, home } = {}) {
94
238
  }
95
239
 
96
240
  export function restoreCheckpoint({ cwd, id, home } = {}) {
97
- const root = repoRoot(cwd);
241
+ const resolved = resolveRoot(cwd);
242
+ if (resolved.kind === "files") {
243
+ const checkpoint = listFileCheckpoints(resolved.root, home).find((item) => item.id === id);
244
+ if (!checkpoint) throw new Error(`checkpoint not found: ${id}`);
245
+ return restoreFileCheckpoint(checkpoint);
246
+ }
247
+ const root = resolved.root;
98
248
  const checkpoints = listCheckpoints({ cwd: root, home });
99
249
  const checkpoint = checkpoints.find((item) => item.id === id);
100
250
  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.slice(0, 5).map((lock) => `${lock.root} (${lock.owner})`).join("; ")}${locks.length > 5 ? " …" : ""}` : ""}`,
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,114 @@ 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 kitSkillCatalog() {
119
+ try {
120
+ const manifest = JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, "../../../skills/manifest.json"), "utf8"));
121
+ const raw = manifest?.skills;
122
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return new Set(Object.keys(raw).map((name) => name.toLowerCase()));
123
+ if (Array.isArray(raw)) return new Set(raw.map((item) => String(item?.name ?? "").toLowerCase()).filter(Boolean));
124
+ return null;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ const KIT_SKILLS = kitSkillCatalog();
131
+
132
+ function skillExists(name) {
133
+ try {
134
+ if (fs.existsSync(path.join(dshSkillsDir(), name, "SKILL.md"))) return true;
135
+ } catch {
136
+ /* fall through to the kit catalog */
137
+ }
138
+ return Boolean(KIT_SKILLS?.has(name));
139
+ }
140
+
141
+ /** Extract explicit skill references, not every hyphenated word. */
142
+ export function extractSkillReferences(text) {
143
+ const names = new Set();
144
+ for (const match of String(text ?? "").matchAll(SKILL_PATH)) names.add(match[1].toLowerCase());
145
+ const lines = String(text ?? "").split(/\r?\n/u);
146
+ for (const line of lines) {
147
+ if (!/(?:\bskill\b|\bнавык)/iu.test(line)) continue;
148
+ for (const match of line.matchAll(BACKTICK)) names.add(match[1].toLowerCase());
149
+ }
150
+ return [...names];
151
+ }
152
+
153
+ /**
154
+ * Validate project instructions before they reach the model.
155
+ *
156
+ * Findings are advisory: a stale skill reference does not stop the turn, but it
157
+ * is surfaced in the prompt and in `/instructions check`, so drift is visible.
158
+ */
159
+ export function validateProjectInstructions(cwd) {
160
+ const result = loadProjectInstructions(cwd);
161
+ const findings = [];
162
+ const seenFiles = new Set();
163
+ let bytes = 0;
164
+ for (const section of result.sections) {
165
+ bytes += Buffer.byteLength(section.text, "utf8");
166
+ const relative = path.relative(result.root, section.file).split(path.sep).join("/");
167
+ seenFiles.add(relative);
168
+ for (const name of extractSkillReferences(section.text)) {
169
+ if (!skillExists(name)) {
170
+ findings.push({
171
+ level: "warning",
172
+ code: "stale-skill",
173
+ file: relative,
174
+ message: `навык «${name}» указан, но ${path.join(dshSkillsDir(), name, "SKILL.md")} не найден`,
175
+ });
176
+ }
177
+ }
178
+ const raw = fs.readFileSync(section.file, "utf8");
179
+ raw.split(/\r?\n/u).forEach((line, index) => {
180
+ const match = /^\s*@([^\s#]+)\s*$/u.exec(line);
181
+ if (!match) return;
182
+ const target = path.resolve(path.dirname(section.file), match[1]);
183
+ const insideRoot = (() => {
184
+ const rel = path.relative(result.root, target);
185
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
186
+ })();
187
+ if (!insideRoot) {
188
+ findings.push({ level: "warning", code: "import-outside", file: relative, line: index + 1, message: `@import вне проекта: ${match[1]}` });
189
+ } else if (!fs.existsSync(target)) {
190
+ findings.push({ level: "warning", code: "import-missing", file: relative, line: index + 1, message: `@import не найден: ${match[1]}` });
191
+ }
192
+ });
193
+ }
194
+ const rootAgents = path.join(result.root, "AGENTS.md");
195
+ const rootClaude = path.join(result.root, "CLAUDE.md");
196
+ if (fs.existsSync(rootAgents) && fs.existsSync(rootClaude)) {
197
+ findings.push({
198
+ level: "warning",
199
+ code: "duplicate-root",
200
+ file: "AGENTS.md",
201
+ message: "в корне одновременно AGENTS.md и CLAUDE.md: проверьте, нет ли противоречий",
202
+ });
203
+ }
204
+ if (bytes > MAX_BYTES) {
205
+ findings.push({ level: "warning", code: "too-large", file: ".", message: `инструкции ${bytes} байт > ${MAX_BYTES}` });
206
+ }
207
+ return {
208
+ ok: findings.every((item) => item.level !== "error"),
209
+ root: result.root,
210
+ files: [...seenFiles],
211
+ bytes,
212
+ findings,
213
+ };
104
214
  }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Advisory writer locks for project agents.
3
+ *
4
+ * The lock is acquired atomically with O_EXCL (`wx`), refreshed by a heartbeat,
5
+ * and released by the owner. It is still advisory: other tools can edit the
6
+ * project; the value is that two `project_agent` writers do not start on the
7
+ * same root by accident. A dead PID or an expired heartbeat makes a lock
8
+ * stealable, so a crashed agent cannot block the project forever.
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
+ const HEARTBEAT_MS = 30 * 1000;
17
+ const heartbeats = new Map();
18
+
19
+ function homeDirectory(home) {
20
+ return home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
21
+ }
22
+
23
+ function lockDirectory(home) {
24
+ return path.join(homeDirectory(home), "agent-extensions", "locks");
25
+ }
26
+
27
+ function lockFile(root, home) {
28
+ const digest = crypto.createHash("sha256").update(path.resolve(root).toLowerCase()).digest("hex").slice(0, 20);
29
+ return path.join(lockDirectory(home), `${digest}.json`);
30
+ }
31
+
32
+ function readLock(file) {
33
+ try {
34
+ return JSON.parse(fs.readFileSync(file, "utf8"));
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ function processAlive(pid) {
41
+ if (!Number.isInteger(pid) || pid <= 0) return false;
42
+ try {
43
+ process.kill(pid, 0);
44
+ return true;
45
+ } catch (error) {
46
+ return error?.code === "EPERM";
47
+ }
48
+ }
49
+
50
+ function isStale(lock, now = Date.now()) {
51
+ const heartbeat = Date.parse(lock?.heartbeatAt ?? lock?.createdAt ?? "");
52
+ const ttl = Number(lock?.ttlMs) > 0 ? Number(lock.ttlMs) : DEFAULT_TTL_MS;
53
+ if (!Number.isFinite(heartbeat) || now - heartbeat > ttl) return true;
54
+ return !processAlive(Number(lock?.pid));
55
+ }
56
+
57
+ function atomicWrite(file, value) {
58
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
59
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
60
+ fs.renameSync(temporary, file);
61
+ }
62
+
63
+ function createExclusive(file, value) {
64
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
65
+ const fd = fs.openSync(file, "wx", 0o600);
66
+ try {
67
+ fs.writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`);
68
+ } finally {
69
+ fs.closeSync(fd);
70
+ }
71
+ }
72
+
73
+ function stopHeartbeat(file) {
74
+ const timer = heartbeats.get(file);
75
+ if (timer) clearInterval(timer);
76
+ heartbeats.delete(file);
77
+ }
78
+
79
+ function startHeartbeat(file, owner) {
80
+ stopHeartbeat(file);
81
+ const timer = setInterval(() => {
82
+ try {
83
+ const current = readLock(file);
84
+ if (!current || String(current.owner) !== String(owner)) {
85
+ stopHeartbeat(file);
86
+ return;
87
+ }
88
+ atomicWrite(file, { ...current, heartbeatAt: new Date().toISOString() });
89
+ } catch {
90
+ stopHeartbeat(file);
91
+ }
92
+ }, HEARTBEAT_MS);
93
+ timer.unref?.();
94
+ heartbeats.set(file, timer);
95
+ }
96
+
97
+ export function acquireLock({ cwd, owner, scope = "writer", ttlMs = DEFAULT_TTL_MS, home } = {}) {
98
+ if (!cwd) throw new Error("lock: cwd is required");
99
+ if (!owner) throw new Error("lock: owner is required");
100
+ const root = path.resolve(cwd);
101
+ const file = lockFile(root, home);
102
+ const now = new Date().toISOString();
103
+ const lock = {
104
+ id: crypto.randomUUID(),
105
+ root,
106
+ owner: String(owner),
107
+ scope: String(scope),
108
+ pid: process.pid,
109
+ createdAt: now,
110
+ heartbeatAt: now,
111
+ ttlMs: Number(ttlMs) > 0 ? Number(ttlMs) : DEFAULT_TTL_MS,
112
+ };
113
+ for (let attempt = 0; attempt < 3; attempt += 1) {
114
+ try {
115
+ createExclusive(file, lock);
116
+ startHeartbeat(file, owner);
117
+ return { ok: true, lock, refreshed: false, stop: () => stopHeartbeat(file) };
118
+ } catch (error) {
119
+ if (error?.code !== "EEXIST") throw error;
120
+ const existing = readLock(file);
121
+ if (!existing) continue;
122
+ if (String(existing.owner) === String(owner)) {
123
+ const refreshed = { ...existing, heartbeatAt: now };
124
+ atomicWrite(file, refreshed);
125
+ startHeartbeat(file, owner);
126
+ return { ok: true, lock: refreshed, refreshed: true, stop: () => stopHeartbeat(file) };
127
+ }
128
+ if (!isStale(existing)) return { ok: false, holder: existing, file };
129
+ try { fs.rmSync(file, { force: true }); } catch { /* another contender may win */ }
130
+ }
131
+ }
132
+ return { ok: false, holder: readLock(file) ?? null, file };
133
+ }
134
+
135
+ export function releaseLock({ cwd, owner, home } = {}) {
136
+ if (!cwd || !owner) return { ok: false, reason: "cwd and owner are required" };
137
+ const file = lockFile(cwd, home);
138
+ const existing = readLock(file);
139
+ if (!existing) {
140
+ stopHeartbeat(file);
141
+ return { ok: true, released: false };
142
+ }
143
+ if (String(existing.owner) !== String(owner)) return { ok: false, reason: "lock belongs to another owner", holder: existing };
144
+ stopHeartbeat(file);
145
+ fs.rmSync(file, { force: true });
146
+ return { ok: true, released: true };
147
+ }
148
+
149
+ export function refreshLock({ cwd, owner, home } = {}) {
150
+ const file = lockFile(cwd, home);
151
+ const existing = readLock(file);
152
+ if (!existing || String(existing.owner) !== String(owner)) return { ok: false, reason: "lock not held by owner" };
153
+ const refreshed = { ...existing, heartbeatAt: new Date().toISOString() };
154
+ atomicWrite(file, refreshed);
155
+ return { ok: true, lock: refreshed };
156
+ }
157
+
158
+ export function listLocks({ home, includeStale = false } = {}) {
159
+ const directory = lockDirectory(home);
160
+ if (!fs.existsSync(directory)) return [];
161
+ return fs.readdirSync(directory)
162
+ .filter((name) => name.endsWith(".json"))
163
+ .map((name) => readLock(path.join(directory, name)))
164
+ .filter(Boolean)
165
+ .filter((lock) => includeStale || !isStale(lock))
166
+ .sort((left, right) => String(right.heartbeatAt).localeCompare(String(left.heartbeatAt)));
167
+ }
168
+
169
+ export function lockCount({ home } = {}) {
170
+ return listLocks({ home }).length;
171
+ }
172
+
173
+ export const LOCK_TTL_MS = DEFAULT_TTL_MS;
174
+ export const LOCK_HEARTBEAT_MS = HEARTBEAT_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,