claudepluginhub 0.9.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,130 @@
1
+ import type { Finding, InstallationRecord, ScanResult } from './report.js';
2
+ import type { SelectionOutput } from './select.js';
3
+ /**
4
+ * The single source of truth for finding codes and their severities. Rules
5
+ * and renderers both key off this table, so severity policy cannot drift.
6
+ *
7
+ * Facts vs findings: capability inventory (hooks exist, MCP servers exist,
8
+ * env key names, monitors, estimates) lives on plugin entries as FIELDS. The
9
+ * findings list carries only actionable conditions — a healthy plugin with
10
+ * hooks and MCP servers produces zero findings.
11
+ *
12
+ * Remediation policy: inspection-first, never chained, never destructive on
13
+ * ambiguity. A mutating suggestion appears only when its target is
14
+ * unambiguous from the finding itself.
15
+ */
16
+ export declare const FINDING_CODES: {
17
+ readonly record_malformed: {
18
+ readonly severity: "warning";
19
+ readonly title: "Malformed plugin list record";
20
+ };
21
+ readonly claude_plugin_load_error: {
22
+ readonly severity: "error";
23
+ readonly title: "Claude Code reports a plugin load error";
24
+ };
25
+ readonly install_path_missing: {
26
+ readonly severity: "error";
27
+ readonly title: "Install path does not exist";
28
+ };
29
+ readonly install_path_unreadable: {
30
+ readonly severity: "error";
31
+ readonly title: "Install path is not readable";
32
+ };
33
+ readonly install_path_not_directory: {
34
+ readonly severity: "error";
35
+ readonly title: "Install path is not a directory";
36
+ };
37
+ readonly disabled_record_issue: {
38
+ readonly severity: "info";
39
+ readonly title: "Disabled installation has stale or invalid content";
40
+ };
41
+ readonly duplicate_record: {
42
+ readonly severity: "warning";
43
+ readonly title: "Duplicate installation record";
44
+ };
45
+ readonly duplicate_enabled_records: {
46
+ readonly severity: "warning";
47
+ readonly title: "Multiple enabled installation records";
48
+ };
49
+ readonly effective_selection_ambiguous: {
50
+ readonly severity: "warning";
51
+ readonly title: "Effective plugin selection is ambiguous";
52
+ };
53
+ readonly scope_unknown: {
54
+ readonly severity: "info";
55
+ readonly title: "Unrecognized plugin scope";
56
+ };
57
+ readonly manifest_invalid_json: {
58
+ readonly severity: "error";
59
+ readonly title: "Plugin manifest is not valid JSON";
60
+ };
61
+ readonly manifest_invalid_name: {
62
+ readonly severity: "error";
63
+ readonly title: "Plugin manifest name is invalid";
64
+ };
65
+ readonly manifest_field_invalid: {
66
+ readonly severity: "error";
67
+ readonly title: "Plugin manifest field has an invalid type";
68
+ };
69
+ readonly declared_component_missing: {
70
+ readonly severity: "warning";
71
+ readonly title: "Manifest-declared component path is missing";
72
+ };
73
+ readonly component_parse_error: {
74
+ readonly severity: "warning";
75
+ readonly title: "Component configuration could not be parsed";
76
+ };
77
+ readonly exact_component_overlap: {
78
+ readonly severity: "warning";
79
+ readonly title: "Exact component content overlap";
80
+ };
81
+ readonly hook_broad_unconditional: {
82
+ readonly severity: "warning";
83
+ readonly title: "Broad unconditional command hook";
84
+ };
85
+ readonly prerequisite_missing: {
86
+ readonly severity: "warning";
87
+ readonly title: "Declared executable not found on PATH";
88
+ };
89
+ readonly bin_not_executable: {
90
+ readonly severity: "warning";
91
+ readonly title: "bin/ file is not executable";
92
+ };
93
+ readonly dependency_missing: {
94
+ readonly severity: "warning";
95
+ readonly title: "Declared plugin dependency is not installed";
96
+ };
97
+ readonly dependency_disabled: {
98
+ readonly severity: "warning";
99
+ readonly title: "Declared plugin dependency is disabled";
100
+ };
101
+ readonly dependency_resolution_unknown: {
102
+ readonly severity: "info";
103
+ readonly title: "Plugin dependency could not be verified";
104
+ };
105
+ readonly lsp_extension_conflict: {
106
+ readonly severity: "warning";
107
+ readonly title: "Multiple LSP servers claim the same extension";
108
+ };
109
+ readonly scan_incomplete: {
110
+ readonly severity: "warning";
111
+ readonly title: "Plugin scan hit a resource limit";
112
+ };
113
+ readonly symlink_skipped: {
114
+ readonly severity: "warning";
115
+ readonly title: "Symlinks skipped during scan";
116
+ };
117
+ };
118
+ export type FindingCode = keyof typeof FINDING_CODES;
119
+ export declare function makeFinding(code: FindingCode, message: string, pluginIds: string[], evidence?: Record<string, unknown>, remediation?: string): Finding;
120
+ export interface AnalysisInput {
121
+ selection: SelectionOutput;
122
+ /** Scan lookup by record (memoized per canonical root inside the scanner). */
123
+ scanFor: (record: InstallationRecord) => ScanResult;
124
+ droppedRecords: number;
125
+ }
126
+ export interface AnalysisOutput {
127
+ global: Finding[];
128
+ byContext: Map<string, Finding[]>;
129
+ }
130
+ export declare function analyze(input: AnalysisInput): AnalysisOutput;
Binary file
@@ -0,0 +1,29 @@
1
+ import type { Scanner } from './inventory.js';
2
+ import type { DoctorFlags, DoctorReport, InstallationRecord } from './report.js';
3
+ /**
4
+ * Doctor orchestrator. Read-only by construction: the only child process is
5
+ * the Claude CLI itself, and the only filesystem access is bounded reads
6
+ * inside plugin install roots.
7
+ *
8
+ * Exit codes: 0 = completed without failing findings; 1 = completed but found
9
+ * errors (or warnings under --strict); 2 = could not run / could not perform
10
+ * the primary inventory (bad arguments, Claude CLI missing, unusable
11
+ * `plugin list --json` output).
12
+ */
13
+ export interface DoctorRunInputs {
14
+ records: InstallationRecord[];
15
+ droppedRecords: number;
16
+ claudeVersion: string | null;
17
+ cwdCanonical: string;
18
+ flags: DoctorFlags;
19
+ scanner: Scanner;
20
+ }
21
+ export declare function buildDoctorReport(inputs: DoctorRunInputs): DoctorReport;
22
+ export declare function exitCodeFor(report: DoctorReport, strict: boolean): number;
23
+ /**
24
+ * Exit via process.exitCode, never process.exit(): a forced exit tears the
25
+ * process down before a large report piped to a slow consumer has drained,
26
+ * truncating stdout mid-document. Setting exitCode lets Node flush stdout
27
+ * naturally and then exit on its own.
28
+ */
29
+ export declare function runDoctor(argv: string[]): Promise<void>;
@@ -0,0 +1,235 @@
1
+ import { DOCTOR_HELP, parseDoctorFlags } from './args.js';
2
+ import { probeClaude } from './claude-source.js';
3
+ import { canonicalize } from './paths.js';
4
+ import { selectEffective } from './select.js';
5
+ import { createScanner } from './inventory.js';
6
+ import { analyze } from './rules.js';
7
+ import { estimatePlugin } from './estimate.js';
8
+ import { renderHuman, renderJson } from './render.js';
9
+ import { boundEvidenceString, cappedList, recapList, comparePluginEntries, DOCTOR_SCHEMA_VERSION, MAX_CAPABILITY_ITEMS, MAX_EVIDENCE_ITEMS, MAX_FINDINGS, MAX_PATHS_PER_TYPE, MAX_PLUGINS_PER_CONTEXT, MAX_UNKNOWN_SCOPE_RECORDS, } from './report.js';
10
+ const VERSION_UNKNOWN_NOTE = 'Version "unknown" is documented-legitimate (npm sources or local directories outside a git repository).';
11
+ function componentSummaries(scan) {
12
+ const byType = {
13
+ skills: [],
14
+ commands: [],
15
+ agents: [],
16
+ outputStyles: [],
17
+ themes: [...scan.themeFiles],
18
+ };
19
+ const typeKey = {
20
+ skill: 'skills',
21
+ command: 'commands',
22
+ agent: 'agents',
23
+ outputStyle: 'outputStyles',
24
+ };
25
+ for (const component of scan.components) {
26
+ byType[typeKey[component.type]].push(component.relPath);
27
+ }
28
+ const out = {};
29
+ for (const [type, paths] of Object.entries(byType)) {
30
+ out[type] = {
31
+ count: paths.length,
32
+ paths: cappedList(paths.sort().map(boundEvidenceString), MAX_PATHS_PER_TYPE),
33
+ };
34
+ }
35
+ return out;
36
+ }
37
+ function capabilities(scan) {
38
+ const byEvent = new Map();
39
+ for (const hook of scan.hooks) {
40
+ const entry = byEvent.get(hook.event) ?? { count: 0, broad: 0, conditional: 0 };
41
+ entry.count += 1;
42
+ if (hook.broad)
43
+ entry.broad += 1;
44
+ if (hook.conditional)
45
+ entry.conditional += 1;
46
+ byEvent.set(hook.event, entry);
47
+ }
48
+ return {
49
+ hooks: {
50
+ total: scan.hooks.length,
51
+ byEvent: cappedList([...byEvent.entries()]
52
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
53
+ .map(([event, stats]) => ({ event, ...stats })), MAX_CAPABILITY_ITEMS),
54
+ },
55
+ mcp: cappedList(scan.mcp.map((m) => ({
56
+ name: m.name,
57
+ kind: m.kind,
58
+ executable: m.command?.executable ?? null,
59
+ targetOrigin: m.targetOrigin,
60
+ envKeys: recapList(m.envKeys, MAX_EVIDENCE_ITEMS),
61
+ headerKeys: recapList(m.headerKeys, MAX_EVIDENCE_ITEMS),
62
+ })), MAX_CAPABILITY_ITEMS),
63
+ lsp: cappedList(scan.lsp.map((l) => ({
64
+ name: l.name,
65
+ extensions: recapList(l.extensions, MAX_EVIDENCE_ITEMS),
66
+ languages: recapList(l.languages, MAX_EVIDENCE_ITEMS),
67
+ })), MAX_CAPABILITY_ITEMS),
68
+ monitors: cappedList(scan.monitors.map((m) => ({
69
+ name: m.name,
70
+ when: m.when,
71
+ executable: m.command?.executable ?? null,
72
+ })), MAX_CAPABILITY_ITEMS),
73
+ binCount: scan.bin.length,
74
+ };
75
+ }
76
+ function makeEntry(record, selection, scan) {
77
+ const scanned = scan.pathIssue === null;
78
+ const estimate = selection === 'sole' && scanned ? estimatePlugin(scan) : null;
79
+ return {
80
+ id: record.id,
81
+ version: record.version,
82
+ versionNote: record.version === 'unknown' ? VERSION_UNKNOWN_NOTE : null,
83
+ scope: record.scope,
84
+ enabled: record.enabled,
85
+ selection,
86
+ nativeErrors: record.errors,
87
+ components: scanned ? componentSummaries(scan) : null,
88
+ capabilities: scanned ? capabilities(scan) : null,
89
+ estAlwaysOnTokens: estimate ? estimate.alwaysOnTokens : null,
90
+ estimated: estimate ? estimate.estimated : false,
91
+ largestOnInvoke: estimate ? estimate.largestOnInvoke : [],
92
+ inventoryIncomplete: scan.incomplete,
93
+ };
94
+ }
95
+ function buildContextReport(contextSelection, findings, scanFor) {
96
+ const { context, applicable, disabled, instances } = contextSelection;
97
+ const selectionByRecord = new Map();
98
+ for (const instance of instances) {
99
+ for (const contender of instance.contenders) {
100
+ selectionByRecord.set(contender, instance.selection);
101
+ }
102
+ }
103
+ // Sort and cap FIRST, then build entries — a hostile record list must not
104
+ // cost one PluginEntry (and one scan lookup) per record beyond the cap.
105
+ const listedRecords = [...applicable].sort(comparePluginEntries);
106
+ const keptRecords = listedRecords.slice(0, MAX_PLUGINS_PER_CONTEXT);
107
+ const plugins = {
108
+ items: keptRecords.map((record) => makeEntry(record, record.enabled ? (selectionByRecord.get(record) ?? 'sole') : 'disabled', scanFor(record))),
109
+ total: listedRecords.length,
110
+ omitted: listedRecords.length - keptRecords.length,
111
+ };
112
+ // Context totals count only unambiguous instances (the ambiguity findings
113
+ // say exactly that); the aggregate estimate is honest about coverage — an
114
+ // unreachable, incomplete, or unestimable scan makes it a lower bound.
115
+ const soleInstances = instances.filter((i) => i.selection === 'sole' && i.record !== null);
116
+ let estimatedAlwaysOnTokens = null;
117
+ let estimateComplete = true;
118
+ if (soleInstances.length > 0) {
119
+ let sum = 0;
120
+ for (const instance of soleInstances) {
121
+ const scan = scanFor(instance.record);
122
+ if (scan.pathIssue !== null) {
123
+ estimateComplete = false;
124
+ continue;
125
+ }
126
+ const estimate = estimatePlugin(scan);
127
+ sum += estimate.alwaysOnTokens;
128
+ if (!estimate.estimated)
129
+ estimateComplete = false;
130
+ }
131
+ estimatedAlwaysOnTokens = sum;
132
+ }
133
+ return {
134
+ key: context.key,
135
+ label: context.label,
136
+ isCurrent: context.isCurrent,
137
+ plugins,
138
+ findings: cappedList(findings, MAX_FINDINGS),
139
+ summary: {
140
+ activePlugins: soleInstances.length,
141
+ ambiguousPlugins: instances.filter((i) => i.selection === 'ambiguous').length,
142
+ disabledRecords: disabled.length,
143
+ estimatedAlwaysOnTokens,
144
+ estimateComplete,
145
+ },
146
+ };
147
+ }
148
+ export function buildDoctorReport(inputs) {
149
+ const { records, droppedRecords, claudeVersion, cwdCanonical, flags, scanner } = inputs;
150
+ const selection = selectEffective(records, cwdCanonical, flags);
151
+ const scanCache = new Map();
152
+ const scanFor = (record) => {
153
+ const cached = scanCache.get(record);
154
+ if (cached)
155
+ return cached;
156
+ const scan = scanner.scan(record.installPath);
157
+ scanCache.set(record, scan);
158
+ return scan;
159
+ };
160
+ const analysis = analyze({ selection, scanFor, droppedRecords });
161
+ const contexts = selection.contexts.map((contextSelection) => buildContextReport(contextSelection, analysis.byContext.get(contextSelection.context.key) ?? [], scanFor));
162
+ const allFindings = [...analysis.global, ...[...analysis.byContext.values()].flat()];
163
+ const summary = {
164
+ errors: allFindings.filter((f) => f.severity === 'error').length,
165
+ warnings: allFindings.filter((f) => f.severity === 'warning').length,
166
+ notes: allFindings.filter((f) => f.severity === 'info').length,
167
+ otherProjectRecordsIgnored: selection.otherProjectRecords.length,
168
+ };
169
+ const stats = scanner.stats();
170
+ return {
171
+ schemaVersion: DOCTOR_SCHEMA_VERSION,
172
+ claude: { version: claudeVersion },
173
+ options: { scope: flags.scope, allProjects: flags.allProjects, strict: flags.strict },
174
+ contexts,
175
+ contextsOmitted: selection.contextsOmitted,
176
+ findings: cappedList(analysis.global, MAX_FINDINGS),
177
+ unknownScopeRecords: cappedList(selection.unknownScopeRecords
178
+ .map((r) => ({ id: r.id, rawScope: r.rawScope, enabled: r.enabled }))
179
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), MAX_UNKNOWN_SCOPE_RECORDS),
180
+ summary,
181
+ scan: stats,
182
+ };
183
+ }
184
+ export function exitCodeFor(report, strict) {
185
+ if (report.summary.errors > 0)
186
+ return 1;
187
+ if (strict && report.summary.warnings > 0)
188
+ return 1;
189
+ return 0;
190
+ }
191
+ /**
192
+ * Exit via process.exitCode, never process.exit(): a forced exit tears the
193
+ * process down before a large report piped to a slow consumer has drained,
194
+ * truncating stdout mid-document. Setting exitCode lets Node flush stdout
195
+ * naturally and then exit on its own.
196
+ */
197
+ export async function runDoctor(argv) {
198
+ const parsed = parseDoctorFlags(argv);
199
+ if (parsed.kind === 'error') {
200
+ process.stderr.write(`Error: ${parsed.message}\nRun \`npx claudepluginhub doctor --help\` for usage.\n`);
201
+ process.exitCode = 2;
202
+ return;
203
+ }
204
+ if (parsed.kind === 'help') {
205
+ process.stdout.write(DOCTOR_HELP);
206
+ process.exitCode = 0;
207
+ return;
208
+ }
209
+ const { flags } = parsed;
210
+ const probe = probeClaude();
211
+ if (!probe.ok) {
212
+ process.stderr.write(`Error: ${probe.reason}\n`);
213
+ process.exitCode = 2;
214
+ return;
215
+ }
216
+ const cwdCanonical = canonicalize(process.cwd());
217
+ let report;
218
+ try {
219
+ report = buildDoctorReport({
220
+ records: probe.records,
221
+ droppedRecords: probe.droppedRecords,
222
+ claudeVersion: probe.claudeVersion,
223
+ cwdCanonical,
224
+ flags,
225
+ scanner: createScanner(),
226
+ });
227
+ }
228
+ catch (err) {
229
+ process.stderr.write(`Error: doctor failed unexpectedly: ${err.message}\n`);
230
+ process.exitCode = 2;
231
+ return;
232
+ }
233
+ process.stdout.write(flags.json ? renderJson(report) : renderHuman(report));
234
+ process.exitCode = exitCodeFor(report, flags.strict);
235
+ }
@@ -0,0 +1,28 @@
1
+ import type { CommandFact, NativePluginError } from './report.js';
2
+ /**
3
+ * Bound an externally sourced identifier (server/monitor name, hook event,
4
+ * extension, env/header key) so hostile input cannot inflate the report.
5
+ */
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
+ /** Reduce a URL to scheme://host[:port] — never path, query, fragment, userinfo. */
16
+ export declare function sanitizeUrlOrigin(raw: unknown): string;
17
+ /**
18
+ * Reduce a command declaration to {form, executable basename}. The serialized
19
+ * command string is intentionally not retained anywhere.
20
+ */
21
+ export declare function sanitizeCommand(command: unknown, args: unknown): CommandFact | null;
22
+ export declare function isDependencyErrorKind(kind: string): boolean;
23
+ /**
24
+ * Tolerant parse of a record's optional `errors` field. Any unexpected shape
25
+ * yields [] (or a generic entry per element) — it never invalidates the
26
+ * record, and raw native text is never stored.
27
+ */
28
+ export declare function sanitizeNativeErrors(raw: unknown): NativePluginError[];
@@ -0,0 +1,150 @@
1
+ import { basename } from 'node:path';
2
+ /**
3
+ * Data-minimizing sanitization: the report is safe to share because sensitive
4
+ * material is NOT STORED, not because regexes mask it. URLs keep only their
5
+ * origin (paths/queries/fragments/userinfo can carry opaque credentials);
6
+ * commands keep only their form and an executable basename; env/header VALUES
7
+ * are dropped at parse time and have no field to live in; native error
8
+ * messages are reduced to a classified kind plus our own canonical summary.
9
+ */
10
+ const MAX_EXECUTABLE_CHARS = 64;
11
+ const MAX_NAME_CHARS = 64;
12
+ /**
13
+ * Bound an externally sourced identifier (server/monitor name, hook event,
14
+ * extension, env/header key) so hostile input cannot inflate the report.
15
+ */
16
+ export function boundName(value) {
17
+ return value.length > MAX_NAME_CHARS ? `${value.slice(0, MAX_NAME_CHARS - 1)}…` : value;
18
+ }
19
+ /**
20
+ * Opaque credential-shaped token, tuned to leave real tool names alone:
21
+ * ≥20 chars AND either a solid base64/hex-ish run with no word separators
22
+ * (AKIA-style keys) or a mixed-case+digit blob (JWT segments, random
23
+ * tokens). Hyphenated lowercase names like `typescript-language-server`
24
+ * must survive — they are the diagnostic value.
25
+ */
26
+ export function looksOpaque(token) {
27
+ if (token.length < 20)
28
+ return false;
29
+ if (/^[A-Za-z0-9+/=_]+$/.test(token))
30
+ return true;
31
+ if (!/^[A-Za-z0-9+/=_.-]+$/.test(token))
32
+ return false;
33
+ return /[a-z]/.test(token) && /[A-Z]/.test(token) && /\d/.test(token);
34
+ }
35
+ /** Reduce a URL to scheme://host[:port] — never path, query, fragment, userinfo. */
36
+ export function sanitizeUrlOrigin(raw) {
37
+ if (typeof raw !== 'string' || raw.length === 0)
38
+ return '<unparseable-url>';
39
+ try {
40
+ const url = new URL(raw);
41
+ return url.origin !== 'null' ? url.origin : `${url.protocol}//${url.host}`;
42
+ }
43
+ catch {
44
+ return '<unparseable-url>';
45
+ }
46
+ }
47
+ /**
48
+ * Reduce a command declaration to {form, executable basename}. The serialized
49
+ * command string is intentionally not retained anywhere.
50
+ */
51
+ export function sanitizeCommand(command, args) {
52
+ if (typeof command !== 'string' || command.trim().length === 0)
53
+ return null;
54
+ const form = Array.isArray(args) ? 'exec' : 'shell';
55
+ const firstToken = form === 'shell' ? command.trim().split(/\s+/)[0] : command.trim();
56
+ let executable = basename(firstToken);
57
+ if (looksOpaque(executable))
58
+ executable = '<redacted>';
59
+ if (executable.length > MAX_EXECUTABLE_CHARS) {
60
+ executable = `${executable.slice(0, MAX_EXECUTABLE_CHARS - 1)}…`;
61
+ }
62
+ return { form, executable };
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
+ /** Documented dependency/load error codes (plugin-dependencies docs). */
69
+ const RECOGNIZED_CODES = new Set([
70
+ 'dependency-unsatisfied',
71
+ 'dependency-version-unsatisfied',
72
+ 'range-conflict',
73
+ 'no-matching-tag',
74
+ ]);
75
+ const CODE_TOKEN_RE = /^[a-z0-9-]{1,64}$/;
76
+ /** Strict plugin-id validation for ids extracted from native messages. */
77
+ const DEPENDENCY_ID_RE = /^[a-zA-Z0-9_.-]+(@[a-zA-Z0-9_.-]+)?$/;
78
+ const DEPENDENCY_MESSAGE_RE = /^Dependency "([^"]{1,128})" is not installed/;
79
+ const DEPENDENCY_KINDS = new Set([
80
+ 'dependency-missing',
81
+ 'dependency-unsatisfied',
82
+ 'dependency-version-unsatisfied',
83
+ 'range-conflict',
84
+ 'no-matching-tag',
85
+ ]);
86
+ export function isDependencyErrorKind(kind) {
87
+ return DEPENDENCY_KINDS.has(kind);
88
+ }
89
+ function fromString(message) {
90
+ const match = message.match(DEPENDENCY_MESSAGE_RE);
91
+ if (match) {
92
+ const candidate = match[1];
93
+ const dependencyId = DEPENDENCY_ID_RE.test(candidate) ? candidate : undefined;
94
+ return {
95
+ kind: 'dependency-missing',
96
+ recognized: true,
97
+ summary: dependencyId
98
+ ? `Claude Code reports that dependency "${dependencyId}" is not installed`
99
+ : 'Claude Code reports that a declared dependency is not installed',
100
+ ...(dependencyId ? { dependencyId } : {}),
101
+ };
102
+ }
103
+ return {
104
+ kind: 'unknown',
105
+ recognized: false,
106
+ summary: 'Claude Code reports a plugin load error',
107
+ };
108
+ }
109
+ function fromObject(value) {
110
+ const rawCode = value.code;
111
+ if (typeof rawCode === 'string' && CODE_TOKEN_RE.test(rawCode)) {
112
+ if (RECOGNIZED_CODES.has(rawCode)) {
113
+ return {
114
+ kind: rawCode,
115
+ recognized: true,
116
+ summary: `Claude Code reports a plugin load error (${rawCode})`,
117
+ };
118
+ }
119
+ return {
120
+ kind: rawCode,
121
+ recognized: false,
122
+ summary: `Claude Code reports a plugin load error (code: ${rawCode})`,
123
+ };
124
+ }
125
+ return {
126
+ kind: 'unknown',
127
+ recognized: false,
128
+ summary: 'Claude Code reports a plugin load error',
129
+ };
130
+ }
131
+ /**
132
+ * Tolerant parse of a record's optional `errors` field. Any unexpected shape
133
+ * yields [] (or a generic entry per element) — it never invalidates the
134
+ * record, and raw native text is never stored.
135
+ */
136
+ export function sanitizeNativeErrors(raw) {
137
+ if (!Array.isArray(raw))
138
+ return [];
139
+ const out = [];
140
+ for (const element of raw.slice(0, 20)) {
141
+ if (typeof element === 'string') {
142
+ out.push(fromString(element));
143
+ }
144
+ else if (element && typeof element === 'object' && !Array.isArray(element)) {
145
+ out.push(fromObject(element));
146
+ }
147
+ // other element shapes are ignored — tolerant by design
148
+ }
149
+ return out;
150
+ }
@@ -0,0 +1,53 @@
1
+ import type { DoctorFlags, EffectiveInstance, InstallationRecord, ProjectContext } from './report.js';
2
+ /**
3
+ * Project contexts and effective-instance selection.
4
+ *
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).
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.
30
+ */
31
+ export interface ContextSelection {
32
+ context: ProjectContext;
33
+ /** Applicable records after --scope filtering, enabled and disabled. */
34
+ applicable: InstallationRecord[];
35
+ disabled: InstallationRecord[];
36
+ instances: EffectiveInstance[];
37
+ }
38
+ export interface SelectionOutput {
39
+ contexts: ContextSelection[];
40
+ /** Distinct project paths beyond MAX_CONTEXTS that were not analyzed. */
41
+ contextsOmitted: number;
42
+ unknownScopeRecords: InstallationRecord[];
43
+ /** Project/local records not attributable to any built context (other
44
+ * projects in default mode; missing/stale project paths or omitted
45
+ * contexts under --all-projects). */
46
+ otherProjectRecords: InstallationRecord[];
47
+ }
48
+ export interface BuiltContexts {
49
+ contexts: ProjectContext[];
50
+ omitted: number;
51
+ }
52
+ export declare function buildContexts(records: InstallationRecord[], cwdCanonical: string, allProjects: boolean): BuiltContexts;
53
+ export declare function selectEffective(records: InstallationRecord[], cwdCanonical: string, flags: DoctorFlags): SelectionOutput;
Binary file
package/dist/index.js CHANGED
@@ -29,6 +29,8 @@ Commands:
29
29
  list List all installed collections
