claudepluginhub 0.16.0 → 0.17.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.
Files changed (55) hide show
  1. package/README.md +34 -1
  2. package/dist/args.js +0 -6
  3. package/dist/collection-install.d.ts +4 -23
  4. package/dist/collection-install.js +9 -45
  5. package/dist/component-install.js +8 -27
  6. package/dist/detect.d.ts +0 -2
  7. package/dist/detect.js +3 -7
  8. package/dist/doctor/claude-source.d.ts +4 -6
  9. package/dist/doctor/claude-source.js +1 -2
  10. package/dist/doctor/color.d.ts +0 -1
  11. package/dist/doctor/color.js +0 -1
  12. package/dist/doctor/equivalence.d.ts +1 -1
  13. package/dist/doctor/equivalence.js +68 -149
  14. package/dist/doctor/estimate.js +12 -61
  15. package/dist/doctor/html-report.d.ts +1 -6
  16. package/dist/doctor/html-report.js +43 -116
  17. package/dist/doctor/inventory.d.ts +10 -24
  18. package/dist/doctor/inventory.js +29 -63
  19. package/dist/doctor/overlap.d.ts +3 -6
  20. package/dist/doctor/render.js +20 -38
  21. package/dist/doctor/report.d.ts +7 -16
  22. package/dist/doctor/report.js +3 -6
  23. package/dist/doctor/rules.d.ts +6 -16
  24. package/dist/doctor/rules.js +13 -26
  25. package/dist/doctor/run.d.ts +1 -1
  26. package/dist/doctor/run.js +5 -6
  27. package/dist/doctor/sanitize.d.ts +0 -8
  28. package/dist/doctor/sanitize.js +1 -6
  29. package/dist/doctor/select.d.ts +10 -25
  30. package/dist/doctor/select.js +2 -3
  31. package/dist/download.d.ts +4 -0
  32. package/dist/download.js +12 -18
  33. package/dist/fetch.d.ts +4 -8
  34. package/dist/fetch.js +13 -19
  35. package/dist/github-install.js +1 -12
  36. package/dist/index.js +14 -22
  37. package/dist/install.js +1 -2
  38. package/dist/mcp/server.d.ts +25 -0
  39. package/dist/mcp/server.js +103 -0
  40. package/dist/mcp/tools.d.ts +73 -0
  41. package/dist/mcp/tools.js +231 -0
  42. package/dist/output.d.ts +0 -5
  43. package/dist/output.js +0 -12
  44. package/dist/prompts.d.ts +3 -10
  45. package/dist/prompts.js +5 -20
  46. package/dist/recommend.d.ts +54 -56
  47. package/dist/recommend.js +69 -127
  48. package/dist/remove.d.ts +1 -1
  49. package/dist/remove.js +5 -10
  50. package/dist/update.js +5 -8
  51. package/dist/validation.d.ts +0 -5
  52. package/dist/validation.js +3 -10
  53. package/dist/wrapper.d.ts +0 -1
  54. package/dist/wrapper.js +1 -8
  55. package/package.json +1 -1
@@ -1,21 +1,14 @@
1
- import { boundEvidenceString, boundMessage, cappedList, compareFindings, MAX_EVIDENCE_ITEMS, MAX_PLUGIN_IDS_PER_FINDING, } from './report.js';
1
+ import { boundEvidenceString, boundMessage, cappedList, compareBytes, compareFindings, MAX_EVIDENCE_ITEMS, MAX_PLUGIN_IDS_PER_FINDING, } from './report.js';
2
2
  import { isDependencyErrorKind } from './sanitize.js';
3
3
  import { findOverlaps } from './overlap.js';
4
+ import { duplicateRecordKey } from './equivalence.js';
4
5
  /**
5
- * The single source of truth for finding codes, severities, and categories.
6
- * Rules and renderers both key off this table, so severity and category
7
- * policy cannot drift.
6
+ * Single source of truth for finding severity (drives exit codes / --strict) and
7
+ * category (drives which output section shows it).
8
8
  *
9
- * Category controls PRESENTATION tier (which output section a finding
10
- * appears in). Severity controls exit codes and --strict behaviour.
11
- *
12
- * Facts vs findings: capability inventory (hooks exist, MCP servers exist,
13
- * env key names, monitors, estimates) lives on plugin entries as FIELDS. The
14
- * findings list carries only actionable conditions — a healthy plugin with
15
- * hooks and MCP servers produces zero findings.
16
- *
17
- * Remediation policy: inspection-first, never chained, never destructive on
18
- * ambiguity. A mutating suggestion appears only when its target is
9
+ * Capability facts (hooks, MCP servers, estimates) live on plugin entries, not
10
+ * here: a healthy plugin produces zero findings. Remediations are
11
+ * inspection-first; a mutating suggestion appears only when its target is
19
12
  * unambiguous from the finding itself.
20
13
  */
