launch-doctor 0.4.2 → 0.4.3

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/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.3] - 2026-12-04
11
+
12
+ ### Added
13
+
14
+ - **Every finding has a stable id** (`ref` in `--json`): 8 letters and digits from the rule, the file and the text of the line, the same on every scan while the finding is unchanged, even when the line moves. `launch-doctor prompt` accepts it as well as a number.
15
+ - **MCP tools to work through findings one at a time.** `scan_project` now returns a short list (at most 25 findings, critical first, each with its id, rule, file and line), the Security and Launch readiness grades, and coverage notes, instead of every fix prompt at once; text is capped at 12,000 characters. New tools: `explain_finding` (why it matters, how to confirm, how to fix, false-alarm hint), `fix_prompt` (the prompt for one finding), `rescan` (only the files of the given ids or paths, or the files changed since the last commit, and which ids are now fixed) and `grade_history`. They share one core with the CLI.
16
+ - `launch-doctor explain <n|id>` prints the same explanation in the terminal.
17
+ - **`--report`** writes `.launchdoctor/report.md`: every finding with why it matters, how to confirm it, how to fix it and when it is a false alarm, built from the same explanations. Each finding points to its fix prompt (`launch-doctor prompt N`) instead of copying it, and no secret value is written. The short report's Next lines point to it.
18
+ - **`init --mcp`** prints the exact `claude mcp add` command and ready JSON for Cursor and Claude Desktop; it edits no config file. `launch-doctor mcp [folder]` serves a given folder (Claude Desktop does not start servers in your project).
19
+ - `init` adds `.launchdoctor/` to `.gitignore` (creating the file if needed).
20
+ - **An explanation for every rule**, written once in `src/explanations.ts`: what it is, why it matters (what an attacker or a surprise bill looks like), how to confirm it by hand, how to fix it, and when it is a false alarm. A test fails if a rule has none.
21
+
22
+ ### Changed
23
+
24
+ - **The MCP server makes no network requests for a project scan** (no email DNS lookups; `offline` is accepted and ignored, and `domain` is gone). Only `scan_url` uses the network, with the address it is given. Every tool reads only inside the folder the server started in: a `path` outside it is refused.
25
+
10
26
  ## [0.4.2] - 2026-12-04
11
27
 
12
28
  ### Added
@@ -211,7 +227,8 @@ First release.
211
227
  - `.launchdoctorignore` for silencing findings by id or skipping paths.
212
228
  - Support for JavaScript / TypeScript and Python projects.
213
229
 
214
- [Unreleased]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.2...HEAD
230
+ [Unreleased]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.3...HEAD
231
+ [0.4.3]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.2...v0.4.3
215
232
  [0.4.2]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.1...v0.4.2
216
233
  [0.4.1]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.0...v0.4.1
217
234
  [0.4.0]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.3.0...v0.4.0
package/README.md CHANGED
@@ -54,7 +54,7 @@ This is the `--demo` report. It shows the verdict, a Security grade and a Launch
54
54
  ██║ ██║██║ ██║██║ ██║ ██║ ██║██╔══██╗
55
55
  ██████╔╝╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║
56
56
  ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
57
- Launch Doctor v0.4.2 · my-weekend-saas · 13 files · Vite, React, Supabase +2
57
+ Launch Doctor v0.4.3 · my-weekend-saas · 13 files · Vite, React, Supabase +2
58
58
 
59
59
  NOT READY TO LAUNCH: 6 critical problems
60
60
 
