dsh-desktop-kit 2.23.1 → 2.23.17

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 (32) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +255 -245
  3. package/client.js +130 -8
  4. package/docs/AGENT-HARNESS.md +9 -0
  5. package/docs/TEST-2.23.2.md +23 -0
  6. package/index.js +2 -0
  7. package/package.json +3 -3
  8. package/plugins/dsh-agent-extensions/README.md +5 -0
  9. package/plugins/dsh-agent-extensions/client.js +129 -7
  10. package/plugins/dsh-agent-extensions/index.js +24 -5
  11. package/plugins/dsh-agent-extensions/lib/agents.js +26 -3
  12. package/plugins/dsh-agent-extensions/lib/api.js +55 -1
  13. package/plugins/dsh-agent-extensions/lib/board.js +8 -2
  14. package/plugins/dsh-agent-extensions/lib/findings.js +67 -0
  15. package/plugins/dsh-agent-extensions/lib/project.js +2 -0
  16. package/plugins/dsh-agent-extensions/lib/routing.js +72 -0
  17. package/plugins/dsh-agent-extensions/lib/scaffold.js +120 -21
  18. package/plugins/dsh-agent-extensions/lib/settings.js +94 -0
  19. package/plugins/dsh-agent-extensions/lib/swarm.js +10 -5
  20. package/plugins/dsh-mcp-manager/README.md +10 -0
  21. package/plugins/dsh-mcp-manager/index.js +62 -2
  22. package/plugins/dsh-mcp-manager/lib/bootstrap.js +94 -0
  23. package/plugins/dsh-mcp-manager/lib/catalog.js +128 -0
  24. package/plugins/dsh-research-ledger/README.md +48 -0
  25. package/plugins/dsh-research-ledger/cordis.patch.yml +3 -0
  26. package/plugins/dsh-research-ledger/index.js +145 -0
  27. package/plugins/dsh-research-ledger/lib/ledger.js +346 -0
  28. package/plugins/dsh-research-ledger/package.json +25 -0
  29. package/plugins/dsh-skill-autopilot/index.js +65 -13
  30. package/skills/manifest.json +8 -8
  31. package/skills/research-first/SKILL.md +1 -0
  32. package/skills-baseline.json +480 -0
@@ -10,6 +10,8 @@ import { loadAgents, projectFor } from "./project.js";
10
10
  import { clearChildPolicy, setChildPolicy } from "./policy.js";
11
11
  import { loadRuns, runPreview, updateRun, upsertRun } from "./runs.js";
12
12
  import { saveTranscript } from "./transcripts.js";
13
+ import { findingsPrompt, parseFindings, validateFindings } from "./findings.js";
14
+ import { agentOptionsFor, chooseAgentRoute } from "./routing.js";
13
15
 
14
16
  const background = new Map();
15
17
 
@@ -47,6 +49,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
47
49
  else signal?.addEventListener?.("abort", abort, { once: true });
48
50
  const reservedId = crypto.randomUUID();
49
51
  let activeId = reservedId;
52
+ const route = chooseAgentRoute(definition, task, options.route);
50
53
  setChildPolicy(reservedId, definition);
51
54
  let activation;
52
55
  try {
@@ -55,7 +58,9 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
55
58
  definition.body,
56
59
  "</project-agent>",
57
60
  options.teamId ? `<team id="${options.teamId}">Use team_board action=post/read with teamId=${options.teamId} to share findings; use add-task/claim/done for work items. Use team_message to=\"parent\" for a live message to the lead; sibling live messaging is not available — the board is the shared channel.</team>` : "",
58
- options.leadContext ? `<team-lead>You coordinate this team. Members: ${options.leadContext}. Read the board first; assign/claim tasks; use team_message to=<run-id> for live directions and team_message to=\"parent\" to report to the parent.</team-lead>` : "",
61
+ options.leadContext ? `<team-lead>You coordinate this team. Members: ${options.leadContext}. Read the board first; assign/claim tasks with acceptance criteria and non-overlapping scopes; use team_message to=<run-id> for live directions and team_message to=\"parent\" to report to the parent. Finish with a PASS/FAIL synthesis, blockers and unresolved risks.</team-lead>` : "",
62
+ "<quality>Evidence over confidence: for code claims cite file:line; for test claims quote the command and result; separate facts from assumptions; never invent a test, source or passing result. Findings: severity · location · evidence · impact · fix. If evidence is missing, say unknown. Final report: PASS/FAIL, blockers, uncertain items.</quality>",
63
+ definition.output === "findings" ? findingsPrompt() : "",
59
64
  "",
60
65
  "Task:",
61
66
  String(task ?? ""),
@@ -69,7 +74,7 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
69
74
  parent: exec.agent,
70
75
  signal: controller.signal,
71
76
  cwd,
72
- ...(definition.model ? { agentOptions: { model: definition.model } } : {}),
77
+ ...(route.model || route.reasoningEffort ? { agentOptions: agentOptionsFor(route) } : {}),
73
78
  },
