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.
- package/CHANGELOG.md +23 -0
- package/README.en.md +22 -6
- package/README.md +33 -9
- package/client.js +1 -1
- package/docs/MEASURED.md +7 -7
- package/docs/TEST-2.32.0.md +32 -0
- package/docs/TEST-2.33.0.md +33 -0
- package/docs/measured.json +9 -9
- package/package.json +2 -1
- package/plugins/dsh-agent-extensions/lib/agents.js +20 -1
- package/plugins/dsh-agent-extensions/lib/checkpoints.js +109 -5
- package/plugins/dsh-agent-extensions/lib/commands.js +40 -3
- package/plugins/dsh-agent-extensions/lib/instructions.js +96 -1
- package/plugins/dsh-agent-extensions/lib/locks.js +114 -0
- package/plugins/dsh-agent-extensions/lib/policy.js +5 -0
- package/plugins/dsh-agent-extensions/lib/project.js +7 -1
- package/plugins/dsh-agent-extensions/lib/scaffold.js +14 -14
- package/plugins/dsh-browser-qa/lib/ui-gate.js +5 -1
- package/plugins/dsh-guardrails/index.js +31 -4
- package/plugins/dsh-guardrails/lib/hooks.js +22 -5
- package/plugins/dsh-guardrails/lib/runtime.js +122 -0
- package/plugins/dsh-project-memory/index.js +28 -3
- package/plugins/dsh-quality-pipeline/index.js +14 -3
- package/plugins/dsh-quality-pipeline/lib/text.js +1 -1
|
@@ -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: "Список или запуск проектных
|
|
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
|
-
|
|
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,
|
|
@@ -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
|
"---",
|
|
@@ -282,7 +282,8 @@ export function createUiGate(ctx) {
|
|
|
282
282
|
if (!strict) return missing;
|
|
283
283
|
if (!state.a11yAt || state.a11yAt < state.lastEditAt) missing.push("a11y-missing");
|
|
284
284
|
else if (Number(state.a11y?.serious ?? 0) > 0) missing.push("a11y-issues");
|
|
285
|
-
if (state.interactAt
|
|
285
|
+
if (!state.interactAt || state.interactAt < state.lastEditAt) missing.push("interact-missing");
|
|
286
|
+
else if (state.interact && state.interact.pass !== true) missing.push("interact-fail");
|
|
286
287
|
return missing;
|
|
287
288
|
}
|
|
288
289
|
|
|
@@ -307,6 +308,9 @@ export function createUiGate(ctx) {
|
|
|
307
308
|
if (missing.includes("a11y-issues")) {
|
|
308
309
|
lines.push(`browser_qa a11y нашёл serious ${state.a11y?.serious ?? "?"}: почини и прогони a11y заново — порог 0.`);
|
|
309
310
|
}
|
|
311
|
+
if (missing.includes("interact-missing")) {
|
|
312
|
+
lines.push("Гейт качества требует поведение, а не только геометрию: запусти browser_qa action=interact хотя бы по одному ключевому сценарию (меню, форма, модалка) и приложи PASS.");
|
|
313
|
+
}
|
|
310
314
|
if (missing.includes("interact-fail")) {
|
|
311
315
|
lines.push("Сценарий browser_qa action=interact упал: элемент перекрыт, невидим или не прошло ожидание. Почини и прогони сценарий заново.");
|
|
312
316
|
}
|
|
@@ -32,13 +32,14 @@ import {
|
|
|
32
32
|
policyPath,
|
|
33
33
|
} from "./lib/policy.js";
|
|
34
34
|
import { scanProject } from "./lib/scan.js";
|
|
35
|
+
import { createRuntimeState } from "./lib/runtime.js";
|
|
35
36
|
|
|
36
37
|
/** Tool and hook plugin depends on the tool registry only. */
|
|
37
38
|
export const inject = ["tools"];
|
|
38
39
|
|
|
39
40
|
const PLUGIN_NAME = "dsh-guardrails";
|
|
40
41
|
const PLUGIN_VERSION = "1.0.0";
|
|
41
|
-
const ACTIONS = ["status", "check", "policy"];
|
|
42
|
+
const ACTIONS = ["status", "check", "policy", "runtime"];
|
|
42
43
|
const DEFAULT_ACTION = "status";
|
|
43
44
|
const TEXT_LIMIT = 24_000;
|
|
44
45
|
|
|
@@ -306,6 +307,30 @@ function renderScanReport(value) {
|
|
|
306
307
|
return lines.join("\n");
|
|
307
308
|
}
|
|
308
309
|
|
|
310
|
+
/* ------------------------------------------------------------------ */
|
|
311
|
+
/* runtime */
|
|
312
|
+
/* ------------------------------------------------------------------ */
|
|
313
|
+
|
|
314
|
+
function runtimeValue(runtime, mode) {
|
|
315
|
+
const snapshot = runtime.snapshot();
|
|
316
|
+
const lines = [
|
|
317
|
+
"Guardrails runtime (in-memory, no command text):",
|
|
318
|
+
`permission: ${mode ? `${mode.name} (sandbox=${mode.sandbox}, approval=${mode.approval ?? "default"})` : "unknown (no DSH permission preset)"}`,
|
|
319
|
+
`decisions: ${snapshot.count} · ask ${snapshot.asks} · deny ${snapshot.denies}`,
|
|
320
|
+
];
|
|
321
|
+
if (!snapshot.last) {
|
|
322
|
+
lines.push("Последних ask/deny нет: за этот процесс не было решений.");
|
|
323
|
+
} else {
|
|
324
|
+
for (const item of snapshot.decisions) {
|
|
325
|
+
lines.push(
|
|
326
|
+
`- ${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}`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
lines.push("DSH владеет approval-карточкой; runtime только фиксирует ask/deny для диагностики.");
|
|
331
|
+
return { ok: true, enabled: true, ...snapshot, text: lines.join("\n") };
|
|
332
|
+
}
|
|
333
|
+
|
|
309
334
|
/* ------------------------------------------------------------------ */
|
|
310
335
|
/* Plugin entry */
|
|
311
336
|
/* ------------------------------------------------------------------ */
|
|
@@ -314,7 +339,8 @@ export function apply(ctx) {
|
|
|
314
339
|
const env = process.env;
|
|
315
340
|
const logger = ctx?.logger;
|
|
316
341
|
const hookState = createHookState();
|
|
317
|
-
const
|
|
342
|
+
const runtime = createRuntimeState();
|
|
343
|
+
const guard = createGuard({ env, logger, runtime, modeFor: (agent) => resolveMode(ctx, agent) });
|
|
318
344
|
try {
|
|
319
345
|
registerHooks(ctx, guard, hookState);
|
|
320
346
|
} catch (error) {
|
|
@@ -325,7 +351,7 @@ export function apply(ctx) {
|
|
|
325
351
|
const tool = {
|
|
326
352
|
name: "guardrails",
|
|
327
353
|
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.",
|
|
354
|
+
"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
355
|
parameters: {
|
|
330
356
|
type: "object",
|
|
331
357
|
additionalProperties: false,
|
|
@@ -333,7 +359,7 @@ export function apply(ctx) {
|
|
|
333
359
|
action: {
|
|
334
360
|
type: "string",
|
|
335
361
|
enum: ACTIONS,
|
|
336
|
-
description: "status (rules, protected paths, hooks) | check (bounded read-only scan) | policy (effective JSON policy).",
|
|
362
|
+
description: "status (rules, protected paths, hooks) | check (bounded read-only scan) | policy (effective JSON policy) | runtime (permission preset + recent ask/deny).",
|
|
337
363
|
},
|
|
338
364
|
root: {
|
|
339
365
|
type: "string",
|
|
@@ -368,6 +394,7 @@ export function apply(ctx) {
|
|
|
368
394
|
const loaded = loadPolicy({ env });
|
|
369
395
|
if (action === "policy") return policyValue(loaded);
|
|
370
396
|
if (action === "status") return statusValue(loaded, hookState);
|
|
397
|
+
if (action === "runtime") return runtimeValue(runtime, resolveMode(ctx, exec?.agent));
|
|
371
398
|
if (action === "check") return await checkValue(loaded, args, exec, logger);
|
|
372
399
|
return {
|
|
373
400
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
186
|
-
|
|
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) {
|