21
14
  export const FINDING_CODES = {
@@ -64,7 +57,6 @@ export function makeFinding(code, message, pluginIds, evidence, remediation) {
64
57
  function evidenceList(values) {
65
58
  return cappedList(values.map(boundEvidenceString), MAX_EVIDENCE_ITEMS);
66
59
  }
67
- /** Union of applicable records across contexts, deduplicated by identity. */
68
60
  function unionApplicable(selection) {
69
61
  const seen = new Set();
70
62
  for (const context of selection.contexts) {
@@ -73,9 +65,7 @@ function unionApplicable(selection) {
73
65
  }
74
66
  return [...seen];
75
67
  }
76
- // ---------------------------------------------------------------------------
77
- // Global rules (record/installation/scan level — same truth in every context)
78
- // ---------------------------------------------------------------------------
68
+ // Global rules: record/installation/scan level, identical in every context.
79
69
  function ruleRecordMalformed(dropped, out) {
80
70
  if (dropped > 0) {
81
71
  out.push(makeFinding('record_malformed', `${dropped} record(s) from \`claude plugin list --json\` were malformed and skipped.`, [], { droppedCount: dropped }));
@@ -90,7 +80,7 @@ function ruleScopeUnknown(records, out) {
90
80
  function ruleDuplicateRecord(records, scanEquivalentKeys, out) {
91
81
  const groups = new Map();
92
82
  for (const record of records) {
93
- const key = [record.id, record.rawScope, record.projectPathCanonical ?? '', record.version].join('\0');
83
+ const key = duplicateRecordKey(record);
94
84
  const group = groups.get(key) ?? [];
95
85
  group.push(record);
96
86
  groups.set(key, group);
@@ -188,7 +178,7 @@ function ruleScans(records, scanFor, out) {
188
178
  out.push(makeFinding(code, message, [pluginId], evidence, remediation));
189
179
  },
190
180
  };
191
- for (const record of enabled.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
181
+ for (const record of enabled.sort((a, b) => compareBytes(a.id, b.id))) {
192
182
  collectScanIssues(record, scanFor(record), sink);
193
183
  }
194
184
  // Intentionally disabled records (no native errors): issues are
@@ -197,7 +187,7 @@ function ruleScans(records, scanFor, out) {
197
187
  // "intentionally disabled": its claude_plugin_load_error (error severity)
198
188
  // is the signal, and it must not also read as harmless housekeeping.
199
189
  const disabledEmitted = new Set();
200
- for (const record of disabled.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
190
+ for (const record of disabled.sort((a, b) => compareBytes(a.id, b.id))) {
201
191
  if (record.errors.length > 0)
202
192
  continue;
203
193
  const issues = [];
@@ -216,9 +206,7 @@ function ruleScans(records, scanFor, out) {
216
206
  out.push(makeFinding('disabled_record_issue', `${record.id} (disabled) has issues in its cached installation: ${[...new Set(issues)].sort().join(', ')}. Harmless while disabled; shown for completeness.`, [record.id], { issues: evidenceList([...new Set(issues)].sort()) }));
217
207
  }
218
208
  }
219
- // ---------------------------------------------------------------------------
220
- // Context-scoped rules (run per project context, on unambiguous instances)
221
- // ---------------------------------------------------------------------------
209
+ // Context-scoped rules: run per project context, on unambiguous instances.
222
210
  function ruleAmbiguity(context, out) {
223
211
  for (const instance of context.instances) {
224
212
  if (instance.reason === 'scan_equivalent') {
@@ -308,7 +296,7 @@ function ruleLspConflicts(context, scanFor, out) {
308
296
  }
309
297
  }
310
298
  }
311
- for (const [extension, claimants] of [...claims.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) {
299
+ for (const [extension, claimants] of [...claims.entries()].sort((a, b) => compareBytes(a[0], b[0]))) {
312
300
  if (claimants.length < 2)
313
301
  continue;
314
302
  const pluginIds = [...new Set(claimants.map((c) => c.pluginId))];
@@ -316,7 +304,6 @@ function ruleLspConflicts(context, scanFor, out) {
316
304
  out.push(makeFinding('lsp_extension_conflict', `${claimants.length} enabled LSP servers claim ${extension}: ${names.join(', ')}. Per the documented first-wins behavior, only the first registered server starts and the others never do — registration order is not observable here, so no winner is asserted.`, pluginIds, { extension, servers: evidenceList(names) }));
317
305
  }
318
306
  }
319
- // ---------------------------------------------------------------------------
320
307
  export function analyze(input) {
321
308
  const { selection, scanFor, droppedRecords, scanEquivalentKeys } = input;
322
309
  const applicable = unionApplicable(selection);
@@ -16,7 +16,7 @@ export interface OpenReportResult {
16
16
  path: string;
17
17
  opened: boolean;
18
18
  }
19
- /** Write HTML to a file with exclusive-create (EEXIST if path already exists). */
19
+ /** Exclusive create: throws EEXIST rather than overwriting. */
20
20
  export declare function writeReportFile(filePath: string, html: string): void;
21
21
  export declare function openReport(report: DoctorReport, opener: BrowserOpener): Promise<OpenReportResult>;
22
22
  export declare function buildDoctorReport(inputs: DoctorRunInputs): DoctorReport;
@@ -12,8 +12,8 @@ import { estimatePlugin } from './estimate.js';
12
12
  import { renderHuman, renderJson } from './render.js';
13
13
  import { renderHtml } from './html-report.js';
14
14
  import { defaultOpener } from './open-browser.js';
15
- import { boundEvidenceString, cappedList, recapList, comparePluginEntries, DOCTOR_SCHEMA_VERSION, MAX_CAPABILITY_ITEMS, MAX_EFFECTIVE_PLUGINS_PER_CONTEXT, MAX_EVIDENCE_ITEMS, MAX_FINDINGS, MAX_PATHS_PER_TYPE, MAX_PLUGINS_PER_CONTEXT, MAX_TOP_CONTRIBUTORS, MAX_UNKNOWN_SCOPE_RECORDS, } from './report.js';
16
- /** Write HTML to a file with exclusive-create (EEXIST if path already exists). */
15
+ import { boundEvidenceString, cappedList, recapList, compareBytes, comparePluginEntries, DOCTOR_SCHEMA_VERSION, MAX_CAPABILITY_ITEMS, MAX_EFFECTIVE_PLUGINS_PER_CONTEXT, MAX_EVIDENCE_ITEMS, MAX_FINDINGS, MAX_PATHS_PER_TYPE, MAX_PLUGINS_PER_CONTEXT, MAX_TOP_CONTRIBUTORS, MAX_UNKNOWN_SCOPE_RECORDS, } from './report.js';
16
+ /** Exclusive create: throws EEXIST rather than overwriting. */
17
17
  export function writeReportFile(filePath, html) {
18
18
  writeFileSync(filePath, html, { flag: 'wx', mode: 0o600 });
19
19
  }
@@ -67,7 +67,7 @@ function capabilities(scan) {
67
67
  hooks: {
68
68
  total: scan.hooks.length,
69
69
  byEvent: cappedList([...byEvent.entries()]
70
- .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
70
+ .sort((a, b) => compareBytes(a[0], b[0]))
71
71
  .map(([event, stats]) => ({ event, ...stats })), MAX_CAPABILITY_ITEMS),
72
72
  },
73
73
  mcp: cappedList(scan.mcp.map((m) => ({
@@ -119,7 +119,6 @@ function buildEffectivePlugins(contextSelection, scanFor) {
119
119
  const estimate = instance.selection === 'sole' && scanned ? estimatePlugin(scan) : null;
120
120
  const allScopes = cappedList([...new Set(instance.contenders.map((r) => r.scope))].sort(), MAX_CAPABILITY_ITEMS);
121
121
  const allVersions = cappedList([...new Set(instance.contenders.map((r) => r.version))].sort(), MAX_CAPABILITY_ITEMS);
122
- const isAmbiguous = instance.selection === 'ambiguous';
123
122
  return {
124
123
  id: instance.id,
125
124
  selection: instance.selection,
@@ -129,7 +128,7 @@ function buildEffectivePlugins(contextSelection, scanFor) {
129
128
  versions: allVersions,
130
129
  estAlwaysOnTokens: estimate ? estimate.alwaysOnTokens : null,
131
130
  estimated: estimate ? estimate.estimated : false,
132
- inventoryIncomplete: isAmbiguous ? false : (scan ? scan.incomplete : false),
131
+ inventoryIncomplete: scan?.incomplete ?? false,
133
132
  components: scanned ? componentSummaries(scan) : null,
134
133
  capabilities: scanned ? capabilities(scan) : null,
135
134
  largestOnInvoke: estimate ? estimate.largestOnInvoke : [],
@@ -248,7 +247,7 @@ export function buildDoctorReport(inputs) {
248
247
  findings: cappedList(analysis.global, MAX_FINDINGS),
249
248
  unknownScopeRecords: cappedList(selection.unknownScopeRecords
250
249
  .map((r) => ({ id: r.id, rawScope: r.rawScope, enabled: r.enabled }))
251
- .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), MAX_UNKNOWN_SCOPE_RECORDS),
250
+ .sort((a, b) => compareBytes(a.id, b.id)), MAX_UNKNOWN_SCOPE_RECORDS),
252
251
  summary,
253
252
  scan: stats,
254
253
  };
@@ -4,14 +4,6 @@ import type { CommandFact, NativePluginError } from './report.js';
4
4
  * extension, env/header key) so hostile input cannot inflate the report.
5
5
  */
6
6
  export declare function boundName(value: string): string;
7
- /**
8
- * Opaque credential-shaped token, tuned to leave real tool names alone:
9
- * ≥20 chars AND either a solid base64/hex-ish run with no word separators
10
- * (AKIA-style keys) or a mixed-case+digit blob (JWT segments, random
11
- * tokens). Hyphenated lowercase names like `typescript-language-server`
12
- * must survive — they are the diagnostic value.
13
- */
14
- export declare function looksOpaque(token: string): boolean;
15
7
  /** Reduce a URL to scheme://host[:port] — never path, query, fragment, userinfo. */
16
8
  export declare function sanitizeUrlOrigin(raw: unknown): string;
17
9
  /**
@@ -23,7 +23,7 @@ export function boundName(value) {
23
23
  * tokens). Hyphenated lowercase names like `typescript-language-server`
24
24
  * must survive — they are the diagnostic value.
25
25
  */
26
- export function looksOpaque(token) {
26
+ function looksOpaque(token) {
27
27
  if (token.length < 20)
28
28
  return false;
29
29
  if (/^[A-Za-z0-9+/=_]+$/.test(token))
@@ -61,10 +61,6 @@ export function sanitizeCommand(command, args) {
61
61
  }
62
62
  return { form, executable };
63
63
  }
64
- // ---------------------------------------------------------------------------
65
- // Native `errors` field (observed: array of human-readable strings; object
66
- // elements with a `code` token tolerated as an alternate/future shape)
67
- // ---------------------------------------------------------------------------
68
64
  /** Documented dependency/load error codes (plugin-dependencies docs). */
69
65
  const RECOGNIZED_CODES = new Set([
70
66
  'dependency-unsatisfied',
@@ -144,7 +140,6 @@ export function sanitizeNativeErrors(raw) {
144
140
  else if (element && typeof element === 'object' && !Array.isArray(element)) {
145
141
  out.push(fromObject(element));
146
142
  }
147
- // other element shapes are ignored — tolerant by design
148
143
  }
149
144
  return out;
150
145
  }
@@ -1,32 +1,17 @@
1
1
  import type { DoctorFlags, EffectiveInstance, InstallationRecord, ProjectContext } from './report.js';
2
2
  /**
3
- * Project contexts and effective-instance selection.
3
+ * Records → per-context applicability → effective instances (one per context +
4
+ * plugin id).
4
5
  *
5
- * Layering (the load-bearing distinction of Doctor's model):
6
- * 1. Installation records — what `claude plugin list --json` reports.
7
- * 2. Applicability — which records participate in a given project context.
8
- * 3. Effective instances — the unique runtime view per (context, plugin id).
6
+ * Default mode has one context (cwd); --all-projects adds one per distinct
7
+ * project/local projectPath. user/managed records apply in every context,
8
+ * project/local only in their own; analyses never aggregate across contexts.
9
9
  *
10
- * Contexts: default mode analyzes ONE context (the current cwd).
11
- * --all-projects builds one context per distinct canonical projectPath seen on
12
- * project/local records, plus the cwd context. `user` and `managed` records
13
- * apply independently within EVERY context; `project`/`local` records apply
14
- * only within their matching context. Cross-context aggregation never happens:
15
- * overlap, LSP conflicts, hook analysis, dependency resolution, and context
16
- * estimates each run inside one context.
17
- *
18
- * Selection is conservative by design. The settings docs establish a
19
- * precedence order for setting VALUES (managed > local > project > user) and
20
- * say `enabledPlugins` merges across scopes, but no documented public rule or
21
- * machine-readable field states which INSTANCE loads when the same plugin id
22
- * is enabled at multiple scopes — or twice within one scope (observed in the
23
- * wild). So: candidates that collapse to one (identical canonical installPath
24
- * AND version — the shared-cache case) are 'sole'; anything else is
25
- * 'ambiguous' and is excluded from aggregate analyses. There is deliberately
26
- * NO precedence branch; a one-version experiment is not a public contract.
27
- *
28
- * Unknown scope strings (future Claude versions) are preserved for the report
29
- * but excluded from analysis — never assumed globally applicable.
10
+ * No public rule says which INSTANCE loads when one plugin id is enabled more
11
+ * than once (settings precedence covers values, not instances), so there is
12
+ * deliberately no precedence branch: candidates collapsing to one canonical
13
+ * installPath + version are 'sole', anything else is 'ambiguous' and excluded
14
+ * from aggregate analyses. Unknown scopes are reported but never applied.
30
15
  */
31
16
  export interface ContextSelection {
32
17
  context: ProjectContext;
@@ -31,7 +31,7 @@ function appliesToContext(record, context) {
31
31
  if (record.scope === 'project' || record.scope === 'local') {
32
32
  return record.projectPathCanonical === context.canonicalPath;
33
33
  }
34
- return false; // unknown scopes never apply — handled separately
34
+ return false;
35
35
  }
36
36
  function passesScopeFilter(record, flags) {
37
37
  if (flags.scope === 'all')
@@ -49,8 +49,7 @@ function selectWithinContext(context, applicable) {
49
49
  }
50
50
  const instances = [];
51
51
  for (const [id, group] of [...byId.entries()].sort((a, b) => compareBytes(a[0], b[0]))) {
52
- // Realpath dedup: identical canonical installPath AND version = one
53
- // candidate (the same cached directory enabled at several scopes).
52
+ // Same cached directory enabled at several scopes = one candidate.
54
53
  const distinct = new Map();
55
54
  for (const record of group) {
56
55
  const key = `${record.installPathCanonical ?? record.installPath}\0${record.version}`;
@@ -2,12 +2,16 @@ import type { Scope } from './prompts.js';
2
2
  import type { ComponentLock } from './lock.js';
3
3
  export interface FlatComponent {
4
4
  source: string;
5
+ /** Branch, tag or commit to fetch from; null = default branch. Pinned listings install and update at the pin. */
6
+ ref: string | null;
5
7
  type: 'command' | 'agent' | 'skill' | 'hook' | 'mcp' | 'lsp';
6
8
  componentName: string;
7
9
  sourcePath: string;
8
10
  downloadPath?: string;
9
11
  inlineConfig: unknown | null;
10
12
  }
13
+ /** The ref every GitHub read for this component must use. */
14
+ export declare function resolveFetchRef(component: Pick<FlatComponent, 'source' | 'ref'>): Promise<string | null>;
11
15
  export declare function getBaseDir(scope: Scope): string;
12
16
  export type InstallResult = {
13
17
  status: 'installed';
package/dist/download.js CHANGED
@@ -3,6 +3,10 @@ import { dirname, join, resolve, sep } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { fetchDefaultBranch, fetchTree, downloadFile, findTreeSha, findBlobSha, listFilesUnder, } from './github.js';
5
5
  import { printError, printProgress } from './output.js';
6
+ /** The ref every GitHub read for this component must use. */
7
+ export async function resolveFetchRef(component) {
8
+ return component.ref ?? fetchDefaultBranch(component.source);
9
+ }
6
10
  export function getBaseDir(scope) {
7
11
  if (scope === 'user') {
8
12
  return join(homedir(), '.claude');
@@ -44,9 +48,8 @@ function isSafePath(destPath, baseDir) {
44
48
  export async function downloadSkill(component, scope) {
45
49
  const { source, sourcePath, componentName } = component;
46
50
  const downloadSource = component.downloadPath ?? sourcePath;
47
- // Strip /SKILL.md to get directory path (repo-root-relative for GitHub API)
48
51
  const dirPath = downloadSource.replace(/\/SKILL\.md$/, '');
49
- const branch = await fetchDefaultBranch(source);
52
+ const branch = await resolveFetchRef(component);
50
53
  if (!branch)
51
54
  return null;
52
55
  const tree = await fetchTree(source, branch);
@@ -101,7 +104,7 @@ export async function downloadSkill(component, scope) {
101
104
  export async function downloadSingleFile(component, scope) {
102
105
  const { source, type, sourcePath, componentName } = component;
103
106
  const effectivePath = component.downloadPath ?? sourcePath;
104
- const branch = await fetchDefaultBranch(source);
107
+ const branch = await resolveFetchRef(component);
105
108
  if (!branch)
106
109
  return null;
107
110
  const tree = await fetchTree(source, branch);
@@ -139,22 +142,17 @@ function isRecord(value) {
139
142
  return typeof value === 'object' && value !== null && !Array.isArray(value);
140
143
  }
141
144
  /**
142
- * Minimal structural contracts for what we write into settings.json —
143
- * derived from the official Claude Code settings shapes. Deliberately loose
144
- * (extra fields fine, no enum of event names) so new Claude Code features
145
- * don't get rejected; the point is to never write something Claude Code
146
- * cannot parse at all.
145
+ * Deliberately loose shape checks (extra fields and unknown hook events pass):
146
+ * the goal is only to never write settings Claude Code cannot parse.
147
147
  */
148
148
  function isValidMcpServerEntry(value) {
149
149
  if (!isRecord(value))
150
150
  return false;
151
- // stdio servers need a command; remote servers need a url
152
151
  return typeof value.command === 'string' || typeof value.url === 'string';
153
152
  }
154
153
  function isValidLspServerEntry(value) {
155
154
  return isRecord(value) && typeof value.command === 'string';
156
155
  }
157
- /** A hook event's value: array of matcher groups, each with a hooks array of typed handlers. */
158
156
  function isValidHookEventHandlers(value) {
159
157
  if (!Array.isArray(value))
160
158
  return false;
@@ -164,14 +162,13 @@ function isValidHookEventHandlers(value) {
164
162
  }
165
163
  async function resolveConfig(component) {
166
164
  const { inlineConfig, source, sourcePath } = component;
167
- // Inline config object — use directly
168
165
  if (inlineConfig && typeof inlineConfig === 'object') {
169
166
  return inlineConfig;
170
167
  }
171
- // String path — download and parse
168
+ // A string is a path to the config file; absent means sourcePath.
172
169
  if (typeof inlineConfig === 'string' || !inlineConfig) {
173
170
  const filePath = typeof inlineConfig === 'string' ? inlineConfig : sourcePath;
174
- const branch = await fetchDefaultBranch(source);
171
+ const branch = await resolveFetchRef(component);
175
172
  if (!branch)
176
173
  return null;
177
174
  const content = await downloadFile(source, branch, filePath);
@@ -201,8 +198,7 @@ export async function mergeConfig(component, scope) {
201
198
  const mcpConfig = config.mcpServers
202
199
  ? config.mcpServers
203
200
  : config;
204
- // Validate BEFORE any write: a malformed server entry means the whole
205
- // component is skipped loudly — never write config Claude Code can't parse.
201
+ // Validate before any write: one malformed entry skips the whole component.
206
202
  const badMcpKeys = Object.keys(mcpConfig).filter((key) => !isValidMcpServerEntry(mcpConfig[key]));
207
203
  if (badMcpKeys.length > 0) {
208
204
  printError(`Skipping ${componentName}: malformed MCP server config (${badMcpKeys.join(', ')}) — each server needs a "command" or "url" string`);
@@ -258,7 +254,6 @@ export async function mergeConfig(component, scope) {
258
254
  if (!Array.isArray(handlers))
259
255
  continue;
260
256
  const existing = (hooks[event] ?? []);
261
- // Only add handlers not already present (by deep equality)
262
257
  const newHandlers = handlers.filter((h) => !existing.some((e) => JSON.stringify(e) === JSON.stringify(h)));
263
258
  if (newHandlers.length > 0) {
264
259
  hooks[event] = [...existing, ...newHandlers];
@@ -269,7 +264,7 @@ export async function mergeConfig(component, scope) {
269
264
  configFragment = hookConfig;
270
265
  }
271
266
  writeJsonFile(settingsPath, settings);
272
- const branch = await fetchDefaultBranch(source);
267
+ const branch = await resolveFetchRef(component);
273
268
  const tree = branch ? await fetchTree(source, branch) : null;
274
269
  const hash = tree ? (findBlobSha(tree, sourcePath) ?? 'unknown') : 'unknown';
275
270
  return {
@@ -312,7 +307,6 @@ export async function installComponent(component, scope, checkExisting) {
312
307
  const lock = await downloadSingleFile(component, scope);
313
308
  return lock ? { status: 'installed', lock } : { status: 'failed' };
314
309
  }
315
- // Config-based: hook, mcp, lsp
316
310
  const lock = await mergeConfig(component, scope);
317
311
  return lock ? { status: 'installed', lock } : { status: 'failed' };
318
312
  }
package/dist/fetch.d.ts CHANGED
@@ -7,6 +7,8 @@ export interface MarketplacePlugin {
7
7
  repo?: string;
8
8
  url?: string;
9
9
  path?: string;
10
+ ref?: string;
11
+ sha?: string;
10
12
  };
11
13
  strict: boolean;
12
14
  description?: string;
@@ -26,16 +28,10 @@ export interface MarketplaceJSON {
26
28
  }
27
29
  export declare function resolveMarketplaceUrl(input: string): string | null;
28
30
  /**
29
- * Plugin collections reference whole plugins (source only), which the
30
- * component downloader can't cherry-pick — they install via native delegation
31
- * (collection-install.ts) instead of the flatten/download path.
31
+ * Collections and wrapper marketplaces reference whole plugins, which the
32
+ * component downloader can't cherry-pick; both install via native delegation.
32
33
  */
33
34
  export declare function isCollectionUrl(url: string): boolean;
34
- /**
35
- * Single-plugin wrapper marketplaces (/api/plugins/<slug>/marketplace.json)
36
- * reference one whole plugin (source only) — like collections, they install
37
- * via native delegation, not the flatten/download path.
38
- */
39
35
  export declare function isPluginWrapperUrl(url: string): boolean;
40
36
  export declare function fetchMarketplace(url: string): Promise<MarketplaceJSON | null>;
41
37
  export declare function flattenComponents(manifest: MarketplaceJSON): FlatComponent[];
package/dist/fetch.js CHANGED
@@ -2,7 +2,6 @@ import { printError, printWarning } from './output.js';
2
2
  export const BASE_URL = 'https://claudepluginhub.com';
3
3
  const ALLOWED_HOSTS = ['claudepluginhub.com', 'www.claudepluginhub.com'];
4
4
  export function resolveMarketplaceUrl(input) {
5
- // Full URL
6
5
  if (input.startsWith('http://') || input.startsWith('https://')) {
7
6
  try {
8
7
  const parsed = new URL(input);
@@ -41,24 +40,18 @@ export function resolveMarketplaceUrl(input) {
41
40
  return null;
42
41
  }
43
42
  /**
44
- * Plugin collections reference whole plugins (source only), which the
45
- * component downloader can't cherry-pick — they install via native delegation
46
- * (collection-install.ts) instead of the flatten/download path.
43
+ * Collections and wrapper marketplaces reference whole plugins, which the
44
+ * component downloader can't cherry-pick; both install via native delegation.
47
45
  */
48
46
  export function isCollectionUrl(url) {
49
47
  return url.includes('/api/collections/');
50
48
  }
51
- /**
52
- * Single-plugin wrapper marketplaces (/api/plugins/<slug>/marketplace.json)
53
- * reference one whole plugin (source only) — like collections, they install
54
- * via native delegation, not the flatten/download path.
55
- */
56
49
  export function isPluginWrapperUrl(url) {
57
50
  return url.includes('/api/plugins/');
58
51
  }
59
52
  export async function fetchMarketplace(url) {
60
53
  try {
61
- // Ensure ?source=cli is present for install tracking
54
+ // ?source=cli attributes the fetch as a CLI install.
62
55
  const parsed = new URL(url);
63
56
  if (!parsed.searchParams.has('source')) {
64
57
  parsed.searchParams.set('source', 'cli');
@@ -90,11 +83,7 @@ export async function fetchMarketplace(url) {
90
83
  return null;
91
84
  }
92
85
  }
93
- /**
94
- * Marketplace-entry component paths are `./`-prefixed per the plugin spec
95
- * (paths relative to the plugin root). Strip the prefix before prefix checks
96
- * and GitHub API calls — the downloader works with bare repo-relative paths.
97
- */
86
+ /** Marketplace component paths are `./`-prefixed; the downloader needs bare repo-relative paths. */
98
87
  function stripDotSlash(path) {
99
88
  return path.replace(/^\.\//, '');
100
89
  }
@@ -103,8 +92,8 @@ export function flattenComponents(manifest) {
103
92
  let skippedWholePlugin = 0;
104
93
  for (const plugin of manifest.plugins) {
105
94
  const repo = plugin.source.repo;
106
- // Whole-plugin references (git/git-subdir sources, no component arrays)
107
- // can't be cherry-picked; they belong to the collection install path.
95
+ // Spec precedence: an exact commit wins over a branch/tag; null = default branch.
96
+ const ref = plugin.source.sha ?? plugin.source.ref ?? null;
108
97
  if (!repo) {
109
98
  printWarning(`Skipping "${plugin.name}" — whole-plugin reference (component install can't cherry-pick it)`);
110
99
  skippedWholePlugin++;
@@ -119,6 +108,7 @@ export function flattenComponents(manifest) {
119
108
  const name = relPath.replace(/\.md$/, '');
120
109
  components.push({
121
110
  source: repo,
111
+ ref,
122
112
  type: 'command',
123
113
  componentName: name,
124
114
  sourcePath: path,
@@ -133,6 +123,7 @@ export function flattenComponents(manifest) {
133
123
  const name = relPath.replace(/\.md$/, '');
134
124
  components.push({
135
125
  source: repo,
126
+ ref,
136
127
  type: 'agent',
137
128
  componentName: name,
138
129
  sourcePath: path,
@@ -143,12 +134,12 @@ export function flattenComponents(manifest) {
143
134
  if (plugin.skills) {
144
135
  for (const rawPath of plugin.skills) {
145
136
  const path = stripDotSlash(rawPath);
146
- // Skill name is the directory containing SKILL.md
147
- // e.g. "plugins/foo/skills/review/SKILL.md" -> "review"
137
+ // "plugins/foo/skills/review/SKILL.md" -> "review"
148
138
  const withoutSkillMd = path.replace(/\/SKILL\.md$/, '');
149
139
  const skillName = withoutSkillMd.split('/').pop() ?? withoutSkillMd;
150
140
  components.push({
151
141
  source: repo,
142
+ ref,
152
143
  type: 'skill',
153
144
  componentName: skillName,
154
145
  sourcePath: path,
@@ -159,6 +150,7 @@ export function flattenComponents(manifest) {
159
150
  if (plugin.hooks) {
160
151
  components.push({
161
152
  source: repo,
153
+ ref,
162
154
  type: 'hook',
163
155
  componentName: `${plugin.name}-hooks`,
164
156
  sourcePath: typeof plugin.hooks === 'string' ? stripDotSlash(plugin.hooks) : 'hooks/hooks.json',
@@ -168,6 +160,7 @@ export function flattenComponents(manifest) {
168
160
  if (plugin.mcpServers) {
169
161
  components.push({
170
162
  source: repo,
163
+ ref,
171
164
  type: 'mcp',
172
165
  componentName: `${plugin.name}-mcp`,
173
166
  sourcePath: typeof plugin.mcpServers === 'string' ? stripDotSlash(plugin.mcpServers) : '.mcp.json',
@@ -177,6 +170,7 @@ export function flattenComponents(manifest) {
177
170
  if (plugin.lspServers) {
178
171
  components.push({
179
172
  source: repo,
173
+ ref,
180
174
  type: 'lsp',
181
175
  componentName: `${plugin.name}-lsp`,
182
176
  sourcePath: typeof plugin.lspServers === 'string' ? stripDotSlash(plugin.lspServers) : '.lsp.json',
@@ -30,7 +30,6 @@ async function installMarketplace(ownerRepo, detection, yes, scopeOverride, plug
30
30
  printError('No valid plugins found in marketplace.');
31
31
  process.exit(1);
32
32
  }
33
- // Plugin selection
34
33
  let selectedPlugins = manifest.plugins;
35
34
  if (pluginName) {
36
35
  const match = manifest.plugins.find((p) => p.name === pluginName);
@@ -59,7 +58,6 @@ async function installMarketplace(ownerRepo, detection, yes, scopeOverride, plug
59
58
  process.exit(0);
60
59
  }
61
60
  }
62
- // Scope picker
63
61
  let scope = scopeOverride ?? 'project';
64
62
  if (!yes && !scopeOverride) {
65
63
  print('');
@@ -70,7 +68,6 @@ async function installMarketplace(ownerRepo, detection, yes, scopeOverride, plug
70
68
  }
71
69
  scope = chosenScope;
72
70
  }
73
- // Add marketplace
74
71
  print('');
75
72
  printStep(`Adding marketplace from ${ownerRepo}...`);
76
73
  const addResult = claudeMarketplaceAdd(ownerRepo, scope);
@@ -79,7 +76,6 @@ async function installMarketplace(ownerRepo, detection, yes, scopeOverride, plug
79
76
  process.exit(1);
80
77
  }
81
78
  printSuccess('Marketplace added');
82
- // Install each selected plugin
83
79
  let failures = 0;
84
80
  for (const plugin of selectedPlugins) {
85
81
  printStep(`Installing ${plugin.name}...`);
@@ -104,7 +100,6 @@ async function installMarketplace(ownerRepo, detection, yes, scopeOverride, plug
104
100
  }
105
101
  async function installStandalone(ownerRepo, detection, yes, scopeOverride) {
106
102
  printSuccess(`Plugin "${detection.name}" (strict: ${detection.strict})`);
107
- // Scope picker
108
103
  let scope = scopeOverride ?? 'project';
109
104
  if (!yes && !scopeOverride) {
110
105
  print('');
@@ -115,7 +110,6 @@ async function installStandalone(ownerRepo, detection, yes, scopeOverride) {
115
110
  }
116
111
  scope = chosenScope;
117
112
  }
118
- // Write wrapper marketplace
119
113
  print('');
120
114
  printStep('Creating wrapper marketplace...');
121
115
  const { wrapperDir, marketplaceName } = writeWrapperMarketplace({
@@ -125,7 +119,6 @@ async function installStandalone(ownerRepo, detection, yes, scopeOverride) {
125
119
  strict: detection.strict,
126
120
  });
127
121
  printSuccess(`Wrapper at ${DIM}${wrapperDir}${RESET}`);
128
- // Add wrapper marketplace
129
122
  printStep('Adding marketplace...');
130
123
  const addResult = claudeMarketplaceAdd(wrapperDir, scope);
131
124
  if (!addResult.ok) {
@@ -133,7 +126,6 @@ async function installStandalone(ownerRepo, detection, yes, scopeOverride) {
133
126
  process.exit(1);
134
127
  }
135
128
  printSuccess('Marketplace added');
136
- // Install the plugin
137
129
  printStep(`Installing ${detection.name}...`);
138
130
  const installResult = claudePluginInstall(detection.name, marketplaceName, scope);
139
131
  if (!installResult.ok) {
@@ -175,7 +167,6 @@ export async function runGithubRemove(ownerRepo, scopeOverride) {
175
167
  }
176
168
  printStep(`Removing ${ownerRepo} (scope: ${scope})...`);
177
169
  let anyFailed = false;
178
- // Best-effort: uninstall plugin
179
170
  const uninstallResult = claudePluginUninstall(meta.pluginName, scope);
180
171
  if (uninstallResult.ok) {
181
172
  printSuccess(`Uninstalled plugin ${meta.pluginName}`);
@@ -184,7 +175,6 @@ export async function runGithubRemove(ownerRepo, scopeOverride) {
184
175
  printWarning(`Could not uninstall plugin: ${uninstallResult.output}`);
185
176
  anyFailed = true;
186
177
  }
187
- // Best-effort: remove marketplace
188
178
  const removeResult = claudeMarketplaceRemove(meta.marketplaceName, scope);
189
179
  if (removeResult.ok) {
190
180
  printSuccess(`Removed marketplace ${meta.marketplaceName}`);
@@ -194,7 +184,7 @@ export async function runGithubRemove(ownerRepo, scopeOverride) {
194
184
  anyFailed = true;
195
185
  }
196
186
  if (anyFailed) {
197
- // Keep wrapper metadata so the user can retry cleanup later
187
+ // Keep the wrapper metadata so a retry can finish the cleanup.
198
188
  print('');
199
189
  print(`${YELLOW}${BOLD}Partially removed.${RESET} Some cleanup steps failed.`);
200
190
  const wrapperDir = getWrapperDir(ownerRepo, scope);
@@ -203,7 +193,6 @@ export async function runGithubRemove(ownerRepo, scopeOverride) {
203
193
  print(`Retry with ${DIM}npx claudepluginhub remove ${ownerRepo} --scope ${scope}${RESET}`);
204
194
  }
205
195
  else {
206
- // All native cleanup succeeded — safe to delete wrapper
207
196
  removeWrapperDir(ownerRepo, scope);
208
197
  printSuccess('Removed wrapper directory');
209
198
  print('');