@@ -130,15 +130,34 @@ The report shows two grades: **Security** (secrets, database, access control, pa
130
130
  |---|---|
131
131
  | `npx launch-doctor [folder]` | Check a project: the short report, and `LAUNCH_FIXES.md` with a fix prompt for every problem |
132
132
  | `npx launch-doctor --verbose` | The full report: every category and every finding |
133
+ | `npx launch-doctor --report` | Write `.launchdoctor/report.md`: every finding explained, with its fix prompt number |
134
+ | `npx launch-doctor explain <n>` | What finding n means, how to confirm it and how to fix it |
133
135
  | `npx launch-doctor --demo` | Check a built-in sample app full of mistakes |
134
136
  | `npx launch-doctor prompt <n> --copy` | Copy fix prompt n to the clipboard |
135
137
  | `npx launch-doctor --ci` | Exit with code 1 on critical problems, for CI |
136
138
  | `npx launch-doctor scan <url>` | Check your deployed site from the outside |
137
139
  | `npx launch-doctor init` | Create `.launchdoctorignore` and a GitHub Actions workflow |
140
+ | `npx launch-doctor init --mcp` | Print the setup for Claude Code, Cursor and Claude Desktop |
138
141
  | `npx launch-doctor init --hooks` | Check every AI edit and every commit (`--upgrade` moves them to a new version) |
139
142
 
140
143
  Every option, the exit codes and the rarely used flags (`--history-depth`, `--config-from`, `--sarif` and others) are in [docs/cli.md](docs/cli.md).
141
144
 
145
+ ## Use it inside Claude Code / Cursor
146
+
147
+ Launch Doctor is also an MCP server, so your AI coding tool can run the checks, read the findings and fix them with you. Set it up in your project folder:
148
+
149
+ ```bash
150
+ claude mcp add launch-doctor -- npx -y "launch-doctor@^0.4.0" mcp
151
+ ```
152
+
153
+ `npx launch-doctor init --mcp` prints that command and ready JSON for Cursor (`.cursor/mcp.json`) and Claude Desktop; it changes nothing. Then ask:
154
+
155
+ - *"Scan this app with Launch Doctor."* It runs `scan_project`: the two grades and a short list of findings, each with an id.
156
+ - *"Explain finding 2."* It runs `explain_finding`: why it matters, how to confirm it, how to fix it, and when it is a false alarm.
157
+ - *"Fix the top issue, then rescan."* It gets the fix prompt with `fix_prompt`, makes the change, and runs `rescan` on that finding to check it is gone.
158
+
159
+ The server only reads your project folder, writes nothing, never returns secret values (only the file, the line and a masked hint), and uses the network only when you ask it to check a live site with `scan_url`. The tools and their options: [docs/ai-tools.md](docs/ai-tools.md#mcp-server).
160
+
142
161
  ## Using with AI coding tools
143
162
 
144
163
  `LAUNCH_FIXES.md` starts with one prompt for all the critical problems, then has one prompt per problem with the file, the line and the risk in plain English. Paste them one at a time into Claude Code, Cursor, Windsurf, Lovable or Bolt, or copy one with `npx launch-doctor prompt <n> --copy`. `npx launch-doctor init --hooks` makes Claude Code and Cursor run the check after every edit, and `npx launch-doctor mcp` lets your AI tool run it itself. Details: [docs/ai-tools.md](docs/ai-tools.md).
@@ -163,7 +182,7 @@ Launch Doctor analyzes your codebase locally on your device. Your source code, f
163
182
  - **No telemetry:** Launch Doctor does not collect usage data or phone home.
164
183
  - **Git history analysis (`--history`):** Runs local `git log` commands directly on your system without network requests.
165
184
  - **Pull request comments (`--pr-comment`):** calls the GitHub API with the workflow's token to read the pull request's changed files and post comments. It only runs on GitHub Actions and sends finding titles, explanations, fix prompts and file paths, never your source code.
166
- - **MCP server (`mcp`):** talks to your AI tool over stdin and stdout only; it opens no port. Its tools make the same network calls as the CLI: email DNS lookups for `scan_project` (unless `offline`), and the requests to the site you name for `scan_url`, which only accepts public sites.
185
+ - **MCP server (`mcp`):** talks to your AI tool over stdin and stdout only; it opens no port. Its project tools make no network requests at all (no email DNS lookups) and only read inside the folder the server started in. Only `scan_url` uses the network: the requests to the site you name, which must be a public site.
167
186
  - **Hooks (`init --hooks`):** the hooks themselves make no network requests beyond `npx --yes "launch-doctor@^X.Y.0"`, which downloads the package from the npm registry the first time if it isn't installed. `--changed` and `--staged` skip the email DNS lookups.
168
187
  - **Grade history and badge (`--record`):** written to `.launchdoctor/` in your project. No badge service is involved and nothing is sent anywhere.
169
188
  - **Scheduled monitoring (`init --monitor`):** the workflow runs on GitHub's servers and makes the same requests as the commands it runs (`npx`, the email DNS lookups, and `scan` when `LAUNCH_DOCTOR_URL` is set), then pushes its commit to the `launch-doctor-grades` branch of your repository.
@@ -209,7 +228,7 @@ For apps that handle significant money or sensitive personal or health data, use
209
228
 
210
229
  ## How it is tested
211
230
 
212
- - 386 automated tests run on every change, on Windows, macOS and Linux, with Node.js 22 and 24.
231
+ - 409 automated tests run on every change, on Windows, macOS and Linux, with Node.js 22 and 24.
213
232
  - A stress-test harness (`scripts/stress/`, see [CONTRIBUTING.md](CONTRIBUTING.md#stress-tests)) runs Launch Doctor against hostile inputs: repositories whose git settings try to run programs, symlink loops and FIFOs, files built to make a regular expression backtrack, terminal escape sequences, hostile servers for `scan`, and MCP requests to private addresses. Before 0.4.0 it found 10 security problems; each is fixed and has a regression test, and the whole suite now passes on Windows and Linux.
214
233
  - Every check that existed in 0.2 has been confirmed against a small project (or fake site) that contains exactly that problem, and every command in this README has been run (the `scan` examples against a local test site rather than a real one).
215
234
  - The features new in 0.3.0 (the GitHub Action, the MCP server, mobile apps, and Clerk, Convex, Appwrite, Paddle and Lemon Squeezy) have their own tests and were spot-checked by hand, which found and fixed two bugs before release. They have been tried less than the older checks. Posting pull request comments is tested against a fake GitHub API; it has not yet run on many real pull requests.
@@ -6,6 +6,15 @@ export declare const BASELINE_FILE = ".launchdoctor-baseline.json";
6
6
  * It doesn't include the line number, so it survives lines moving up or down.
7
7
  */
8
8
  export declare function fingerprint(ctx: ProjectContext, f: Finding): string;
9
+ /** The text of a finding's line with whitespace collapsed, or '' when it has no line. */
10
+ export declare function lineContext(ctx: ProjectContext, f: Finding): string;
11
+ /** A short stable id from the rule id, the file and the line's text. */
12
+ export declare function findingRef(id: string, file: string, context: string): string;
13
+ /**
14
+ * Give every finding its ref. Two findings that would get the same one (same rule, same file, no line) are told
15
+ * apart by their order, which is stable because the checks run in a fixed order.
16
+ */
17
+ export declare function assignRefs(findings: Finding[], contextOf: (f: Finding) => string): void;
9
18
  /**
10
19
  * Fingerprints in the project's baseline file, or null if there is none (or it can't be read).
11
20
  * With `configFrom`, the file is read from that git ref instead of the working folder.
@@ -20,6 +20,32 @@ export function fingerprint(ctx, f) {
20
20
  const hash = createHash('sha256').update(text).digest('hex').slice(0, 16);
21
21
  return `${f.id}|${file}|${hash}`;
22
22
  }
23
+ /** The text of a finding's line with whitespace collapsed, or '' when it has no line. */
24
+ export function lineContext(ctx, f) {
25
+ const file = f.location?.file;
26
+ const line = f.location?.line;
27
+ if (!file || !line)
28
+ return '';
29
+ return (ctx.file(file)?.content.split(/\r?\n/)[line - 1] ?? '').trim().replace(/\s+/g, ' ');
30
+ }
31
+ /** A short stable id from the rule id, the file and the line's text. */
32
+ export function findingRef(id, file, context) {
33
+ return createHash('sha256').update(`${id}\n${file}\n${context}`).digest('hex').slice(0, 8);
34
+ }
35
+ /**
36
+ * Give every finding its ref. Two findings that would get the same one (same rule, same file, no line) are told
37
+ * apart by their order, which is stable because the checks run in a fixed order.
38
+ */
39
+ export function assignRefs(findings, contextOf) {
40
+ const seen = new Map();
41
+ for (const f of findings) {
42
+ const file = f.location?.file ?? '';
43
+ const base = findingRef(f.id, file, contextOf(f));
44
+ const n = seen.get(base) ?? 0;
45
+ seen.set(base, n + 1);
46
+ f.ref = n ? findingRef(f.id, file, `${contextOf(f)}\n#${n}`) : base;
47
+ }
48
+ }
23
49
  /**
24
50
  * Fingerprints in the project's baseline file, or null if there is none (or it can't be read).
25
51
  * With `configFrom`, the file is read from that git ref instead of the working folder.
package/dist/src/cli.js CHANGED
@@ -1,25 +1,27 @@
1
1
  #!/usr/bin/env node
2
- import { appendFileSync, existsSync, rmSync, statSync } from 'node:fs';
3
- import { isAbsolute, join, relative, resolve } from 'node:path';
2
+ import { appendFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { shouldShowBanner } from './banner.js';
4
5
  import { applyBaseline, BASELINE_FILE, loadBaseline, writeBaseline } from './baseline.js';
5
- import { changedFiles } from './changed.js';
6
- import { createDemoProject, removeOnSignal } from './demo.js';
6
+ import { shortWhere } from './checks/common.js';
7
+ import { CoreError, changedPaths, findFinding, findingDetails, gradeHistory, projectRoot, promptNumber, scan as scanProject, withDemo, } from './core.js';
8
+ import { removeOnSignal } from './demo.js';
7
9
  import { renderFixes } from './fixes.js';
8
- import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
9
10
  import { git } from './git.js';
11
+ import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
10
12
  import { failingFindings } from './grade.js';
11
13
  import { BADGE_FILE, describeEntry, entryFor, GRADES_FILE, headCommit, loadGrades, recordGrade, renderGradeTable, } from './grades.js';
12
- import { shouldShowBanner } from './banner.js';
13
14
  import { DEFAULT_HISTORY_DEPTH } from './history.js';
14
15
  import { runHook } from './hook.js';
15
16
  import { pinnedPackage, setupHooks, upgradeHooks } from './hooks-setup.js';
16
- import { CATEGORY_IDS, runDoctor } from './index.js';
17
- import { badgeUrl, GRADES_BRANCH, githubRepo, runInit } from './init.js';
17
+ import { CATEGORY_IDS } from './index.js';
18
+ import { badgeUrl, ensureGitignore, GRADES_BRANCH, githubRepo, mcpSetupText, runInit } from './init.js';
18
19
  import { runLiveScan } from './live.js';
19
20
  import { runMcpServer } from './mcp.js';
20
21
  import { assertConfigRef } from './project.js';
21
- import { copyToClipboard, promptFor, unsupportedLanguage } from './prompt.js';
22
- import { bold, dim, renderReport } from './report.js';
22
+ import { copyToClipboard, unsupportedLanguage } from './prompt.js';
23
+ import { bold, dim, renderReport, wrap } from './report.js';
24
+ import { REPORT_FILE, renderReportMd } from './report-md.js';
23
25
  import { writeRegularFile } from './safe-fs.js';
24
26
  import { renderSarif } from './sarif.js';
25
27
  import { renderEmptyFolder, renderOtherLanguage, renderShortReport } from './short-report.js';
@@ -35,7 +37,10 @@ const HELP = `
35
37
  npx launch-doctor init --hooks --upgrade
36
38
  Move those hooks onto this version (only the launch-doctor command changes)
37
39
  npx launch-doctor init --monitor Add a GitHub Actions workflow that re-checks the project every week
40
+ npx launch-doctor init --mcp Print the setup for Claude Code, Cursor and Claude Desktop (changes nothing)
38
41
  npx launch-doctor grades [folder] Show the grades saved with --record
42
+ npx launch-doctor explain <n> [folder]
43
+ What finding n means: why it matters, how to confirm and fix it
39
44
  npx launch-doctor prompt <n> [folder] [--copy]
40
45
  Print fix prompt n (the numbers in the report and LAUNCH_FIXES.md)
41
46
  npx launch-doctor scan <url> Check your deployed site (exposed files, source maps, open Supabase tables, headers)
@@ -66,6 +71,7 @@ const HELP = `
66
71
  --staged Only report on files staged for the next commit (for a pre-commit hook)
67
72
  --demo Scan a built-in sample app full of mistakes
68
73
  --verbose Show the full report: every category and every finding
74
+ --report Also write .launchdoctor/report.md: every finding explained, with its fix prompt number
69
75
  --copy With prompt <n>, copy the fix prompt to the clipboard
70
76
  --no-banner Don't print the ASCII banner (it only shows in an interactive terminal)
71
77
  -h, --help Show this help
@@ -112,6 +118,7 @@ function parseArgs(argv) {
112
118
  demo: false,
113
119
  banner: true,
114
120
  verbose: false,
121
+ report: false,
115
122
  help: false,
116
123
  version: false,
117
124
  };
@@ -139,6 +146,8 @@ function parseArgs(argv) {
139
146
  args.banner = false;
140
147
  else if (a === '--verbose')
141
148
  args.verbose = true;
149
+ else if (a === '--report')
150
+ args.report = true;
142
151
  else if (a === '--pr-comment')
143
152
  args.prComment = true;
144
153
  else if (a === '--no-file')
@@ -233,6 +242,17 @@ function cleanDomain(input) {
233
242
  fail(`"${input}" doesn't look like a domain (example: myapp.com)`);
234
243
  return domain;
235
244
  }
245
+ /** Run a core call; a CoreError (folder not found, not a git repository...) becomes the usual usage error. */
246
+ function core(fn) {
247
+ try {
248
+ return fn();
249
+ }
250
+ catch (err) {
251
+ if (err instanceof CoreError)
252
+ fail(err.message);
253
+ throw err;
254
+ }
255
+ }
236
256
  function fail(message) {
237
257
  process.stderr.write(`launch-doctor: ${message}\n`);
238
258
  process.exit(2);
@@ -241,12 +261,14 @@ function init(argv) {
241
261
  const hooks = argv.includes('--hooks');
242
262
  const monitor = argv.includes('--monitor');
243
263
  const upgrade = argv.includes('--upgrade');
244
- const rest = argv.filter((a) => a !== '--hooks' && a !== '--monitor' && a !== '--upgrade');
264
+ const mcpSetup = argv.includes('--mcp');
265
+ const rest = argv.filter((a) => a !== '--hooks' && a !== '--monitor' && a !== '--upgrade' && a !== '--mcp');
245
266
  const extra = rest.filter((a) => a.startsWith('-'));
246
267
  if (extra.length)
247
- fail(`init only takes --hooks, --hooks --upgrade or --monitor (got ${extra.join(' ')})`);
248
- if (hooks && monitor)
249
- fail('Run "init --hooks" and "init --monitor" one at a time');
268
+ fail(`init only takes --hooks, --hooks --upgrade, --monitor or --mcp (got ${extra.join(' ')})`);
269
+ if ([hooks, monitor, mcpSetup].filter(Boolean).length > 1) {
270
+ fail('Run "init --hooks", "init --monitor" and "init --mcp" one at a time');
271
+ }
250
272
  if (upgrade && !hooks)
251
273
  fail('--upgrade goes with --hooks: launch-doctor init --hooks --upgrade');
252
274
  if (rest.length > 1)
@@ -254,6 +276,11 @@ function init(argv) {
254
276
  const root = resolve(rest[0] ?? '.');
255
277
  if (!existsSync(root) || !statSync(root).isDirectory())
256
278
  fail(`Folder not found: ${root}`);
279
+ if (mcpSetup) {
280
+ // Printed only: the user's Claude Code, Cursor and Claude Desktop settings are never edited.
281
+ process.stdout.write(mcpSetupText(root, pinnedPackage()));
282
+ return;
283
+ }
257
284
  if (hooks && upgrade) {
258
285
  upgradeHooksCommand(root);
259
286
  return;
@@ -276,6 +303,15 @@ function init(argv) {
276
303
  process.stdout.write(` created ${f}\n`);
277
304
  for (const f of skipped)
278
305
  process.stdout.write(` skipped ${f} ${dim('(already exists)')}\n`);
306
+ if (!monitor) {
307
+ const ignored = ensureGitignore(root);
308
+ if (ignored === 'created' || ignored === 'updated') {
309
+ process.stdout.write(` ${ignored} .gitignore ${dim('(added .launchdoctor/, where grades and report.md are kept)')}\n`);
310
+ }
311
+ else if (ignored === 'skipped') {
312
+ process.stdout.write(` skipped .gitignore ${dim('(a link or special file: add .launchdoctor/ to it yourself)')}\n`);
313
+ }
314
+ }
279
315
  if (monitor && created.length) {
280
316
  const repo = githubRepo(git(root, ['remote', 'get-url', 'origin'])) ?? undefined;
281
317
  process.stdout.write(`\n It runs every Monday and keeps grades.json and badge.svg on the ${GRADES_BRANCH} branch\n` +
@@ -316,10 +352,7 @@ function grades(argv) {
316
352
  fail(`grades only takes --json (got ${extra.join(' ')})`);
317
353
  if (rest.length > 1)
318
354
  fail('grades takes at most one folder');
319
- const root = resolve(rest[0] ?? '.');
320
- if (!existsSync(root) || !statSync(root).isDirectory())
321
- fail(`Folder not found: ${root}`);
322
- const entries = loadGrades(root);
355
+ const entries = core(() => gradeHistory(rest[0] ?? '.'));
323
356
  if (json)
324
357
  process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`);
325
358
  else
@@ -350,7 +383,9 @@ const MCP_HELP = `
350
383
  ${bold('launch-doctor mcp')} - an MCP server for Claude Code, Cursor and other AI coding tools
351
384
 
352
385
  ${bold('Usage')}
353
- npx launch-doctor mcp Your AI tool starts this itself and talks to it over stdin and stdout
386
+ npx launch-doctor mcp [folder] Your AI tool starts this itself and talks to it over stdin and stdout.
387
+ The tools read only that folder (default: the one it starts in).
388
+ npx launch-doctor init --mcp Print the exact setup commands and JSON for your tools
354
389
 
355
390
  ${bold('Tools it offers')}
356
391
  scan_project Check a project folder: grade, findings with fix prompts, and the checklist
@@ -367,9 +402,12 @@ async function mcp(argv) {
367
402
  process.stdout.write(MCP_HELP);
368
403
  return;
369
404
  }
370
- if (argv.length)
371
- fail(`mcp doesn't take options (got ${argv.join(' ')}). Run "launch-doctor mcp --help" for setup.`);
372
- await runMcpServer();
405
+ const options = argv.filter((a) => a.startsWith('-'));
406
+ if (options.length || argv.length > 1) {
407
+ fail(`mcp takes only a project folder (got ${argv.join(' ')}). Run "launch-doctor mcp --help" for setup.`);
408
+ }
409
+ // The project the tools read: the given folder, or the folder the AI tool started the server in.
410
+ await runMcpServer(process.stdin, process.stdout, core(() => projectRoot(argv[0] ?? '.')));
373
411
  }
374
412
  const SCAN_HELP = `
375
413
  ${bold('launch-doctor scan')} - check your deployed site from the outside
@@ -599,9 +637,11 @@ async function prompt(argv) {
599
637
  else if (a.startsWith('-'))
600
638
  fail(`Unknown option ${a}. Run "launch-doctor prompt --help" to see the options.`);
601
639
  else if (n === undefined) {
602
- if (!/^\d+$/.test(a) || Number(a) < 1)
603
- fail(`prompt needs a prompt number (1 or more), not "${a}"`);
604
- n = Number(a);
640
+ // A fix-prompt number (1, 2...) or a finding's id from the report (8 letters and digits).
641
+ if (!(/^\d+$/.test(a) && Number(a) >= 1) && !/^[0-9a-f]{8}$/i.test(a)) {
642
+ fail(`prompt needs a prompt number (1 or more) or a finding id, not "${a}"`);
643
+ }
644
+ n = a;
605
645
  }
606
646
  else if (!folder)
607
647
  folder = a;
@@ -612,28 +652,18 @@ async function prompt(argv) {
612
652
  fail('prompt needs a number, for example: npx launch-doctor prompt 1 --copy');
613
653
  if (demo && folder)
614
654
  fail('--demo uses a built-in sample app, so leave out the folder');
615
- let root = resolve(folder ?? '.');
616
- if (demo) {
617
- root = createDemoProject();
618
- offline = true;
619
- }
620
- else if (!existsSync(root) || !statSync(root).isDirectory())
621
- fail(`Folder not found: ${root}`);
622
- let report;
623
- try {
624
- report = await runDoctor(root, { offline, domain });
625
- }
626
- finally {
627
- if (demo)
628
- rmSync(root, { recursive: true, force: true });
629
- }
655
+ const request = (root) => scanProject({ root, offline: demo || offline, domain });
656
+ const report = demo ? await withDemo(request) : await request(core(() => projectRoot(folder ?? '.')));
630
657
  const total = report.counts.critical + report.counts.warning + report.counts.baseline;
631
- const finding = promptFor(report, n);
658
+ const finding = findFinding(report, n);
632
659
  if (!finding) {
633
- fail(total
634
- ? `There ${total === 1 ? 'is only 1 fix prompt' : `are only ${total} fix prompts`}, so there is no prompt ${n}.`
635
- : 'There are no fix prompts: Launch Doctor found nothing to fix.');
660
+ fail(!/^\d+$/.test(n)
661
+ ? `No finding with id ${n} in this project (ids come from the report; they change when the line changes).`
662
+ : total
663
+ ? `There ${total === 1 ? 'is only 1 fix prompt' : `are only ${total} fix prompts`}, so there is no prompt ${n}.`
664
+ : 'There are no fix prompts: Launch Doctor found nothing to fix.');
636
665
  }
666
+ n = String(promptNumber(report, finding));
637
667
  const title = finding.display?.title ?? finding.title;
638
668
  if (copy) {
639
669
  if (copyToClipboard(finding.fixPrompt)) {
@@ -644,6 +674,47 @@ async function prompt(argv) {
644
674
  }
645
675
  process.stdout.write(`Fix prompt ${n}: ${title}\n\n${finding.fixPrompt}\n`);
646
676
  }
677
+ /** `launch-doctor explain <n|id> [folder] [--demo]`: what one finding means, from the same core as the MCP tool. */
678
+ async function explain(argv) {
679
+ const demo = argv.includes('--demo');
680
+ const rest = argv.filter((a) => a !== '--demo');
681
+ const extra = rest.filter((a) => a.startsWith('-'));
682
+ if (extra.length)
683
+ fail(`explain only takes --demo (got ${extra.join(' ')})`);
684
+ const [key, folder, more] = rest;
685
+ if (!key || more)
686
+ fail('explain needs one finding: a number from the report or its id, for example: launch-doctor explain 1');
687
+ if (demo && folder)
688
+ fail('--demo uses a built-in sample app, so leave out the folder');
689
+ const request = (root) => scanProject({ root, offline: true });
690
+ const report = demo ? await withDemo(request) : await request(core(() => projectRoot(folder ?? '.')));
691
+ const finding = findFinding(report, key);
692
+ if (!finding)
693
+ fail(`No finding ${key} in this project. Run launch-doctor first to see the numbers and ids.`);
694
+ const d = findingDetails(report, finding);
695
+ const e = d.explanation;
696
+ const out = [
697
+ '',
698
+ ` ${bold(`${d.number}. ${d.title}`)}`,
699
+ ` ${dim(`${d.severity} · id ${d.ref} · rule ${d.rule}${d.file ? ` · ${shortWhere({ file: d.file, line: d.line })}` : ''}`)}`,
700
+ '',
701
+ ...wrap(d.why, 76, ' '),
702
+ ...(e
703
+ ? [
704
+ ['Why it matters', e.whyItMatters],
705
+ ['How to confirm', e.howToConfirm],
706
+ ['How to fix', e.howToFix],
707
+ ['False alarm?', e.falsePositiveHint],
708
+ ].flatMap(([label, text]) => ['', ` ${bold(label)}`, ...wrap(text, 76, ' ')])
709
+ : []),
710
+ ...(d.rotate ? ['', ` ${bold('Rotate the key first:')} ${d.rotate}`] : []),
711
+ ...(d.usage ? [` ${bold('Check whether someone used it:')} ${d.usage}`] : []),
712
+ '',
713
+ ` ${dim(`The fix prompt: launch-doctor prompt ${d.number}${demo ? ' --demo' : folder ? ` ${folder}` : ''} --copy`)}`,
714
+ '',
715
+ ];
716
+ process.stdout.write(`${out.join('\n')}\n`);
717
+ }
647
718
  async function main() {
648
719
  if (process.argv[2] === 'init')
649
720
  return init(process.argv.slice(3));
@@ -657,6 +728,8 @@ async function main() {
657
728
  return grades(process.argv.slice(3));
658
729
  if (process.argv[2] === 'prompt')
659
730
  return prompt(process.argv.slice(3));
731
+ if (process.argv[2] === 'explain')
732
+ return explain(process.argv.slice(3));
660
733
  const args = parseArgs(process.argv.slice(2));
661
734
  if (args.help) {
662
735
  process.stdout.write(HELP);
@@ -666,24 +739,22 @@ async function main() {
666
739
  process.stdout.write(`${version()}\n`);
667
740
  return;
668
741
  }
669
- let stopDemoCleanup;
670
742
  if (args.demo) {
671
743
  if (args.path)
672
744
  fail('--demo scans a built-in sample app, so leave out the folder');
673
- // Ctrl+C mid-scan would otherwise skip the finally below and leave the folder in the temp directory.
674
- let demoDir;
675
- stopDemoCleanup = removeOnSignal(() => demoDir);
676
- demoDir = createDemoProject();
677
- args.path = demoDir;
678
745
  args.offline = true;
679
746
  if (!args.out)
680
747
  args.writeFile = false;
681
- if (!args.json)
682
- process.stdout.write(`\n ${dim('Demo: scanning a sample app with the usual weekend-project mistakes…')}\n`);
683
748
  }
684
- const root = resolve(args.path ?? '.');
685
- if (!existsSync(root) || !statSync(root).isDirectory())
686
- fail(`Folder not found: ${root}`);
749
+ // The demo's folder is only known once the core creates it.
750
+ let root = args.demo ? '' : core(() => projectRoot(args.path ?? '.'));
751
+ if (args.report) {
752
+ // The report describes the whole project, in the project's own .launchdoctor/ folder.
753
+ if (args.demo)
754
+ fail('--report writes to the project folder, so it needs a real project, not --demo');
755
+ if (args.changeMode)
756
+ fail(`--report describes the whole project, so it can't be used with --${args.changeMode}`);
757
+ }
687
758
  if (args.record) {
688
759
  // A recorded grade is compared with the next one, so it has to be for the whole project.
689
760
  if (args.demo)
@@ -692,6 +763,8 @@ async function main() {
692
763
  fail('--record saves the grade for the whole project, so leave out --only and --skip');
693
764
  }
694
765
  if (args.configFrom) {
766
+ if (args.demo)
767
+ fail('--config-from needs a real project folder, not --demo');
695
768
  if (args.updateBaseline)
696
769
  fail('--config-from reads the baseline from git, so it cannot be used with --update-baseline');
697
770
  try {
@@ -715,10 +788,8 @@ async function main() {
715
788
  if (on)
716
789
  fail(`${flag} reports on some files only, so it can't be used with ${name}`);
717
790
  }
718
- const files = changedFiles(root, args.changeMode);
719
- if (!files)
720
- fail(`${flag} needs a folder inside a git repository`);
721
- onlyFiles = files;
791
+ const mode = args.changeMode;
792
+ onlyFiles = core(() => changedPaths(root, mode));
722
793
  // A partial report must not overwrite LAUNCH_FIXES.md, which describes the whole project.
723
794
  if (!args.out)
724
795
  args.writeFile = false;
@@ -726,28 +797,35 @@ async function main() {
726
797
  // The short report is the default for a person at a terminal; CI, hooks and pull requests keep the full one.
727
798
  const short = !args.verbose && !args.json && !args.ci && !args.changeMode && !args.prComment;
728
799
  const progress = short && process.stdout.isTTY ? progressLine() : undefined;
800
+ const request = (dir) => scanProject({
801
+ root: dir,
802
+ onProgress: progress?.update,
803
+ offline: args.offline,
804
+ domain: args.domain,
805
+ only: args.only,
806
+ skip: args.skip,
807
+ // When updating, start from scratch so every current finding is saved.
808
+ baseline: args.baseline && !args.updateBaseline,
809
+ configFrom: args.configFrom,
810
+ history: args.history ? args.historyDepth : undefined,
811
+ onlyFiles,
812
+ });
729
813
  let report;
814
+ // Ctrl+C mid-scan would otherwise leave the demo folder in the temp directory, so the handler goes in first.
815
+ let demoDir;
816
+ const stopDemoCleanup = args.demo ? removeOnSignal(() => demoDir) : undefined;
730
817
  try {
731
- report = await runDoctor(root, {
732
- onProgress: progress?.update,
733
- offline: args.offline,
734
- domain: args.domain,
735
- only: args.only,
736
- skip: args.skip,
737
- // When updating, start from scratch so every current finding is saved.
738
- baseline: args.baseline && !args.updateBaseline,
739
- configFrom: args.configFrom,
740
- history: args.history ? { depth: args.historyDepth } : undefined,
741
- onlyFiles,
742
- });
818
+ report = args.demo
819
+ ? await withDemo(request, (dir) => {
820
+ root = demoDir = dir;
821
+ if (!args.json)
822
+ process.stdout.write(`\n ${dim('Demo: scanning a sample app with the usual weekend-project mistakes…')}\n`);
823
+ })
824
+ : await request(root);
743
825
  }
744
826
  finally {
745
827
  progress?.clear();
746
- // The demo project lives in a temp folder; always clean it up, even if the scan throws.
747
- if (args.demo) {
748
- rmSync(root, { recursive: true, force: true });
749
- stopDemoCleanup?.();
750
- }
828
+ stopDemoCleanup?.();
751
829
  }
752
830
  if (report.filesScanned === 0) {
753
831
  if (!short)
@@ -795,6 +873,20 @@ async function main() {
795
873
  process.stderr.write(`${dim(`Couldn't write ${target}: ${err.message}`)}\n`);
796
874
  }
797
875
  }
876
+ let reportFile;
877
+ if (args.report) {
878
+ const path = join(root, REPORT_FILE);
879
+ try {
880
+ mkdirSync(dirname(path), { recursive: true });
881
+ writeRegularFile(path, renderReportMd(report, { target: args.path ? ` ${shellArg(args.path)}` : '' }));
882
+ const rel = relative(process.cwd(), path);
883
+ reportFile = rel && !rel.startsWith('..') ? rel.replace(/\\/g, '/') : path;
884
+ }
885
+ catch (err) {
886
+ process.stderr.write(`${dim(`Couldn't write ${path}: ${err.message}`)}
887
+ `);
888
+ }
889
+ }
798
890
  if (args.sarif) {
799
891
  const sarifPath = isAbsolute(args.sarif) ? args.sarif : resolve(process.cwd(), args.sarif);
800
892
  const fallbackUri = ['package.json', 'pyproject.toml', 'requirements.txt', 'README.md'].find((f) => existsSync(join(root, f)));
@@ -843,7 +935,7 @@ async function main() {
843
935
  const lastRecorded = last && describeEntry(last);
844
936
  const target = args.demo ? ' --demo' : args.path ? ` ${shellArg(args.path)}` : '';
845
937
  process.stdout.write(short
846
- ? renderShortReport(report, { fixFile, lastRecorded, banner: showBanner, target, demo: args.demo })
938
+ ? renderShortReport(report, { fixFile, reportFile, lastRecorded, banner: showBanner, target, demo: args.demo })
847
939
  : renderReport(report, { fixFile, lastRecorded, banner: showBanner }));
848
940
  }
849
941
  if (recorded)