launch-doctor 0.3.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +77 -6
  2. package/LICENSE +1 -0
  3. package/README.md +95 -20
  4. package/dist/src/access.d.ts +52 -0
  5. package/dist/src/access.js +482 -0
  6. package/dist/src/baseline.d.ts +6 -3
  7. package/dist/src/baseline.js +15 -8
  8. package/dist/src/changed.d.ts +12 -0
  9. package/dist/src/changed.js +34 -0
  10. package/dist/src/checks/access.d.ts +7 -0
  11. package/dist/src/checks/access.js +868 -0
  12. package/dist/src/checks/costs.d.ts +7 -0
  13. package/dist/src/checks/costs.js +14 -6
  14. package/dist/src/checks/database.js +79 -3
  15. package/dist/src/checks/first-impressions.js +22 -2
  16. package/dist/src/checks/legal.js +3 -1
  17. package/dist/src/checks/monitoring.js +8 -5
  18. package/dist/src/checks/payments.js +10 -2
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +82 -9
  21. package/dist/src/checks/supabase-storage.d.ts +31 -0
  22. package/dist/src/checks/supabase-storage.js +216 -0
  23. package/dist/src/cli.js +111 -9
  24. package/dist/src/demo.js +1 -0
  25. package/dist/src/detect.d.ts +1 -1
  26. package/dist/src/detect.js +1 -1
  27. package/dist/src/fixes.js +8 -5
  28. package/dist/src/git.d.ts +25 -0
  29. package/dist/src/git.js +121 -0
  30. package/dist/src/github.d.ts +11 -1
  31. package/dist/src/github.js +56 -14
  32. package/dist/src/history.js +17 -3
  33. package/dist/src/hook.d.ts +13 -0
  34. package/dist/src/hook.js +96 -0
  35. package/dist/src/hooks-setup.d.ts +24 -0
  36. package/dist/src/hooks-setup.js +187 -0
  37. package/dist/src/ignore.d.ts +36 -0
  38. package/dist/src/ignore.js +164 -0
  39. package/dist/src/index.js +28 -3
  40. package/dist/src/live.d.ts +9 -0
  41. package/dist/src/live.js +73 -22
  42. package/dist/src/mcp.js +7 -2
  43. package/dist/src/net-guard.d.ts +34 -0
  44. package/dist/src/net-guard.js +144 -0
  45. package/dist/src/project.d.ts +34 -5
  46. package/dist/src/project.js +145 -111
  47. package/dist/src/report.d.ts +2 -0
  48. package/dist/src/report.js +11 -0
  49. package/dist/src/routes.d.ts +10 -0
  50. package/dist/src/routes.js +21 -4
  51. package/dist/src/safe-fs.d.ts +19 -0
  52. package/dist/src/safe-fs.js +77 -0
  53. package/dist/src/sanitize.d.ts +17 -0
  54. package/dist/src/sanitize.js +90 -0
  55. package/dist/src/sarif.js +1 -1
  56. package/dist/src/summary.d.ts +4 -0
  57. package/dist/src/summary.js +9 -4
  58. package/dist/src/types.d.ts +24 -0
  59. package/dist/src/util.d.ts +1 -1
  60. package/dist/src/util.js +1 -1
  61. package/package.json +9 -5
@@ -3,6 +3,11 @@ import type { Finding, Report } from './types.js';
3
3
  export declare const SUMMARY_MARKER = "<!-- launch-doctor:summary -->";
4
4
  /** At most this many inline comments per run, so a big pull request isn't buried. */
5
5
  export declare const MAX_INLINE = 20;