30
30
  remove <identifier> Remove
31
31
  recommend Recommend plugins for the current project
32
+ doctor Diagnose the Claude Code plugin setup (read-only,
33
+ offline; see \`doctor --help\`)
32
34
 
33
35
  Identifiers:
34
36
  owner/repo GitHub plugin or marketplace (via Claude Code)
@@ -54,8 +56,8 @@ Notes:
54
56
 
55
57
  Recommend (reads local manifest dependency names + config filenames only —
56
58
  never file contents):
57
- recommend Ranked plugins for your detected stacks
58
- recommend --limit 20 Number of results (1-50, default 10)
59
+ recommend Top plugins grouped by each detected stack
60
+ recommend --limit 6 Results per stack (1-50, default 4)
59
61
  recommend --json Raw JSON output
60
62
 
61
63
  Options:
@@ -71,6 +73,14 @@ Options:
71
73
  }
72
74
  async function main() {
73
75
  const args = process.argv.slice(2);
76
+ // doctor owns its full flag parsing (incl. `--scope all`, which the global
77
+ // parseArgs rejects, and its own --help) — route it before the global help
78
+ // intercept and parseArgs. It also owns its banner and exit codes (0/1/2).
79
+ if (args[0] === 'doctor') {
80
+ const { runDoctor } = await import('./doctor/run.js');
81
+ await runDoctor(args.slice(1));
82
+ return;
83
+ }
74
84
  if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
75
85
  printBanner();
76
86
  printUsage();