checkchange 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/LICENSE +21 -0
  2. package/README.md +150 -0
  3. package/dist/attribution.d.ts +19 -0
  4. package/dist/attribution.js +175 -0
  5. package/dist/auto-coverage.d.ts +8 -0
  6. package/dist/auto-coverage.js +93 -0
  7. package/dist/cache.d.ts +70 -0
  8. package/dist/cache.js +458 -0
  9. package/dist/cli.d.ts +51 -0
  10. package/dist/cli.js +810 -0
  11. package/dist/complexity-providers/pythonASTComplexityProvider.d.ts +9 -0
  12. package/dist/complexity-providers/pythonASTComplexityProvider.js +148 -0
  13. package/dist/complexity-providers/pythonDescriptorProvider.d.ts +17 -0
  14. package/dist/complexity-providers/pythonDescriptorProvider.js +119 -0
  15. package/dist/complexity-providers.d.ts +6 -0
  16. package/dist/complexity-providers.js +1 -0
  17. package/dist/complexity.d.ts +14 -0
  18. package/dist/complexity.js +75 -0
  19. package/dist/coverage-providers/lcovProvider.d.ts +12 -0
  20. package/dist/coverage-providers/lcovProvider.js +126 -0
  21. package/dist/coverage.d.ts +28 -0
  22. package/dist/coverage.js +451 -0
  23. package/dist/crap.d.ts +31 -0
  24. package/dist/crap.js +84 -0
  25. package/dist/crapCalc.d.ts +5 -0
  26. package/dist/crapCalc.js +11 -0
  27. package/dist/delta.d.ts +100 -0
  28. package/dist/delta.js +214 -0
  29. package/dist/evidence.d.ts +201 -0
  30. package/dist/evidence.js +906 -0
  31. package/dist/execute.d.ts +59 -0
  32. package/dist/execute.js +92 -0
  33. package/dist/formatters/github.d.ts +5 -0
  34. package/dist/formatters/github.js +27 -0
  35. package/dist/formatters/index.d.ts +47 -0
  36. package/dist/formatters/index.js +14 -0
  37. package/dist/formatters/junit.d.ts +5 -0
  38. package/dist/formatters/junit.js +32 -0
  39. package/dist/formatters/sarif.d.ts +5 -0
  40. package/dist/formatters/sarif.js +35 -0
  41. package/dist/fs-safety.d.ts +10 -0
  42. package/dist/fs-safety.js +47 -0
  43. package/dist/git.d.ts +50 -0
  44. package/dist/git.js +137 -0
  45. package/dist/help.d.ts +40 -0
  46. package/dist/help.js +274 -0
  47. package/dist/index.d.ts +6 -0
  48. package/dist/index.js +4 -0
  49. package/dist/providers/config.d.ts +41 -0
  50. package/dist/providers/config.js +172 -0
  51. package/dist/providers/genericCommand.d.ts +3 -0
  52. package/dist/providers/genericCommand.js +89 -0
  53. package/dist/providers/index.d.ts +7 -0
  54. package/dist/providers/index.js +4 -0
  55. package/dist/providers/prepare.d.ts +124 -0
  56. package/dist/providers/prepare.js +459 -0
  57. package/dist/providers/runner-detection.d.ts +30 -0
  58. package/dist/providers/runner-detection.js +207 -0
  59. package/dist/rules.d.ts +27 -0
  60. package/dist/rules.js +54 -0
  61. package/package.json +52 -0