6
+ /**
7
+ * GitHub rejects a comment longer than 65,536 characters (and then no summary is posted at all). The summary comment
8
+ * is kept under this, with room to spare: lists get shorter until it fits.
9
+ */
10
+ export declare const MAX_COMMENT_CHARS = 60000;
6
11
  export interface PrContext {
7
12
  apiUrl: string;
8
13
  serverUrl: string;
@@ -13,6 +18,8 @@ export interface PrContext {
13
18
  token: string;
14
19
  /** Where the scanned folder sits inside the repository ("" for the repository root, "web" for ./web). */
15
20
  prefix: string;
21
+ /** The workflow run (GITHUB_RUN_ID), to link to its job summary, which lists every finding. */
22
+ runId?: string;
16
23
  }
17
24
  /**
18
25
  * Work out which pull request we're running for from the GitHub Actions environment.
@@ -49,7 +56,10 @@ export declare function repoPath(prefix: string, file: string): string;
49
56
  export declare function placeFindings(report: Report, changed: Map<string, ChangedLines>, prefix: string): Placement;
50
57
  /** The body of one inline review comment: what's wrong, why, the fix prompt, and how to silence it. */
51
58
  export declare function renderInlineComment(item: InlineFinding): string;
52
- /** The one summary comment on the pull request, edited in place on every run. */
59
+ /**
60
+ * The one summary comment on the pull request, edited in place on every run. It always fits GitHub's limit: when
61
+ * the full lists would make it too long, they are cut (fewer and fewer items) and say where to see everything.
62
+ */
53
63
  export declare function renderPrComment(report: Report, placement: Placement, ctx: PrContext): string;
54
64
  export declare class GitHubError extends Error {
55
65
  readonly status: number;
@@ -1,13 +1,28 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { isAbsolute, relative } from 'node:path';
3
+ import { htmlCommentSafe, md, mdCode } from './sanitize.js';
3
4
  import { categoryTable, escapeCell } from './summary.js';
4
5
  /** Marks our one summary comment on a pull request, so later runs edit it instead of adding another. */
5
6
  export const SUMMARY_MARKER = '<!-- launch-doctor:summary -->';
6
7
  const FINDING_MARKER = /<!-- launch-doctor:finding (\S+) -->/;
8
+ /**
9
+ * A finding's key as written into its inline comment's hidden marker: a file path in it can't end the HTML comment
10
+ * ("-->"), and it has no spaces, so FINDING_MARKER reads it back whole (keys with spaces were reposted every run).
11
+ */
12
+ function markerKey(key) {
13
+ return htmlCommentSafe(key).replace(/\s/g, '_');
14
+ }
7
15
  /** At most this many inline comments per run, so a big pull request isn't buried. */
8
16
  export const MAX_INLINE = 20;
9
- /** At most this many findings per list in the summary comment (GitHub caps a comment at 65,536 characters). */
17
+ /** At most this many findings per list in the summary comment. */
10
18
  const MAX_LISTED = 50;
19
+ /**
20
+ * GitHub rejects a comment longer than 65,536 characters (and then no summary is posted at all). The summary comment
21
+ * is kept under this, with room to spare: lists get shorter until it fits.
22
+ */
23
+ export const MAX_COMMENT_CHARS = 60_000;
24
+ /** A finding title longer than this is cut in lists (a title can hold a long name from a file). */
25
+ const MAX_TITLE_CHARS = 300;
11
26
  /**
12
27
  * Work out which pull request we're running for from the GitHub Actions environment.
13
28
  * Returns a reason string instead when there's nothing to comment on.
@@ -47,6 +62,7 @@ export function prContextFromEnv(root, env = process.env) {
47
62
  headSha,
48
63
  token,
49
64
  prefix,
65
+ ...(env.GITHUB_RUN_ID ? { runId: env.GITHUB_RUN_ID } : {}),
50
66
  };
51
67
  }
52
68
  /** Line numbers (in the new version of the file) that a unified diff patch adds. */
@@ -111,10 +127,10 @@ const label = (f) => (f.severity === 'critical' ? '[CRITICAL]' : '[WARN]');
111
127
  export function renderInlineComment(item) {
112
128
  const f = item.finding;
113
129
  return [
114
- `<!-- launch-doctor:finding ${item.key} -->`,
115
- `**${label(f)} ${f.title}**`,
130
+ `<!-- launch-doctor:finding ${markerKey(item.key)} -->`,
131
+ `**${label(f)} ${md(f.title)}**`,
116
132
  '',
117
- f.why,
133
+ md(f.why, { oneLine: false }),
118
134
  '',
119
135
  '<details><summary>Fix prompt (paste into Claude Code, Cursor, Lovable or Bolt)</summary>',
120
136
  '',
@@ -131,12 +147,23 @@ function fence(text) {
131
147
  const ticks = '`'.repeat(longest + 1);
132
148
  return `${ticks}text\n${text}\n${ticks}`;
133
149
  }
134
- function listItems(items, line) {
135
- const out = items.slice(0, MAX_LISTED).map(line);
136
- if (items.length > MAX_LISTED)
137
- out.push(`- ...and ${items.length - MAX_LISTED} more`);
150
+ /** Where every finding can be seen when a list in the summary comment is cut short. */
151
+ function seeAll(ctx) {
152
+ const summary = ctx.runId
153
+ ? `the [job summary](${ctx.serverUrl}/${ctx.repo}/actions/runs/${encodeURIComponent(ctx.runId)}) of this run`
154
+ : "this run's job summary";
155
+ return `Every finding is listed in ${summary}, and \`npx launch-doctor\` writes them all to LAUNCH_FIXES.md.`;
156
+ }
157
+ function listItems(items, line, max, ctx) {
158
+ const out = items.slice(0, max).map(line);
159
+ if (items.length > max)
160
+ out.push(`- ...and ${items.length - max} more. ${seeAll(ctx)}`);
138
161
  return out;
139
162
  }
163
+ /** A title for a list line, cut to MAX_TITLE_CHARS before it is escaped. */
164
+ function listTitle(title) {
165
+ return escapeCell(title.length > MAX_TITLE_CHARS ? `${title.slice(0, MAX_TITLE_CHARS)}...` : title);
166
+ }
140
167
  function countText(findings) {
141
168
  const crit = findings.filter((f) => f.severity === 'critical').length;
142
169
  const warn = findings.length - crit;
@@ -147,10 +174,25 @@ function countText(findings) {
147
174
  parts.push(`${warn} warning${warn === 1 ? '' : 's'}`);
148
175
  return parts.join(', ');
149
176
  }
150
- /** The one summary comment on the pull request, edited in place on every run. */
177
+ /**
178
+ * The one summary comment on the pull request, edited in place on every run. It always fits GitHub's limit: when
179
+ * the full lists would make it too long, they are cut (fewer and fewer items) and say where to see everything.
180
+ */
151
181
  export function renderPrComment(report, placement, ctx) {
182
+ let max = MAX_LISTED;
183
+ let body = renderPrCommentListing(report, placement, ctx, max);
184
+ while (body.length > MAX_COMMENT_CHARS && max > 0) {
185
+ max = Math.floor(max / 2);
186
+ body = renderPrCommentListing(report, placement, ctx, max);
187
+ }
188
+ // With no list items left it is a few short lines; a cut here is only a last resort (a huge repository name?).
189
+ if (body.length > MAX_COMMENT_CHARS)
190
+ body = `${body.slice(0, MAX_COMMENT_CHARS - 200)}\n\n...cut short. ${seeAll(ctx)}`;
191
+ return body;
192
+ }
193
+ function renderPrCommentListing(report, placement, ctx, max) {
152
194
  const link = (path, line) => `${ctx.serverUrl}/${ctx.repo}/blob/${ctx.headSha}/${path.split('/').map(encodeURIComponent).join('/')}${line ? `#L${line}` : ''}`;
153
- const where = (path, line) => `[\`${line ? `${path}:${line}` : path}\`](${link(path, line)})`;
195
+ const where = (path, line) => `[${mdCode(line ? `${path}:${line}` : path)}](${link(path, line)})`;
154
196
  const out = [
155
197
  SUMMARY_MARKER,
156
198
  `## Launch Doctor: grade ${report.grade}`,
@@ -161,7 +203,7 @@ export function renderPrComment(report, placement, ctx) {
161
203
  '',
162
204
  ];
163
205
  if (placement.inPr.length) {
164
- out.push(`${countText(placement.inPr.map((i) => i.finding))} on lines this pull request adds. Each one has an inline comment with a fix prompt.`, '', ...listItems(placement.inPr, (i) => `- ${label(i.finding)} ${escapeCell(i.finding.title)} (${where(i.path, i.line)})`));
206
+ out.push(`${countText(placement.inPr.map((i) => i.finding))} on lines this pull request adds. Each one has an inline comment with a fix prompt.`, '', ...listItems(placement.inPr, (i) => `- ${label(i.finding)} ${listTitle(i.finding.title)} (${where(i.path, i.line)})`, max, ctx));
165
207
  }
166
208
  else {
167
209
  out.push('No problems in the lines this pull request adds.');
@@ -170,8 +212,8 @@ export function renderPrComment(report, placement, ctx) {
170
212
  if (placement.elsewhere.length) {
171
213
  out.push(`<details><summary>Already in the project: ${countText(placement.elsewhere)}</summary>`, '', ...listItems(placement.elsewhere, (f) => {
172
214
  const loc = f.location ? ` (${where(repoPath(ctx.prefix, f.location.file), f.location.line)})` : '';
173
- return `- ${label(f)} ${escapeCell(f.title)}${loc}`;
174
- }), '', '</details>', '');
215
+ return `- ${label(f)} ${listTitle(f.title)}${loc}`;
216
+ }, max, ctx), '', '</details>', '');
175
217
  }
176
218
  out.push('<details><summary>Scorecard</summary>', '', ...categoryTable(report), '', '</details>', '');
177
219
  const notes = [];
@@ -241,7 +283,7 @@ export async function postPrFeedback(report, ctx, fetchImpl = globalThis.fetch)
241
283
  // Inline comments: skip findings we already commented on in an earlier run.
242
284
  const reviewComments = await gh.list(`${base}/pulls/${ctx.number}/comments`);
243
285
  const seen = new Set(reviewComments.map((c) => FINDING_MARKER.exec(c.body ?? '')?.[1]).filter(Boolean));
244
- const fresh = placement.inPr.filter((i) => !seen.has(i.key));
286
+ const fresh = placement.inPr.filter((i) => !seen.has(markerKey(i.key)));
245
287
  const toPost = fresh.slice(0, MAX_INLINE);
246
288
  let inlineError;
247
289
  if (toPost.length) {
@@ -1,11 +1,14 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
3
  import { matchKeys } from './checks/secrets.js';
4
- import { gitArgs, isRealEnvPath } from './project.js';
4
+ import { gitArgs, SAFE_DIFF } from './git.js';
5
+ import { isRealEnvPath } from './project.js';
5
6
  import { mask } from './util.js';
6
7
  export const DEFAULT_HISTORY_DEPTH = 500;
7
8
  /** Stop reading git output after this many bytes, so huge repos don't take forever. */
8
9
  export const HISTORY_BYTE_CAP = 64 * 1024 * 1024;
10
+ /** And after this long, whatever has been read by then. */
11
+ const HISTORY_TIMEOUT_MS = 120_000;
9
12
  /**
10
13
  * Look for API keys that were added in past commits and are no longer in the code.
11
14
  * Only added lines ("+" in the diff) are checked. Keys that are still in the working tree are
@@ -14,7 +17,7 @@ export const HISTORY_BYTE_CAP = 64 * 1024 * 1024;
14
17
  export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
15
18
  if (!ctx.gitRoot)
16
19
  return { findings: [], commitsScanned: 0, truncated: false };
17
- const args = gitArgs([
20
+ const args = gitArgs(ctx.root, [
18
21
  'log',
19
22
  '-p',
20
23
  '--all',
@@ -22,10 +25,18 @@ export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
22
25
  '-U0',
23
26
  `--max-count=${depth}`,
24
27
  '--pretty=format:commit %H',
25
- '--no-ext-diff',
28
+ ...SAFE_DIFF,
26
29
  ]);
30
+ // null: this repository's config can't be made safe to run git in (see src/git.ts).
31
+ if (!args)
32
+ return { findings: [], commitsScanned: 0, truncated: false };
27
33
  const child = spawn('git', args, { cwd: ctx.root, stdio: ['ignore', 'pipe', 'ignore'] });
28
34
  const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
35
+ let timedOut = false;
36
+ const timer = setTimeout(() => {
37
+ timedOut = true;
38
+ child.kill();
39
+ }, HISTORY_TIMEOUT_MS);
29
40
  const hits = new Map();
30
41
  let commit = '';
31
42
  let path = '';
@@ -56,6 +67,9 @@ export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
56
67
  }
57
68
  }
58
69
  await new Promise((resolve) => (child.exitCode !== null ? resolve(null) : child.once('close', resolve)));
70
+ clearTimeout(timer);
71
+ if (timedOut)
72
+ truncated = true;
59
73
  // What's in the code today is reported by the normal scan (real .env files are meant to hold keys).
60
74
  const current = ctx.files
61
75
  .filter((f) => !isRealEnvPath(f.path))
@@ -0,0 +1,13 @@
1
+ import type { Finding, Report } from './types.js';
2
+ export type HookKind = 'claude' | 'cursor';
3
+ export interface HookResult {
4
+ exitCode: number;
5
+ stdout: string;
6
+ stderr: string;
7
+ }
8
+ /** Findings a hook should bring up: new ones (not in the baseline), worst first. */
9
+ export declare function hookFindings(report: Report): Finding[];
10
+ /** The message an AI coding tool reads: what is wrong, where, and the prompt that fixes it. */
11
+ export declare function renderHookMessage(findings: Finding[], scope: string): string;
12
+ /** Run a hook. `stdin` is the JSON the AI tool sent. Never throws. */
13
+ export declare function runHook(kind: HookKind, stdin: string, env?: NodeJS.ProcessEnv): Promise<HookResult>;
@@ -0,0 +1,96 @@
1
+ import { isAbsolute, relative, resolve } from 'node:path';
2
+ import { changedFiles } from './changed.js';
3
+ import { runDoctor } from './index.js';
4
+ /** How many findings one message carries. More than this is a wall of text the agent skims. */
5
+ const MAX_FINDINGS = 5;
6
+ const NOTHING = {
7
+ claude: { exitCode: 0, stdout: '', stderr: '' },
8
+ cursor: { exitCode: 0, stdout: '{}\n', stderr: '' },
9
+ };
10
+ /** Findings a hook should bring up: new ones (not in the baseline), worst first. */
11
+ export function hookFindings(report) {
12
+ return report.categories
13
+ .flatMap((c) => c.findings)
14
+ .filter((f) => !f.baseline)
15
+ .sort((a, b) => Number(b.severity === 'critical') - Number(a.severity === 'critical'));
16
+ }
17
+ /** The message an AI coding tool reads: what is wrong, where, and the prompt that fixes it. */
18
+ export function renderHookMessage(findings, scope) {
19
+ const lines = [
20
+ `Launch Doctor found ${findings.length === 1 ? 'a problem' : `${findings.length} problems`} in ${scope}:`,
21
+ '',
22
+ ];
23
+ findings.slice(0, MAX_FINDINGS).forEach((f, i) => {
24
+ const where = f.location ? ` (${f.location.file}${f.location.line ? `:${f.location.line}` : ''})` : '';
25
+ lines.push(`${i + 1}. [${f.severity}] ${f.title}${where} [id: ${f.id}]`, ` Why: ${f.why}`, ` Fix: ${f.fixPrompt}`, '');
26
+ });
27
+ if (findings.length > MAX_FINDINGS)
28
+ lines.push(`...and ${findings.length - MAX_FINDINGS} more. Run "npx launch-doctor --changed" to see them all.`, '');
29
+ lines.push('Please fix these. If one is a false alarm, do not silence it yourself: tell the user why, and let them decide whether to add a launch-doctor-ignore comment.');
30
+ return lines.join('\n');
31
+ }
32
+ function parse(stdin) {
33
+ try {
34
+ const v = JSON.parse(stdin);
35
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
36
+ }
37
+ catch {
38
+ return {};
39
+ }
40
+ }
41
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
42
+ /**
43
+ * Claude Code PostToolUse hook, run after Claude edits a file. Checks that one file; when it has a
44
+ * problem, exit code 2 sends the message to Claude on stderr (the edit has already happened).
45
+ * Anything unexpected exits 0: a hook must never get in the way of the work.
46
+ */
47
+ async function claudeHook(input, env) {
48
+ const toolInput = input.tool_input;
49
+ const file = str(toolInput?.file_path);
50
+ if (!file)
51
+ return NOTHING.claude;
52
+ const root = resolve(env.CLAUDE_PROJECT_DIR || str(input.cwd) || process.cwd());
53
+ const rel = relative(root, resolve(root, file));
54
+ // Outside the project (or on another drive): not ours to check.
55
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
56
+ return NOTHING.claude;
57
+ const report = await runDoctor(root, { onlyFiles: [rel.replace(/\\/g, '/')] });
58
+ const findings = hookFindings(report);
59
+ if (!findings.length)
60
+ return NOTHING.claude;
61
+ return { exitCode: 2, stdout: '', stderr: `${renderHookMessage(findings, rel.replace(/\\/g, '/'))}\n` };
62
+ }
63
+ /**
64
+ * Cursor stop hook, run when the agent finishes. Checks every file changed since the last commit;
65
+ * a "followup_message" is sent to the agent as its next prompt. (afterFileEdit is not used: Cursor's
66
+ * documentation doesn't say its output reaches the agent.)
67
+ */
68
+ async function cursorHook(input, env) {
69
+ if (input.status !== undefined && input.status !== 'completed')
70
+ return NOTHING.cursor;
71
+ const roots = Array.isArray(input.workspace_roots) ? input.workspace_roots : [];
72
+ const root = resolve(str(roots[0]) || env.CURSOR_PROJECT_DIR || process.cwd());
73
+ const files = changedFiles(root, 'changed');
74
+ if (!files?.length)
75
+ return NOTHING.cursor;
76
+ const report = await runDoctor(root, { onlyFiles: files });
77
+ const findings = hookFindings(report);
78
+ if (!findings.length)
79
+ return NOTHING.cursor;
80
+ const scope = files.length === 1 ? files[0] : `the ${files.length} files you changed`;
81
+ return {
82
+ exitCode: 0,
83
+ stdout: `${JSON.stringify({ followup_message: renderHookMessage(findings, scope) })}\n`,
84
+ stderr: '',
85
+ };
86
+ }
87
+ /** Run a hook. `stdin` is the JSON the AI tool sent. Never throws. */
88
+ export async function runHook(kind, stdin, env = process.env) {
89
+ try {
90
+ const input = parse(stdin);
91
+ return kind === 'claude' ? await claudeHook(input, env) : await cursorHook(input, env);
92
+ }
93
+ catch {
94
+ return NOTHING[kind];
95
+ }
96
+ }
@@ -0,0 +1,24 @@
1
+ export interface HookSetupResult {
2
+ created: string[];
3
+ /** Existing files that a launch-doctor hook was added to. */
4
+ updated: string[];
5
+ /** [file, why] for everything left alone. */
6
+ skipped: [string, string][];
7
+ }
8
+ /**
9
+ * The package spec every generated hook runs: the current minor range from package.json ("launch-doctor@^0.4.0"), so a
10
+ * hook never silently picks up a newer minor version (or a new major one) just because it was published to npm.
11
+ */
12
+ export declare function pinnedPackage(): string;
13
+ /**
14
+ * A value in single quotes for a POSIX shell. Nothing inside single quotes is expanded, so a folder named
15
+ * `app$(curl ...)` stays a folder name; a single quote in the value is written as '\''.
16
+ */
17
+ export declare function shellQuote(value: string): string;
18
+ /**
19
+ * The block added to the pre-commit hook. Only exit code 1 (critical problems in the staged files)
20
+ * stops the commit. If the tool itself fails (no network for npx, for example) the commit goes ahead.
21
+ */
22
+ export declare function preCommitBlock(projectDir: string): string;
23
+ /** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
24
+ export declare function setupHooks(root: string): HookSetupResult;
@@ -0,0 +1,187 @@
1
+ import { chmodSync, mkdirSync, realpathSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { gitHooksDir } from './git.js';
4
+ import { CONFIG_FILE_MAX_BYTES, findGitRoot } from './project.js';
5
+ import { entryKind, readRegularFile, writeRegularFile } from './safe-fs.js';
6
+ import { version } from './version.js';
7
+ /**
8
+ * The package spec every generated hook runs: the current minor range from package.json ("launch-doctor@^0.4.0"), so a
9
+ * hook never silently picks up a newer minor version (or a new major one) just because it was published to npm.
10
+ */
11
+ export function pinnedPackage() {
12
+ const [major, minor] = version().split('.');
13
+ return `launch-doctor@^${major}.${minor}.0`;
14
+ }
15
+ /**
16
+ * `--yes` so npx never stops to ask for permission when an AI tool or git runs it without a terminal. The package is in
17
+ * double quotes because "^" means something to cmd.exe and to zsh with extended globbing.
18
+ */
19
+ const claudeCommand = () => `npx --yes "${pinnedPackage()}" hook claude`;
20
+ const cursorCommand = () => `npx --yes "${pinnedPackage()}" hook cursor`;
21
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
22
+ /**
23
+ * Read a JSON file. `null` = it doesn't exist, `'invalid'` = it isn't a JSON object, `'special'` = it is a link,
24
+ * a FIFO or another special file (never opened or written through, see src/safe-fs.ts).
25
+ */
26
+ function readJson(path) {
27
+ const kind = entryKind(path);
28
+ if (kind === 'missing')
29
+ return null;
30
+ const text = kind === 'file' ? readRegularFile(path, CONFIG_FILE_MAX_BYTES) : null;
31
+ if (text === null)
32
+ return 'special';
33
+ try {
34
+ const v = JSON.parse(text);
35
+ return isObject(v) ? v : 'invalid';
36
+ }
37
+ catch {
38
+ return 'invalid';
39
+ }
40
+ }
41
+ const SPECIAL = 'it is a link or a special file, not a regular file, so it was left alone';
42
+ function writeJson(path, data) {
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ writeRegularFile(path, `${JSON.stringify(data, null, 2)}\n`);
45
+ }
46
+ /**
47
+ * Does this hook list already run a launch-doctor hook command? Any version counts, including the unpinned commands
48
+ * older releases wrote: re-running init never adds a second hook, and never rewrites one the user already has.
49
+ */
50
+ const hasOurCommand = (entries, tool) => new RegExp(String.raw `\blaunch-doctor(?:@[^\s"\\]+)?\\?"? hook ${tool}\b`).test(JSON.stringify(entries ?? null));
51
+ /** .claude/settings.json: a PostToolUse hook that checks every file Claude Code writes or edits. */
52
+ function setupClaude(root, result) {
53
+ const rel = '.claude/settings.json';
54
+ const path = join(root, rel);
55
+ const settings = readJson(path);
56
+ if (settings === 'special')
57
+ return void result.skipped.push([rel, SPECIAL]);
58
+ if (settings === 'invalid')
59
+ return void result.skipped.push([rel, "it isn't a valid JSON object, so it was left alone"]);
60
+ const data = settings ?? {};
61
+ const hooks = data.hooks ?? {};
62
+ if (!isObject(hooks))
63
+ return void result.skipped.push([rel, '"hooks" has an unexpected shape, so it was left alone']);
64
+ const post = hooks.PostToolUse ?? [];
65
+ if (!Array.isArray(post))
66
+ return void result.skipped.push([rel, '"hooks.PostToolUse" has an unexpected shape, so it was left alone']);
67
+ if (hasOurCommand(post, 'claude'))
68
+ return void result.skipped.push([rel, 'already set up']);
69
+ post.push({ matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: claudeCommand(), timeout: 60 }] });
70
+ writeJson(path, { ...data, hooks: { ...hooks, PostToolUse: post } });
71
+ (settings === null ? result.created : result.updated).push(rel);
72
+ }
73
+ /** .cursor/hooks.json: a stop hook that checks the files the agent changed before it finishes. */
74
+ function setupCursor(root, result) {
75
+ const rel = '.cursor/hooks.json';
76
+ const path = join(root, rel);
77
+ const config = readJson(path);
78
+ if (config === 'special')
79
+ return void result.skipped.push([rel, SPECIAL]);
80
+ if (config === 'invalid')
81
+ return void result.skipped.push([rel, "it isn't a valid JSON object, so it was left alone"]);
82
+ const data = config ?? {};
83
+ const hooks = data.hooks ?? {};
84
+ if (!isObject(hooks))
85
+ return void result.skipped.push([rel, '"hooks" has an unexpected shape, so it was left alone']);
86
+ const stop = hooks.stop ?? [];
87
+ if (!Array.isArray(stop))
88
+ return void result.skipped.push([rel, '"hooks.stop" has an unexpected shape, so it was left alone']);
89
+ if (hasOurCommand(stop, 'cursor'))
90
+ return void result.skipped.push([rel, 'already set up']);
91
+ stop.push({ command: cursorCommand(), timeout: 60 });
92
+ writeJson(path, { version: 1, ...data, hooks: { ...hooks, stop } });
93
+ (config === null ? result.created : result.updated).push(rel);
94
+ }
95
+ const MARK_START = '# >>> launch-doctor (added by "launch-doctor init --hooks") >>>';
96
+ const MARK_END = '# <<< launch-doctor <<<';
97
+ /**
98
+ * A value in single quotes for a POSIX shell. Nothing inside single quotes is expanded, so a folder named
99
+ * `app$(curl ...)` stays a folder name; a single quote in the value is written as '\''.
100
+ */
101
+ export function shellQuote(value) {
102
+ return `'${value.replace(/'/g, `'\\''`)}'`;
103
+ }
104
+ /**
105
+ * The block added to the pre-commit hook. Only exit code 1 (critical problems in the staged files)
106
+ * stops the commit. If the tool itself fails (no network for npx, for example) the commit goes ahead.
107
+ */
108
+ export function preCommitBlock(projectDir) {
109
+ // "./" keeps a folder named like an option ("-x", "--ci") from being read as one.
110
+ const dir = projectDir ? ` ${shellQuote(projectDir.startsWith('-') ? `./${projectDir}` : projectDir)}` : '';
111
+ return [
112
+ MARK_START,
113
+ '# Quiet when everything is fine: the report is only shown if something is wrong.',
114
+ `launch_doctor_output=$(npx --yes "${pinnedPackage()}"${dir} --staged --ci --no-file 2>&1)`,
115
+ 'launch_doctor_status=$?',
116
+ 'if [ "$launch_doctor_status" -ne 0 ]; then',
117
+ ' printf "%s\\n" "$launch_doctor_output" >&2',
118
+ 'fi',
119
+ 'if [ "$launch_doctor_status" -eq 1 ]; then',
120
+ ' echo "Launch Doctor found critical problems in the files you are committing. Fix them, or commit anyway with: git commit --no-verify" >&2',
121
+ ' exit 1',
122
+ 'fi',
123
+ MARK_END,
124
+ '',
125
+ ].join('\n');
126
+ }
127
+ /** A hook script a POSIX shell can run (so the block can be added to it). */
128
+ const SHELL_SHEBANG = /^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?)?(?:\S*\/)?(?:sh|bash|zsh|dash|ash)\b/;
129
+ /** .git/pre-commit (or wherever core.hooksPath points): checks the staged files. */
130
+ function setupPreCommit(root, result) {
131
+ const gitRoot = findGitRoot(root);
132
+ if (!gitRoot)
133
+ return void result.skipped.push(['pre-commit hook', "this folder isn't in a git repository"]);
134
+ const hooksPath = gitHooksDir(root);
135
+ if (!hooksPath)
136
+ return void result.skipped.push(['pre-commit hook', "couldn't find the git hooks folder"]);
137
+ const file = resolve(root, hooksPath, 'pre-commit');
138
+ const shown = relative(root, file).replace(/\\/g, '/');
139
+ const label = shown.startsWith('..') || isAbsolute(shown) ? file : shown;
140
+ // When the project is a subfolder of the repository, tell the CLI which folder to check.
141
+ // Real paths on both sides: git and the shell may spell the same folder differently (symlinks, Windows short names).
142
+ const projectDir = relative(realpathSync.native(gitRoot), realpathSync.native(root)).replace(/\\/g, '/');
143
+ const block = preCommitBlock(projectDir);
144
+ const kind = entryKind(file);
145
+ if (kind === 'missing') {
146
+ mkdirSync(dirname(file), { recursive: true });
147
+ writeRegularFile(file, `#!/bin/sh\n${block}`);
148
+ try {
149
+ chmodSync(file, 0o755);
150
+ }
151
+ catch {
152
+ // Windows has no file modes; Git for Windows runs the hook anyway.
153
+ }
154
+ return void result.created.push(label);
155
+ }
156
+ // A hook that is a symlink (to a script kept in the repository, say) is left for you to edit.
157
+ const text = kind === 'file' ? readRegularFile(file, CONFIG_FILE_MAX_BYTES) : null;
158
+ if (text === null) {
159
+ return void result.skipped.push([
160
+ label,
161
+ `${SPECIAL}; add "npx launch-doctor --staged --ci --no-file" to the script it runs yourself`,
162
+ ]);
163
+ }
164
+ if (text.includes(MARK_START))
165
+ return void result.skipped.push([label, 'already set up']);
166
+ const lines = text.split('\n');
167
+ const hasShebang = lines[0].startsWith('#!');
168
+ if (hasShebang && !SHELL_SHEBANG.test(lines[0])) {
169
+ return void result.skipped.push([
170
+ label,
171
+ 'it is not a shell script, so add "npx launch-doctor --staged --ci --no-file" to it yourself',
172
+ ]);
173
+ }
174
+ // Right after the shebang, so a later "exit 0" in the existing hook can't skip it.
175
+ const head = hasShebang ? [lines[0]] : [];
176
+ const rest = hasShebang ? lines.slice(1) : lines;
177
+ writeRegularFile(file, [...head, block.trimEnd(), ...rest].join('\n'));
178
+ result.updated.push(label);
179
+ }
180
+ /** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
181
+ export function setupHooks(root) {
182
+ const result = { created: [], updated: [], skipped: [] };
183
+ setupClaude(root, result);
184
+ setupCursor(root, result);
185
+ setupPreCommit(root, result);
186
+ return result;
187
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Gitignore-style matching for .launchdoctorignore (and for .gitignore when git isn't available).
3
+ *
4
+ * Rules are compiled once. A glob is matched by stepping through the path one character at a time while keeping
5
+ * the set of places in the pattern that could be reached (no backtracking), so the time is at most the path's
6
+ * length times the pattern's length, whatever the glob looks like. A glob turned into a regular expression could
7
+ * take exponential time (`a*a*a*...b`, `**` repeated 40 times), which let a crafted ignore file hang a scan.
8
+ */
9
+ type Token = {
10
+ kind: 'char';
11
+ c: string;
12
+ } | {
13
+ kind: 'one';
14
+ } | {
15
+ kind: 'star';
16
+ } | {
17
+ kind: 'globstar';
18
+ };
19
+ interface Glob {
20
+ tokens: Token[];
21
+ /** The longest run of plain characters in the glob: a path without it can't match, which is cheap to check. */
22
+ mustContain: string;
23
+ }
24
+ export interface IgnoreRule {
25
+ glob: Glob;
26
+ negate: boolean;
27
+ anchored: boolean;
28
+ anyDepth: boolean;
29
+ }
30
+ /** Parse gitignore-style text into rules. */
31
+ export declare function compileIgnore(text: string): IgnoreRule[];
32
+ /** Is `path` (relative, with "/") ignored by these rules? The last matching rule wins, as in git. */
33
+ export declare function matchesIgnore(rules: IgnoreRule[], path: string): boolean;
34
+ /** Minimal .gitignore matching for one path, used when git isn't available. Compiles each distinct text once. */
35
+ export declare function matchesGitignore(gitignore: string, path: string): boolean;
36
+ export {};