74
79
  signal: controller.signal,
75
80
  delivery: "caller",
@@ -143,7 +148,25 @@ export async function runProjectAgent(ctx, exec, definition, task, options = {})
143
148
  const text = textFromOutput(result?.output);
144
149
  await activation.dispose?.();
145
150
  if (!text) throw new Error(`project agent ${definition.name} returned no text`);
146
- return { text, stopReason: result?.stopReason ?? "completed", worktree: options.worktree ?? null };
151
+ let findings = null;
152
+ let findingsError = "";
153
+ if (definition.output === "findings") {
154
+ const parsed = parseFindings(text);
155
+ if (!parsed.ok) findingsError = parsed.error;
156
+ else {
157
+ const validated = validateFindings(parsed.value);
158
+ if (validated.ok) findings = validated.value;
159
+ else findingsError = validated.errors.join("; ");
160
+ }
161
+ if (!findings) findingsError = `findings contract violated: ${findingsError}`;
162
+ }
163
+ return {
164
+ text: findingsError ? `${text}\n\n[findings-format] ${findingsError}` : text,
165
+ stopReason: result?.stopReason ?? "completed",
166
+ worktree: options.worktree ?? null,
167
+ ...(definition.output === "findings" ? { findings, findingsValid: Boolean(findings), findingsError } : {}),
168
+ route,
169
+ };
147
170
  } catch (error) {
148
171
  clearChildPolicy(activeId);
149
172
  if (isBackground) {
@@ -7,6 +7,7 @@ import { worktreeSummary } from "./worktrees.js";
7
7
  import { readBoard } from "./board.js";
8
8
  import { extractTranscript, loadTranscript } from "./transcripts.js";
9
9
  import { loadTeams } from "./teams.js";
10
+ import { applyMcpBootstrap, bootstrapState, readSettings, updateSettings } from "./settings.js";
10
11
 
11
12
  export const RPC_NAMESPACE = "dsh-agent-extensions";
12
13
  const ROUTE_BASE = "/api/dsh-agent-extensions";
@@ -155,7 +156,60 @@ export function registerAgentApi(ctx) {
155
156
  },
156
157
  };
157
158
 
158
- for (const route of [listRoute, cancelRoute]) {
159
+ const settingsRoute = {
160
+ path: `${ROUTE_BASE}/settings`,
161
+ methods: ["POST"],
162
+ requestBody: "buffered",
163
+ fetch: async (request) => {
164
+ let rpcId = "invalid-request";
165
+ try {
166
+ const value = await envelope(request);
167
+ rpcId = value.rpcId;
168
+ if (value.method === `${RPC_NAMESPACE}/settings`) {
169
+ return ok(rpcId, { settings: readSettings(), mcpBootstrap: bootstrapState() });
170
+ }
171
+ if (value.method === `${RPC_NAMESPACE}/settings.update`) {
172
+ const payload = value.payload ?? {};
173
+ const settings = updateSettings(payload.settings ?? {});
174
+ if (payload.mcpBootstrap) {
175
+ const state = payload.mcpBootstrap;
176
+ applyMcpBootstrap(state.enabled === true, state.trusted === true);
177
+ }
178
+ return ok(rpcId, { settings, mcpBootstrap: bootstrapState() });
179
+ }
180
+ throw new Error("endpoint/method mismatch");
181
+ } catch (error) {
182
+ return fail(rpcId, error instanceof Error ? error.message : String(error));
183
+ }
184
+ },
185
+ };
186
+
187
+ const settingsUpdateRoute = {
188
+ path: `${ROUTE_BASE}/settings.update`,
189
+ methods: ["POST"],
190
+ requestBody: "buffered",
191
+ fetch: async (request) => {
192
+ let rpcId = "invalid-request";
193
+ try {
194
+ const value = await envelope(request);
195
+ rpcId = value.rpcId;
196
+ if (value.method !== `${RPC_NAMESPACE}/settings.update`) throw new Error("endpoint/method mismatch");
197
+ const payload = value.payload ?? {};
198
+ const settings = updateSettings({
199
+ ...(payload.settings ?? {}),
200
+ ...(payload.mcpBootstrap ? { mcpBootstrap: payload.mcpBootstrap } : {}),
201
+ });
202
+ if (payload.mcpBootstrap) {
203
+ applyMcpBootstrap(payload.mcpBootstrap.enabled === true, payload.mcpBootstrap.trusted === true);
204
+ }
205
+ return ok(rpcId, { settings, mcpBootstrap: bootstrapState() });
206
+ } catch (error) {
207
+ return fail(rpcId, error instanceof Error ? error.message : String(error));
208
+ }
209
+ },
210
+ };
211
+
212
+ for (const route of [listRoute, cancelRoute, settingsRoute, settingsUpdateRoute]) {
159
213
  ctx.effect(() => {
160
214
  const dispose = ctx.connection.fetch.register(route);
161
215
  return () => { try { void Promise.resolve(dispose()).catch(() => {}); } catch { /* unloading */ } };
@@ -131,7 +131,7 @@ function validateDependencies(tasks, id, dependsOn) {
131
131
  return ids;
132
132
  }
133
133
 
134
- export function addTask(cwd, { teamId = "", title = "", owner = "", dependsOn = [], priority = "normal" } = {}) {
134
+ export function addTask(cwd, { teamId = "", title = "", owner = "", dependsOn = [], priority = "normal", acceptance = "", requireEvidence = false } = {}) {
135
135
  const clean = redact(title).trim();
136
136
  if (!clean) throw new Error("board task title is required");
137
137
  const root = projectRoot(cwd);
@@ -143,6 +143,9 @@ export function addTask(cwd, { teamId = "", title = "", owner = "", dependsOn =
143
143
  owner: String(owner),
144
144
  status: "open",
145
145
  priority: ["low", "normal", "high"].includes(priority) ? priority : "normal",
146
+ acceptance: redact(acceptance).trim(),
147
+ requiresEvidence: requireEvidence === true || redact(acceptance).trim().length > 0,
148
+ evidence: "",
146
149
  dependsOn: [],
147
150
  createdAt: new Date().toISOString(),
148
151
  updatedAt: new Date().toISOString(),
@@ -158,7 +161,7 @@ export function addTask(cwd, { teamId = "", title = "", owner = "", dependsOn =
158
161
  return { root, task: { ...task, ...(task.state ?? {}) } };
159
162
  }
160
163
 
161
- export function updateTask(cwd, { id = "", status = "", owner = "" } = {}) {
164
+ export function updateTask(cwd, { id = "", status = "", owner = "", evidence = "" } = {}) {
162
165
  if (!["open", "claimed", "done"].includes(status)) throw new Error("board task status must be open, claimed or done");
163
166
  const root = projectRoot(cwd);
164
167
  let result;
@@ -175,6 +178,9 @@ export function updateTask(cwd, { id = "", status = "", owner = "" } = {}) {
175
178
  } else if (status === "done") {
176
179
  if (task.owner && owner && task.owner !== owner) throw new Error(`board task is owned by ${task.owner}`);
177
180
  if (!state.ready) throw new Error(`board task cannot be done before: ${state.blockedBy.join(", ")}`);
181
+ const cleanEvidence = redact(evidence).trim();
182
+ if (task.requiresEvidence && !cleanEvidence) throw new Error("board task requires evidence before done (file:line, command/result or URL/date)");
183
+ if (cleanEvidence) task.evidence = cleanEvidence.slice(0, MAX_TEXT);
178
184
  task.status = "done";
179
185
  } else {
180
186
  task.status = "open";
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Structured findings contract for project agents.
3
+ *
4
+ * Agents with `output: findings` must return one JSON object with a verdict,
5
+ * findings, test evidence and unknowns. Parsing is tolerant (raw JSON or a
6
+ * fenced block); validation is strict enough to reject hand-waving.
7
+ */
8
+ const SEVERITIES = new Set(["blocker", "high", "medium", "low", "info"]);
9
+ const VERDICTS = new Set(["PASS", "FAIL", "UNKNOWN"]);
10
+
11
+ export function parseFindings(text) {
12
+ const source = String(text ?? "");
13
+ const fenced = source.match(/```(?:json)?\s*([\s\S]*?)```/iu);
14
+ const candidate = fenced ? fenced[1] : source.slice(source.indexOf("{"), source.lastIndexOf("}") + 1);
15
+ if (!candidate || candidate.trim().length === 0) return { ok: false, value: null, error: "JSON findings block not found" };
16
+ try {
17
+ return { ok: true, value: JSON.parse(candidate), error: "" };
18
+ } catch (error) {
19
+ return { ok: false, value: null, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
20
+ }
21
+ }
22
+
23
+ export function validateFindings(value) {
24
+ const errors = [];
25
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, errors: ["findings root must be an object"], value: null };
26
+ if (!VERDICTS.has(value.verdict)) errors.push(`verdict must be one of ${[...VERDICTS].join(", ")}`);
27
+ if (typeof value.summary !== "string" || value.summary.trim().length < 10) errors.push("summary must be a non-empty string (>= 10 chars)");
28
+ if (!Array.isArray(value.findings)) errors.push("findings must be an array");
29
+ const findings = Array.isArray(value.findings) ? value.findings : [];
30
+ findings.forEach((finding, index) => {
31
+ if (!finding || typeof finding !== "object") {
32
+ errors.push(`findings[${index}] must be an object`);
33
+ return;
34
+ }
35
+ if (!SEVERITIES.has(finding.severity)) errors.push(`findings[${index}].severity is invalid`);
36
+ if (typeof finding.location !== "string" || finding.location.trim().length === 0) errors.push(`findings[${index}].location is required`);
37
+ if (typeof finding.evidence !== "string" || finding.evidence.trim().length === 0) errors.push(`findings[${index}].evidence is required`);
38
+ if (typeof finding.impact !== "string" || finding.impact.trim().length === 0) errors.push(`findings[${index}].impact is required`);
39
+ if (typeof finding.fix !== "string" || finding.fix.trim().length === 0) errors.push(`findings[${index}].fix is required`);
40
+ });
41
+ if (value.tests !== undefined && !Array.isArray(value.tests)) errors.push("tests must be an array");
42
+ if (value.unknowns !== undefined && !Array.isArray(value.unknowns)) errors.push("unknowns must be an array");
43
+ return {
44
+ ok: errors.length === 0,
45
+ errors,
46
+ value: errors.length === 0 ? {
47
+ verdict: value.verdict,
48
+ summary: value.summary.trim(),
49
+ findings: findings.map((finding) => ({
50
+ severity: finding.severity,
51
+ location: String(finding.location).trim(),
52
+ evidence: String(finding.evidence).trim(),
53
+ impact: String(finding.impact).trim(),
54
+ fix: String(finding.fix).trim(),
55
+ })),
56
+ tests: (value.tests ?? []).map((test) => ({
57
+ command: typeof test?.command === "string" ? test.command.trim() : "",
58
+ result: typeof test?.result === "string" ? test.result.trim() : "",
59
+ })),
60
+ unknowns: (value.unknowns ?? []).map((item) => String(item).trim()).filter(Boolean),
61
+ } : null,
62
+ };
63
+ }
64
+
65
+ export function findingsPrompt() {
66
+ return '<findings-output>Return ONE JSON object: {"verdict":"PASS|FAIL|UNKNOWN","summary":"...","findings":[{"severity":"blocker|high|medium|low|info","location":"file:line or URL","evidence":"command/result or quote","impact":"...","fix":"..."}],"tests":[{"command":"...","result":"..."}],"unknowns":["..."]}. No prose outside the JSON block.</findings-output>';
67
+ }
@@ -72,8 +72,10 @@ export function loadAgents(projectDir, dshDir) {
72
72
  name: id,
73
73
  description: typeof parsed.meta.description === "string" ? parsed.meta.description : "",
74
74
  model: typeof parsed.meta.model === "string" ? parsed.meta.model : "",
75
+ effort: typeof parsed.meta.effort === "string" ? parsed.meta.effort : "",
75
76
  tools: typeof parsed.meta.tools === "string" ? parsed.meta.tools : "",
76
77
  permission: typeof parsed.meta.permission === "string" ? parsed.meta.permission : "full",
78
+ output: typeof parsed.meta.output === "string" ? parsed.meta.output : "",
77
79
  body: parsed.body,
78
80
  file: path.join(directory, name),
79
81
  });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Model/effort routing for project agents.
3
+ *
4
+ * Explicit frontmatter wins; otherwise the role has a safe default and the task
5
+ * complexity can only promote effort, never silently downgrade quality-critical
6
+ * roles. `max` is reserved for an explicit override or a critical task.
7
+ */
8
+
9
+ const PRO = "deepseek-v4-pro";
10
+ const FLASH = "deepseek-flash";
11
+ const EFFORTS = new Set(["off", "low", "high", "max"]);
12
+
13
+ const ROLE_DEFAULTS = {
14
+ coordinator: { model: PRO, effort: "high" },
15
+ synthesizer: { model: PRO, effort: "high" },
16
+ verifier: { model: PRO, effort: "high" },
17
+ reviewer: { model: PRO, effort: "high" },
18
+ researcher: { model: PRO, effort: "high" },
19
+ security: { model: PRO, effort: "high" },
20
+ performance: { model: PRO, effort: "high" },
21
+ tester: { model: FLASH, effort: "low" },
22
+ };
23
+
24
+ const CRITICAL = /(?:critical|critically|security|vulnerab|exploit|migration|migrate|architecture|refactor|audit|data loss|критич|безопас|уязвим|миграц|архитект|рефактор|аудит|потер[яи] данных)/iu;
25
+ const SIMPLE = /(?:typo|rename|format|lint|status|grep|list|опечат|переимен|формат|статус|список)/iu;
26
+ const MAX_QUALITY = /(?:max quality|maximum quality|best possible|quality:max|максимальн\w* качеств)/iu;
27
+
28
+ export function normalizeEffort(value) {
29
+ const effort = String(value ?? "").toLowerCase();
30
+ return EFFORTS.has(effort) ? effort : "";
31
+ }
32
+
33
+ export function chooseAgentRoute(definition = {}, task = "", override = {}) {
34
+ const role = String(definition?.name ?? "").toLowerCase();
35
+ const defaults = ROLE_DEFAULTS[role] ?? { model: PRO, effort: "high" };
36
+ const explicitModel = String(definition?.model ?? "").trim();
37
+ const explicitEffort = normalizeEffort(definition?.effort);
38
+ const text = String(task ?? "");
39
+ let model = explicitModel || defaults.model;
40
+ let effort = explicitEffort || defaults.effort;
41
+ const reasons = [];
42
+
43
+ if (explicitModel) reasons.push("agent model");
44
+ if (explicitEffort) reasons.push("agent effort");
45
+
46
+ if (CRITICAL.test(text)) {
47
+ if (!explicitModel && model === FLASH) { model = PRO; reasons.push("critical -> pro"); }
48
+ if (!explicitEffort && effort !== "high" && effort !== "max") { effort = "high"; reasons.push("critical -> high"); }
49
+ }
50
+ if (MAX_QUALITY.test(text)) {
51
+ effort = "max";
52
+ reasons.push("explicit max quality");
53
+ }
54
+ if (!explicitEffort && SIMPLE.test(text) && effort === "high" && !CRITICAL.test(text)) {
55
+ effort = "low";
56
+ reasons.push("simple task -> low");
57
+ }
58
+
59
+ const overrideModel = String(override?.model ?? "").trim();
60
+ const overrideEffort = normalizeEffort(override?.effort);
61
+ if (overrideModel) { model = overrideModel; reasons.push("tool model override"); }
62
+ if (overrideEffort) { effort = overrideEffort; reasons.push("tool effort override"); }
63
+
64
+ return { model, reasoningEffort: effort, reasons, role };
65
+ }
66
+
67
+ export function agentOptionsFor(route) {
68
+ const options = {};
69
+ if (route?.model) options.model = route.model;
70
+ if (route?.reasoningEffort) options.reasoningEffort = route.reasoningEffort;
71
+ return options;
72
+ }
@@ -12,6 +12,8 @@ import fs from "node:fs";
12
12
  import os from "node:os";
13
13
  import path from "node:path";
14
14
 
15
+ import { readSettings } from "./settings.js";
16
+
15
17
  const SCAFFOLD_VERSION = 1;
16
18
  const PROVISION_CACHE = new Map();
17
19
  const PROVISION_TTL = 30_000;
@@ -61,11 +63,63 @@ const AGENT_TEMPLATES = {
61
63
  "---",
62
64
  "name: coordinator",
63
65
  "description: Координирует рой: читает board, назначает задачи, пишет участникам.",
64
- "tools: read, grep, team_board, team_message",
66
+ "tools: read, grep, repo_map, team_board, team_message",
67
+ "permission: read-only",
68
+ "---",
69
+ "",
70
+ "Ты лид команды. Сначала прочитай board, затем назначай задачи и пиши участникам через team_message. Не меняй код. Требуй acceptance criteria, evidence и финальный PASS/FAIL.",
71
+ "",
72
+ ].join("\n"),
73
+ "verifier.md": [
74
+ "---",
75
+ "name: verifier",
76
+ "description: Проверяет claims, ссылки, даты и тесты; возвращает structured findings.",
77
+ "tools: read, grep, glob, repo_map, web_fetch, research_ledger, team_board, team_message",
78
+ "model: deepseek-v4-pro",
79
+ "permission: read-only",
80
+ "output: findings",
81
+ "---",
82
+ "",
83
+ "Ты верификатор. Проверяй каждое утверждение: источник доступен, дата актуальна, цитата соответствует claim, тест реально запускался. Ищи противоречия и неподтверждённые выводы. Верни только JSON по findings-контракту.",
84
+ "",
85
+ ].join("\n"),
86
+ "synthesizer.md": [
87
+ "---",
88
+ "name: synthesizer",
89
+ "description: Сводит findings команды в единый PASS/FAIL без дублей.",
90
+ "tools: read, repo_map, research_ledger, team_board, team_message",
91
+ "model: deepseek-v4-pro",
92
+ "permission: read-only",
93
+ "output: findings",
94
+ "---",
95
+ "",
96
+ "Ты синтезатор. Собери находки команды, убери дубли, отдели факты от предположений, проверь ссылки через ledger и верни единый JSON по findings-контракту с blockers и unknowns.",
97
+ "",
98
+ ].join("\n"),
99
+ "security.md": [
100
+ "---",
101
+ "name: security",
102
+ "description: Ищет уязвимости, секреты, права и опасные дефолты; не меняет код.",
103
+ "tools: read, grep, glob, repo_map, guardrails, team_board, team_message",
104
+ "model: deepseek-v4-pro",
105
+ "permission: read-only",
106
+ "output: findings",
107
+ "---",
108
+ "",
109
+ "Ты security-ревьюер. Проверяй auth/authz, ввод, секреты, зависимости, права и опасные команды. Для каждого finding — severity, file:line, evidence и fix. Не меняй файлы.",
110
+ "",
111
+ ].join("\n"),
112
+ "performance.md": [
113
+ "---",
114
+ "name: performance",
115
+ "description: Ищет узкие места, лишние запросы и регрессии производительности.",
116
+ "tools: read, grep, glob, repo_map, browser_qa, team_board, team_message",
117
+ "model: deepseek-v4-pro",
65
118
  "permission: read-only",
119
+ "output: findings",
66
120
  "---",
67
121
  "",
68
- "Ты лид команды. Сначала прочитай board, затем назначай задачи и пиши участникам через team_message. Не меняй код.",
122
+ "Ты performance-ревьюер. Ищи N+1, лишние рендеры, блокирующие операции, размер бандла и регрессии. Каждый finding — severity, file:line, evidence (метрика/команда) и fix.",
69
123
  "",
70
124
  ].join("\n"),
71
125
  };
@@ -73,8 +127,68 @@ const AGENT_TEMPLATES = {
73
127
  const TEAM_TEMPLATES = {
74
128
  "review.json": { name: "review", members: ["reviewer", "researcher"], lead: "coordinator", description: "Ревью релиза: код и практики" },
75
129
  "research.json": { name: "research", members: ["researcher", "reviewer"], lead: "coordinator", description: "Исследование с проверкой фактов" },
130
+ "audit.json": { name: "audit", members: ["researcher", "reviewer", "verifier"], lead: "coordinator", description: "Read-only аудит: факты, код, проверка ссылок" },
131
+ "security.json": { name: "security", members: ["security", "reviewer"], lead: "coordinator", description: "Read-only security-аудит" },
76
132
  };
77
133
 
134
+ function readPackage(cwd) {
135
+ try {
136
+ return JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+
142
+ function packageRunner(cwd) {
143
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
144
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
145
+ if (fs.existsSync(path.join(cwd, "bun.lockb"))) return "bun";
146
+ return "npm";
147
+ }
148
+
149
+ function projectMeta(cwd) {
150
+ const pkg = readPackage(cwd) ?? {};
151
+ const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
152
+ const stack = [...new Set([
153
+ ...Object.keys(deps).filter((name) => /^(?:react|vue|svelte|next|nuxt|nestjs|express|fastify|laravel|django|flask|fastapi|spring|rails|phoenix|astro|vite|typescript|tailwindcss|postgres|pg|prisma|drizzle|redis|graphql)$/iu.test(name)),
154
+ ])].slice(0, 10);
155
+ const scripts = pkg.scripts && typeof pkg.scripts === "object" ? pkg.scripts : {};
156
+ const runner = packageRunner(cwd);
157
+ const commands = ["test", "lint", "typecheck", "build"]
158
+ .filter((name) => typeof scripts[name] === "string" && scripts[name].trim().length > 0)
159
+ .slice(0, 4)
160
+ .map((name) => `${runner} ${name}`);
161
+ let remote = "";
162
+ try {
163
+ const match = fs.readFileSync(path.join(cwd, ".git", "config"), "utf8").match(/^\s*url\s*=\s*(.+)$/mu);
164
+ remote = match ? match[1].trim() : "";
165
+ } catch { /* no git */ }
166
+ return {
167
+ name: typeof pkg.name === "string" ? pkg.name : path.basename(cwd),
168
+ version: typeof pkg.version === "string" ? pkg.version : "",
169
+ stack,
170
+ scripts,
171
+ commands,
172
+ runner,
173
+ remote,
174
+ };
175
+ }
176
+
177
+ function projectMarkdown(cwd, meta) {
178
+ return [
179
+ "# Project",
180
+ "",
181
+ `Root: ${cwd}`,
182
+ `Package: ${meta.name}${meta.version ? ` ${meta.version}` : ""}`,
183
+ meta.stack.length > 0 ? `Stack: ${meta.stack.join(", ")}` : "",
184
+ meta.remote ? `Git: ${meta.remote}` : "",
185
+ meta.commands.length > 0 ? `Verify: ${meta.commands.join(" · ")}` : "",
186
+ "",
187
+ "Created automatically by dsh-desktop-kit on the first session. Edit freely; `/init --force` regenerates.",
188
+ "",
189
+ ].filter((line) => line !== "").join("\n");
190
+ }
191
+
78
192
  function hasGitHub(cwd) {
79
193
  try {
80
194
  return /github\.com/iu.test(fs.readFileSync(path.join(cwd, ".git", "config"), "utf8"));
@@ -169,6 +283,7 @@ export function shouldScaffold(cwd) {
169
283
 
170
284
  export function ensureProjectScaffold(cwd) {
171
285
  if (!shouldScaffold(cwd)) return { skipped: true, created: [] };
286
+ if (readSettings().autoScaffold === false) return { skipped: true, reason: "autoScaffold:false", created: [], dsh: path.join(cwd, ".dsh") };
172
287
  const dsh = path.join(cwd, ".dsh");
173
288
  const configFile = path.join(dsh, "kit.json");
174
289
  try {
@@ -178,6 +293,7 @@ export function ensureProjectScaffold(cwd) {
178
293
  const cached = PROVISION_CACHE.get(cwd);
179
294
  if (cached && Date.now() - cached < PROVISION_TTL) return { skipped: false, cached: true, created: [], dsh };
180
295
  const created = [];
296
+ const meta = projectMeta(cwd);
181
297
  fs.mkdirSync(dsh, { recursive: true });
182
298
  for (const directory of ["agents", "commands", "rules", "teams"]) {
183
299
  const target = path.join(dsh, directory);
@@ -206,7 +322,7 @@ export function ensureProjectScaffold(cwd) {
206
322
  if (writeIfMissing(path.join(dsh, "agents", ".gitkeep"), "")) created.push(path.join(dsh, "agents", ".gitkeep"));
207
323
  if (writeIfMissing(path.join(dsh, "commands", ".gitkeep"), "")) created.push(path.join(dsh, "commands", ".gitkeep"));
208
324
  if (writeIfMissing(path.join(dsh, "hooks.json"), `${JSON.stringify({ hooks: {} }, null, 2)}\n`)) created.push(path.join(dsh, "hooks.json"));
209
- if (writeIfMissing(path.join(dsh, "verify.json"), `${JSON.stringify({ commands: [] }, null, 2)}\n`)) created.push(path.join(dsh, "verify.json"));
325
+ if (writeIfMissing(path.join(dsh, "verify.json"), `${JSON.stringify({ commands: meta.commands }, null, 2)}\n`)) created.push(path.join(dsh, "verify.json"));
210
326
  if (writeIfMissing(path.join(dsh, "mcp.json"), `${JSON.stringify({ mcpServers: {} }, null, 2)}\n`)) created.push(path.join(dsh, "mcp.json"));
211
327
  if (suggestMcp(cwd, dsh)) created.push(path.join(dsh, "mcp.suggestions.json"));
212
328
  if (
@@ -239,24 +355,7 @@ export function ensureProjectScaffold(cwd) {
239
355
  }
240
356
  const projectFile = path.join(dsh, "PROJECT.md");
241
357
  if (!fs.existsSync(projectFile)) {
242
- let pkg = {};
243
- try { pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")); } catch { /* optional */ }
244
- fs.writeFileSync(
245
- projectFile,
246
- [
247
- "# Project",
248
- "",
249
- `Root: ${cwd}`,
250
- pkg.name ? `Package: ${pkg.name}${pkg.version ? ` ${pkg.version}` : ""}` : "",
251
- pkg.scripts?.test ? `Tests: ${pkg.scripts.test}` : "",
252
- "",
253
- "Created automatically by dsh-desktop-kit. Edit freely; `/init --force` regenerates.",
254
- "",
255
- ]
256
- .filter(Boolean)
257
- .join("\n"),
258
- "utf8",
259
- );
358
+ fs.writeFileSync(projectFile, projectMarkdown(cwd, meta), "utf8");
260
359
  created.push(projectFile);
261
360
  }
262
361
  const ruleFile = path.join(dsh, "rules", "project.md");
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Profile-level Kit controls shown in Settings → Agents.
3
+ * Stored at ~/.dsh/kit.settings.json; feature readers use the same file.
4
+ */
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ export const DEFAULTS = {
10
+ researchFirst: true,
11
+ autoScaffold: true,
12
+ swarm: { enabled: true, threshold: 3, maxAgents: 4 },
13
+ mcpBootstrap: { enabled: true, trusted: true },
14
+ };
15
+
16
+ function home() {
17
+ return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
18
+ }
19
+
20
+ export function settingsPath() {
21
+ return path.join(home(), "kit.settings.json");
22
+ }
23
+
24
+ export function readSettings() {
25
+ let current = {};
26
+ try {
27
+ current = JSON.parse(fs.readFileSync(settingsPath(), "utf8"));
28
+ } catch { /* defaults */ }
29
+ return {
30
+ researchFirst: current.researchFirst !== false,
31
+ autoScaffold: current.autoScaffold !== false,
32
+ swarm: {
33
+ enabled: current.swarm?.enabled !== false,
34
+ threshold: Number.isFinite(Number(current.swarm?.threshold)) ? Math.max(1, Math.min(5, Number(current.swarm.threshold))) : DEFAULTS.swarm.threshold,
35
+ maxAgents: Number.isFinite(Number(current.swarm?.maxAgents)) ? Math.max(2, Math.min(6, Number(current.swarm.maxAgents))) : DEFAULTS.swarm.maxAgents,
36
+ },
37
+ mcpBootstrap: {
38
+ enabled: current.mcpBootstrap?.enabled !== false,
39
+ trusted: current.mcpBootstrap?.trusted === true,
40
+ },
41
+ };
42
+ }
43
+
44
+ export function updateSettings(patch = {}) {
45
+ const current = readSettings();
46
+ const next = {
47
+ ...current,
48
+ ...(typeof patch.researchFirst === "boolean" ? { researchFirst: patch.researchFirst } : {}),
49
+ ...(typeof patch.autoScaffold === "boolean" ? { autoScaffold: patch.autoScaffold } : {}),
50
+ swarm: {
51
+ ...current.swarm,
52
+ ...(typeof patch.swarm?.enabled === "boolean" ? { enabled: patch.swarm.enabled } : {}),
53
+ ...(Number.isFinite(Number(patch.swarm?.threshold)) ? { threshold: Math.max(1, Math.min(5, Number(patch.swarm.threshold))) } : {}),
54
+ ...(Number.isFinite(Number(patch.swarm?.maxAgents)) ? { maxAgents: Math.max(2, Math.min(6, Number(patch.swarm.maxAgents))) } : {}),
55
+ },
56
+ mcpBootstrap: {
57
+ ...current.mcpBootstrap,
58
+ ...(typeof patch.mcpBootstrap?.enabled === "boolean" ? { enabled: patch.mcpBootstrap.enabled } : {}),
59
+ ...(typeof patch.mcpBootstrap?.trusted === "boolean" ? { trusted: patch.mcpBootstrap.trusted } : {}),
60
+ },
61
+ };
62
+ const file = settingsPath();
63
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
64
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, encoding: "utf8" });
65
+ return next;
66
+ }
67
+
68
+ export function bootstrapState() {
69
+ try {
70
+ const parsed = JSON.parse(fs.readFileSync(path.join(home(), "mcp.bootstrap.json"), "utf8"));
71
+ return { enabled: parsed?.enabled === true, trusted: parsed?.trusted === true };
72
+ } catch {
73
+ return { enabled: false, trusted: false };
74
+ }
75
+ }
76
+
77
+ export function applyMcpBootstrap(enabled, trusted) {
78
+ const file = path.join(home(), "mcp.bootstrap.json");
79
+ const state = { enabled: enabled === true, trusted: trusted === true, updatedAt: new Date().toISOString() };
80
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
81
+ fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600, encoding: "utf8" });
82
+ const configFile = path.join(home(), "mcp.json");
83
+ try {
84
+ const config = JSON.parse(fs.readFileSync(configFile, "utf8"));
85
+ for (const id of ["memory", "sequential-thinking", "github"]) {
86
+ if (config.mcpServers?.[id]) {
87
+ config.mcpServers[id].trusted = trusted === true;
88
+ config.mcpServers[id].enabled = true;
89
+ }
90
+ }
91
+ fs.writeFileSync(configFile, `${JSON.stringify(config, null, 2)}\n`, "utf8");
92
+ } catch { /* config may be absent; bootstrap installs it later */ }
93
+ return state;
94
+ }
@@ -8,6 +8,8 @@
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
10
 
11
+ import { readSettings } from "./settings.js";
12
+
11
13
  const BROAD = [
12
14
  /(?:audit|review|architecture|security|migration|refactor|research|compare|analy[sz]e|investigate)/iu,
13
15
  /(?:провер|ревью|архитект|безопас|миграц|рефактор|исслед|сравн|проанализ|разбер)/iu,
@@ -23,7 +25,8 @@ export function loadSwarmOptions(projectRoot) {
23
25
  const parsed = JSON.parse(fs.readFileSync(path.join(projectRoot, ".dsh", "swarm.json"), "utf8"));
24
26
  return { enabled: parsed.enabled !== false, threshold: Number(parsed.threshold) || 3, maxAgents: Math.max(2, Math.min(6, Number(parsed.maxAgents) || 4)) };
25
27
  } catch {
26
- return { enabled: true, threshold: 3, maxAgents: 4 };
28
+ const global = readSettings().swarm;
29
+ return { enabled: global.enabled !== false, threshold: global.threshold, maxAgents: global.maxAgents };
27
30
  }
28
31
  }
29
32
 
@@ -45,10 +48,12 @@ export function chooseSwarm(task, teams = [], agents = [], options = {}) {
45
48
 
46
49
  const maxAgents = Math.max(2, Math.min(6, Number(options.maxAgents) || 4));
47
50
  const research = EXTERNAL.some((pattern) => pattern.test(text));
48
- const preset = teams.find((team) => team.members.every((name) => agents.some((agent) => agent.name === name)))
49
- ?? teams[0]
50
- ?? null;
51
- if (preset && preset.members.length >= 2) {
51
+ /* Auto-swarm is read-only by design. A preset that contains a writer is
52
+ * explicit-only (`project_agent action=team worktrees=true`); never route a
53
+ * background auto-swarm into writable agents. */
54
+ const readOnlyNames = new Set(readOnly.map((agent) => agent.name));
55
+ const preset = teams.find((team) => team.members.length >= 2 && team.members.every((name) => readOnlyNames.has(name))) ?? null;
56
+ if (preset) {
52
57
  return { swarm: true, score, reasons, research, maxAgents, preset: preset.id, members: preset.members.slice(0, maxAgents), lead: preset.lead || "" };
53
58
  }
54
59
  const preferred = ["reviewer", "researcher", "tester"];