@@ -0,0 +1,59 @@
1
+ export interface TraceSpan {
2
+ stage: string;
3
+ durationMs: number;
4
+ status: string;
5
+ correlationId: string;
6
+ }
7
+ export interface TraceExecSpan extends TraceSpan {
8
+ stage: 'exec';
9
+ command: string;
10
+ args: string[];
11
+ exitCode: number | null;
12
+ }
13
+ export interface TraceWarning {
14
+ source: string;
15
+ message: string;
16
+ correlationId: string;
17
+ }
18
+ /**
19
+ * In-memory trace collector for one pipeline run. Holds the per-run
20
+ * correlation ID and every span recorded (stage spans from the evidence
21
+ * pipeline, exec spans from execute()). Never leaves the process — the
22
+ * deterministic EvidenceOutput (evidence-contract.md:341) carries no timing.
23
+ */
24
+ export declare class TraceRun {
25
+ readonly correlationId: string;
26
+ readonly spans: Array<TraceSpan | TraceExecSpan>;
27
+ readonly warnings: TraceWarning[];
28
+ constructor(correlationId?: string);
29
+ /** Records one pipeline-stage span (git, complexity, ..., evidence). */
30
+ recordStage(stage: string, durationMs: number, status: string): void;
31
+ /** Records one child-process span; wired from execute() when given a TraceRun. */
32
+ recordExec(command: string, args: string[], durationMs: number, exitCode: number | null): void;
33
+ /** Records one non-fatal warning (parse/conversion skip) into the trace buffer. */
34
+ recordWarning(source: string, message: string): void;
35
+ }
36
+ export interface CommandResult {
37
+ command: string;
38
+ args: string[];
39
+ cwd: string | undefined;
40
+ exitCode: number | null;
41
+ stdout: string;
42
+ stderr: string;
43
+ durationMs: number;
44
+ timedOut: boolean;
45
+ errorCode: string | undefined;
46
+ }
47
+ /**
48
+ * Wrapper around child_process.execFile that returns a CommandResult.
49
+ * Handles ENOENT (command not found) by setting exitCode to null.
50
+ * @param command The command to execute
51
+ * @param args The arguments to pass to the command
52
+ * @param options Options: cwd, timeout, maxBuffer
53
+ * @returns Promise<CommandResult>
54
+ */
55
+ export declare function execute(command: string, args?: string[], options?: {
56
+ cwd?: string;
57
+ timeout?: number;
58
+ maxBuffer?: number;
59
+ }, trace?: TraceRun): Promise<CommandResult>;
@@ -0,0 +1,92 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ /**
4
+ * In-memory trace collector for one pipeline run. Holds the per-run
5
+ * correlation ID and every span recorded (stage spans from the evidence
6
+ * pipeline, exec spans from execute()). Never leaves the process — the
7
+ * deterministic EvidenceOutput (evidence-contract.md:341) carries no timing.
8
+ */
9
+ export class TraceRun {
10
+ correlationId;
11
+ spans = [];
12
+ warnings = [];
13
+ constructor(correlationId = randomUUID()) {
14
+ this.correlationId = correlationId;
15
+ }
16
+ /** Records one pipeline-stage span (git, complexity, ..., evidence). */
17
+ recordStage(stage, durationMs, status) {
18
+ this.spans.push({ stage, durationMs, status, correlationId: this.correlationId });
19
+ }
20
+ /** Records one child-process span; wired from execute() when given a TraceRun. */
21
+ recordExec(command, args, durationMs, exitCode) {
22
+ this.spans.push({ stage: 'exec', command, args, durationMs, exitCode, status: 'ok', correlationId: this.correlationId });
23
+ }
24
+ /** Records one non-fatal warning (parse/conversion skip) into the trace buffer. */
25
+ recordWarning(source, message) {
26
+ this.warnings.push({ source, message, correlationId: this.correlationId });
27
+ }
28
+ }
29
+ /**
30
+ * Wrapper around child_process.execFile that returns a CommandResult.
31
+ * Handles ENOENT (command not found) by setting exitCode to null.
32
+ * @param command The command to execute
33
+ * @param args The arguments to pass to the command
34
+ * @param options Options: cwd, timeout, maxBuffer
35
+ * @returns Promise<CommandResult>
36
+ */
37
+ export function execute(command, args = [], options = {}, trace) {
38
+ const { cwd, timeout, maxBuffer } = options;
39
+ const start = Date.now();
40
+ return new Promise((resolve) => {
41
+ execFile(command, args, { cwd, timeout, maxBuffer }, (error, stdout, stderr) => {
42
+ const end = Date.now();
43
+ const durationMs = end - start;
44
+ let exitCode;
45
+ let timedOut = false;
46
+ let errorCode;
47
+ if (error) {
48
+ if (error.name === 'TimeoutError') {
49
+ timedOut = true;
50
+ }
51
+ let maybeExitCode = null;
52
+ if ('exitCode' in error) {
53
+ maybeExitCode = error.exitCode;
54
+ }
55
+ else if ('code' in error && typeof error.code === 'number') {
56
+ maybeExitCode = error.code;
57
+ }
58
+ if (maybeExitCode !== null) {
59
+ exitCode = maybeExitCode;
60
+ }
61
+ else if (error.code === 'ENOENT') {
62
+ exitCode = null;
63
+ errorCode = error.code;
64
+ }
65
+ else {
66
+ exitCode = null;
67
+ // If error.code is a string (but not ENOENT), we still want to capture it
68
+ if (typeof error.code === 'string') {
69
+ errorCode = error.code;
70
+ }
71
+ }
72
+ }
73
+ else {
74
+ exitCode = 0;
75
+ }
76
+ resolve({
77
+ command,
78
+ args,
79
+ cwd,
80
+ exitCode,
81
+ stdout: stdout ?? '',
82
+ stderr: stderr ?? '',
83
+ durationMs,
84
+ timedOut,
85
+ errorCode
86
+ });
87
+ // Tracing seam: record the exec span into the per-run trace (in-memory only).
88
+ if (trace)
89
+ trace.recordExec(command, args, durationMs, exitCode);
90
+ });
91
+ });
92
+ }
@@ -0,0 +1,5 @@
1
+ import type { EvidenceOutputShape } from './index.js';
2
+ /** GitHub Actions annotations + PR-comment markdown table. */
3
+ export declare function formatGitHub(out: EvidenceOutputShape, opts: {
4
+ cwd: string;
5
+ }): string;
@@ -0,0 +1,27 @@
1
+ /** PR-comment markdown table over changed functions + rule results + gate. */
2
+ function prTable(out) {
3
+ const rows = out.ruleResults
4
+ .map((r, i) => {
5
+ const fn = out.changedFunctions[i];
6
+ return `| ${r.file} | ${r.method} | ${fn.lineStart}-${fn.lineEnd} | ${r.result} | ${r.crap ?? 'n/a'} | ${r.coverage ?? 'n/a'} |`;
7
+ })
8
+ .join('\n');
9
+ return [
10
+ '| File | Method | Lines | Result | CRAP | Coverage |',
11
+ '|------|--------|-------|--------|------|----------|',
12
+ rows,
13
+ '',
14
+ `Gate: ${out.gate}`,
15
+ `Completeness: ${out.completeness}`,
16
+ ].join('\n');
17
+ }
18
+ /** GitHub Actions annotations + PR-comment markdown table. */
19
+ export function formatGitHub(out, opts) {
20
+ void opts;
21
+ const annotations = out.ruleResults
22
+ .map((r, i) => ({ r, fn: out.changedFunctions[i] }))
23
+ .filter(({ r }) => r.result === 'WARN' || r.result === 'NOT_EVALUATED')
24
+ .map(({ r, fn }) => `::warning file=${r.file},line=${fn.lineStart},endLine=${fn.lineEnd},title=high CRAP:: ${r.method} CRAP ${r.crap} > ${r.threshold} (cc ${r.cc}, cov ${r.coverage})`)
25
+ .join('\n');
26
+ return [annotations, prTable(out)].filter(Boolean).join('\n\n---\n\n');
27
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Formatters are pure sidecars: (EvidenceOutputShape, opts) => string.
3
+ * They never call engine code and never emit absolute paths — file paths are
4
+ * taken verbatim (forward-slash relative) from ruleResults[].file.
5
+ *
6
+ * NOTE: ruleResults carry no line info (RuleResult: rules.ts:6-15 has no
7
+ * lineStart/lineEnd), so formatters pair each entry with the index-aligned
8
+ * changedFunctions[i] entry for region lines. Alignment is guaranteed by
9
+ * construction: evaluateHighCrap is changed.map() (rules.ts:23) and
10
+ * buildEvidenceOutput's changedFunctionsWithLanguage is also a 1:1 .map()
11
+ * (evidence.ts:603).
12
+ */
13
+ export interface ChangedFunctionShape {
14
+ file: string;
15
+ method: string;
16
+ lineStart: number;
17
+ lineEnd: number;
18
+ cc: number;
19
+ crap: number | null;
20
+ coverage: number | null;
21
+ }
22
+ export interface RuleResultShape {
23
+ ruleId: string;
24
+ result: 'PASS' | 'WARN' | 'NOT_EVALUATED';
25
+ file: string;
26
+ method: string;
27
+ crap: number | null;
28
+ threshold: number;
29
+ cc: number;
30
+ coverage: number | null;
31
+ }
32
+ /** Stable EvidenceOutputShape subset consumed by formatters (structural clone
33
+ * of the CLI-private interface at cli.ts:126 — that one is not exported, so
34
+ * formatters define their own and CLI passes its cast output in Task 2). */
35
+ export interface EvidenceOutputShape {
36
+ analysisStatus: string;
37
+ gate: string | null;
38
+ completeness: string;
39
+ schemaVersion: string;
40
+ changedFunctions: ChangedFunctionShape[];
41
+ ruleResults: RuleResultShape[];
42
+ }
43
+ export declare const FORMATS: readonly ["github", "junit", "sarif"];
44
+ export type FormatType = (typeof FORMATS)[number];
45
+ export declare function format(out: EvidenceOutputShape, fmt: FormatType, opts: {
46
+ cwd: string;
47
+ }): string;
@@ -0,0 +1,14 @@
1
+ import { formatGitHub } from './github.js';
2
+ import { formatJUnit } from './junit.js';
3
+ import { formatSARIF } from './sarif.js';
4
+ export const FORMATS = ['github', 'junit', 'sarif'];
5
+ export function format(out, fmt, opts) {
6
+ switch (fmt) {
7
+ case 'github':
8
+ return formatGitHub(out, opts);
9
+ case 'junit':
10
+ return formatJUnit(out, opts);
11
+ case 'sarif':
12
+ return formatSARIF(out, opts);
13
+ }
14
+ }
@@ -0,0 +1,5 @@
1
+ import type { EvidenceOutputShape } from './index.js';
2
+ /** JUnit XML: one <testcase> per changed function; failures == WARN count. */
3
+ export declare function formatJUnit(out: EvidenceOutputShape, opts: {
4
+ cwd: string;
5
+ }): string;
@@ -0,0 +1,32 @@
1
+ /** Escape XML entities in attribute/text content. */
2
+ function escapeXml(s) {
3
+ return s
4
+ .replace(/&/g, '&amp;')
5
+ .replace(/</g, '&lt;')
6
+ .replace(/>/g, '&gt;')
7
+ .replace(/"/g, '&quot;')
8
+ .replace(/'/g, '&apos;');
9
+ }
10
+ /** JUnit XML: one <testcase> per changed function; failures == WARN count. */
11
+ export function formatJUnit(out, opts) {
12
+ void opts;
13
+ const warnCount = out.ruleResults.filter((r) => r.result === 'WARN').length;
14
+ const cases = out.ruleResults
15
+ .map((r, i) => {
16
+ const fn = out.changedFunctions[i];
17
+ const attrs = `classname="${escapeXml(fn.file)}" name="${escapeXml(r.method)}" file="${escapeXml(r.file)}" line="${fn.lineStart}"`;
18
+ if (r.result === 'WARN') {
19
+ const message = `CRAP ${r.crap} > ${r.threshold}`;
20
+ return ` <testcase ${attrs}>\n <failure message="${escapeXml(message)}">${escapeXml(r.method)} ${escapeXml(message)}</failure>\n </testcase>`;
21
+ }
22
+ if (r.result === 'NOT_EVALUATED') {
23
+ return ` <testcase ${attrs}>\n <skipped/>\n </testcase>`;
24
+ }
25
+ return ` <testcase ${attrs}/>`;
26
+ })
27
+ .join('\n');
28
+ return (`<?xml version="1.0" encoding="UTF-8"?>\n` +
29
+ `<testsuite name="checkchange" tests="${out.changedFunctions.length}" failures="${warnCount}">\n` +
30
+ `${cases}\n` +
31
+ `</testsuite>\n`);
32
+ }
@@ -0,0 +1,5 @@
1
+ import type { EvidenceOutputShape } from './index.js';
2
+ /** SARIF 2.1.0: one result per WARN with verbatim relative uri + line region. */
3
+ export declare function formatSARIF(out: EvidenceOutputShape, opts: {
4
+ cwd: string;
5
+ }): string;
@@ -0,0 +1,35 @@
1
+ /** SARIF 2.1.0: one result per WARN with verbatim relative uri + line region. */
2
+ export function formatSARIF(out, opts) {
3
+ void opts;
4
+ const results = out.ruleResults
5
+ .map((r, i) => ({ r, fn: out.changedFunctions[i] }))
6
+ .filter(({ r }) => r.result === 'WARN')
7
+ .map(({ r, fn }) => ({
8
+ ruleId: 'changed-function-high-crap',
9
+ level: 'warning',
10
+ locations: [
11
+ {
12
+ physicalLocation: {
13
+ artifactLocation: { uri: r.file },
14
+ region: { startLine: fn.lineStart, endLine: fn.lineEnd },
15
+ },
16
+ },
17
+ ],
18
+ message: { text: `${r.method} CRAP ${r.crap} > ${r.threshold} (cc ${r.cc}, cov ${r.coverage})` },
19
+ }));
20
+ return JSON.stringify({
21
+ version: '2.1.0',
22
+ runs: [
23
+ {
24
+ tool: {
25
+ driver: {
26
+ name: 'checkchange',
27
+ version: out.schemaVersion,
28
+ rules: [{ id: 'changed-function-high-crap' }],
29
+ },
30
+ },
31
+ results,
32
+ },
33
+ ],
34
+ }, null, 2);
35
+ }
@@ -0,0 +1,10 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ /**
3
+ * Open an existing regular file only when its resolved target is contained by root.
4
+ *
5
+ * Error handling is fail-closed: realpath(), containment, open(), and post-open
6
+ * validation failures propagate without an alternate-path retry. Reads through
7
+ * the returned handle remain bound to the opened file. The module header
8
+ * defines the pre-open race excluded from this contract.
9
+ */
10
+ export declare function openWithinRoot(root: string, candidate: string): Promise<FileHandle>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Filesystem read seam with a deliberately bounded security contract.
3
+ *
4
+ * CLOSED: the lexical-fallback class. Errors never trigger an alternate-path
5
+ * read; post-open operations use one descriptor; containment is verified before
6
+ * open; and the descriptor remains stable after open if path names change.
7
+ *
8
+ * OUT OF SCOPE: pre-open ancestor-directory substitution by a privileged local
9
+ * attacker racing realpath() to open(). Portable Node has no openat equivalent;
10
+ * O_NOFOLLOW guards only the final path component (platform-dependent).
11
+ */
12
+ import { constants } from 'node:fs';
13
+ import { open, realpath } from 'node:fs/promises';
14
+ import { isAbsolute, relative, resolve } from 'node:path';
15
+ function isWithinRoot(root, candidate) {
16
+ const rel = relative(root, candidate);
17
+ return rel !== '..' && !rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) && !isAbsolute(rel);
18
+ }
19
+ /**
20
+ * Open an existing regular file only when its resolved target is contained by root.
21
+ *
22
+ * Error handling is fail-closed: realpath(), containment, open(), and post-open
23
+ * validation failures propagate without an alternate-path retry. Reads through
24
+ * the returned handle remain bound to the opened file. The module header
25
+ * defines the pre-open race excluded from this contract.
26
+ */
27
+ export async function openWithinRoot(root, candidate) {
28
+ const candidatePath = resolve(root, candidate);
29
+ const realRoot = await realpath(root);
30
+ const realCandidate = await realpath(candidatePath);
31
+ if (!isWithinRoot(realRoot, realCandidate)) {
32
+ throw new Error(`openWithinRoot: candidate escapes root: ${candidatePath}`);
33
+ }
34
+ const noFollow = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
35
+ const handle = await open(realCandidate, constants.O_RDONLY | noFollow);
36
+ try {
37
+ const stats = await handle.stat();
38
+ if (!stats.isFile()) {
39
+ throw new Error(`openWithinRoot: candidate is not a regular file: ${candidatePath}`);
40
+ }
41
+ return handle;
42
+ }
43
+ catch (error) {
44
+ await handle.close().catch(() => undefined);
45
+ throw error;
46
+ }
47
+ }
package/dist/git.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { type TraceRun } from './execute.js';
2
+ export declare const gitProvenance: {
3
+ readonly tool: "node:child_process";
4
+ readonly version: string;
5
+ };
6
+ export interface GitChangeIntervals {
7
+ intervals: Map<string, Array<{
8
+ start: number;
9
+ end: number;
10
+ }>>;
11
+ rawDiff: string;
12
+ }
13
+ /**
14
+ * Validates that the current directory is a git repository.
15
+ * @param cwd The current working directory (defaults to process.cwd())
16
+ * @throws If not a git repository or if git executable is not found
17
+ */
18
+ export declare function validateGitRepo(cwd?: string, trace?: TraceRun): Promise<void>;
19
+ /**
20
+ * Resolves a base reference to a commit hash.
21
+ * @param base The base reference (e.g., branch name, tag, commit hash)
22
+ * @param cwd The current working directory (defaults to process.cwd())
23
+ * @returns The resolved commit hash
24
+ * @throws If the base reference cannot be resolved or if git executable is not found
25
+ */
26
+ export declare function resolveBaseRef(base: string, cwd?: string, trace?: TraceRun): Promise<string>;
27
+ /**
28
+ * Attempts to auto-detect the default base branch.
29
+ * @param verbose If true, logs the detected base to stderr
30
+ * @param cwd The current working directory (defaults to process.cwd())
31
+ * @returns The detected base reference (e.g., 'origin/master') or null if undetectable
32
+ */
33
+ export declare function detectDefaultBase(verbose?: boolean, cwd?: string): Promise<string | null>;
34
+ /**
35
+ * Parses the output of `git diff --unified=0` to extract changed line intervals per file.
36
+ * @param diffText The output of `git diff --unified=0`
37
+ * @returns A map from file path to an array of {start, end} intervals (1-based, inclusive)
38
+ */
39
+ export declare function parseChangedIntervals(diffText: string): Map<string, Array<{
40
+ start: number;
41
+ end: number;
42
+ }>>;
43
+ /**
44
+ * Gets the changed intervals for the given base reference.
45
+ * @param base The base reference to compare against (e.g., branch name, tag, commit hash)
46
+ * @param cwd The current working directory (defaults to process.cwd())
47
+ * @returns An object containing the intervals map and the raw diff output
48
+ * @throws If the git commands fail
49
+ */
50
+ export declare function getChangedIntervals(base: string, cwd?: string, trace?: TraceRun): Promise<GitChangeIntervals>;
package/dist/git.js ADDED
@@ -0,0 +1,137 @@
1
+ import { execute } from './execute.js';
2
+ // Provenance for the git lineage stage. git runs via node:child_process, so the
3
+ // node version is the driver identifier (per diagnostics-schema-design.md example).
4
+ export const gitProvenance = { tool: 'node:child_process', version: process.version };
5
+ /**
6
+ * Validates that the current directory is a git repository.
7
+ * @param cwd The current working directory (defaults to process.cwd())
8
+ * @throws If not a git repository or if git executable is not found
9
+ */
10
+ export async function validateGitRepo(cwd = process.cwd(), trace) {
11
+ const result = await execute('git', ['rev-parse', '--git-dir'], { cwd }, trace);
12
+ if (result.errorCode === 'ENOENT') {
13
+ throw new Error('Git executable not found');
14
+ }
15
+ if (result.exitCode !== 0) {
16
+ throw new Error('Not a git repository');
17
+ }
18
+ }
19
+ /**
20
+ * Resolves a base reference to a commit hash.
21
+ * @param base The base reference (e.g., branch name, tag, commit hash)
22
+ * @param cwd The current working directory (defaults to process.cwd())
23
+ * @returns The resolved commit hash
24
+ * @throws If the base reference cannot be resolved or if git executable is not found
25
+ */
26
+ export async function resolveBaseRef(base, cwd = process.cwd(), trace) {
27
+ const result = await execute('git', ['rev-parse', '--verify', `${base}^{commit}`], { cwd }, trace);
28
+ if (result.errorCode === 'ENOENT') {
29
+ throw new Error('Git executable not found');
30
+ }
31
+ if (result.exitCode !== 0) {
32
+ throw new Error(`Cannot resolve base reference: ${base}`);
33
+ }
34
+ return result.stdout.trim();
35
+ }
36
+ /**
37
+ * Attempts to auto-detect the default base branch.
38
+ * @param verbose If true, logs the detected base to stderr
39
+ * @param cwd The current working directory (defaults to process.cwd())
40
+ * @returns The detected base reference (e.g., 'origin/master') or null if undetectable
41
+ */
42
+ export async function detectDefaultBase(verbose = false, cwd = process.cwd()) {
43
+ // Helper to run a git command and return stdout if successful, null otherwise
44
+ const tryGitRevParse = async (ref) => {
45
+ const result = await execute('git', ['rev-parse', '--verify', `${ref}^{commit}`], { cwd });
46
+ return result.exitCode === 0;
47
+ };
48
+ // 1. Try `git symbolic-ref refs/remotes/origin/HEAD`
49
+ const symRefResult = await execute('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], { cwd });
50
+ if (symRefResult.exitCode === 0) {
51
+ // Output is like "refs/remotes/origin/master"
52
+ let ref = symRefResult.stdout.trim();
53
+ // Remove the "refs/remotes/" prefix to get "origin/master"
54
+ if (ref.startsWith('refs/remotes/')) {
55
+ ref = ref.substring('refs/remotes/'.length);
56
+ }
57
+ // Verify the ref is resolvable
58
+ if (await tryGitRevParse(ref)) {
59
+ if (verbose) {
60
+ process.stderr.write(`[verbose] auto-detected base: ${ref}\n`);
61
+ }
62
+ return ref;
63
+ }
64
+ }
65
+ // 2. Fallback candidates
66
+ const candidates = ['origin/master', 'origin/main', 'master', 'main'];
67
+ for (const candidate of candidates) {
68
+ if (await tryGitRevParse(candidate)) {
69
+ if (verbose) {
70
+ process.stderr.write(`[verbose] auto-detected base: ${candidate}\n`);
71
+ }
72
+ return candidate;
73
+ }
74
+ }
75
+ // Nothing worked
76
+ return null;
77
+ }
78
+ /**
79
+ * Parses the output of `git diff --unified=0` to extract changed line intervals per file.
80
+ * @param diffText The output of `git diff --unified=0`
81
+ * @returns A map from file path to an array of {start, end} intervals (1-based, inclusive)
82
+ */
83
+ export function parseChangedIntervals(diffText) {
84
+ const intervals = new Map();
85
+ let currentFile = '';
86
+ for (const line of diffText.split('\n')) {
87
+ // Detect file header: diff --git a/<old> b/<new>
88
+ if (line.startsWith('diff --git ')) {
89
+ const match = line.match(/diff --git .* b\/(.*)/);
90
+ if (match) {
91
+ currentFile = match[1];
92
+ // Initialize the intervals array for this file if not present
93
+ if (!intervals.has(currentFile)) {
94
+ intervals.set(currentFile, []);
95
+ }
96
+ }
97
+ continue;
98
+ }
99
+ // Parse hunk header: @@ -<oldStart>,<oldLen> +<newStart>,<newLen> @@
100
+ const hunkMatch = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
101
+ if (hunkMatch) {
102
+ const newStart = parseInt(hunkMatch[3], 10);
103
+ const newLen = hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1;
104
+ // If newLen is 0, then there are no new lines (deletion)
105
+ if (newLen > 0) {
106
+ const newEnd = newStart + newLen - 1;
107
+ const fileIntervals = intervals.get(currentFile);
108
+ if (fileIntervals) {
109
+ fileIntervals.push({ start: newStart, end: newEnd });
110
+ }
111
+ }
112
+ // If newLen === 0, we skip because there is no new interval (it's a deletion)
113
+ continue;
114
+ }
115
+ }
116
+ return intervals;
117
+ }
118
+ /**
119
+ * Gets the changed intervals for the given base reference.
120
+ * @param base The base reference to compare against (e.g., branch name, tag, commit hash)
121
+ * @param cwd The current working directory (defaults to process.cwd())
122
+ * @returns An object containing the intervals map and the raw diff output
123
+ * @throws If the git commands fail
124
+ */
125
+ export async function getChangedIntervals(base, cwd = process.cwd(), trace) {
126
+ await validateGitRepo(cwd, trace);
127
+ const resolvedBase = await resolveBaseRef(base, cwd, trace);
128
+ const diffResult = await execute('git', ['diff', '--unified=0', resolvedBase], { cwd }, trace);
129
+ if (diffResult.errorCode === 'ENOENT') {
130
+ throw new Error('Git executable not found');
131
+ }
132
+ if (diffResult.exitCode !== 0) {
133
+ throw new Error(`Git diff failed: ${diffResult.stderr}`);
134
+ }
135
+ const intervals = parseChangedIntervals(diffResult.stdout);
136
+ return { intervals, rawDiff: diffResult.stdout };
137
+ }
package/dist/help.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ export type HelpFlagType = 'string' | 'boolean' | 'number';
2
+ /** One flag as advertised in the machine-readable help. */
3
+ export interface HelpFlag {
4
+ name: string;
5
+ type: HelpFlagType;
6
+ /** Literal default; null when the flag is optional and has no default. */
7
+ default: string | number | boolean | null;
8
+ description: string;
9
+ }
10
+ export interface HelpEntry {
11
+ command: string;
12
+ description: string;
13
+ /** One-line invocation, without the leading "Usage: ". */
14
+ usage: string;
15
+ /**
16
+ * Help body up to (not including) the Examples block: usage line, then
17
+ * options and any command-specific sections. Kept as literal lines so the
18
+ * rendered text stays byte-exact — option columns are hand-aligned, and
19
+ * `check` is pinned to the pre-existing output by test/cli-help.spec.ts.
20
+ */
21
+ head: string;
22
+ flags: HelpFlag[];
23
+ examples: string[];
24
+ }
25
+ export type CommandName = 'check' | 'doctor' | 'explain' | 'trace' | 'delta' | 'prepare-repo';
26
+ export declare const HELP_REGISTRY: Record<CommandName, HelpEntry>;
27
+ /**
28
+ * Render help for one subcommand, or the overview when `command` is undefined
29
+ * (bare `checkchange --help`). No trailing newline — the caller prints it.
30
+ */
31
+ export declare function formatHelpText(command: CommandName | undefined): string;
32
+ /** Machine-readable help: same shape for every command (spec §J). */
33
+ export declare function formatHelpJson(command: CommandName | undefined): unknown;
34
+ /**
35
+ * `checkchange <version>`, read from this package's package.json at runtime
36
+ * (never hardcoded — src/rules.ts:4 is the reason that matters). moduleDir is
37
+ * src/ or dist/, so the manifest sits one level up; same idiom as
38
+ * src/evidence.ts:74. Never throws: an unreadable manifest yields 'unknown'.
39
+ */
40
+ export declare function formatVersion(): string;