claudepluginhub 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -3
- package/dist/doctor/args.d.ts +12 -0
- package/dist/doctor/args.js +111 -0
- package/dist/doctor/claude-source.d.ts +27 -0
- package/dist/doctor/claude-source.js +115 -0
- package/dist/doctor/color.d.ts +11 -0
- package/dist/doctor/color.js +23 -0
- package/dist/doctor/equivalence.d.ts +9 -0
- package/dist/doctor/equivalence.js +263 -0
- package/dist/doctor/estimate.d.ts +30 -0
- package/dist/doctor/estimate.js +47 -0
- package/dist/doctor/html-report.d.ts +9 -0
- package/dist/doctor/html-report.js +385 -0
- package/dist/doctor/inventory.d.ts +69 -0
- package/dist/doctor/inventory.js +1175 -0
- package/dist/doctor/open-browser.d.ts +11 -0
- package/dist/doctor/open-browser.js +38 -0
- package/dist/doctor/overlap.d.ts +22 -0
- package/dist/doctor/overlap.js +23 -0
- package/dist/doctor/paths.d.ts +9 -0
- package/dist/doctor/paths.js +23 -0
- package/dist/doctor/render.d.ts +3 -0
- package/dist/doctor/render.js +353 -0
- package/dist/doctor/report.d.ts +347 -0
- package/dist/doctor/report.js +70 -0
- package/dist/doctor/rules.d.ts +167 -0
- package/dist/doctor/rules.js +342 -0
- package/dist/doctor/run.d.ts +24 -0
- package/dist/doctor/run.js +315 -0
- package/dist/doctor/sanitize.d.ts +28 -0
- package/dist/doctor/sanitize.js +150 -0
- package/dist/doctor/select.d.ts +53 -0
- package/dist/doctor/select.js +100 -0
- package/dist/doctor/wrap.d.ts +2 -0
- package/dist/doctor/wrap.js +84 -0
- package/dist/index.js +10 -0
- package/package.json +1 -1
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { mkdtempSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { DOCTOR_HELP, parseDoctorFlags } from './args.js';
|
|
5
|
+
import { probeClaude } from './claude-source.js';
|
|
6
|
+
import { canonicalize } from './paths.js';
|
|
7
|
+
import { selectEffective } from './select.js';
|
|
8
|
+
import { resolveEquivalences } from './equivalence.js';
|
|
9
|
+
import { createScanner } from './inventory.js';
|
|
10
|
+
import { analyze } from './rules.js';
|
|
11
|
+
import { estimatePlugin } from './estimate.js';
|
|
12
|
+
import { renderHuman, renderJson } from './render.js';
|
|
13
|
+
import { renderHtml } from './html-report.js';
|
|
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). */
|
|
17
|
+
export function writeReportFile(filePath, html) {
|
|
18
|
+
writeFileSync(filePath, html, { flag: 'wx', mode: 0o600 });
|
|
19
|
+
}
|
|
20
|
+
export async function openReport(report, opener) {
|
|
21
|
+
const html = renderHtml(report);
|
|
22
|
+
const tmpDir = mkdtempSync(join(tmpdir(), 'cph-doctor-'));
|
|
23
|
+
const reportPath = join(tmpDir, 'report.html');
|
|
24
|
+
writeReportFile(reportPath, html);
|
|
25
|
+
const opened = await opener.open(reportPath);
|
|
26
|
+
return { path: reportPath, opened };
|
|
27
|
+
}
|
|
28
|
+
const VERSION_UNKNOWN_NOTE = 'Version "unknown" is documented-legitimate (npm sources or local directories outside a git repository).';
|
|
29
|
+
function componentSummaries(scan) {
|
|
30
|
+
const byType = {
|
|
31
|
+
skills: [],
|
|
32
|
+
commands: [],
|
|
33
|
+
agents: [],
|
|
34
|
+
outputStyles: [],
|
|
35
|
+
themes: [...scan.themeFiles],
|
|
36
|
+
};
|
|
37
|
+
const typeKey = {
|
|
38
|
+
skill: 'skills',
|
|
39
|
+
command: 'commands',
|
|
40
|
+
agent: 'agents',
|
|
41
|
+
outputStyle: 'outputStyles',
|
|
42
|
+
};
|
|
43
|
+
for (const component of scan.components) {
|
|
44
|
+
byType[typeKey[component.type]].push(component.relPath);
|
|
45
|
+
}
|
|
46
|
+
const out = {};
|
|
47
|
+
for (const [type, paths] of Object.entries(byType)) {
|
|
48
|
+
out[type] = {
|
|
49
|
+
count: paths.length,
|
|
50
|
+
paths: cappedList(paths.sort().map(boundEvidenceString), MAX_PATHS_PER_TYPE),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function capabilities(scan) {
|
|
56
|
+
const byEvent = new Map();
|
|
57
|
+
for (const hook of scan.hooks) {
|
|
58
|
+
const entry = byEvent.get(hook.event) ?? { count: 0, broad: 0, conditional: 0 };
|
|
59
|
+
entry.count += 1;
|
|
60
|
+
if (hook.broad)
|
|
61
|
+
entry.broad += 1;
|
|
62
|
+
if (hook.conditional)
|
|
63
|
+
entry.conditional += 1;
|
|
64
|
+
byEvent.set(hook.event, entry);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
hooks: {
|
|
68
|
+
total: scan.hooks.length,
|
|
69
|
+
byEvent: cappedList([...byEvent.entries()]
|
|
70
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
|
|
71
|
+
.map(([event, stats]) => ({ event, ...stats })), MAX_CAPABILITY_ITEMS),
|
|
72
|
+
},
|
|
73
|
+
mcp: cappedList(scan.mcp.map((m) => ({
|
|
74
|
+
name: m.name,
|
|
75
|
+
kind: m.kind,
|
|
76
|
+
executable: m.command?.executable ?? null,
|
|
77
|
+
targetOrigin: m.targetOrigin,
|
|
78
|
+
envKeys: recapList(m.envKeys, MAX_EVIDENCE_ITEMS),
|
|
79
|
+
headerKeys: recapList(m.headerKeys, MAX_EVIDENCE_ITEMS),
|
|
80
|
+
})), MAX_CAPABILITY_ITEMS),
|
|
81
|
+
lsp: cappedList(scan.lsp.map((l) => ({
|
|
82
|
+
name: l.name,
|
|
83
|
+
extensions: recapList(l.extensions, MAX_EVIDENCE_ITEMS),
|
|
84
|
+
languages: recapList(l.languages, MAX_EVIDENCE_ITEMS),
|
|
85
|
+
})), MAX_CAPABILITY_ITEMS),
|
|
86
|
+
monitors: cappedList(scan.monitors.map((m) => ({
|
|
87
|
+
name: m.name,
|
|
88
|
+
when: m.when,
|
|
89
|
+
executable: m.command?.executable ?? null,
|
|
90
|
+
})), MAX_CAPABILITY_ITEMS),
|
|
91
|
+
binCount: scan.bin.length,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function makeEntry(record, selection, scan) {
|
|
95
|
+
const scanned = scan.pathIssue === null;
|
|
96
|
+
const estimate = selection === 'sole' && scanned ? estimatePlugin(scan) : null;
|
|
97
|
+
return {
|
|
98
|
+
id: record.id,
|
|
99
|
+
version: record.version,
|
|
100
|
+
versionNote: record.version === 'unknown' ? VERSION_UNKNOWN_NOTE : null,
|
|
101
|
+
scope: record.scope,
|
|
102
|
+
enabled: record.enabled,
|
|
103
|
+
selection,
|
|
104
|
+
nativeErrors: record.errors,
|
|
105
|
+
components: scanned ? componentSummaries(scan) : null,
|
|
106
|
+
capabilities: scanned ? capabilities(scan) : null,
|
|
107
|
+
estAlwaysOnTokens: estimate ? estimate.alwaysOnTokens : null,
|
|
108
|
+
estimated: estimate ? estimate.estimated : false,
|
|
109
|
+
largestOnInvoke: estimate ? estimate.largestOnInvoke : [],
|
|
110
|
+
inventoryIncomplete: scan.incomplete,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function buildEffectivePlugins(contextSelection, scanFor) {
|
|
114
|
+
return contextSelection.instances.map((instance) => {
|
|
115
|
+
const record = instance.record;
|
|
116
|
+
const scan = record ? scanFor(record) : null;
|
|
117
|
+
const scanned = scan && scan.pathIssue === null;
|
|
118
|
+
const estimate = instance.selection === 'sole' && scanned ? estimatePlugin(scan) : null;
|
|
119
|
+
const allScopes = cappedList([...new Set(instance.contenders.map((r) => r.scope))].sort(), MAX_CAPABILITY_ITEMS);
|
|
120
|
+
const allVersions = cappedList([...new Set(instance.contenders.map((r) => r.version))].sort(), MAX_CAPABILITY_ITEMS);
|
|
121
|
+
const isAmbiguous = instance.selection === 'ambiguous';
|
|
122
|
+
return {
|
|
123
|
+
id: instance.id,
|
|
124
|
+
selection: instance.selection,
|
|
125
|
+
reason: instance.reason,
|
|
126
|
+
recordCount: instance.contenders.length,
|
|
127
|
+
scopes: allScopes,
|
|
128
|
+
versions: allVersions,
|
|
129
|
+
estAlwaysOnTokens: estimate ? estimate.alwaysOnTokens : null,
|
|
130
|
+
estimated: estimate ? estimate.estimated : false,
|
|
131
|
+
inventoryIncomplete: isAmbiguous ? false : (scan ? scan.incomplete : false),
|
|
132
|
+
components: scanned ? componentSummaries(scan) : null,
|
|
133
|
+
capabilities: scanned ? capabilities(scan) : null,
|
|
134
|
+
largestOnInvoke: estimate ? estimate.largestOnInvoke : [],
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
function buildContributors(effectivePlugins) {
|
|
139
|
+
const sole = effectivePlugins.filter((ep) => ep.selection === 'sole' && ep.estAlwaysOnTokens !== null);
|
|
140
|
+
if (sole.length === 0)
|
|
141
|
+
return null;
|
|
142
|
+
const sorted = [...sole].sort((a, b) => (b.estAlwaysOnTokens ?? 0) - (a.estAlwaysOnTokens ?? 0));
|
|
143
|
+
const top = sorted.slice(0, MAX_TOP_CONTRIBUTORS).map((ep) => ({
|
|
144
|
+
id: ep.id,
|
|
145
|
+
tokens: ep.estAlwaysOnTokens ?? 0,
|
|
146
|
+
}));
|
|
147
|
+
const remaining = sorted.slice(MAX_TOP_CONTRIBUTORS);
|
|
148
|
+
return {
|
|
149
|
+
top,
|
|
150
|
+
remainingCount: remaining.length,
|
|
151
|
+
remainingTokens: remaining.reduce((sum, ep) => sum + (ep.estAlwaysOnTokens ?? 0), 0),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function countCategory(findings, category) {
|
|
155
|
+
return findings.filter((f) => f.category === category).length;
|
|
156
|
+
}
|
|
157
|
+
function buildContextReport(contextSelection, findings, scanFor) {
|
|
158
|
+
const { context, applicable, disabled, instances } = contextSelection;
|
|
159
|
+
const selectionByRecord = new Map();
|
|
160
|
+
for (const instance of instances) {
|
|
161
|
+
for (const contender of instance.contenders) {
|
|
162
|
+
selectionByRecord.set(contender, instance.selection);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const listedRecords = [...applicable].sort(comparePluginEntries);
|
|
166
|
+
const keptRecords = listedRecords.slice(0, MAX_PLUGINS_PER_CONTEXT);
|
|
167
|
+
const plugins = {
|
|
168
|
+
items: keptRecords.map((record) => makeEntry(record, record.enabled ? (selectionByRecord.get(record) ?? 'sole') : 'disabled', scanFor(record))),
|
|
169
|
+
total: listedRecords.length,
|
|
170
|
+
omitted: listedRecords.length - keptRecords.length,
|
|
171
|
+
};
|
|
172
|
+
const allEffective = buildEffectivePlugins(contextSelection, scanFor);
|
|
173
|
+
const effectivePlugins = cappedList(allEffective, MAX_EFFECTIVE_PLUGINS_PER_CONTEXT);
|
|
174
|
+
const contributors = buildContributors(allEffective);
|
|
175
|
+
const soleInstances = instances.filter((i) => i.selection === 'sole' && i.record !== null);
|
|
176
|
+
let estimatedAlwaysOnTokens = null;
|
|
177
|
+
let estimateComplete = true;
|
|
178
|
+
if (soleInstances.length > 0) {
|
|
179
|
+
let sum = 0;
|
|
180
|
+
for (const instance of soleInstances) {
|
|
181
|
+
const scan = scanFor(instance.record);
|
|
182
|
+
if (scan.pathIssue !== null) {
|
|
183
|
+
estimateComplete = false;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const estimate = estimatePlugin(scan);
|
|
187
|
+
sum += estimate.alwaysOnTokens;
|
|
188
|
+
if (!estimate.estimated)
|
|
189
|
+
estimateComplete = false;
|
|
190
|
+
}
|
|
191
|
+
estimatedAlwaysOnTokens = sum;
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
key: context.key,
|
|
195
|
+
label: context.label,
|
|
196
|
+
isCurrent: context.isCurrent,
|
|
197
|
+
plugins,
|
|
198
|
+
effectivePlugins,
|
|
199
|
+
contributors,
|
|
200
|
+
findings: cappedList(findings, MAX_FINDINGS),
|
|
201
|
+
summary: {
|
|
202
|
+
activePlugins: soleInstances.length,
|
|
203
|
+
ambiguousPlugins: instances.filter((i) => i.selection === 'ambiguous').length,
|
|
204
|
+
disabledRecords: disabled.length,
|
|
205
|
+
estimatedAlwaysOnTokens,
|
|
206
|
+
estimateComplete,
|
|
207
|
+
confirmedProblems: countCategory(findings, 'confirmed_problem'),
|
|
208
|
+
reviewItems: countCategory(findings, 'review'),
|
|
209
|
+
coverageGaps: countCategory(findings, 'coverage'),
|
|
210
|
+
maintenanceNotes: countCategory(findings, 'maintenance'),
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
export function buildDoctorReport(inputs) {
|
|
215
|
+
const { records, droppedRecords, claudeVersion, cwdCanonical, flags, scanner } = inputs;
|
|
216
|
+
const baseSelection = selectEffective(records, cwdCanonical, flags);
|
|
217
|
+
const scanCache = new Map();
|
|
218
|
+
const scanFor = (record) => {
|
|
219
|
+
const cached = scanCache.get(record);
|
|
220
|
+
if (cached)
|
|
221
|
+
return cached;
|
|
222
|
+
const scan = scanner.scan(record.installPath);
|
|
223
|
+
scanCache.set(record, scan);
|
|
224
|
+
return scan;
|
|
225
|
+
};
|
|
226
|
+
const { resolved: selection, scanEquivalentKeys } = resolveEquivalences(baseSelection, scanFor);
|
|
227
|
+
const analysis = analyze({ selection, scanFor, droppedRecords, scanEquivalentKeys });
|
|
228
|
+
const contexts = selection.contexts.map((contextSelection) => buildContextReport(contextSelection, analysis.byContext.get(contextSelection.context.key) ?? [], scanFor));
|
|
229
|
+
const allFindings = [...analysis.global, ...[...analysis.byContext.values()].flat()];
|
|
230
|
+
const summary = {
|
|
231
|
+
errors: allFindings.filter((f) => f.severity === 'error').length,
|
|
232
|
+
warnings: allFindings.filter((f) => f.severity === 'warning').length,
|
|
233
|
+
notes: allFindings.filter((f) => f.severity === 'info').length,
|
|
234
|
+
confirmedProblems: countCategory(allFindings, 'confirmed_problem'),
|
|
235
|
+
reviewItems: countCategory(allFindings, 'review'),
|
|
236
|
+
coverageGaps: countCategory(allFindings, 'coverage'),
|
|
237
|
+
maintenanceNotes: countCategory(allFindings, 'maintenance'),
|
|
238
|
+
otherProjectRecordsIgnored: selection.otherProjectRecords.length,
|
|
239
|
+
};
|
|
240
|
+
const stats = scanner.stats();
|
|
241
|
+
return {
|
|
242
|
+
schemaVersion: DOCTOR_SCHEMA_VERSION,
|
|
243
|
+
claude: { version: claudeVersion },
|
|
244
|
+
options: { scope: flags.scope, allProjects: flags.allProjects, strict: flags.strict },
|
|
245
|
+
contexts,
|
|
246
|
+
contextsOmitted: selection.contextsOmitted,
|
|
247
|
+
findings: cappedList(analysis.global, MAX_FINDINGS),
|
|
248
|
+
unknownScopeRecords: cappedList(selection.unknownScopeRecords
|
|
249
|
+
.map((r) => ({ id: r.id, rawScope: r.rawScope, enabled: r.enabled }))
|
|
250
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), MAX_UNKNOWN_SCOPE_RECORDS),
|
|
251
|
+
summary,
|
|
252
|
+
scan: stats,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
export function exitCodeFor(report, strict) {
|
|
256
|
+
if (report.summary.errors > 0)
|
|
257
|
+
return 1;
|
|
258
|
+
if (strict && report.summary.warnings > 0)
|
|
259
|
+
return 1;
|
|
260
|
+
return 0;
|
|
261
|
+
}
|
|
262
|
+
export async function runDoctor(argv, deps) {
|
|
263
|
+
const parsed = parseDoctorFlags(argv);
|
|
264
|
+
if (parsed.kind === 'error') {
|
|
265
|
+
process.stderr.write(`Error: ${parsed.message}\nRun \`npx claudepluginhub doctor --help\` for usage.\n`);
|
|
266
|
+
process.exitCode = 2;
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (parsed.kind === 'help') {
|
|
270
|
+
process.stdout.write(DOCTOR_HELP);
|
|
271
|
+
process.exitCode = 0;
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const { flags } = parsed;
|
|
275
|
+
const probe = probeClaude();
|
|
276
|
+
if (!probe.ok) {
|
|
277
|
+
process.stderr.write(`Error: ${probe.reason}\n`);
|
|
278
|
+
process.exitCode = 2;
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const cwdCanonical = canonicalize(process.cwd());
|
|
282
|
+
let report;
|
|
283
|
+
try {
|
|
284
|
+
report = buildDoctorReport({
|
|
285
|
+
records: probe.records,
|
|
286
|
+
droppedRecords: probe.droppedRecords,
|
|
287
|
+
claudeVersion: probe.claudeVersion,
|
|
288
|
+
cwdCanonical,
|
|
289
|
+
flags,
|
|
290
|
+
scanner: createScanner(),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
catch (err) {
|
|
294
|
+
process.stderr.write(`Error: doctor failed unexpectedly: ${err.message}\n`);
|
|
295
|
+
process.exitCode = 2;
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (flags.open) {
|
|
299
|
+
try {
|
|
300
|
+
const opener = deps?.opener ?? defaultOpener();
|
|
301
|
+
const result = await openReport(report, opener);
|
|
302
|
+
if (!result.opened) {
|
|
303
|
+
process.stderr.write(`Could not open a browser. Report saved to: ${result.path}\n`);
|
|
304
|
+
}
|
|
305
|
+
else if (flags.verbose) {
|
|
306
|
+
process.stderr.write(`Report saved to: ${result.path}\n`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
catch (err) {
|
|
310
|
+
process.stderr.write(`Warning: could not generate local report: ${err.message}\n`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
process.stdout.write(flags.json ? renderJson(report) : renderHuman(report, flags));
|
|
314
|
+
process.exitCode = exitCodeFor(report, flags.strict);
|
|
315
|
+
}
|
|
@@ -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;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { basename } from 'node:path';
|
|
2
|
+
import { compareBytes, MAX_CONTEXTS } from './report.js';
|
|
3
|
+
export function buildContexts(records, cwdCanonical, allProjects) {
|
|
4
|
+
const paths = new Set([cwdCanonical]);
|
|
5
|
+
if (allProjects) {
|
|
6
|
+
for (const record of records) {
|
|
7
|
+
if ((record.scope === 'project' || record.scope === 'local') &&
|
|
8
|
+
record.projectPathCanonical) {
|
|
9
|
+
paths.add(record.projectPathCanonical);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const others = [...paths].filter((p) => p !== cwdCanonical).sort(compareBytes);
|
|
14
|
+
// Hard cap so an arbitrarily long plugin list cannot fan the report out
|
|
15
|
+
// into an unbounded number of context sections (cwd always kept first).
|
|
16
|
+
const ordered = [cwdCanonical, ...others].slice(0, MAX_CONTEXTS);
|
|
17
|
+
const omitted = 1 + others.length - ordered.length;
|
|
18
|
+
return {
|
|
19
|
+
contexts: ordered.map((canonicalPath, index) => ({
|
|
20
|
+
key: `project-${index + 1}`,
|
|
21
|
+
label: basename(canonicalPath) || canonicalPath,
|
|
22
|
+
isCurrent: canonicalPath === cwdCanonical,
|
|
23
|
+
canonicalPath,
|
|
24
|
+
})),
|
|
25
|
+
omitted,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function appliesToContext(record, context) {
|
|
29
|
+
if (record.scope === 'user' || record.scope === 'managed')
|
|
30
|
+
return true;
|
|
31
|
+
if (record.scope === 'project' || record.scope === 'local') {
|
|
32
|
+
return record.projectPathCanonical === context.canonicalPath;
|
|
33
|
+
}
|
|
34
|
+
return false; // unknown scopes never apply — handled separately
|
|
35
|
+
}
|
|
36
|
+
function passesScopeFilter(record, flags) {
|
|
37
|
+
if (flags.scope === 'all')
|
|
38
|
+
return true;
|
|
39
|
+
return record.scope === flags.scope;
|
|
40
|
+
}
|
|
41
|
+
function selectWithinContext(context, applicable) {
|
|
42
|
+
const byId = new Map();
|
|
43
|
+
for (const record of applicable) {
|
|
44
|
+
if (!record.enabled)
|
|
45
|
+
continue;
|
|
46
|
+
const group = byId.get(record.id) ?? [];
|
|
47
|
+
group.push(record);
|
|
48
|
+
byId.set(record.id, group);
|
|
49
|
+
}
|
|
50
|
+
const instances = [];
|
|
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).
|
|
54
|
+
const distinct = new Map();
|
|
55
|
+
for (const record of group) {
|
|
56
|
+
const key = `${record.installPathCanonical ?? record.installPath}\0${record.version}`;
|
|
57
|
+
if (!distinct.has(key))
|
|
58
|
+
distinct.set(key, record);
|
|
59
|
+
}
|
|
60
|
+
const candidates = [...distinct.values()];
|
|
61
|
+
if (candidates.length === 1) {
|
|
62
|
+
instances.push({
|
|
63
|
+
contextKey: context.key,
|
|
64
|
+
id,
|
|
65
|
+
selection: 'sole',
|
|
66
|
+
reason: group.length === 1 ? 'single' : 'shared_install',
|
|
67
|
+
record: candidates[0],
|
|
68
|
+
contenders: group,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
instances.push({
|
|
73
|
+
contextKey: context.key,
|
|
74
|
+
id,
|
|
75
|
+
selection: 'ambiguous',
|
|
76
|
+
reason: 'unresolved',
|
|
77
|
+
record: null,
|
|
78
|
+
contenders: group,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return instances;
|
|
83
|
+
}
|
|
84
|
+
export function selectEffective(records, cwdCanonical, flags) {
|
|
85
|
+
const unknownScopeRecords = records.filter((r) => r.scope === 'unknown');
|
|
86
|
+
const { contexts, omitted } = buildContexts(records, cwdCanonical, flags.allProjects);
|
|
87
|
+
const contextPaths = new Set(contexts.map((c) => c.canonicalPath));
|
|
88
|
+
const otherProjectRecords = records.filter((r) => (r.scope === 'project' || r.scope === 'local') &&
|
|
89
|
+
(r.projectPathCanonical === null || !contextPaths.has(r.projectPathCanonical)));
|
|
90
|
+
const selections = contexts.map((context) => {
|
|
91
|
+
const applicable = records.filter((r) => appliesToContext(r, context) && passesScopeFilter(r, flags));
|
|
92
|
+
return {
|
|
93
|
+
context,
|
|
94
|
+
applicable,
|
|
95
|
+
disabled: applicable.filter((r) => !r.enabled),
|
|
96
|
+
instances: selectWithinContext(context, applicable),
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
return { contexts: selections, contextsOmitted: omitted, unknownScopeRecords, otherProjectRecords };
|
|
100
|
+
}
|