claudepluginhub 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1036 @@
1
+ import { accessSync, constants, existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync, } from 'node:fs';
2
+ import { basename, delimiter, join, resolve } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { isWithin, canonicalize } from './paths.js';
5
+ import { boundName, sanitizeCommand, sanitizeUrlOrigin } from './sanitize.js';
6
+ import { VALID_NAME_RE } from '../validation.js';
7
+ export const DEFAULT_LIMITS = {
8
+ maxPlugins: 200,
9
+ maxFilesPerPlugin: 2000,
10
+ maxFileBytes: 512 * 1024,
11
+ maxPluginBytes: 32 * 1024 * 1024,
12
+ maxTotalBytes: 128 * 1024 * 1024,
13
+ maxDepth: 12,
14
+ };
15
+ /** Documented tool-matched hook events (hooks reference). */
16
+ export const TOOL_MATCHED_EVENTS = new Set([
17
+ 'PreToolUse',
18
+ 'PostToolUse',
19
+ 'PostToolUseFailure',
20
+ 'PermissionRequest',
21
+ 'PermissionDenied',
22
+ ]);
23
+ const FRONTMATTER_MAX_LINES = 100;
24
+ const FRONTMATTER_MAX_BYTES = 16 * 1024;
25
+ const MAX_KEYS = 50;
26
+ /**
27
+ * Aggregate cap on hook/MCP/LSP/monitor facts per plugin. Parse helpers stop
28
+ * producing at MAX_FACTS_PER_TYPE + 1 so the scanner can DETECT the overflow
29
+ * and flag it ('max-facts' → scan_incomplete) instead of capping silently.
30
+ */
31
+ export const MAX_FACTS_PER_TYPE = 100;
32
+ export function createScanner(overrides) {
33
+ const limits = { ...DEFAULT_LIMITS, ...overrides };
34
+ const memo = new Map();
35
+ let pluginsScanned = 0;
36
+ let totalBytesRead = 0;
37
+ let truncated = false;
38
+ function emptyManifest() {
39
+ return {
40
+ present: false,
41
+ inspected: false,
42
+ parseError: false,
43
+ name: null,
44
+ nameInvalid: false,
45
+ invalidFields: [],
46
+ declaredMissing: [],
47
+ dependencies: [],
48
+ };
49
+ }
50
+ function emptyResult() {
51
+ return {
52
+ pathIssue: null,
53
+ manifest: emptyManifest(),
54
+ components: [],
55
+ themeFiles: [],
56
+ hooks: [],
57
+ mcp: [],
58
+ lsp: [],
59
+ monitors: [],
60
+ bin: [],
61
+ parseErrors: [],
62
+ symlinksSkipped: [],
63
+ filesScanned: 0,
64
+ bytesRead: 0,
65
+ limitsHit: [],
66
+ incomplete: false,
67
+ };
68
+ }
69
+ function readBounded(absPath, size, state) {
70
+ if (size > limits.maxFileBytes) {
71
+ state.limitsHit.add('max-file-bytes');
72
+ state.incomplete = true;
73
+ return null;
74
+ }
75
+ if (state.bytesRead + size > limits.maxPluginBytes) {
76
+ state.limitsHit.add('max-plugin-bytes');
77
+ state.incomplete = true;
78
+ return null;
79
+ }
80
+ if (totalBytesRead + size > limits.maxTotalBytes) {
81
+ state.limitsHit.add('max-total-bytes');
82
+ state.incomplete = true;
83
+ truncated = true;
84
+ return null;
85
+ }
86
+ let content;
87
+ try {
88
+ content = readFileSync(absPath, 'utf-8');
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ state.bytesRead += size;
94
+ totalBytesRead += size;
95
+ return content;
96
+ }
97
+ /**
98
+ * Deterministic bounded walk. Calls visit(relPath, absPath, size) for every
99
+ * regular file reached. Returns false when a budget aborted the walk.
100
+ */
101
+ function walk(rootCanonical, startRel, state, visit) {
102
+ const visitedDirs = new Set();
103
+ function recurse(dirAbs, dirRel, depth) {
104
+ let entries;
105
+ try {
106
+ entries = readdirSync(dirAbs).sort();
107
+ }
108
+ catch {
109
+ return true;
110
+ }
111
+ for (const entry of entries) {
112
+ const abs = join(dirAbs, entry);
113
+ const rel = dirRel ? `${dirRel}/${entry}` : entry;
114
+ if (state.filesScanned >= limits.maxFilesPerPlugin) {
115
+ state.limitsHit.add('max-files');
116
+ state.incomplete = true;
117
+ return false;
118
+ }
119
+ let info;
120
+ try {
121
+ info = lstatSync(abs);
122
+ }
123
+ catch {
124
+ continue;
125
+ }
126
+ let targetAbs = abs;
127
+ let isDir = info.isDirectory();
128
+ let isFile = info.isFile();
129
+ let size = info.size;
130
+ if (info.isSymbolicLink()) {
131
+ let real;
132
+ try {
133
+ real = realpathSync(abs);
134
+ }
135
+ catch {
136
+ state.symlinksSkipped.push(rel);
137
+ state.incomplete = true;
138
+ continue;
139
+ }
140
+ if (!isWithin(rootCanonical, real)) {
141
+ state.symlinksSkipped.push(rel);
142
+ state.incomplete = true;
143
+ continue;
144
+ }
145
+ let realInfo;
146
+ try {
147
+ realInfo = statSync(real);
148
+ }
149
+ catch {
150
+ state.symlinksSkipped.push(rel);
151
+ state.incomplete = true;
152
+ continue;
153
+ }
154
+ targetAbs = real;
155
+ isDir = realInfo.isDirectory();
156
+ isFile = realInfo.isFile();
157
+ size = realInfo.size;
158
+ }
159
+ if (isDir) {
160
+ if (depth + 1 > limits.maxDepth) {
161
+ state.limitsHit.add('max-depth');
162
+ state.incomplete = true;
163
+ continue;
164
+ }
165
+ const canonicalDir = info.isSymbolicLink() ? targetAbs : abs;
166
+ if (visitedDirs.has(canonicalDir))
167
+ continue; // cycle guard
168
+ visitedDirs.add(canonicalDir);
169
+ if (!recurse(targetAbs, rel, depth + 1))
170
+ return false;
171
+ }
172
+ else if (isFile) {
173
+ state.filesScanned += 1;
174
+ visit(rel, targetAbs, size);
175
+ }
176
+ }
177
+ return true;
178
+ }
179
+ // Unconditional realpath containment before any traversal: catches both
180
+ // a symlinked start entry and a symlink on an INTERMEDIATE component of
181
+ // the declared path (lstat on the final entry alone would miss it).
182
+ const startReal = containedReal(rootCanonical, startRel, state);
183
+ if (startReal === null)
184
+ return;
185
+ let startInfo;
186
+ try {
187
+ startInfo = statSync(startReal);
188
+ }
189
+ catch {
190
+ return;
191
+ }
192
+ if (startInfo.isDirectory()) {
193
+ visitedDirs.add(startReal);
194
+ recurse(startReal, startRel, 1);
195
+ }
196
+ else if (startInfo.isFile()) {
197
+ if (state.filesScanned < limits.maxFilesPerPlugin) {
198
+ state.filesScanned += 1;
199
+ visit(startRel, startReal, startInfo.size);
200
+ }
201
+ }
202
+ }
203
+ function scan(installPath) {
204
+ const rootCanonical = canonicalize(installPath);
205
+ const memoized = memo.get(rootCanonical);
206
+ if (memoized)
207
+ return memoized;
208
+ const result = emptyResult();
209
+ if (pluginsScanned >= limits.maxPlugins) {
210
+ result.limitsHit = ['max-plugins'];
211
+ result.incomplete = true;
212
+ truncated = true;
213
+ memo.set(rootCanonical, result);
214
+ return result;
215
+ }
216
+ let rootInfo;
217
+ try {
218
+ rootInfo = statSync(rootCanonical);
219
+ }
220
+ catch {
221
+ result.pathIssue = 'missing';
222
+ memo.set(rootCanonical, result);
223
+ return result;
224
+ }
225
+ if (!rootInfo.isDirectory()) {
226
+ result.pathIssue = 'not-directory';
227
+ memo.set(rootCanonical, result);
228
+ return result;
229
+ }
230
+ try {
231
+ readdirSync(rootCanonical);
232
+ }
233
+ catch {
234
+ result.pathIssue = 'unreadable';
235
+ memo.set(rootCanonical, result);
236
+ return result;
237
+ }
238
+ pluginsScanned += 1;
239
+ const state = {
240
+ filesScanned: 0,
241
+ bytesRead: 0,
242
+ limitsHit: new Set(),
243
+ symlinksSkipped: [],
244
+ parseErrors: [],
245
+ incomplete: false,
246
+ };
247
+ // Direct reads (manifest, root SKILL.md, config files) go through the
248
+ // same containment and budgets as the walk: realpath must stay inside the
249
+ // canonical root (escapes are reported, never read), the per-plugin file
250
+ // count applies, and bytes are charged through readBounded.
251
+ const openDirect = (rel) => {
252
+ const opened = safeOpen(rootCanonical, rel, state);
253
+ if (!opened)
254
+ return { found: false, content: null };
255
+ if (state.filesScanned >= limits.maxFilesPerPlugin) {
256
+ state.limitsHit.add('max-files');
257
+ state.incomplete = true;
258
+ return { found: true, content: null };
259
+ }
260
+ state.filesScanned += 1;
261
+ return { found: true, content: readBounded(opened.abs, opened.size, state) };
262
+ };
263
+ scanPlugin(rootCanonical, state, result, (abs, size) => readBounded(abs, size, state), walk, openDirect);
264
+ result.filesScanned = state.filesScanned;
265
+ result.bytesRead = state.bytesRead;
266
+ result.limitsHit = [...state.limitsHit].sort();
267
+ result.symlinksSkipped = state.symlinksSkipped.sort();
268
+ result.parseErrors = state.parseErrors.sort();
269
+ result.incomplete = state.incomplete;
270
+ memo.set(rootCanonical, result);
271
+ return result;
272
+ }
273
+ return {
274
+ scan,
275
+ stats: () => ({
276
+ pluginsScanned,
277
+ filesScanned: [...memo.values()].reduce((sum, r) => sum + r.filesScanned, 0),
278
+ bytesRead: totalBytesRead,
279
+ truncated: truncated || [...memo.values()].some((r) => r.incomplete),
280
+ }),
281
+ };
282
+ }
283
+ /**
284
+ * Contained path resolution: the lexical resolve AND the realpath must both
285
+ * stay inside the canonical root. Applied unconditionally — a symlink on an
286
+ * INTERMEDIATE component ("bridge/commands" where bridge points outside)
287
+ * escapes even though the final entry is a plain file or directory, and only
288
+ * the realpath sees that. An escaping path is recorded as skipped and never
289
+ * touched; a missing path is simply absent (null without a report).
290
+ */
291
+ function containedReal(rootCanonical, rel, state) {
292
+ const lexical = resolve(rootCanonical, rel);
293
+ if (!isWithin(rootCanonical, lexical))
294
+ return null;
295
+ let real;
296
+ try {
297
+ real = realpathSync(lexical);
298
+ }
299
+ catch {
300
+ try {
301
+ lstatSync(lexical);
302
+ }
303
+ catch {
304
+ return null; // truly absent
305
+ }
306
+ // Exists but unresolvable (dangling link, loop) — report, don't hide.
307
+ state.symlinksSkipped.push(rel);
308
+ state.incomplete = true;
309
+ return null;
310
+ }
311
+ if (!isWithin(rootCanonical, real)) {
312
+ state.symlinksSkipped.push(rel);
313
+ state.incomplete = true;
314
+ return null;
315
+ }
316
+ return real;
317
+ }
318
+ function safeOpen(rootCanonical, rel, state) {
319
+ const real = containedReal(rootCanonical, rel, state);
320
+ if (real === null)
321
+ return null;
322
+ let info;
323
+ try {
324
+ info = statSync(real);
325
+ }
326
+ catch {
327
+ return null;
328
+ }
329
+ if (!info.isFile())
330
+ return null;
331
+ return { abs: real, size: info.size };
332
+ }
333
+ /**
334
+ * Cap a list of externally sourced items. Truncation NEVER happens silently:
335
+ * exceeding the cap records the given limit marker and marks the scan
336
+ * incomplete.
337
+ */
338
+ function boundList(items, state, marker) {
339
+ if (items.length > MAX_KEYS) {
340
+ state.limitsHit.add(marker);
341
+ state.incomplete = true;
342
+ return items.slice(0, MAX_KEYS);
343
+ }
344
+ return items;
345
+ }
346
+ /** Cap a manifest path list so a hostile manifest cannot fan out the scan. */
347
+ function boundPaths(paths, state) {
348
+ return boundList(paths, state, 'max-manifest-paths');
349
+ }
350
+ /**
351
+ * Whether a raw `skills` manifest value explicitly declares the plugin root
352
+ * ("." or "./"), checked BEFORE normalization — normalizeManifestPath strips
353
+ * "./" to "", so this must look at the raw strings (mirrors the platform's
354
+ * manifestIncludesRootPath).
355
+ */
356
+ function declaresRootPath(rawSkills) {
357
+ const values = typeof rawSkills === 'string' ? [rawSkills] : Array.isArray(rawSkills) ? rawSkills : [];
358
+ return values.some((v) => typeof v === 'string' && v.trim().replace(/\/+$/, '') === '.');
359
+ }
360
+ /** True when skills/ exists (contained) and has at least one entry. */
361
+ function skillsDirHasEntries(rootCanonical) {
362
+ try {
363
+ const real = realpathSync(join(rootCanonical, 'skills'));
364
+ if (!isWithin(rootCanonical, real))
365
+ return false;
366
+ return readdirSync(real).length > 0;
367
+ }
368
+ catch {
369
+ return false;
370
+ }
371
+ }
372
+ /** Strip a leading "./" and any trailing "/" from a manifest path. */
373
+ function normalizeManifestPath(value) {
374
+ let out = value.trim();
375
+ while (out.startsWith('./'))
376
+ out = out.slice(2);
377
+ while (out.endsWith('/'))
378
+ out = out.slice(0, -1);
379
+ return out;
380
+ }
381
+ function stringPaths(value) {
382
+ if (typeof value === 'string')
383
+ return value.trim() ? [normalizeManifestPath(value)] : [];
384
+ if (Array.isArray(value)) {
385
+ return value
386
+ .filter((v) => typeof v === 'string' && v.trim().length > 0)
387
+ .map(normalizeManifestPath);
388
+ }
389
+ return [];
390
+ }
391
+ /**
392
+ * Bounded single-line frontmatter reader. Not YAML: block scalars, multi-line
393
+ * values, or an unterminated fence make the file "not understood" — the
394
+ * component is then reported as unestimated rather than invalid.
395
+ */
396
+ export function parseFrontmatter(content) {
397
+ if (!content.startsWith('---'))
398
+ return { name: null, description: null, understood: true };
399
+ const slice = content.slice(0, FRONTMATTER_MAX_BYTES);
400
+ const lines = slice.split('\n');
401
+ let name = null;
402
+ let description = null;
403
+ let closed = false;
404
+ let blockScalar = false;
405
+ for (let i = 1; i < Math.min(lines.length, FRONTMATTER_MAX_LINES); i += 1) {
406
+ const line = lines[i];
407
+ if (line.trim() === '---') {
408
+ closed = true;
409
+ break;
410
+ }
411
+ const match = line.match(/^(name|description)\s*:\s*(.*)$/);
412
+ if (!match)
413
+ continue;
414
+ const value = match[2].trim();
415
+ if (value === '' || value === '|' || value === '>' || value.startsWith('|') || value.startsWith('>')) {
416
+ blockScalar = true;
417
+ continue;
418
+ }
419
+ const unquoted = value.replace(/^["']/, '').replace(/["']$/, '');
420
+ if (match[1] === 'name')
421
+ name = unquoted;
422
+ else
423
+ description = unquoted;
424
+ }
425
+ return { name, description, understood: closed && !blockScalar };
426
+ }
427
+ function normalizeForHash(content) {
428
+ return content.replace(/\r\n/g, '\n').replace(/\s+$/, '');
429
+ }
430
+ export function hashComponentContent(content) {
431
+ return createHash('sha256').update(normalizeForHash(content), 'utf-8').digest('hex');
432
+ }
433
+ function fileStem(relPath) {
434
+ const base = basename(relPath);
435
+ const dot = base.lastIndexOf('.');
436
+ return dot > 0 ? base.slice(0, dot) : base;
437
+ }
438
+ function buildComponent(type, relPath, content) {
439
+ if (content === null) {
440
+ return {
441
+ type,
442
+ relPath,
443
+ name: type === 'skill' ? basename(relPath) : fileStem(relPath),
444
+ description: null,
445
+ estimable: false,
446
+ nameDescChars: 0,
447
+ bodyChars: 0,
448
+ hash: null,
449
+ };
450
+ }
451
+ const frontmatter = parseFrontmatter(content);
452
+ const fallbackName = type === 'skill' ? basename(relPath.replace(/\/SKILL\.md$/, '')) : fileStem(relPath);
453
+ const name = frontmatter.name ?? (fallbackName === 'SKILL.md' ? 'skill' : fallbackName);
454
+ return {
455
+ type,
456
+ relPath,
457
+ name,
458
+ description: frontmatter.description,
459
+ estimable: frontmatter.understood,
460
+ nameDescChars: name.length + (frontmatter.description?.length ?? 0),
461
+ bodyChars: content.length,
462
+ hash: type === 'outputStyle' ? null : hashComponentContent(content),
463
+ };
464
+ }
465
+ function parseDependencies(raw) {
466
+ if (!Array.isArray(raw))
467
+ return [];
468
+ const out = [];
469
+ for (const entry of raw.slice(0, MAX_KEYS)) {
470
+ if (typeof entry === 'string') {
471
+ const valid = VALID_NAME_RE.test(entry);
472
+ out.push({
473
+ name: valid ? entry : null,
474
+ versionRange: null,
475
+ marketplace: null,
476
+ parseable: valid,
477
+ });
478
+ }
479
+ else if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
480
+ const dep = entry;
481
+ const nameValid = typeof dep.name === 'string' && VALID_NAME_RE.test(dep.name);
482
+ out.push({
483
+ name: nameValid ? dep.name : null,
484
+ versionRange: typeof dep.version === 'string' ? dep.version : null,
485
+ marketplace: typeof dep.marketplace === 'string' && VALID_NAME_RE.test(dep.marketplace)
486
+ ? dep.marketplace
487
+ : null,
488
+ parseable: nameValid,
489
+ });
490
+ }
491
+ else {
492
+ out.push({ name: null, versionRange: null, marketplace: null, parseable: false });
493
+ }
494
+ }
495
+ return out;
496
+ }
497
+ function isPathOrArray(value) {
498
+ return (typeof value === 'string' ||
499
+ (Array.isArray(value) && value.every((v) => typeof v === 'string')));
500
+ }
501
+ function isPathArrayOrObject(value) {
502
+ if (typeof value === 'string')
503
+ return true;
504
+ if (Array.isArray(value)) {
505
+ return value.every((v) => typeof v === 'string' || (v !== null && typeof v === 'object'));
506
+ }
507
+ return value !== null && typeof value === 'object';
508
+ }
509
+ /**
510
+ * PATH-style prerequisite lookup. Pure fs — the command is never executed.
511
+ * Returns null when the declaration cannot be resolved statically
512
+ * (env expansion other than ${CLAUDE_PLUGIN_ROOT}, relative paths):
513
+ * "unresolvable" must never be reported as "missing".
514
+ */
515
+ export function commandOnPath(rawCommand, args, rootCanonical, env = process.env) {
516
+ const form = Array.isArray(args) ? 'exec' : 'shell';
517
+ let target = form === 'shell' ? rawCommand.trim().split(/\s+/)[0] : rawCommand.trim();
518
+ if (target.length === 0)
519
+ return null;
520
+ target = target.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, rootCanonical);
521
+ if (target.includes('${'))
522
+ return null;
523
+ const isExecutable = (candidate) => {
524
+ try {
525
+ if (process.platform === 'win32') {
526
+ return existsSync(candidate);
527
+ }
528
+ accessSync(candidate, constants.X_OK);
529
+ return statSync(candidate).isFile();
530
+ }
531
+ catch {
532
+ return false;
533
+ }
534
+ };
535
+ if (target.includes('/') || target.includes('\\')) {
536
+ if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target))
537
+ return isExecutable(target);
538
+ return null; // relative path — base directory is ambiguous at runtime
539
+ }
540
+ const pathEntries = (env.PATH ?? '').split(delimiter).filter(Boolean);
541
+ const suffixes = process.platform === 'win32'
542
+ ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').map((s) => s.toLowerCase())
543
+ : [''];
544
+ for (const dir of pathEntries) {
545
+ for (const suffix of suffixes) {
546
+ if (isExecutable(join(dir, target + suffix)))
547
+ return true;
548
+ }
549
+ }
550
+ return false;
551
+ }
552
+ /** Bounded key-name list keeping the ORIGINAL key count as total/omitted. */
553
+ function boundedKeys(value) {
554
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
555
+ return { items: [], total: 0, omitted: 0 };
556
+ }
557
+ const keys = Object.keys(value).filter((k) => typeof k === 'string');
558
+ const items = keys.slice(0, MAX_KEYS).map(boundName).sort();
559
+ return { items, total: keys.length, omitted: keys.length - items.length };
560
+ }
561
+ function parseHooksConfig(raw) {
562
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
563
+ return [];
564
+ const container = raw;
565
+ const events = container.hooks && typeof container.hooks === 'object' && !Array.isArray(container.hooks)
566
+ ? container.hooks
567
+ : container;
568
+ const facts = [];
569
+ for (const [event, entriesRaw] of Object.entries(events)) {
570
+ if (facts.length > MAX_FACTS_PER_TYPE)
571
+ break;
572
+ if (!Array.isArray(entriesRaw))
573
+ continue;
574
+ for (const entryRaw of entriesRaw) {
575
+ if (facts.length > MAX_FACTS_PER_TYPE)
576
+ break;
577
+ if (!entryRaw || typeof entryRaw !== 'object' || Array.isArray(entryRaw))
578
+ continue;
579
+ const entry = entryRaw;
580
+ const matcher = entry.matcher;
581
+ const handlers = Array.isArray(entry.hooks)
582
+ ? entry.hooks
583
+ : typeof entry.type === 'string'
584
+ ? [entry]
585
+ : [];
586
+ const entryConditional = typeof entry.if === 'string' && entry.if.length > 0;
587
+ for (const handlerRaw of handlers) {
588
+ if (facts.length > MAX_FACTS_PER_TYPE)
589
+ break;
590
+ if (!handlerRaw || typeof handlerRaw !== 'object' || Array.isArray(handlerRaw))
591
+ continue;
592
+ const handler = handlerRaw;
593
+ const type = typeof handler.type === 'string' ? handler.type : 'unknown';
594
+ const toolMatched = TOOL_MATCHED_EVENTS.has(event);
595
+ const broad = toolMatched && (matcher === undefined || matcher === '' || matcher === '*');
596
+ facts.push({
597
+ event: boundName(event),
598
+ toolMatched,
599
+ broad,
600
+ conditional: entryConditional || (typeof handler.if === 'string' && handler.if.length > 0),
601
+ type: boundName(type),
602
+ command: sanitizeCommand(handler.command, handler.args),
603
+ targetOrigin: type === 'http' ? sanitizeUrlOrigin(handler.url) : null,
604
+ });
605
+ }
606
+ }
607
+ }
608
+ return facts;
609
+ }
610
+ function parseMcpConfig(raw, rootCanonical) {
611
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
612
+ return [];
613
+ const container = raw;
614
+ const servers = container.mcpServers &&
615
+ typeof container.mcpServers === 'object' &&
616
+ !Array.isArray(container.mcpServers)
617
+ ? container.mcpServers
618
+ : container;
619
+ const facts = [];
620
+ for (const [name, cfgRaw] of Object.entries(servers)) {
621
+ if (facts.length > MAX_FACTS_PER_TYPE)
622
+ break;
623
+ if (!cfgRaw || typeof cfgRaw !== 'object' || Array.isArray(cfgRaw))
624
+ continue;
625
+ const cfg = cfgRaw;
626
+ const hasUrl = typeof cfg.url === 'string' && cfg.url.length > 0;
627
+ const hasCommand = typeof cfg.command === 'string' && cfg.command.length > 0;
628
+ const kind = hasUrl ? 'remote' : hasCommand ? 'stdio' : 'unknown';
629
+ facts.push({
630
+ name: boundName(name),
631
+ kind,
632
+ command: hasCommand ? sanitizeCommand(cfg.command, cfg.args) : null,
633
+ targetOrigin: hasUrl ? sanitizeUrlOrigin(cfg.url) : null,
634
+ envKeys: boundedKeys(cfg.env),
635
+ headerKeys: boundedKeys(cfg.headers),
636
+ commandFound: hasCommand
637
+ ? commandOnPath(cfg.command, cfg.args, rootCanonical)
638
+ : null,
639
+ });
640
+ }
641
+ return facts;
642
+ }
643
+ function parseLspConfig(raw, rootCanonical) {
644
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
645
+ return [];
646
+ const container = raw;
647
+ const entries = [];
648
+ if (typeof container.command === 'string') {
649
+ entries.push(['lsp', container]);
650
+ }
651
+ else {
652
+ const map = container.lspServers &&
653
+ typeof container.lspServers === 'object' &&
654
+ !Array.isArray(container.lspServers)
655
+ ? container.lspServers
656
+ : container;
657
+ for (const [name, cfg] of Object.entries(map)) {
658
+ if (entries.length > MAX_FACTS_PER_TYPE)
659
+ break;
660
+ if (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) {
661
+ entries.push([name, cfg]);
662
+ }
663
+ }
664
+ }
665
+ const facts = [];
666
+ for (const [name, cfg] of entries) {
667
+ const hasCommand = typeof cfg.command === 'string' && cfg.command.length > 0;
668
+ const extMap = cfg.extensionToLanguage &&
669
+ typeof cfg.extensionToLanguage === 'object' &&
670
+ !Array.isArray(cfg.extensionToLanguage)
671
+ ? cfg.extensionToLanguage
672
+ : {};
673
+ const uniqueLanguages = [
674
+ ...new Set(Object.values(extMap)
675
+ .filter((v) => typeof v === 'string')
676
+ .map(boundName)),
677
+ ].sort();
678
+ facts.push({
679
+ name: boundName(name),
680
+ command: hasCommand ? sanitizeCommand(cfg.command, cfg.args) : null,
681
+ extensions: boundedKeys(extMap),
682
+ languages: {
683
+ items: uniqueLanguages.slice(0, MAX_KEYS),
684
+ total: uniqueLanguages.length,
685
+ omitted: Math.max(0, uniqueLanguages.length - MAX_KEYS),
686
+ },
687
+ commandFound: hasCommand
688
+ ? commandOnPath(cfg.command, cfg.args, rootCanonical)
689
+ : null,
690
+ });
691
+ }
692
+ return facts;
693
+ }
694
+ function parseMonitorEntries(raw) {
695
+ const list = Array.isArray(raw)
696
+ ? raw
697
+ : raw && typeof raw === 'object' && Array.isArray(raw.monitors)
698
+ ? raw.monitors
699
+ : [];
700
+ const facts = [];
701
+ for (const entry of list) {
702
+ if (facts.length > MAX_FACTS_PER_TYPE)
703
+ break;
704
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
705
+ continue;
706
+ const monitor = entry;
707
+ facts.push({
708
+ name: typeof monitor.name === 'string' ? boundName(monitor.name) : null,
709
+ when: typeof monitor.when === 'string' ? boundName(monitor.when) : null,
710
+ command: sanitizeCommand(monitor.command, undefined),
711
+ });
712
+ }
713
+ return facts;
714
+ }
715
+ function scanPlugin(rootCanonical, state, result, read, walk, openDirect) {
716
+ // --- manifest -------------------------------------------------------------
717
+ const manifestRel = '.claude-plugin/plugin.json';
718
+ const manifestAbs = join(rootCanonical, manifestRel);
719
+ let manifest = {};
720
+ let manifestExists = false;
721
+ try {
722
+ lstatSync(manifestAbs);
723
+ manifestExists = true;
724
+ }
725
+ catch {
726
+ manifestExists = false;
727
+ }
728
+ if (manifestExists) {
729
+ result.manifest.present = true;
730
+ const direct = openDirect(manifestRel);
731
+ // A refused read (escaping symlink → symlink_skipped, or a tripped budget
732
+ // → scan_incomplete) is already reported through those channels. The
733
+ // manifest stays UNINSPECTED: only content that was actually read may
734
+ // produce content-derived claims (invalid JSON / name / fields).
735
+ if (direct.content !== null) {
736
+ result.manifest.inspected = true;
737
+ try {
738
+ const parsed = JSON.parse(direct.content);
739
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
740
+ manifest = parsed;
741
+ }
742
+ else {
743
+ result.manifest.parseError = true;
744
+ }
745
+ }
746
+ catch {
747
+ result.manifest.parseError = true;
748
+ }
749
+ }
750
+ }
751
+ if (result.manifest.inspected && !result.manifest.parseError) {
752
+ const name = manifest.name;
753
+ if (typeof name === 'string' && VALID_NAME_RE.test(name)) {
754
+ result.manifest.name = name;
755
+ }
756
+ else {
757
+ result.manifest.nameInvalid = true;
758
+ if (typeof name === 'string')
759
+ result.manifest.name = null;
760
+ }
761
+ const experimental = manifest.experimental && typeof manifest.experimental === 'object' && !Array.isArray(manifest.experimental)
762
+ ? manifest.experimental
763
+ : {};
764
+ const themesValue = manifest.themes !== undefined ? manifest.themes : experimental.themes;
765
+ const monitorsValue = manifest.monitors !== undefined ? manifest.monitors : experimental.monitors;
766
+ const checks = [
767
+ ['commands', manifest.commands, isPathOrArray],
768
+ ['agents', manifest.agents, isPathOrArray],
769
+ ['skills', manifest.skills, isPathOrArray],
770
+ ['outputStyles', manifest.outputStyles, isPathOrArray],
771
+ ['themes', themesValue, isPathOrArray],
772
+ ['hooks', manifest.hooks, isPathArrayOrObject],
773
+ ['mcpServers', manifest.mcpServers, isPathArrayOrObject],
774
+ ['lspServers', manifest.lspServers, isPathArrayOrObject],
775
+ ['monitors', monitorsValue, isPathArrayOrObject],
776
+ ['dependencies', manifest.dependencies, (v) => Array.isArray(v)],
777
+ ];
778
+ for (const [field, value, valid] of checks) {
779
+ if (value !== undefined && !valid(value)) {
780
+ result.manifest.invalidFields.push(field);
781
+ // invalid declarations are ignored below — defaults apply
782
+ if (field === 'themes')
783
+ delete experimental.themes;
784
+ delete manifest[field];
785
+ }
786
+ }
787
+ if (Array.isArray(manifest.dependencies) && manifest.dependencies.length > MAX_KEYS) {
788
+ state.limitsHit.add('max-dependencies');
789
+ state.incomplete = true;
790
+ }
791
+ result.manifest.dependencies = parseDependencies(manifest.dependencies);
792
+ }
793
+ else if (result.manifest.parseError) {
794
+ manifest = {};
795
+ }
796
+ const experimental = manifest.experimental && typeof manifest.experimental === 'object' && !Array.isArray(manifest.experimental)
797
+ ? manifest.experimental
798
+ : {};
799
+ // --- component path resolution (docs: skills ADD, others REPLACE) ---------
800
+ const commandsRoots = boundPaths(stringPaths(manifest.commands), state);
801
+ const agentsRoots = boundPaths(stringPaths(manifest.agents), state);
802
+ const outputStylesRoots = boundPaths(stringPaths(manifest.outputStyles), state);
803
+ const themesRoots = boundPaths(stringPaths(manifest.themes !== undefined ? manifest.themes : experimental.themes), state);
804
+ // A declared "." / "./" means the root SKILL.md (handled below as the
805
+ // documented special case) — it must not become a whole-tree walk root.
806
+ const explicitRootSkill = declaresRootPath(manifest.skills);
807
+ const declaredSkillsRoots = boundPaths(stringPaths(manifest.skills), state).filter((p) => p !== '' && p !== '.');
808
+ const skillsRoots = ['skills', ...declaredSkillsRoots];
809
+ const declared = [
810
+ ...commandsRoots,
811
+ ...agentsRoots,
812
+ ...outputStylesRoots,
813
+ ...themesRoots,
814
+ ...declaredSkillsRoots,
815
+ ...boundPaths(stringPaths(manifest.hooks), state),
816
+ ...boundPaths(stringPaths(manifest.mcpServers), state),
817
+ ...boundPaths(stringPaths(manifest.lspServers), state),
818
+ ...boundPaths(stringPaths(manifest.monitors !== undefined ? manifest.monitors : experimental.monitors), state),
819
+ ];
820
+ for (const rel of [...new Set(declared)].sort()) {
821
+ // Contained lexical resolve first: a "../…" or absolute declaration is
822
+ // reported as missing without ever touching the filesystem outside the
823
+ // root. Presence uses lstat (no symlink follow) — reads are contained
824
+ // separately when the path is actually opened or walked.
825
+ const lexical = resolve(rootCanonical, rel);
826
+ if (!isWithin(rootCanonical, lexical)) {
827
+ result.manifest.declaredMissing.push(rel);
828
+ continue;
829
+ }
830
+ try {
831
+ lstatSync(lexical);
832
+ }
833
+ catch {
834
+ result.manifest.declaredMissing.push(rel);
835
+ }
836
+ }
837
+ const collectMd = (roots, type) => {
838
+ for (const root of [...new Set(roots)].sort()) {
839
+ walk(rootCanonical, root, state, (relPath, absPath, size) => {
840
+ if (!relPath.endsWith('.md'))
841
+ return;
842
+ if (type === 'skill' && basename(relPath) !== 'SKILL.md')
843
+ return;
844
+ result.components.push(buildComponent(type, relPath, read(absPath, size)));
845
+ });
846
+ }
847
+ };
848
+ collectMd(commandsRoots.length > 0 ? commandsRoots : ['commands'], 'command');
849
+ collectMd(agentsRoots.length > 0 ? agentsRoots : ['agents'], 'agent');
850
+ collectMd(outputStylesRoots.length > 0 ? outputStylesRoots : ['output-styles'], 'outputStyle');
851
+ collectMd(skillsRoots, 'skill');
852
+ // Documented special case: a single-skill plugin may keep SKILL.md at root.
853
+ // It counts ONLY when the manifest explicitly declares "." / "./", or when
854
+ // there is no `skills` manifest field AND no entries under skills/ — a root
855
+ // SKILL.md alongside a skills/ directory or a declared skills path is
856
+ // repository housekeeping, not a component.
857
+ const rootSkillEligible = explicitRootSkill || (manifest.skills === undefined && !skillsDirHasEntries(rootCanonical));
858
+ if (rootSkillEligible) {
859
+ const direct = openDirect('SKILL.md');
860
+ if (direct.found) {
861
+ result.components.push(buildComponent('skill', 'SKILL.md', direct.content));
862
+ }
863
+ }
864
+ // --- themes ----------------------------------------------------------------
865
+ for (const root of themesRoots.length > 0 ? [...new Set(themesRoots)].sort() : ['themes']) {
866
+ walk(rootCanonical, root, state, (relPath, absPath, size) => {
867
+ if (!relPath.endsWith('.json'))
868
+ return;
869
+ result.themeFiles.push(relPath);
870
+ const content = read(absPath, size);
871
+ if (content !== null) {
872
+ try {
873
+ JSON.parse(content);
874
+ }
875
+ catch {
876
+ state.parseErrors.push(relPath);
877
+ }
878
+ }
879
+ });
880
+ }
881
+ // --- JSON config helpers -----------------------------------------------------
882
+ const readJsonConfig = (rel) => {
883
+ const direct = openDirect(rel);
884
+ if (direct.content === null)
885
+ return undefined;
886
+ try {
887
+ return JSON.parse(direct.content);
888
+ }
889
+ catch {
890
+ state.parseErrors.push(rel);
891
+ return undefined;
892
+ }
893
+ };
894
+ const configSources = (value, defaultRel) => {
895
+ if (value === undefined)
896
+ return { files: [defaultRel], inline: [] };
897
+ if (typeof value === 'string')
898
+ return { files: [normalizeManifestPath(value)], inline: [] };
899
+ if (Array.isArray(value)) {
900
+ return {
901
+ files: boundPaths(value.filter((v) => typeof v === 'string').map(normalizeManifestPath), state),
902
+ inline: boundList(value.filter((v) => v !== null && typeof v === 'object'), state, 'max-inline-configs'),
903
+ };
904
+ }
905
+ if (value !== null && typeof value === 'object')
906
+ return { files: [], inline: [value] };
907
+ return { files: [defaultRel], inline: [] };
908
+ };
909
+ // Aggregate fact cap per plugin: whatever the parse helpers produced,
910
+ // never keep more than MAX_FACTS_PER_TYPE — and never drop silently.
911
+ const pushFacts = (target, incoming) => {
912
+ for (const fact of incoming) {
913
+ if (target.length >= MAX_FACTS_PER_TYPE) {
914
+ state.limitsHit.add('max-facts');
915
+ state.incomplete = true;
916
+ return;
917
+ }
918
+ target.push(fact);
919
+ }
920
+ };
921
+ // --- hooks -------------------------------------------------------------------
922
+ {
923
+ const { files, inline } = configSources(manifest.hooks, 'hooks/hooks.json');
924
+ for (const rel of files) {
925
+ const parsed = readJsonConfig(rel);
926
+ if (parsed !== undefined)
927
+ pushFacts(result.hooks, parseHooksConfig(parsed));
928
+ }
929
+ for (const cfg of inline)
930
+ pushFacts(result.hooks, parseHooksConfig(cfg));
931
+ }
932
+ // --- MCP servers ---------------------------------------------------------------
933
+ {
934
+ const { files, inline } = configSources(manifest.mcpServers, '.mcp.json');
935
+ for (const rel of files) {
936
+ const parsed = readJsonConfig(rel);
937
+ if (parsed !== undefined)
938
+ pushFacts(result.mcp, parseMcpConfig(parsed, rootCanonical));
939
+ }
940
+ for (const cfg of inline)
941
+ pushFacts(result.mcp, parseMcpConfig({ mcpServers: cfg }, rootCanonical));
942
+ }
943
+ // --- LSP servers -----------------------------------------------------------------
944
+ {
945
+ const { files, inline } = configSources(manifest.lspServers, '.lsp.json');
946
+ for (const rel of files) {
947
+ const parsed = readJsonConfig(rel);
948
+ if (parsed !== undefined)
949
+ pushFacts(result.lsp, parseLspConfig(parsed, rootCanonical));
950
+ }
951
+ for (const cfg of inline)
952
+ pushFacts(result.lsp, parseLspConfig(cfg, rootCanonical));
953
+ }
954
+ // Per-fact key lists (env/header keys, extensions, languages) are bounded
955
+ // at parse time with true totals — any omission marks the scan incomplete.
956
+ const keysOmitted = result.mcp.some((m) => m.envKeys.omitted > 0 || m.headerKeys.omitted > 0) ||
957
+ result.lsp.some((l) => l.extensions.omitted > 0 || l.languages.omitted > 0);
958
+ if (keysOmitted) {
959
+ state.limitsHit.add('max-keys');
960
+ state.incomplete = true;
961
+ }
962
+ // --- monitors ----------------------------------------------------------------------
963
+ {
964
+ const monitorsValue = manifest.monitors !== undefined ? manifest.monitors : experimental.monitors;
965
+ const { files, inline } = configSources(monitorsValue, 'monitors/monitors.json');
966
+ for (const rel of files) {
967
+ const parsed = readJsonConfig(rel);
968
+ if (parsed !== undefined)
969
+ pushFacts(result.monitors, parseMonitorEntries(parsed));
970
+ }
971
+ if (inline.length > 0)
972
+ pushFacts(result.monitors, parseMonitorEntries(inline));
973
+ }
974
+ // --- bin/ (spec: on PATH while the plugin is enabled; tree-only, no manifest) --------
975
+ // The directory itself goes through the contained-realpath helper: a bin/
976
+ // that is a symlink pointing outside the root must not be listed at all.
977
+ const binReal = containedReal(rootCanonical, 'bin', state);
978
+ if (binReal !== null) {
979
+ let entries = [];
980
+ try {
981
+ entries = readdirSync(binReal).sort();
982
+ }
983
+ catch {
984
+ entries = [];
985
+ }
986
+ if (entries.length > MAX_KEYS) {
987
+ state.limitsHit.add('max-facts');
988
+ state.incomplete = true;
989
+ }
990
+ for (const entry of entries.slice(0, MAX_KEYS)) {
991
+ const abs = join(binReal, entry);
992
+ let info;
993
+ try {
994
+ info = lstatSync(abs);
995
+ }
996
+ catch {
997
+ continue;
998
+ }
999
+ if (info.isSymbolicLink()) {
1000
+ try {
1001
+ const real = realpathSync(abs);
1002
+ if (!isWithin(rootCanonical, real)) {
1003
+ state.symlinksSkipped.push(`bin/${entry}`);
1004
+ state.incomplete = true;
1005
+ continue;
1006
+ }
1007
+ info = statSync(real);
1008
+ }
1009
+ catch {
1010
+ state.symlinksSkipped.push(`bin/${entry}`);
1011
+ state.incomplete = true;
1012
+ continue;
1013
+ }
1014
+ }
1015
+ if (!info.isFile())
1016
+ continue;
1017
+ state.filesScanned += 1;
1018
+ result.bin.push({
1019
+ relPath: `bin/${entry}`,
1020
+ executable: process.platform === 'win32' ? true : (info.mode & 0o111) !== 0,
1021
+ });
1022
+ }
1023
+ }
1024
+ // Overlapping declared roots (e.g. "cmds" and "cmds/sub") reach the same
1025
+ // file twice — one file is one component.
1026
+ const seenComponents = new Set();
1027
+ result.components = result.components.filter((component) => {
1028
+ const key = `${component.type} ${component.relPath}`;
1029
+ if (seenComponents.has(key))
1030
+ return false;
1031
+ seenComponents.add(key);
1032
+ return true;
1033
+ });
1034
+ result.components.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
1035
+ result.themeFiles.sort();
1036
+ }