@sssb/tools 0.2.0 → 0.4.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,583 @@
1
+ // @ts-check
2
+ // THE ADOPTER'S OWN SETTINGS, REPORTED (`sssb doctor`, adoption review follow-up 8). The settings only the adopter can
3
+ // make: on the workspace's GitHub repository, that `sssb / all-checks` is a required check on the default branch, that
4
+ // private vulnerability reporting is on, and, for a private repository in an organization, that the organization's
5
+ // Actions policy lets it call SSSB's reusable workflow; and on this machine, that the Claude Code plugin the workspace
6
+ // enables is installed. Never a failure, never a write, never a prompt:
7
+ //
8
+ // - GitHub is read with `gh api --method GET <path>` and nothing else (`ghGet`), with a short timeout, stdin closed
9
+ // and prompts off. A `gh` that is missing, signed out, offline, or refused for a setting yields "not checked" with
10
+ // the reason, and doctor moves on.
11
+ // - Neither is looked at when `CI` is set: CI's token is the job's `GITHUB_TOKEN`, which cannot be relied on to read
12
+ // these settings (the Actions policies, for one, answer 403 to a caller without administration), a CI runner
13
+ // does not normally have Claude Code, and the check would add network calls to the gate that runs doctor on every
14
+ // PR. The line says so, so a log is not silent about it.
15
+ //
16
+ // The functions here judge what they are handed; `settingsReports` reads the world and hands it over.
17
+ import { spawnSync } from 'node:child_process'
18
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
19
+ import os from 'node:os'
20
+ import path from 'node:path'
21
+ import { githubRepositoryOf } from './doctor-checks.js'
22
+
23
+ /** The check an adopter requires: SSSB's reusable workflow, called by a job named `sssb`, ends in `all-checks`. */
24
+ export const REQUIRED_CHECK = 'sssb / all-checks'
25
+
26
+ /** @typedef {Record<string, string | undefined>} Env an environment: `process.env`'s shape without Node's `NODE_ENV` typing */
27
+ /** @typedef {{ status: 'ok' | 'report', title: string, lines?: string[] }} Report */
28
+ /**
29
+ * @typedef {{ ok: false, kind: 'missing' | 'auth' | 'network' | 'timeout' | 'forbidden' | 'not-found' | 'error', http: number | null, message: string }} GhFailure
30
+ * @typedef {{ ok: true, json: any }} GhSuccess
31
+ * @typedef {(apiPath: string) => GhSuccess | GhFailure} Gh one read-only GET of GitHub's API
32
+ */
33
+
34
+ /** Milliseconds `gh` has to answer one request: doctor stays fast, and a hung network is "not checked". */
35
+ const GH_TIMEOUT_MS = 8000
36
+
37
+ /**
38
+ * Whether the environment says this is CI (`CI` is set by GitHub Actions and most other runners), the way tools read it:
39
+ * set, and not `0` or `false`.
40
+ * @param {Env} env
41
+ */
42
+ export const isCi = (env) => {
43
+ const value = (env.CI ?? '').trim().toLowerCase()
44
+ return value !== '' && value !== '0' && value !== 'false'
45
+ }
46
+
47
+ /**
48
+ * The real `Gh`: `gh api --method GET <path>`. Nothing but a GET ever goes through here, and a request that would
49
+ * prompt (a login, an update notice) cannot: stdin is closed and `gh`'s prompts are off.
50
+ * @param {Env} [env]
51
+ * @returns {Gh}
52
+ */
53
+ export function ghGet(env = process.env) {
54
+ return (apiPath) => {
55
+ const result = spawnSync('gh', ['api', '--method', 'GET', apiPath], {
56
+ encoding: 'utf8',
57
+ timeout: GH_TIMEOUT_MS,
58
+ stdio: ['ignore', 'pipe', 'pipe'],
59
+ env: Object.assign(/** @type {NodeJS.ProcessEnv} */ ({}), env, {
60
+ GH_PROMPT_DISABLED: '1',
61
+ GH_NO_UPDATE_NOTIFIER: '1',
62
+ GH_SPINNER_DISABLED: '1',
63
+ GH_HOST: 'github.com',
64
+ }),
65
+ })
66
+ const error = /** @type {NodeJS.ErrnoException | undefined} */ (result.error)
67
+ if (error?.code === 'ENOENT') return { ok: false, kind: 'missing', http: null, message: 'gh is not installed' }
68
+ if (error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM')
69
+ return {
70
+ ok: false,
71
+ kind: 'timeout',
72
+ http: null,
73
+ message: `gh did not answer within ${GH_TIMEOUT_MS / 1000} seconds`,
74
+ }
75
+ if (error) return { ok: false, kind: 'error', http: null, message: error.message }
76
+ const stdout = result.stdout ?? ''
77
+ if (result.status === 0) {
78
+ try {
79
+ return { ok: true, json: JSON.parse(stdout) }
80
+ } catch {
81
+ return {
82
+ ok: false,
83
+ kind: 'error',
84
+ http: null,
85
+ message: 'GitHub answered with something that is not JSON',
86
+ }
87
+ }
88
+ }
89
+ return failureOf(result.stderr ?? '', stdout)
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Classify a failed `gh api` call from what it printed.
95
+ * @param {string} stderr
96
+ * @param {string} stdout the response body, when GitHub sent one
97
+ * @returns {GhFailure}
98
+ */
99
+ export function failureOf(stderr, stdout) {
100
+ const http = Number(/HTTP (\d{3})/.exec(stderr)?.[1] ?? NaN) || null
101
+ let body = ''
102
+ try {
103
+ const parsed = JSON.parse(stdout)
104
+ if (typeof parsed?.message === 'string') body = parsed.message
105
+ } catch {
106
+ // No body: stderr says enough.
107
+ }
108
+ const text = stderr.trim().split('\n')[0] ?? ''
109
+ if (http === 401 || /gh auth login|not logged in|authentication required|GH_TOKEN/i.test(stderr))
110
+ return { ok: false, kind: 'auth', http, message: 'gh is not signed in (run `gh auth login`)' }
111
+ if (
112
+ /error connecting|dial tcp|no such host|could not resolve|i\/o timeout|network is unreachable|connection refused/i.test(
113
+ stderr,
114
+ )
115
+ )
116
+ return { ok: false, kind: 'network', http, message: 'GitHub could not be reached' }
117
+ if (http === 403)
118
+ return { ok: false, kind: 'forbidden', http, message: `GitHub refused (HTTP 403${body ? `: ${body}` : ''})` }
119
+ if (http === 404) return { ok: false, kind: 'not-found', http, message: body || 'GitHub says not found (HTTP 404)' }
120
+ return { ok: false, kind: 'error', http, message: body || text || 'gh failed' }
121
+ }
122
+
123
+ /**
124
+ * The `owner/name` of the workspace's own GitHub repository: its `origin` remote, read with git, or null.
125
+ * @param {string} root
126
+ */
127
+ export function originRepository(root) {
128
+ const result = spawnSync('git', ['-C', root, 'config', '--get', 'remote.origin.url'], {
129
+ encoding: 'utf8',
130
+ stdio: ['ignore', 'pipe', 'ignore'],
131
+ timeout: 5000,
132
+ })
133
+ return result.status === 0 ? githubRepositoryOf(result.stdout.trim()) : null
134
+ }
135
+
136
+ /**
137
+ * Every `uses:` of a reusable workflow of `repository` in the workflow files, whole: `owner/name/.github/workflows/
138
+ * file.yml@ref`, which an organization's Actions policy is written against.
139
+ * @param {string} repository `owner/name`, lowercased
140
+ * @param {{ file: string, text: string }[]} workflows
141
+ * @returns {string[]}
142
+ */
143
+ export function reusableWorkflowCalls(repository, workflows) {
144
+ const uses = /^\s*(?:-\s+)?uses:\s*['"]?(([\w.-]+\/[\w.-]+)\/\.github\/workflows\/[^@\s'"]+@[^\s'"#]+)/
145
+ const calls = new Set()
146
+ for (const { text } of workflows)
147
+ for (const line of text.split('\n')) {
148
+ const match = uses.exec(line)
149
+ if (match?.[2]?.toLowerCase() === repository) calls.add(/** @type {string} */ (match[1]))
150
+ }
151
+ return [...calls]
152
+ }
153
+
154
+ /** @param {string} what @param {GhFailure} failure */
155
+ const notChecked = (what, failure) => `${what}: not checked: ${failure.message}`
156
+
157
+ /** @param {unknown} value @returns {any[]} the value when GitHub sent a list, else none */
158
+ const listOf = (value) => (Array.isArray(value) ? value : [])
159
+
160
+ /**
161
+ * The classic and ruleset sides of "is this check required on this branch": the contexts a ruleset requires (the
162
+ * rules that apply to the branch, an organization's included), and the ones branch protection requires.
163
+ * @param {GhSuccess | GhFailure} rules `GET repos/{r}/rules/branches/{branch}`
164
+ * @param {GhSuccess | GhFailure} protection `GET repos/{r}/branches/{branch}/protection/required_status_checks`
165
+ */
166
+ export function requiredContexts(rules, protection) {
167
+ /** @type {string[]} */
168
+ const fromRules = []
169
+ if (rules.ok && Array.isArray(rules.json))
170
+ for (const rule of rules.json)
171
+ if (rule?.type === 'required_status_checks')
172
+ for (const check of listOf(rule.parameters?.required_status_checks))
173
+ if (typeof check?.context === 'string') fromRules.push(check.context)
174
+ /** @type {string[]} */
175
+ const fromProtection = []
176
+ if (protection.ok) {
177
+ for (const context of listOf(protection.json?.contexts))
178
+ if (typeof context === 'string') fromProtection.push(context)
179
+ for (const check of listOf(protection.json?.checks))
180
+ if (typeof check?.context === 'string') fromProtection.push(check.context)
181
+ }
182
+ return { fromRules, fromProtection: [...new Set(fromProtection)] }
183
+ }
184
+
185
+ /**
186
+ * IS `sssb / all-checks` REQUIRED on the default branch, by a ruleset or by branch protection. Observed with a
187
+ * non-admin account (push access) on SSSB's own repository: the rules for the branch are readable and list the check
188
+ * (`rules/branches/{branch}`, https://docs.github.com/rest/repos/rules#get-rules-for-a-branch), the branch itself is
189
+ * readable and says `protected` and what `protection.required_status_checks` holds (`branches/{branch}`), and branch
190
+ * protection's own endpoint answers 404 "Not Found" (https://docs.github.com/rest/branches/branch-protection#get-status-checks-protection),
191
+ * which for that account does not say whether the branch is protected. So "not required" is said only when the
192
+ * rulesets were read and branch protection was read too (its own endpoint, or the branch's `protection`), or answered
193
+ * that nothing is required; otherwise the line is "not confirmed" and says what could not be read.
194
+ * @param {string} repository
195
+ * @param {string} branch
196
+ * @param {Gh} gh
197
+ * @returns {Report}
198
+ */
199
+ export function requiredCheckReport(repository, branch, gh) {
200
+ const what = `github: ${REQUIRED_CHECK} is a required check on ${branch}`
201
+ const encoded = encodeURIComponent(branch)
202
+ // 100 a page: a branch can carry more than the default 30 rules, and the one that matters can be on page two.
203
+ const rules = gh(`repos/${repository}/rules/branches/${encoded}?per_page=100`)
204
+ const protection = gh(`repos/${repository}/branches/${encoded}/protection/required_status_checks`)
205
+ const read = requiredContexts(rules, protection)
206
+ const { fromRules } = read
207
+ let { fromProtection } = read
208
+ // An admin's 404 can say nothing is required by branch protection ("Branch not protected", or "Required status checks
209
+ // not enabled": GitHub's messages, not seen from the non-admin account above, whose 404 is a bare "Not Found").
210
+ const unprotected =
211
+ !protection.ok &&
212
+ protection.kind === 'not-found' &&
213
+ /not protected|required status checks not enabled/i.test(protection.message)
214
+ // Branch protection's own endpoint is admin-only. The branch itself is readable by anyone who can read the
215
+ // repository, and says whether it is protected and, when it is, what it requires.
216
+ let protectionRead = protection.ok || unprotected
217
+ if (!protectionRead) {
218
+ const branchInfo = gh(`repos/${repository}/branches/${encoded}`)
219
+ const info = branchInfo.ok ? branchInfo.json : null
220
+ if (info?.protected === false) protectionRead = true
221
+ // A protected branch counts as read only when the answer carries its required checks: without them it says
222
+ // nothing about what is required, and "not required" would be a guess.
223
+ else if (info?.protected === true && typeof info.protection?.required_status_checks === 'object') {
224
+ const checks = info.protection.required_status_checks
225
+ protectionRead = true
226
+ if (checks !== null && checks.enforcement_level !== 'off') {
227
+ const contexts = [...listOf(checks.contexts), ...listOf(checks.checks).map((check) => check?.context)]
228
+ fromProtection = [...new Set(contexts.filter((c) => typeof c === 'string'))]
229
+ }
230
+ }
231
+ }
232
+ if (fromRules.includes(REQUIRED_CHECK)) return { status: 'ok', title: `${what} (a ruleset requires it)` }
233
+ if (fromProtection.includes(REQUIRED_CHECK))
234
+ return { status: 'ok', title: `${what} (branch protection requires it)` }
235
+
236
+ const required = [...new Set([...fromRules, ...fromProtection])]
237
+ if (rules.ok && Array.isArray(rules.json) && protectionRead)
238
+ return {
239
+ status: 'report',
240
+ title:
241
+ `${what}: it is not (reported, not failed: it fails unless every one of SSSB's jobs ran and passed, so ` +
242
+ `require it in a ruleset or branch protection on ${branch}; changing a setting stays yours)`,
243
+ lines: [
244
+ required.length > 0
245
+ ? `required today: ${required.join(', ')}`
246
+ : `nothing is a required check on ${branch}`,
247
+ ],
248
+ }
249
+ /** @type {string[]} */
250
+ const unread = []
251
+ if (!rules.ok) unread.push(`rulesets: ${rules.message}`)
252
+ else if (!Array.isArray(rules.json)) unread.push('rulesets: GitHub answered with something that is not a list')
253
+ if (!protectionRead && !protection.ok) unread.push(`branch protection: ${protection.message}`)
254
+ return {
255
+ status: 'report',
256
+ title: `${what}: not confirmed: no ruleset requires it, but not everything could be read`,
257
+ lines: unread,
258
+ }
259
+ }
260
+
261
+ /**
262
+ * PRIVATE VULNERABILITY REPORTING, which `SECURITY.md` and `CODE_OF_CONDUCT.md` send reporters to.
263
+ * @param {string} repository
264
+ * @param {Gh} gh
265
+ * @returns {Report}
266
+ */
267
+ export function vulnerabilityReportingReport(repository, gh) {
268
+ const what = 'github: private vulnerability reporting'
269
+ const answer = gh(`repos/${repository}/private-vulnerability-reporting`)
270
+ if (!answer.ok) return { status: 'report', title: notChecked(what, answer) }
271
+ if (answer.json?.enabled === true) return { status: 'ok', title: `${what} is on` }
272
+ return {
273
+ status: 'report',
274
+ title:
275
+ `${what} is off (reported, not failed: until it is on, the security and conduct policies point reporters to a ` +
276
+ 'private channel that does not exist; Settings → Code security)',
277
+ }
278
+ }
279
+
280
+ /** A glob over an action pattern: `*` is any run of characters, all else literal, case-insensitive like GitHub's names. */
281
+ const globMatches = (/** @type {string} */ pattern, /** @type {string} */ value) =>
282
+ new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`, 'i').test(value)
283
+
284
+ /**
285
+ * One level's (organization's or repository's) Actions policy, read, and whether it lets the workflows through.
286
+ * @param {string} scope `orgs/{o}` or `repos/{o}/{r}`
287
+ * @param {string[]} calls the reusable workflows the workspace calls
288
+ * @param {Gh} gh
289
+ * @returns {{ allows: boolean | null, line: string }} `allows` null: not read
290
+ */
291
+ function actionsPolicy(scope, calls, gh) {
292
+ const name = scope.startsWith('orgs/') ? "the organization's" : "the repository's"
293
+ const permissions = gh(`${scope}/actions/permissions`)
294
+ if (!permissions.ok) return { allows: null, line: `${name} Actions policy: not read: ${permissions.message}` }
295
+ const { enabled, enabled_repositories: enabledRepositories, allowed_actions: allowed } = permissions.json ?? {}
296
+ // A repository's answer is `enabled`; an organization's is `enabled_repositories`.
297
+ if (enabled === false) return { allows: false, line: `${name} Actions policy: Actions are not enabled` }
298
+ if (enabledRepositories === 'none')
299
+ return { allows: false, line: `${name} Actions policy: Actions are enabled for no repository` }
300
+ // Which repositories an organization enabled is a list this does not read: say so rather than say "yes".
301
+ if (enabledRepositories === 'selected')
302
+ return {
303
+ allows: null,
304
+ line: `${name} Actions policy: Actions are enabled for selected repositories only; whether this one is among them was not read`,
305
+ }
306
+ if (allowed === 'all' || typeof allowed !== 'string')
307
+ return { allows: true, line: `${name} Actions policy: all actions and workflows allowed` }
308
+ // The organization's own actions and reusable workflows are always allowed: only a call into another owner is held
309
+ // to the policy.
310
+ const owner = scope.split('/')[1] ?? ''
311
+ const foreign = calls.filter((call) => call.split('/')[0]?.toLowerCase() !== owner.toLowerCase())
312
+ if (foreign.length === 0)
313
+ return {
314
+ allows: true,
315
+ line: `${name} Actions policy: ${allowed}, and ${calls.join(', ')} ${calls.length === 1 ? 'is' : 'are'} the organization's own`,
316
+ }
317
+ if (allowed === 'local_only')
318
+ return {
319
+ allows: false,
320
+ line: `${name} Actions policy: only the organization's own actions and reusable workflows, and ${foreign.join(', ')} is not`,
321
+ }
322
+ const selected = gh(`${scope}/actions/permissions/selected-actions`)
323
+ if (!selected.ok)
324
+ return {
325
+ allows: null,
326
+ line: `${name} Actions policy: selected actions only; the list was not read: ${selected.message}`,
327
+ }
328
+ /** @type {string[]} */
329
+ const patterns = Array.isArray(selected.json?.patterns_allowed) ? selected.json.patterns_allowed : []
330
+ // A pattern that blocks (`!owner/*`) overrides the ones that allow, and the matching here only knows the allowing ones.
331
+ if (patterns.some((pattern) => pattern.startsWith('!')))
332
+ return {
333
+ allows: null,
334
+ line: `${name} Actions policy: selected actions only, with a blocking pattern (!…) that was not evaluated`,
335
+ }
336
+ const blocked = foreign.filter((call) => !patterns.some((pattern) => globMatches(pattern, call)))
337
+ return blocked.length === 0
338
+ ? {
339
+ allows: true,
340
+ line: `${name} Actions policy: selected actions only, and its patterns match ${foreign.join(', ')}`,
341
+ }
342
+ : {
343
+ allows: false,
344
+ line: `${name} Actions policy: selected actions only, and none of its ${patterns.length} pattern(s) matches ${blocked.join(', ')}`,
345
+ }
346
+ }
347
+
348
+ /**
349
+ * CAN A PRIVATE REPOSITORY IN AN ORGANIZATION CALL SSSB'S REUSABLE WORKFLOW: the organization's Actions policy (and the
350
+ * repository's) must allow it. Read where GitHub lets the account read it (an admin's), so each level is judged on its
351
+ * own and one that is not readable is named, never guessed.
352
+ * @param {string} repository
353
+ * @param {string[]} calls
354
+ * @param {Gh} gh
355
+ * @returns {Report}
356
+ */
357
+ export function reusableWorkflowReport(repository, calls, gh) {
358
+ const what = "github: this private repository can call SSSB's reusable workflow"
359
+ if (calls.length === 0)
360
+ return { status: 'report', title: `${what}: not checked: no workflow under .github/workflows calls one` }
361
+ const levels = [
362
+ actionsPolicy(`orgs/${repository.split('/')[0]}`, calls, gh),
363
+ actionsPolicy(`repos/${repository}`, calls, gh),
364
+ ]
365
+ const lines = levels.map(({ line }) => line)
366
+ if (levels.some(({ allows }) => allows === false))
367
+ return {
368
+ status: 'report',
369
+ title:
370
+ `${what}: it cannot (reported, not failed: allow public reusable workflows in the organization's Actions ` +
371
+ 'settings, or the called workflow never runs)',
372
+ lines,
373
+ }
374
+ if (levels.every(({ allows }) => allows === null))
375
+ return { status: 'report', title: `${what}: not checked: neither policy could be read`, lines }
376
+ if (levels.some(({ allows }) => allows === null))
377
+ return { status: 'ok', title: `${what}: yes, as far as the policies that could be read go`, lines }
378
+ return { status: 'ok', title: `${what}: yes`, lines }
379
+ }
380
+
381
+ /**
382
+ * Every GitHub setting doctor reports, for the repository `repository`.
383
+ * @param {string} repository `owner/name`, lowercased
384
+ * @param {{ gh: Gh, workflows: { file: string, text: string }[], kitRepository: string | null }} input
385
+ * @returns {Report[]}
386
+ */
387
+ export function githubReports(repository, { gh, workflows, kitRepository }) {
388
+ const repo = gh(`repos/${repository}`)
389
+ if (!repo.ok) return [{ status: 'report', title: `github settings of ${repository}: not checked: ${repo.message}` }]
390
+ const branch = typeof repo.json?.default_branch === 'string' ? repo.json.default_branch : 'main'
391
+ /** @type {Report[]} */
392
+ const reports = [requiredCheckReport(repository, branch, gh), vulnerabilityReportingReport(repository, gh)]
393
+ if (repo.json?.private === true && repo.json?.owner?.type === 'Organization')
394
+ reports.push(
395
+ reusableWorkflowReport(
396
+ repository,
397
+ kitRepository === null ? [] : reusableWorkflowCalls(kitRepository, workflows),
398
+ gh,
399
+ ),
400
+ )
401
+ return reports
402
+ }
403
+
404
+ /**
405
+ * Where Claude Code keeps its plugins: `CLAUDE_CONFIG_DIR`, else `~/.claude`.
406
+ * @param {Env} env
407
+ */
408
+ export const claudeConfigDir = (env) => env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.claude')
409
+
410
+ /** @param {string} dir the real path of `dir`, or its resolved path when it is gone */
411
+ const real = (dir) => {
412
+ try {
413
+ return realpathSync(dir)
414
+ } catch {
415
+ return path.resolve(dir)
416
+ }
417
+ }
418
+
419
+ /**
420
+ * THE PLUGIN THE WORKSPACE ENABLES IS INSTALLED. Enabling is the workspace's (`enabledPlugins` in its shared
421
+ * `.claude/settings.json`) and installing is the person's, once per clone (`claude plugin install <plugin> --scope
422
+ * project`), so a workspace can enable a plugin nobody has. Claude Code records each install in
423
+ * `<config dir>/plugins/installed_plugins.json`, under `plugins["<plugin>@<marketplace>"]`, a list of entries with a
424
+ * `scope` (a user-scope entry is the one shape seen on a real machine, version 2 of the record). That a project or
425
+ * local entry names its project in `projectPath` is ASSUMED, not seen: installed for this workspace when an entry is a
426
+ * user-scope (or managed) one, or one whose `projectPath` is this very directory.
427
+ * @param {{
428
+ * settings: { file: string, text: string } | null,
429
+ * installed: { file: string, text: string } | null,
430
+ * root: string,
431
+ * }} input `installed`: the install record, null when this machine has none
432
+ * @returns {Report | null} null: the workspace enables no plugin, so there is nothing to report
433
+ */
434
+ export function pluginReport({ settings, installed, root }) {
435
+ const what = 'claude plugin'
436
+ if (settings === null) return null
437
+ /** @type {unknown} */
438
+ let parsed
439
+ try {
440
+ parsed = JSON.parse(settings.text)
441
+ } catch {
442
+ return { status: 'report', title: `${what}: not checked: ${settings.file} is not JSON doctor can read` }
443
+ }
444
+ const enabledPlugins = /** @type {any} */ (parsed)?.enabledPlugins
445
+ const enabled = Object.entries(typeof enabledPlugins === 'object' && enabledPlugins ? enabledPlugins : {})
446
+ .filter(([, on]) => on === true || (Array.isArray(on) && on.length > 0))
447
+ .map(([key]) => key)
448
+ if (enabled.length === 0) return null
449
+ const names = enabled.join(', ')
450
+ const install = enabled.map((key) => `claude plugin install ${key} --scope project`)
451
+ if (installed === null)
452
+ return {
453
+ status: 'report',
454
+ title:
455
+ `${what}: ${names} ${enabled.length === 1 ? 'is' : 'are'} enabled by ${settings.file} but not installed: this ` +
456
+ 'machine has no plugin install record (reported, not failed: enabling installs nothing; ' +
457
+ 'ignore it when nobody here uses Claude Code)',
458
+ lines: install,
459
+ }
460
+ /** @type {any} */
461
+ let record
462
+ try {
463
+ record = JSON.parse(installed.text)
464
+ } catch {
465
+ return { status: 'report', title: `${what}: not checked: ${installed.file} is not JSON doctor can read` }
466
+ }
467
+ const plugins = typeof record?.plugins === 'object' && record.plugins ? record.plugins : {}
468
+ const here = real(root)
469
+ /** @type {string[]} */
470
+ const missing = []
471
+ /** @type {string[]} */
472
+ const lines = []
473
+ for (const key of enabled) {
474
+ // An older record keeps one entry, not a list, for a plugin: a user-level install.
475
+ const recorded = plugins[key]
476
+ const entries = Array.isArray(recorded)
477
+ ? recorded
478
+ : typeof recorded === 'object' && recorded
479
+ ? [{ scope: 'user', ...recorded }]
480
+ : []
481
+ const mine = entries.filter(
482
+ (/** @type {any} */ entry) =>
483
+ entry?.scope === 'user' ||
484
+ entry?.scope === 'managed' ||
485
+ (typeof entry?.projectPath === 'string' && real(entry.projectPath) === here),
486
+ )
487
+ if (mine.length > 0) {
488
+ lines.push(
489
+ `${key}: installed${typeof mine[0].version === 'string' && mine[0].version ? ` (${mine[0].version})` : ''}, scope ${mine[0].scope}`,
490
+ )
491
+ continue
492
+ }
493
+ missing.push(key)
494
+ const elsewhere = entries
495
+ .map((/** @type {any} */ entry) => entry?.projectPath)
496
+ .filter((/** @type {unknown} */ p) => typeof p === 'string')
497
+ lines.push(
498
+ `${key}: not installed for this workspace` +
499
+ (elsewhere.length > 0 ? ` (installed only for ${elsewhere.join(', ')})` : '') +
500
+ `: claude plugin install ${key} --scope project`,
501
+ )
502
+ }
503
+ return missing.length === 0
504
+ ? { status: 'ok', title: `${what}: ${names} ${enabled.length === 1 ? 'is' : 'are'} installed`, lines }
505
+ : {
506
+ status: 'report',
507
+ title:
508
+ `${what}: ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} enabled by ${settings.file} but not ` +
509
+ 'installed (reported, not failed: enabling installs nothing, so run the command once per clone, after ' +
510
+ 'trusting the folder; ignore it when nobody here uses Claude Code)',
511
+ lines,
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Everything this module reports for a workspace: read here, judged above.
517
+ * @param {{
518
+ * root: string,
519
+ * env?: Env,
520
+ * gh?: Gh,
521
+ * workflows: { file: string, text: string }[],
522
+ * kitRepository: string | null,
523
+ * }} input
524
+ * @returns {Report[]}
525
+ */
526
+ export function settingsReports({ root, env = process.env, gh = ghGet(env), workflows, kitRepository }) {
527
+ const title = 'github settings and plugin install'
528
+ if (isCi(env))
529
+ return [
530
+ {
531
+ status: 'report',
532
+ title:
533
+ `${title}: not checked: CI is set (a CI token cannot be relied on to read these settings and a ` +
534
+ 'CI runner does not normally have Claude Code; run `sssb doctor` on your own machine)',
535
+ },
536
+ ]
537
+ /** @type {Report[]} */
538
+ const reports = []
539
+ // Nothing in here may stop doctor: a file that cannot be read, or an answer shaped unlike GitHub's documents, is a
540
+ // line that says so.
541
+ reports.push(
542
+ ...guarded('github settings', () => {
543
+ const repository = originRepository(root)
544
+ return repository === null
545
+ ? [
546
+ {
547
+ status: /** @type {const} */ ('report'),
548
+ title: 'github settings: not checked: the workspace has no `origin` remote on github.com to read the settings of',
549
+ },
550
+ ]
551
+ : githubReports(repository, { gh, workflows, kitRepository })
552
+ }),
553
+ )
554
+ reports.push(
555
+ ...guarded('claude plugin', () => {
556
+ const read = (/** @type {string} */ file) => (existsSync(file) ? readFileSync(file, 'utf8') : null)
557
+ const settingsText = read(path.join(root, '.claude', 'settings.json'))
558
+ const installedFile = path.join(claudeConfigDir(env), 'plugins', 'installed_plugins.json')
559
+ const installedText = read(installedFile)
560
+ const plugin = pluginReport({
561
+ settings: settingsText === null ? null : { file: '.claude/settings.json', text: settingsText },
562
+ installed: installedText === null ? null : { file: installedFile, text: installedText },
563
+ root,
564
+ })
565
+ return plugin === null ? [] : [plugin]
566
+ }),
567
+ )
568
+ return reports
569
+ }
570
+
571
+ /**
572
+ * Run one group of reports; an error it throws is the group's one line, "not checked", with the error's message.
573
+ * @param {string} what
574
+ * @param {() => Report[]} produce
575
+ * @returns {Report[]}
576
+ */
577
+ function guarded(what, produce) {
578
+ try {
579
+ return produce()
580
+ } catch (error) {
581
+ return [{ status: 'report', title: `${what}: not checked: ${error instanceof Error ? error.message : error}` }]
582
+ }
583
+ }