dsh-desktop-kit 2.30.0 → 2.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.en.md +118 -0
- package/README.md +71 -11
- package/client.js +1 -1
- package/docs/COMPATIBILITY.md +2 -1
- package/docs/LAPTOP-INSTALL.md +9 -5
- package/docs/MEASURED.md +25 -0
- package/docs/TEST-2.31.0.md +61 -0
- package/docs/TEST-2.32.0.md +32 -0
- package/docs/TEST-2.33.0.md +33 -0
- package/docs/UPGRADING.md +3 -1
- package/docs/images/hero-2.31.png +0 -0
- package/docs/measured.json +30 -0
- package/docs/preview/hero-2.31.html +133 -0
- package/doctor.ps1 +161 -142
- package/index.js +76 -5
- package/install.ps1 +178 -99
- package/lib/kit-diagnostics.js +780 -0
- package/package.json +8 -4
- 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-integrations/lib/job-sandbox.ps1 +1 -1
- package/plugins/dsh-profile-transfer/bootstrap/install-on-clean-machine.ps1 +1 -1
- 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
- package/skills/manifest.json +2 -2
- package/skills-baseline.json +9 -5
- package/uninstall.ps1 +1 -1
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kit diagnostics: environment probe, installation plan and tune measurements.
|
|
3
|
+
*
|
|
4
|
+
* Pure Node ESM with no DSH runtime imports, so it can be unit-tested outside
|
|
5
|
+
* the harness. Every external check is best-effort: a missing tool is data,
|
|
6
|
+
* never an exception. Nothing in this module changes the profile — only
|
|
7
|
+
* `applyTune` writes, and it writes a measurements block into
|
|
8
|
+
* `kit.settings.json` after taking a backup.
|
|
9
|
+
*
|
|
10
|
+
* Used by the `/kit doctor|plan|tune` commands (index.js), the tests in
|
|
11
|
+
* tools/kit-diagnostics-tests.mjs and tools/measure.mjs.
|
|
12
|
+
*/
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { spawnSync } from "node:child_process";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
|
|
19
|
+
import { loadSkillState, STATE_FILE } from "./skills-sync.js";
|
|
20
|
+
|
|
21
|
+
const KIT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
22
|
+
|
|
23
|
+
/** Keep in sync with tools/skill-cost.mjs: bytes / 3.2 ≈ tokens. */
|
|
24
|
+
export const TOKENS_PER_BYTE = 3.2;
|
|
25
|
+
export const SKILL_CORE_BUDGET = 6000;
|
|
26
|
+
export const DIAGNOSTICS_SCHEMA = 1;
|
|
27
|
+
export const USAGE_WINDOW_DAYS = 30;
|
|
28
|
+
|
|
29
|
+
export const KIT_VERSION = (() => {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(fs.readFileSync(path.join(KIT_ROOT, "package.json"), "utf8")).version ?? "unknown";
|
|
32
|
+
} catch {
|
|
33
|
+
return "unknown";
|
|
34
|
+
}
|
|
35
|
+
})();
|
|
36
|
+
|
|
37
|
+
/* ------------------------------------------------------------------ */
|
|
38
|
+
/* Small file helpers */
|
|
39
|
+
/* ------------------------------------------------------------------ */
|
|
40
|
+
|
|
41
|
+
function readJson(file) {
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function readText(file) {
|
|
50
|
+
try {
|
|
51
|
+
return fs.readFileSync(file, "utf8");
|
|
52
|
+
} catch {
|
|
53
|
+
return "";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function statSafe(file) {
|
|
58
|
+
try {
|
|
59
|
+
return fs.statSync(file);
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function ensureDir(dir) {
|
|
66
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function writeAtomic(file, text) {
|
|
70
|
+
ensureDir(path.dirname(file));
|
|
71
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
72
|
+
fs.writeFileSync(tmp, text, "utf8");
|
|
73
|
+
fs.renameSync(tmp, file);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Replace the DSH home prefix with %DSH_HOME% so output can be pasted safely. */
|
|
77
|
+
export function tokenizeHome(text, home) {
|
|
78
|
+
const raw = String(text ?? "");
|
|
79
|
+
if (!home) return raw;
|
|
80
|
+
const normalizedHome = path.resolve(home);
|
|
81
|
+
const variants = new Set([normalizedHome, normalizedHome.replace(/\\/g, "/"), normalizedHome.replace(/\//g, "\\")]);
|
|
82
|
+
let result = raw;
|
|
83
|
+
for (const variant of variants) {
|
|
84
|
+
if (!variant) continue;
|
|
85
|
+
const pattern = new RegExp(variant.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
|
|
86
|
+
result = result.replace(pattern, "%DSH_HOME%");
|
|
87
|
+
}
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/* ------------------------------------------------------------------ */
|
|
92
|
+
/* Process probes */
|
|
93
|
+
/* ------------------------------------------------------------------ */
|
|
94
|
+
|
|
95
|
+
function runLine(commandLine, { timeoutMs = 5000 } = {}) {
|
|
96
|
+
if (process.platform === "win32") {
|
|
97
|
+
const result = spawnSync("cmd.exe", ["/d", "/s", "/c", commandLine], {
|
|
98
|
+
timeout: timeoutMs,
|
|
99
|
+
windowsHide: true,
|
|
100
|
+
encoding: "utf8",
|
|
101
|
+
});
|
|
102
|
+
return { ok: result.status === 0, status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
|
103
|
+
}
|
|
104
|
+
const result = spawnSync(commandLine, { shell: true, timeout: timeoutMs, encoding: "utf8" });
|
|
105
|
+
return { ok: result.status === 0, status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function probeBinary(command, args = ["--version"], { timeoutMs = 4000 } = {}) {
|
|
109
|
+
try {
|
|
110
|
+
const result = spawnSync(command, args, {
|
|
111
|
+
timeout: timeoutMs,
|
|
112
|
+
windowsHide: true,
|
|
113
|
+
encoding: "utf8",
|
|
114
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
115
|
+
});
|
|
116
|
+
if (result.error) return { found: false, version: null, status: null };
|
|
117
|
+
const text = `${result.stdout ?? ""}`.trim().split(/\r?\n/u)[0] ?? "";
|
|
118
|
+
return { found: result.status === 0 || text.length > 0, version: text || null, status: result.status };
|
|
119
|
+
} catch {
|
|
120
|
+
return { found: false, version: null, status: null };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function findDsh() {
|
|
125
|
+
const override = process.env.DSH_KIT_DSH_BIN;
|
|
126
|
+
const candidates = [];
|
|
127
|
+
if (override && override.trim().length > 0) candidates.push(override.trim());
|
|
128
|
+
candidates.push("dsh");
|
|
129
|
+
const localAppData = process.env.LOCALAPPDATA || "";
|
|
130
|
+
if (localAppData) {
|
|
131
|
+
candidates.push(path.join(localAppData, "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd"));
|
|
132
|
+
}
|
|
133
|
+
for (const candidate of candidates) {
|
|
134
|
+
if (candidate !== "dsh" && !fs.existsSync(candidate)) continue;
|
|
135
|
+
const commandLine = `"${candidate}" --version`;
|
|
136
|
+
const result = process.platform === "win32" ? runLine(commandLine) : runLine(`${candidate} --version`);
|
|
137
|
+
if (result.ok || result.stdout.trim().length > 0) {
|
|
138
|
+
return { found: true, command: candidate, version: result.stdout.trim().split(/\r?\n/u)[0] || null };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return { found: false, command: null, version: null };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function detectDshRunning() {
|
|
145
|
+
try {
|
|
146
|
+
if (process.platform === "win32") {
|
|
147
|
+
const result = spawnSync("tasklist", ["/FI", "IMAGENAME eq DeepSeek Harness.exe", "/NH"], {
|
|
148
|
+
timeout: 4000,
|
|
149
|
+
windowsHide: true,
|
|
150
|
+
encoding: "utf8",
|
|
151
|
+
});
|
|
152
|
+
return `${result.stdout ?? ""}`.includes("DeepSeek Harness");
|
|
153
|
+
}
|
|
154
|
+
const result = spawnSync("pgrep", ["-f", "DeepSeek Harness"], { timeout: 4000, encoding: "utf8" });
|
|
155
|
+
return result.status === 0;
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function detectBrowser() {
|
|
162
|
+
const candidates = [];
|
|
163
|
+
if (process.env.CHROME_PATH) candidates.push({ file: process.env.CHROME_PATH, kind: "chrome" });
|
|
164
|
+
const programFiles = process.env.ProgramFiles || "C:\\Program Files";
|
|
165
|
+
const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
|
|
166
|
+
const localAppData = process.env.LOCALAPPDATA || "";
|
|
167
|
+
candidates.push(
|
|
168
|
+
{ file: path.join(programFiles, "Google", "Chrome", "Application", "chrome.exe"), kind: "chrome" },
|
|
169
|
+
{ file: path.join(programFilesX86, "Google", "Chrome", "Application", "chrome.exe"), kind: "chrome" },
|
|
170
|
+
...(localAppData ? [{ file: path.join(localAppData, "Google", "Chrome", "Application", "chrome.exe"), kind: "chrome" }] : []),
|
|
171
|
+
{ file: path.join(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe"), kind: "edge" },
|
|
172
|
+
{ file: path.join(programFiles, "Microsoft", "Edge", "Application", "msedge.exe"), kind: "edge" },
|
|
173
|
+
);
|
|
174
|
+
for (const candidate of candidates) {
|
|
175
|
+
if (candidate.file && fs.existsSync(candidate.file)) return { found: true, path: candidate.file, kind: candidate.kind };
|
|
176
|
+
}
|
|
177
|
+
return { found: false, path: null, kind: null };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function detectGh() {
|
|
181
|
+
const version = probeBinary("gh", ["--version"]);
|
|
182
|
+
if (!version.found) return { found: false, version: null, authed: false };
|
|
183
|
+
let authed = false;
|
|
184
|
+
try {
|
|
185
|
+
const result = spawnSync("gh", ["auth", "status"], { timeout: 5000, windowsHide: true, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
186
|
+
authed = result.status === 0;
|
|
187
|
+
} catch {
|
|
188
|
+
authed = false;
|
|
189
|
+
}
|
|
190
|
+
return { found: true, version: version.version, authed };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function detectGit() {
|
|
194
|
+
const version = probeBinary("git", ["--version"]);
|
|
195
|
+
return { found: version.found, version: version.version };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function diskFree(target) {
|
|
199
|
+
try {
|
|
200
|
+
const root = path.parse(path.resolve(target || ".")).root || path.resolve(target || ".");
|
|
201
|
+
const stat = fs.statfsSync(root);
|
|
202
|
+
const free = stat.bfree * stat.bsize;
|
|
203
|
+
const total = stat.blocks * stat.bsize;
|
|
204
|
+
return { freeGb: roundGb(free), totalGb: roundGb(total) };
|
|
205
|
+
} catch {
|
|
206
|
+
return { freeGb: null, totalGb: null };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function roundGb(bytes) {
|
|
211
|
+
return Math.round((bytes / (1024 * 1024 * 1024)) * 10) / 10;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/* ------------------------------------------------------------------ */
|
|
215
|
+
/* Profile and dossier readers */
|
|
216
|
+
/* ------------------------------------------------------------------ */
|
|
217
|
+
|
|
218
|
+
export function defaultHome() {
|
|
219
|
+
return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function readProfiles(home) {
|
|
223
|
+
const root = path.join(home, "profiles");
|
|
224
|
+
let entries = [];
|
|
225
|
+
try {
|
|
226
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
227
|
+
} catch {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
return entries
|
|
231
|
+
.filter((entry) => entry.isDirectory())
|
|
232
|
+
.map((entry) => entry.name)
|
|
233
|
+
.sort()
|
|
234
|
+
.map((name) => {
|
|
235
|
+
const directory = path.join(root, name);
|
|
236
|
+
const manifestFile = path.join(directory, "package.json");
|
|
237
|
+
const manifest = readJson(manifestFile);
|
|
238
|
+
const bundles = manifest?.dsh?.profile?.bundles;
|
|
239
|
+
const dependency = manifest?.dependencies?.["dsh-desktop-kit"] ?? null;
|
|
240
|
+
const installedFile = path.join(directory, "node_modules", "dsh-desktop-kit", "package.json");
|
|
241
|
+
const installed = readJson(installedFile);
|
|
242
|
+
let linked = false;
|
|
243
|
+
try {
|
|
244
|
+
linked = fs.lstatSync(path.join(directory, "node_modules", "dsh-desktop-kit")).isSymbolicLink();
|
|
245
|
+
} catch {
|
|
246
|
+
linked = false;
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
name,
|
|
250
|
+
directory,
|
|
251
|
+
manifestFile,
|
|
252
|
+
exists: manifest !== null,
|
|
253
|
+
bundles: Array.isArray(bundles) ? bundles.filter((item) => typeof item === "string") : [],
|
|
254
|
+
dependency,
|
|
255
|
+
installedKitVersion: typeof installed?.version === "string" ? installed.version : null,
|
|
256
|
+
linked,
|
|
257
|
+
};
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function readMcp(home) {
|
|
262
|
+
const file = path.join(home, "mcp.json");
|
|
263
|
+
const parsed = readJson(file);
|
|
264
|
+
const servers = parsed && typeof parsed.mcpServers === "object" && parsed.mcpServers !== null ? parsed.mcpServers : {};
|
|
265
|
+
const names = Object.keys(servers);
|
|
266
|
+
const enabled = names.filter((name) => servers[name]?.enabled !== false);
|
|
267
|
+
const trusted = names.filter((name) => servers[name]?.trusted === true);
|
|
268
|
+
const pending = enabled.filter((name) => servers[name]?.trusted !== true);
|
|
269
|
+
return { file, exists: parsed !== null, servers: names, enabled, trusted, pending };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function readSkills(home) {
|
|
273
|
+
const directory = path.join(home, "skills");
|
|
274
|
+
let count = 0;
|
|
275
|
+
try {
|
|
276
|
+
count = fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).length;
|
|
277
|
+
} catch {
|
|
278
|
+
count = 0;
|
|
279
|
+
}
|
|
280
|
+
const state = loadSkillState(directory);
|
|
281
|
+
const packaged = Object.keys(state.skills).length;
|
|
282
|
+
const conflicts = Object.keys(state.conflicts);
|
|
283
|
+
return {
|
|
284
|
+
directory,
|
|
285
|
+
count,
|
|
286
|
+
packaged,
|
|
287
|
+
conflicts,
|
|
288
|
+
updatedAt: state.updatedAt || null,
|
|
289
|
+
stateFile: path.join(directory, STATE_FILE),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/* ------------------------------------------------------------------ */
|
|
294
|
+
/* Environment probe */
|
|
295
|
+
/* ------------------------------------------------------------------ */
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* @param {object} [options]
|
|
299
|
+
* @param {string} [options.home] DSH home, defaults to DSH_HOME / ~/.dsh
|
|
300
|
+
* @param {string} [options.profile] profile name, defaults to "desktop"
|
|
301
|
+
* @param {string} [options.repoPath] kit source root (for version), defaults to this package
|
|
302
|
+
* @param {boolean} [options.skipExternal] skip process probes (tests, CI containers)
|
|
303
|
+
*/
|
|
304
|
+
export function detectEnvironment(options = {}) {
|
|
305
|
+
const home = path.resolve(options.home || defaultHome());
|
|
306
|
+
const profileName = options.profile || "desktop";
|
|
307
|
+
const repoPath = path.resolve(options.repoPath || KIT_ROOT);
|
|
308
|
+
const skipExternal = options.skipExternal === true;
|
|
309
|
+
const now = options.now instanceof Date ? options.now : new Date();
|
|
310
|
+
|
|
311
|
+
const repoPackage = readJson(path.join(repoPath, "package.json"));
|
|
312
|
+
const kitVersion = typeof repoPackage?.version === "string" ? repoPackage.version : KIT_VERSION;
|
|
313
|
+
const profiles = readProfiles(home);
|
|
314
|
+
const profile = profiles.find((item) => item.name === profileName) ?? {
|
|
315
|
+
name: profileName,
|
|
316
|
+
directory: path.join(home, "profiles", profileName),
|
|
317
|
+
manifestFile: path.join(home, "profiles", profileName, "package.json"),
|
|
318
|
+
exists: false,
|
|
319
|
+
bundles: [],
|
|
320
|
+
dependency: null,
|
|
321
|
+
installedKitVersion: null,
|
|
322
|
+
linked: false,
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const dshRunning = skipExternal ? null : detectDshRunning();
|
|
326
|
+
const dsh = skipExternal ? { found: false, command: null, version: null, skipped: true } : findDsh();
|
|
327
|
+
const gh = skipExternal ? { found: false, version: null, authed: false, skipped: true } : detectGh();
|
|
328
|
+
const git = skipExternal ? { found: false, version: null, skipped: true } : detectGit();
|
|
329
|
+
const browser = skipExternal ? { found: false, path: null, kind: null, skipped: true } : detectBrowser();
|
|
330
|
+
const disk = diskFree(home);
|
|
331
|
+
const mcp = readMcp(home);
|
|
332
|
+
const skills = readSkills(home);
|
|
333
|
+
const settingsFile = path.join(home, "kit.settings.json");
|
|
334
|
+
const settings = readJson(settingsFile);
|
|
335
|
+
const tuneFile = path.join(home, "kit-tune.json");
|
|
336
|
+
|
|
337
|
+
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
338
|
+
const problems = [];
|
|
339
|
+
const addProblem = (level, code, message) => problems.push({ level, code, message });
|
|
340
|
+
const profileManifest = readJson(profile.manifestFile);
|
|
341
|
+
const dependenciesAll = Object.keys(profileManifest?.dependencies ?? {});
|
|
342
|
+
|
|
343
|
+
if (!skipExternal && !dsh.found) addProblem("error", "dsh-missing", "CLI dsh не найден: установите DeepSeek Harness и запустите его один раз.");
|
|
344
|
+
if (!profile.exists) addProblem("error", "profile-missing", `Профиль «${profileName}» не найден: ${path.join(home, "profiles", profileName)}`);
|
|
345
|
+
if (nodeMajor < 20) addProblem("error", "node-old", `Node.js ${process.versions.node}: нужен >= 20.`);
|
|
346
|
+
if (dshRunning === true) addProblem("warn", "dsh-running", "DSH запущен: профиль нельзя переписывать на лету, закройте окно.");
|
|
347
|
+
if (profile.exists && !profile.dependency) addProblem("warn", "kit-missing", "dsh-desktop-kit не установлен в этом профиле.");
|
|
348
|
+
if (profile.dependency && profile.installedKitVersion && profile.installedKitVersion !== kitVersion) {
|
|
349
|
+
addProblem("warn", "kit-version", `Установлен kit ${profile.installedKitVersion}, в источнике ${kitVersion}.`);
|
|
350
|
+
}
|
|
351
|
+
if (skills.conflicts.length > 0) addProblem("warn", "skill-conflicts", `Конфликты навыков: ${skills.conflicts.join(", ")} (ваши правки сохранены).`);
|
|
352
|
+
if (mcp.pending.length > 0) addProblem("warn", "mcp-untrusted", `MCP-серверы без доверия не запустятся: ${mcp.pending.join(", ")}.`);
|
|
353
|
+
const pinned = dependenciesAll.filter((name) => name.startsWith("@deepseek-ai/"));
|
|
354
|
+
if (pinned.length > 0) addProblem("warn", "pinned-dsh-packages", `Закреплены пакеты @deepseek-ai/*: ${pinned.join(", ")} — после обновления DSH возможна несовместимость.`);
|
|
355
|
+
if (!skipExternal && gh.found && !gh.authed) addProblem("info", "gh-anonymous", "gh не авторизован: github_review/PR-проверки ограничены.");
|
|
356
|
+
if (!skipExternal && !browser.found) addProblem("info", "browser-missing", "Chrome/Edge не найден: browser_qa будет недоступен.");
|
|
357
|
+
if (disk.freeGb !== null && disk.freeGb < 2) addProblem("warn", "disk-low", `Свободно ${disk.freeGb} ГБ: установка/обновление может не пройти.`);
|
|
358
|
+
|
|
359
|
+
return {
|
|
360
|
+
schema: DIAGNOSTICS_SCHEMA,
|
|
361
|
+
generatedAt: now.toISOString(),
|
|
362
|
+
home,
|
|
363
|
+
profile: {
|
|
364
|
+
name: profile.name,
|
|
365
|
+
directory: profile.directory,
|
|
366
|
+
manifestFile: profile.manifestFile,
|
|
367
|
+
exists: profile.exists,
|
|
368
|
+
bundles: profile.bundles,
|
|
369
|
+
kitBundled: profile.bundles.includes("dsh-desktop-kit"),
|
|
370
|
+
dependency: profile.dependency,
|
|
371
|
+
installedKitVersion: profile.installedKitVersion,
|
|
372
|
+
linked: profile.linked,
|
|
373
|
+
dependenciesAll,
|
|
374
|
+
},
|
|
375
|
+
kit: { version: kitVersion, root: repoPath, settingsFile, settingsExists: settings !== null, tuneFile },
|
|
376
|
+
dsh: { ...dsh, running: dshRunning },
|
|
377
|
+
node: { version: process.versions.node, ok: nodeMajor >= 20 },
|
|
378
|
+
git,
|
|
379
|
+
gh,
|
|
380
|
+
browser,
|
|
381
|
+
disk,
|
|
382
|
+
skills,
|
|
383
|
+
mcp,
|
|
384
|
+
settings: settings
|
|
385
|
+
? {
|
|
386
|
+
researchFirst: settings.researchFirst ?? null,
|
|
387
|
+
autoScaffold: settings.autoScaffold ?? null,
|
|
388
|
+
swarm: settings.swarm ?? null,
|
|
389
|
+
mcpBootstrap: settings.mcpBootstrap ?? null,
|
|
390
|
+
}
|
|
391
|
+
: null,
|
|
392
|
+
problems,
|
|
393
|
+
ok: problems.every((problem) => problem.level !== "error"),
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/* ------------------------------------------------------------------ */
|
|
398
|
+
/* Installation plan (read-only) */
|
|
399
|
+
/* ------------------------------------------------------------------ */
|
|
400
|
+
|
|
401
|
+
const STATUS_LABEL = { done: "ok", todo: "todo", blocked: "blocked", skip: "skip" };
|
|
402
|
+
|
|
403
|
+
export function planActions(env) {
|
|
404
|
+
const steps = [];
|
|
405
|
+
const add = (id, title, status, reason, extra = {}) => steps.push({ id, title, status, reason, ...extra });
|
|
406
|
+
|
|
407
|
+
add(
|
|
408
|
+
"environment",
|
|
409
|
+
"Окружение",
|
|
410
|
+
env.problems.some((problem) => problem.level === "error") ? "blocked" : "done",
|
|
411
|
+
env.problems.filter((problem) => problem.level === "error").map((problem) => problem.message).join(" ") || "Все обязательные компоненты на месте.",
|
|
412
|
+
);
|
|
413
|
+
add("backup", "Бэкап манифеста профиля", "todo", "package.json и cordis.patch.yml копируются в backup-kit-<дата> перед изменениями.", {
|
|
414
|
+
affects: [env.profile.manifestFile, path.join(env.profile.directory, "cordis.patch.yml")],
|
|
415
|
+
});
|
|
416
|
+
add(
|
|
417
|
+
"package",
|
|
418
|
+
"Пакет dsh-desktop-kit",
|
|
419
|
+
env.profile.dependency && env.profile.installedKitVersion === env.kit.version ? "done" : "todo",
|
|
420
|
+
env.profile.dependency
|
|
421
|
+
? env.profile.installedKitVersion === env.kit.version
|
|
422
|
+
? `Уже установлен ${env.profile.installedKitVersion}.`
|
|
423
|
+
: `Установлен ${env.profile.installedKitVersion ?? "?"}, будет ${env.kit.version}.`
|
|
424
|
+
: `Будет установлен ${env.kit.version} из ${env.kit.root}.`,
|
|
425
|
+
{ command: `dsh plugin --profile ${env.profile.name} add "${env.kit.root}"` },
|
|
426
|
+
);
|
|
427
|
+
add(
|
|
428
|
+
"bundle",
|
|
429
|
+
"Bundle в dsh.profile.bundles",
|
|
430
|
+
env.profile.kitBundled ? "done" : "todo",
|
|
431
|
+
env.profile.kitBundled ? "dsh-desktop-kit уже включён." : "Строка dsh-desktop-kit будет добавлена в dsh.profile.bundles.",
|
|
432
|
+
{ command: "правка package.json профиля", affects: [env.profile.manifestFile] },
|
|
433
|
+
);
|
|
434
|
+
add(
|
|
435
|
+
"restart",
|
|
436
|
+
"Перезапуск DSH",
|
|
437
|
+
env.dsh.running === true ? "todo" : "skip",
|
|
438
|
+
env.dsh.running === true ? "Закройте окно DeepSeek Harness и откройте снова, чтобы kit загрузился." : "DSH не запущен — перезапуск не нужен.",
|
|
439
|
+
);
|
|
440
|
+
add(
|
|
441
|
+
"skills",
|
|
442
|
+
"Синхронизация навыков",
|
|
443
|
+
env.skills.packaged > 0 ? "done" : "todo",
|
|
444
|
+
env.skills.packaged > 0
|
|
445
|
+
? `${env.skills.packaged} навыков уже синхронизировано${env.skills.conflicts.length > 0 ? `, конфликтов ${env.skills.conflicts.length}` : ""}.`
|
|
446
|
+
: "При первом старте kit скопирует навыки; ваши правки не перезаписываются.",
|
|
447
|
+
{ affected: "package skills → %DSH_HOME%/skills" },
|
|
448
|
+
);
|
|
449
|
+
add("verify", "Проверка после установки", "todo", "После старта: /kit doctor и /kit status.");
|
|
450
|
+
|
|
451
|
+
const summary = { done: 0, todo: 0, blocked: 0, skip: 0 };
|
|
452
|
+
for (const step of steps) summary[step.status] += 1;
|
|
453
|
+
return {
|
|
454
|
+
schema: DIAGNOSTICS_SCHEMA,
|
|
455
|
+
generatedAt: env.generatedAt,
|
|
456
|
+
profile: env.profile.name,
|
|
457
|
+
kitVersion: env.kit.version,
|
|
458
|
+
blocked: summary.blocked > 0,
|
|
459
|
+
changes: summary.todo,
|
|
460
|
+
summary,
|
|
461
|
+
steps,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export function formatPlan(plan, env) {
|
|
466
|
+
const lines = [
|
|
467
|
+
`DSH Desktop Kit ${plan.kitVersion} — план установки`,
|
|
468
|
+
`Профиль: ${plan.profile}`,
|
|
469
|
+
"",
|
|
470
|
+
];
|
|
471
|
+
for (const step of plan.steps) {
|
|
472
|
+
lines.push(`[${STATUS_LABEL[step.status] ?? step.status}] ${step.title} — ${tokenizeHome(step.reason, env.home)}`);
|
|
473
|
+
if (step.command) lines.push(` ${tokenizeHome(step.command, env.home)}`);
|
|
474
|
+
}
|
|
475
|
+
lines.push("");
|
|
476
|
+
lines.push(`Итого: изменений ${plan.summary.todo}, готово ${plan.summary.done}, блокеров ${plan.summary.blocked}, пропущено ${plan.summary.skip}.`);
|
|
477
|
+
if (plan.blocked) lines.push("Есть блокеры — установка не начнётся, пока они не устранены.");
|
|
478
|
+
return lines.join("\n");
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/* ------------------------------------------------------------------ */
|
|
482
|
+
/* Doctor output */
|
|
483
|
+
/* ------------------------------------------------------------------ */
|
|
484
|
+
|
|
485
|
+
export function formatDoctor(env) {
|
|
486
|
+
const token = (value) => tokenizeHome(value, env.home);
|
|
487
|
+
const line = (label, value) => ` ${label.padEnd(11)} ${value}`;
|
|
488
|
+
const levelTag = { error: "ОШИБКА", warn: "ВНИМАНИЕ", info: "СПРАВКА" };
|
|
489
|
+
const lines = [`DSH Desktop Kit ${env.kit.version} — диагностика`, ""];
|
|
490
|
+
lines.push("Окружение");
|
|
491
|
+
lines.push(line("dsh", env.dsh.skipped ? "проверка пропущена" : env.dsh.found ? `${env.dsh.version ?? ""} (${token(env.dsh.command ?? "")})` : "не найден"));
|
|
492
|
+
lines.push(line("node", `${env.node.version}${env.node.ok ? "" : " (нужен >= 20)"}`));
|
|
493
|
+
lines.push(line("git", env.git.skipped ? "проверка пропущена" : env.git.found ? env.git.version : "не найден"));
|
|
494
|
+
lines.push(line("gh", env.gh.skipped ? "проверка пропущена" : env.gh.found ? `${env.gh.authed ? "вход выполнен" : "не авторизован"}` : "не найден"));
|
|
495
|
+
lines.push(line("browser", env.browser.skipped ? "проверка пропущена" : env.browser.found ? `${env.browser.kind}: ${token(env.browser.path)}` : "не найден"));
|
|
496
|
+
lines.push(line("DSH", env.dsh.running === true ? "запущен" : env.dsh.running === false ? "не запущен" : "проверка пропущена"));
|
|
497
|
+
lines.push(line("диск", env.disk.freeGb === null ? "неизвестно" : `${env.disk.freeGb} ГБ свободно`));
|
|
498
|
+
lines.push("");
|
|
499
|
+
lines.push("Профиль");
|
|
500
|
+
lines.push(line("имя", env.profile.name));
|
|
501
|
+
lines.push(line("путь", token(env.profile.directory)));
|
|
502
|
+
lines.push(line("существует", env.profile.exists ? "да" : "нет"));
|
|
503
|
+
lines.push(line("эта версия", env.profile.installedKitVersion ?? "не установлена"));
|
|
504
|
+
lines.push(line("bundle", env.profile.kitBundled ? "включён" : "не включён"));
|
|
505
|
+
lines.push(line("источник", env.profile.linked ? "link (dev)" : env.profile.dependency ? "npm/каталог" : "нет"));
|
|
506
|
+
lines.push("");
|
|
507
|
+
lines.push("Навыки");
|
|
508
|
+
lines.push(line("в каталоге", String(env.skills.count)));
|
|
509
|
+
lines.push(line("синхронизировано", String(env.skills.packaged)));
|
|
510
|
+
lines.push(line("конфликты", env.skills.conflicts.length > 0 ? env.skills.conflicts.join(", ") : "нет"));
|
|
511
|
+
lines.push(line("обновлено", env.skills.updatedAt ?? "ещё не записано"));
|
|
512
|
+
lines.push("");
|
|
513
|
+
lines.push("MCP");
|
|
514
|
+
lines.push(line("серверов", String(env.mcp.servers.length)));
|
|
515
|
+
lines.push(line("включено", String(env.mcp.enabled.length)));
|
|
516
|
+
lines.push(line("доверено", env.mcp.trusted.length > 0 ? env.mcp.trusted.join(", ") : "нет"));
|
|
517
|
+
lines.push("");
|
|
518
|
+
if (env.problems.length === 0) {
|
|
519
|
+
lines.push("Проблем не найдено.");
|
|
520
|
+
} else {
|
|
521
|
+
lines.push(`Проблемы (${env.problems.length})`);
|
|
522
|
+
for (const problem of env.problems) lines.push(` [${levelTag[problem.level] ?? problem.level}] ${token(problem.message)}`);
|
|
523
|
+
}
|
|
524
|
+
return lines.join("\n");
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/* ------------------------------------------------------------------ */
|
|
528
|
+
/* Tune measurements */
|
|
529
|
+
/* ------------------------------------------------------------------ */
|
|
530
|
+
|
|
531
|
+
export function readSkillCost(repoPath = KIT_ROOT) {
|
|
532
|
+
const root = path.join(path.resolve(repoPath), "skills");
|
|
533
|
+
const rows = [];
|
|
534
|
+
let entries = [];
|
|
535
|
+
try {
|
|
536
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
537
|
+
} catch {
|
|
538
|
+
return { rows, totalTokens: 0, totalReferences: 0, over: [] };
|
|
539
|
+
}
|
|
540
|
+
for (const entry of entries) {
|
|
541
|
+
if (!entry.isDirectory()) continue;
|
|
542
|
+
const skillDir = path.join(root, entry.name);
|
|
543
|
+
const core = path.join(skillDir, "SKILL.md");
|
|
544
|
+
const stat = statSafe(core);
|
|
545
|
+
if (!stat) continue;
|
|
546
|
+
let referenceBytes = 0;
|
|
547
|
+
let references = 0;
|
|
548
|
+
try {
|
|
549
|
+
for (const item of fs.readdirSync(path.join(skillDir, "references"), { withFileTypes: true })) {
|
|
550
|
+
if (!item.isFile()) continue;
|
|
551
|
+
const refStat = statSafe(path.join(skillDir, "references", item.name));
|
|
552
|
+
if (!refStat) continue;
|
|
553
|
+
references += 1;
|
|
554
|
+
referenceBytes += refStat.size;
|
|
555
|
+
}
|
|
556
|
+
} catch {
|
|
557
|
+
// no references directory
|
|
558
|
+
}
|
|
559
|
+
rows.push({
|
|
560
|
+
name: entry.name,
|
|
561
|
+
bytes: stat.size,
|
|
562
|
+
tokens: Math.round(stat.size / TOKENS_PER_BYTE),
|
|
563
|
+
references,
|
|
564
|
+
referenceTokens: Math.round(referenceBytes / TOKENS_PER_BYTE),
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
rows.sort((left, right) => right.tokens - left.tokens);
|
|
568
|
+
const totalTokens = rows.reduce((sum, row) => sum + row.tokens, 0);
|
|
569
|
+
const totalReferences = rows.reduce((sum, row) => sum + row.referenceTokens, 0);
|
|
570
|
+
const over = rows.filter((row) => row.tokens > SKILL_CORE_BUDGET);
|
|
571
|
+
return { rows, totalTokens, totalReferences, over };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function usageTimestamp(entry) {
|
|
575
|
+
const candidates = [entry.at, entry.ts, entry.time, entry.timestamp, entry.date, entry.createdAt];
|
|
576
|
+
for (const value of candidates) {
|
|
577
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
578
|
+
const date = new Date(value < 1e12 ? value * 1000 : value);
|
|
579
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
580
|
+
}
|
|
581
|
+
if (typeof value === "string" && value.length > 0) {
|
|
582
|
+
const date = new Date(value);
|
|
583
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
export function readSkillUsage(home, { windowDays = USAGE_WINDOW_DAYS, now = new Date() } = {}) {
|
|
590
|
+
const file = path.join(home, "quality", "skill-usage.jsonl");
|
|
591
|
+
const text = readText(file);
|
|
592
|
+
if (text.length === 0) {
|
|
593
|
+
return { available: false, file, events: 0, bySkill: [], windowDays, lastAt: null };
|
|
594
|
+
}
|
|
595
|
+
const since = new Date(now.getTime() - windowDays * 24 * 60 * 60 * 1000);
|
|
596
|
+
const counts = new Map();
|
|
597
|
+
let events = 0;
|
|
598
|
+
let lastAt = null;
|
|
599
|
+
for (const line of text.split(/\r?\n/u)) {
|
|
600
|
+
const trimmed = line.trim();
|
|
601
|
+
if (trimmed.length === 0) continue;
|
|
602
|
+
let entry;
|
|
603
|
+
try {
|
|
604
|
+
entry = JSON.parse(trimmed);
|
|
605
|
+
} catch {
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const name = entry?.skill ?? entry?.name ?? entry?.slug ?? entry?.skillName;
|
|
609
|
+
if (typeof name !== "string" || name.length === 0) continue;
|
|
610
|
+
const at = usageTimestamp(entry);
|
|
611
|
+
if (at && at < since) continue;
|
|
612
|
+
events += 1;
|
|
613
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
614
|
+
if (at && (!lastAt || at > lastAt)) lastAt = at;
|
|
615
|
+
}
|
|
616
|
+
const bySkill = [...counts.entries()]
|
|
617
|
+
.map(([name, count]) => ({ name, count }))
|
|
618
|
+
.sort((left, right) => right.count - left.count || left.name.localeCompare(right.name));
|
|
619
|
+
return { available: true, file, events, bySkill, windowDays, lastAt: lastAt ? lastAt.toISOString() : null };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function buildRecommendations({ cost, usage, mcp, env }) {
|
|
623
|
+
const recommendations = [];
|
|
624
|
+
for (const row of cost.over) {
|
|
625
|
+
recommendations.push({
|
|
626
|
+
id: `skill-core-${row.name}`,
|
|
627
|
+
level: "warn",
|
|
628
|
+
text: `Ядро навыка ${row.name} — ${row.tokens} токенов (бюджет ${SKILL_CORE_BUDGET}).`,
|
|
629
|
+
hint: "Вынесите подробности в references/<тема>.md и оставьте в SKILL.md только правила и карту ссылок.",
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (usage.available && usage.events > 0) {
|
|
633
|
+
const loaded = new Set(usage.bySkill.map((item) => item.name));
|
|
634
|
+
const heavy = cost.rows.filter((row) => row.tokens > 2000 && !loaded.has(row.name));
|
|
635
|
+
for (const row of heavy.slice(0, 5)) {
|
|
636
|
+
recommendations.push({
|
|
637
|
+
id: `skill-idle-${row.name}`,
|
|
638
|
+
level: "info",
|
|
639
|
+
text: `${row.name} (${row.tokens} токенов) не загружался за ${usage.windowDays} дней.`,
|
|
640
|
+
hint: "Проверьте, что тема действительно нужна: мёртвый навык в каталоге — это бюджет контекста.",
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
} else {
|
|
644
|
+
recommendations.push({
|
|
645
|
+
id: "usage-missing",
|
|
646
|
+
level: "info",
|
|
647
|
+
text: "Телеметрии загрузок навыков пока нет.",
|
|
648
|
+
hint: "Она появляется после 2.29 при первом вызове skill; без неё tune оценивает только каталог.",
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
if (mcp.pending.length > 0) {
|
|
652
|
+
recommendations.push({
|
|
653
|
+
id: "mcp-untrusted",
|
|
654
|
+
level: "warn",
|
|
655
|
+
text: `MCP-серверы без доверия не запускаются: ${mcp.pending.join(", ")}.`,
|
|
656
|
+
hint: "Проверьте команду и нажмите «Проверить и доверять» — или отключите сервер.",
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
if (env && env.profile.dependency && env.profile.installedKitVersion && env.profile.installedKitVersion !== env.kit.version) {
|
|
660
|
+
recommendations.push({
|
|
661
|
+
id: "kit-version",
|
|
662
|
+
level: "warn",
|
|
663
|
+
text: `Установлен kit ${env.profile.installedKitVersion}, источник — ${env.kit.version}.`,
|
|
664
|
+
hint: "Обновите пакет и перезапустите DSH; профиль перезаписывается только после закрытия окна.",
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
return recommendations;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
export function collectTuneMetrics(options = {}) {
|
|
671
|
+
const home = path.resolve(options.home || defaultHome());
|
|
672
|
+
const repoPath = path.resolve(options.repoPath || KIT_ROOT);
|
|
673
|
+
const now = options.now instanceof Date ? options.now : new Date();
|
|
674
|
+
const env = detectEnvironment({ home, repoPath, profile: options.profile, skipExternal: true, now });
|
|
675
|
+
const cost = readSkillCost(repoPath);
|
|
676
|
+
const usage = readSkillUsage(home, { now });
|
|
677
|
+
const recommendations = buildRecommendations({ cost, usage, mcp: env.mcp, env });
|
|
678
|
+
const cpus = os.cpus();
|
|
679
|
+
return {
|
|
680
|
+
schema: DIAGNOSTICS_SCHEMA,
|
|
681
|
+
kitVersion: env.kit.version,
|
|
682
|
+
measuredAt: now.toISOString(),
|
|
683
|
+
machine: {
|
|
684
|
+
platform: `${process.platform} ${process.arch}`,
|
|
685
|
+
osRelease: os.release(),
|
|
686
|
+
cpu: cpus[0]?.model?.trim() ?? "unknown",
|
|
687
|
+
cores: cpus.length,
|
|
688
|
+
ramGb: Math.round((os.totalmem() / (1024 * 1024 * 1024)) * 10) / 10,
|
|
689
|
+
node: process.versions.node,
|
|
690
|
+
},
|
|
691
|
+
profile: {
|
|
692
|
+
name: env.profile.name,
|
|
693
|
+
installedKitVersion: env.profile.installedKitVersion,
|
|
694
|
+
bundles: env.profile.bundles,
|
|
695
|
+
},
|
|
696
|
+
skills: {
|
|
697
|
+
count: cost.rows.length,
|
|
698
|
+
totalTokens: cost.totalTokens,
|
|
699
|
+
totalReferenceTokens: cost.totalReferences,
|
|
700
|
+
budget: SKILL_CORE_BUDGET,
|
|
701
|
+
maxTokens: cost.rows[0]?.tokens ?? 0,
|
|
702
|
+
maxSkill: cost.rows[0]?.name ?? null,
|
|
703
|
+
over: cost.over.map((row) => ({ name: row.name, tokens: row.tokens })),
|
|
704
|
+
},
|
|
705
|
+
usage,
|
|
706
|
+
mcp: {
|
|
707
|
+
servers: env.mcp.servers.length,
|
|
708
|
+
enabled: env.mcp.enabled.length,
|
|
709
|
+
trusted: env.mcp.trusted.length,
|
|
710
|
+
pending: env.mcp.pending,
|
|
711
|
+
},
|
|
712
|
+
disk: env.disk,
|
|
713
|
+
recommendations,
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
export function tuneReportPath(home) {
|
|
718
|
+
return path.join(path.resolve(home || defaultHome()), "kit-tune.json");
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
export function writeTuneReport(home, report) {
|
|
722
|
+
const file = tuneReportPath(home);
|
|
723
|
+
writeAtomic(file, `${JSON.stringify(report, null, 2)}\n`);
|
|
724
|
+
return file;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Persist the measurements into kit.settings.json under `tuning`.
|
|
729
|
+
* Behaviour does not change: this block is a record for future versions.
|
|
730
|
+
* The previous settings file is copied to kit.settings.json.bak-<stamp>.
|
|
731
|
+
*/
|
|
732
|
+
export function applyTune(home, report, { now = new Date() } = {}) {
|
|
733
|
+
const resolvedHome = path.resolve(home || defaultHome());
|
|
734
|
+
const settingsFile = path.join(resolvedHome, "kit.settings.json");
|
|
735
|
+
const settings = readJson(settingsFile) ?? {};
|
|
736
|
+
const stamp = now.toISOString().replace(/[-:]/gu, "").replace("T", "-").slice(0, 15);
|
|
737
|
+
const backup = `${settingsFile}.bak-${stamp}`;
|
|
738
|
+
if (statSafe(settingsFile)) fs.copyFileSync(settingsFile, backup);
|
|
739
|
+
const tuning = {
|
|
740
|
+
schema: DIAGNOSTICS_SCHEMA,
|
|
741
|
+
kitVersion: report.kitVersion,
|
|
742
|
+
measuredAt: report.measuredAt,
|
|
743
|
+
updatedAt: now.toISOString(),
|
|
744
|
+
skillBudget: report.skills.budget,
|
|
745
|
+
skillCatalogTokens: report.skills.totalTokens,
|
|
746
|
+
skillCoreMaxTokens: report.skills.maxTokens,
|
|
747
|
+
recommendations: report.recommendations.map((item) => item.id),
|
|
748
|
+
};
|
|
749
|
+
const next = { ...settings, tuning };
|
|
750
|
+
writeAtomic(settingsFile, `${JSON.stringify(next, null, 2)}\n`);
|
|
751
|
+
return { settingsFile, backup: statSafe(backup) ? backup : null, tuning };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export function formatTune(report, applyResult) {
|
|
755
|
+
const lines = [`DSH Desktop Kit ${report.kitVersion} — замеры (${report.measuredAt})`, ""];
|
|
756
|
+
lines.push(`Машина: ${report.machine.cpu}, ${report.machine.cores} потоков, ${report.machine.ramGb} ГБ RAM, Node ${report.machine.node}`);
|
|
757
|
+
lines.push(`Навыки: ${report.skills.count}, ядра ${report.skills.totalTokens} токенов, максимум ${report.skills.maxSkill} ${report.skills.maxTokens}/${report.skills.budget}`);
|
|
758
|
+
lines.push(`References: ${report.skills.totalReferenceTokens} токенов грузятся только по необходимости.`);
|
|
759
|
+
if (report.usage.available) {
|
|
760
|
+
lines.push(`Загрузки навыков за ${report.usage.windowDays} дней: ${report.usage.events}${report.usage.bySkill.length > 0 ? `, топ: ${report.usage.bySkill.slice(0, 3).map((item) => `${item.name}×${item.count}`).join(", ")}` : ""}`);
|
|
761
|
+
} else {
|
|
762
|
+
lines.push("Загрузки навыков: телеметрии пока нет.");
|
|
763
|
+
}
|
|
764
|
+
lines.push(`MCP: ${report.mcp.servers} серверов, включено ${report.mcp.enabled}, доверено ${report.mcp.trusted}${report.mcp.pending.length > 0 ? `, без доверия: ${report.mcp.pending.join(", ")}` : ""}`);
|
|
765
|
+
lines.push(`Диск: ${report.disk.freeGb ?? "?"} ГБ свободно из ${report.disk.totalGb ?? "?"}.`);
|
|
766
|
+
if (report.recommendations.length > 0) {
|
|
767
|
+
lines.push("");
|
|
768
|
+
lines.push("Рекомендации");
|
|
769
|
+
for (const item of report.recommendations) lines.push(` [${item.level}] ${item.text}\n ${item.hint}`);
|
|
770
|
+
}
|
|
771
|
+
lines.push("");
|
|
772
|
+
if (applyResult) {
|
|
773
|
+
lines.push(`Замеры записаны: ${applyResult.settingsFile}`);
|
|
774
|
+
if (applyResult.backup) lines.push(`Бэкап настроек: ${applyResult.backup}`);
|
|
775
|
+
lines.push("Поведение не изменилось: блок tuning — это запись замеров для будущих версий.");
|
|
776
|
+
}
|
|
777
|
+
return lines.join("\n");
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export { KIT_ROOT };
|