dsh-plugin-trim 0.0.0-stage → 0.2.4

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/dist/index.js ADDED
@@ -0,0 +1,4676 @@
1
+ import { createRequire } from "node:module";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { defineTool } from "@deepseek-ai/dsh-tools";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { constants } from "node:fs";
6
+ import { access, appendFile, chmod, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import { dirname, isAbsolute, join, resolve } from "node:path";
9
+ import { parse } from "yaml";
10
+ import { satisfies, valid } from "semver";
11
+ import { scopeOf } from "@deepseek-ai/dsh-scope";
12
+ // src/config.ts
13
+ /** Defaults used when the loader starts the plugin without an explicit config. */
14
+ const DEFAULT_CONFIG = {
15
+ mode: "advise",
16
+ protect: [],
17
+ pinned: [],
18
+ trackUsage: true,
19
+ usageRetentionDays: 30,
20
+ maxDrafts: 20,
21
+ enableDedupe: true,
22
+ persistExcerpts: false,
23
+ tokenRatio: 3.5,
24
+ toolOwners: {},
25
+ compatEnabled: true,
26
+ compatScanAllProfiles: true,
27
+ compatMaxProfiles: 20,
28
+ compatIncludeInfo: false,
29
+ compatMaxFindings: 100,
30
+ compatReadLockfile: true,
31
+ compatReadWorkspace: true,
32
+ compatStrictOfficialOverrides: false,
33
+ compatCacheTtlMs: 3e4
34
+ };
35
+ /** Merge a partial/undefined loader config over the defaults. */
36
+ function normalizeConfig(config) {
37
+ return {
38
+ ...DEFAULT_CONFIG,
39
+ ...config ?? {}
40
+ };
41
+ }
42
+ /** Schemastery configuration for the trim plugin. */
43
+ const Config = z.object({
44
+ mode: z.union(["advise", "auto-safe"]).default("advise"),
45
+ protect: z.array(z.string()).default([]),
46
+ pinned: z.array(z.string()).default([]),
47
+ trackUsage: z.boolean().default(true),
48
+ usageRetentionDays: z.natural().min(1).max(365).default(30),
49
+ maxDrafts: z.natural().min(1).max(200).default(20),
50
+ enableDedupe: z.boolean().default(true),
51
+ persistExcerpts: z.boolean().default(false),
52
+ tokenRatio: z.number().min(1).max(10).default(3.5),
53
+ toolOwners: z.dict(z.string()).default({}),
54
+ compatEnabled: z.boolean().default(true),
55
+ compatScanAllProfiles: z.boolean().default(true),
56
+ compatMaxProfiles: z.natural().min(1).max(100).default(20),
57
+ compatIncludeInfo: z.boolean().default(false),
58
+ compatMaxFindings: z.natural().min(1).max(500).default(100),
59
+ compatReadLockfile: z.boolean().default(true),
60
+ compatReadWorkspace: z.boolean().default(true),
61
+ compatStrictOfficialOverrides: z.boolean().default(false),
62
+ compatCacheTtlMs: z.natural().min(0).max(6e5).default(3e4)
63
+ });
64
+ // ../shared-meta/src/ids.ts
65
+ /** Create a sortable, readable id such as `trim-20261108-091500-ab12cd34`. */
66
+ function newId(prefix, date = /* @__PURE__ */ new Date()) {
67
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
68
+ return `${prefix}-${`${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`}-${randomUUID().slice(0, 8)}`;
69
+ }
70
+ /** Opaque rollback/snapshot token. */
71
+ function randomToken() {
72
+ return randomUUID();
73
+ }
74
+ /** Stable 12-character content hash used for findings and fingerprints. */
75
+ function shortHash(input) {
76
+ return createHash("sha256").update(input).digest("hex").slice(0, 12);
77
+ }
78
+ // ../shared-meta/src/text.ts
79
+ const CJK_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/g;
80
+ const PUNCT_RE = /[^\p{L}\p{N}\s]/gu;
81
+ const SPACE_RE = /\s+/g;
82
+ /** Extract visible text from model content blocks without importing DSH types. */
83
+ function flattenTextBlocks(blocks) {
84
+ if (!Array.isArray(blocks)) return "";
85
+ const parts = [];
86
+ for (const block of blocks) if (isRecord(block) && block.type === "text" && typeof block.text === "string") parts.push(block.text);
87
+ return parts.join("\n");
88
+ }
89
+ /** Lowercase, collapse whitespace, and strip punctuation for stable comparison. */
90
+ function normalizeLine(text) {
91
+ return text.toLowerCase().replace(SPACE_RE, " ").replace(PUNCT_RE, " ").replace(SPACE_RE, " ").trim();
92
+ }
93
+ /** Split on blank lines, falling back to non-empty lines. */
94
+ function splitParagraphs(text) {
95
+ const paragraphs = text.split(/\n\s*\n/g).map((part) => part.trim()).filter(Boolean);
96
+ if (paragraphs.length > 1) return paragraphs;
97
+ return text.split(/\n/g).map((line) => line.trim()).filter(Boolean);
98
+ }
99
+ /** CJK-aware token estimate. CJK characters count as one token; other text uses 3.5 chars/token. */
100
+ function estimateTokens(text) {
101
+ if (text.length === 0) return 0;
102
+ const cjk = (text.match(CJK_RE) ?? []).length;
103
+ const other = text.length - cjk;
104
+ return cjk + Math.ceil(other / 3.5);
105
+ }
106
+ /** Truncate without splitting surrogate pairs. */
107
+ function truncate(text, max) {
108
+ if (text.length <= max) return text;
109
+ if (max <= 1) return text.slice(0, max);
110
+ return `${text.slice(0, max - 1)}…`;
111
+ }
112
+ /** Word/CJK bigram-ish tokens used for shingling. CJK runs become single-character tokens. */
113
+ function wordTokens(text) {
114
+ const normalized = normalizeLine(text);
115
+ if (!normalized) return [];
116
+ const tokens = [];
117
+ for (const part of normalized.split(" ")) {
118
+ if (!part) continue;
119
+ if (CJK_RE.test(part)) {
120
+ CJK_RE.lastIndex = 0;
121
+ for (const char of part) tokens.push(char);
122
+ } else tokens.push(part);
123
+ }
124
+ return tokens;
125
+ }
126
+ /** Contiguous n-gram shingles; short inputs produce one shingle. */
127
+ function shingles(tokens, n = 3) {
128
+ if (tokens.length === 0) return /* @__PURE__ */ new Set();
129
+ if (tokens.length <= n) return /* @__PURE__ */ new Set([tokens.join(" ")]);
130
+ const result = /* @__PURE__ */ new Set();
131
+ for (let i = 0; i <= tokens.length - n; i++) result.add(tokens.slice(i, i + n).join(" "));
132
+ return result;
133
+ }
134
+ /** Jaccard similarity of two shingle sets. Empty sets compare as 0. */
135
+ function jaccard(a, b) {
136
+ if (a.size === 0 || b.size === 0) return 0;
137
+ let intersection = 0;
138
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a];
139
+ for (const item of small) if (large.has(item)) intersection++;
140
+ return intersection / (a.size + b.size - intersection);
141
+ }
142
+ function isRecord(value) {
143
+ return typeof value === "object" && value !== null && !Array.isArray(value);
144
+ }
145
+ function uniq(values) {
146
+ return [...new Set(values)];
147
+ }
148
+ function clamp(value, min, max) {
149
+ return Math.min(max, Math.max(min, value));
150
+ }
151
+ function round(value, digits = 2) {
152
+ const factor = 10 ** digits;
153
+ return Math.round(value * factor) / factor;
154
+ }
155
+ /** JSON stringify with sorted object keys, for stable comparisons. */
156
+ function stableStringify(value) {
157
+ return JSON.stringify(sortJson(value));
158
+ }
159
+ function sortJson(value) {
160
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
161
+ if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
162
+ if (Array.isArray(value)) return value.map((item) => sortJson(item));
163
+ if (isRecord(value)) {
164
+ const out = {};
165
+ for (const key of Object.keys(value).sort()) out[key] = sortJson(value[key]);
166
+ return out;
167
+ }
168
+ return String(value);
169
+ }
170
+ /** Structural JSON equality with sorted keys. */
171
+ function deepEqualJson(a, b) {
172
+ return stableStringify(a) === stableStringify(b);
173
+ }
174
+ /** Escape text for one Markdown table cell. */
175
+ function escapeMarkdownCell(text) {
176
+ return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim();
177
+ }
178
+ /** Render a bounded fenced JSON block. */
179
+ function jsonBlock(value, maxChars = 12e3) {
180
+ return `\`\`\`json\n${truncate(JSON.stringify(value, null, 2), maxChars)}\n\`\`\``;
181
+ }
182
+ // ../shared-meta/src/store.ts
183
+ /** Local store failure with a stable code. */
184
+ var StoreError = class extends Error {
185
+ code;
186
+ constructor(code, message, options) {
187
+ super(message, options);
188
+ this.name = "StoreError";
189
+ this.code = code;
190
+ }
191
+ };
192
+ /** Resolve the DSH home: `$DSH_HOME`, else `~/.dsh`. */
193
+ function resolveDshHome(env = process.env) {
194
+ const configured = env.DSH_HOME?.trim();
195
+ return configured ? resolve(configured) : join(homedir(), ".dsh");
196
+ }
197
+ /** Join a path under `<dshHome>/experience-optimizer`. */
198
+ function dataDir(...segments) {
199
+ return join(resolveDshHome(), "experience-optimizer", ...segments);
200
+ }
201
+ /** Create a directory with owner-only permissions. */
202
+ async function ensureDir(path) {
203
+ await mkdir(path, {
204
+ recursive: true,
205
+ mode: 448
206
+ });
207
+ await chmod(path, 448).catch(() => void 0);
208
+ }
209
+ async function fileExists(path) {
210
+ try {
211
+ await access(path, constants.F_OK);
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+ /** Read a UTF-8 text file with an optional byte cap. */
218
+ async function readTextFile(path, maxBytes = 5242880) {
219
+ try {
220
+ const info = await stat(path);
221
+ if (info.size > maxBytes) throw new StoreError("too-large", `${path} is ${info.size} bytes (limit ${maxBytes})`);
222
+ return await readFile(path, "utf8");
223
+ } catch (error) {
224
+ if (isNotFound(error)) return void 0;
225
+ throw error;
226
+ }
227
+ }
228
+ /** Read and parse JSON; missing files return undefined. */
229
+ async function readJson(path) {
230
+ const text = await readTextFile(path);
231
+ if (text === void 0) return void 0;
232
+ try {
233
+ return JSON.parse(text);
234
+ } catch (error) {
235
+ throw new StoreError("parse", `invalid JSON at ${path}`, { cause: error });
236
+ }
237
+ }
238
+ /** Atomically replace a JSON file. */
239
+ async function writeJsonAtomic(path, value, mode = 384) {
240
+ const directory = dirname(path);
241
+ await ensureDir(directory);
242
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
243
+ try {
244
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, {
245
+ encoding: "utf8",
246
+ mode
247
+ });
248
+ await chmod(temporary, mode).catch(() => void 0);
249
+ await rename(temporary, path);
250
+ } catch (error) {
251
+ await unlink(temporary).catch(() => void 0);
252
+ throw new StoreError("write", `cannot write ${path}`, { cause: error });
253
+ }
254
+ }
255
+ /** Append JSON lines in one batch. */
256
+ async function appendJsonl(path, lines) {
257
+ if (lines.length === 0) return;
258
+ await ensureDir(dirname(path));
259
+ const text = lines.map((line) => `${JSON.stringify(line)}\n`).join("");
260
+ try {
261
+ await appendFile(path, text, {
262
+ encoding: "utf8",
263
+ mode: 384
264
+ });
265
+ } catch (error) {
266
+ throw new StoreError("write", `cannot append ${path}`, { cause: error });
267
+ }
268
+ }
269
+ /** Read JSON lines, skipping malformed records. */
270
+ async function readJsonl(path, limit) {
271
+ const text = await readTextFile(path);
272
+ if (text === void 0) return [];
273
+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
274
+ const selected = limit === void 0 ? lines : lines.slice(-limit);
275
+ const result = [];
276
+ for (const line of selected) try {
277
+ result.push(JSON.parse(line));
278
+ } catch {}
279
+ return result;
280
+ }
281
+ /** List JSON files by newest mtime first. */
282
+ async function listJsonFiles(directory) {
283
+ let names;
284
+ try {
285
+ names = await readdir(directory);
286
+ } catch (error) {
287
+ if (isNotFound(error)) return [];
288
+ throw error;
289
+ }
290
+ const files = names.filter((name) => name.endsWith(".json")).map((name) => join(directory, name));
291
+ return (await Promise.all(files.map(async (path) => ({
292
+ path,
293
+ mtime: (await stat(path)).mtimeMs
294
+ })))).sort((a, b) => b.mtime - a.mtime).map((item) => item.path);
295
+ }
296
+ /** Delete oldest files beyond `max`. */
297
+ async function pruneToCount(directory, max) {
298
+ const files = await listJsonFiles(directory);
299
+ for (const path of files.slice(Math.max(0, max))) await unlink(path).catch(() => void 0);
300
+ }
301
+ /** Replace a file atomically with arbitrary text. */
302
+ async function writeTextAtomic(path, text, mode = 384) {
303
+ const directory = dirname(path);
304
+ await ensureDir(directory);
305
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
306
+ try {
307
+ await writeFile(temporary, text, {
308
+ encoding: "utf8",
309
+ mode
310
+ });
311
+ await chmod(temporary, mode).catch(() => void 0);
312
+ await rename(temporary, path);
313
+ } catch (error) {
314
+ await unlink(temporary).catch(() => void 0);
315
+ throw new StoreError("write", `cannot write ${path}`, { cause: error });
316
+ }
317
+ }
318
+ function isNotFound(error) {
319
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
320
+ }
321
+ // ../shared-meta/src/audit.ts
322
+ const DEFAULT_MAX_BYTES = 2097152;
323
+ /** Append-only audit log with one-size rotation. */
324
+ var AuditLog = class {
325
+ path;
326
+ rotatedPath;
327
+ maxBytes;
328
+ writes = 0;
329
+ constructor(path = dataDir("audit.jsonl"), maxBytes = DEFAULT_MAX_BYTES) {
330
+ this.path = path;
331
+ this.rotatedPath = path.replace(/\.jsonl$/, ".1.jsonl");
332
+ this.maxBytes = maxBytes;
333
+ }
334
+ /** Append one record; failures are the caller's to report. */
335
+ async append(record) {
336
+ await appendJsonl(this.path, [record]);
337
+ this.writes++;
338
+ if (this.writes % 25 === 0) await this.rotateIfNeeded();
339
+ }
340
+ /** Read the most recent records, oldest first. */
341
+ async read(limit = 50) {
342
+ return readJsonl(this.path, limit);
343
+ }
344
+ async rotateIfNeeded() {
345
+ try {
346
+ if ((await stat(this.path)).size <= this.maxBytes) return;
347
+ await unlink(this.rotatedPath).catch(() => void 0);
348
+ const { rename } = await import("node:fs/promises");
349
+ await rename(this.path, this.rotatedPath);
350
+ } catch {}
351
+ }
352
+ };
353
+ // ../shared-meta/src/http.ts
354
+ /** Reject cross-site browser requests; allow same-origin and non-browser callers without Origin. */
355
+ function isSameOrigin(req) {
356
+ if (req.headers["sec-fetch-site"] === "cross-site") return false;
357
+ const origin = req.headers.origin;
358
+ if (origin === void 0 || origin.length === 0) return true;
359
+ try {
360
+ return new URL(origin).host === req.headers.host;
361
+ } catch {
362
+ return false;
363
+ }
364
+ }
365
+ /** Read and parse a JSON request body with a bounded size. */
366
+ async function readJsonBody(req, maxBytes = 65536) {
367
+ const chunks = [];
368
+ let size = 0;
369
+ for await (const chunk of req) {
370
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
371
+ size += buffer.length;
372
+ if (size > maxBytes) throw new Error(`request body exceeds ${maxBytes} bytes`);
373
+ chunks.push(buffer);
374
+ }
375
+ const text = Buffer.concat(chunks).toString("utf8").trim();
376
+ if (text.length === 0) return {};
377
+ return JSON.parse(text);
378
+ }
379
+ /** Write a JSON response. */
380
+ function sendJson(res, status, body) {
381
+ const text = JSON.stringify(body);
382
+ res.writeHead(status, {
383
+ "content-type": "application/json; charset=utf-8",
384
+ "cache-control": "no-store",
385
+ "content-length": Buffer.byteLength(text)
386
+ });
387
+ res.end(text);
388
+ }
389
+ /** Write a structured error response. */
390
+ function sendError(res, status, message) {
391
+ sendJson(res, status, {
392
+ ok: false,
393
+ error: { message }
394
+ });
395
+ }
396
+ // src/compat/loader-graph.ts
397
+ /** Normalize Cordis `inject` declarations (array or object) to service names. */
398
+ function normalizeInject(value) {
399
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "string");
400
+ if (isRecord(value)) return Object.keys(value);
401
+ return [];
402
+ }
403
+ /** Normalize Cordis `provide` declarations (string, array, or object) to service names. */
404
+ function normalizeProvide(value) {
405
+ if (typeof value === "string") return [value];
406
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "string");
407
+ if (isRecord(value)) return Object.keys(value);
408
+ return [];
409
+ }
410
+ function readModuleExports(namespace) {
411
+ if (!isRecord(namespace)) return {};
412
+ const direct = {
413
+ name: typeof namespace.name === "string" ? namespace.name : void 0,
414
+ inject: namespace.inject,
415
+ provide: namespace.provide,
416
+ default: namespace.default
417
+ };
418
+ if (isRecord(namespace.default)) {
419
+ const fallback = namespace.default;
420
+ direct.name ??= typeof fallback.name === "string" ? fallback.name : void 0;
421
+ direct.inject ??= fallback.inject;
422
+ direct.provide ??= fallback.provide;
423
+ }
424
+ return direct;
425
+ }
426
+ /** Map Cordis FiberState numbers to the inventory vocabulary. */
427
+ function mapFiberState(state) {
428
+ switch (state) {
429
+ case 0: return "pending";
430
+ case 1: return "loading";
431
+ case 2: return "active";
432
+ case 3: return "failed";
433
+ case 5: return "unloading";
434
+ default: return null;
435
+ }
436
+ }
437
+ function buildInventoryMaps(inventory) {
438
+ const byEntryId = /* @__PURE__ */ new Map();
439
+ const byModule = /* @__PURE__ */ new Map();
440
+ for (const entry of inventory?.entries ?? []) {
441
+ byEntryId.set(entry.entryId, entry);
442
+ if (!byModule.has(entry.moduleName)) byModule.set(entry.moduleName, entry);
443
+ }
444
+ return {
445
+ byEntryId,
446
+ byModule
447
+ };
448
+ }
449
+ function findInventoryEntry(entry, maps) {
450
+ const id = entry.id;
451
+ return maps.byEntryId.get(id) ?? maps.byEntryId.get(`include:${id}`) ?? maps.byModule.get(entry.options.name);
452
+ }
453
+ function snapshotFromEntry(entry, maps) {
454
+ const inventory = findInventoryEntry(entry, maps);
455
+ const exports = readModuleExports(entry.moduleNamespace);
456
+ const provide = uniq([...[...entry.fiber?.provisions ?? []].map((impl) => impl.name).filter((name) => typeof name === "string"), ...normalizeProvide(exports.provide)]);
457
+ const inject = uniq([
458
+ ...Object.keys(entry.fiber?.inject ?? {}),
459
+ ...normalizeInject(entry.options.inject),
460
+ ...normalizeInject(exports.inject)
461
+ ]);
462
+ return {
463
+ id: entry.id,
464
+ parentId: entry.id.includes(":") ? entry.id.slice(0, entry.id.lastIndexOf(":")) : null,
465
+ depth: entry.id.split(":").length - 1,
466
+ moduleName: entry.options.name,
467
+ pluginName: exports.name,
468
+ enabled: !entry.disabled,
469
+ group: false,
470
+ fiberState: inventory?.fiberPhase ?? mapFiberState(entry.fiber?.state),
471
+ diagnostic: inventory?.diagnostic,
472
+ provide,
473
+ inject,
474
+ config: entry.options.config,
475
+ source: entry.options.name === "@deepseek-ai/dsh-mcp-client" ? "mcp" : "loader",
476
+ mcpServerName: entry.options.name === "@deepseek-ai/dsh-mcp-client" && isRecord(entry.options.config) && typeof entry.options.config.name === "string" ? entry.options.config.name : void 0
477
+ };
478
+ }
479
+ function flattenPresetRows(rows, presetId, depth, out) {
480
+ if (!Array.isArray(rows)) return;
481
+ for (const raw of rows) {
482
+ if (!isRecord(raw)) continue;
483
+ const row = raw;
484
+ if (typeof row.name !== "string") continue;
485
+ if (row.group === true) {
486
+ flattenPresetRows(row.config, presetId, depth + 1, out);
487
+ continue;
488
+ }
489
+ out.push({
490
+ id: `${presetId}:${row.id ?? row.name}`,
491
+ parentId: presetId,
492
+ depth,
493
+ moduleName: row.name,
494
+ enabled: row.disabled !== true,
495
+ group: false,
496
+ fiberState: null,
497
+ provide: [],
498
+ inject: normalizeInject(row.inject),
499
+ config: row.config,
500
+ source: "preset",
501
+ presetId
502
+ });
503
+ }
504
+ }
505
+ /** Collect loader, preset, and MCP rows from one Loader tree. */
506
+ function collectLoaderGraph(loader, inventory) {
507
+ const entries = [];
508
+ const diagnostics = [];
509
+ if (loader === void 0) {
510
+ diagnostics.push("loader service unavailable; compatibility analysis is degraded");
511
+ return {
512
+ entries,
513
+ diagnostics
514
+ };
515
+ }
516
+ const maps = buildInventoryMaps(inventory);
517
+ try {
518
+ for (const entry of loader.entries()) {
519
+ if (entry.options.group) continue;
520
+ try {
521
+ const snapshot = snapshotFromEntry(entry, maps);
522
+ entries.push(snapshot);
523
+ if (snapshot.moduleName.includes("agent-preset")) {
524
+ const config = entry.options.config;
525
+ if (isRecord(config) && Array.isArray(config.plugins)) {
526
+ const presetId = typeof config.id === "string" ? `preset:${config.id}` : `preset:${entry.id}`;
527
+ const presetRows = [];
528
+ flattenPresetRows(config.plugins, presetId, snapshot.depth + 1, presetRows);
529
+ entries.push(...presetRows);
530
+ }
531
+ }
532
+ } catch (error) {
533
+ diagnostics.push(`loader entry ${entry.id} could not be inspected: ${errorText$1(error)}`);
534
+ }
535
+ }
536
+ } catch (error) {
537
+ diagnostics.push(`loader traversal failed: ${errorText$1(error)}`);
538
+ }
539
+ return {
540
+ entries,
541
+ diagnostics
542
+ };
543
+ }
544
+ function errorText$1(error) {
545
+ return error instanceof Error ? error.message : String(error);
546
+ }
547
+ // src/compat/manifests.ts
548
+ /** Strip a package subpath to its installable package name. */
549
+ function rootPackageName(spec) {
550
+ if (spec.startsWith("@")) {
551
+ const parts = spec.split("/");
552
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : spec;
553
+ }
554
+ return spec.split("/")[0] ?? spec;
555
+ }
556
+ /** True for Node built-ins and Cordis pseudo-specifiers that have no package.json. */
557
+ function isResolvablePackage(spec) {
558
+ return spec.length > 0 && !spec.startsWith("cordis:") && !spec.startsWith("node:") && !spec.startsWith(".") && !spec.startsWith("/");
559
+ }
560
+ /** Resolve package manifests from the profile, the DSH installation, and this module. */
561
+ var ManifestResolver = class {
562
+ cache = /* @__PURE__ */ new Map();
563
+ ttlMs;
564
+ profileDir;
565
+ constructor(profileDir, ttlMs = 6e4) {
566
+ this.profileDir = profileDir;
567
+ this.ttlMs = ttlMs;
568
+ }
569
+ async resolve(spec) {
570
+ if (!isResolvablePackage(spec)) return void 0;
571
+ const name = rootPackageName(spec);
572
+ const cached = this.cache.get(name);
573
+ if (cached !== void 0 && Date.now() - cached.at < this.ttlMs) return cached.value;
574
+ const value = await this.resolveFresh(name);
575
+ this.cache.set(name, {
576
+ at: Date.now(),
577
+ value
578
+ });
579
+ return value;
580
+ }
581
+ async resolveFresh(name) {
582
+ for (const candidate of this.candidatePaths(name)) try {
583
+ const path = candidate();
584
+ if (path === void 0) continue;
585
+ const manifest = await readJson(path);
586
+ if (manifest !== void 0 && typeof manifest === "object") return {
587
+ path,
588
+ manifest
589
+ };
590
+ } catch {}
591
+ }
592
+ candidatePaths(name) {
593
+ const spec = `${name}/package.json`;
594
+ const profileRequire = createRequire(join(this.profileDir, "package.json"));
595
+ const argvBase = process.argv[1];
596
+ const installRequire = argvBase !== void 0 && isAbsolute(argvBase) ? createRequire(argvBase) : void 0;
597
+ const here = createRequire(import.meta.url);
598
+ const candidates = [() => profileRequire.resolve(spec), () => here.resolve(spec)];
599
+ if (installRequire !== void 0) candidates.splice(1, 0, () => installRequire.resolve(spec, { paths: [dirname(argvBase), process.cwd()] }));
600
+ return candidates;
601
+ }
602
+ };
603
+ /** Read a version string from a manifest without trusting its type. */
604
+ function manifestVersion(manifest) {
605
+ return typeof manifest?.version === "string" ? manifest.version : void 0;
606
+ }
607
+ /** Supported platforms from `dsh.bundle.platforms`; empty means all platforms. */
608
+ function manifestPlatforms(manifest) {
609
+ const platforms = manifest?.dsh?.bundle?.platforms;
610
+ return Array.isArray(platforms) ? platforms.filter((item) => typeof item === "string") : [];
611
+ }
612
+ /** Engine ranges, keeping only string values. */
613
+ function manifestEngines(manifest) {
614
+ const engines = manifest?.engines;
615
+ if (engines === void 0 || engines === null || typeof engines !== "object") return {};
616
+ const out = {};
617
+ for (const [key, value] of Object.entries(engines)) if (typeof value === "string") out[key] = value;
618
+ return out;
619
+ }
620
+ /** Peer dependency ranges, keeping only string values. */
621
+ function manifestPeers(manifest) {
622
+ const peers = manifest?.peerDependencies;
623
+ if (peers === void 0 || peers === null || typeof peers !== "object") return {};
624
+ const out = {};
625
+ for (const [key, value] of Object.entries(peers)) if (typeof value === "string") out[key] = value;
626
+ return out;
627
+ }
628
+ /** Read `dsh.bundle.patch` paths. */
629
+ function manifestPatchPaths(manifest) {
630
+ const patch = manifest?.dsh?.bundle?.patch;
631
+ if (typeof patch === "string") return [patch];
632
+ if (Array.isArray(patch)) return patch.filter((item) => typeof item === "string");
633
+ return [];
634
+ }
635
+ /** Resolve a bundle directory from its manifest path. */
636
+ function manifestDir(resolved) {
637
+ return resolved === void 0 ? void 0 : dirname(resolved.path);
638
+ }
639
+ // src/compat/patches.ts
640
+ const jsSentinelTag = {
641
+ tag: "tag:yaml.org,2002:js",
642
+ resolve: (value) => ({ __js: value })
643
+ };
644
+ /** True when a value is the non-executed `!!js` placeholder. */
645
+ function isJsSentinel(value) {
646
+ return isRecord(value) && typeof value.__js === "string";
647
+ }
648
+ /** Parse one patch file without executing `!!js` expressions. */
649
+ function parsePatchText(text, layer, sourceFile) {
650
+ let parsed;
651
+ try {
652
+ parsed = parse(text, { customTags: [jsSentinelTag] });
653
+ } catch (error) {
654
+ return {
655
+ rows: scanPatchFallback(text, layer, sourceFile),
656
+ error: errorText$1(error)
657
+ };
658
+ }
659
+ const rows = [];
660
+ flattenPatch(parsed, layer, sourceFile, rows);
661
+ return { rows };
662
+ }
663
+ function flattenPatch(value, layer, sourceFile, out) {
664
+ if (Array.isArray(value)) {
665
+ for (const item of value) flattenPatch(item, layer, sourceFile, out);
666
+ return;
667
+ }
668
+ if (!isRecord(value)) return;
669
+ if (Array.isArray(value.insert)) flattenPatch(value.insert, layer, sourceFile, out);
670
+ else if (isRecord(value.insert)) flattenPatch(value.insert, layer, sourceFile, out);
671
+ if (typeof value.id === "string") out.push({
672
+ layer,
673
+ id: value.id,
674
+ name: typeof value.name === "string" ? value.name : void 0,
675
+ disabled: typeof value.disabled === "boolean" || isJsSentinel(value.disabled) ? value.disabled : void 0,
676
+ config: value.config,
677
+ sourceFile
678
+ });
679
+ }
680
+ /** Last-resort line scanner; only extracts ids and names. */
681
+ function scanPatchFallback(text, layer, sourceFile) {
682
+ const rows = [];
683
+ let current;
684
+ for (const line of text.split(/\r?\n/)) {
685
+ const id = /^\s*-\s*id:\s*['"]?([^'"\s]+)['"]?\s*$/.exec(line);
686
+ if (id?.[1] !== void 0) {
687
+ current = {
688
+ layer,
689
+ id: id[1],
690
+ sourceFile
691
+ };
692
+ rows.push(current);
693
+ continue;
694
+ }
695
+ const name = /^\s*name:\s*['"]?([^'"\s]+)['"]?\s*$/.exec(line);
696
+ if (name?.[1] !== void 0 && current !== void 0) current.name = name[1];
697
+ }
698
+ return rows;
699
+ }
700
+ /** Read all patch layers for a profile without evaluating expressions. */
701
+ async function readProfilePatchLayers(options) {
702
+ const rows = [];
703
+ const diagnostics = [];
704
+ const resolver = new ManifestResolver(options.profileDir);
705
+ for (const bundle of options.bundles) {
706
+ const resolved = await resolver.resolve(bundle);
707
+ const manifest = options.manifests.get(bundle) ?? resolved?.manifest;
708
+ const dir = manifestDir(resolved);
709
+ for (const relative of manifestPatchPaths(manifest)) {
710
+ const path = dir === void 0 ? relative : join(dir, relative);
711
+ const text = await readTextFile(path).catch(() => void 0);
712
+ if (text === void 0) {
713
+ diagnostics.push(`patch unreadable: ${path}`);
714
+ continue;
715
+ }
716
+ const result = parsePatchText(text, bundle, path);
717
+ rows.push(...result.rows);
718
+ if (result.error !== void 0) diagnostics.push(`patch parse fallback (${path}): ${result.error}`);
719
+ }
720
+ }
721
+ for (const [layer, path] of [["profile", join(options.profileDir, "cordis.patch.yml")], ["home", join(options.dshHome, "cordis.patch.yml")]]) {
722
+ const text = await readTextFile(path).catch(() => void 0);
723
+ if (text === void 0) continue;
724
+ const result = parsePatchText(text, layer, path);
725
+ rows.push(...result.rows);
726
+ if (result.error !== void 0) diagnostics.push(`patch parse fallback (${path}): ${result.error}`);
727
+ }
728
+ return {
729
+ rows,
730
+ diagnostics
731
+ };
732
+ }
733
+ /** Find the same row id configured with different values across layers. */
734
+ function findConfigConflicts(rows, options = {}) {
735
+ const byId = /* @__PURE__ */ new Map();
736
+ for (const row of rows) {
737
+ if (options.skipLayer?.(row.layer) === true) continue;
738
+ const list = byId.get(row.id) ?? [];
739
+ list.push(row);
740
+ byId.set(row.id, list);
741
+ }
742
+ const conflicts = [];
743
+ for (const [id, list] of byId) {
744
+ const withConfig = list.filter((row) => row.config !== void 0);
745
+ if (withConfig.length < 2) continue;
746
+ const first = withConfig[0]?.config;
747
+ if (first === void 0) continue;
748
+ if (withConfig.some((row) => !deepEqualJson(first, row.config))) conflicts.push({
749
+ id,
750
+ layers: withConfig.map((row) => row.layer),
751
+ values: withConfig.map((row) => row.config)
752
+ });
753
+ }
754
+ return conflicts;
755
+ }
756
+ // src/compat/lockfile.ts
757
+ /** Parse a pnpm lockfile package key, dropping peer suffixes and protocols. */
758
+ function parsePackageKey(key) {
759
+ const clean = key.replace(/\(.*\)$/, "").trim();
760
+ const at = clean.lastIndexOf("@");
761
+ if (at <= 0) return void 0;
762
+ const name = clean.slice(0, at);
763
+ let version = clean.slice(at + 1);
764
+ version = version.replace(/^npm:/, "");
765
+ if (version.length === 0 || version.includes("/")) return void 0;
766
+ if (valid(version) === null) return void 0;
767
+ return {
768
+ name,
769
+ version
770
+ };
771
+ }
772
+ /** Group lockfile package keys by package name. */
773
+ function summarizeLockfile(path, text) {
774
+ const summary = {
775
+ path,
776
+ packageVersions: {},
777
+ dshVersions: {}
778
+ };
779
+ let parsed;
780
+ try {
781
+ parsed = parse(text);
782
+ } catch (error) {
783
+ summary.parseError = errorText$1(error);
784
+ return summary;
785
+ }
786
+ if (parsed === null || typeof parsed !== "object") return summary;
787
+ const packages = parsed.packages;
788
+ if (packages === null || typeof packages !== "object") return summary;
789
+ for (const key of Object.keys(packages)) {
790
+ const parsedKey = parsePackageKey(key);
791
+ if (parsedKey === void 0) continue;
792
+ const versions = summary.packageVersions[parsedKey.name] ?? [];
793
+ if (!versions.includes(parsedKey.version)) versions.push(parsedKey.version);
794
+ summary.packageVersions[parsedKey.name] = versions;
795
+ if (parsedKey.name.startsWith("@deepseek-ai/dsh")) {
796
+ const dshVersions = summary.dshVersions[parsedKey.name] ?? [];
797
+ if (!dshVersions.includes(parsedKey.version)) dshVersions.push(parsedKey.version);
798
+ summary.dshVersions[parsedKey.name] = dshVersions;
799
+ }
800
+ }
801
+ return summary;
802
+ }
803
+ /** Read and summarize a profile's pnpm lockfile. */
804
+ async function readLockfile(path) {
805
+ const text = await readTextFile(path, 5242880).catch(() => void 0);
806
+ if (text === void 0) return void 0;
807
+ return summarizeLockfile(path, text);
808
+ }
809
+ /** Package names with more than one resolved version. */
810
+ function duplicateVersions(summary) {
811
+ return Object.entries(summary.packageVersions).filter(([, versions]) => versions.length > 1).map(([name, versions]) => ({
812
+ name,
813
+ versions
814
+ }));
815
+ }
816
+ // src/compat/profiles.ts
817
+ const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
818
+ /** Read `<profile>/compatibility.json` with the same validation rules as DSH app-boot. */
819
+ async function readCompatibilityFile(profileDir) {
820
+ const path = join(profileDir, "compatibility.json");
821
+ const text = await readTextFile(path, 1048576).catch(() => void 0);
822
+ if (text === void 0) return {
823
+ exemptions: {},
824
+ warnings: [],
825
+ rewritable: true
826
+ };
827
+ let value;
828
+ try {
829
+ value = JSON.parse(text);
830
+ } catch (error) {
831
+ return {
832
+ exemptions: {},
833
+ warnings: [`${path} is not valid JSON (${errorText$1(error)}); treating the profile as having no exemptions`],
834
+ rewritable: false
835
+ };
836
+ }
837
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {
838
+ exemptions: {},
839
+ warnings: [`${path} must map exact package@version keys to DSH version lists`],
840
+ rewritable: false
841
+ };
842
+ const exemptions = {};
843
+ const warnings = [];
844
+ for (const [key, versions] of Object.entries(value)) {
845
+ const separator = key.lastIndexOf("@");
846
+ if (separator <= 0 || !PACKAGE_NAME_RE.test(key.slice(0, separator)) || valid(key.slice(separator + 1)) === null) {
847
+ warnings.push(`${path}: ${JSON.stringify(key)} is not an exact package-name@version key; ignored`);
848
+ continue;
849
+ }
850
+ if (!Array.isArray(versions) || versions.some((item) => typeof item !== "string" || valid(item) === null)) {
851
+ warnings.push(`${path}: ${key} must contain a list of exact DSH versions; ignored`);
852
+ continue;
853
+ }
854
+ exemptions[key] = versions;
855
+ }
856
+ return {
857
+ exemptions,
858
+ warnings,
859
+ rewritable: warnings.length === 0
860
+ };
861
+ }
862
+ /** Read one profile directory's manifest facts. */
863
+ async function readProfileRaw(profileDir, name) {
864
+ const pkg = await readJson(join(profileDir, "package.json")).catch(() => void 0);
865
+ const bundles = Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles.filter((item) => typeof item === "string") : [];
866
+ const dependencies = pkg?.dependencies !== void 0 && pkg.dependencies !== null && typeof pkg.dependencies === "object" ? Object.fromEntries(Object.entries(pkg.dependencies).filter((entry) => typeof entry[1] === "string")) : {};
867
+ const patchRows = [];
868
+ const patchPath = join(profileDir, "cordis.patch.yml");
869
+ const patchText = await readTextFile(patchPath).catch(() => void 0);
870
+ if (patchText !== void 0) {
871
+ const result = parsePatchText(patchText, "profile", patchPath);
872
+ patchRows.push(...result.rows);
873
+ }
874
+ const compatibility = await readCompatibilityFile(profileDir);
875
+ const resolver = new ManifestResolver(profileDir);
876
+ const manifestVersions = {};
877
+ for (const bundle of bundles.slice(0, 100)) manifestVersions[bundle] = manifestVersion((await resolver.resolve(bundle))?.manifest);
878
+ return {
879
+ name,
880
+ dir: profileDir,
881
+ bundles,
882
+ dependencies,
883
+ patchRows,
884
+ exemptions: compatibility.exemptions,
885
+ compatibilityWarnings: compatibility.warnings,
886
+ compatibilityRewritable: compatibility.rewritable,
887
+ manifestVersions
888
+ };
889
+ }
890
+ /** Scan profile directories under `<dshHome>/profiles`. */
891
+ async function scanProfiles(profilesDir, maxProfiles) {
892
+ const diagnostics = [];
893
+ let names;
894
+ try {
895
+ names = (await readdir(profilesDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
896
+ } catch {
897
+ return {
898
+ profiles: [],
899
+ diagnostics: [`profiles directory unavailable: ${profilesDir}`]
900
+ };
901
+ }
902
+ const selected = names.slice(0, maxProfiles);
903
+ if (names.length > selected.length) diagnostics.push(`profile scan truncated to ${selected.length} of ${names.length}`);
904
+ const profiles = [];
905
+ for (const name of selected) {
906
+ const dir = join(profilesDir, name);
907
+ try {
908
+ profiles.push(await readProfileRaw(dir, name));
909
+ } catch (error) {
910
+ diagnostics.push(`profile ${name} unreadable: ${errorText$1(error)}`);
911
+ }
912
+ }
913
+ return {
914
+ profiles,
915
+ diagnostics
916
+ };
917
+ }
918
+ /** Collect workspace instruction files without scanning the whole project. */
919
+ async function readWorkspace(cwd, dshHome, agentsHome = process.env.DSH_AGENTS_HOME?.trim() || join(homedir(), ".agents")) {
920
+ const candidates = [];
921
+ const seen = /* @__PURE__ */ new Set();
922
+ const add = (path) => {
923
+ if (seen.has(path)) return;
924
+ seen.add(path);
925
+ candidates.push(path);
926
+ };
927
+ let directory = resolve(cwd);
928
+ for (let depth = 0; depth < 8; depth++) {
929
+ add(join(directory, "AGENTS.md"));
930
+ add(join(directory, "CLAUDE.md"));
931
+ add(join(directory, "AGENTS.local.md"));
932
+ add(join(directory, "CLAUDE.local.md"));
933
+ const parent = dirname(directory);
934
+ if (parent === directory) break;
935
+ try {
936
+ await stat(join(directory, ".git"));
937
+ break;
938
+ } catch {
939
+ directory = parent;
940
+ }
941
+ }
942
+ add(join(dshHome, "AGENTS.md"));
943
+ add(join(agentsHome, "AGENTS.md"));
944
+ const instructionFiles = [];
945
+ const instructions = [];
946
+ for (const file of candidates) {
947
+ const text = await readTextFile(file, 2097152).catch(() => void 0);
948
+ if (text === void 0 || text.trim().length === 0) continue;
949
+ instructionFiles.push(file);
950
+ instructions.push({
951
+ file,
952
+ text
953
+ });
954
+ }
955
+ return {
956
+ cwd: resolve(cwd),
957
+ instructionFiles,
958
+ instructions
959
+ };
960
+ }
961
+ // src/compat/runtime-check.ts
962
+ function safeSatisfies(version, range) {
963
+ try {
964
+ return satisfies(version, range, { includePrerelease: true });
965
+ } catch {
966
+ return false;
967
+ }
968
+ }
969
+ let appBootPromise;
970
+ /** Load app-boot lazily; compatibility analysis degrades if its peers are unavailable. */
971
+ async function loadAppBoot() {
972
+ appBootPromise ??= import("@deepseek-ai/dsh-app-boot").then((module) => module).catch(() => void 0);
973
+ return appBootPromise;
974
+ }
975
+ /** Runtime version, preferring the official helper. */
976
+ async function getRuntimeVersion() {
977
+ const appBoot = await loadAppBoot();
978
+ try {
979
+ const version = appBoot?.getDshRuntimeVersion?.();
980
+ if (typeof version === "string" && version.length > 0) return version;
981
+ } catch {}
982
+ try {
983
+ const argvBase = process.argv[1] ?? process.cwd();
984
+ const require = createRequire(argvBase);
985
+ const pkg = require(require.resolve("@deepseek-ai/dsh/package.json", { paths: [dirname(argvBase), process.cwd()] }));
986
+ if (typeof pkg.version === "string") return pkg.version;
987
+ } catch {}
988
+ return process.env.DSH_VERSION ?? "0.0.0";
989
+ }
990
+ /** Check one manifest against the DSH runtime, using app-boot when available. */
991
+ async function evaluateCompatibility(manifest, exemptions, runtimeVersion, fallbackName, fallbackVersion) {
992
+ const appBoot = await loadAppBoot();
993
+ if (typeof appBoot?.evaluatePluginCompatibility === "function") try {
994
+ const result = appBoot.evaluatePluginCompatibility(manifest, exemptions, runtimeVersion);
995
+ if (result !== void 0) return result;
996
+ } catch {}
997
+ return evaluateCompatibilityLocal(manifest, exemptions, runtimeVersion, fallbackName, fallbackVersion);
998
+ }
999
+ /** Local mirror of app-boot's requirement evaluation, used when app-boot is unavailable. */
1000
+ function evaluateCompatibilityLocal(manifest, exemptions, runtimeVersion, fallbackName, fallbackVersion) {
1001
+ const requirements = {};
1002
+ const engines = manifestEngines(manifest);
1003
+ if (typeof engines.dsh === "string") {
1004
+ if (!safeSatisfies(runtimeVersion, engines.dsh)) requirements["engines.dsh"] = engines.dsh;
1005
+ } else for (const [name, range] of Object.entries(manifestPeers(manifest))) {
1006
+ if (name !== "@deepseek-ai/dsh" && !name.startsWith("@deepseek-ai/dsh-")) continue;
1007
+ if (!safeSatisfies(runtimeVersion, [
1008
+ "workspace:^",
1009
+ "workspace:~",
1010
+ "workspace:*"
1011
+ ].includes(range) ? runtimeVersion : range)) requirements[name] = range;
1012
+ }
1013
+ if (Object.keys(requirements).length === 0) return void 0;
1014
+ const name = typeof manifest.name === "string" ? manifest.name : fallbackName ?? "unknown";
1015
+ const version = typeof manifest.version === "string" ? manifest.version : fallbackVersion ?? "0.0.0";
1016
+ return {
1017
+ name,
1018
+ version,
1019
+ runtimeVersion,
1020
+ requirements,
1021
+ exempted: exemptions[`${name}@${version}`]?.includes(runtimeVersion) === true
1022
+ };
1023
+ }
1024
+ /** Check `engines.node` against the running Node. */
1025
+ function checkNodeEngine(manifest, nodeVersion) {
1026
+ const range = manifestEngines(manifest).node;
1027
+ if (typeof range !== "string") return void 0;
1028
+ return safeSatisfies(nodeVersion, range) ? void 0 : range;
1029
+ }
1030
+ /** Unsupported platform list, or undefined when the bundle supports the current platform. */
1031
+ function checkPlatform(manifest, platform) {
1032
+ const platforms = manifestPlatforms(manifest);
1033
+ if (platforms.length === 0) return void 0;
1034
+ return platforms.includes(platform) ? void 0 : platforms;
1035
+ }
1036
+ // src/compat/context.ts
1037
+ /** Read the profile manifest facts without failing the whole scan. */
1038
+ async function readProfileManifestFacts(profileDir) {
1039
+ const pkg = await readJson(join(profileDir, "package.json")).catch(() => void 0);
1040
+ return {
1041
+ bundles: Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles.filter((item) => typeof item === "string") : [],
1042
+ dependencies: pkg?.dependencies !== void 0 && pkg.dependencies !== null ? Object.fromEntries(Object.entries(pkg.dependencies).filter((entry) => typeof entry[1] === "string")) : {}
1043
+ };
1044
+ }
1045
+ /** Collect loader, plugin-manager, prompt, profile, lockfile, and workspace facts. */
1046
+ async function collectCompatContext(options) {
1047
+ const diagnostics = [];
1048
+ const facts = options.bundleNames === void 0 ? await readProfileManifestFacts(options.profileDir) : {
1049
+ bundles: [...options.bundleNames],
1050
+ dependencies: options.dependencies ?? (await readProfileManifestFacts(options.profileDir)).dependencies
1051
+ };
1052
+ const runtime = {
1053
+ dshVersion: options.runtime?.dshVersion ?? await getRuntimeVersion(),
1054
+ nodeVersion: options.runtime?.nodeVersion ?? process.versions.node,
1055
+ platform: options.runtime?.platform ?? process.platform,
1056
+ arch: options.runtime?.arch ?? process.arch
1057
+ };
1058
+ let inventorySnapshot;
1059
+ if (options.inventory !== void 0) try {
1060
+ inventorySnapshot = await options.inventory.list();
1061
+ } catch (error) {
1062
+ diagnostics.push(`plugin inventory unavailable: ${errorText$1(error)}`);
1063
+ }
1064
+ const graph = collectLoaderGraph(options.loader, inventorySnapshot);
1065
+ diagnostics.push(...graph.diagnostics);
1066
+ let bundles = [];
1067
+ let entriesInfo = [];
1068
+ let exemptions = {};
1069
+ if (options.pluginManager !== void 0) {
1070
+ try {
1071
+ bundles = await options.pluginManager.listBundles();
1072
+ } catch (error) {
1073
+ diagnostics.push(`listBundles failed: ${errorText$1(error)}`);
1074
+ }
1075
+ try {
1076
+ entriesInfo = await options.pluginManager.listPlugins();
1077
+ } catch (error) {
1078
+ diagnostics.push(`listPlugins failed: ${errorText$1(error)}`);
1079
+ }
1080
+ try {
1081
+ exemptions = options.pluginManager.listVersionExemptions().exemptions;
1082
+ } catch (error) {
1083
+ diagnostics.push(`listVersionExemptions failed: ${errorText$1(error)}`);
1084
+ }
1085
+ } else diagnostics.push("pluginManager unavailable; compatibility analysis is read-only static mode");
1086
+ const profileRaw = await readProfileRaw(options.profileDir, options.profileName).catch((error) => {
1087
+ diagnostics.push(`current profile unreadable: ${errorText$1(error)}`);
1088
+ });
1089
+ const allBundleNames = [.../* @__PURE__ */ new Set([
1090
+ ...facts.bundles,
1091
+ ...profileRaw?.bundles ?? [],
1092
+ ...bundles.map((bundle) => bundle.name),
1093
+ ...graph.entries.filter((entry) => entry.source === "loader").map((entry) => rootPackageName(entry.moduleName))
1094
+ ])].slice(0, 200);
1095
+ const manifestResolver = new ManifestResolver(options.profileDir, 6e4);
1096
+ const manifests = /* @__PURE__ */ new Map();
1097
+ for (const name of allBundleNames) {
1098
+ const resolved = await manifestResolver.resolve(name);
1099
+ manifests.set(rootPackageName(name), resolved?.manifest);
1100
+ }
1101
+ let patchRows = profileRaw?.patchRows ?? [];
1102
+ if (facts.bundles.length > 0) try {
1103
+ const patchResult = await readProfilePatchLayers({
1104
+ profileDir: options.profileDir,
1105
+ dshHome: options.dshHome,
1106
+ bundles: facts.bundles,
1107
+ manifests
1108
+ });
1109
+ patchRows = patchResult.rows;
1110
+ diagnostics.push(...patchResult.diagnostics);
1111
+ } catch (error) {
1112
+ diagnostics.push(`patch layer read failed: ${errorText$1(error)}`);
1113
+ }
1114
+ let lockfile;
1115
+ if (options.config.compatReadLockfile) {
1116
+ lockfile = await readLockfile(join(options.profileDir, "pnpm-lock.yaml"));
1117
+ if (lockfile?.parseError !== void 0) diagnostics.push(`lockfile parse failed: ${lockfile.parseError}`);
1118
+ }
1119
+ let profiles = profileRaw === void 0 ? [] : [profileRaw];
1120
+ if (options.config.compatScanAllProfiles) {
1121
+ const scanned = await scanProfiles(join(options.dshHome, "profiles"), options.config.compatMaxProfiles);
1122
+ diagnostics.push(...scanned.diagnostics);
1123
+ profiles = scanned.profiles.map((profile) => profile.name === options.profileName && profileRaw !== void 0 ? {
1124
+ ...profile,
1125
+ patchRows,
1126
+ exemptions: {
1127
+ ...profile.exemptions,
1128
+ ...exemptions
1129
+ }
1130
+ } : profile);
1131
+ if (profiles.length === 0 && profileRaw !== void 0) profiles = [profileRaw];
1132
+ }
1133
+ const workspace = options.config.compatReadWorkspace ? await readWorkspace(options.cwd, options.dshHome) : {
1134
+ cwd: options.cwd,
1135
+ instructionFiles: [],
1136
+ instructions: []
1137
+ };
1138
+ let prompt;
1139
+ if (options.prompt !== void 0) try {
1140
+ prompt = await options.prompt.assemble(options.agent, options.toolSet);
1141
+ } catch (error) {
1142
+ diagnostics.push(`prompt assembly unavailable: ${errorText$1(error)}`);
1143
+ }
1144
+ return {
1145
+ runtime,
1146
+ config: options.config,
1147
+ profile: {
1148
+ name: options.profileName,
1149
+ dir: options.profileDir,
1150
+ bundles: facts.bundles.length > 0 ? facts.bundles : profileRaw?.bundles ?? [],
1151
+ dependencies: facts.dependencies,
1152
+ patchRows,
1153
+ exemptions: {
1154
+ ...profileRaw?.exemptions ?? {},
1155
+ ...exemptions
1156
+ },
1157
+ compatibilityWarnings: profileRaw?.compatibilityWarnings ?? [],
1158
+ compatibilityRewritable: profileRaw?.compatibilityRewritable ?? true
1159
+ },
1160
+ loaderEntries: graph.entries,
1161
+ bundles,
1162
+ entriesInfo,
1163
+ inventory: inventorySnapshot,
1164
+ manifests,
1165
+ lockfile,
1166
+ profiles,
1167
+ workspace,
1168
+ prompt,
1169
+ diagnostics
1170
+ };
1171
+ }
1172
+ // src/compat/adapters.ts
1173
+ /** Resolve the current profile facts from Cordis, falling back to environment/defaults. */
1174
+ function resolveProfileFacts(ctx, agent) {
1175
+ const profileContext = safeGet(ctx, "profileContext");
1176
+ const name = typeof profileContext?.name === "string" ? profileContext.name : process.env.DSH_PROFILE?.trim() || "web";
1177
+ const dshHome = typeof profileContext?.home === "string" && profileContext.home.length > 0 ? profileContext.home : resolveDshHome();
1178
+ return {
1179
+ name,
1180
+ dir: typeof profileContext?.dir === "string" && profileContext.dir.length > 0 ? profileContext.dir : join(dshHome, "profiles", name),
1181
+ dshHome,
1182
+ cwd: typeof profileContext?.cwd === "string" && profileContext.cwd.length > 0 ? profileContext.cwd : sessionCwd(agent) ?? process.cwd(),
1183
+ bundles: Array.isArray(profileContext?.startedBundles) ? profileContext.startedBundles.filter((item) => typeof item === "string") : void 0
1184
+ };
1185
+ }
1186
+ function sessionCwd(agent) {
1187
+ if (!isObject(agent)) return void 0;
1188
+ const session = agent.session;
1189
+ if (!isObject(session)) return void 0;
1190
+ const header = session.header;
1191
+ if (!isObject(header)) return void 0;
1192
+ return typeof header.cwd === "string" ? header.cwd : void 0;
1193
+ }
1194
+ function getPluginManager(ctx) {
1195
+ return safeGet(ctx, "pluginManager");
1196
+ }
1197
+ function getInventory(ctx) {
1198
+ return safeGet(ctx, "pluginInventory");
1199
+ }
1200
+ function getLoader(ctx) {
1201
+ return safeGet(ctx, "loader");
1202
+ }
1203
+ /** Build a prompt adapter that preserves the agent scope and step tool set. */
1204
+ function getPromptAdapter(ctx, agent) {
1205
+ const systemPrompt = safeGet(ctx, "systemPrompt");
1206
+ if (typeof systemPrompt?.assemble !== "function") return void 0;
1207
+ let scope;
1208
+ if (isObject(agent) && isObject(agent.ctx)) try {
1209
+ scope = scopeOf(agent.ctx);
1210
+ } catch {
1211
+ scope = void 0;
1212
+ }
1213
+ return { async assemble(agentArg, toolSet) {
1214
+ const assembly = await systemPrompt.assemble({
1215
+ agent: agentArg,
1216
+ scope,
1217
+ toolSet
1218
+ });
1219
+ return isObject(assembly) ? assembly : void 0;
1220
+ } };
1221
+ }
1222
+ /** Narrow a config-like object for the compat collector. */
1223
+ function toCompatConfig(config) {
1224
+ return {
1225
+ compatEnabled: config.compatEnabled,
1226
+ compatScanAllProfiles: config.compatScanAllProfiles,
1227
+ compatMaxProfiles: config.compatMaxProfiles,
1228
+ compatIncludeInfo: config.compatIncludeInfo,
1229
+ compatMaxFindings: config.compatMaxFindings,
1230
+ compatReadLockfile: config.compatReadLockfile,
1231
+ compatReadWorkspace: config.compatReadWorkspace,
1232
+ compatStrictOfficialOverrides: config.compatStrictOfficialOverrides,
1233
+ compatCacheTtlMs: config.compatCacheTtlMs,
1234
+ toolOwners: config.toolOwners
1235
+ };
1236
+ }
1237
+ function safeGet(ctx, key) {
1238
+ try {
1239
+ return ctx.get(key);
1240
+ } catch {
1241
+ return;
1242
+ }
1243
+ }
1244
+ function isObject(value) {
1245
+ return typeof value === "object" && value !== null;
1246
+ }
1247
+ // src/compat/finding.ts
1248
+ /** Build a finding with a deterministic id and deduplicated subjects/evidence. */
1249
+ function makeFinding(input) {
1250
+ const subjects = uniq(input.subjects.filter((subject) => subject.length > 0)).sort();
1251
+ const evidence = dedupeEvidence(input.evidence);
1252
+ return {
1253
+ id: shortHash(`${input.code}|${subjects.join("|")}`),
1254
+ domain: input.domain,
1255
+ code: input.code,
1256
+ severity: input.severity,
1257
+ title: input.title,
1258
+ subjects,
1259
+ evidence,
1260
+ confidence: input.confidence ?? "high",
1261
+ fix: input.fix,
1262
+ autoApplicable: input.autoApplicable ?? false
1263
+ };
1264
+ }
1265
+ function dedupeEvidence(evidence) {
1266
+ const seen = /* @__PURE__ */ new Set();
1267
+ const out = [];
1268
+ for (const item of evidence) {
1269
+ const key = `${item.source}|${item.ref ?? ""}|${item.summary}`;
1270
+ if (seen.has(key)) continue;
1271
+ seen.add(key);
1272
+ out.push(item);
1273
+ }
1274
+ return out;
1275
+ }
1276
+ const SEVERITY_RANK = {
1277
+ error: 0,
1278
+ warn: 1,
1279
+ info: 2
1280
+ };
1281
+ /** Sort findings by severity, domain, code, and subjects. */
1282
+ function sortFindings(findings) {
1283
+ return [...findings].sort((a, b) => {
1284
+ const severity = SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
1285
+ if (severity !== 0) return severity;
1286
+ const domain = a.domain.localeCompare(b.domain);
1287
+ if (domain !== 0) return domain;
1288
+ const code = a.code.localeCompare(b.code);
1289
+ if (code !== 0) return code;
1290
+ return a.subjects.join("|").localeCompare(b.subjects.join("|"));
1291
+ });
1292
+ }
1293
+ /** Merge duplicate findings with the same id, unioning evidence. */
1294
+ function dedupeFindings(findings) {
1295
+ const byId = /* @__PURE__ */ new Map();
1296
+ for (const finding of findings) {
1297
+ const existing = byId.get(finding.id);
1298
+ if (existing === void 0) {
1299
+ byId.set(finding.id, finding);
1300
+ continue;
1301
+ }
1302
+ const subjects = uniq([...existing.subjects, ...finding.subjects]).sort();
1303
+ byId.set(finding.id, {
1304
+ ...existing,
1305
+ subjects,
1306
+ evidence: dedupeEvidence([...existing.evidence, ...finding.evidence]),
1307
+ fix: existing.fix ?? finding.fix,
1308
+ autoApplicable: existing.autoApplicable || finding.autoApplicable,
1309
+ severity: SEVERITY_RANK[finding.severity] < SEVERITY_RANK[existing.severity] ? finding.severity : existing.severity
1310
+ });
1311
+ }
1312
+ return [...byId.values()];
1313
+ }
1314
+ /** Group findings by subject for trim integration. */
1315
+ function findingsBySubject(findings) {
1316
+ const map = /* @__PURE__ */ new Map();
1317
+ for (const finding of findings) for (const subject of finding.subjects) {
1318
+ const list = map.get(subject) ?? [];
1319
+ list.push(finding);
1320
+ map.set(subject, list);
1321
+ }
1322
+ return map;
1323
+ }
1324
+ // src/compat/rules-runtime.ts
1325
+ const INCOMPATIBLE_DIAGNOSTIC_RE = /incompatib|version requirement|peer dependenc/i;
1326
+ /** Plugin ↔ DSH runtime, Node, platform, exemptions, and duplicate DSH copies. */
1327
+ async function runRuntimeRules(context) {
1328
+ const findings = [];
1329
+ const selected = new Set(context.profile.bundles.map((name) => rootPackageName(name)));
1330
+ for (const bundle of context.bundles) {
1331
+ const name = rootPackageName(bundle.name);
1332
+ const manifest = context.manifests.get(name);
1333
+ const subjects = [name];
1334
+ if (manifest === void 0) {
1335
+ if (bundle.error?.incompatible !== void 0 && bundle.error.incompatible.length > 0) for (const incompatible of bundle.error.incompatible) findings.push(makeFinding({
1336
+ domain: "plugin-runtime",
1337
+ code: "RT_PREFLIGHT_DENIED",
1338
+ severity: "error",
1339
+ title: `${incompatible.name} was denied by the DSH compatibility preflight`,
1340
+ subjects: [incompatible.name],
1341
+ confidence: "high",
1342
+ evidence: [{
1343
+ source: "plugin-manager",
1344
+ ref: `${incompatible.name}@${incompatible.version}`,
1345
+ summary: `requires ${JSON.stringify(incompatible.requirements)} on dsh ${incompatible.runtimeVersion}`
1346
+ }],
1347
+ fix: {
1348
+ kind: "update",
1349
+ summary: "update the plugin or DSH, or grant an exact-version exemption after accepting the risk",
1350
+ safe: false,
1351
+ requiresConsent: true
1352
+ }
1353
+ }));
1354
+ if (bundle.error?.code === "unsupported-platform") findings.push(makeFinding({
1355
+ domain: "plugin-runtime",
1356
+ code: "RT_PLATFORM_UNSUPPORTED",
1357
+ severity: "error",
1358
+ title: `${name} does not support this platform`,
1359
+ subjects,
1360
+ confidence: "high",
1361
+ evidence: [{
1362
+ source: "plugin-manager",
1363
+ ref: name,
1364
+ summary: `bundle reports unsupported-platform for ${context.runtime.platform}`
1365
+ }],
1366
+ fix: {
1367
+ kind: "disable",
1368
+ summary: "disable the optional bundle on this platform",
1369
+ safe: true,
1370
+ target: name,
1371
+ requiresConsent: true
1372
+ }
1373
+ }));
1374
+ if ((bundle.enabled || bundle.installed) && bundle.error?.code !== "unsupported-platform" && !bundle.error?.incompatible?.length) findings.push(makeFinding({
1375
+ domain: "plugin-runtime",
1376
+ code: "RT_MANIFEST_UNAVAILABLE",
1377
+ severity: "info",
1378
+ title: `${name} manifest could not be resolved`,
1379
+ subjects,
1380
+ confidence: "low",
1381
+ evidence: [{
1382
+ source: "manifest",
1383
+ ref: name,
1384
+ summary: "runtime manifest checks were skipped for this bundle"
1385
+ }],
1386
+ fix: {
1387
+ kind: "none",
1388
+ summary: "no action; manifest resolution is best-effort",
1389
+ safe: true,
1390
+ requiresConsent: false
1391
+ }
1392
+ }));
1393
+ continue;
1394
+ }
1395
+ const issue = await evaluateCompatibility(manifest, context.profile.exemptions, context.runtime.dshVersion, name, bundle.version);
1396
+ if (issue !== void 0) for (const [requirement, range] of Object.entries(issue.requirements)) {
1397
+ const isEngine = requirement === "engines.dsh";
1398
+ if (issue.exempted) findings.push(makeFinding({
1399
+ domain: "plugin-runtime",
1400
+ code: "RT_EXEMPTION_ACTIVE",
1401
+ severity: "warn",
1402
+ title: `${issue.name}@${issue.version} runs under an exact-version exemption`,
1403
+ subjects: [issue.name],
1404
+ confidence: "high",
1405
+ evidence: [{
1406
+ source: "plugin-manager",
1407
+ ref: `${issue.name}@${issue.version}`,
1408
+ summary: `${requirement} ${range} does not match dsh ${issue.runtimeVersion}; exemption is active`
1409
+ }],
1410
+ fix: {
1411
+ kind: "update",
1412
+ summary: "prefer updating the plugin; keep the exemption only as an informed risk",
1413
+ safe: false,
1414
+ requiresConsent: true
1415
+ }
1416
+ }));
1417
+ else findings.push(makeFinding({
1418
+ domain: "plugin-runtime",
1419
+ code: isEngine ? "RT_ENGINE_UNMET" : "RT_PEER_UNMET",
1420
+ severity: "error",
1421
+ title: `${issue.name}@${issue.version} is incompatible with dsh ${issue.runtimeVersion}`,
1422
+ subjects: [issue.name],
1423
+ confidence: "high",
1424
+ evidence: [{
1425
+ source: "manifest",
1426
+ ref: `${issue.name}@${issue.version}`,
1427
+ summary: `${requirement} ${range} does not match dsh ${issue.runtimeVersion}`
1428
+ }],
1429
+ fix: {
1430
+ kind: "update",
1431
+ summary: "update the plugin or DSH; an exact-version exemption requires explicit risk acceptance",
1432
+ safe: false,
1433
+ requiresConsent: true
1434
+ }
1435
+ }));
1436
+ }
1437
+ const nodeRange = checkNodeEngine(manifest, context.runtime.nodeVersion);
1438
+ if (nodeRange !== void 0) findings.push(makeFinding({
1439
+ domain: "plugin-runtime",
1440
+ code: "RT_NODE_UNMET",
1441
+ severity: "error",
1442
+ title: `${name} does not support Node ${context.runtime.nodeVersion}`,
1443
+ subjects,
1444
+ confidence: "high",
1445
+ evidence: [{
1446
+ source: "manifest",
1447
+ ref: name,
1448
+ summary: `engines.node ${nodeRange} does not match Node ${context.runtime.nodeVersion}`
1449
+ }],
1450
+ fix: {
1451
+ kind: "update",
1452
+ summary: "switch Node or update the plugin",
1453
+ safe: false,
1454
+ requiresConsent: true
1455
+ }
1456
+ }));
1457
+ const platforms = checkPlatform(manifest, context.runtime.platform);
1458
+ if (platforms !== void 0) findings.push(makeFinding({
1459
+ domain: "plugin-runtime",
1460
+ code: "RT_PLATFORM_UNSUPPORTED",
1461
+ severity: "error",
1462
+ title: `${name} does not support ${context.runtime.platform}`,
1463
+ subjects,
1464
+ confidence: "high",
1465
+ evidence: [{
1466
+ source: "manifest",
1467
+ ref: name,
1468
+ summary: `dsh.bundle.platforms ${JSON.stringify(platforms)} excludes ${context.runtime.platform}`
1469
+ }],
1470
+ fix: {
1471
+ kind: "disable",
1472
+ summary: "disable the optional bundle on this platform",
1473
+ safe: true,
1474
+ target: name,
1475
+ requiresConsent: true
1476
+ }
1477
+ }));
1478
+ }
1479
+ for (const entry of context.entriesInfo) {
1480
+ if (typeof entry.diagnostic !== "string") continue;
1481
+ if (!INCOMPATIBLE_DIAGNOSTIC_RE.test(entry.diagnostic)) continue;
1482
+ if (!/incompatible/i.test(entry.diagnostic)) continue;
1483
+ findings.push(makeFinding({
1484
+ domain: "plugin-runtime",
1485
+ code: "RT_PREFLIGHT_DENIED",
1486
+ severity: "error",
1487
+ title: `${entry.moduleName} was denied by the compatibility preflight`,
1488
+ subjects: [entry.moduleName],
1489
+ confidence: "medium",
1490
+ evidence: [{
1491
+ source: "plugin-manager",
1492
+ ref: entry.entryId,
1493
+ summary: entry.diagnostic
1494
+ }],
1495
+ fix: {
1496
+ kind: "update",
1497
+ summary: "update the plugin/DSH or grant an exact-version exemption after accepting the risk",
1498
+ safe: false,
1499
+ requiresConsent: true
1500
+ }
1501
+ }));
1502
+ }
1503
+ for (const [key, versions] of Object.entries(context.profile.exemptions)) {
1504
+ const separator = key.lastIndexOf("@");
1505
+ if (separator <= 0) continue;
1506
+ const name = key.slice(0, separator);
1507
+ if (!selected.has(name)) continue;
1508
+ findings.push(makeFinding({
1509
+ domain: "plugin-runtime",
1510
+ code: "RT_EXEMPTION_ACTIVE",
1511
+ severity: "warn",
1512
+ title: `${key} has an exact-version exemption`,
1513
+ subjects: [name],
1514
+ confidence: "high",
1515
+ evidence: [{
1516
+ source: "profile-file",
1517
+ ref: "compatibility.json",
1518
+ summary: `exemption allows dsh ${versions.join(", ")}`
1519
+ }],
1520
+ fix: {
1521
+ kind: "update",
1522
+ summary: "prefer a compatible plugin version; the exemption is an informed risk",
1523
+ safe: false,
1524
+ requiresConsent: true
1525
+ }
1526
+ }));
1527
+ }
1528
+ if (context.config.compatReadLockfile) {
1529
+ if (context.lockfile === void 0) findings.push(makeFinding({
1530
+ domain: "plugin-runtime",
1531
+ code: "RT_LOCKFILE_UNAVAILABLE",
1532
+ severity: "info",
1533
+ title: "pnpm-lock.yaml is unavailable",
1534
+ subjects: [context.profile.name],
1535
+ confidence: "high",
1536
+ evidence: [{
1537
+ source: "lockfile",
1538
+ ref: context.profile.dir,
1539
+ summary: "duplicate package version analysis was skipped"
1540
+ }],
1541
+ fix: {
1542
+ kind: "none",
1543
+ summary: "no action",
1544
+ safe: true,
1545
+ requiresConsent: false
1546
+ }
1547
+ }));
1548
+ else for (const [name, versions] of Object.entries(context.lockfile.dshVersions)) {
1549
+ if (versions.length <= 1) continue;
1550
+ findings.push(makeFinding({
1551
+ domain: "plugin-runtime",
1552
+ code: "RT_DUPLICATE_DSH_COPIES",
1553
+ severity: "warn",
1554
+ title: `multiple DSH copies of ${name} are installed`,
1555
+ subjects: [name],
1556
+ confidence: "high",
1557
+ evidence: [{
1558
+ source: "lockfile",
1559
+ ref: context.lockfile.path,
1560
+ summary: `versions ${versions.join(", ")}`
1561
+ }],
1562
+ fix: {
1563
+ kind: "update",
1564
+ summary: "deduplicate with pnpm overrides or align the affected plugins",
1565
+ safe: false,
1566
+ requiresConsent: true
1567
+ }
1568
+ }));
1569
+ }
1570
+ }
1571
+ return findings;
1572
+ }
1573
+ // src/compat/rules-plugin.ts
1574
+ const CORE_SERVICES = /* @__PURE__ */ new Set([
1575
+ "tools",
1576
+ "sessions",
1577
+ "agents",
1578
+ "systemPrompt",
1579
+ "loader",
1580
+ "llm",
1581
+ "schedule",
1582
+ "pluginManager",
1583
+ "workingDirectory",
1584
+ "sandboxPolicy",
1585
+ "approval",
1586
+ "storage",
1587
+ "userQuestions",
1588
+ "jobs",
1589
+ "web",
1590
+ "mcp",
1591
+ "skills",
1592
+ "commands",
1593
+ "settings",
1594
+ "credentials",
1595
+ "authorization",
1596
+ "profileContext",
1597
+ "pluginInventory",
1598
+ "subagent",
1599
+ "workflow",
1600
+ "goal",
1601
+ "tokenMeter",
1602
+ "sessionProjections",
1603
+ "attachments",
1604
+ "spill",
1605
+ "terminal",
1606
+ "timeContext"
1607
+ ]);
1608
+ const REGISTRATION_FAILURE_RE = /duplicate|already registered|already provided|conflict|UNKNOWN_TOOL|tool .* exists/i;
1609
+ /** Plugin ↔ plugin conflicts: services, rows, configs, MCP, registration, overlap, versions. */
1610
+ async function runPluginRules(context) {
1611
+ const findings = [];
1612
+ const entries = context.loaderEntries.filter((entry) => entry.enabled);
1613
+ const scopeOf = (entry) => entry.source === "preset" ? entry.presetId ?? "preset" : entry.parentId ?? "root";
1614
+ const providers = /* @__PURE__ */ new Map();
1615
+ for (const entry of entries) for (const service of entry.provide) {
1616
+ const list = providers.get(service) ?? [];
1617
+ list.push(entry);
1618
+ providers.set(service, list);
1619
+ }
1620
+ for (const [service, list] of providers) {
1621
+ const byScope = /* @__PURE__ */ new Map();
1622
+ for (const entry of list) {
1623
+ const scope = scopeOf(entry);
1624
+ const scoped = byScope.get(scope) ?? [];
1625
+ scoped.push(entry);
1626
+ byScope.set(scope, scoped);
1627
+ }
1628
+ for (const [scope, scoped] of byScope) {
1629
+ if (scoped.length <= 1) continue;
1630
+ findings.push(makeFinding({
1631
+ domain: "plugin-plugin",
1632
+ code: "PP_SERVICE_DUPLICATE",
1633
+ severity: "error",
1634
+ title: `service "${service}" is provided by multiple plugins`,
1635
+ subjects: scoped.map((entry) => entry.moduleName),
1636
+ confidence: "high",
1637
+ evidence: [{
1638
+ source: "loader",
1639
+ ref: scope,
1640
+ summary: scoped.map((entry) => entry.moduleName).join(", ")
1641
+ }],
1642
+ fix: {
1643
+ kind: "disable",
1644
+ summary: "disable one provider; keep the service owner that the deployment depends on",
1645
+ safe: false,
1646
+ requiresConsent: true,
1647
+ target: scoped[0]?.moduleName
1648
+ }
1649
+ }));
1650
+ }
1651
+ }
1652
+ const providedAnywhere = new Set(providers.keys());
1653
+ for (const entry of entries) {
1654
+ if (entry.inject.length === 0) continue;
1655
+ if (entry.fiberState !== "pending" && entry.fiberState !== "failed") continue;
1656
+ const missing = entry.inject.filter((service) => !providedAnywhere.has(service) && !CORE_SERVICES.has(service));
1657
+ if (missing.length === 0) continue;
1658
+ findings.push(makeFinding({
1659
+ domain: "plugin-plugin",
1660
+ code: "PP_SERVICE_MISSING",
1661
+ severity: entry.fiberState === "failed" ? "error" : "warn",
1662
+ title: `${entry.moduleName} is waiting for missing services`,
1663
+ subjects: [entry.moduleName],
1664
+ confidence: "medium",
1665
+ evidence: [{
1666
+ source: "loader",
1667
+ ref: entry.id,
1668
+ summary: `required ${missing.join(", ")}; fiber ${entry.fiberState}${entry.diagnostic === void 0 ? "" : ` (${entry.diagnostic})`}`
1669
+ }],
1670
+ fix: {
1671
+ kind: "enable",
1672
+ summary: "enable or install a provider for the missing service, or disable the consumer",
1673
+ safe: false,
1674
+ requiresConsent: true
1675
+ }
1676
+ }));
1677
+ }
1678
+ for (const finding of detectServiceCycles(entries, providers)) findings.push(finding);
1679
+ const enabledBundles = context.bundles.filter((bundle) => bundle.enabled && bundle.error === void 0);
1680
+ const rows = /* @__PURE__ */ new Map();
1681
+ for (const bundle of enabledBundles) for (const row of bundle.rows) {
1682
+ const list = rows.get(row.rowId) ?? [];
1683
+ list.push(bundle.name);
1684
+ rows.set(row.rowId, list);
1685
+ }
1686
+ for (const [rowId, names] of rows) {
1687
+ const unique = [...new Set(names)];
1688
+ if (unique.length <= 1) continue;
1689
+ findings.push(makeFinding({
1690
+ domain: "plugin-plugin",
1691
+ code: "PP_ROW_DUPLICATE",
1692
+ severity: "error",
1693
+ title: `row "${rowId}" is declared by multiple enabled bundles`,
1694
+ subjects: unique,
1695
+ confidence: "high",
1696
+ evidence: [{
1697
+ source: "plugin-manager",
1698
+ ref: rowId,
1699
+ summary: `declared by ${unique.join(", ")}`
1700
+ }],
1701
+ fix: {
1702
+ kind: "disable",
1703
+ summary: "disable one of the bundles declaring this row",
1704
+ safe: false,
1705
+ requiresConsent: true,
1706
+ target: unique[0]
1707
+ }
1708
+ }));
1709
+ }
1710
+ const officialLayers = new Set(enabledBundles.filter((bundle) => bundle.official || bundle.name.startsWith("@deepseek-ai/dsh-")).map((bundle) => bundle.name));
1711
+ const conflicts = findConfigConflicts(context.profile.patchRows, { skipLayer: (layer) => !context.config.compatStrictOfficialOverrides && (officialLayers.has(layer) || layer === "root") }).filter((conflict) => {
1712
+ return conflict.layers.filter((layer) => layer !== "profile" && layer !== "home").length >= 2;
1713
+ });
1714
+ for (const conflict of conflicts) findings.push(makeFinding({
1715
+ domain: "plugin-plugin",
1716
+ code: "PP_CONFIG_CONFLICT",
1717
+ severity: "warn",
1718
+ title: `row "${conflict.id}" has conflicting configuration across bundles`,
1719
+ subjects: conflict.layers,
1720
+ confidence: "medium",
1721
+ evidence: [{
1722
+ source: "profile-file",
1723
+ ref: conflict.id,
1724
+ summary: `layers ${conflict.layers.join(", ")} set different config values`
1725
+ }],
1726
+ fix: {
1727
+ kind: "edit-patch",
1728
+ summary: "keep one layer authoritative and remove or align the other configuration",
1729
+ safe: false,
1730
+ requiresConsent: true
1731
+ }
1732
+ }));
1733
+ const mcp = context.loaderEntries.filter((entry) => entry.source === "mcp" && typeof entry.mcpServerName === "string");
1734
+ const byServer = /* @__PURE__ */ new Map();
1735
+ for (const entry of mcp) {
1736
+ const name = entry.mcpServerName ?? "";
1737
+ const list = byServer.get(name) ?? [];
1738
+ list.push(entry);
1739
+ byServer.set(name, list);
1740
+ }
1741
+ for (const [serverName, list] of byServer) {
1742
+ if (list.length <= 1) continue;
1743
+ findings.push(makeFinding({
1744
+ domain: "plugin-plugin",
1745
+ code: "PP_MCP_SERVER_DUPLICATE",
1746
+ severity: "error",
1747
+ title: `MCP server name "${serverName}" is used more than once`,
1748
+ subjects: list.map((entry) => entry.moduleName),
1749
+ confidence: "high",
1750
+ evidence: [{
1751
+ source: "loader",
1752
+ ref: serverName,
1753
+ summary: "MCP tool names are mcp__<serverName>__<tool>; duplicate names collide"
1754
+ }],
1755
+ fix: {
1756
+ kind: "rename",
1757
+ summary: "give each MCP server a unique name or disable one entry",
1758
+ safe: false,
1759
+ requiresConsent: true
1760
+ }
1761
+ }));
1762
+ }
1763
+ for (const entry of mcp) {
1764
+ if (entry.fiberState !== "failed") continue;
1765
+ findings.push(makeFinding({
1766
+ domain: "plugin-plugin",
1767
+ code: "PP_MCP_STARTUP_FAILED",
1768
+ severity: "warn",
1769
+ title: `MCP server "${entry.mcpServerName ?? entry.id}" failed to start`,
1770
+ subjects: [entry.moduleName],
1771
+ confidence: "medium",
1772
+ evidence: [{
1773
+ source: "plugin-manager",
1774
+ ref: entry.id,
1775
+ summary: entry.diagnostic ?? "MCP fiber is in failed state"
1776
+ }],
1777
+ fix: {
1778
+ kind: "edit-patch",
1779
+ summary: "fix the MCP transport/command/network configuration",
1780
+ safe: false,
1781
+ requiresConsent: true
1782
+ }
1783
+ }));
1784
+ }
1785
+ for (const entry of context.loaderEntries) {
1786
+ if (entry.fiberState !== "failed" || entry.diagnostic === void 0) continue;
1787
+ if (!REGISTRATION_FAILURE_RE.test(entry.diagnostic)) continue;
1788
+ findings.push(makeFinding({
1789
+ domain: "plugin-plugin",
1790
+ code: "PP_RUNTIME_REGISTRATION_FAILED",
1791
+ severity: "error",
1792
+ title: `${entry.moduleName} failed while registering a tool, service, or prompt section`,
1793
+ subjects: [entry.moduleName],
1794
+ confidence: "high",
1795
+ evidence: [{
1796
+ source: "plugin-manager",
1797
+ ref: entry.id,
1798
+ summary: entry.diagnostic
1799
+ }],
1800
+ fix: {
1801
+ kind: "disable",
1802
+ summary: "inspect the diagnostic; disable one side of the registration conflict",
1803
+ safe: false,
1804
+ requiresConsent: true,
1805
+ target: entry.moduleName
1806
+ }
1807
+ }));
1808
+ }
1809
+ if (context.lockfile !== void 0) for (const duplicate of duplicateVersions(context.lockfile)) {
1810
+ if (duplicate.name.startsWith("@deepseek-ai/dsh")) continue;
1811
+ findings.push(makeFinding({
1812
+ domain: "plugin-plugin",
1813
+ code: "PP_PACKAGE_VERSION_DUPLICATE",
1814
+ severity: "warn",
1815
+ title: `multiple versions of ${duplicate.name} are installed`,
1816
+ subjects: [duplicate.name],
1817
+ confidence: "high",
1818
+ evidence: [{
1819
+ source: "lockfile",
1820
+ ref: context.lockfile.path,
1821
+ summary: duplicate.versions.join(", ")
1822
+ }],
1823
+ fix: {
1824
+ kind: "update",
1825
+ summary: "deduplicate with pnpm overrides or align the dependent plugins",
1826
+ safe: false,
1827
+ requiresConsent: true
1828
+ }
1829
+ }));
1830
+ }
1831
+ findings.push(...capabilityOverlap(enabledBundles));
1832
+ if (context.prompt !== void 0) findings.push(...promptOverlap(context));
1833
+ const knownModules = /* @__PURE__ */ new Set([
1834
+ ...context.bundles.flatMap((bundle) => bundle.rows.map((row) => rootPackageName(row.moduleName))),
1835
+ ...context.entriesInfo.map((entry) => rootPackageName(entry.moduleName)),
1836
+ ...context.manifests.keys()
1837
+ ]);
1838
+ for (const bundle of enabledBundles) {
1839
+ if (bundle.availability !== "profile") continue;
1840
+ const manifest = context.manifests.get(rootPackageName(bundle.name));
1841
+ if (manifest === void 0) continue;
1842
+ const bundleNames = new Set(context.bundles.map((item) => rootPackageName(item.name)));
1843
+ for (const [peer, range] of Object.entries(manifestPeers(manifest))) {
1844
+ if (peer === "@deepseek-ai/dsh") continue;
1845
+ if (!peer.startsWith("@deepseek-ai/dsh-")) continue;
1846
+ if (bundleNames.has(peer)) continue;
1847
+ if (knownModules.has(peer)) continue;
1848
+ findings.push(makeFinding({
1849
+ domain: "plugin-plugin",
1850
+ code: "PP_MISSING_PEER_BUNDLE",
1851
+ severity: "warn",
1852
+ title: `${bundle.name} expects peer ${peer} which is not in this profile`,
1853
+ subjects: [bundle.name, peer],
1854
+ confidence: "medium",
1855
+ evidence: [{
1856
+ source: "manifest",
1857
+ ref: `${bundle.name}@${bundle.version ?? "unknown"}`,
1858
+ summary: `peerDependencies ${peer}: ${range}`
1859
+ }],
1860
+ fix: {
1861
+ kind: "enable",
1862
+ summary: "install or select the peer bundle if the plugin needs it",
1863
+ safe: false,
1864
+ requiresConsent: true
1865
+ }
1866
+ }));
1867
+ }
1868
+ }
1869
+ return findings;
1870
+ }
1871
+ function detectServiceCycles(entries, providers) {
1872
+ const findings = [];
1873
+ const byId = /* @__PURE__ */ new Map();
1874
+ for (const entry of entries) byId.set(entry.id, entry);
1875
+ const edges = /* @__PURE__ */ new Map();
1876
+ for (const entry of entries) for (const service of entry.inject) for (const provider of providers.get(service) ?? []) {
1877
+ if (provider.id === entry.id) continue;
1878
+ const targets = edges.get(entry.id) ?? /* @__PURE__ */ new Set();
1879
+ targets.add(provider.id);
1880
+ edges.set(entry.id, targets);
1881
+ }
1882
+ const state = /* @__PURE__ */ new Map();
1883
+ const path = [];
1884
+ const seenCycles = /* @__PURE__ */ new Set();
1885
+ const visit = (id) => {
1886
+ if (findings.length > 20) return;
1887
+ const current = state.get(id);
1888
+ if (current === "visiting") {
1889
+ const start = path.indexOf(id);
1890
+ if (start < 0) return;
1891
+ const cycle = path.slice(start);
1892
+ if (cycle.length > 5) return;
1893
+ const key = [...cycle].sort().join("|");
1894
+ if (seenCycles.has(key)) return;
1895
+ seenCycles.add(key);
1896
+ const subjects = cycle.map((entryId) => byId.get(entryId)?.moduleName ?? entryId);
1897
+ findings.push(makeFinding({
1898
+ domain: "plugin-plugin",
1899
+ code: "PP_SERVICE_CYCLE",
1900
+ severity: "warn",
1901
+ title: "possible service dependency cycle detected",
1902
+ subjects,
1903
+ confidence: "low",
1904
+ evidence: [{
1905
+ source: "loader",
1906
+ ref: cycle.join(" -> "),
1907
+ summary: "plugins depend on services provided by each other"
1908
+ }],
1909
+ fix: {
1910
+ kind: "reorder",
1911
+ summary: "break the dependency cycle by reordering or disabling one plugin",
1912
+ safe: false,
1913
+ requiresConsent: true
1914
+ }
1915
+ }));
1916
+ return;
1917
+ }
1918
+ if (current === "done") return;
1919
+ state.set(id, "visiting");
1920
+ path.push(id);
1921
+ for (const target of edges.get(id) ?? []) visit(target);
1922
+ path.pop();
1923
+ state.set(id, "done");
1924
+ };
1925
+ for (const entry of entries) visit(entry.id);
1926
+ return findings;
1927
+ }
1928
+ function capabilityOverlap(bundles) {
1929
+ const findings = [];
1930
+ const withText = bundles.filter((bundle) => typeof bundle.description === "string" && bundle.description.length > 20).slice(0, 50);
1931
+ for (let i = 0; i < withText.length; i++) {
1932
+ const left = withText[i];
1933
+ if (left === void 0 || left.description === void 0) continue;
1934
+ const leftShingles = shingles(wordTokens(left.description), 3);
1935
+ for (let j = i + 1; j < withText.length; j++) {
1936
+ const right = withText[j];
1937
+ if (right === void 0 || right.description === void 0) continue;
1938
+ const similarity = jaccard(leftShingles, shingles(wordTokens(right.description), 3));
1939
+ if (similarity < .55) continue;
1940
+ findings.push(makeFinding({
1941
+ domain: "plugin-plugin",
1942
+ code: "PP_CAPABILITY_OVERLAP",
1943
+ severity: "info",
1944
+ title: `${left.name} and ${right.name} describe overlapping capabilities`,
1945
+ subjects: [left.name, right.name],
1946
+ confidence: "medium",
1947
+ evidence: [{
1948
+ source: "plugin-manager",
1949
+ ref: left.name,
1950
+ summary: `description similarity ${similarity.toFixed(2)}`
1951
+ }],
1952
+ fix: {
1953
+ kind: "none",
1954
+ summary: "review whether both bundles are needed for this task",
1955
+ safe: true,
1956
+ requiresConsent: false
1957
+ }
1958
+ }));
1959
+ }
1960
+ }
1961
+ return findings;
1962
+ }
1963
+ function promptOverlap(context) {
1964
+ const sections = [...context.prompt?.sections ?? [], ...context.prompt?.contexts ?? []];
1965
+ const paragraphs = [];
1966
+ for (const section of sections.slice(0, 200)) for (const text of splitParagraphs(section.text).slice(0, 20)) {
1967
+ const normalized = normalizeLine(text);
1968
+ if (normalized.length < 20) continue;
1969
+ paragraphs.push({
1970
+ section: section.name,
1971
+ text,
1972
+ normalized
1973
+ });
1974
+ }
1975
+ if (paragraphs.length === 0) return [];
1976
+ const findings = [];
1977
+ const byNormalized = /* @__PURE__ */ new Map();
1978
+ for (const paragraph of paragraphs) {
1979
+ const list = byNormalized.get(paragraph.normalized) ?? [];
1980
+ list.push(paragraph);
1981
+ byNormalized.set(paragraph.normalized, list);
1982
+ }
1983
+ for (const [, list] of byNormalized) {
1984
+ const sectionsInGroup = [...new Set(list.map((item) => item.section))];
1985
+ if (sectionsInGroup.length <= 1) continue;
1986
+ const conflict = hasConflictingNumbersOrNegation(list.map((item) => item.text));
1987
+ findings.push(makeFinding({
1988
+ domain: "plugin-plugin",
1989
+ code: "PP_PROMPT_OVERLAP",
1990
+ severity: conflict ? "warn" : "info",
1991
+ title: conflict ? "overlapping prompt rules contain conflicting values" : "duplicate prompt text appears in multiple sections",
1992
+ subjects: sectionsInGroup,
1993
+ confidence: "medium",
1994
+ evidence: [{
1995
+ source: "prompt",
1996
+ ref: sectionsInGroup.join(", "),
1997
+ summary: list[0]?.text.slice(0, 120) ?? ""
1998
+ }],
1999
+ fix: {
2000
+ kind: "none",
2001
+ summary: conflict ? "resolve the semantic conflict manually; do not auto-merge" : "keep one authoritative section and remove or reference the duplicate",
2002
+ safe: !conflict,
2003
+ requiresConsent: false
2004
+ }
2005
+ }));
2006
+ if (findings.length >= 20) break;
2007
+ }
2008
+ return findings;
2009
+ }
2010
+ function hasConflictingNumbersOrNegation(texts) {
2011
+ const negations = /\b(not|never|no|禁止|不得|不要|必须|always|must)\b/i;
2012
+ const numbers = /\d+/g;
2013
+ const first = texts[0] ?? "";
2014
+ const firstNumbers = new Set(first.match(numbers) ?? []);
2015
+ for (const text of texts.slice(1)) {
2016
+ const current = new Set(text.match(numbers) ?? []);
2017
+ if (firstNumbers.size !== current.size) return true;
2018
+ for (const value of firstNumbers) if (!current.has(value)) return true;
2019
+ if (negations.test(first) !== negations.test(text)) return true;
2020
+ }
2021
+ return false;
2022
+ }
2023
+ // src/compat/rules-profile.ts
2024
+ /** Profile/workspace consistency rules. */
2025
+ async function runProfileRules(context) {
2026
+ const findings = [];
2027
+ const profile = context.profile;
2028
+ const bundleCounts = /* @__PURE__ */ new Map();
2029
+ for (const bundle of profile.bundles) bundleCounts.set(bundle, (bundleCounts.get(bundle) ?? 0) + 1);
2030
+ for (const [bundle, count] of bundleCounts) {
2031
+ if (count <= 1) continue;
2032
+ findings.push(makeFinding({
2033
+ domain: "profile",
2034
+ code: "PW_DUPLICATE_BUNDLE",
2035
+ severity: "error",
2036
+ title: `bundle "${bundle}" is listed ${count} times in the profile`,
2037
+ subjects: [bundle, profile.name],
2038
+ confidence: "high",
2039
+ evidence: [{
2040
+ source: "profile-file",
2041
+ ref: `${profile.dir}/package.json`,
2042
+ summary: "dsh.profile.bundles contains a duplicate entry"
2043
+ }],
2044
+ fix: {
2045
+ kind: "edit-patch",
2046
+ summary: "remove the duplicate entry from dsh.profile.bundles",
2047
+ safe: false,
2048
+ requiresConsent: true
2049
+ }
2050
+ }));
2051
+ }
2052
+ const selected = new Set(profile.bundles);
2053
+ const declared = new Set(Object.keys(profile.dependencies));
2054
+ const installedNames = new Set(context.bundles.filter((bundle) => bundle.availability === "profile" || bundle.installed).map((bundle) => bundle.name));
2055
+ for (const name of declared) {
2056
+ if (selected.has(name)) continue;
2057
+ if (!installedNames.has(name)) continue;
2058
+ findings.push(makeFinding({
2059
+ domain: "profile",
2060
+ code: "PW_ORPHAN_BUNDLE",
2061
+ severity: "warn",
2062
+ title: `${name} is installed but not selected in this profile`,
2063
+ subjects: [name, profile.name],
2064
+ confidence: "high",
2065
+ evidence: [{
2066
+ source: "profile-file",
2067
+ ref: `${profile.dir}/package.json`,
2068
+ summary: "dependency exists but dsh.profile.bundles does not select it"
2069
+ }],
2070
+ fix: {
2071
+ kind: "enable",
2072
+ summary: "select the bundle if it is wanted, or remove the unused dependency",
2073
+ safe: false,
2074
+ requiresConsent: true
2075
+ }
2076
+ }));
2077
+ }
2078
+ for (const name of selected) {
2079
+ if (declared.has(name)) continue;
2080
+ if (name.startsWith("@deepseek-ai/dsh-")) continue;
2081
+ const info = context.bundles.find((bundle) => bundle.name === name);
2082
+ if (info?.official === true || info?.availability === "installation") continue;
2083
+ findings.push(makeFinding({
2084
+ domain: "profile",
2085
+ code: "PW_ORPHAN_BUNDLE",
2086
+ severity: "warn",
2087
+ title: `${name} is selected but not declared as a profile dependency`,
2088
+ subjects: [name, profile.name],
2089
+ confidence: "medium",
2090
+ evidence: [{
2091
+ source: "profile-file",
2092
+ ref: `${profile.dir}/package.json`,
2093
+ summary: "bundle is selected but absent from dependencies"
2094
+ }],
2095
+ fix: {
2096
+ kind: "edit-patch",
2097
+ summary: "declare the dependency or remove the selection",
2098
+ safe: false,
2099
+ requiresConsent: true
2100
+ }
2101
+ }));
2102
+ }
2103
+ const officialLayers = new Set(context.bundles.filter((bundle) => bundle.official || bundle.name.startsWith("@deepseek-ai/dsh-")).map((bundle) => bundle.name));
2104
+ const conflicts = findConfigConflicts(profile.patchRows, { skipLayer: (layer) => !context.config.compatStrictOfficialOverrides && officialLayers.has(layer) }).filter((conflict) => conflict.layers.includes("profile") && conflict.layers.some((layer) => layer !== "profile" && layer !== "home"));
2105
+ for (const conflict of conflicts) findings.push(makeFinding({
2106
+ domain: "profile",
2107
+ code: "PW_PATCH_CONFLICT",
2108
+ severity: "warn",
2109
+ title: `profile patch overrides row "${conflict.id}" with a different configuration`,
2110
+ subjects: [conflict.id, profile.name],
2111
+ confidence: "medium",
2112
+ evidence: [{
2113
+ source: "profile-file",
2114
+ ref: `${profile.dir}/cordis.patch.yml`,
2115
+ summary: `layers ${conflict.layers.join(", ")} set different config values`
2116
+ }],
2117
+ fix: {
2118
+ kind: "edit-patch",
2119
+ summary: "confirm the override is intentional; align or remove one configuration",
2120
+ safe: false,
2121
+ requiresConsent: true
2122
+ }
2123
+ }));
2124
+ findings.push(...profileDrift(context));
2125
+ for (const warning of profile.compatibilityWarnings) findings.push(makeFinding({
2126
+ domain: "profile",
2127
+ code: "PW_COMPAT_FILE_INVALID",
2128
+ severity: "warn",
2129
+ title: "compatibility.json contains records the reader rejected",
2130
+ subjects: [profile.name],
2131
+ confidence: "high",
2132
+ evidence: [{
2133
+ source: "profile-file",
2134
+ ref: "compatibility.json",
2135
+ summary: warning
2136
+ }],
2137
+ fix: {
2138
+ kind: "edit-patch",
2139
+ summary: "repair or remove the rejected records before changing exemptions",
2140
+ safe: false,
2141
+ requiresConsent: true
2142
+ }
2143
+ }));
2144
+ if (context.config.compatReadWorkspace && context.prompt !== void 0) findings.push(...workspaceOverlap(context));
2145
+ return findings;
2146
+ }
2147
+ function profileDrift(context) {
2148
+ const findings = [];
2149
+ const profiles = context.profiles;
2150
+ if (profiles.length <= 1) return findings;
2151
+ const allBundles = /* @__PURE__ */ new Set();
2152
+ for (const profile of profiles) for (const bundle of profile.bundles) allBundles.add(bundle);
2153
+ for (const bundle of allBundles) {
2154
+ const present = profiles.filter((profile) => profile.bundles.includes(bundle)).map((profile) => profile.name);
2155
+ if (present.length === profiles.length) continue;
2156
+ findings.push(makeFinding({
2157
+ domain: "profile",
2158
+ code: "PW_BUNDLE_DRIFT",
2159
+ severity: "info",
2160
+ title: `${bundle} is selected in only some profiles`,
2161
+ subjects: [bundle, ...present],
2162
+ confidence: "high",
2163
+ evidence: [{
2164
+ source: "profile-file",
2165
+ ref: bundle,
2166
+ summary: `present in ${present.join(", ") || "none"}; missing elsewhere`
2167
+ }],
2168
+ fix: {
2169
+ kind: "none",
2170
+ summary: "align the profiles only if the difference is unintended",
2171
+ safe: true,
2172
+ requiresConsent: false
2173
+ }
2174
+ }));
2175
+ }
2176
+ const versions = /* @__PURE__ */ new Map();
2177
+ for (const profile of profiles) for (const [bundle, version] of Object.entries(profile.manifestVersions)) {
2178
+ if (version === void 0) continue;
2179
+ const set = versions.get(bundle) ?? /* @__PURE__ */ new Set();
2180
+ set.add(version);
2181
+ versions.set(bundle, set);
2182
+ }
2183
+ for (const [bundle, set] of versions) {
2184
+ if (set.size <= 1) continue;
2185
+ findings.push(makeFinding({
2186
+ domain: "profile",
2187
+ code: "PW_VERSION_DRIFT",
2188
+ severity: "warn",
2189
+ title: `${bundle} has different versions across profiles`,
2190
+ subjects: [bundle, ...profiles.map((profile) => profile.name)],
2191
+ confidence: "medium",
2192
+ evidence: [{
2193
+ source: "manifest",
2194
+ ref: bundle,
2195
+ summary: [...set].join(", ")
2196
+ }],
2197
+ fix: {
2198
+ kind: "update",
2199
+ summary: "align the versions if the profiles should behave the same",
2200
+ safe: false,
2201
+ requiresConsent: true
2202
+ }
2203
+ }));
2204
+ }
2205
+ const exemptionKeys = /* @__PURE__ */ new Set();
2206
+ for (const profile of profiles) for (const key of Object.keys(profile.exemptions)) exemptionKeys.add(key);
2207
+ for (const key of exemptionKeys) {
2208
+ const values = /* @__PURE__ */ new Set();
2209
+ for (const profile of profiles) values.add(JSON.stringify(profile.exemptions[key] ?? []));
2210
+ if (values.size <= 1) continue;
2211
+ findings.push(makeFinding({
2212
+ domain: "profile",
2213
+ code: "PW_EXEMPTION_DRIFT",
2214
+ severity: "warn",
2215
+ title: `version exemption "${key}" differs across profiles`,
2216
+ subjects: [key, ...profiles.map((profile) => profile.name)],
2217
+ confidence: "medium",
2218
+ evidence: [{
2219
+ source: "profile-file",
2220
+ ref: "compatibility.json",
2221
+ summary: profiles.map((profile) => `${profile.name}: ${JSON.stringify(profile.exemptions[key] ?? [])}`).join("; ")
2222
+ }],
2223
+ fix: {
2224
+ kind: "edit-patch",
2225
+ summary: "align or intentionally separate the exemption per profile",
2226
+ safe: false,
2227
+ requiresConsent: true
2228
+ }
2229
+ }));
2230
+ }
2231
+ return findings;
2232
+ }
2233
+ function workspaceOverlap(context) {
2234
+ const findings = [];
2235
+ const sections = [...context.prompt?.sections ?? [], ...context.prompt?.contexts ?? []];
2236
+ const pluginParagraphs = [];
2237
+ for (const section of sections.slice(0, 200)) for (const paragraph of splitParagraphs(section.text).slice(0, 10)) {
2238
+ const normalized = normalizeLine(paragraph);
2239
+ if (normalized.length < 30) continue;
2240
+ pluginParagraphs.push({
2241
+ section: section.name,
2242
+ normalized,
2243
+ shingles: shingles(wordTokens(paragraph), 3)
2244
+ });
2245
+ }
2246
+ if (pluginParagraphs.length === 0) return findings;
2247
+ for (const instruction of context.workspace.instructions.slice(0, 10)) for (const paragraph of splitParagraphs(instruction.text).slice(0, 40)) {
2248
+ const normalized = normalizeLine(paragraph);
2249
+ if (normalized.length < 30) continue;
2250
+ const instructionShingles = shingles(wordTokens(paragraph), 3);
2251
+ for (const pluginParagraph of pluginParagraphs) {
2252
+ const similarity = normalized === pluginParagraph.normalized ? 1 : jaccard(instructionShingles, pluginParagraph.shingles);
2253
+ if (similarity < .8) continue;
2254
+ findings.push(makeFinding({
2255
+ domain: "workspace",
2256
+ code: "PW_WORKSPACE_RULE_OVERLAP",
2257
+ severity: "info",
2258
+ title: "workspace instruction overlaps a plugin prompt section",
2259
+ subjects: [instruction.file, pluginParagraph.section],
2260
+ confidence: "low",
2261
+ evidence: [{
2262
+ source: "prompt",
2263
+ ref: `${instruction.file} ↔ ${pluginParagraph.section}`,
2264
+ summary: `similarity ${similarity.toFixed(2)}`
2265
+ }],
2266
+ fix: {
2267
+ kind: "none",
2268
+ summary: "keep one authoritative rule source if the overlap is intentional",
2269
+ safe: true,
2270
+ requiresConsent: false
2271
+ }
2272
+ }));
2273
+ if (findings.length >= 20) return findings;
2274
+ }
2275
+ }
2276
+ return findings;
2277
+ }
2278
+ // src/compat/report.ts
2279
+ /** Run every compatibility rule against one collected context. */
2280
+ async function runCompatibilityRules(context) {
2281
+ const [runtime, plugin, profile] = await Promise.all([
2282
+ runRuntimeRules(context),
2283
+ runPluginRules(context),
2284
+ runProfileRules(context)
2285
+ ]);
2286
+ return sortFindings(dedupeFindings([
2287
+ ...runtime,
2288
+ ...plugin,
2289
+ ...profile
2290
+ ]));
2291
+ }
2292
+ /** Build the serializable report. */
2293
+ function buildReport(context, findings, options) {
2294
+ const sorted = sortFindings(findings);
2295
+ const selected = sorted.slice(0, options.maxFindings);
2296
+ const byDomain = {
2297
+ "plugin-plugin": 0,
2298
+ "plugin-runtime": 0,
2299
+ profile: 0,
2300
+ workspace: 0
2301
+ };
2302
+ let error = 0;
2303
+ let warn = 0;
2304
+ let info = 0;
2305
+ for (const finding of sorted) {
2306
+ byDomain[finding.domain] += 1;
2307
+ if (finding.severity === "error") error++;
2308
+ else if (finding.severity === "warn") warn++;
2309
+ else info++;
2310
+ }
2311
+ return {
2312
+ schemaVersion: 1,
2313
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2314
+ runtime: { ...context.runtime },
2315
+ profile: {
2316
+ name: context.profile.name,
2317
+ dir: context.profile.dir,
2318
+ bundles: [...context.profile.bundles]
2319
+ },
2320
+ findings: selected,
2321
+ summary: {
2322
+ error,
2323
+ warn,
2324
+ info,
2325
+ byDomain
2326
+ },
2327
+ profiles: context.profiles.map((profile) => ({
2328
+ name: profile.name,
2329
+ dir: profile.dir,
2330
+ bundles: [...profile.bundles],
2331
+ versions: { ...profile.manifestVersions },
2332
+ exemptions: { ...profile.exemptions },
2333
+ compatibilityWarnings: [...profile.compatibilityWarnings],
2334
+ findings: []
2335
+ })),
2336
+ workspaces: [{
2337
+ cwd: context.workspace.cwd,
2338
+ instructionFiles: [...context.workspace.instructionFiles],
2339
+ mcpEntries: context.loaderEntries.filter((entry) => entry.source === "mcp" && typeof entry.mcpServerName === "string").map((entry) => entry.mcpServerName),
2340
+ findings: []
2341
+ }],
2342
+ diagnostics: [...context.diagnostics],
2343
+ truncated: sorted.length > selected.length,
2344
+ totalFindings: sorted.length
2345
+ };
2346
+ }
2347
+ const SEVERITY_LABEL = {
2348
+ error: "E",
2349
+ warn: "W",
2350
+ info: "I"
2351
+ };
2352
+ /** Render a bounded Markdown matrix plus detailed findings. */
2353
+ function renderReport(report, options) {
2354
+ const lines = [];
2355
+ lines.push("# 兼容性报告");
2356
+ lines.push("");
2357
+ lines.push(`- 运行时:DSH ${report.runtime.dshVersion} / Node ${report.runtime.nodeVersion} / ${report.runtime.platform}-${report.runtime.arch}`);
2358
+ lines.push(`- Profile:${report.profile.name}(${report.profile.bundles.length} 个 bundle)`);
2359
+ lines.push(`- 发现:${report.summary.error} error / ${report.summary.warn} warn / ${report.summary.info} info${report.truncated ? `(已截断,共 ${report.totalFindings ?? report.findings.length} 条)` : ""}`);
2360
+ lines.push("");
2361
+ const visible = report.findings.filter((finding) => options.includeInfo || finding.severity !== "info");
2362
+ if (visible.length === 0) lines.push("未发现需要处理的兼容性问题。");
2363
+ else {
2364
+ lines.push("## 兼容性矩阵");
2365
+ lines.push("");
2366
+ lines.push("| 主体 | 运行时 | 插件间 | Profile/工作区 |");
2367
+ lines.push("|---|---|---|---|");
2368
+ const subjects = [...new Set(visible.flatMap((finding) => finding.subjects))].sort((a, b) => a.localeCompare(b)).slice(0, 30);
2369
+ for (const subject of subjects) {
2370
+ const row = [escapeMarkdownCell(subject)];
2371
+ for (const domain of [
2372
+ "plugin-runtime",
2373
+ "plugin-plugin",
2374
+ "profile"
2375
+ ]) {
2376
+ const matches = visible.filter((finding) => finding.domain === domain && finding.subjects.includes(subject));
2377
+ row.push(matches.length === 0 ? "—" : matches.slice(0, 2).map((finding) => `${SEVERITY_LABEL[finding.severity]}:${finding.code}`).join("<br>"));
2378
+ }
2379
+ lines.push(`| ${row.join(" | ")} |`);
2380
+ }
2381
+ lines.push("");
2382
+ lines.push("图例:E=error,W=warn,I=info,—=无发现。");
2383
+ lines.push("");
2384
+ lines.push("## 详细发现");
2385
+ lines.push("");
2386
+ for (const finding of visible) {
2387
+ lines.push(`### ${SEVERITY_LABEL[finding.severity]} ${finding.code} · ${finding.title}`);
2388
+ lines.push("");
2389
+ lines.push(`- 领域:${finding.domain}`);
2390
+ lines.push(`- 主体:${finding.subjects.join(", ")}`);
2391
+ lines.push(`- 置信度:${finding.confidence}`);
2392
+ for (const evidence of finding.evidence) lines.push(`- 证据(${evidence.source}${evidence.ref === void 0 ? "" : ` · ${evidence.ref}`}):${evidence.summary}`);
2393
+ if (finding.fix !== void 0) lines.push(`- 修复建议:${finding.fix.summary}${finding.fix.requiresConsent ? "(需要用户确认)" : ""}`);
2394
+ lines.push("");
2395
+ }
2396
+ }
2397
+ const lowConfidence = [...new Set(report.findings.filter((finding) => finding.confidence === "low").flatMap((finding) => finding.subjects))];
2398
+ if (lowConfidence.length > 0) {
2399
+ lines.push("## 低置信度发现(需人工确认)");
2400
+ lines.push("");
2401
+ for (const item of lowConfidence.slice(0, 20)) lines.push(`- ${item}`);
2402
+ lines.push("");
2403
+ }
2404
+ if (report.diagnostics.length > 0) {
2405
+ lines.push("## 未完成的分析");
2406
+ lines.push("");
2407
+ for (const diagnostic of report.diagnostics.slice(0, 20)) lines.push(`- ${diagnostic}`);
2408
+ lines.push("");
2409
+ }
2410
+ lines.push("## 机器可读摘要");
2411
+ lines.push("");
2412
+ lines.push(jsonBlock({
2413
+ summary: report.summary,
2414
+ findings: visible.map((finding) => ({
2415
+ code: finding.code,
2416
+ severity: finding.severity,
2417
+ domain: finding.domain,
2418
+ subjects: finding.subjects,
2419
+ confidence: finding.confidence,
2420
+ fix: finding.fix
2421
+ }))
2422
+ }, 8e3));
2423
+ return lines.join("\n");
2424
+ }
2425
+ // src/compat/analyze.ts
2426
+ const cache = /* @__PURE__ */ new Map();
2427
+ /** Collect, analyze, render, and optionally persist a compatibility report. */
2428
+ async function analyzeCompatibility(ctx, config, options = {}) {
2429
+ const facts = resolveProfileFacts(ctx, options.agent);
2430
+ const scope = options.scope ?? "current";
2431
+ const agentKey = agentId(options.agent);
2432
+ const includeInfo = options.includeInfo ?? config.compatIncludeInfo;
2433
+ const maxFindings = clampInteger(options.maxFindings ?? config.compatMaxFindings, 1, 500);
2434
+ const key = `${facts.dir}|${scope}|${agentKey}|${includeInfo ? 1 : 0}|${maxFindings}`;
2435
+ const ttl = Math.max(0, config.compatCacheTtlMs);
2436
+ const cached = cache.get(key);
2437
+ if (options.force !== true && cached !== void 0 && Date.now() - cached.at < ttl) {
2438
+ if (options.writeReport !== false && (cached.result.reportPath === void 0 || !await fileExists(cached.result.reportPath))) {
2439
+ const path = dataDir("compat", "report.json");
2440
+ await writeJsonAtomic(path, cached.result.report).catch(() => void 0);
2441
+ const updated = {
2442
+ ...cached.result,
2443
+ reportPath: path
2444
+ };
2445
+ cache.set(key, {
2446
+ at: Date.now(),
2447
+ result: updated
2448
+ });
2449
+ return updated;
2450
+ }
2451
+ return cached.result;
2452
+ }
2453
+ const scopedConfig = {
2454
+ ...toCompatConfig(config),
2455
+ compatScanAllProfiles: scope === "profiles" || scope === "all",
2456
+ compatReadWorkspace: scope !== "profiles"
2457
+ };
2458
+ const context = await collectCompatContext({
2459
+ profileName: facts.name,
2460
+ profileDir: facts.dir,
2461
+ dshHome: facts.dshHome,
2462
+ cwd: facts.cwd,
2463
+ loader: getLoader(ctx),
2464
+ pluginManager: getPluginManager(ctx),
2465
+ inventory: getInventory(ctx),
2466
+ prompt: getPromptAdapter(ctx, options.agent),
2467
+ agent: options.agent,
2468
+ toolSet: options.toolSet,
2469
+ config: scopedConfig
2470
+ });
2471
+ const findings = config.compatEnabled ? await runCompatibilityRules(context) : [];
2472
+ if (!config.compatEnabled) context.diagnostics.push("compatibility analysis is disabled by config");
2473
+ const report = buildReport(context, findings, {
2474
+ includeInfo,
2475
+ maxFindings
2476
+ });
2477
+ const markdown = renderReport(report, {
2478
+ includeInfo,
2479
+ maxFindings
2480
+ });
2481
+ let reportPath;
2482
+ if (options.writeReport !== false) {
2483
+ reportPath = dataDir("compat", "report.json");
2484
+ await writeJsonAtomic(reportPath, report).catch((error) => {
2485
+ context.diagnostics.push(`failed to write compatibility report: ${errorText(error)}`);
2486
+ });
2487
+ }
2488
+ await new AuditLog().append({
2489
+ t: (/* @__PURE__ */ new Date()).toISOString(),
2490
+ actor: "trim",
2491
+ action: "analyze_compatibility",
2492
+ subject: facts.name,
2493
+ result: report.summary.error > 0 ? "fail" : "ok",
2494
+ summary: `${report.summary.error} error / ${report.summary.warn} warn / ${report.summary.info} info`,
2495
+ metrics: {
2496
+ error: report.summary.error,
2497
+ warn: report.summary.warn,
2498
+ info: report.summary.info,
2499
+ findings: report.findings.length
2500
+ }
2501
+ }).catch(() => void 0);
2502
+ const result = {
2503
+ report,
2504
+ findings,
2505
+ context,
2506
+ markdown,
2507
+ reportPath
2508
+ };
2509
+ cache.set(key, {
2510
+ at: Date.now(),
2511
+ result
2512
+ });
2513
+ return result;
2514
+ }
2515
+ function agentId(agent) {
2516
+ if (typeof agent !== "object" || agent === null) return "";
2517
+ const id = agent.id;
2518
+ return typeof id === "string" ? id : "";
2519
+ }
2520
+ function clampInteger(value, min, max) {
2521
+ if (!Number.isFinite(value)) return min;
2522
+ return Math.min(max, Math.max(min, Math.trunc(value)));
2523
+ }
2524
+ function errorText(error) {
2525
+ return error instanceof Error ? error.message : String(error);
2526
+ }
2527
+ // src/score.ts
2528
+ const WEIGHTS = {
2529
+ taskMatch: .35,
2530
+ usage: .25,
2531
+ overlapPenalty: .2,
2532
+ costPenalty: .15
2533
+ };
2534
+ /** Names of enabled bundles whose descriptions substantially overlap another enabled bundle. */
2535
+ function computeOverlapSet(scan) {
2536
+ const bundles = scan.bundles.filter((bundle) => bundle.enabled && typeof bundle.description === "string" && bundle.description.length > 20);
2537
+ const overlap = /* @__PURE__ */ new Set();
2538
+ for (let i = 0; i < bundles.length; i++) {
2539
+ const left = bundles[i];
2540
+ if (left?.description === void 0) continue;
2541
+ const leftShingles = shingles(wordTokens(left.description), 3);
2542
+ for (let j = i + 1; j < bundles.length; j++) {
2543
+ const right = bundles[j];
2544
+ if (right?.description === void 0) continue;
2545
+ if (jaccard(leftShingles, shingles(wordTokens(right.description), 3)) < .55) continue;
2546
+ overlap.add(left.name);
2547
+ overlap.add(right.name);
2548
+ }
2549
+ }
2550
+ return overlap;
2551
+ }
2552
+ function scoreBundle(scan, task, bundle, overlap) {
2553
+ return scoreCommon({
2554
+ scan,
2555
+ task,
2556
+ overlap,
2557
+ id: `bundle:${bundle.name}`,
2558
+ kind: "bundle",
2559
+ name: bundle.name,
2560
+ bundleName: bundle.name,
2561
+ enabled: bundle.enabled,
2562
+ protectedItem: bundle.protected,
2563
+ guardStatus: bundle.guardStatus,
2564
+ contextTokens: bundle.contextTokens,
2565
+ usageCalls: bundle.usage.calls,
2566
+ usageSuccesses: bundle.usage.successes,
2567
+ usageSessionCalls: bundle.usage.sessionCalls,
2568
+ description: bundle.description,
2569
+ findings: bundle.findings
2570
+ });
2571
+ }
2572
+ function scoreEntry(scan, task, entry, overlap) {
2573
+ const parent = scan.bundles.find((bundle) => bundle.name === entry.bundleName);
2574
+ return scoreCommon({
2575
+ scan,
2576
+ task,
2577
+ overlap,
2578
+ id: `entry:${entry.entryId}`,
2579
+ kind: "entry",
2580
+ name: entry.entryId,
2581
+ bundleName: entry.bundleName,
2582
+ enabled: entry.enabled,
2583
+ protectedItem: entry.protected || parent?.protected === true || entry.patchId === void 0,
2584
+ guardStatus: entry.guardStatus,
2585
+ contextTokens: entry.contextTokens,
2586
+ usageCalls: entry.usage.calls,
2587
+ usageSuccesses: entry.usage.successes,
2588
+ usageSessionCalls: entry.usage.sessionCalls,
2589
+ description: parent?.description,
2590
+ findings: entry.findings,
2591
+ moduleName: entry.moduleName,
2592
+ fiberPhase: entry.fiberPhase
2593
+ });
2594
+ }
2595
+ function scoreCommon(input) {
2596
+ const evidence = [];
2597
+ if (input.protectedItem) return {
2598
+ id: input.id,
2599
+ kind: input.kind,
2600
+ name: input.name,
2601
+ bundleName: input.bundleName,
2602
+ action: "keep",
2603
+ risk: "low",
2604
+ score: 1,
2605
+ evidence: [{
2606
+ kind: "user-pref",
2607
+ summary: "核心/管理/preset/用户锁定项,受保护",
2608
+ weight: 1
2609
+ }],
2610
+ observedEnabled: input.enabled,
2611
+ protected: true,
2612
+ reason: "受保护项不参与裁剪",
2613
+ findings: []
2614
+ };
2615
+ if (input.guardStatus === "incompatible") return {
2616
+ id: input.id,
2617
+ kind: input.kind,
2618
+ name: input.name,
2619
+ bundleName: input.bundleName,
2620
+ action: "review",
2621
+ risk: "high",
2622
+ score: -1,
2623
+ evidence: [{
2624
+ kind: "guard",
2625
+ summary: "运行时不兼容或启动失败;不自动启用/禁用",
2626
+ weight: 1
2627
+ }, ...compatEvidence(input.findings)],
2628
+ observedEnabled: input.enabled,
2629
+ protected: false,
2630
+ reason: "先处理兼容性 error,再考虑启用或禁用",
2631
+ findings: []
2632
+ };
2633
+ const text = `${input.name} ${input.description ?? ""} ${input.moduleName ?? ""}`.toLowerCase();
2634
+ const matched = input.task.tag === "unknown" ? [] : input.task.keywords.filter((keyword) => text.includes(keyword));
2635
+ const taskMatch = clamp(matched.length * .4, 0, 1);
2636
+ if (matched.length > 0) evidence.push({
2637
+ kind: "task-match",
2638
+ summary: `匹配任务关键词:${matched.slice(0, 5).join("、")}`,
2639
+ weight: WEIGHTS.taskMatch * taskMatch
2640
+ });
2641
+ const successRate = input.usageCalls > 0 ? input.usageSuccesses / input.usageCalls : .5;
2642
+ const historical = Math.min(1, input.usageCalls / 20) * successRate;
2643
+ const session = Math.min(1, input.usageSessionCalls / 5) * .8;
2644
+ const usage = Math.max(historical, session);
2645
+ if (input.usageCalls > 0 || input.usageSessionCalls > 0) evidence.push({
2646
+ kind: "usage",
2647
+ summary: `历史调用 ${input.usageCalls},会话内 ${input.usageSessionCalls},成功率 ${round(successRate, 2)}`,
2648
+ weight: WEIGHTS.usage * usage
2649
+ });
2650
+ else evidence.push({
2651
+ kind: "usage",
2652
+ summary: "没有可用使用记录",
2653
+ weight: 0
2654
+ });
2655
+ const overlap = input.overlap.has(input.name) || input.bundleName !== void 0 && input.overlap.has(input.bundleName);
2656
+ if (overlap) evidence.push({
2657
+ kind: "overlap",
2658
+ summary: "描述/能力与其他插件重叠",
2659
+ weight: -WEIGHTS.overlapPenalty
2660
+ });
2661
+ const cost = Math.min(1, input.contextTokens / 4e3);
2662
+ if (input.contextTokens > 0) evidence.push({
2663
+ kind: "cost",
2664
+ summary: `可归属上下文约 ${input.contextTokens} tokens`,
2665
+ weight: -WEIGHTS.costPenalty * cost
2666
+ });
2667
+ else evidence.push({
2668
+ kind: "cost",
2669
+ summary: "没有可归属的 host 上下文成本",
2670
+ weight: 0
2671
+ });
2672
+ for (const finding of input.findings.slice(0, 4)) evidence.push({
2673
+ kind: "compat",
2674
+ summary: `${finding.code}: ${finding.title}`,
2675
+ weight: finding.severity === "error" ? .5 : .2
2676
+ });
2677
+ let score = WEIGHTS.taskMatch * taskMatch + WEIGHTS.usage * usage - WEIGHTS.overlapPenalty * (overlap ? 1 : 0) - WEIGHTS.costPenalty * cost;
2678
+ score = round(clamp(score, -1, 1), 3);
2679
+ let action;
2680
+ const hasError = input.findings.some((finding) => finding.severity === "error");
2681
+ if (input.enabled) {
2682
+ if (taskMatch >= .8 && !hasError) action = "keep";
2683
+ else if (score >= .5) action = "keep";
2684
+ else if (score >= .25) action = "disable-if-unused";
2685
+ else if (score >= .05) action = "review";
2686
+ else action = "suggest-disable";
2687
+ } else {
2688
+ const enableScore = taskMatch * .8 + usage * .2;
2689
+ action = taskMatch > 0 && enableScore >= .6 ? "enable" : "review";
2690
+ }
2691
+ let risk = "low";
2692
+ if (input.task.confidence < .6) risk = "high";
2693
+ else if (hasError) risk = "medium";
2694
+ else if (input.guardStatus === "warn") risk = "medium";
2695
+ else if (input.fiberPhase === "pending" || input.fiberPhase === "failed") risk = "medium";
2696
+ if (action === "suggest-disable" && risk !== "low") action = "review";
2697
+ if (action === "enable" && risk === "high") action = "review";
2698
+ if (action === "enable" && hasError) action = "review";
2699
+ if (input.task.tag === "unknown" && action === "suggest-disable") action = "review";
2700
+ if (input.task.confidence < .6 && action === "suggest-disable") action = "review";
2701
+ return {
2702
+ id: input.id,
2703
+ kind: input.kind,
2704
+ name: input.name,
2705
+ bundleName: input.bundleName,
2706
+ action,
2707
+ risk,
2708
+ score,
2709
+ evidence,
2710
+ observedEnabled: input.enabled,
2711
+ protected: false,
2712
+ reason: reasonFor(action, input, taskMatch, usage, cost),
2713
+ findings: []
2714
+ };
2715
+ }
2716
+ function compatEvidence(findings) {
2717
+ return findings.slice(0, 4).map((finding) => ({
2718
+ kind: "compat",
2719
+ summary: `${finding.code}: ${finding.title}`,
2720
+ weight: .5
2721
+ }));
2722
+ }
2723
+ function reasonFor(action, input, taskMatch, usage, cost) {
2724
+ switch (action) {
2725
+ case "keep": return `任务匹配 ${round(taskMatch, 2)}、使用 ${round(usage, 2)}、成本 ${round(cost, 2)},收益可覆盖成本`;
2726
+ case "enable": return "已禁用但与当前任务强相关;可在确认后启用";
2727
+ case "suggest-disable": return `任务匹配低、使用 ${round(usage, 2)}、成本 ${round(cost, 2)},建议临时禁用`;
2728
+ case "disable-if-unused": return "边际收益偏低;若本任务未使用可禁用";
2729
+ default: return input.task.confidence < .6 ? "任务识别置信度不足,只建议人工复核" : "证据不足或存在兼容性风险,建议人工复核";
2730
+ }
2731
+ }
2732
+ // src/draft.ts
2733
+ /** Build a local, reversible slim-profile draft. Does not change plugin state. */
2734
+ function buildSlimProfile(scan, task, config, options = {}) {
2735
+ const overlap = computeOverlapSet(scan);
2736
+ const items = [];
2737
+ for (const bundle of scan.bundles) {
2738
+ if (!bundle.enabled && bundle.availability === "missing") continue;
2739
+ items.push(scoreBundle(scan, task, bundle, overlap));
2740
+ }
2741
+ for (const entry of scan.entries) {
2742
+ if (entry.bundleName === void 0 || entry.patchId === void 0) continue;
2743
+ items.push(scoreEntry(scan, task, entry, overlap));
2744
+ }
2745
+ const bundleDisables = new Set(items.filter((item) => item.kind === "bundle" && item.action === "suggest-disable").map((item) => item.bundleName).filter((name) => name !== void 0));
2746
+ let filtered = items.filter((item) => !(item.kind === "entry" && item.bundleName !== void 0 && bundleDisables.has(item.bundleName)));
2747
+ if (options.includeReview === false) filtered = filtered.filter((item) => item.action !== "review");
2748
+ const maxDisable = Math.max(0, options.maxDisable ?? 20);
2749
+ let disableCount = 0;
2750
+ filtered = filtered.filter((item) => {
2751
+ if (item.action !== "suggest-disable") return true;
2752
+ disableCount++;
2753
+ return disableCount <= maxDisable;
2754
+ });
2755
+ filtered.sort(compareItems);
2756
+ const summary = {
2757
+ keep: filtered.filter((item) => item.action === "keep").length,
2758
+ enable: filtered.filter((item) => item.action === "enable").length,
2759
+ disable: filtered.filter((item) => item.action === "suggest-disable").length,
2760
+ review: filtered.filter((item) => item.action === "review").length,
2761
+ protected: filtered.filter((item) => item.protected).length
2762
+ };
2763
+ return {
2764
+ schemaVersion: 1,
2765
+ id: newId("slim"),
2766
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2767
+ task,
2768
+ mode: options.mode ?? config.mode,
2769
+ items: filtered,
2770
+ dedupe: scan.dedupe,
2771
+ summary,
2772
+ status: "draft"
2773
+ };
2774
+ }
2775
+ /** Items eligible for apply: low-risk disables/enables and not protected. */
2776
+ function applicableItems(profile) {
2777
+ return profile.items.filter((item) => item.protected === false && item.risk === "low" && (item.action === "suggest-disable" || item.action === "enable"));
2778
+ }
2779
+ const ACTION_RANK = {
2780
+ "suggest-disable": 0,
2781
+ enable: 1,
2782
+ review: 2,
2783
+ "disable-if-unused": 3,
2784
+ keep: 4
2785
+ };
2786
+ function compareItems(a, b) {
2787
+ const action = ACTION_RANK[a.action] - ACTION_RANK[b.action];
2788
+ if (action !== 0) return action;
2789
+ const risk = riskRank(a.risk) - riskRank(b.risk);
2790
+ if (risk !== 0) return risk;
2791
+ return a.name.localeCompare(b.name);
2792
+ }
2793
+ function riskRank(risk) {
2794
+ return risk === "low" ? 0 : risk === "medium" ? 1 : 2;
2795
+ }
2796
+ /** Keep the compat findings attached to an item for rendering. */
2797
+ function attachFindings(profile, scan) {
2798
+ const byId = new Map(scan.bundles.map((bundle) => [`bundle:${bundle.name}`, bundle.findings]));
2799
+ for (const entry of scan.entries) byId.set(`entry:${entry.entryId}`, entry.findings);
2800
+ return {
2801
+ ...profile,
2802
+ items: profile.items.map((item) => ({
2803
+ ...item,
2804
+ findings: sortFindings(byId.get(item.id) ?? [])
2805
+ }))
2806
+ };
2807
+ }
2808
+ // src/task.ts
2809
+ const TASK_KEYWORDS = {
2810
+ bugfix: [
2811
+ "bug",
2812
+ "fix",
2813
+ "修复",
2814
+ "报错",
2815
+ "错误",
2816
+ "崩溃",
2817
+ "debug",
2818
+ "调试",
2819
+ "失败",
2820
+ "failing",
2821
+ "regression",
2822
+ "异常",
2823
+ "问题",
2824
+ "排查",
2825
+ "crash"
2826
+ ],
2827
+ feature: [
2828
+ "实现",
2829
+ "新增",
2830
+ "开发",
2831
+ "feature",
2832
+ "implement",
2833
+ "add",
2834
+ "重构",
2835
+ "refactor",
2836
+ "迁移",
2837
+ "migrate",
2838
+ "支持",
2839
+ "设计",
2840
+ "build",
2841
+ "create",
2842
+ "编写"
2843
+ ],
2844
+ review: [
2845
+ "审查",
2846
+ "review",
2847
+ "代码审查",
2848
+ "pr",
2849
+ "合并",
2850
+ "merge",
2851
+ "diff",
2852
+ "评审",
2853
+ "检查代码",
2854
+ "code review"
2855
+ ],
2856
+ docs: [
2857
+ "文档",
2858
+ "docs",
2859
+ "documentation",
2860
+ "说明",
2861
+ "readme",
2862
+ "注释",
2863
+ "写文档",
2864
+ "注释",
2865
+ "guide",
2866
+ "教程"
2867
+ ],
2868
+ release: [
2869
+ "发布",
2870
+ "release",
2871
+ "版本",
2872
+ "version",
2873
+ "changelog",
2874
+ "打包",
2875
+ "publish",
2876
+ "发版",
2877
+ "上线",
2878
+ "部署"
2879
+ ],
2880
+ report: [
2881
+ "周报",
2882
+ "日报",
2883
+ "报告",
2884
+ "report",
2885
+ "总结",
2886
+ "summarize",
2887
+ "汇总",
2888
+ "周会",
2889
+ "月报",
2890
+ "汇报",
2891
+ "简报"
2892
+ ],
2893
+ research: [
2894
+ "调研",
2895
+ "research",
2896
+ "搜索",
2897
+ "search",
2898
+ "资料",
2899
+ "对比",
2900
+ "compare",
2901
+ "分析",
2902
+ "研究",
2903
+ "查找",
2904
+ "调查"
2905
+ ]
2906
+ };
2907
+ const TOOL_HINTS = {
2908
+ web_search: ["research"],
2909
+ web_fetch: ["research"],
2910
+ write: [
2911
+ "docs",
2912
+ "report",
2913
+ "feature"
2914
+ ],
2915
+ edit: ["bugfix", "feature"],
2916
+ bash: [
2917
+ "bugfix",
2918
+ "feature",
2919
+ "release"
2920
+ ],
2921
+ schedule_create: ["report"],
2922
+ present: ["report", "docs"],
2923
+ read: [
2924
+ "review",
2925
+ "docs",
2926
+ "bugfix"
2927
+ ],
2928
+ grep: ["review", "bugfix"],
2929
+ glob: ["review", "bugfix"]
2930
+ };
2931
+ /** Detect the current task with explainable keyword/tool evidence. */
2932
+ function detectTask(input) {
2933
+ if (input.explicit !== void 0 && input.explicit !== "unknown") return {
2934
+ tag: input.explicit,
2935
+ confidence: 1,
2936
+ keywords: [],
2937
+ source: "explicit",
2938
+ evidence: [{
2939
+ kind: "task-match",
2940
+ summary: `用户指定任务类型 ${input.explicit}`,
2941
+ weight: 1
2942
+ }]
2943
+ };
2944
+ const extracted = input.messages === void 0 ? extractFromAgent(input.agent) : void 0;
2945
+ const messages = input.messages ?? extracted?.messages ?? [];
2946
+ const toolNames = input.toolNames ?? extracted?.toolNames ?? [];
2947
+ const text = buildText(input.goal, messages);
2948
+ if (text.trim().length === 0) return unknownTask("没有足够的会话文本;请显式传入 taskTag 或 goal");
2949
+ const scores = /* @__PURE__ */ new Map();
2950
+ for (const [tag, keywords] of Object.entries(TASK_KEYWORDS)) {
2951
+ const matched = [];
2952
+ let score = 0;
2953
+ for (const keyword of keywords) {
2954
+ if (!text.includes(keyword)) continue;
2955
+ matched.push(keyword);
2956
+ score += keyword.length >= 4 ? 1.5 : 1;
2957
+ }
2958
+ if (matched.length > 0) scores.set(tag, {
2959
+ score,
2960
+ keywords: matched
2961
+ });
2962
+ }
2963
+ for (const toolName of toolNames) for (const tag of TOOL_HINTS[toolName] ?? []) {
2964
+ const current = scores.get(tag) ?? {
2965
+ score: 0,
2966
+ keywords: []
2967
+ };
2968
+ current.score += .5;
2969
+ scores.set(tag, current);
2970
+ }
2971
+ if (scores.size === 0) return unknownTask("没有匹配到任务关键词", text);
2972
+ const ranked = [...scores.entries()].sort((a, b) => b[1].score - a[1].score);
2973
+ const [tag, best] = ranked[0];
2974
+ const second = ranked[1];
2975
+ const ambiguity = second !== void 0 && best.score - second[1].score < 1 ? .1 : 0;
2976
+ let confidence = .55;
2977
+ if (best.score >= 4) confidence = .9;
2978
+ else if (best.score >= 2.5) confidence = .75;
2979
+ else if (best.score >= 1.5) confidence = .65;
2980
+ confidence = Math.max(.2, Math.min(.95, confidence - ambiguity));
2981
+ const evidence = [{
2982
+ kind: "task-match",
2983
+ summary: `匹配关键词:${best.keywords.slice(0, 6).join("、")}`,
2984
+ weight: confidence
2985
+ }];
2986
+ if (toolNames.length > 0) evidence.push({
2987
+ kind: "context",
2988
+ summary: `本会话工具:${toolNames.slice(0, 8).join(", ")}`,
2989
+ weight: .2
2990
+ });
2991
+ return {
2992
+ tag,
2993
+ confidence,
2994
+ keywords: best.keywords,
2995
+ evidence,
2996
+ source: input.goal !== void 0 && input.goal.trim().length > 0 ? "goal" : "session"
2997
+ };
2998
+ }
2999
+ function unknownTask(summary, text) {
3000
+ return {
3001
+ tag: "unknown",
3002
+ confidence: .2,
3003
+ keywords: [],
3004
+ source: "unknown",
3005
+ evidence: [{
3006
+ kind: "task-match",
3007
+ summary: text === void 0 ? summary : `${summary}(文本长度 ${text.length})`,
3008
+ weight: .2
3009
+ }]
3010
+ };
3011
+ }
3012
+ function buildText(goal, messages) {
3013
+ const parts = [];
3014
+ if (goal !== void 0 && goal.trim().length > 0) parts.push(goal);
3015
+ const userMessages = messages.filter((message) => message.role === "user").slice(-6);
3016
+ for (const message of userMessages) {
3017
+ const text = flattenTextBlocks(message.content);
3018
+ if (text.length > 0) parts.push(text);
3019
+ }
3020
+ const assistantMessages = messages.filter((message) => message.role === "assistant").slice(-4);
3021
+ for (const message of assistantMessages) {
3022
+ const text = flattenTextBlocks(message.content);
3023
+ if (text.length > 0) parts.push(text);
3024
+ }
3025
+ return truncate(parts.join("\n"), 8e3).toLowerCase();
3026
+ }
3027
+ /** Extract recent messages and tool-call names from a live Agent without importing DSH types. */
3028
+ function extractFromAgent(agent) {
3029
+ if (typeof agent !== "object" || agent === null) return {
3030
+ messages: [],
3031
+ toolNames: []
3032
+ };
3033
+ const session = agent.session;
3034
+ if (typeof session !== "object" || session === null) return {
3035
+ messages: [],
3036
+ toolNames: []
3037
+ };
3038
+ const derive = session.deriveMessages;
3039
+ if (typeof derive !== "function") return {
3040
+ messages: [],
3041
+ toolNames: []
3042
+ };
3043
+ let messages;
3044
+ try {
3045
+ messages = derive.call(session);
3046
+ } catch {
3047
+ return {
3048
+ messages: [],
3049
+ toolNames: []
3050
+ };
3051
+ }
3052
+ const recent = messages.slice(-40).filter(isMessageLike);
3053
+ const toolNames = [];
3054
+ for (const message of recent) {
3055
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
3056
+ for (const block of message.content) if (typeof block === "object" && block !== null && block.type === "tool-call" && typeof block.name === "string") toolNames.push(block.name);
3057
+ }
3058
+ return {
3059
+ messages: recent,
3060
+ toolNames: [...new Set(toolNames)].slice(-30)
3061
+ };
3062
+ }
3063
+ function isMessageLike(value) {
3064
+ return typeof value === "object" && value !== null && typeof value.role === "string" && "content" in value;
3065
+ }
3066
+ // src/protect.ts
3067
+ const PROTECTED_PACKAGES = /* @__PURE__ */ new Set([
3068
+ "dsh-plugin-trim",
3069
+ "dsh-plugin-recipe",
3070
+ "dsh-shared-meta",
3071
+ "@deepseek-ai/dsh-plugin-manager",
3072
+ "@deepseek-ai/dsh-plugin-manager/tools",
3073
+ "@deepseek-ai/dsh-tools",
3074
+ "@deepseek-ai/dsh-system-prompt",
3075
+ "@deepseek-ai/dsh-agent",
3076
+ "@deepseek-ai/dsh-agent-loop",
3077
+ "@deepseek-ai/dsh-session",
3078
+ "@deepseek-ai/dsh-session-projection",
3079
+ "@deepseek-ai/dsh-llm",
3080
+ "@deepseek-ai/dsh-host-webserver",
3081
+ "@deepseek-ai/dsh-api-gateway",
3082
+ "@deepseek-ai/dsh-client-modules",
3083
+ "@deepseek-ai/dsh-hmr",
3084
+ "@deepseek-ai/dsh-base",
3085
+ "@deepseek-ai/dsh-web-app",
3086
+ "@deepseek-ai/dsh-headless",
3087
+ "@deepseek-ai/dsh-sdk-app",
3088
+ "@deepseek-ai/dsh-sdk-minimal",
3089
+ "@deepseek-ai/dsh-persona",
3090
+ "@deepseek-ai/dsh-agent-preset",
3091
+ "@deepseek-ai/dsh-agent-preset-registry",
3092
+ "@deepseek-ai/cordis-plugin-loader",
3093
+ "@deepseek-ai/cordis-plugin-include"
3094
+ ]);
3095
+ const PROTECTED_PREFIXES = [
3096
+ "@deepseek-ai/dsh-agent-",
3097
+ "@deepseek-ai/dsh-session-",
3098
+ "@deepseek-ai/dsh-llm-",
3099
+ "@deepseek-ai/dsh-client-",
3100
+ "@deepseek-ai/dsh-api-"
3101
+ ];
3102
+ const PROTECTED_ENTRY_PREFIX = /^preset[-:]/;
3103
+ /** Build the conservative protection policy for trim suggestions and apply. */
3104
+ function buildProtection(input) {
3105
+ const protectedModules = new Set(PROTECTED_PACKAGES);
3106
+ for (const preset of input.inventory?.agentPresets ?? []) for (const row of preset.rows) protectedModules.add(row.moduleName);
3107
+ for (const extra of [...input.extraProtect ?? [], ...input.pinned ?? []]) protectedModules.add(extra);
3108
+ const protectedBundles = /* @__PURE__ */ new Set();
3109
+ for (const bundle of input.bundles) {
3110
+ if (bundle.readOnlyReason !== void 0) {
3111
+ protectedBundles.add(bundle.name);
3112
+ continue;
3113
+ }
3114
+ if (isProtectedModule(bundle.name)) {
3115
+ protectedBundles.add(bundle.name);
3116
+ continue;
3117
+ }
3118
+ if (protectedModules.has(bundle.name)) {
3119
+ protectedBundles.add(bundle.name);
3120
+ continue;
3121
+ }
3122
+ if (bundle.rows.some((row) => isProtectedModule(row.moduleName) || protectedModules.has(row.moduleName))) protectedBundles.add(bundle.name);
3123
+ }
3124
+ return {
3125
+ protectedModules,
3126
+ protectedEntryPredicate: (entry) => {
3127
+ if (entry.readOnlyReason !== void 0) return true;
3128
+ if (PROTECTED_ENTRY_PREFIX.test(entry.entryId)) return true;
3129
+ if (protectedModules.has(entry.moduleName)) return true;
3130
+ if (isProtectedModule(entry.moduleName)) return true;
3131
+ if (entry.moduleName.includes("agent-preset")) return true;
3132
+ if (entry.moduleName.includes("dsh-persona")) return true;
3133
+ return false;
3134
+ },
3135
+ protectedBundlePredicate: (bundle) => protectedBundles.has(bundle.name) || protectedModules.has(bundle.name) || bundle.readOnlyReason !== void 0 || isProtectedModule(bundle.name) || bundle.rows.some((row) => protectedModules.has(row.moduleName) || isProtectedModule(row.moduleName))
3136
+ };
3137
+ }
3138
+ /** Whether a module/package name falls under the core protection policy. */
3139
+ function isProtectedModule(moduleName) {
3140
+ const root = moduleName.replace(/\/.*$/, "");
3141
+ if (PROTECTED_PACKAGES.has(moduleName) || PROTECTED_PACKAGES.has(root)) return true;
3142
+ return PROTECTED_PREFIXES.some((prefix) => moduleName.startsWith(prefix));
3143
+ }
3144
+ // src/tool-owners.ts
3145
+ /** Built-in tool name to owning package mapping, conservative and overridable. */
3146
+ const DEFAULT_TOOL_OWNERS = {
3147
+ bash: "@deepseek-ai/dsh-tool-bash",
3148
+ pwsh: "@deepseek-ai/dsh-tool-pwsh",
3149
+ read: "@deepseek-ai/dsh-tool-fs",
3150
+ read_image: "@deepseek-ai/dsh-tool-fs",
3151
+ write: "@deepseek-ai/dsh-tool-fs",
3152
+ edit: "@deepseek-ai/dsh-tool-fs",
3153
+ apply_patch: "@deepseek-ai/dsh-tool-fs",
3154
+ glob: "@deepseek-ai/dsh-tool-fs-search",
3155
+ grep: "@deepseek-ai/dsh-tool-fs-search",
3156
+ todo_write: "@deepseek-ai/dsh-tool-todo",
3157
+ schedule_create: "@deepseek-ai/dsh-tool-schedule",
3158
+ schedule_list: "@deepseek-ai/dsh-tool-schedule",
3159
+ schedule_view: "@deepseek-ai/dsh-tool-schedule",
3160
+ schedule_edit: "@deepseek-ai/dsh-tool-schedule",
3161
+ web_search: "@deepseek-ai/dsh-tool-web",
3162
+ web_fetch: "@deepseek-ai/dsh-tool-web",
3163
+ present: "@deepseek-ai/dsh-tool-present",
3164
+ subagent: "@deepseek-ai/dsh-tool-subagent",
3165
+ subagent_fork: "@deepseek-ai/dsh-tool-subagent",
3166
+ workflow: "@deepseek-ai/dsh-tool-workflow",
3167
+ ask_user_question: "@deepseek-ai/dsh-tool-ask-user",
3168
+ job_list: "@deepseek-ai/dsh-tool-jobs",
3169
+ job_output: "@deepseek-ai/dsh-tool-jobs",
3170
+ job_kill: "@deepseek-ai/dsh-tool-jobs",
3171
+ goal_create: "@deepseek-ai/dsh-tool-goal",
3172
+ goal_get: "@deepseek-ai/dsh-tool-goal",
3173
+ goal_update: "@deepseek-ai/dsh-tool-goal",
3174
+ skill: "@deepseek-ai/dsh-tool-skill",
3175
+ session_query: "@deepseek-ai/dsh-tool-session-query",
3176
+ working_directory: "@deepseek-ai/dsh-tool-working-directory",
3177
+ terminal_create: "@deepseek-ai/dsh-tool-terminal",
3178
+ terminal_write: "@deepseek-ai/dsh-tool-terminal",
3179
+ terminal_read: "@deepseek-ai/dsh-tool-terminal",
3180
+ terminal_list: "@deepseek-ai/dsh-tool-terminal",
3181
+ terminal_kill: "@deepseek-ai/dsh-tool-terminal",
3182
+ ralph: "@deepseek-ai/dsh-tool-ralph"
3183
+ };
3184
+ /** Built-in prompt section/context name to owning package mapping. */
3185
+ const DEFAULT_SECTION_OWNERS = {
3186
+ "tool-bash": "@deepseek-ai/dsh-tool-bash",
3187
+ "tool-pwsh": "@deepseek-ai/dsh-tool-pwsh",
3188
+ "tool-read": "@deepseek-ai/dsh-tool-fs",
3189
+ "tool-write": "@deepseek-ai/dsh-tool-fs",
3190
+ "tool-edit": "@deepseek-ai/dsh-tool-fs",
3191
+ "tool-apply-patch": "@deepseek-ai/dsh-tool-fs",
3192
+ "tool-glob": "@deepseek-ai/dsh-tool-fs-search",
3193
+ "tool-grep": "@deepseek-ai/dsh-tool-fs-search",
3194
+ "tool-jobs": "@deepseek-ai/dsh-tool-jobs",
3195
+ "tool-pty": "@deepseek-ai/dsh-tool-terminal",
3196
+ "tool-web-search": "@deepseek-ai/dsh-tool-web",
3197
+ "tool-web-fetch": "@deepseek-ai/dsh-tool-web",
3198
+ "tool-goal": "@deepseek-ai/dsh-tool-goal",
3199
+ "tool-schedule": "@deepseek-ai/dsh-tool-schedule",
3200
+ "tool-workflow": "@deepseek-ai/dsh-tool-workflow",
3201
+ "tool-ralph": "@deepseek-ai/dsh-tool-ralph",
3202
+ "tool-subagent": "@deepseek-ai/dsh-tool-subagent",
3203
+ "tool-skill": "@deepseek-ai/dsh-tool-skill",
3204
+ "tool-session-query": "@deepseek-ai/dsh-tool-session-query",
3205
+ "tool-computer-use": "@deepseek-ai/dsh-tool-computer-use",
3206
+ "working-directory": "@deepseek-ai/dsh-tool-working-directory",
3207
+ "sandbox-policy": "@deepseek-ai/dsh-sandbox-policy",
3208
+ "approval-policy": "@deepseek-ai/dsh-user-approval",
3209
+ "subagent-delegation": "@deepseek-ai/dsh-subagent",
3210
+ "web-surface": "@deepseek-ai/dsh-web"
3211
+ };
3212
+ /** Resolve an owning package, preferring user overrides. */
3213
+ function ownerOfTool(toolName, overrides = {}) {
3214
+ return overrides[toolName] ?? DEFAULT_TOOL_OWNERS[toolName];
3215
+ }
3216
+ /** Resolve an owning package for a prompt section/context. */
3217
+ function ownerOfSection(name) {
3218
+ return DEFAULT_SECTION_OWNERS[name];
3219
+ }
3220
+ // src/dedupe.ts
3221
+ /** Find exact and near-duplicate prompt paragraphs across sections. */
3222
+ function dedupeSections(sections, options) {
3223
+ const paragraphs = [];
3224
+ for (const section of sections.slice(0, 200)) for (const text of splitParagraphs(section.text).slice(0, 20)) {
3225
+ const normalized = normalizeLine(text);
3226
+ if (normalized.length < 20) continue;
3227
+ paragraphs.push({
3228
+ section: section.name,
3229
+ owner: ownerOfSection(section.name),
3230
+ text,
3231
+ normalized,
3232
+ shingles: shingles(wordTokens(text), 3)
3233
+ });
3234
+ }
3235
+ if (paragraphs.length < 2) return [];
3236
+ const groups = [];
3237
+ const used = /* @__PURE__ */ new Set();
3238
+ const threshold = options.similarityThreshold ?? .8;
3239
+ for (let i = 0; i < paragraphs.length; i++) {
3240
+ if (used.has(i)) continue;
3241
+ const base = paragraphs[i];
3242
+ const group = [base];
3243
+ used.add(i);
3244
+ for (let j = i + 1; j < paragraphs.length; j++) {
3245
+ if (used.has(j)) continue;
3246
+ const candidate = paragraphs[j];
3247
+ if ((base.normalized === candidate.normalized ? 1 : jaccard(base.shingles, candidate.shingles)) < threshold) continue;
3248
+ group.push(candidate);
3249
+ used.add(j);
3250
+ }
3251
+ if (uniq(group.map((item) => item.section)).length > 1) groups.push(group);
3252
+ if (groups.length >= 20) break;
3253
+ }
3254
+ const out = [];
3255
+ const seen = /* @__PURE__ */ new Set();
3256
+ for (const group of groups) {
3257
+ const sectionsInGroup = uniq(group.map((item) => item.section)).sort();
3258
+ const key = sectionsInGroup.join("|");
3259
+ if (seen.has(key)) continue;
3260
+ seen.add(key);
3261
+ const members = sectionsInGroup.map((section) => {
3262
+ const first = group.find((item) => item.section === section);
3263
+ return {
3264
+ section,
3265
+ owner: first?.owner,
3266
+ textLength: first?.text.length ?? 0
3267
+ };
3268
+ });
3269
+ const authority = pickAuthority(members);
3270
+ const conflict = hasConflict(group.map((item) => item.text));
3271
+ out.push({
3272
+ fingerprint: shortHash(key),
3273
+ members,
3274
+ authority,
3275
+ conflict,
3276
+ reason: conflict ? "疑似语义冲突,仅标记不合并" : "保留权威来源,其余建议改为引用或摘要",
3277
+ excerpt: options.persistExcerpts ? truncate(group[0]?.text ?? "", 160) : void 0
3278
+ });
3279
+ }
3280
+ return out;
3281
+ }
3282
+ function pickAuthority(members) {
3283
+ return [...members].sort((a, b) => {
3284
+ const aCore = isAuthoritativeOwner(a.owner) ? 1 : 0;
3285
+ const bCore = isAuthoritativeOwner(b.owner) ? 1 : 0;
3286
+ if (aCore !== bCore) return bCore - aCore;
3287
+ if (a.textLength !== b.textLength) return b.textLength - a.textLength;
3288
+ return a.section.localeCompare(b.section);
3289
+ })[0]?.section ?? "";
3290
+ }
3291
+ function isAuthoritativeOwner(owner) {
3292
+ if (owner === void 0) return false;
3293
+ return owner.includes("dsh-tool-fs") || owner.includes("dsh-tool-bash") || owner.includes("dsh-system-prompt");
3294
+ }
3295
+ function hasConflict(texts) {
3296
+ const negation = /(?:^|\s)(not|never|no|禁止|不得|不要|必须|always|must)(?:\s|$)/i;
3297
+ const numberSets = texts.map((text) => new Set(text.match(/\d+/g) ?? []));
3298
+ const first = numberSets[0] ?? /* @__PURE__ */ new Set();
3299
+ for (const current of numberSets.slice(1)) {
3300
+ if (current.size !== first.size) return true;
3301
+ for (const value of first) if (!current.has(value)) return true;
3302
+ }
3303
+ const firstNegation = negation.test(texts[0] ?? "");
3304
+ for (const text of texts.slice(1)) if (negation.test(text) !== firstNegation) return true;
3305
+ return false;
3306
+ }
3307
+ // src/usage.ts
3308
+ /** Append-only local usage ledger. Records tool names, success, and time only. */
3309
+ var UsageLedger = class {
3310
+ path;
3311
+ retentionDays;
3312
+ maxBytes;
3313
+ enabled;
3314
+ buffer = [];
3315
+ timer;
3316
+ flushPromise;
3317
+ constructor(options = {}) {
3318
+ this.path = options.path ?? dataDir("trim", "usage.jsonl");
3319
+ this.retentionDays = options.retentionDays ?? 30;
3320
+ this.maxBytes = options.maxBytes ?? 1048576;
3321
+ this.enabled = options.enabled ?? true;
3322
+ }
3323
+ record(toolName, ok) {
3324
+ if (!this.enabled || toolName.length === 0) return;
3325
+ this.buffer.push({
3326
+ t: (/* @__PURE__ */ new Date()).toISOString(),
3327
+ n: toolName,
3328
+ ok
3329
+ });
3330
+ if (this.timer === void 0) {
3331
+ this.timer = setTimeout(() => {
3332
+ this.timer = void 0;
3333
+ this.flush();
3334
+ }, 2e3);
3335
+ this.timer.unref?.();
3336
+ }
3337
+ }
3338
+ async flush() {
3339
+ if (this.flushPromise !== void 0) return this.flushPromise;
3340
+ if (this.buffer.length === 0) return;
3341
+ const lines = this.buffer;
3342
+ this.buffer = [];
3343
+ this.flushPromise = (async () => {
3344
+ try {
3345
+ await appendJsonl(this.path, lines);
3346
+ await this.compactIfNeeded();
3347
+ } finally {
3348
+ this.flushPromise = void 0;
3349
+ }
3350
+ })();
3351
+ return this.flushPromise;
3352
+ }
3353
+ async dispose() {
3354
+ if (this.timer !== void 0) {
3355
+ clearTimeout(this.timer);
3356
+ this.timer = void 0;
3357
+ }
3358
+ await this.flush();
3359
+ }
3360
+ /** Aggregate retained lines by tool name. */
3361
+ async aggregate() {
3362
+ await this.flush();
3363
+ const lines = await readJsonl(this.path);
3364
+ const cutoff = Date.now() - this.retentionDays * 24 * 60 * 60 * 1e3;
3365
+ const map = /* @__PURE__ */ new Map();
3366
+ for (const line of lines) {
3367
+ if (typeof line.t !== "string" || typeof line.n !== "string") continue;
3368
+ const at = Date.parse(line.t);
3369
+ if (!Number.isFinite(at) || at < cutoff) continue;
3370
+ const current = map.get(line.n) ?? {
3371
+ calls: 0,
3372
+ successes: 0,
3373
+ sessionCalls: 0
3374
+ };
3375
+ current.calls += 1;
3376
+ if (line.ok === true) current.successes += 1;
3377
+ if (current.lastUsedAt === void 0 || line.t > current.lastUsedAt) current.lastUsedAt = line.t;
3378
+ map.set(line.n, current);
3379
+ }
3380
+ return map;
3381
+ }
3382
+ /** Add current-session tool calls to an aggregate without pretending to know success. */
3383
+ addSessionUsage(aggregate, toolNames) {
3384
+ const counts = /* @__PURE__ */ new Map();
3385
+ for (const name of toolNames) counts.set(name, (counts.get(name) ?? 0) + 1);
3386
+ for (const [name, count] of counts) {
3387
+ const current = aggregate.get(name) ?? {
3388
+ calls: 0,
3389
+ successes: 0,
3390
+ sessionCalls: 0
3391
+ };
3392
+ current.sessionCalls += count;
3393
+ aggregate.set(name, current);
3394
+ }
3395
+ return aggregate;
3396
+ }
3397
+ async compactIfNeeded() {
3398
+ try {
3399
+ if ((await stat(this.path)).size <= this.maxBytes) return;
3400
+ const lines = await readJsonl(this.path);
3401
+ const cutoff = Date.now() - this.retentionDays * 24 * 60 * 60 * 1e3;
3402
+ const text = lines.filter((line) => {
3403
+ const at = typeof line.t === "string" ? Date.parse(line.t) : NaN;
3404
+ return Number.isFinite(at) && at >= cutoff;
3405
+ }).slice(-5e4).map((line) => JSON.stringify(line)).join("\n");
3406
+ await writeTextAtomic(this.path, text.length === 0 ? "" : `${text}\n`);
3407
+ } catch {}
3408
+ }
3409
+ };
3410
+ function mergeUsage(a, b) {
3411
+ return {
3412
+ calls: a.calls + b.calls,
3413
+ successes: a.successes + b.successes,
3414
+ sessionCalls: a.sessionCalls + b.sessionCalls,
3415
+ lastUsedAt: latest(a.lastUsedAt, b.lastUsedAt)
3416
+ };
3417
+ }
3418
+ function usageForOwner(usage, owner, toolNames) {
3419
+ let total = {
3420
+ calls: 0,
3421
+ successes: 0,
3422
+ sessionCalls: 0
3423
+ };
3424
+ for (const toolName of toolNames) {
3425
+ const stats = usage.get(toolName);
3426
+ if (stats !== void 0) total = mergeUsage(total, stats);
3427
+ }
3428
+ return total;
3429
+ }
3430
+ function latest(a, b) {
3431
+ if (a === void 0) return b;
3432
+ if (b === void 0) return a;
3433
+ return a > b ? a : b;
3434
+ }
3435
+ // src/scan.ts
3436
+ /** Normalize plugin metadata, prompt costs, usage, and compat findings into one scan result. */
3437
+ async function scanPlugins(options) {
3438
+ const { config, compat } = options;
3439
+ const protection = buildProtection({
3440
+ bundles: compat.context.bundles,
3441
+ entries: compat.context.entriesInfo,
3442
+ inventory: options.inventory,
3443
+ extraProtect: config.protect,
3444
+ pinned: config.pinned
3445
+ });
3446
+ const findingsMap = findingsBySubject(compat.findings);
3447
+ const sections = [...(compat.context.prompt?.sections ?? []).map((section) => ({
3448
+ name: section.name,
3449
+ owner: ownerOfSection(section.name) ?? "unattributed",
3450
+ tokens: estimateTokens(section.text),
3451
+ chars: section.text.length,
3452
+ source: "section"
3453
+ })), ...(compat.context.prompt?.contexts ?? []).map((section) => ({
3454
+ name: section.name,
3455
+ owner: ownerOfSection(section.name) ?? "unattributed",
3456
+ tokens: estimateTokens(section.text),
3457
+ chars: section.text.length,
3458
+ source: "context"
3459
+ }))];
3460
+ const tools = (compat.context.prompt?.tools ?? []).map((tool) => ({
3461
+ name: tool.name,
3462
+ owner: ownerOfTool(tool.name, config.toolOwners) ?? "unattributed",
3463
+ tokens: estimateTokens(JSON.stringify(tool.parameters ?? {}) + (tool.description ?? ""))
3464
+ }));
3465
+ const byOwner = {};
3466
+ for (const section of sections) addCost(byOwner, section.owner ?? "unattributed", section.tokens);
3467
+ for (const tool of tools) addCost(byOwner, tool.owner ?? "unattributed", tool.tokens);
3468
+ const totalTokens = Object.values(byOwner).reduce((sum, value) => sum + value, 0);
3469
+ const toolsByOwner = /* @__PURE__ */ new Map();
3470
+ for (const tool of tools) {
3471
+ if (tool.owner === void 0) continue;
3472
+ const list = toolsByOwner.get(tool.owner) ?? [];
3473
+ list.push(tool.name);
3474
+ toolsByOwner.set(tool.owner, list);
3475
+ }
3476
+ const usageAggregate = options.usageLedger === void 0 ? /* @__PURE__ */ new Map() : await options.usageLedger.aggregate();
3477
+ const sessionToolNames = options.sessionToolNames ?? extractFromAgent(options.agent).toolNames;
3478
+ options.usageLedger?.addSessionUsage(usageAggregate, sessionToolNames);
3479
+ const usageByTool = Object.fromEntries(usageAggregate);
3480
+ const usageByOwner = {};
3481
+ for (const [owner, names] of toolsByOwner) usageByOwner[owner] = usageForOwner(usageAggregate, owner, names);
3482
+ const bundles = compat.context.bundles.map((bundle) => {
3483
+ const rowModuleNames = uniq(bundle.rows.map((row) => rootPackageName(row.moduleName)));
3484
+ const findings = uniqFindings([...findingsMap.get(bundle.name) ?? [], ...rowModuleNames.flatMap((name) => findingsMap.get(name) ?? [])]);
3485
+ const usage = mergeBundleUsage(usageByOwner, rowModuleNames);
3486
+ return {
3487
+ name: bundle.name,
3488
+ version: bundle.version,
3489
+ description: bundle.description,
3490
+ enabled: bundle.enabled,
3491
+ installed: bundle.installed,
3492
+ availability: bundle.availability,
3493
+ official: bundle.official,
3494
+ optional: bundle.optional,
3495
+ removable: bundle.removable,
3496
+ readOnlyReason: bundle.readOnlyReason,
3497
+ guardStatus: guardStatusFor(findings, protection.protectedBundlePredicate(bundle)),
3498
+ rowModuleNames,
3499
+ contextTokens: rowModuleNames.reduce((sum, name) => sum + (byOwner[name] ?? 0), 0),
3500
+ usage,
3501
+ protected: protection.protectedBundlePredicate(bundle),
3502
+ findings
3503
+ };
3504
+ });
3505
+ const bundleByEntry = /* @__PURE__ */ new Map();
3506
+ for (const bundle of compat.context.bundles) for (const row of bundle.rows) if (row.entryId !== void 0) bundleByEntry.set(row.entryId, bundle.name);
3507
+ const entries = compat.context.entriesInfo.map((entry) => {
3508
+ const root = rootPackageName(entry.moduleName);
3509
+ const findings = findingsMap.get(entry.moduleName) ?? findingsMap.get(root) ?? [];
3510
+ const usage = mergeBundleUsage(usageByOwner, [root]);
3511
+ return {
3512
+ entryId: entry.entryId,
3513
+ moduleName: entry.moduleName,
3514
+ bundleName: bundleByEntry.get(entry.entryId),
3515
+ enabled: entry.enabled,
3516
+ fiberPhase: entry.fiberPhase,
3517
+ diagnostic: entry.diagnostic,
3518
+ patchId: entry.patchId,
3519
+ readOnlyReason: entry.readOnlyReason,
3520
+ guardStatus: guardStatusFor(findings, protection.protectedEntryPredicate(entry)),
3521
+ contextTokens: byOwner[root] ?? 0,
3522
+ usage,
3523
+ protected: protection.protectedEntryPredicate(entry),
3524
+ findings
3525
+ };
3526
+ });
3527
+ const presetModules = uniq([...(options.inventory?.agentPresets ?? []).flatMap((preset) => preset.rows.map((row) => row.moduleName)), ...compat.context.loaderEntries.filter((entry) => entry.source === "preset").map((entry) => entry.moduleName)]);
3528
+ const dedupe = config.enableDedupe && compat.context.prompt !== void 0 ? dedupeSections([...compat.context.prompt.sections, ...compat.context.prompt.contexts], { persistExcerpts: config.persistExcerpts }) : [];
3529
+ return {
3530
+ managementAvailable: options.pluginManager !== void 0,
3531
+ compat: {
3532
+ summary: compat.report.summary,
3533
+ topFindings: compat.findings.slice(0, 5),
3534
+ reportPath: compat.reportPath
3535
+ },
3536
+ bundles,
3537
+ entries,
3538
+ context: {
3539
+ totalTokens,
3540
+ byOwner,
3541
+ sections,
3542
+ tools,
3543
+ unattributedTokens: byOwner.unattributed ?? 0
3544
+ },
3545
+ presetModules,
3546
+ usage: {
3547
+ byTool: usageByTool,
3548
+ byOwner: usageByOwner
3549
+ },
3550
+ dedupe,
3551
+ diagnostics: [...compat.context.diagnostics]
3552
+ };
3553
+ }
3554
+ function addCost(map, owner, tokens) {
3555
+ map[owner] = (map[owner] ?? 0) + tokens;
3556
+ }
3557
+ function mergeBundleUsage(usageByOwner, owners) {
3558
+ let total = {
3559
+ calls: 0,
3560
+ successes: 0,
3561
+ sessionCalls: 0
3562
+ };
3563
+ for (const owner of owners) {
3564
+ const stats = usageByOwner[owner];
3565
+ if (stats !== void 0) total = mergeUsage(total, stats);
3566
+ }
3567
+ return total;
3568
+ }
3569
+ function guardStatusFor(findings, protectedItem) {
3570
+ if (protectedItem) return "protected";
3571
+ if (findings.some((finding) => finding.severity === "error" && finding.code.startsWith("RT_"))) return "incompatible";
3572
+ if (findings.some((finding) => finding.severity === "error")) return "warn";
3573
+ if (findings.some((finding) => finding.severity === "warn")) return "warn";
3574
+ return "ok";
3575
+ }
3576
+ function uniqFindings(items) {
3577
+ const map = /* @__PURE__ */ new Map();
3578
+ for (const item of items) map.set(item.id, item);
3579
+ return [...map.values()];
3580
+ }
3581
+ // src/store.ts
3582
+ function draftPath(profileId) {
3583
+ return dataDir("trim", "profiles", `${safeId(profileId)}.json`);
3584
+ }
3585
+ function snapshotPath(token) {
3586
+ return dataDir("trim", "snapshots", `${safeId(token)}.json`);
3587
+ }
3588
+ async function saveDraft(profile, maxDrafts) {
3589
+ await writeJsonAtomic(draftPath(profile.id), profile);
3590
+ await pruneToCount(dataDir("trim", "profiles"), maxDrafts);
3591
+ }
3592
+ async function loadDraft(profileId) {
3593
+ return readJson(draftPath(profileId));
3594
+ }
3595
+ async function saveSnapshot(snapshot, maxDrafts) {
3596
+ await writeJsonAtomic(snapshotPath(snapshot.token), snapshot);
3597
+ await pruneToCount(dataDir("trim", "snapshots"), maxDrafts);
3598
+ }
3599
+ async function loadSnapshot(token) {
3600
+ return readJson(snapshotPath(token));
3601
+ }
3602
+ async function listSnapshots() {
3603
+ return listJsonFiles(dataDir("trim", "snapshots"));
3604
+ }
3605
+ function safeId(value) {
3606
+ return value.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 120);
3607
+ }
3608
+ // src/apply.ts
3609
+ var ApplyRefusedError = class extends Error {
3610
+ constructor(message) {
3611
+ super(message);
3612
+ this.name = "ApplyRefusedError";
3613
+ }
3614
+ };
3615
+ const CONFLICT_FIX_CODES = /* @__PURE__ */ new Set([
3616
+ "PP_SERVICE_DUPLICATE",
3617
+ "PP_ROW_DUPLICATE",
3618
+ "PP_MCP_SERVER_DUPLICATE",
3619
+ "PP_RUNTIME_REGISTRATION_FAILED",
3620
+ "RT_PLATFORM_UNSUPPORTED",
3621
+ "RT_ENGINE_UNMET",
3622
+ "RT_PEER_UNMET",
3623
+ "RT_PREFLIGHT_DENIED"
3624
+ ]);
3625
+ /** Apply low-risk items from a saved draft, with a crash-safe snapshot and automatic rollback. */
3626
+ async function applySlimProfile(profileId, options) {
3627
+ if (options.confirm !== true) throw new ApplyRefusedError("apply requires confirm: true; ask the user to explicitly approve the exact profileId and items first");
3628
+ const draft = await loadDraft(profileId);
3629
+ if (draft === void 0) throw new Error(`unknown slim profile: ${profileId}`);
3630
+ const desiredIds = options.items === void 0 ? void 0 : new Set(options.items);
3631
+ let candidates = applicableItems(draft).filter((item) => desiredIds === void 0 || desiredIds.has(item.id));
3632
+ if (candidates.length === 0) return {
3633
+ profileId,
3634
+ items: []
3635
+ };
3636
+ const [bundles, entries] = await Promise.all([options.manager.listBundles(), options.manager.listPlugins()]);
3637
+ const bundleEnabled = new Map(bundles.map((bundle) => [bundle.name, bundle.enabled]));
3638
+ const entryEnabled = new Map(entries.map((entry) => [entry.entryId, entry.enabled]));
3639
+ const freshFindings = findingsBySubject(options.findings ?? []);
3640
+ const disabledBundles = new Set(candidates.filter((item) => item.kind === "bundle" && item.action === "suggest-disable").map((item) => item.bundleName).filter((name) => name !== void 0));
3641
+ candidates = candidates.filter((item) => !(item.kind === "entry" && item.bundleName !== void 0 && disabledBundles.has(item.bundleName)));
3642
+ const token = randomToken();
3643
+ const snapshot = {
3644
+ schemaVersion: 1,
3645
+ token,
3646
+ profileId,
3647
+ profileName: options.profileName,
3648
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3649
+ status: "pending",
3650
+ items: candidates.map((item) => ({
3651
+ id: item.id,
3652
+ kind: item.kind,
3653
+ name: item.name,
3654
+ previousEnabled: currentEnabled(item, bundleEnabled, entryEnabled),
3655
+ desiredEnabled: item.action === "enable",
3656
+ status: "pending"
3657
+ }))
3658
+ };
3659
+ await saveSnapshot(snapshot, options.maxDrafts);
3660
+ const results = [];
3661
+ let restartRequired = false;
3662
+ let failed = false;
3663
+ for (let index = 0; index < candidates.length; index++) {
3664
+ const item = candidates[index];
3665
+ const snapshotItem = snapshot.items[index];
3666
+ if (snapshotItem === void 0) continue;
3667
+ const current = currentEnabled(item, bundleEnabled, entryEnabled);
3668
+ if (current !== item.observedEnabled) {
3669
+ results.push({
3670
+ id: item.id,
3671
+ kind: item.kind,
3672
+ name: item.name,
3673
+ status: "stale",
3674
+ error: "plugin state changed since the draft was created"
3675
+ });
3676
+ snapshotItem.status = "skipped";
3677
+ await saveSnapshot(snapshot, options.maxDrafts);
3678
+ continue;
3679
+ }
3680
+ if (current === snapshotItem.desiredEnabled) {
3681
+ results.push({
3682
+ id: item.id,
3683
+ kind: item.kind,
3684
+ name: item.name,
3685
+ status: "skipped",
3686
+ error: "already in the desired state"
3687
+ });
3688
+ snapshotItem.status = "skipped";
3689
+ await saveSnapshot(snapshot, options.maxDrafts);
3690
+ continue;
3691
+ }
3692
+ if (item.protected) {
3693
+ results.push({
3694
+ id: item.id,
3695
+ kind: item.kind,
3696
+ name: item.name,
3697
+ status: "skipped",
3698
+ error: "protected"
3699
+ });
3700
+ snapshotItem.status = "skipped";
3701
+ await saveSnapshot(snapshot, options.maxDrafts);
3702
+ continue;
3703
+ }
3704
+ const blocked = blockedByCompat(item, [...freshFindings.get(item.name) ?? [], ...item.bundleName === void 0 ? [] : freshFindings.get(item.bundleName) ?? []]);
3705
+ if (blocked !== void 0) {
3706
+ results.push({
3707
+ id: item.id,
3708
+ kind: item.kind,
3709
+ name: item.name,
3710
+ status: "blocked-by-compat",
3711
+ error: blocked
3712
+ });
3713
+ snapshotItem.status = "skipped";
3714
+ await saveSnapshot(snapshot, options.maxDrafts);
3715
+ continue;
3716
+ }
3717
+ let change;
3718
+ try {
3719
+ change = await applyOne(item, options.manager);
3720
+ } catch (error) {
3721
+ change = {
3722
+ changed: false,
3723
+ application: "failed",
3724
+ error: { diagnostic: error instanceof Error ? error.message : String(error) }
3725
+ };
3726
+ }
3727
+ const status = mapStatus(change);
3728
+ if (status === "failed") {
3729
+ failed = true;
3730
+ snapshotItem.status = "failed";
3731
+ snapshotItem.application = change.application;
3732
+ snapshotItem.error = change.error?.diagnostic ?? change.error?.code;
3733
+ results.push({
3734
+ id: item.id,
3735
+ kind: item.kind,
3736
+ name: item.name,
3737
+ status: "failed",
3738
+ application: change.application,
3739
+ error: snapshotItem.error
3740
+ });
3741
+ } else {
3742
+ snapshotItem.status = "applied";
3743
+ snapshotItem.application = change.application;
3744
+ results.push({
3745
+ id: item.id,
3746
+ kind: item.kind,
3747
+ name: item.name,
3748
+ status,
3749
+ application: change.application,
3750
+ fixKind: fixKindFor(item, [...freshFindings.get(item.name) ?? [], ...item.bundleName === void 0 ? [] : freshFindings.get(item.bundleName) ?? []])
3751
+ });
3752
+ if (change.application === "restart-required") restartRequired = true;
3753
+ if (item.kind === "bundle") bundleEnabled.set(item.name, snapshotItem.desiredEnabled);
3754
+ else entryEnabled.set(item.name, snapshotItem.desiredEnabled);
3755
+ }
3756
+ await saveSnapshot(snapshot, options.maxDrafts);
3757
+ if (failed) break;
3758
+ }
3759
+ if (failed) {
3760
+ await autoRollback(snapshot, options.manager);
3761
+ snapshot.status = "partial";
3762
+ await saveSnapshot(snapshot, options.maxDrafts);
3763
+ draft.status = "partial";
3764
+ await saveDraft(draft, options.maxDrafts).catch(() => void 0);
3765
+ await audit$1(profileId, "apply", "fail", "applied then rolled back after a failure", results.length);
3766
+ return {
3767
+ profileId,
3768
+ token,
3769
+ items: results,
3770
+ rolledBack: true,
3771
+ restartRequired
3772
+ };
3773
+ }
3774
+ snapshot.status = "applied";
3775
+ await saveSnapshot(snapshot, options.maxDrafts);
3776
+ draft.status = "applied";
3777
+ await saveDraft(draft, options.maxDrafts).catch(() => void 0);
3778
+ await audit$1(profileId, "apply", "ok", `applied ${results.filter((item) => item.status !== "skipped").length} items`, results.length);
3779
+ return {
3780
+ profileId,
3781
+ token,
3782
+ items: results,
3783
+ restartRequired
3784
+ };
3785
+ }
3786
+ async function applyOne(item, manager) {
3787
+ const enabled = item.action === "enable";
3788
+ if (item.kind === "bundle") {
3789
+ if (typeof manager.setBundleEnabled !== "function") throw new Error("plugin manager cannot set bundles");
3790
+ return manager.setBundleEnabled(item.name, enabled);
3791
+ }
3792
+ if (typeof manager.setPluginEnabled !== "function") throw new Error("plugin manager cannot set plugins");
3793
+ return manager.setPluginEnabled(item.name, enabled);
3794
+ }
3795
+ async function autoRollback(snapshot, manager) {
3796
+ for (const item of [...snapshot.items].reverse()) {
3797
+ if (item.status !== "applied") continue;
3798
+ try {
3799
+ if (item.kind === "bundle") await manager.setBundleEnabled?.(item.name, item.previousEnabled);
3800
+ else await manager.setPluginEnabled?.(item.name, item.previousEnabled);
3801
+ item.status = "skipped";
3802
+ item.error = "rolled back after a later failure";
3803
+ } catch {}
3804
+ }
3805
+ }
3806
+ function mapStatus(change) {
3807
+ if (change.application === "applied") return "applied";
3808
+ if (change.application === "restart-required") return "applied-pending-restart";
3809
+ return "failed";
3810
+ }
3811
+ function currentEnabled(item, bundles, entries) {
3812
+ return item.kind === "bundle" ? bundles.get(item.name) ?? item.observedEnabled : entries.get(item.name) ?? item.observedEnabled;
3813
+ }
3814
+ function blockedByCompat(item, findings) {
3815
+ const errors = [...item.findings, ...findings].filter((finding) => finding.severity === "error");
3816
+ if (errors.length === 0) return void 0;
3817
+ if (item.action === "enable") return `enabling would collide with ${errors.map((finding) => finding.code).join(", ")}`;
3818
+ if (errors.every((finding) => CONFLICT_FIX_CODES.has(finding.code))) return void 0;
3819
+ return `compatibility error is not safe to auto-resolve: ${errors.map((finding) => finding.code).join(", ")}`;
3820
+ }
3821
+ function fixKindFor(item, findings) {
3822
+ if (item.action !== "suggest-disable") return void 0;
3823
+ const combined = [...item.findings, ...findings];
3824
+ if (combined.some((finding) => finding.code.startsWith("PP_"))) return "conflict";
3825
+ if (combined.some((finding) => finding.code.startsWith("RT_"))) return "workaround";
3826
+ }
3827
+ async function audit$1(subject, action, result, summary, count) {
3828
+ await new AuditLog().append({
3829
+ t: (/* @__PURE__ */ new Date()).toISOString(),
3830
+ actor: "trim",
3831
+ action,
3832
+ subject,
3833
+ result,
3834
+ summary,
3835
+ metrics: { items: count }
3836
+ }).catch(() => void 0);
3837
+ }
3838
+ // src/rollback.ts
3839
+ /** Restore a previous apply snapshot, skipping state changed outside trim. */
3840
+ async function rollbackSlimProfile(options) {
3841
+ const token = options.token ?? await latestToken(options.profileName);
3842
+ if (token === void 0) throw new Error("no rollback snapshot found");
3843
+ const snapshot = await loadSnapshot(token);
3844
+ if (snapshot === void 0) throw new Error(`unknown rollback token: ${token}`);
3845
+ const [bundles, entries] = await Promise.all([options.manager.listBundles(), options.manager.listPlugins()]);
3846
+ const bundleEnabled = new Map(bundles.map((bundle) => [bundle.name, bundle.enabled]));
3847
+ const entryEnabled = new Map(entries.map((entry) => [entry.entryId, entry.enabled]));
3848
+ const results = [];
3849
+ for (const item of [...snapshot.items].reverse()) {
3850
+ if (item.status !== "applied" && item.status !== "failed") {
3851
+ results.push({
3852
+ id: item.id,
3853
+ kind: item.kind,
3854
+ name: item.name,
3855
+ status: "skipped"
3856
+ });
3857
+ continue;
3858
+ }
3859
+ const current = item.kind === "bundle" ? bundleEnabled.get(item.name) ?? item.desiredEnabled : entryEnabled.get(item.name) ?? item.desiredEnabled;
3860
+ const pendingRestart = item.application === "restart-required";
3861
+ const matchesPrevious = current === item.previousEnabled;
3862
+ const matchesDesired = current === item.desiredEnabled;
3863
+ if (matchesPrevious && !pendingRestart) {
3864
+ results.push({
3865
+ id: item.id,
3866
+ kind: item.kind,
3867
+ name: item.name,
3868
+ status: "already-restored"
3869
+ });
3870
+ continue;
3871
+ }
3872
+ if (!matchesPrevious && !matchesDesired) {
3873
+ results.push({
3874
+ id: item.id,
3875
+ kind: item.kind,
3876
+ name: item.name,
3877
+ status: "externally-changed"
3878
+ });
3879
+ continue;
3880
+ }
3881
+ try {
3882
+ if (item.kind === "bundle") {
3883
+ if (typeof options.manager.setBundleEnabled !== "function") throw new Error("plugin manager cannot set bundles");
3884
+ await options.manager.setBundleEnabled(item.name, item.previousEnabled);
3885
+ bundleEnabled.set(item.name, item.previousEnabled);
3886
+ } else {
3887
+ if (typeof options.manager.setPluginEnabled !== "function") throw new Error("plugin manager cannot set plugins");
3888
+ await options.manager.setPluginEnabled(item.name, item.previousEnabled);
3889
+ entryEnabled.set(item.name, item.previousEnabled);
3890
+ }
3891
+ results.push({
3892
+ id: item.id,
3893
+ kind: item.kind,
3894
+ name: item.name,
3895
+ status: "restored"
3896
+ });
3897
+ item.status = "skipped";
3898
+ } catch (error) {
3899
+ results.push({
3900
+ id: item.id,
3901
+ kind: item.kind,
3902
+ name: item.name,
3903
+ status: "failed",
3904
+ error: error instanceof Error ? error.message : String(error)
3905
+ });
3906
+ }
3907
+ }
3908
+ snapshot.status = "rolled-back";
3909
+ await saveSnapshot(snapshot, options.maxDrafts);
3910
+ const draft = await loadDraft(snapshot.profileId);
3911
+ if (draft !== void 0) {
3912
+ draft.status = "rolled-back";
3913
+ await saveDraft(draft, options.maxDrafts).catch(() => void 0);
3914
+ }
3915
+ await new AuditLog().append({
3916
+ t: (/* @__PURE__ */ new Date()).toISOString(),
3917
+ actor: "trim",
3918
+ action: "rollback",
3919
+ subject: snapshot.profileId,
3920
+ result: results.some((item) => item.status === "failed") ? "fail" : "ok",
3921
+ summary: `restored ${results.filter((item) => item.status === "restored").length} items`,
3922
+ metrics: { items: results.length }
3923
+ }).catch(() => void 0);
3924
+ return {
3925
+ token,
3926
+ items: results
3927
+ };
3928
+ }
3929
+ async function latestToken(profileName) {
3930
+ const files = await listSnapshots();
3931
+ for (const file of files) {
3932
+ const token = file.replace(/\.json$/, "").split(/[\\/]/).pop();
3933
+ if (token === void 0) continue;
3934
+ if (profileName === void 0) return token;
3935
+ try {
3936
+ if ((await loadSnapshot(token))?.profileName === profileName) return token;
3937
+ } catch {}
3938
+ }
3939
+ }
3940
+ // src/tools.ts
3941
+ const TASK_TAGS$1 = [
3942
+ "bugfix",
3943
+ "feature",
3944
+ "review",
3945
+ "docs",
3946
+ "release",
3947
+ "report",
3948
+ "research",
3949
+ "unknown"
3950
+ ];
3951
+ /** Register all trim model-facing tools. */
3952
+ function registerTrimTools(ctx, deps) {
3953
+ registerScanTool(ctx, deps);
3954
+ registerSuggestTool(ctx, deps);
3955
+ registerApplyTool(ctx, deps);
3956
+ registerRollbackTool(ctx, deps);
3957
+ }
3958
+ function registerScanTool(ctx, deps) {
3959
+ ctx.tools.register(defineTool({
3960
+ name: "trim_scan_plugins",
3961
+ description: "Read-only scan of installed DSH bundles/entries, current prompt context cost, usage, dedupe groups, and a compatibility summary. Use when the user asks which plugins are consuming context or wants a plugin inventory. Does not change plugin state.",
3962
+ parameters: {
3963
+ detail: {
3964
+ type: "string",
3965
+ enum: ["summary", "full"],
3966
+ description: "summary shows top rows; full shows more entries. Default summary."
3967
+ },
3968
+ maxRows: {
3969
+ type: "integer",
3970
+ description: "Maximum rows per table, 1..100. Default 20."
3971
+ }
3972
+ },
3973
+ output: {
3974
+ schema: { type: "string" },
3975
+ render: (_args, value) => [{
3976
+ type: "text",
3977
+ text: value
3978
+ }]
3979
+ },
3980
+ async execute(args, exec) {
3981
+ const compat = await analyzeCompatibility(ctx, deps.config, {
3982
+ scope: "current",
3983
+ includeInfo: true,
3984
+ writeReport: false,
3985
+ agent: exec.agent,
3986
+ toolSet: exec.toolSet
3987
+ });
3988
+ const sessionToolNames = extractFromAgent(exec.agent).toolNames;
3989
+ const scan = await scanPlugins({
3990
+ config: deps.config,
3991
+ compat,
3992
+ pluginManager: getPluginManager(ctx),
3993
+ inventory: await inventoryOf$1(ctx),
3994
+ usageLedger: deps.ledger,
3995
+ agent: exec.agent,
3996
+ sessionToolNames
3997
+ });
3998
+ await audit("scan_plugins", "ok", `scanned ${scan.bundles.length} bundles`);
3999
+ return renderScan(scan, args.detail === "full" ? 100 : Math.min(100, Math.max(1, args.maxRows ?? 20)));
4000
+ },
4001
+ presentCall: () => ({
4002
+ card: "generic",
4003
+ title: "Scan plugin context",
4004
+ kind: "read"
4005
+ })
4006
+ }));
4007
+ }
4008
+ function registerSuggestTool(ctx, deps) {
4009
+ ctx.tools.register(defineTool({
4010
+ name: "trim_suggest_profile",
4011
+ description: "Build a read-only slim-profile draft for the current task: which plugins to keep, enable, disable, or review, with explainable evidence, compatibility findings, and dedupe suggestions. Writes only a local draft; never changes plugin enablement. Call trim_apply_profile only after the user explicitly approves the returned profileId.",
4012
+ parameters: {
4013
+ taskTag: {
4014
+ type: "string",
4015
+ enum: TASK_TAGS$1,
4016
+ description: "Optional explicit task tag; overrides text detection."
4017
+ },
4018
+ goal: {
4019
+ type: "string",
4020
+ description: "Optional task goal when the user states it explicitly."
4021
+ },
4022
+ includeReview: {
4023
+ type: "boolean",
4024
+ description: "Include review-only items. Default true."
4025
+ },
4026
+ maxDisable: {
4027
+ type: "integer",
4028
+ description: "Maximum disable suggestions, 0..100. Default 20."
4029
+ }
4030
+ },
4031
+ output: {
4032
+ schema: { type: "string" },
4033
+ render: (_args, value) => [{
4034
+ type: "text",
4035
+ text: value
4036
+ }]
4037
+ },
4038
+ async execute(args, exec) {
4039
+ const task = detectTask({
4040
+ explicit: args.taskTag,
4041
+ goal: args.goal,
4042
+ agent: exec.agent
4043
+ });
4044
+ const compat = await analyzeCompatibility(ctx, deps.config, {
4045
+ scope: "current",
4046
+ includeInfo: true,
4047
+ writeReport: true,
4048
+ agent: exec.agent,
4049
+ toolSet: exec.toolSet
4050
+ });
4051
+ const scan = await scanPlugins({
4052
+ config: deps.config,
4053
+ compat,
4054
+ pluginManager: getPluginManager(ctx),
4055
+ inventory: await inventoryOf$1(ctx),
4056
+ usageLedger: deps.ledger,
4057
+ task,
4058
+ agent: exec.agent
4059
+ });
4060
+ let profile = buildSlimProfile(scan, task, deps.config, {
4061
+ includeReview: args.includeReview,
4062
+ maxDisable: args.maxDisable
4063
+ });
4064
+ profile = attachFindings(profile, scan);
4065
+ let saved = true;
4066
+ try {
4067
+ await saveDraft(profile, deps.config.maxDrafts);
4068
+ } catch {
4069
+ saved = false;
4070
+ }
4071
+ await audit("suggest_profile", saved ? "ok" : "fail", `draft ${profile.id}: ${profile.summary.disable} disable / ${profile.summary.enable} enable / ${profile.summary.review} review`);
4072
+ return renderSuggest(profile, scan, saved);
4073
+ },
4074
+ presentCall: () => ({
4075
+ card: "generic",
4076
+ title: "Suggest slim profile",
4077
+ kind: "read"
4078
+ })
4079
+ }));
4080
+ }
4081
+ function registerApplyTool(ctx, deps) {
4082
+ ctx.tools.register(defineTool({
4083
+ name: "trim_apply_profile",
4084
+ description: "Apply low-risk keep/enable/disable items from a saved slim-profile draft. Requires confirm: true and must be called only after the user explicitly approved the exact profileId and items in this conversation. Protected/core/preset items are never changed. Returns a rollback token. Only low-risk disables/enables are applied; compatibility errors can block an item.",
4085
+ parameters: {
4086
+ profileId: {
4087
+ type: "string",
4088
+ required: true,
4089
+ description: "The profileId returned by trim_suggest_profile."
4090
+ },
4091
+ confirm: {
4092
+ type: "boolean",
4093
+ required: true,
4094
+ description: "Must be true only after explicit user approval of the exact draft."
4095
+ },
4096
+ items: {
4097
+ type: "array",
4098
+ items: { type: "string" },
4099
+ description: "Optional subset of item ids to apply. Omit to apply all eligible items."
4100
+ }
4101
+ },
4102
+ output: {
4103
+ schema: { type: "string" },
4104
+ render: (_args, value) => [{
4105
+ type: "text",
4106
+ text: value
4107
+ }]
4108
+ },
4109
+ async execute(args, exec) {
4110
+ if (args.confirm !== true) return "❌ 应用精简方案需要用户明确确认:请先让用户批准具体的 profileId 与 items,再调用 `trim_apply_profile({ profileId, confirm: true })`。";
4111
+ const manager = getPluginManager(ctx);
4112
+ if (manager === void 0) return "❌ 当前 profile 没有可用的 pluginManager,无法应用精简方案。请改用 `trim_scan_plugins` 只读查看。";
4113
+ const compat = await analyzeCompatibility(ctx, deps.config, {
4114
+ scope: "current",
4115
+ includeInfo: true,
4116
+ writeReport: true,
4117
+ force: true,
4118
+ agent: exec.agent,
4119
+ toolSet: exec.toolSet
4120
+ });
4121
+ try {
4122
+ const result = await applySlimProfile(args.profileId, {
4123
+ confirm: args.confirm,
4124
+ items: args.items,
4125
+ manager,
4126
+ maxDrafts: deps.config.maxDrafts,
4127
+ findings: compat.findings,
4128
+ profileName: resolveProfileFacts(ctx, exec.agent).name
4129
+ });
4130
+ await audit("apply_profile", "ok", `applied ${result.items.length} items`);
4131
+ return renderApply(result);
4132
+ } catch (error) {
4133
+ if (error instanceof ApplyRefusedError) return `❌ ${error.message}`;
4134
+ return `❌ 应用失败:${error instanceof Error ? error.message : String(error)}`;
4135
+ }
4136
+ },
4137
+ presentCall: () => ({
4138
+ card: "generic",
4139
+ title: "Apply slim profile",
4140
+ kind: "other"
4141
+ })
4142
+ }));
4143
+ }
4144
+ function registerRollbackTool(ctx, deps) {
4145
+ ctx.tools.register(defineTool({
4146
+ name: "trim_rollback_profile",
4147
+ description: "Restore plugin enablement from a previous trim apply snapshot. Omit token to use the latest snapshot. Skips items already restored or changed outside trim. Returns per-item results.",
4148
+ parameters: { token: {
4149
+ type: "string",
4150
+ description: "Rollback token returned by trim_apply_profile. Omit for the latest snapshot."
4151
+ } },
4152
+ output: {
4153
+ schema: { type: "string" },
4154
+ render: (_args, value) => [{
4155
+ type: "text",
4156
+ text: value
4157
+ }]
4158
+ },
4159
+ async execute(args) {
4160
+ const manager = getPluginManager(ctx);
4161
+ if (manager === void 0) return "❌ 当前 profile 没有可用的 pluginManager,无法回滚。";
4162
+ try {
4163
+ const result = await rollbackSlimProfile({
4164
+ token: args.token,
4165
+ manager,
4166
+ maxDrafts: deps.config.maxDrafts,
4167
+ profileName: resolveProfileFacts(ctx).name
4168
+ });
4169
+ await audit("rollback_profile", "ok", `restored ${result.items.filter((item) => item.status === "restored").length} items`);
4170
+ return renderRollback(result);
4171
+ } catch (error) {
4172
+ return `❌ 回滚失败:${error instanceof Error ? error.message : String(error)}`;
4173
+ }
4174
+ },
4175
+ presentCall: () => ({
4176
+ card: "generic",
4177
+ title: "Rollback slim profile",
4178
+ kind: "other"
4179
+ })
4180
+ }));
4181
+ }
4182
+ async function inventoryOf$1(ctx) {
4183
+ const adapter = getInventory(ctx);
4184
+ if (adapter === void 0) return void 0;
4185
+ try {
4186
+ return await adapter.list();
4187
+ } catch {
4188
+ return;
4189
+ }
4190
+ }
4191
+ async function audit(action, result, summary) {
4192
+ await new AuditLog().append({
4193
+ t: (/* @__PURE__ */ new Date()).toISOString(),
4194
+ actor: "trim",
4195
+ action,
4196
+ subject: "trim",
4197
+ result,
4198
+ summary
4199
+ }).catch(() => void 0);
4200
+ }
4201
+ function renderScan(scan, maxRows) {
4202
+ const lines = [];
4203
+ lines.push("# 插件与上下文扫描");
4204
+ lines.push("");
4205
+ lines.push(`- 管理可用:${scan.managementAvailable ? "是" : "否(只读模式)"}`);
4206
+ lines.push(`- 兼容性:${scan.compat.summary.error} error / ${scan.compat.summary.warn} warn / ${scan.compat.summary.info} info`);
4207
+ lines.push(`- 可归属上下文:${scan.context.totalTokens} tokens(未归属 ${scan.context.unattributedTokens})`);
4208
+ lines.push("");
4209
+ if (scan.compat.topFindings.length > 0) {
4210
+ lines.push("## 兼容性摘要");
4211
+ lines.push("");
4212
+ for (const finding of scan.compat.topFindings) lines.push(`- **${finding.severity.toUpperCase()} ${finding.code}** ${finding.title}`);
4213
+ lines.push("");
4214
+ }
4215
+ lines.push("## 上下文成本 Top");
4216
+ lines.push("");
4217
+ lines.push("| 名称 | 类型 | owner | tokens |");
4218
+ lines.push("|---|---|---|---|");
4219
+ const costs = [...scan.context.sections.map((section) => ({
4220
+ name: section.name,
4221
+ kind: section.source,
4222
+ owner: section.owner ?? "unattributed",
4223
+ tokens: section.tokens
4224
+ })), ...scan.context.tools.map((tool) => ({
4225
+ name: tool.name,
4226
+ kind: "tool",
4227
+ owner: tool.owner ?? "unattributed",
4228
+ tokens: tool.tokens
4229
+ }))].sort((a, b) => b.tokens - a.tokens).slice(0, maxRows);
4230
+ for (const cost of costs) lines.push(`| ${escapeMarkdownCell(cost.name)} | ${cost.kind} | ${escapeMarkdownCell(cost.owner)} | ${cost.tokens} |`);
4231
+ if (costs.length === 0) lines.push("| (无可归属项) | — | — | 0 |");
4232
+ lines.push("");
4233
+ lines.push("## Bundles");
4234
+ lines.push("");
4235
+ lines.push("| bundle | enabled | protected | guard | tokens | calls | 描述 |");
4236
+ lines.push("|---|---|---|---|---|---|---|");
4237
+ const sortedBundles = [...scan.bundles].sort((a, b) => b.contextTokens - a.contextTokens || Number(b.enabled) - Number(a.enabled));
4238
+ for (const bundle of sortedBundles.slice(0, maxRows)) lines.push(`| ${escapeMarkdownCell(bundle.name)} | ${bundle.enabled ? "yes" : "no"} | ${bundle.protected ? "yes" : "no"} | ${bundle.guardStatus} | ${bundle.contextTokens} | ${bundle.usage.calls + bundle.usage.sessionCalls} | ${escapeMarkdownCell(truncate(bundle.description ?? "", 80))} |`);
4239
+ if (scan.bundles.length === 0) lines.push("| (无) | — | — | — | 0 | 0 | — |");
4240
+ lines.push("");
4241
+ lines.push("## Entries");
4242
+ lines.push("");
4243
+ lines.push("| entry | module | enabled | phase | guard | tokens |");
4244
+ lines.push("|---|---|---|---|---|---|");
4245
+ const sortedEntries = [...scan.entries].sort((a, b) => b.contextTokens - a.contextTokens);
4246
+ for (const entry of sortedEntries.slice(0, maxRows)) lines.push(`| ${escapeMarkdownCell(entry.entryId)} | ${escapeMarkdownCell(entry.moduleName)} | ${entry.enabled ? "yes" : "no"} | ${entry.fiberPhase ?? "—"} | ${entry.guardStatus} | ${entry.contextTokens} |`);
4247
+ if (scan.entries.length === 0) lines.push("| (无) | — | — | — | — | 0 |");
4248
+ lines.push("");
4249
+ if (scan.presetModules.length > 0) {
4250
+ lines.push("## Agent preset 提供(trim 不可单独开关)");
4251
+ lines.push("");
4252
+ lines.push(`- ${scan.presetModules.slice(0, 30).join(", ")}${scan.presetModules.length > 30 ? ` … 共 ${scan.presetModules.length} 个` : ""}`);
4253
+ lines.push("");
4254
+ }
4255
+ if (scan.dedupe.length > 0) {
4256
+ lines.push("## 跨插件 prompt 重复");
4257
+ lines.push("");
4258
+ lines.push("| 权威 section | 其他 section | 冲突 | 说明 |");
4259
+ lines.push("|---|---|---|---|");
4260
+ for (const group of scan.dedupe.slice(0, 10)) {
4261
+ const others = group.members.filter((member) => member.section !== group.authority).map((member) => member.section);
4262
+ lines.push(`| ${escapeMarkdownCell(group.authority)} | ${escapeMarkdownCell(others.join(", "))} | ${group.conflict ? "yes" : "no"} | ${escapeMarkdownCell(group.reason)} |`);
4263
+ }
4264
+ lines.push("");
4265
+ }
4266
+ if (scan.diagnostics.length > 0) {
4267
+ lines.push("## 诊断");
4268
+ lines.push("");
4269
+ for (const diagnostic of scan.diagnostics.slice(0, 20)) lines.push(`- ${diagnostic}`);
4270
+ lines.push("");
4271
+ }
4272
+ lines.push(jsonBlock({
4273
+ bundles: scan.bundles.length,
4274
+ entries: scan.entries.length,
4275
+ totalTokens: scan.context.totalTokens,
4276
+ unattributedTokens: scan.context.unattributedTokens,
4277
+ compat: scan.compat.summary,
4278
+ dedupeGroups: scan.dedupe.length
4279
+ }, 4e3));
4280
+ lines.push("");
4281
+ lines.push("> 未修改任何插件状态。需要可执行建议时调用 `trim_suggest_profile`。");
4282
+ return lines.join("\n");
4283
+ }
4284
+ function renderSuggest(profile, scan, saved = true) {
4285
+ const lines = [];
4286
+ lines.push("# 精简方案草稿");
4287
+ lines.push("");
4288
+ if (!saved) {
4289
+ lines.push("⚠️ 草稿未能写入本地数据目录;以下建议仍可阅读,但无法通过 trim_apply_profile 应用。请检查 DSH_HOME 权限。");
4290
+ lines.push("");
4291
+ }
4292
+ lines.push(`- 任务:**${profile.task.tag}**(置信度 ${profile.task.confidence.toFixed(2)},来源 ${profile.task.source})`);
4293
+ lines.push(`- 摘要:保留 ${profile.summary.keep} / 启用 ${profile.summary.enable} / 禁用 ${profile.summary.disable} / 复核 ${profile.summary.review} / 受保护 ${profile.summary.protected}`);
4294
+ lines.push(`- 兼容性:${scan.compat.summary.error} error / ${scan.compat.summary.warn} warn / ${scan.compat.summary.info} info`);
4295
+ if (!scan.managementAvailable) {
4296
+ lines.push("");
4297
+ lines.push("⚠️ 当前 profile 没有可用的 pluginManager;本方案仅供只读参考,无法通过 trim_apply_profile 应用。");
4298
+ }
4299
+ lines.push("");
4300
+ lines.push("## 任务证据");
4301
+ lines.push("");
4302
+ for (const evidence of profile.task.evidence.slice(0, 6)) lines.push(`- ${evidence.summary}`);
4303
+ lines.push("");
4304
+ const actionable = profile.items.filter((item) => item.action !== "keep").slice(0, 30);
4305
+ if (actionable.length > 0) {
4306
+ lines.push("## 建议");
4307
+ lines.push("");
4308
+ lines.push("| item | action | risk | score | 关键证据 |");
4309
+ lines.push("|---|---|---|---|---|");
4310
+ for (const item of actionable) lines.push(`| ${escapeMarkdownCell(item.id)} | ${item.action} | ${item.risk} | ${item.score} | ${escapeMarkdownCell(item.evidence.slice(0, 3).map((evidence) => evidence.summary).join(";"))} |`);
4311
+ lines.push("");
4312
+ } else {
4313
+ lines.push("没有需要变更的项;当前插件集合看起来已经合适。");
4314
+ lines.push("");
4315
+ }
4316
+ if (profile.dedupe.length > 0) {
4317
+ lines.push("## 去重建议");
4318
+ lines.push("");
4319
+ for (const group of profile.dedupe.slice(0, 10)) lines.push(`- 保留 **${group.authority}**;其余 ${group.members.filter((member) => member.section !== group.authority).map((member) => member.section).join(", ")}(${group.conflict ? "存在冲突,仅标记" : "建议引用/摘要"})`);
4320
+ lines.push("");
4321
+ }
4322
+ lines.push("## 可应用项");
4323
+ lines.push("");
4324
+ const eligible = profile.items.filter((item) => item.protected === false && item.risk === "low" && (item.action === "suggest-disable" || item.action === "enable"));
4325
+ if (eligible.length === 0) lines.push("没有低风险可应用项;以上建议仅供人工复核。");
4326
+ else for (const item of eligible) lines.push(`- ${item.id}:${item.action}`);
4327
+ lines.push("");
4328
+ lines.push(`profileId: \`${profile.id}\``);
4329
+ lines.push("");
4330
+ lines.push("> 未修改任何插件状态。仅在用户明确同意上述 profileId 与具体 items 后,才调用 `trim_apply_profile({ profileId, confirm: true })`。");
4331
+ lines.push("");
4332
+ lines.push(jsonBlock({
4333
+ profileId: profile.id,
4334
+ task: profile.task,
4335
+ summary: profile.summary,
4336
+ eligible: eligible.map((item) => ({
4337
+ id: item.id,
4338
+ action: item.action
4339
+ })),
4340
+ compat: scan.compat.summary
4341
+ }, 6e3));
4342
+ return lines.join("\n");
4343
+ }
4344
+ function renderApply(result) {
4345
+ const lines = [];
4346
+ lines.push("# 应用结果");
4347
+ lines.push("");
4348
+ lines.push("| item | status | application | 说明 |");
4349
+ lines.push("|---|---|---|---|");
4350
+ for (const item of result.items) lines.push(`| ${escapeMarkdownCell(item.id)} | ${item.status} | ${item.application ?? "—"} | ${escapeMarkdownCell(item.error ?? item.fixKind ?? "")} |`);
4351
+ if (result.items.length === 0) lines.push("| (无可应用项) | — | — | — |");
4352
+ lines.push("");
4353
+ if (result.token !== void 0) lines.push(`rollbackToken: \`${result.token}\``);
4354
+ if (result.rolledBack === true) lines.push("⚠️ 应用中途失败,已自动回滚本次已成功项。");
4355
+ if (result.restartRequired === true) lines.push("⚠️ 部分变更需要重启 DSH 后生效。");
4356
+ lines.push("");
4357
+ if (result.token !== void 0) lines.push("如需恢复:`trim_rollback_profile({ token })`。");
4358
+ return lines.join("\n");
4359
+ }
4360
+ function renderRollback(result) {
4361
+ const lines = [];
4362
+ lines.push("# 回滚结果");
4363
+ lines.push("");
4364
+ lines.push("| item | status | 说明 |");
4365
+ lines.push("|---|---|---|");
4366
+ for (const item of result.items) lines.push(`| ${escapeMarkdownCell(item.id)} | ${item.status} | ${escapeMarkdownCell(item.error ?? "")} |`);
4367
+ if (result.items.length === 0) lines.push("| (无) | — | — |");
4368
+ lines.push("");
4369
+ lines.push(`token: \`${result.token}\``);
4370
+ return lines.join("\n");
4371
+ }
4372
+ // src/compat/tool.ts
4373
+ /** Register the read-only compatibility analysis tool. */
4374
+ function registerCompatTool(ctx, config) {
4375
+ ctx.tools.register(defineTool({
4376
+ name: "trim_analyze_compatibility",
4377
+ description: "Read-only compatibility analysis for the current DSH profile: plugin-plugin conflicts (services, rows, configs, MCP namespaces, registrations), plugin-runtime mismatches (engines, peers, Node, platform, exemptions), and profile/workspace drift. Returns a compatibility matrix and writes a local JSON report. Never changes plugin enablement, grants exemptions, or edits patches.",
4378
+ parameters: {
4379
+ scope: {
4380
+ type: "string",
4381
+ enum: [
4382
+ "current",
4383
+ "profiles",
4384
+ "all"
4385
+ ],
4386
+ description: "current: this profile only; profiles: also compare all profiles under $DSH_HOME/profiles; all: profiles plus workspace instruction overlap."
4387
+ },
4388
+ includeInfo: {
4389
+ type: "boolean",
4390
+ description: "Include info-level findings in the Markdown matrix; the JSON report always keeps them."
4391
+ },
4392
+ maxFindings: {
4393
+ type: "integer",
4394
+ description: "Maximum findings in the report, 1..500. Defaults to the configured limit."
4395
+ },
4396
+ writeReport: {
4397
+ type: "boolean",
4398
+ description: "Write the JSON report to $DSH_HOME/experience-optimizer/compat/report.json. Default true."
4399
+ }
4400
+ },
4401
+ output: {
4402
+ schema: { type: "string" },
4403
+ render: (_args, value) => [{
4404
+ type: "text",
4405
+ text: value
4406
+ }]
4407
+ },
4408
+ async execute(args, exec) {
4409
+ const result = await analyzeCompatibility(ctx, config, {
4410
+ scope: args.scope ?? "current",
4411
+ includeInfo: args.includeInfo,
4412
+ maxFindings: args.maxFindings,
4413
+ writeReport: args.writeReport,
4414
+ agent: exec.agent,
4415
+ toolSet: exec.toolSet
4416
+ });
4417
+ return `${[
4418
+ "> 兼容性分析为只读操作,未修改任何插件、patch 或豁免。",
4419
+ result.reportPath === void 0 ? "" : `> 报告文件:${result.reportPath}`,
4420
+ ""
4421
+ ].filter((line) => line.length > 0).join("\n")}\n\n${result.markdown}`;
4422
+ },
4423
+ presentCall: () => ({
4424
+ card: "generic",
4425
+ title: "Analyze plugin compatibility",
4426
+ kind: "read"
4427
+ })
4428
+ }));
4429
+ }
4430
+ // src/api.ts
4431
+ const API_PREFIX = "/api/dsh-experience-optimizer";
4432
+ const TASK_TAGS = [
4433
+ "bugfix",
4434
+ "feature",
4435
+ "review",
4436
+ "docs",
4437
+ "release",
4438
+ "report",
4439
+ "research",
4440
+ "unknown"
4441
+ ];
4442
+ /** Register the same-origin JSON API used by the Web client panel. */
4443
+ function registerTrimApi(ctx, config, ledger) {
4444
+ if (typeof ctx.inject !== "function") return;
4445
+ ctx.inject(["webServer"], (webCtx) => {
4446
+ const server = webCtx.get("webServer");
4447
+ if (server === void 0) return;
4448
+ webCtx.effect(() => server.register({
4449
+ kind: "prefix",
4450
+ path: API_PREFIX,
4451
+ handler: (req, res) => handle(req, res, ctx, config, ledger)
4452
+ }), "trim.webApi");
4453
+ });
4454
+ }
4455
+ async function handle(req, res, ctx, config, ledger) {
4456
+ const connection = ctx.get("connection");
4457
+ if (connection === void 0 || typeof connection.requestRejection !== "function") {
4458
+ sendError(res, 401, "authentication unavailable");
4459
+ return;
4460
+ }
4461
+ let rejection;
4462
+ try {
4463
+ rejection = connection.requestRejection({ headers: req.headers });
4464
+ } catch {
4465
+ sendError(res, 401, "authentication failed");
4466
+ return;
4467
+ }
4468
+ if (rejection !== void 0) {
4469
+ sendError(res, rejection, "authentication required");
4470
+ return;
4471
+ }
4472
+ if (!isSameOrigin(req)) {
4473
+ sendError(res, 403, "cross-site request rejected");
4474
+ return;
4475
+ }
4476
+ const path = new URL(req.url ?? "/", "http://localhost").pathname.slice(29) || "/";
4477
+ try {
4478
+ if (req.method === "GET" && path === "/overview") {
4479
+ sendJson(res, 200, {
4480
+ ok: true,
4481
+ data: await overview(ctx, config, ledger)
4482
+ });
4483
+ return;
4484
+ }
4485
+ if (req.method === "POST" && path === "/suggest") {
4486
+ sendJson(res, 200, {
4487
+ ok: true,
4488
+ data: await suggest(ctx, config, ledger, await readJsonBody(req))
4489
+ });
4490
+ return;
4491
+ }
4492
+ if (req.method === "POST" && path === "/apply") {
4493
+ sendJson(res, 200, {
4494
+ ok: true,
4495
+ data: await apply$1(ctx, config, await readJsonBody(req))
4496
+ });
4497
+ return;
4498
+ }
4499
+ if (req.method === "POST" && path === "/rollback") {
4500
+ sendJson(res, 200, {
4501
+ ok: true,
4502
+ data: await rollback(ctx, config, await readJsonBody(req))
4503
+ });
4504
+ return;
4505
+ }
4506
+ sendError(res, 404, `unknown endpoint ${path}`);
4507
+ } catch (error) {
4508
+ sendError(res, 500, error instanceof Error ? error.message : String(error));
4509
+ }
4510
+ }
4511
+ async function overview(ctx, config, ledger) {
4512
+ const compat = await analyzeCompatibility(ctx, config, {
4513
+ scope: "current",
4514
+ includeInfo: true,
4515
+ writeReport: false
4516
+ });
4517
+ const scan = await scanPlugins({
4518
+ config,
4519
+ compat,
4520
+ pluginManager: getPluginManager(ctx),
4521
+ inventory: await inventoryOf(ctx),
4522
+ usageLedger: ledger
4523
+ });
4524
+ const byOwner = Object.entries(scan.context.byOwner).map(([owner, tokens]) => ({
4525
+ owner,
4526
+ tokens
4527
+ })).sort((a, b) => b.tokens - a.tokens).slice(0, 12);
4528
+ return {
4529
+ runtime: compat.report.runtime,
4530
+ profile: compat.report.profile,
4531
+ compat: compat.report.summary,
4532
+ findings: compat.findings.map(toFinding),
4533
+ context: {
4534
+ totalTokens: scan.context.totalTokens,
4535
+ unattributedTokens: scan.context.unattributedTokens,
4536
+ topSections: [...scan.context.sections].sort((a, b) => b.tokens - a.tokens).slice(0, 12),
4537
+ topTools: [...scan.context.tools].sort((a, b) => b.tokens - a.tokens).slice(0, 12),
4538
+ byOwner
4539
+ },
4540
+ bundles: [...scan.bundles].sort((a, b) => b.contextTokens - a.contextTokens).slice(0, 80).map((bundle) => ({
4541
+ name: bundle.name,
4542
+ version: bundle.version,
4543
+ enabled: bundle.enabled,
4544
+ protected: bundle.protected,
4545
+ guardStatus: bundle.guardStatus,
4546
+ contextTokens: bundle.contextTokens,
4547
+ usage: bundle.usage,
4548
+ description: bundle.description
4549
+ })),
4550
+ entries: [...scan.entries].sort((a, b) => b.contextTokens - a.contextTokens).slice(0, 60).map((entry) => ({
4551
+ entryId: entry.entryId,
4552
+ moduleName: entry.moduleName,
4553
+ bundleName: entry.bundleName,
4554
+ enabled: entry.enabled,
4555
+ fiberPhase: entry.fiberPhase,
4556
+ guardStatus: entry.guardStatus,
4557
+ contextTokens: entry.contextTokens
4558
+ })),
4559
+ dedupe: scan.dedupe,
4560
+ managementAvailable: scan.managementAvailable,
4561
+ diagnostics: scan.diagnostics
4562
+ };
4563
+ }
4564
+ async function suggest(ctx, config, ledger, body) {
4565
+ const task = detectTask({
4566
+ explicit: typeof body.taskTag === "string" && TASK_TAGS.includes(body.taskTag) ? body.taskTag : void 0,
4567
+ goal: typeof body.goal === "string" ? body.goal : void 0
4568
+ });
4569
+ const compat = await analyzeCompatibility(ctx, config, {
4570
+ scope: "current",
4571
+ includeInfo: true,
4572
+ writeReport: true
4573
+ });
4574
+ const scan = await scanPlugins({
4575
+ config,
4576
+ compat,
4577
+ pluginManager: getPluginManager(ctx),
4578
+ inventory: await inventoryOf(ctx),
4579
+ usageLedger: ledger,
4580
+ task
4581
+ });
4582
+ let profile = buildSlimProfile(scan, task, config, {
4583
+ includeReview: body.includeReview !== false,
4584
+ maxDisable: typeof body.maxDisable === "number" ? body.maxDisable : void 0
4585
+ });
4586
+ profile = attachFindings(profile, scan);
4587
+ await saveDraft(profile, config.maxDrafts);
4588
+ return {
4589
+ profile,
4590
+ compat: compat.report.summary,
4591
+ scan: {
4592
+ totalTokens: scan.context.totalTokens,
4593
+ unattributedTokens: scan.context.unattributedTokens,
4594
+ managementAvailable: scan.managementAvailable
4595
+ },
4596
+ findings: compat.findings.map(toFinding)
4597
+ };
4598
+ }
4599
+ async function apply$1(ctx, config, body) {
4600
+ if (body.confirm !== true) throw new ApplyRefusedError("confirm must be true");
4601
+ const profileId = typeof body.profileId === "string" ? body.profileId : "";
4602
+ if (profileId.length === 0) throw new Error("profileId is required");
4603
+ const manager = getPluginManager(ctx);
4604
+ if (manager === void 0) throw new Error("pluginManager is unavailable");
4605
+ const items = Array.isArray(body.items) ? body.items.filter((item) => typeof item === "string") : void 0;
4606
+ const compat = await analyzeCompatibility(ctx, config, {
4607
+ scope: "current",
4608
+ includeInfo: true,
4609
+ writeReport: true,
4610
+ force: true
4611
+ });
4612
+ return applySlimProfile(profileId, {
4613
+ confirm: true,
4614
+ items,
4615
+ manager,
4616
+ maxDrafts: config.maxDrafts,
4617
+ findings: compat.findings,
4618
+ profileName: resolveProfileFacts(ctx).name
4619
+ });
4620
+ }
4621
+ async function rollback(ctx, config, body) {
4622
+ const manager = getPluginManager(ctx);
4623
+ if (manager === void 0) throw new Error("pluginManager is unavailable");
4624
+ return rollbackSlimProfile({
4625
+ token: typeof body.token === "string" && body.token.length > 0 ? body.token : void 0,
4626
+ manager,
4627
+ maxDrafts: config.maxDrafts,
4628
+ profileName: resolveProfileFacts(ctx).name
4629
+ });
4630
+ }
4631
+ async function inventoryOf(ctx) {
4632
+ const adapter = getInventory(ctx);
4633
+ if (adapter === void 0) return void 0;
4634
+ try {
4635
+ return await adapter.list();
4636
+ } catch {
4637
+ return;
4638
+ }
4639
+ }
4640
+ function toFinding(finding) {
4641
+ return {
4642
+ code: finding.code,
4643
+ severity: finding.severity,
4644
+ domain: finding.domain,
4645
+ title: finding.title,
4646
+ subjects: finding.subjects,
4647
+ confidence: finding.confidence,
4648
+ fix: finding.fix,
4649
+ evidence: finding.evidence
4650
+ };
4651
+ }
4652
+ // src/index.ts
4653
+ const name = "dsh-plugin-trim";
4654
+ const inject = ["tools"];
4655
+ /** Register trim tools and the local usage observer. */
4656
+ function apply(ctx, config) {
4657
+ const resolved = normalizeConfig(config);
4658
+ const ledger = new UsageLedger({
4659
+ retentionDays: resolved.usageRetentionDays,
4660
+ enabled: resolved.trackUsage
4661
+ });
4662
+ if (resolved.trackUsage) ctx.on("tools/result", (exec, result) => {
4663
+ if (exec.name.startsWith("trim_") || exec.name.startsWith("recipe_")) return;
4664
+ try {
4665
+ ledger.record(exec.name, !result.isError);
4666
+ } catch {}
4667
+ });
4668
+ ctx.effect(() => () => ledger.dispose(), "trim.usage.flush");
4669
+ registerTrimTools(ctx, {
4670
+ config: resolved,
4671
+ ledger
4672
+ });
4673
+ registerCompatTool(ctx, resolved);
4674
+ registerTrimApi(ctx, resolved, ledger);
4675
+ }
4676
+ export { Config, analyzeCompatibility, apply, applySlimProfile, buildReport, buildSlimProfile, collectCompatContext, detectTask, inject, name, renderReport, rollbackSlimProfile, runCompatibilityRules, scanPlugins };